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 DeriveGeneric #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeSynonymInstances #-} -- | Provides structured logging and report on training process. -- -- This module mainly exposes a type for `Message`s that are output by `word2vec` when -- working on input and training the underlying model and an interface mechanism for -- publishing those messages using any underlying `MonadIO` instance. module Log where import Control.Monad.Trans (MonadIO) import Data.Aeson import Data.Time.Clock import GHC.Generics import Model.Types import Words.Dictionary -- |All type of messages emitted by application while working. data Message = AnalyzingDirectory FilePath | EncodedDictionary Dictionary | TokenizingFiles Int | TokenizingFile FilePath | TokenizedFile FilePath [ String ] | TokenizedFiles [[String]] | WritingModelFile FilePath | LoadingModelFile FilePath | WritingPCAFile FilePath | WritingDiagram FilePath [ String ] -- Training | StartTraining Int | TrainingSentence Int Int | TrainWord String String | TrainingWindow Double String [String] | InitialWordVector Int WordVector | BeforeUpdate Int WordVector | DotProduct Double | ErrorGradient Double | InputLayerAfterGradient WordVector | HiddenLayerAfterGradient WordVector | UpdatedWordVector Int WordVector | TrainedSentence NominalDiffTime | Done deriving (Show, Generic) instance ToJSON Message data Level = Coarse | Middle | Fine deriving (Eq, Show, Read, Enum) class (MonadIO io) => Progress io where progress :: Level -> Message -> io ()
abailly/hs-word2vec
src/Log.hs
bsd-3-clause
2,087
0
10
692
290
173
117
44
0
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} module Sky.Util.NewContainer ( module Data.Hashable , BaseContainer(..) , Constructible(..) , Collapseable(..) , Intersectable(..) , Container(..) , HasLookup(..) , MapLike(..) , MapFoldable(..) , ContainerMappable(..) , TreeSet , HashSet , TreeMap , HashMap ) where -- The old one used functional dependencies, the new one uses type families ---------------------------------------------------------------------------------------------------- {- This module tries to present an consistent interface for containers, specifically for Data.Set, Data.Map and Hash-* equivalents. Some functions from the prelude are redefined, so best import it like this: import Prelude hiding (lookup, (!!)) import Sky.Util.NewContainer -} ---------------------------------------------------------------------------------------------------- {- TODO: - Define ValueT for all containers, not only for "HasLookup" - Then define ContainerMappable on ValueT, not on ElemT - This resembles the stuff from: https://hackage.haskell.org/package/collections-api-1.0.0.0/docs/Data-Collections.html - This module needs a lot of cleanup, since most of the stuff is fixed in base in the meantime: - Every data structure should be a Monoid, so we get mempty, ... - Singleton + mappend = fromList? - We have Foldable which includes toList, length, null, elem - Traverseable - IsList contains the item type (k, v) and toList, fromList - What class only contains "pure" but not "fapply" (aka <*>) ? - Definitely not in base are - mapWithKey, foldrWithKey, traverseWithKey ... -} import Prelude (Bool (..), Eq (..), Int, Ord (..), String, error, flip, fst, head, length, snd, tail, undefined, ($), (++), (.), (==)) import qualified Prelude import Data.Foldable hiding (toList) import Data.Maybe import Data.Monoid import Control.Monad (Monad (..)) import qualified Data.List --import Data.Map (Map) import qualified Data.Map as DataMap --import Data.Set (Set) import qualified Data.Set as DataSet import Data.Hashable import qualified Data.HashMap.Strict as HashMap import qualified Data.HashSet as HashSet type TreeSet v = DataSet.Set v type HashSet v = HashSet.HashSet v type TreeMap k v = DataMap.Map k v type HashMap k v = HashMap.HashMap k v ---------------------------------------------------------------------------------------------------- class BaseContainer c where -- ElemT is not the value type, but the type a container would "toList" to. -- E.g.: In a map "k -> v" this is (k,v). type ElemT c :: * class (BaseContainer c) => Constructible c where empty :: c insert :: ElemT c -> c -> c -- Optional singleton :: ElemT c -> c singleton v = insert v empty fromList :: [ElemT c] -> c fromList [] = empty fromList (x:xs) = insert x (fromList xs) class (BaseContainer c) => Collapseable c where c_foldMap :: Monoid m => (ElemT c -> m) -> c -> m -- Optional elements :: c -> [ElemT c] elements c = c_foldMap (\x -> [x]) c size :: c -> Int size c = length (elements c) isEmpty :: c -> Bool isEmpty c = Prelude.null (elements c) toList :: c -> [ElemT c] toList = elements -- Implement for performance on ordered containers toAscList :: Ord (ElemT c) => c -> [ElemT c] toAscList = Data.List.sort . toList class (BaseContainer c) => Intersectable c where {- Note: These functions may be left-biased, e.g. for maps, they do not neccessarily commute with "contains", but certainly with "hasKey" -} union :: c -> c -> c --union a b = fromList $ (toList a) ++ (toList b) intersection :: c -> c -> c --intersection a b = fromList $ Prelude.filter (b `contains`) (toList a) disjunct :: c -> c -> Bool --disjunct a b = isEmpty (intersection a b) class (Intersectable c) => Diffable c where difference :: c -> c -> c --difference a b = fromList $ Prelude.filter (\x -> not $ b `contains` x) (toList a) symmetricDifference :: c -> c -> c symmetricDifference a b = union (difference a b) (difference b a) class (Constructible c, Collapseable c, Intersectable c) => Container c where -- Note: We do not require diffable, not all containers support it contains :: c -> ElemT c -> Bool --contains c v = not $ isEmpty $ intersection c $ singleton v infixl 9 !! class HasLookup c where type KeyT c :: * type ValueT c :: * lookup :: KeyT c -> c -> Maybe (ValueT c) isMemberOf :: KeyT c -> c -> Bool isMemberOf k m = isJust $ lookup k m (!!) :: c -> KeyT c -> ValueT c (!!) m k = fromMaybe (error $ "Invalid key for lookup (!!)") $ lookup k m class (HasLookup m, Collapseable m, (KeyT m, ValueT m) ~ ElemT m) => MapLike m where mapInsert :: KeyT m -> ValueT m -> m -> m mapDelete :: KeyT m -> m -> m -- Additionally keys :: m -> [KeyT m] keys m = Prelude.map fst (elements m) keysSet :: (Container c, ElemT c ~ KeyT m) => m -> c keysSet = fromList . keys values :: m -> [ValueT m] values m = Prelude.map snd (elements m) --mapInsert k v m = insert (k,v) m hasKey :: m -> (KeyT m) -> Bool hasKey m k = isMemberOf k m class MapFoldable m where mapWithKey :: (k -> va -> vb) -> m k va -> m k vb --mapWithKey f m = fromList $ map (\(k,v) -> f foldrWithKey :: (k -> v -> a -> a) -> a -> m k v -> a foldlWithKey :: (a -> k -> v -> a) -> a -> m k v -> a -- Monadic foldlMWithKey :: forall a k v x. (Monad x) => (a -> k -> v -> x a) -> a -> m k v -> x a foldlMWithKey f a0 m = foldrWithKey f' return m a0 where f' :: k -> v -> (a -> x a) -> (a -> x a) f' k v next a = f a k v >>= next class (BaseContainer c, BaseContainer d) => ContainerMappable c d where -- Like the functor fmap, but works for containers with restrictions on the element type cmap :: (ElemT c -> ElemT d) -> c -> d {- -- This would require OverlappingInstances instance (Prelude.Functor f, BaseContainer (f a), BaseContainer (f b), a ~ ElemT (f a), b ~ ElemT (f b)) => ContainerMappable (f a) (f b) where cmap = Prelude.fmap -} ---------------------------------------------------------------------------------------------------- instance BaseContainer [v] where type ElemT [v] = v instance Constructible [v] where empty = [] insert v l = v:l singleton v = [v] fromList = Prelude.id instance Collapseable [v] where c_foldMap = foldMap elements = Prelude.id size l = length l isEmpty l = Prelude.null l toList = Prelude.id instance (Eq v) => Intersectable [v] where union = Data.List.union -- no nub for efficiency intersection = Data.List.intersect -- no nub for efficiency --intersection a b = Prelude.filter (b `contains`) a disjunct a b = isEmpty (intersection a b) instance (Eq v) => Diffable [v] where difference = (Data.List.\\) instance (Eq v) => Container [v] where contains l v = Prelude.elem v l instance HasLookup [v] where type KeyT [v] = Int type ValueT [v] = v lookup i l = if (i < 0) Prelude.|| (i >= size l) then Nothing else Just $ (Prelude.!!) l i instance ContainerMappable [a] [b] where cmap = Prelude.fmap {- type List v = [] v type Tuple k v = (,) k v --type ListAsMap k v = [(k,v)] type ListAsMap k v = List (Tuple k v) -- eliminate k and v how!?!? instance (Eq k, Eq v) => MapLike (ListAsMap k v) k v where lookup k l = Prelude.lookup k l instance MapFoldable ListAsMap where mapWithKey f l = Prelude.map f' l where f' (k,v) = (k, f k v) foldWithKey f a l = Prelude.foldr f' a l where f' a (k,v) = f k v a -} {- -- It works with newtype at least newtype ListAsMap k v = ListAsMap [(k,v)] lm_toList (ListAsMap x) = x instance MapFoldable ListAsMap where mapWithKey f l = ListAsMap $ Prelude.map f' (lm_toList l) where f' (k,v) = (k, f k v) --foldWithKey :: (k -> v -> a -> a) -> a -> m k v -> a foldWithKey f a l = Prelude.foldr f' a (lm_toList l) where f' (k,v) a = f k v a -} ---------------------------------------------------------------------------------------------------- instance BaseContainer (TreeSet v) where type ElemT (TreeSet v) = v instance (Ord v) => Constructible (TreeSet v) where empty = DataSet.empty insert v m = DataSet.insert v m singleton v = DataSet.singleton v fromList = DataSet.fromList instance Collapseable (TreeSet v) where c_foldMap = foldMap elements = DataSet.toList size = DataSet.size isEmpty = DataSet.null toList = DataSet.toList toAscList = DataSet.toAscList instance (Ord v) => Intersectable (TreeSet v) where union = DataSet.union intersection = DataSet.intersection disjunct a b = isEmpty (intersection a b) instance (Ord v) => Diffable (TreeSet v) where difference = DataSet.difference instance (Ord v) => Container (TreeSet v) where contains m v = DataSet.member v m instance (Ord b) => ContainerMappable (TreeSet a) (TreeSet b) where cmap = DataSet.map ---------------------------------------------------------------------------------------------------- -- HashSet is missing Foldable instance BaseContainer (HashSet v) where type ElemT (HashSet v) = v instance (Hashable v, Ord v) => Constructible (HashSet v) where empty = HashSet.empty insert v m = HashSet.insert v m singleton v = HashSet.singleton v fromList = HashSet.fromList instance Collapseable (HashSet v) where c_foldMap = foldMap elements = HashSet.toList size = HashSet.size isEmpty = HashSet.null toList = HashSet.toList --toAscList = HashSet.toAscList -- HashSet is unordered, resp, orders by hash instance (Eq v, Hashable v) => Intersectable (HashSet v) where union a b = HashSet.union a b intersection a b = HashSet.intersection a b disjunct a b = isEmpty (intersection a b) instance (Eq v, Hashable v) => Diffable (HashSet v) where difference = HashSet.difference instance (Hashable v, Ord v) => Container (HashSet v) where contains m v = HashSet.member v m instance (Hashable b, Ord b) => ContainerMappable (HashSet a) (HashSet b) where cmap = HashSet.map ---------------------------------------------------------------------------------------------------- instance BaseContainer (TreeMap k v) where type ElemT (TreeMap k v) = (k,v) instance (Ord k) => Constructible (TreeMap k v) where empty = DataMap.empty insert (k,v) m = DataMap.insert k v m singleton (k,v) = DataMap.singleton k v fromList = DataMap.fromList instance Collapseable (TreeMap k v) where c_foldMap f m = DataMap.foldWithKey f' mempty m where -- Handle map as collection of (k,v) pairs f' k v a = f (k,v) `mappend` a elements = DataMap.toList size = DataMap.size isEmpty = DataMap.null toList = DataMap.toList instance (Ord k) => Intersectable (TreeMap k v) where union a b = DataMap.union a b intersection a b = DataMap.intersection a b disjunct a b = isEmpty (intersection a b) instance (Ord k) => Diffable (TreeMap k v) where difference = DataMap.difference instance (Ord k, Eq v) => Container (TreeMap k v) where contains m (k,v) = case DataMap.lookup k m of Nothing -> False Just v2 -> v == v2 instance (Ord k) => HasLookup (TreeMap k v) where type KeyT (TreeMap k v) = k type ValueT (TreeMap k v) = v lookup k m = DataMap.lookup k m isMemberOf = DataMap.member instance (Ord k) => MapLike (TreeMap k v) where mapInsert k v m = DataMap.insert k v m mapDelete k m = DataMap.delete k m keys m = DataMap.keys m values m = DataMap.elems m hasKey = flip DataMap.member instance MapFoldable DataMap.Map where mapWithKey = DataMap.mapWithKey foldrWithKey = DataMap.foldrWithKey foldlWithKey = DataMap.foldlWithKey -- Not yet, see TODO. This would remap your keys, too! --instance (Ord b) => ContainerMappable (TreeMap ka a) (TreeMap kb b) where -- cmap = ... ---------------------------------------------------------------------------------------------------- instance BaseContainer (HashMap k v) where type ElemT (HashMap k v) = (k,v) instance (Hashable k, Ord k) => Constructible (HashMap k v) where empty = HashMap.empty insert (k,v) m = HashMap.insert k v m singleton (k,v) = HashMap.singleton k v fromList = HashMap.fromList instance Collapseable (HashMap k v) where c_foldMap f m = -- Handle map as collection of (k,v) pairs HashMap.foldrWithKey f' mempty m where f' k v a = f (k,v) `mappend` a elements = HashMap.toList size = HashMap.size isEmpty = HashMap.null toList = HashMap.toList instance (Eq k, Hashable k) => Intersectable (HashMap k v) where union a b = HashMap.union a b intersection a b = HashMap.intersection a b disjunct a b = isEmpty (intersection a b) instance (Eq k, Hashable k) => Diffable (HashMap k v) where difference = HashMap.difference instance (Hashable k, Ord k, Eq v) => Container (HashMap k v) where contains m (k,v) = case HashMap.lookup k m of Nothing -> False Just v2 -> v == v2 instance (Hashable k, Ord k) => HasLookup (HashMap k v) where type KeyT (HashMap k v) = k type ValueT (HashMap k v) = v lookup k m = HashMap.lookup k m isMemberOf = HashMap.member instance (Hashable k, Ord k) => MapLike (HashMap k v) where mapInsert k v m = HashMap.insert k v m mapDelete k m = HashMap.delete k m keys m = HashMap.keys m values m = HashMap.elems m hasKey = flip HashMap.member instance MapFoldable HashMap.HashMap where mapWithKey = HashMap.mapWithKey foldrWithKey = HashMap.foldrWithKey foldlWithKey = HashMap.foldlWithKey' -- Not yet, see TODO. This would remap your keys, too! --instance (Ord b) => ContainerMappable (HashMap ka a) (HashMap kb b) where -- cmap = ...
xicesky/sky-haskell-playground
src/Sky/Util/NewContainer.hs
bsd-3-clause
14,533
0
14
3,639
3,861
2,068
1,793
255
0
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} -- | Logic related to downloading update. module Pos.Network.Update.Download ( installerHash , downloadUpdate ) where import Universum import Control.Exception.Safe (handleAny) import Control.Lens (views) import Control.Monad.Except (ExceptT (..), throwError) import qualified Data.ByteArray as BA import qualified Data.ByteString.Lazy as BSL import qualified Data.HashMap.Strict as HM import Formatting (build, sformat, stext, (%)) import Network.HTTP.Client (Manager, newManager) import Network.HTTP.Client.TLS (tlsManagerSettings) import Network.HTTP.Simple (getResponseBody, getResponseStatus, getResponseStatusCode, httpLBS, parseRequest, setRequestManager) import qualified Serokell.Util.Base16 as B16 import Serokell.Util.Text (listJsonIndent, mapJson) import System.Directory (doesFileExist) import Pos.Binary.Class (Raw) import Pos.Chain.Update (ConfirmedProposalState (..), SoftwareVersion (..), UpdateConfiguration, UpdateData (..), UpdateParams (..), UpdateProposal (..), curSoftwareVersion, ourSystemTag) import Pos.Core.Exception (reportFatalError) import Pos.Crypto (Hash, castHash, hash) import Pos.DB.Update (UpdateContext (..), isUpdateInstalled) import Pos.Infra.Reporting (reportOrLogW) import Pos.Listener.Update (UpdateMode) import Pos.Util.Concurrent (withMVar) import Pos.Util.Util (HasLens (..), (<//>)) import Pos.Util.Wlog (WithLogger, logDebug, logInfo, logWarning) -- | Compute hash of installer, this is hash is 'udPkgHash' from 'UpdateData'. -- -- NB: we compute it by first CBOR-encoding it and then applying hash -- function, which is a bit strange, but it's done for historical -- reasons. installerHash :: LByteString -> Hash Raw installerHash = castHash . hash -- | Download a software update for given 'ConfirmedProposalState' and -- put it into a variable which holds 'ConfirmedProposalState' of -- downloaded update. -- Parallel downloads aren't supported, so this function may blocks. -- If we have already downloaded an update successfully, this function won't -- download new updates. -- -- The caller must ensure that: -- 1. This update is for our software. -- 2. This update is for our system (according to system tag). -- 3. This update brings newer software version than our current version. downloadUpdate :: forall ctx m . UpdateMode ctx m => ConfirmedProposalState -> m () downloadUpdate cps = do downloadLock <- ucDownloadLock <$> view (lensOf @UpdateContext) withMVar downloadLock $ \() -> do downloadedUpdateMVar <- ucDownloadedUpdate <$> view (lensOf @UpdateContext) tryReadMVar downloadedUpdateMVar >>= \case Nothing -> do updHash <- getUpdateHash cps installed <- isUpdateInstalled updHash if installed then onAlreadyInstalled else downloadUpdateDo updHash cps Just existingCPS -> onAlreadyDownloaded existingCPS where proposalToDL = cpsUpdateProposal cps onAlreadyDownloaded ConfirmedProposalState {..} = logInfo $ sformat ("We won't download an update for proposal "%build% ", because we have already downloaded another update: "%build% " and we are waiting for it to be applied") proposalToDL cpsUpdateProposal onAlreadyInstalled = logInfo $ sformat ("We won't download an update for proposal "%build% ", because it's already installed") proposalToDL getUpdateHash :: UpdateMode ctx m => ConfirmedProposalState -> m (Hash Raw) getUpdateHash ConfirmedProposalState{..} = do useInstaller <- views (lensOf @UpdateParams) upUpdateWithPkg uc <- view (lensOf @UpdateConfiguration) let data_ = upData cpsUpdateProposal dataHash = if useInstaller then udPkgHash else udAppDiffHash mupdHash = dataHash <$> HM.lookup (ourSystemTag uc) data_ logDebug $ sformat ("Proposal's upData: "%mapJson) data_ -- It must be enforced by the caller. maybe (reportFatalError $ sformat ("We are trying to download an update not for our "% "system, update proposal is: "%build) cpsUpdateProposal) pure mupdHash -- Download and save archive update by given `ConfirmedProposalState` downloadUpdateDo :: UpdateMode ctx m => Hash Raw -> ConfirmedProposalState -> m () downloadUpdateDo updHash cps@ConfirmedProposalState {..} = do updateServers <- views (lensOf @UpdateParams) upUpdateServers uc <- view (lensOf @UpdateConfiguration) logInfo $ sformat ("We are going to start downloading an update for "%build) cpsUpdateProposal res <- handleAny handleErr $ runExceptT $ do let updateVersion = upSoftwareVersion cpsUpdateProposal -- It's just a sanity check which must always pass due to the -- outside logic. We take only updates for our software and -- explicitly request only new updates. This invariant must be -- ensure by the caller of 'downloadUpdate'. unless (isVersionAppropriate uc updateVersion) $ reportFatalError $ sformat ("Update #"%build%" hasn't been downloaded: "% "its version is not newer than current software "% "software version or it's not for our "% "software at all") updHash updPath <- views (lensOf @UpdateParams) upUpdatePath whenM (liftIO $ doesFileExist updPath) $ throwError "There's unapplied update already downloaded" logInfo "Downloading update..." file <- ExceptT $ downloadHash updateServers updHash <&> first (sformat ("Update download (hash "%build% ") has failed: "%stext) updHash) logInfo $ "Update was downloaded, saving to " <> show updPath liftIO $ BSL.writeFile updPath file logInfo $ "Update was downloaded, saved to " <> show updPath downloadedMVar <- views (lensOf @UpdateContext) ucDownloadedUpdate putMVar downloadedMVar cps logInfo "Update MVar filled, wallet is notified" whenLeft res logDownloadError where handleErr e = Left (pretty e) <$ reportOrLogW "Update downloading failed: " e logDownloadError e = logWarning $ sformat ("Failed to download update proposal "%build%": "%stext) cpsUpdateProposal e -- Check that we really should download an update with given -- 'SoftwareVersion'. isVersionAppropriate :: UpdateConfiguration -> SoftwareVersion -> Bool isVersionAppropriate uc ver = svAppName ver == svAppName (curSoftwareVersion uc) && svNumber ver > svNumber (curSoftwareVersion uc) -- Download a file by its hash. -- -- Tries all servers in turn, fails if none of them work. downloadHash :: (MonadIO m, WithLogger m) => [Text] -> Hash Raw -> m (Either Text LByteString) downloadHash updateServers h = do manager <- liftIO $ newManager tlsManagerSettings let -- try all servers in turn until there's a Right go errs (serv:rest) = do let uri = toString serv <//> showHash h logDebug $ "Trying url " <> show uri liftIO (downloadUri manager uri h) >>= \case Left e -> go (e:errs) rest Right r -> return (Right r) -- if there were no servers, that's really weird go [] [] = return . Left $ "no update servers are known" -- if we've tried all servers already, fail go errs [] = return . Left $ sformat ("all update servers failed: "%listJsonIndent 2) (reverse errs) go [] updateServers where showHash :: Hash a -> FilePath showHash = toString . B16.encode . BA.convert -- Download a file and check its hash. downloadUri :: Manager -> String -> Hash Raw -> IO (Either Text LByteString) downloadUri manager uri h = do request <- setRequestManager manager <$> parseRequest uri resp <- httpLBS request let (st, stc) = (getResponseStatus resp, getResponseStatusCode resp) h' = installerHash (getResponseBody resp) return $ if | stc /= 200 -> Left ("error, " <> show st) | h /= h' -> Left "hash mismatch" | otherwise -> Right (getResponseBody resp) {- TODO * check timeouts? * how should we in general deal with e.g. 1B/s download speed? * if we expect updates to be big, use laziness/conduits (httpLBS isn't lazy, despite the “L” in its name) -}
input-output-hk/pos-haskell-prototype
lib/src/Pos/Network/Update/Download.hs
mit
8,997
0
19
2,467
1,799
938
861
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.KMS.CreateKey -- Copyright : (c) 2013-2015 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) -- -- Creates a customer master key. Customer master keys can be used to -- encrypt small amounts of data (less than 4K) directly, but they are most -- commonly used to encrypt or envelope data keys that are then used to -- encrypt customer data. For more information about data keys, see -- GenerateDataKey and GenerateDataKeyWithoutPlaintext. -- -- /See:/ <http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html AWS API Reference> for CreateKey. module Network.AWS.KMS.CreateKey ( -- * Creating a Request createKey , CreateKey -- * Request Lenses , ckKeyUsage , ckPolicy , ckDescription -- * Destructuring the Response , createKeyResponse , CreateKeyResponse -- * Response Lenses , ckrsKeyMetadata , ckrsResponseStatus ) where import Network.AWS.KMS.Types import Network.AWS.KMS.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'createKey' smart constructor. data CreateKey = CreateKey' { _ckKeyUsage :: !(Maybe KeyUsageType) , _ckPolicy :: !(Maybe Text) , _ckDescription :: !(Maybe Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateKey' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ckKeyUsage' -- -- * 'ckPolicy' -- -- * 'ckDescription' createKey :: CreateKey createKey = CreateKey' { _ckKeyUsage = Nothing , _ckPolicy = Nothing , _ckDescription = Nothing } -- | Specifies the intended use of the key. Currently this defaults to -- ENCRYPT\/DECRYPT, and only symmetric encryption and decryption are -- supported. ckKeyUsage :: Lens' CreateKey (Maybe KeyUsageType) ckKeyUsage = lens _ckKeyUsage (\ s a -> s{_ckKeyUsage = a}); -- | Policy to be attached to the key. This is required and delegates back to -- the account. The key is the root of trust. ckPolicy :: Lens' CreateKey (Maybe Text) ckPolicy = lens _ckPolicy (\ s a -> s{_ckPolicy = a}); -- | Description of the key. We recommend that you choose a description that -- helps your customer decide whether the key is appropriate for a task. ckDescription :: Lens' CreateKey (Maybe Text) ckDescription = lens _ckDescription (\ s a -> s{_ckDescription = a}); instance AWSRequest CreateKey where type Rs CreateKey = CreateKeyResponse request = postJSON kMS response = receiveJSON (\ s h x -> CreateKeyResponse' <$> (x .?> "KeyMetadata") <*> (pure (fromEnum s))) instance ToHeaders CreateKey where toHeaders = const (mconcat ["X-Amz-Target" =# ("TrentService.CreateKey" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON CreateKey where toJSON CreateKey'{..} = object (catMaybes [("KeyUsage" .=) <$> _ckKeyUsage, ("Policy" .=) <$> _ckPolicy, ("Description" .=) <$> _ckDescription]) instance ToPath CreateKey where toPath = const "/" instance ToQuery CreateKey where toQuery = const mempty -- | /See:/ 'createKeyResponse' smart constructor. data CreateKeyResponse = CreateKeyResponse' { _ckrsKeyMetadata :: !(Maybe KeyMetadata) , _ckrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateKeyResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ckrsKeyMetadata' -- -- * 'ckrsResponseStatus' createKeyResponse :: Int -- ^ 'ckrsResponseStatus' -> CreateKeyResponse createKeyResponse pResponseStatus_ = CreateKeyResponse' { _ckrsKeyMetadata = Nothing , _ckrsResponseStatus = pResponseStatus_ } -- | Metadata associated with the key. ckrsKeyMetadata :: Lens' CreateKeyResponse (Maybe KeyMetadata) ckrsKeyMetadata = lens _ckrsKeyMetadata (\ s a -> s{_ckrsKeyMetadata = a}); -- | The response status code. ckrsResponseStatus :: Lens' CreateKeyResponse Int ckrsResponseStatus = lens _ckrsResponseStatus (\ s a -> s{_ckrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-kms/gen/Network/AWS/KMS/CreateKey.hs
mpl-2.0
5,038
0
13
1,165
753
450
303
94
1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="hi-IN"> <title>HTTPS Info | ZAP Add-on</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/httpsInfo/src/main/javahelp/org/zaproxy/zap/extension/httpsinfo/resources/help_hi_IN/helpset_hi_IN.hs
apache-2.0
969
80
67
160
419
212
207
-1
-1
{- Author: George Karachalias <george.karachalias@cs.kuleuven.be> Pattern Matching Coverage Checking. -} {-# LANGUAGE CPP, GADTs, DataKinds, KindSignatures #-} module Check ( -- Checking and printing checkSingle, checkMatches, isAnyPmCheckEnabled, -- See Note [Type and Term Equality Propagation] genCaseTmCs1, genCaseTmCs2 ) where #include "HsVersions.h" import TmOracle import DynFlags import HsSyn import TcHsSyn import Id import ConLike import DataCon import Name import FamInstEnv import TysWiredIn import TyCon import SrcLoc import Util import Outputable import FastString import DsMonad -- DsM, initTcDsForSolver, getDictsDs import TcSimplify -- tcCheckSatisfiability import TcType -- toTcType, toTcTypeBag import Bag import ErrUtils import MonadUtils -- MonadIO import Var -- EvVar import Type import UniqSupply import DsGRHSs -- isTrueLHsExpr import Data.List -- find import Data.Maybe -- isNothing, isJust, fromJust import Control.Monad -- liftM3, forM import Coercion import TcEvidence import IOEnv {- This module checks pattern matches for: \begin{enumerate} \item Equations that are redundant \item Equations with inaccessible right-hand-side \item Exhaustiveness \end{enumerate} The algorithm is based on the paper: "GADTs Meet Their Match: Pattern-matching Warnings That Account for GADTs, Guards, and Laziness" http://people.cs.kuleuven.be/~george.karachalias/papers/p424-karachalias.pdf %************************************************************************ %* * Pattern Match Check Types %* * %************************************************************************ -} type PmM a = DsM a data PatTy = PAT | VA -- Used only as a kind, to index PmPat -- The *arity* of a PatVec [p1,..,pn] is -- the number of p1..pn that are not Guards data PmPat :: PatTy -> * where PmCon :: { pm_con_con :: DataCon , pm_con_arg_tys :: [Type] , pm_con_tvs :: [TyVar] , pm_con_dicts :: [EvVar] , pm_con_args :: [PmPat t] } -> PmPat t -- For PmCon arguments' meaning see @ConPatOut@ in hsSyn/HsPat.hs PmVar :: { pm_var_id :: Id } -> PmPat t PmLit :: { pm_lit_lit :: PmLit } -> PmPat t -- See Note [Literals in PmPat] PmNLit :: { pm_lit_id :: Id , pm_lit_not :: [PmLit] } -> PmPat 'VA PmGrd :: { pm_grd_pv :: PatVec , pm_grd_expr :: PmExpr } -> PmPat 'PAT -- data T a where -- MkT :: forall p q. (Eq p, Ord q) => p -> q -> T [p] -- or MkT :: forall p q r. (Eq p, Ord q, [p] ~ r) => p -> q -> T r type Pattern = PmPat 'PAT -- ^ Patterns type ValAbs = PmPat 'VA -- ^ Value Abstractions type PatVec = [Pattern] -- ^ Pattern Vectors data ValVec = ValVec [ValAbs] Delta -- ^ Value Vector Abstractions -- | Term and type constraints to accompany each value vector abstraction. -- For efficiency, we store the term oracle state instead of the term -- constraints. TODO: Do the same for the type constraints? data Delta = MkDelta { delta_ty_cs :: Bag EvVar , delta_tm_cs :: TmState } type ValSetAbs = [ValVec] -- ^ Value Set Abstractions type Uncovered = ValSetAbs -- Instead of keeping the whole sets in memory, we keep a boolean for both the -- covered and the divergent set (we store the uncovered set though, since we -- want to print it). For both the covered and the divergent we have: -- -- True <=> The set is non-empty -- -- hence: -- C = True ==> Useful clause (no warning) -- C = False, D = True ==> Clause with inaccessible RHS -- C = False, D = False ==> Redundant clause type Triple = (Bool, Uncovered, Bool) -- | Pattern check result -- -- * Redundant clauses -- * Not-covered clauses -- * Clauses with inaccessible RHS type PmResult = ([Located [LPat Id]], Uncovered, [Located [LPat Id]]) {- %************************************************************************ %* * Entry points to the checker: checkSingle and checkMatches %* * %************************************************************************ -} -- | Check a single pattern binding (let) checkSingle :: DynFlags -> DsMatchContext -> Id -> Pat Id -> DsM () checkSingle dflags ctxt@(DsMatchContext _ locn) var p = do mb_pm_res <- tryM (checkSingle' locn var p) case mb_pm_res of Left _ -> warnPmIters dflags ctxt Right res -> dsPmWarn dflags ctxt res -- | Check a single pattern binding (let) checkSingle' :: SrcSpan -> Id -> Pat Id -> DsM PmResult checkSingle' locn var p = do resetPmIterDs -- set the iter-no to zero fam_insts <- dsGetFamInstEnvs clause <- translatePat fam_insts p missing <- mkInitialUncovered [var] (cs,us,ds) <- runMany (pmcheckI clause []) missing -- no guards return $ case (cs,ds) of (True, _ ) -> ([], us, []) -- useful (False, False) -> ( m, us, []) -- redundant (False, True ) -> ([], us, m) -- inaccessible rhs where m = [L locn [L locn p]] -- | Check a matchgroup (case, functions, etc.) checkMatches :: DynFlags -> DsMatchContext -> [Id] -> [LMatch Id (LHsExpr Id)] -> DsM () checkMatches dflags ctxt vars matches = do mb_pm_res <- tryM (checkMatches' vars matches) case mb_pm_res of Left _ -> warnPmIters dflags ctxt Right res -> dsPmWarn dflags ctxt res -- | Check a matchgroup (case, functions, etc.) checkMatches' :: [Id] -> [LMatch Id (LHsExpr Id)] -> DsM PmResult checkMatches' vars matches | null matches = return ([], [], []) | otherwise = do resetPmIterDs -- set the iter-no to zero missing <- mkInitialUncovered vars (rs,us,ds) <- go matches missing return (map hsLMatchToLPats rs, us, map hsLMatchToLPats ds) where go [] missing = return ([], missing, []) go (m:ms) missing = do fam_insts <- dsGetFamInstEnvs (clause, guards) <- translateMatch fam_insts m (cs, missing', ds) <- runMany (pmcheckI clause guards) missing (rs, final_u, is) <- go ms missing' return $ case (cs, ds) of (True, _ ) -> ( rs, final_u, is) -- useful (False, False) -> (m:rs, final_u, is) -- redundant (False, True ) -> ( rs, final_u, m:is) -- inaccessible hsLMatchToLPats :: LMatch id body -> Located [LPat id] hsLMatchToLPats (L l (Match _ pats _ _)) = L l pats {- %************************************************************************ %* * Transform source syntax to *our* syntax %* * %************************************************************************ -} -- ----------------------------------------------------------------------- -- * Utilities nullaryConPattern :: DataCon -> Pattern -- Nullary data constructor and nullary type constructor nullaryConPattern con = PmCon { pm_con_con = con, pm_con_arg_tys = [] , pm_con_tvs = [], pm_con_dicts = [], pm_con_args = [] } {-# INLINE nullaryConPattern #-} truePattern :: Pattern truePattern = nullaryConPattern trueDataCon {-# INLINE truePattern #-} -- | A fake guard pattern (True <- _) used to represent cases we cannot handle fake_pat :: Pattern fake_pat = PmGrd { pm_grd_pv = [truePattern] , pm_grd_expr = PmExprOther EWildPat } {-# INLINE fake_pat #-} -- | Check whether a guard pattern is generated by the checker (unhandled) isFakeGuard :: [Pattern] -> PmExpr -> Bool isFakeGuard [PmCon { pm_con_con = c }] (PmExprOther EWildPat) | c == trueDataCon = True | otherwise = False isFakeGuard _pats _e = False -- | Generate a `canFail` pattern vector of a specific type mkCanFailPmPat :: Type -> PmM PatVec mkCanFailPmPat ty = do var <- mkPmVar ty return [var, fake_pat] vanillaConPattern :: DataCon -> [Type] -> PatVec -> Pattern -- ADT constructor pattern => no existentials, no local constraints vanillaConPattern con arg_tys args = PmCon { pm_con_con = con, pm_con_arg_tys = arg_tys , pm_con_tvs = [], pm_con_dicts = [], pm_con_args = args } {-# INLINE vanillaConPattern #-} -- | Create an empty list pattern of a given type nilPattern :: Type -> Pattern nilPattern ty = PmCon { pm_con_con = nilDataCon, pm_con_arg_tys = [ty] , pm_con_tvs = [], pm_con_dicts = [] , pm_con_args = [] } {-# INLINE nilPattern #-} mkListPatVec :: Type -> PatVec -> PatVec -> PatVec mkListPatVec ty xs ys = [PmCon { pm_con_con = consDataCon , pm_con_arg_tys = [ty] , pm_con_tvs = [], pm_con_dicts = [] , pm_con_args = xs++ys }] {-# INLINE mkListPatVec #-} -- | Create a (non-overloaded) literal pattern mkLitPattern :: HsLit -> Pattern mkLitPattern lit = PmLit { pm_lit_lit = PmSLit lit } {-# INLINE mkLitPattern #-} -- ----------------------------------------------------------------------- -- * Transform (Pat Id) into of (PmPat Id) translatePat :: FamInstEnvs -> Pat Id -> PmM PatVec translatePat fam_insts pat = case pat of WildPat ty -> mkPmVars [ty] VarPat id -> return [PmVar (unLoc id)] ParPat p -> translatePat fam_insts (unLoc p) LazyPat _ -> mkPmVars [hsPatType pat] -- like a variable -- ignore strictness annotations for now BangPat p -> translatePat fam_insts (unLoc p) AsPat lid p -> do -- Note [Translating As Patterns] ps <- translatePat fam_insts (unLoc p) let [e] = map vaToPmExpr (coercePatVec ps) g = PmGrd [PmVar (unLoc lid)] e return (ps ++ [g]) SigPatOut p _ty -> translatePat fam_insts (unLoc p) -- See Note [Translate CoPats] CoPat wrapper p ty | isIdHsWrapper wrapper -> translatePat fam_insts p | WpCast co <- wrapper, isReflexiveCo co -> translatePat fam_insts p | otherwise -> do ps <- translatePat fam_insts p (xp,xe) <- mkPmId2Forms ty let g = mkGuard ps (HsWrap wrapper (unLoc xe)) return [xp,g] -- (n + k) ===> x (True <- x >= k) (n <- x-k) NPlusKPat (L _ _n) _k1 _k2 _ge _minus ty -> mkCanFailPmPat ty -- (fun -> pat) ===> x (pat <- fun x) ViewPat lexpr lpat arg_ty -> do ps <- translatePat fam_insts (unLoc lpat) -- See Note [Guards and Approximation] case all cantFailPattern ps of True -> do (xp,xe) <- mkPmId2Forms arg_ty let g = mkGuard ps (HsApp lexpr xe) return [xp,g] False -> mkCanFailPmPat arg_ty -- list ListPat ps ty Nothing -> do foldr (mkListPatVec ty) [nilPattern ty] <$> translatePatVec fam_insts (map unLoc ps) -- overloaded list ListPat lpats elem_ty (Just (pat_ty, _to_list)) | Just e_ty <- splitListTyConApp_maybe pat_ty , (_, norm_elem_ty) <- normaliseType fam_insts Nominal elem_ty -- elem_ty is frequently something like -- `Item [Int]`, but we prefer `Int` , norm_elem_ty `eqType` e_ty -> -- We have to ensure that the element types are exactly the same. -- Otherwise, one may give an instance IsList [Int] (more specific than -- the default IsList [a]) with a different implementation for `toList' translatePat fam_insts (ListPat lpats e_ty Nothing) -- See Note [Guards and Approximation] | otherwise -> mkCanFailPmPat pat_ty ConPatOut { pat_con = L _ (PatSynCon _) } -> -- Pattern synonyms have a "matcher" -- (see Note [Pattern synonym representation] in PatSyn.hs -- We should be able to transform (P x y) -- to v (Just (x, y) <- matchP v (\x y -> Just (x,y)) Nothing -- That is, a combination of a variable pattern and a guard -- But there are complications with GADTs etc, and this isn't done yet mkCanFailPmPat (hsPatType pat) ConPatOut { pat_con = L _ (RealDataCon con) , pat_arg_tys = arg_tys , pat_tvs = ex_tvs , pat_dicts = dicts , pat_args = ps } -> do args <- translateConPatVec fam_insts arg_tys ex_tvs con ps return [PmCon { pm_con_con = con , pm_con_arg_tys = arg_tys , pm_con_tvs = ex_tvs , pm_con_dicts = dicts , pm_con_args = args }] NPat (L _ ol) mb_neg _eq ty -> translateNPat fam_insts ol mb_neg ty LitPat lit -- If it is a string then convert it to a list of characters | HsString src s <- lit -> foldr (mkListPatVec charTy) [nilPattern charTy] <$> translatePatVec fam_insts (map (LitPat . HsChar src) (unpackFS s)) | otherwise -> return [mkLitPattern lit] PArrPat ps ty -> do tidy_ps <- translatePatVec fam_insts (map unLoc ps) let fake_con = parrFakeCon (length ps) return [vanillaConPattern fake_con [ty] (concat tidy_ps)] TuplePat ps boxity tys -> do tidy_ps <- translatePatVec fam_insts (map unLoc ps) let tuple_con = tupleDataCon boxity (length ps) return [vanillaConPattern tuple_con tys (concat tidy_ps)] SumPat p alt arity ty -> do tidy_p <- translatePat fam_insts (unLoc p) let sum_con = sumDataCon alt arity return [vanillaConPattern sum_con ty tidy_p] -- -------------------------------------------------------------------------- -- Not supposed to happen ConPatIn {} -> panic "Check.translatePat: ConPatIn" SplicePat {} -> panic "Check.translatePat: SplicePat" SigPatIn {} -> panic "Check.translatePat: SigPatIn" -- | Translate an overloaded literal (see `tidyNPat' in deSugar/MatchLit.hs) translateNPat :: FamInstEnvs -> HsOverLit Id -> Maybe (SyntaxExpr Id) -> Type -> PmM PatVec translateNPat fam_insts (OverLit val False _ ty) mb_neg outer_ty | not type_change, isStringTy ty, HsIsString src s <- val, Nothing <- mb_neg = translatePat fam_insts (LitPat (HsString src s)) | not type_change, isIntTy ty, HsIntegral src i <- val = translatePat fam_insts (mk_num_lit HsInt src i) | not type_change, isWordTy ty, HsIntegral src i <- val = translatePat fam_insts (mk_num_lit HsWordPrim src i) where type_change = not (outer_ty `eqType` ty) mk_num_lit c src i = LitPat $ case mb_neg of Nothing -> c src i Just _ -> c src (-i) translateNPat _ ol mb_neg _ = return [PmLit { pm_lit_lit = PmOLit (isJust mb_neg) ol }] -- | Translate a list of patterns (Note: each pattern is translated -- to a pattern vector but we do not concatenate the results). translatePatVec :: FamInstEnvs -> [Pat Id] -> PmM [PatVec] translatePatVec fam_insts pats = mapM (translatePat fam_insts) pats -- | Translate a constructor pattern translateConPatVec :: FamInstEnvs -> [Type] -> [TyVar] -> DataCon -> HsConPatDetails Id -> PmM PatVec translateConPatVec fam_insts _univ_tys _ex_tvs _ (PrefixCon ps) = concat <$> translatePatVec fam_insts (map unLoc ps) translateConPatVec fam_insts _univ_tys _ex_tvs _ (InfixCon p1 p2) = concat <$> translatePatVec fam_insts (map unLoc [p1,p2]) translateConPatVec fam_insts univ_tys ex_tvs c (RecCon (HsRecFields fs _)) -- Nothing matched. Make up some fresh term variables | null fs = mkPmVars arg_tys -- The data constructor was not defined using record syntax. For the -- pattern to be in record syntax it should be empty (e.g. Just {}). -- So just like the previous case. | null orig_lbls = ASSERT(null matched_lbls) mkPmVars arg_tys -- Some of the fields appear, in the original order (there may be holes). -- Generate a simple constructor pattern and make up fresh variables for -- the rest of the fields | matched_lbls `subsetOf` orig_lbls = ASSERT(length orig_lbls == length arg_tys) let translateOne (lbl, ty) = case lookup lbl matched_pats of Just p -> translatePat fam_insts p Nothing -> mkPmVars [ty] in concatMapM translateOne (zip orig_lbls arg_tys) -- The fields that appear are not in the correct order. Make up fresh -- variables for all fields and add guards after matching, to force the -- evaluation in the correct order. | otherwise = do arg_var_pats <- mkPmVars arg_tys translated_pats <- forM matched_pats $ \(x,pat) -> do pvec <- translatePat fam_insts pat return (x, pvec) let zipped = zip orig_lbls [ x | PmVar x <- arg_var_pats ] guards = map (\(name,pvec) -> case lookup name zipped of Just x -> PmGrd pvec (PmExprVar (idName x)) Nothing -> panic "translateConPatVec: lookup") translated_pats return (arg_var_pats ++ guards) where -- The actual argument types (instantiated) arg_tys = dataConInstOrigArgTys c (univ_tys ++ mkTyVarTys ex_tvs) -- Some label information orig_lbls = map flSelector $ dataConFieldLabels c matched_pats = [ (getName (unLoc (hsRecFieldId x)), unLoc (hsRecFieldArg x)) | L _ x <- fs] matched_lbls = [ name | (name, _pat) <- matched_pats ] subsetOf :: Eq a => [a] -> [a] -> Bool subsetOf [] _ = True subsetOf (_:_) [] = False subsetOf (x:xs) (y:ys) | x == y = subsetOf xs ys | otherwise = subsetOf (x:xs) ys -- Translate a single match translateMatch :: FamInstEnvs -> LMatch Id (LHsExpr Id) -> PmM (PatVec,[PatVec]) translateMatch fam_insts (L _ (Match _ lpats _ grhss)) = do pats' <- concat <$> translatePatVec fam_insts pats guards' <- mapM (translateGuards fam_insts) guards return (pats', guards') where extractGuards :: LGRHS Id (LHsExpr Id) -> [GuardStmt Id] extractGuards (L _ (GRHS gs _)) = map unLoc gs pats = map unLoc lpats guards = map extractGuards (grhssGRHSs grhss) -- ----------------------------------------------------------------------- -- * Transform source guards (GuardStmt Id) to PmPats (Pattern) -- | Translate a list of guard statements to a pattern vector translateGuards :: FamInstEnvs -> [GuardStmt Id] -> PmM PatVec translateGuards fam_insts guards = do all_guards <- concat <$> mapM (translateGuard fam_insts) guards return (replace_unhandled all_guards) -- It should have been (return all_guards) but it is too expressive. -- Since the term oracle does not handle all constraints we generate, -- we (hackily) replace all constraints the oracle cannot handle with a -- single one (we need to know if there is a possibility of falure). -- See Note [Guards and Approximation] for all guard-related approximations -- we implement. where replace_unhandled :: PatVec -> PatVec replace_unhandled gv | any_unhandled gv = fake_pat : [ p | p <- gv, shouldKeep p ] | otherwise = gv any_unhandled :: PatVec -> Bool any_unhandled gv = any (not . shouldKeep) gv shouldKeep :: Pattern -> Bool shouldKeep p | PmVar {} <- p = True | PmCon {} <- p = length (allConstructors (pm_con_con p)) == 1 && all shouldKeep (pm_con_args p) shouldKeep (PmGrd pv e) | all shouldKeep pv = True | isNotPmExprOther e = True -- expensive but we want it shouldKeep _other_pat = False -- let the rest.. -- | Check whether a pattern can fail to match cantFailPattern :: Pattern -> Bool cantFailPattern p | PmVar {} <- p = True | PmCon {} <- p = length (allConstructors (pm_con_con p)) == 1 && all cantFailPattern (pm_con_args p) cantFailPattern (PmGrd pv _e) = all cantFailPattern pv cantFailPattern _ = False -- | Translate a guard statement to Pattern translateGuard :: FamInstEnvs -> GuardStmt Id -> PmM PatVec translateGuard fam_insts guard = case guard of BodyStmt e _ _ _ -> translateBoolGuard e LetStmt binds -> translateLet (unLoc binds) BindStmt p e _ _ _ -> translateBind fam_insts p e LastStmt {} -> panic "translateGuard LastStmt" ParStmt {} -> panic "translateGuard ParStmt" TransStmt {} -> panic "translateGuard TransStmt" RecStmt {} -> panic "translateGuard RecStmt" ApplicativeStmt {} -> panic "translateGuard ApplicativeLastStmt" -- | Translate let-bindings translateLet :: HsLocalBinds Id -> PmM PatVec translateLet _binds = return [] -- | Translate a pattern guard translateBind :: FamInstEnvs -> LPat Id -> LHsExpr Id -> PmM PatVec translateBind fam_insts (L _ p) e = do ps <- translatePat fam_insts p return [mkGuard ps (unLoc e)] -- | Translate a boolean guard translateBoolGuard :: LHsExpr Id -> PmM PatVec translateBoolGuard e | isJust (isTrueLHsExpr e) = return [] -- The formal thing to do would be to generate (True <- True) -- but it is trivial to solve so instead we give back an empty -- PatVec for efficiency | otherwise = return [mkGuard [truePattern] (unLoc e)] {- Note [Guards and Approximation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Even if the algorithm is really expressive, the term oracle we use is not. Hence, several features are not translated *properly* but we approximate. The list includes: 1. View Patterns ---------------- A view pattern @(f -> p)@ should be translated to @x (p <- f x)@. The term oracle does not handle function applications so we know that the generated constraints will not be handled at the end. Hence, we distinguish between two cases: a) Pattern @p@ cannot fail. Then this is just a binding and we do the *right thing*. b) Pattern @p@ can fail. This means that when checking the guard, we will generate several cases, with no useful information. E.g.: h (f -> [a,b]) = ... h x ([a,b] <- f x) = ... uncovered set = { [x |> { False ~ (f x ~ []) }] , [x |> { False ~ (f x ~ (t1:[])) }] , [x |> { False ~ (f x ~ (t1:t2:t3:t4)) }] } So we have two problems: 1) Since we do not print the constraints in the general case (they may be too many), the warning will look like this: Pattern match(es) are non-exhaustive In an equation for `h': Patterns not matched: _ _ _ Which is not short and not more useful than a single underscore. 2) The size of the uncovered set increases a lot, without gaining more expressivity in our warnings. Hence, in this case, we replace the guard @([a,b] <- f x)@ with a *dummy* @fake_pat@: @True <- _@. That is, we record that there is a possibility of failure but we minimize it to a True/False. This generates a single warning and much smaller uncovered sets. 2. Overloaded Lists ------------------- An overloaded list @[...]@ should be translated to @x ([...] <- toList x)@. The problem is exactly like above, as its solution. For future reference, the code below is the *right thing to do*: ListPat lpats elem_ty (Just (pat_ty, to_list)) otherwise -> do (xp, xe) <- mkPmId2Forms pat_ty ps <- translatePatVec (map unLoc lpats) let pats = foldr (mkListPatVec elem_ty) [nilPattern elem_ty] ps g = mkGuard pats (HsApp (noLoc to_list) xe) return [xp,g] 3. Overloaded Literals ---------------------- The case with literals is a bit different. a literal @l@ should be translated to @x (True <- x == from l)@. Since we want to have better warnings for overloaded literals as it is a very common feature, we treat them differently. They are mainly covered in Note [Undecidable Equality on Overloaded Literals] in PmExpr. 4. N+K Patterns & Pattern Synonyms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An n+k pattern (n+k) should be translated to @x (True <- x >= k) (n <- x-k)@. Since the only pattern of the three that causes failure is guard @(n <- x-k)@, and has two possible outcomes. Hence, there is no benefit in using a dummy and we implement the proper thing. Pattern synonyms are simply not implemented yet. Hence, to be conservative, we generate a dummy pattern, assuming that the pattern can fail. 5. Actual Guards ---------------- During translation, boolean guards and pattern guards are translated properly. Let bindings though are omitted by function @translateLet@. Since they are lazy bindings, we do not actually want to generate a (strict) equality (like we do in the pattern bind case). Hence, we safely drop them. Additionally, top-level guard translation (performed by @translateGuards@) replaces guards that cannot be reasoned about (like the ones we described in 1-4) with a single @fake_pat@ to record the possibility of failure to match. Note [Translate CoPats] ~~~~~~~~~~~~~~~~~~~~~~~ The pattern match checker did not know how to handle coerced patterns `CoPat` efficiently, which gave rise to #11276. The original approach translated `CoPat`s: pat |> co ===> x (pat <- (e |> co)) Instead, we now check whether the coercion is a hole or if it is just refl, in which case we can drop it. Unfortunately, data families generate useful coercions so guards are still generated in these cases and checking data families is not really efficient. %************************************************************************ %* * Utilities for Pattern Match Checking %* * %************************************************************************ -} -- ---------------------------------------------------------------------------- -- * Basic utilities -- | Get the type out of a PmPat. For guard patterns (ps <- e) we use the type -- of the first (or the single -WHEREVER IT IS- valid to use?) pattern pmPatType :: PmPat p -> Type pmPatType (PmCon { pm_con_con = con, pm_con_arg_tys = tys }) = mkTyConApp (dataConTyCon con) tys pmPatType (PmVar { pm_var_id = x }) = idType x pmPatType (PmLit { pm_lit_lit = l }) = pmLitType l pmPatType (PmNLit { pm_lit_id = x }) = idType x pmPatType (PmGrd { pm_grd_pv = pv }) = ASSERT(patVecArity pv == 1) (pmPatType p) where Just p = find ((==1) . patternArity) pv -- | Generate a value abstraction for a given constructor (generate -- fresh variables of the appropriate type for arguments) mkOneConFull :: Id -> DataCon -> PmM (ValAbs, ComplexEq, Bag EvVar) -- * x :: T tys, where T is an algebraic data type -- NB: in the case of a data familiy, T is the *representation* TyCon -- e.g. data instance T (a,b) = T1 a b -- leads to -- data TPair a b = T1 a b -- The "representation" type -- It is TPair, not T, that is given to mkOneConFull -- -- * 'con' K is a constructor of data type T -- -- After instantiating the universal tyvars of K we get -- K tys :: forall bs. Q => s1 .. sn -> T tys -- -- Results: ValAbs: K (y1::s1) .. (yn::sn) -- ComplexEq: x ~ K y1..yn -- [EvVar]: Q mkOneConFull x con = do let -- res_ty == TyConApp (dataConTyCon cabs_con) cabs_arg_tys res_ty = idType x (univ_tvs, ex_tvs, eq_spec, thetas, arg_tys, _) = dataConFullSig con data_tc = dataConTyCon con -- The representation TyCon tc_args = case splitTyConApp_maybe res_ty of Just (tc, tys) -> ASSERT( tc == data_tc ) tys Nothing -> pprPanic "mkOneConFull: Not TyConApp:" (ppr res_ty) subst1 = zipTvSubst univ_tvs tc_args (subst, ex_tvs') <- cloneTyVarBndrs subst1 ex_tvs <$> getUniqueSupplyM -- Fresh term variables (VAs) as arguments to the constructor arguments <- mapM mkPmVar (substTys subst arg_tys) -- All constraints bound by the constructor (alpha-renamed) let theta_cs = substTheta subst (eqSpecPreds eq_spec ++ thetas) evvars <- mapM (nameType "pm") theta_cs let con_abs = PmCon { pm_con_con = con , pm_con_arg_tys = tc_args , pm_con_tvs = ex_tvs' , pm_con_dicts = evvars , pm_con_args = arguments } return (con_abs, (PmExprVar (idName x), vaToPmExpr con_abs), listToBag evvars) -- ---------------------------------------------------------------------------- -- * More smart constructors and fresh variable generation -- | Create a guard pattern mkGuard :: PatVec -> HsExpr Id -> Pattern mkGuard pv e | all cantFailPattern pv = PmGrd pv expr | PmExprOther {} <- expr = fake_pat | otherwise = PmGrd pv expr where expr = hsExprToPmExpr e -- | Create a term equality of the form: `(False ~ (x ~ lit))` mkNegEq :: Id -> PmLit -> ComplexEq mkNegEq x l = (falsePmExpr, PmExprVar (idName x) `PmExprEq` PmExprLit l) {-# INLINE mkNegEq #-} -- | Create a term equality of the form: `(x ~ lit)` mkPosEq :: Id -> PmLit -> ComplexEq mkPosEq x l = (PmExprVar (idName x), PmExprLit l) {-# INLINE mkPosEq #-} -- | Generate a variable pattern of a given type mkPmVar :: Type -> PmM (PmPat p) mkPmVar ty = PmVar <$> mkPmId ty {-# INLINE mkPmVar #-} -- | Generate many variable patterns, given a list of types mkPmVars :: [Type] -> PmM PatVec mkPmVars tys = mapM mkPmVar tys {-# INLINE mkPmVars #-} -- | Generate a fresh `Id` of a given type mkPmId :: Type -> PmM Id mkPmId ty = getUniqueM >>= \unique -> let occname = mkVarOccFS (fsLit (show unique)) name = mkInternalName unique occname noSrcSpan in return (mkLocalId name ty) -- | Generate a fresh term variable of a given and return it in two forms: -- * A variable pattern -- * A variable expression mkPmId2Forms :: Type -> PmM (Pattern, LHsExpr Id) mkPmId2Forms ty = do x <- mkPmId ty return (PmVar x, noLoc (HsVar (noLoc x))) -- ---------------------------------------------------------------------------- -- * Converting between Value Abstractions, Patterns and PmExpr -- | Convert a value abstraction an expression vaToPmExpr :: ValAbs -> PmExpr vaToPmExpr (PmCon { pm_con_con = c, pm_con_args = ps }) = PmExprCon c (map vaToPmExpr ps) vaToPmExpr (PmVar { pm_var_id = x }) = PmExprVar (idName x) vaToPmExpr (PmLit { pm_lit_lit = l }) = PmExprLit l vaToPmExpr (PmNLit { pm_lit_id = x }) = PmExprVar (idName x) -- | Convert a pattern vector to a list of value abstractions by dropping the -- guards (See Note [Translating As Patterns]) coercePatVec :: PatVec -> [ValAbs] coercePatVec pv = concatMap coercePmPat pv -- | Convert a pattern to a list of value abstractions (will be either an empty -- list if the pattern is a guard pattern, or a singleton list in all other -- cases) by dropping the guards (See Note [Translating As Patterns]) coercePmPat :: Pattern -> [ValAbs] coercePmPat (PmVar { pm_var_id = x }) = [PmVar { pm_var_id = x }] coercePmPat (PmLit { pm_lit_lit = l }) = [PmLit { pm_lit_lit = l }] coercePmPat (PmCon { pm_con_con = con, pm_con_arg_tys = arg_tys , pm_con_tvs = tvs, pm_con_dicts = dicts , pm_con_args = args }) = [PmCon { pm_con_con = con, pm_con_arg_tys = arg_tys , pm_con_tvs = tvs, pm_con_dicts = dicts , pm_con_args = coercePatVec args }] coercePmPat (PmGrd {}) = [] -- drop the guards -- | Get all constructors in the family (including given) allConstructors :: DataCon -> [DataCon] allConstructors = tyConDataCons . dataConTyCon -- ----------------------------------------------------------------------- -- * Types and constraints newEvVar :: Name -> Type -> EvVar newEvVar name ty = mkLocalId name (toTcType ty) nameType :: String -> Type -> PmM EvVar nameType name ty = do unique <- getUniqueM let occname = mkVarOccFS (fsLit (name++"_"++show unique)) idname = mkInternalName unique occname noSrcSpan return (newEvVar idname ty) {- %************************************************************************ %* * The type oracle %* * %************************************************************************ -} -- | Check whether a set of type constraints is satisfiable. tyOracle :: Bag EvVar -> PmM Bool tyOracle evs = do { ((_warns, errs), res) <- initTcDsForSolver $ tcCheckSatisfiability evs ; case res of Just sat -> return sat Nothing -> pprPanic "tyOracle" (vcat $ pprErrMsgBagWithLoc errs) } {- %************************************************************************ %* * Sanity Checks %* * %************************************************************************ -} -- | The arity of a pattern/pattern vector is the -- number of top-level patterns that are not guards type PmArity = Int -- | Compute the arity of a pattern vector patVecArity :: PatVec -> PmArity patVecArity = sum . map patternArity -- | Compute the arity of a pattern patternArity :: Pattern -> PmArity patternArity (PmGrd {}) = 0 patternArity _other_pat = 1 {- %************************************************************************ %* * Heart of the algorithm: Function pmcheck %* * %************************************************************************ Main functions are: * mkInitialUncovered :: [Id] -> PmM Uncovered Generates the initial uncovered set. Term and type constraints in scope are checked, if they are inconsistent, the set is empty, otherwise, the set contains only a vector of variables with the constraints in scope. * pmcheck :: PatVec -> [PatVec] -> ValVec -> PmM Triple Checks redundancy, coverage and inaccessibility, using auxilary functions `pmcheckGuards` and `pmcheckHd`. Mainly handles the guard case which is common in all three checks (see paper) and calls `pmcheckGuards` when the whole clause is checked, or `pmcheckHd` when the pattern vector does not start with a guard. * pmcheckGuards :: [PatVec] -> ValVec -> PmM Triple Processes the guards. * pmcheckHd :: Pattern -> PatVec -> [PatVec] -> ValAbs -> ValVec -> PmM Triple Worker: This function implements functions `covered`, `uncovered` and `divergent` from the paper at once. Slightly different from the paper because it does not even produce the covered and uncovered sets. Since we only care about whether a clause covers SOMETHING or if it may forces ANY argument, we only store a boolean in both cases, for efficiency. -} -- | Lift a pattern matching action from a single value vector abstration to a -- value set abstraction, but calling it on every vector and the combining the -- results. runMany :: (ValVec -> PmM Triple) -> (Uncovered -> PmM Triple) runMany pm us = mapAndUnzip3M pm us >>= \(css, uss, dss) -> return (or css, concat uss, or dss) {-# INLINE runMany #-} -- | Generate the initial uncovered set. It initializes the -- delta with all term and type constraints in scope. mkInitialUncovered :: [Id] -> PmM Uncovered mkInitialUncovered vars = do ty_cs <- getDictsDs tm_cs <- map toComplex . bagToList <$> getTmCsDs sat_ty <- tyOracle ty_cs return $ case (sat_ty, tmOracle initialTmState tm_cs) of (True, Just tm_state) -> [ValVec patterns (MkDelta ty_cs tm_state)] -- If any of the term/type constraints are non -- satisfiable, the initial uncovered set is empty _non_satisfiable -> [] where patterns = map PmVar vars -- | Increase the counter for elapsed algorithm iterations, check that the -- limit is not exceeded and call `pmcheck` pmcheckI :: PatVec -> [PatVec] -> ValVec -> PmM Triple pmcheckI ps guards vva = incrCheckPmIterDs >> pmcheck ps guards vva {-# INLINE pmcheckI #-} -- | Increase the counter for elapsed algorithm iterations, check that the -- limit is not exceeded and call `pmcheckGuards` pmcheckGuardsI :: [PatVec] -> ValVec -> PmM Triple pmcheckGuardsI gvs vva = incrCheckPmIterDs >> pmcheckGuards gvs vva {-# INLINE pmcheckGuardsI #-} -- | Increase the counter for elapsed algorithm iterations, check that the -- limit is not exceeded and call `pmcheckHd` pmcheckHdI :: Pattern -> PatVec -> [PatVec] -> ValAbs -> ValVec -> PmM Triple pmcheckHdI p ps guards va vva = incrCheckPmIterDs >> pmcheckHd p ps guards va vva {-# INLINE pmcheckHdI #-} -- | Matching function: Check simultaneously a clause (takes separately the -- patterns and the list of guards) for exhaustiveness, redundancy and -- inaccessibility. pmcheck :: PatVec -> [PatVec] -> ValVec -> PmM Triple pmcheck [] guards vva@(ValVec [] _) | null guards = return (True, [], False) | otherwise = pmcheckGuardsI guards vva -- Guard pmcheck (p@(PmGrd pv e) : ps) guards vva@(ValVec vas delta) -- short-circuit if the guard pattern is useless. -- we just have two possible outcomes: fail here or match and recurse -- none of the two contains any useful information about the failure -- though. So just have these two cases but do not do all the boilerplate | isFakeGuard pv e = forces . mkCons vva <$> pmcheckI ps guards vva | otherwise = do y <- mkPmId (pmPatType p) let tm_state = extendSubst y e (delta_tm_cs delta) delta' = delta { delta_tm_cs = tm_state } utail <$> pmcheckI (pv ++ ps) guards (ValVec (PmVar y : vas) delta') pmcheck [] _ (ValVec (_:_) _) = panic "pmcheck: nil-cons" pmcheck (_:_) _ (ValVec [] _) = panic "pmcheck: cons-nil" pmcheck (p:ps) guards (ValVec (va:vva) delta) = pmcheckHdI p ps guards va (ValVec vva delta) -- | Check the list of guards pmcheckGuards :: [PatVec] -> ValVec -> PmM Triple pmcheckGuards [] vva = return (False, [vva], False) pmcheckGuards (gv:gvs) vva = do (cs, vsa, ds ) <- pmcheckI gv [] vva (css, vsas, dss) <- runMany (pmcheckGuardsI gvs) vsa return (cs || css, vsas, ds || dss) -- | Worker function: Implements all cases described in the paper for all three -- functions (`covered`, `uncovered` and `divergent`) apart from the `Guard` -- cases which are handled by `pmcheck` pmcheckHd :: Pattern -> PatVec -> [PatVec] -> ValAbs -> ValVec -> PmM Triple -- Var pmcheckHd (PmVar x) ps guards va (ValVec vva delta) | Just tm_state <- solveOneEq (delta_tm_cs delta) (PmExprVar (idName x), vaToPmExpr va) = ucon va <$> pmcheckI ps guards (ValVec vva (delta {delta_tm_cs = tm_state})) | otherwise = return (False, [], False) -- ConCon pmcheckHd ( p@(PmCon {pm_con_con = c1, pm_con_args = args1})) ps guards (va@(PmCon {pm_con_con = c2, pm_con_args = args2})) (ValVec vva delta) | c1 /= c2 = return (False, [ValVec (va:vva) delta], False) | otherwise = kcon c1 (pm_con_arg_tys p) (pm_con_tvs p) (pm_con_dicts p) <$> pmcheckI (args1 ++ ps) guards (ValVec (args2 ++ vva) delta) -- LitLit pmcheckHd (PmLit l1) ps guards (va@(PmLit l2)) vva = case eqPmLit l1 l2 of True -> ucon va <$> pmcheckI ps guards vva False -> return $ ucon va (False, [vva], False) -- ConVar pmcheckHd (p@(PmCon { pm_con_con = con })) ps guards (PmVar x) (ValVec vva delta) = do cons_cs <- mapM (mkOneConFull x) (allConstructors con) inst_vsa <- flip concatMapM cons_cs $ \(va, tm_ct, ty_cs) -> do let ty_state = ty_cs `unionBags` delta_ty_cs delta -- not actually a state sat_ty <- if isEmptyBag ty_cs then return True else tyOracle ty_state return $ case (sat_ty, solveOneEq (delta_tm_cs delta) tm_ct) of (True, Just tm_state) -> [ValVec (va:vva) (MkDelta ty_state tm_state)] _ty_or_tm_failed -> [] force_if (canDiverge (idName x) (delta_tm_cs delta)) <$> runMany (pmcheckI (p:ps) guards) inst_vsa -- LitVar pmcheckHd (p@(PmLit l)) ps guards (PmVar x) (ValVec vva delta) = force_if (canDiverge (idName x) (delta_tm_cs delta)) <$> mkUnion non_matched <$> case solveOneEq (delta_tm_cs delta) (mkPosEq x l) of Just tm_state -> pmcheckHdI p ps guards (PmLit l) $ ValVec vva (delta {delta_tm_cs = tm_state}) Nothing -> return (False, [], False) where us | Just tm_state <- solveOneEq (delta_tm_cs delta) (mkNegEq x l) = [ValVec (PmNLit x [l] : vva) (delta { delta_tm_cs = tm_state })] | otherwise = [] non_matched = (False, us, False) -- LitNLit pmcheckHd (p@(PmLit l)) ps guards (PmNLit { pm_lit_id = x, pm_lit_not = lits }) (ValVec vva delta) | all (not . eqPmLit l) lits , Just tm_state <- solveOneEq (delta_tm_cs delta) (mkPosEq x l) -- Both guards check the same so it would be sufficient to have only -- the second one. Nevertheless, it is much cheaper to check whether -- the literal is in the list so we check it first, to avoid calling -- the term oracle (`solveOneEq`) if possible = mkUnion non_matched <$> pmcheckHdI p ps guards (PmLit l) (ValVec vva (delta { delta_tm_cs = tm_state })) | otherwise = return non_matched where us | Just tm_state <- solveOneEq (delta_tm_cs delta) (mkNegEq x l) = [ValVec (PmNLit x (l:lits) : vva) (delta { delta_tm_cs = tm_state })] | otherwise = [] non_matched = (False, us, False) -- ---------------------------------------------------------------------------- -- The following three can happen only in cases like #322 where constructors -- and overloaded literals appear in the same match. The general strategy is -- to replace the literal (positive/negative) by a variable and recurse. The -- fact that the variable is equal to the literal is recorded in `delta` so -- no information is lost -- LitCon pmcheckHd (PmLit l) ps guards (va@(PmCon {})) (ValVec vva delta) = do y <- mkPmId (pmPatType va) let tm_state = extendSubst y (PmExprLit l) (delta_tm_cs delta) delta' = delta { delta_tm_cs = tm_state } pmcheckHdI (PmVar y) ps guards va (ValVec vva delta') -- ConLit pmcheckHd (p@(PmCon {})) ps guards (PmLit l) (ValVec vva delta) = do y <- mkPmId (pmPatType p) let tm_state = extendSubst y (PmExprLit l) (delta_tm_cs delta) delta' = delta { delta_tm_cs = tm_state } pmcheckHdI p ps guards (PmVar y) (ValVec vva delta') -- ConNLit pmcheckHd (p@(PmCon {})) ps guards (PmNLit { pm_lit_id = x }) vva = pmcheckHdI p ps guards (PmVar x) vva -- Impossible: handled by pmcheck pmcheckHd (PmGrd {}) _ _ _ _ = panic "pmcheckHd: Guard" -- ---------------------------------------------------------------------------- -- * Utilities for main checking -- | Take the tail of all value vector abstractions in the uncovered set utail :: Triple -> Triple utail (cs, vsa, ds) = (cs, vsa', ds) where vsa' = [ ValVec vva delta | ValVec (_:vva) delta <- vsa ] -- | Prepend a value abstraction to all value vector abstractions in the -- uncovered set ucon :: ValAbs -> Triple -> Triple ucon va (cs, vsa, ds) = (cs, vsa', ds) where vsa' = [ ValVec (va:vva) delta | ValVec vva delta <- vsa ] -- | Given a data constructor of arity `a` and an uncovered set containing -- value vector abstractions of length `(a+n)`, pass the first `n` value -- abstractions to the constructor (Hence, the resulting value vector -- abstractions will have length `n+1`) kcon :: DataCon -> [Type] -> [TyVar] -> [EvVar] -> Triple -> Triple kcon con arg_tys ex_tvs dicts (cs, vsa, ds) = (cs, [ ValVec (va:vva) delta | ValVec vva' delta <- vsa , let (args, vva) = splitAt n vva' , let va = PmCon { pm_con_con = con , pm_con_arg_tys = arg_tys , pm_con_tvs = ex_tvs , pm_con_dicts = dicts , pm_con_args = args } ] , ds) where n = dataConSourceArity con -- | Get the union of two covered, uncovered and divergent value set -- abstractions. Since the covered and divergent sets are represented by a -- boolean, union means computing the logical or (at least one of the two is -- non-empty). mkUnion :: Triple -> Triple -> Triple mkUnion (cs1, vsa1, ds1) (cs2, vsa2, ds2) = (cs1 || cs2, vsa1 ++ vsa2, ds1 || ds2) -- | Add a value vector abstraction to a value set abstraction (uncovered). mkCons :: ValVec -> Triple -> Triple mkCons vva (cs, vsa, ds) = (cs, vva:vsa, ds) -- | Set the divergent set to not empty forces :: Triple -> Triple forces (cs, us, _) = (cs, us, True) -- | Set the divergent set to non-empty if the flag is `True` force_if :: Bool -> Triple -> Triple force_if True (cs,us,_) = (cs,us,True) force_if False triple = triple -- ---------------------------------------------------------------------------- -- * Propagation of term constraints inwards when checking nested matches {- Note [Type and Term Equality Propagation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When checking a match it would be great to have all type and term information available so we can get more precise results. For this reason we have functions `addDictsDs' and `addTmCsDs' in DsMonad that store in the environment type and term constraints (respectively) as we go deeper. The type constraints we propagate inwards are collected by `collectEvVarsPats' in HsPat.hs. This handles bug #4139 ( see example https://ghc.haskell.org/trac/ghc/attachment/ticket/4139/GADTbug.hs ) where this is needed. For term equalities we do less, we just generate equalities for HsCase. For example we accurately give 2 redundancy warnings for the marked cases: f :: [a] -> Bool f x = case x of [] -> case x of -- brings (x ~ []) in scope [] -> True (_:_) -> False -- can't happen (_:_) -> case x of -- brings (x ~ (_:_)) in scope (_:_) -> True [] -> False -- can't happen Functions `genCaseTmCs1' and `genCaseTmCs2' are responsible for generating these constraints. -} -- | Generate equalities when checking a case expression: -- case x of { p1 -> e1; ... pn -> en } -- When we go deeper to check e.g. e1 we record two equalities: -- (x ~ y), where y is the initial uncovered when checking (p1; .. ; pn) -- and (x ~ p1). genCaseTmCs2 :: Maybe (LHsExpr Id) -- Scrutinee -> [Pat Id] -- LHS (should have length 1) -> [Id] -- MatchVars (should have length 1) -> DsM (Bag SimpleEq) genCaseTmCs2 Nothing _ _ = return emptyBag genCaseTmCs2 (Just scr) [p] [var] = do fam_insts <- dsGetFamInstEnvs [e] <- map vaToPmExpr . coercePatVec <$> translatePat fam_insts p let scr_e = lhsExprToPmExpr scr return $ listToBag [(var, e), (var, scr_e)] genCaseTmCs2 _ _ _ = panic "genCaseTmCs2: HsCase" -- | Generate a simple equality when checking a case expression: -- case x of { matches } -- When checking matches we record that (x ~ y) where y is the initial -- uncovered. All matches will have to satisfy this equality. genCaseTmCs1 :: Maybe (LHsExpr Id) -> [Id] -> Bag SimpleEq genCaseTmCs1 Nothing _ = emptyBag genCaseTmCs1 (Just scr) [var] = unitBag (var, lhsExprToPmExpr scr) genCaseTmCs1 _ _ = panic "genCaseTmCs1: HsCase" {- Note [Literals in PmPat] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Instead of translating a literal to a variable accompanied with a guard, we treat them like constructor patterns. The following example from "./libraries/base/GHC/IO/Encoding.hs" shows why: mkTextEncoding' :: CodingFailureMode -> String -> IO TextEncoding mkTextEncoding' cfm enc = case [toUpper c | c <- enc, c /= '-'] of "UTF8" -> return $ UTF8.mkUTF8 cfm "UTF16" -> return $ UTF16.mkUTF16 cfm "UTF16LE" -> return $ UTF16.mkUTF16le cfm ... Each clause gets translated to a list of variables with an equal number of guards. For every guard we generate two cases (equals True/equals False) which means that we generate 2^n cases to feed the oracle with, where n is the sum of the length of all strings that appear in the patterns. For this particular example this means over 2^40 cases. Instead, by representing them like with constructor we get the following: 1. We exploit the common prefix with our representation of VSAs 2. We prune immediately non-reachable cases (e.g. False == (x == "U"), True == (x == "U")) Note [Translating As Patterns] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Instead of translating x@p as: x (p <- x) we instead translate it as: p (x <- coercePattern p) for performance reasons. For example: f x@True = 1 f y@False = 2 Gives the following with the first translation: x |> {x == False, x == y, y == True} If we use the second translation we get an empty set, independently of the oracle. Since the pattern `p' may contain guard patterns though, it cannot be used as an expression. That's why we call `coercePatVec' to drop the guard and `vaToPmExpr' to transform the value abstraction to an expression in the guard pattern (value abstractions are a subset of expressions). We keep the guards in the first pattern `p' though. %************************************************************************ %* * Pretty printing of exhaustiveness/redundancy check warnings %* * %************************************************************************ -} -- | Check whether any part of pattern match checking is enabled (does not -- matter whether it is the redundancy check or the exhaustiveness check). isAnyPmCheckEnabled :: DynFlags -> DsMatchContext -> Bool isAnyPmCheckEnabled dflags (DsMatchContext kind _loc) = wopt Opt_WarnOverlappingPatterns dflags || exhaustive dflags kind instance Outputable ValVec where ppr (ValVec vva delta) = let (residual_eqs, subst) = wrapUpTmState (delta_tm_cs delta) vector = substInValAbs subst vva in ppr_uncovered (vector, residual_eqs) -- | Apply a term substitution to a value vector abstraction. All VAs are -- transformed to PmExpr (used only before pretty printing). substInValAbs :: PmVarEnv -> [ValAbs] -> [PmExpr] substInValAbs subst = map (exprDeepLookup subst . vaToPmExpr) -- | Wrap up the term oracle's state once solving is complete. Drop any -- information about unhandled constraints (involving HsExprs) and flatten -- (height 1) the substitution. wrapUpTmState :: TmState -> ([ComplexEq], PmVarEnv) wrapUpTmState (residual, (_, subst)) = (residual, flattenPmVarEnv subst) -- | Issue all the warnings (coverage, exhaustiveness, inaccessibility) dsPmWarn :: DynFlags -> DsMatchContext -> PmResult -> DsM () dsPmWarn dflags ctx@(DsMatchContext kind loc) pm_result = when (flag_i || flag_u) $ do let exists_r = flag_i && notNull redundant exists_i = flag_i && notNull inaccessible exists_u = flag_u && notNull uncovered when exists_r $ forM_ redundant $ \(L l q) -> do putSrcSpanDs l (warnDs (Reason Opt_WarnOverlappingPatterns) (pprEqn q "is redundant")) when exists_i $ forM_ inaccessible $ \(L l q) -> do putSrcSpanDs l (warnDs (Reason Opt_WarnOverlappingPatterns) (pprEqn q "has inaccessible right hand side")) when exists_u $ putSrcSpanDs loc (warnDs flag_u_reason (pprEqns uncovered)) where (redundant, uncovered, inaccessible) = pm_result flag_i = wopt Opt_WarnOverlappingPatterns dflags flag_u = exhaustive dflags kind flag_u_reason = maybe NoReason Reason (exhaustiveWarningFlag kind) maxPatterns = maxUncoveredPatterns dflags -- Print a single clause (for redundant/with-inaccessible-rhs) pprEqn q txt = pp_context True ctx (text txt) $ \f -> ppr_eqn f kind q -- Print several clauses (for uncovered clauses) pprEqns qs = pp_context False ctx (text "are non-exhaustive") $ \_ -> case qs of -- See #11245 [ValVec [] _] -> text "Guards do not cover entire pattern space" _missing -> let us = map ppr qs in hang (text "Patterns not matched:") 4 (vcat (take maxPatterns us) $$ dots maxPatterns us) -- | Issue a warning when the predefined number of iterations is exceeded -- for the pattern match checker warnPmIters :: DynFlags -> DsMatchContext -> PmM () warnPmIters dflags (DsMatchContext kind loc) = when (flag_i || flag_u) $ do iters <- maxPmCheckIterations <$> getDynFlags putSrcSpanDs loc (warnDs NoReason (msg iters)) where ctxt = pprMatchContext kind msg is = fsep [ text "Pattern match checker exceeded" , parens (ppr is), text "iterations in", ctxt <> dot , text "(Use -fmax-pmcheck-iterations=n" , text "to set the maximun number of iterations to n)" ] flag_i = wopt Opt_WarnOverlappingPatterns dflags flag_u = exhaustive dflags kind dots :: Int -> [a] -> SDoc dots maxPatterns qs | qs `lengthExceeds` maxPatterns = text "..." | otherwise = empty -- | Check whether the exhaustiveness checker should run (exhaustiveness only) exhaustive :: DynFlags -> HsMatchContext id -> Bool exhaustive dflags = maybe False (`wopt` dflags) . exhaustiveWarningFlag -- | Denotes whether an exhaustiveness check is supported, and if so, -- via which 'WarningFlag' it's controlled. -- Returns 'Nothing' if check is not supported. exhaustiveWarningFlag :: HsMatchContext id -> Maybe WarningFlag exhaustiveWarningFlag (FunRhs {}) = Just Opt_WarnIncompletePatterns exhaustiveWarningFlag CaseAlt = Just Opt_WarnIncompletePatterns exhaustiveWarningFlag IfAlt = Nothing exhaustiveWarningFlag LambdaExpr = Just Opt_WarnIncompleteUniPatterns exhaustiveWarningFlag PatBindRhs = Just Opt_WarnIncompleteUniPatterns exhaustiveWarningFlag ProcExpr = Just Opt_WarnIncompleteUniPatterns exhaustiveWarningFlag RecUpd = Just Opt_WarnIncompletePatternsRecUpd exhaustiveWarningFlag ThPatSplice = Nothing exhaustiveWarningFlag PatSyn = Nothing exhaustiveWarningFlag ThPatQuote = Nothing exhaustiveWarningFlag (StmtCtxt {}) = Nothing -- Don't warn about incomplete patterns -- in list comprehensions, pattern guards -- etc. They are often *supposed* to be -- incomplete -- True <==> singular pp_context :: Bool -> DsMatchContext -> SDoc -> ((SDoc -> SDoc) -> SDoc) -> SDoc pp_context singular (DsMatchContext kind _loc) msg rest_of_msg_fun = vcat [text txt <+> msg, sep [ text "In" <+> ppr_match <> char ':' , nest 4 (rest_of_msg_fun pref)]] where txt | singular = "Pattern match" | otherwise = "Pattern match(es)" (ppr_match, pref) = case kind of FunRhs (L _ fun) _ -> (pprMatchContext kind, \ pp -> ppr fun <+> pp) _ -> (pprMatchContext kind, \ pp -> pp) ppr_pats :: HsMatchContext Name -> [Pat Id] -> SDoc ppr_pats kind pats = sep [sep (map ppr pats), matchSeparator kind, text "..."] ppr_eqn :: (SDoc -> SDoc) -> HsMatchContext Name -> [LPat Id] -> SDoc ppr_eqn prefixF kind eqn = prefixF (ppr_pats kind (map unLoc eqn)) ppr_constraint :: (SDoc,[PmLit]) -> SDoc ppr_constraint (var, lits) = var <+> text "is not one of" <+> braces (pprWithCommas ppr lits) ppr_uncovered :: ([PmExpr], [ComplexEq]) -> SDoc ppr_uncovered (expr_vec, complex) | null cs = fsep vec -- there are no literal constraints | otherwise = hang (fsep vec) 4 $ text "where" <+> vcat (map ppr_constraint cs) where sdoc_vec = mapM pprPmExprWithParens expr_vec (vec,cs) = runPmPprM sdoc_vec (filterComplex complex) {- Note [Representation of Term Equalities] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the paper, term constraints always take the form (x ~ e). Of course, a more general constraint of the form (e1 ~ e1) can always be transformed to an equivalent set of the former constraints, by introducing a fresh, intermediate variable: { y ~ e1, y ~ e1 }. Yet, implementing this representation gave rise to #11160 (incredibly bad performance for literal pattern matching). Two are the main sources of this problem (the actual problem is how these two interact with each other): 1. Pattern matching on literals generates twice as many constraints as needed. Consider the following (tests/ghci/should_run/ghcirun004): foo :: Int -> Int foo 1 = 0 ... foo 5000 = 4999 The covered and uncovered set *should* look like: U0 = { x |> {} } C1 = { 1 |> { x ~ 1 } } U1 = { x |> { False ~ (x ~ 1) } } ... C10 = { 10 |> { False ~ (x ~ 1), .., False ~ (x ~ 9), x ~ 10 } } U10 = { x |> { False ~ (x ~ 1), .., False ~ (x ~ 9), False ~ (x ~ 10) } } ... If we replace { False ~ (x ~ 1) } with { y ~ False, y ~ (x ~ 1) } we get twice as many constraints. Also note that half of them are just the substitution [x |-> False]. 2. The term oracle (`tmOracle` in deSugar/TmOracle) uses equalities of the form (x ~ e) as substitutions [x |-> e]. More specifically, function `extendSubstAndSolve` applies such substitutions in the residual constraints and partitions them in the affected and non-affected ones, which are the new worklist. Essentially, this gives quadradic behaviour on the number of the residual constraints. (This would not be the case if the term oracle used mutable variables but, since we use it to handle disjunctions on value set abstractions (`Union` case), we chose a pure, incremental interface). Now the problem becomes apparent (e.g. for clause 300): * Set U300 contains 300 substituting constraints [y_i |-> False] and 300 constraints that we know that will not reduce (stay in the worklist). * To check for consistency, we apply the substituting constraints ONE BY ONE (since `tmOracle` is called incrementally, it does not have all of them available at once). Hence, we go through the (non-progressing) constraints over and over, achieving over-quadradic behaviour. If instead we allow constraints of the form (e ~ e), * All uncovered sets Ui contain no substituting constraints and i non-progressing constraints of the form (False ~ (x ~ lit)) so the oracle behaves linearly. * All covered sets Ci contain exactly (i-1) non-progressing constraints and a single substituting constraint. So the term oracle goes through the constraints only once. The performance improvement becomes even more important when more arguments are involved. -}
sgillespie/ghc
compiler/deSugar/Check.hs
bsd-3-clause
59,113
1
22
14,669
11,443
5,959
5,484
-1
-1
{-# LANGUAGE PackageImports #-} module Number.F2m (benchF2m) where import Gauge.Main import System.Random import Crypto.Number.Basic (log2) import Crypto.Number.F2m genInteger :: Int -> Int -> Integer genInteger salt bits = head . dropWhile ((< bits) . log2) . scanl (\a r -> a * 2^(31 :: Int) + abs r) 0 . randoms . mkStdGen $ salt + bits benchMod :: Int -> Benchmark benchMod bits = bench (show bits) $ nf (modF2m m) a where m = genInteger 0 bits a = genInteger 1 (2 * bits) benchMul :: Int -> Benchmark benchMul bits = bench (show bits) $ nf (mulF2m m a) b where m = genInteger 0 bits a = genInteger 1 bits b = genInteger 2 bits benchSquare :: Int -> Benchmark benchSquare bits = bench (show bits) $ nf (squareF2m m) a where m = genInteger 0 bits a = genInteger 1 bits benchInv :: Int -> Benchmark benchInv bits = bench (show bits) $ nf (invF2m m) a where m = genInteger 0 bits a = genInteger 1 bits bitsList :: [Int] bitsList = [64, 128, 256, 512, 1024, 2048] benchF2m = [ bgroup "modF2m" $ map benchMod bitsList , bgroup "mulF2m" $ map benchMul bitsList , bgroup "squareF2m" $ map benchSquare bitsList , bgroup "invF2m" $ map benchInv bitsList ]
vincenthz/cryptonite
benchs/Number/F2m.hs
bsd-3-clause
1,267
0
15
331
503
261
242
38
1
{-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} -- Module : Network.AWS.Data.Internal.Text -- Copyright : (c) 2013-2015 Brendan Hay <brendan.g.hay@gmail.com> -- 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 Network.AWS.Data.Internal.Text ( FromText (..) , fromText , takeLowerText , matchCI , ToText (..) , showText ) where import Control.Applicative import Crypto.Hash import Data.Attoparsec.Text (Parser) import qualified Data.Attoparsec.Text as AText import Data.ByteString (ByteString) import Data.CaseInsensitive (CI) import qualified Data.CaseInsensitive as CI import Data.Int import Data.Monoid import Data.Scientific import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import qualified Data.Text.Lazy as LText import Data.Text.Lazy.Builder (Builder) import qualified Data.Text.Lazy.Builder as Build import qualified Data.Text.Lazy.Builder.Int as Build import qualified Data.Text.Lazy.Builder.RealFloat as Build import qualified Data.Text.Lazy.Builder.Scientific as Build import Network.HTTP.Client import Network.HTTP.Types import Numeric.Natural fromText :: FromText a => Text -> Either String a fromText = AText.parseOnly parser takeLowerText :: Parser Text takeLowerText = Text.toLower <$> AText.takeText matchCI :: Text -> a -> Parser a matchCI x y = AText.asciiCI x <* AText.endOfInput >> return y class FromText a where parser :: Parser a instance FromText Text where parser = AText.takeText instance FromText ByteString where parser = Text.encodeUtf8 <$> AText.takeText instance FromText Int where parser = AText.signed AText.decimal instance FromText Integer where parser = AText.signed AText.decimal instance FromText Scientific where parser = AText.signed AText.scientific instance FromText Natural where parser = AText.decimal instance FromText Double where parser = AText.signed AText.rational instance FromText Bool where parser = matchCI "false" False <|> matchCI "true" True showText :: ToText a => a -> String showText = Text.unpack . toText class ToText a where toText :: a -> Text instance (ToText a, ToText b) => ToText (a, b) where toText (a, b) = "(" <> toText a <> ", " <> toText b <> ")" instance ToText a => ToText [a] where toText xs = "[" <> Text.intercalate ", " (map toText xs) <> "]" instance ToText a => ToText (CI a) where toText = toText . CI.original instance ToText (Response a) where toText rs = Text.pack . show $ rs { responseBody = () } instance ToText Text where toText = id instance ToText ByteString where toText = Text.decodeUtf8 instance ToText Int where toText = shortText . Build.decimal instance ToText Int64 where toText = shortText . Build.decimal instance ToText Integer where toText = shortText . Build.decimal instance ToText Natural where toText = shortText . Build.decimal instance ToText Scientific where toText = shortText . Build.scientificBuilder instance ToText Double where toText = shortText . Build.realFloat instance ToText StdMethod where toText = toText . renderStdMethod instance ToText (Digest a) where toText = toText . digestToHexByteString instance ToText Bool where toText True = "true" toText False = "false" shortText :: Builder -> Text shortText = LText.toStrict . Build.toLazyTextWith 32
kim/amazonka
core/src/Network/AWS/Data/Internal/Text.hs
mpl-2.0
4,082
0
10
1,008
965
540
425
76
1
{-# LANGUAGE CPP, ForeignFunctionInterface #-} module Network.Wai.Handler.Warp.SendFile ( sendFile , readSendFile , packHeader -- for testing #ifndef WINDOWS , positionRead #endif ) where import qualified Data.ByteString as BS import Network.Socket (Socket) #ifdef WINDOWS import Foreign.ForeignPtr (newForeignPtr_) import Foreign.Ptr (plusPtr) import qualified System.IO as IO #else import qualified UnliftIO import Foreign.C.Error (throwErrno) import Foreign.C.Types import Foreign.Ptr (Ptr, castPtr, plusPtr) import Network.Sendfile import Network.Wai.Handler.Warp.FdCache (openFile, closeFile) import System.Posix.Types #endif import Network.Wai.Handler.Warp.Buffer import Network.Wai.Handler.Warp.Imports import Network.Wai.Handler.Warp.Types ---------------------------------------------------------------- -- | Function to send a file based on sendfile() for Linux\/Mac\/FreeBSD. -- This makes use of the file descriptor cache. -- For other OSes, this is identical to 'readSendFile'. -- -- Since: 3.1.0 sendFile :: Socket -> Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile #ifdef SENDFILEFD sendFile s _ _ _ fid off len act hdr = case mfid of -- settingsFdCacheDuration is 0 Nothing -> sendfileWithHeader s path (PartOfFile off len) act hdr Just fd -> sendfileFdWithHeader s fd (PartOfFile off len) act hdr where mfid = fileIdFd fid path = fileIdPath fid #else sendFile _ = readSendFile #endif ---------------------------------------------------------------- packHeader :: Buffer -> BufSize -> (ByteString -> IO ()) -> IO () -> [ByteString] -> Int -> IO Int packHeader _ _ _ _ [] n = return n packHeader buf siz send hook (bs:bss) n | len < room = do let dst = buf `plusPtr` n void $ copy dst bs packHeader buf siz send hook bss (n + len) | otherwise = do let dst = buf `plusPtr` n (bs1, bs2) = BS.splitAt room bs void $ copy dst bs1 bufferIO buf siz send hook packHeader buf siz send hook (bs2:bss) 0 where len = BS.length bs room = siz - n mini :: Int -> Integer -> Int mini i n | fromIntegral i < n = i | otherwise = fromIntegral n -- | Function to send a file based on pread()\/send() for Unix. -- This makes use of the file descriptor cache. -- For Windows, this is emulated by 'Handle'. -- -- Since: 3.1.0 #ifdef WINDOWS readSendFile :: Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile readSendFile buf siz send fid off0 len0 hook headers = do hn <- packHeader buf siz send hook headers 0 let room = siz - hn buf' = buf `plusPtr` hn IO.withBinaryFile path IO.ReadMode $ \h -> do IO.hSeek h IO.AbsoluteSeek off0 n <- IO.hGetBufSome h buf' (mini room len0) bufferIO buf (hn + n) send hook let n' = fromIntegral n fptr <- newForeignPtr_ buf loop h fptr (len0 - n') where path = fileIdPath fid loop h fptr len | len <= 0 = return () | otherwise = do n <- IO.hGetBufSome h buf (mini siz len) when (n /= 0) $ do let bs = PS fptr 0 n n' = fromIntegral n send bs hook loop h fptr (len - n') #else readSendFile :: Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile readSendFile buf siz send fid off0 len0 hook headers = UnliftIO.bracket setup teardown $ \fd -> do hn <- packHeader buf siz send hook headers 0 let room = siz - hn buf' = buf `plusPtr` hn n <- positionRead fd buf' (mini room len0) off0 bufferIO buf (hn + n) send hook let n' = fromIntegral n loop fd (len0 - n') (off0 + n') where path = fileIdPath fid setup = case fileIdFd fid of Just fd -> return fd Nothing -> openFile path teardown fd = case fileIdFd fid of Just _ -> return () Nothing -> closeFile fd loop fd len off | len <= 0 = return () | otherwise = do n <- positionRead fd buf (mini siz len) off bufferIO buf n send let n' = fromIntegral n hook loop fd (len - n') (off + n') positionRead :: Fd -> Buffer -> BufSize -> Integer -> IO Int positionRead fd buf siz off = do bytes <- fromIntegral <$> c_pread fd (castPtr buf) (fromIntegral siz) (fromIntegral off) when (bytes < 0) $ throwErrno "positionRead" return bytes foreign import ccall unsafe "pread" c_pread :: Fd -> Ptr CChar -> ByteCount -> FileOffset -> IO CSsize #endif
sordina/wai
warp/Network/Wai/Handler/Warp/SendFile.hs
bsd-2-clause
4,550
0
16
1,224
921
472
449
76
3
{-# OPTIONS_HADDOCK hide #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.FramebufferObjects.FramebufferObject -- Copyright : (c) Sven Panne 2013 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- This is a purely internal module for handling FrameBufferObjects. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.FramebufferObjects.FramebufferObject ( FramebufferObject(..) ) where import Foreign.Marshal import Graphics.Rendering.OpenGL.GL.GLboolean import Graphics.Rendering.OpenGL.GL.ObjectName import Graphics.Rendering.OpenGL.Raw -------------------------------------------------------------------------------- data FramebufferObject = FramebufferObject { framebufferID :: GLuint } deriving ( Eq, Ord, Show ) instance ObjectName FramebufferObject where isObjectName = fmap unmarshalGLboolean . glIsFramebuffer . framebufferID deleteObjectNames objs = withArrayLen (map framebufferID objs) $ glDeleteFramebuffers . fromIntegral instance GeneratableObjectName FramebufferObject where genObjectNames n = allocaArray n $ \buf -> do glGenFramebuffers (fromIntegral n) buf fmap (map FramebufferObject) $ peekArray n buf
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GL/FramebufferObjects/FramebufferObject.hs
bsd-3-clause
1,441
0
13
224
206
120
86
19
0
{-# LANGUAGE LambdaCase #-} module LoadResources where import Data.List import Data.Maybe import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Map.Internal.Debug import GameEngine.Scene (Resource(..)) import Lens.Micro.Platform import World import Items import Entities itemMap :: Map ItemType Item itemMap = Map.fromList [(itType i,i) | i <- items] weaponInfoMap :: Map Items.Weapon WeaponInfo weaponInfoMap = Map.fromList [(wiType w,w) | w <- weaponInfos] worldResources :: World -> [Resource] worldResources = nub . concatMap resource . view wEntities where itemModels itemType | Just it <- Map.lookup itemType itemMap = [R_MD3 model | model <- itWorldModel it] | otherwise = [] missileMD3 w = fmap R_MD3 . maybeToList $ do wiMissileModel =<< Map.lookup w weaponInfoMap resource = \case EBullet b -> missileMD3 (b^.bType) EWeapon a -> missileMD3 (a^.wType) ++ (itemModels . IT_WEAPON $ a^.wType) EAmmo a -> itemModels . IT_AMMO $ a^.aType EArmor a -> itemModels . IT_ARMOR $ a^.rType EHealth a -> itemModels . IT_HEALTH $ a^.hType EHoldable h -> itemModels . IT_HOLDABLE $ h^.hoType EPowerup p -> itemModels . IT_POWERUP $ p^.puType -- TODO:PLayer _ -> [] hudResources :: [Resource] hudResources = (R_Shader . itIcon <$> items) ++ (R_Shader <$> Map.elems digitMap) where type ShaderName = String digitMap :: Map Char ShaderName digitMap = Map.fromList [ ('0', "gfx/2d/numbers/zero_32b") , ('1', "gfx/2d/numbers/one_32b") , ('2', "gfx/2d/numbers/two_32b") , ('3', "gfx/2d/numbers/three_32b") , ('4', "gfx/2d/numbers/four_32b") , ('5', "gfx/2d/numbers/five_32b") , ('6', "gfx/2d/numbers/six_32b") , ('7', "gfx/2d/numbers/seven_32b") , ('8', "gfx/2d/numbers/eight_32b") , ('9', "gfx/2d/numbers/nine_32b") , ('-', "gfx/2d/numbers/minus_32b") ]
csabahruska/quake3
game/LoadResources.hs
bsd-3-clause
1,900
0
14
365
619
338
281
47
8
{-# LANGUAGE RecordWildCards #-} import Control.Applicative import Control.Exception import Control.Monad import Control.Monad.Trans.Resource (runResourceT) import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy.Char8 as L8 import Data.List import Data.Maybe import Distribution.PackageDescription.Parse import Distribution.Text import Distribution.System import Distribution.Package import Distribution.PackageDescription hiding (options) import Distribution.Verbosity import System.Console.GetOpt import System.Environment import System.Directory import System.IO.Error import System.Process import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Zip as Zip import qualified Codec.Compression.GZip as GZip import Data.Aeson import qualified Data.CaseInsensitive as CI import Data.Conduit import qualified Data.Conduit.Combinators as CC import Data.List.Extra import qualified Data.Text as T import Development.Shake import Development.Shake.FilePath import Network.HTTP.Conduit import Network.HTTP.Types import Network.Mime import Prelude -- Silence AMP warning -- | Entrypoint. main :: IO () main = shakeArgsWith shakeOptions { shakeFiles = releaseDir , shakeVerbosity = Chatty , shakeChange = ChangeModtimeAndDigestInput } options $ \flags args -> do gStackPackageDescription <- packageDescription <$> readPackageDescription silent "stack.cabal" gGithubAuthToken <- lookupEnv githubAuthTokenEnvVar gGitRevCount <- length . lines <$> readProcess "git" ["rev-list", "HEAD"] "" gGitSha <- trim <$> readProcess "git" ["rev-parse", "HEAD"] "" gHomeDir <- getHomeDirectory let gGpgKey = "0x575159689BEFB442" gAllowDirty = False gGithubReleaseTag = Nothing Platform arch _ = buildPlatform gArch = arch gBinarySuffix = "" gUploadLabel = Nothing gTestHaddocks = True gProjectRoot = "" -- Set to real value velow. gBuildArgs = [] global0 = foldl (flip id) Global{..} flags -- Need to get paths after options since the '--arch' argument can effect them. projectRoot' <- getStackPath global0 "project-root" let global = global0 { gProjectRoot = projectRoot' } return $ Just $ rules global args where getStackPath global path = do out <- readProcess stackProgName (stackArgs global ++ ["path", "--" ++ path]) "" return $ trim $ fromMaybe out $ stripPrefix (path ++ ":") out -- | Additional command-line options. options :: [OptDescr (Either String (Global -> Global))] options = [ Option "" [gpgKeyOptName] (ReqArg (\v -> Right $ \g -> g{gGpgKey = v}) "USER-ID") "GPG user ID to sign distribution package with." , Option "" [allowDirtyOptName] (NoArg $ Right $ \g -> g{gAllowDirty = True}) "Allow a dirty working tree for release." , Option "" [githubAuthTokenOptName] (ReqArg (\v -> Right $ \g -> g{gGithubAuthToken = Just v}) "TOKEN") ("Github personal access token (defaults to " ++ githubAuthTokenEnvVar ++ " environment variable).") , Option "" [githubReleaseTagOptName] (ReqArg (\v -> Right $ \g -> g{gGithubReleaseTag = Just v}) "TAG") "Github release tag to upload to." , Option "" [archOptName] (ReqArg (\v -> case simpleParse v of Nothing -> Left $ "Unknown architecture in --arch option: " ++ v Just arch -> Right $ \g -> g{gArch = arch}) "ARCHITECTURE") "Architecture to build (e.g. 'i386' or 'x86_64')." , Option "" [binaryVariantOptName] (ReqArg (\v -> Right $ \g -> g{gBinarySuffix = v}) "SUFFIX") "Extra suffix to add to binary executable archive filename." , Option "" [uploadLabelOptName] (ReqArg (\v -> Right $ \g -> g{gUploadLabel = Just v}) "LABEL") "Label to give the uploaded release asset" , Option "" [noTestHaddocksOptName] (NoArg $ Right $ \g -> g{gTestHaddocks = False}) "Disable testing building haddocks." -- FIXME: Use 'static' flag in stack.cabal instead. See https://github.com/commercialhaskell/stack/issues/3045. , Option "" [staticOptName] (NoArg $ Right $ \g -> g{gBuildArgs = gBuildArgs g ++ ["--split-objs", "--ghc-options=-optc-Os -optl-static -fPIC"]}) "Build a static binary." , Option "" [buildArgsOptName] (ReqArg (\v -> Right $ \g -> g{gBuildArgs = gBuildArgs g ++ words v}) "\"ARG1 ARG2 ...\"") "Additional arguments to pass to 'stack build'." ] -- | Shake rules. rules :: Global -> [String] -> Rules () rules global@Global{..} args = do case args of [] -> error "No wanted target(s) specified." _ -> want args phony releasePhony $ do need [checkPhony] need [uploadPhony] phony cleanPhony $ removeFilesAfter releaseDir ["//*"] phony checkPhony $ need [releaseCheckDir </> binaryExeFileName] phony uploadPhony $ mapM_ (\f -> need [releaseDir </> f <.> uploadExt]) binaryPkgFileNames phony buildPhony $ mapM_ (\f -> need [releaseDir </> f]) binaryPkgFileNames distroPhonies ubuntuDistro ubuntuVersions debPackageFileName distroPhonies debianDistro debianVersions debPackageFileName distroPhonies centosDistro centosVersions rpmPackageFileName distroPhonies fedoraDistro fedoraVersions rpmPackageFileName releaseDir </> "*" <.> uploadExt %> \out -> do let srcFile = dropExtension out mUploadLabel = if takeExtension srcFile == ascExt then fmap (++ " (GPG signature)") gUploadLabel else gUploadLabel uploadToGithubRelease global srcFile mUploadLabel copyFileChanged srcFile out releaseCheckDir </> binaryExeFileName %> \out -> do need [releaseBinDir </> binaryName </> stackExeFileName] Stdout dirty <- cmd "git status --porcelain" when (not gAllowDirty && not (null (trim dirty))) $ error ("Working tree is dirty. Use --" ++ allowDirtyOptName ++ " option to continue anyway.") withTempDir $ \tmpDir -> do let cmd0 c = cmd (gProjectRoot </> releaseBinDir </> binaryName </> stackExeFileName) (stackArgs global) ["--local-bin-path=" ++ tmpDir] c () <- cmd0 "install" gBuildArgs $ concat $ concat [["--pedantic --no-haddock-deps"], [" --haddock" | gTestHaddocks]] () <- cmd0 (Cwd "etc/scripts") "install" gBuildArgs "cabal-install" let cmd' c = cmd (AddPath [tmpDir] []) stackProgName (stackArgs global) c () <- cmd' "test" gBuildArgs "--pedantic --flag stack:integration-tests" return () copyFileChanged (releaseBinDir </> binaryName </> stackExeFileName) out releaseDir </> binaryPkgZipFileName %> \out -> do stageFiles <- getBinaryPkgStageFiles putNormal $ "zip " ++ out liftIO $ do entries <- forM stageFiles $ \stageFile -> do Zip.readEntry [Zip.OptLocation (dropDirectoryPrefix (releaseStageDir </> binaryName) stageFile) False] stageFile let archive = foldr Zip.addEntryToArchive Zip.emptyArchive entries L8.writeFile out (Zip.fromArchive archive) releaseDir </> binaryPkgTarGzFileName %> \out -> do stageFiles <- getBinaryPkgStageFiles writeTarGz out releaseStageDir stageFiles releaseStageDir </> binaryName </> stackExeFileName %> \out -> do copyFileChanged (releaseDir </> binaryExeFileName) out releaseStageDir </> (binaryName ++ "//*") %> \out -> do copyFileChanged (dropDirectoryPrefix (releaseStageDir </> binaryName) out) out releaseDir </> binaryExeFileName %> \out -> do need [releaseBinDir </> binaryName </> stackExeFileName] (Stdout versionOut) <- cmd (releaseBinDir </> binaryName </> stackExeFileName) "--version" when (not gAllowDirty && "dirty" `isInfixOf` lower versionOut) $ error ("Refusing continue because 'stack --version' reports dirty. Use --" ++ allowDirtyOptName ++ " option to continue anyway.") case platformOS of Windows -> do -- Windows doesn't have or need a 'strip' command, so skip it. -- Instead, we sign the executable liftIO $ copyFile (releaseBinDir </> binaryName </> stackExeFileName) out actionOnException (command_ [] "c:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Bin\\signtool.exe" ["sign" ,"/v" ,"/d", synopsis gStackPackageDescription ,"/du", homepage gStackPackageDescription ,"/n", "FP Complete, Corporation" ,"/t", "http://timestamp.verisign.com/scripts/timestamp.dll" ,out]) (removeFile out) Linux -> cmd "strip -p --strip-unneeded --remove-section=.comment -o" [out, releaseBinDir </> binaryName </> stackExeFileName] _ -> cmd "strip -o" [out, releaseBinDir </> binaryName </> stackExeFileName] releaseDir </> "*" <.> ascExt %> \out -> do need [out -<.> ""] _ <- liftIO $ tryJust (guard . isDoesNotExistError) (removeFile out) cmd ("gpg " ++ gpgOptions ++ " --detach-sig --armor") [ "-u", gGpgKey , dropExtension out ] releaseBinDir </> binaryName </> stackExeFileName %> \out -> do alwaysRerun actionOnException (cmd stackProgName (stackArgs global) ["--local-bin-path=" ++ takeDirectory out] "install" gBuildArgs "--pedantic") (removeFile out) debDistroRules ubuntuDistro ubuntuVersions debDistroRules debianDistro debianVersions rpmDistroRules centosDistro centosVersions rpmDistroRules fedoraDistro fedoraVersions where debDistroRules debDistro0 debVersions = do let anyVersion0 = anyDistroVersion debDistro0 distroVersionDir anyVersion0 </> debPackageFileName anyVersion0 <.> uploadExt %> \out -> do let DistroVersion{..} = distroVersionFromPath out debVersions pkgFile = dropExtension out need [pkgFile] () <- cmd "deb-s3 upload --preserve-versions --bucket download.fpcomplete.com" [ "--sign=" ++ gGpgKey , "--gpg-options=" ++ replace "-" "\\-" gpgOptions , "--prefix=" ++ dvDistro , "--codename=" ++ dvCodeName , pkgFile ] -- Also upload to the old, incorrect location for people who still have their systems -- configured with it. () <- cmd "deb-s3 upload --preserve-versions --bucket download.fpcomplete.com" [ "--sign=" ++ gGpgKey , "--gpg-options=" ++ replace "-" "\\-" gpgOptions , "--prefix=" ++ dvDistro ++ "/" ++ dvCodeName , pkgFile ] copyFileChanged pkgFile out distroVersionDir anyVersion0 </> debPackageFileName anyVersion0 %> \out -> do docFiles <- getDocFiles let dv@DistroVersion{..} = distroVersionFromPath out debVersions inputFiles = concat [[debStagedExeFile dv ,debStagedBashCompletionFile dv] ,map (debStagedDocDir dv </>) docFiles] need inputFiles cmd "fpm -f -s dir -t deb" "--deb-recommends git --deb-recommends gnupg" "-d g++ -d gcc -d libc6-dev -d libffi-dev -d libgmp-dev -d make -d xz-utils -d zlib1g-dev -d netbase -d ca-certificates" ["-n", stackProgName ,"-C", debStagingDir dv ,"-v", debPackageVersionStr dv ,"-p", out ,"-m", maintainer gStackPackageDescription ,"--description", synopsis gStackPackageDescription ,"--license", display (license gStackPackageDescription) ,"--url", homepage gStackPackageDescription] (map (dropDirectoryPrefix (debStagingDir dv)) inputFiles) debStagedExeFile anyVersion0 %> \out -> do copyFileChanged (releaseDir </> binaryExeFileName) out debStagedBashCompletionFile anyVersion0 %> \out -> do let dv = distroVersionFromPath out debVersions writeBashCompletion (debStagedExeFile dv) out debStagedDocDir anyVersion0 ++ "//*" %> \out -> do let dv@DistroVersion{..} = distroVersionFromPath out debVersions origFile = dropDirectoryPrefix (debStagedDocDir dv) out copyFileChanged origFile out rpmDistroRules rpmDistro0 rpmVersions = do let anyVersion0 = anyDistroVersion rpmDistro0 distroVersionDir anyVersion0 </> rpmPackageFileName anyVersion0 <.> uploadExt %> \out -> do let DistroVersion{..} = distroVersionFromPath out rpmVersions pkgFile = dropExtension out need [pkgFile] let rpmmacrosFile = gHomeDir </> ".rpmmacros" rpmmacrosExists <- liftIO $ System.Directory.doesFileExist rpmmacrosFile when rpmmacrosExists $ error ("'" ++ rpmmacrosFile ++ "' already exists. Move it out of the way first.") actionFinally (do writeFileLines rpmmacrosFile [ "%_signature gpg" , "%_gpg_name " ++ gGpgKey ] () <- cmd "rpm-s3 --verbose --sign --bucket=download.fpcomplete.com" [ "--repopath=" ++ dvDistro ++ "/" ++ dvVersion , pkgFile ] return ()) (liftIO $ removeFile rpmmacrosFile) copyFileChanged pkgFile out distroVersionDir anyVersion0 </> rpmPackageFileName anyVersion0 %> \out -> do docFiles <- getDocFiles let dv@DistroVersion{..} = distroVersionFromPath out rpmVersions inputFiles = concat [[rpmStagedExeFile dv ,rpmStagedBashCompletionFile dv] ,map (rpmStagedDocDir dv </>) docFiles] need inputFiles cmd "fpm -s dir -t rpm" "-d perl -d make -d automake -d gcc -d gmp-devel -d libffi -d zlib -d xz -d tar" ["-n", stackProgName ,"-C", rpmStagingDir dv ,"-v", rpmPackageVersionStr dv ,"--iteration", rpmPackageIterationStr dv ,"-p", out ,"-m", maintainer gStackPackageDescription ,"--description", synopsis gStackPackageDescription ,"--license", display (license gStackPackageDescription) ,"--url", homepage gStackPackageDescription] (map (dropDirectoryPrefix (rpmStagingDir dv)) inputFiles) rpmStagedExeFile anyVersion0 %> \out -> do copyFileChanged (releaseDir </> binaryExeFileName) out rpmStagedBashCompletionFile anyVersion0 %> \out -> do let dv = distroVersionFromPath out rpmVersions writeBashCompletion (rpmStagedExeFile dv) out rpmStagedDocDir anyVersion0 ++ "//*" %> \out -> do let dv@DistroVersion{..} = distroVersionFromPath out rpmVersions origFile = dropDirectoryPrefix (rpmStagedDocDir dv) out copyFileChanged origFile out writeBashCompletion stagedStackExeFile out = do need [stagedStackExeFile] (Stdout bashCompletionScript) <- cmd [stagedStackExeFile] "--bash-completion-script" [stackProgName] writeFileChanged out bashCompletionScript getBinaryPkgStageFiles = do docFiles <- getDocFiles let stageFiles = concat [[releaseStageDir </> binaryName </> stackExeFileName] ,map ((releaseStageDir </> binaryName) </>) docFiles] need stageFiles return stageFiles getDocFiles = getDirectoryFiles "." ["LICENSE", "*.md", "doc//*.md"] distroVersionFromPath path versions = let path' = dropDirectoryPrefix releaseDir path version = takeDirectory1 (dropDirectory1 path') in DistroVersion (takeDirectory1 path') version (lookupVersionCodeName version versions) distroPhonies distro0 versions0 makePackageFileName = forM_ versions0 $ \(version0,_) -> do let dv@DistroVersion{..} = DistroVersion distro0 version0 (lookupVersionCodeName version0 versions0) phony (distroUploadPhony dv) $ need [distroVersionDir dv </> makePackageFileName dv <.> uploadExt] phony (distroBuildPhony dv) $ need [distroVersionDir dv </> makePackageFileName dv] lookupVersionCodeName version versions = fromMaybe (error $ "lookupVersionCodeName: could not find " ++ show version ++ " in " ++ show versions) $ lookup version versions releasePhony = "release" checkPhony = "check" uploadPhony = "upload" cleanPhony = "clean" buildPhony = "build" distroUploadPhony DistroVersion{..} = "upload-" ++ dvDistro ++ "-" ++ dvVersion distroBuildPhony DistroVersion{..} = "build-" ++ dvDistro ++ "-" ++ dvVersion releaseCheckDir = releaseDir </> "check" releaseStageDir = releaseDir </> "stage" releaseBinDir = releaseDir </> "bin" distroVersionDir DistroVersion{..} = releaseDir </> dvDistro </> dvVersion binaryPkgFileNames = binaryPkgArchiveFileNames ++ binaryPkgSignatureFileNames binaryPkgSignatureFileNames = map (<.> ascExt) binaryPkgArchiveFileNames binaryPkgArchiveFileNames = case platformOS of Windows -> [binaryPkgZipFileName, binaryPkgTarGzFileName] _ -> [binaryPkgTarGzFileName] binaryPkgZipFileName = binaryName <.> zipExt binaryPkgTarGzFileName = binaryName <.> tarGzExt binaryExeFileName = binaryName <.> exe binaryName = concat [ stackProgName , "-" , stackVersionStr global , "-" , display platformOS , "-" , display gArch , if null gBinarySuffix then "" else "-" ++ gBinarySuffix ] stackExeFileName = stackProgName <.> exe debStagedDocDir dv = debStagingDir dv </> "usr/share/doc" </> stackProgName debStagedBashCompletionFile dv = debStagingDir dv </> "etc/bash_completion.d/stack" debStagedExeFile dv = debStagingDir dv </> "usr/bin/stack" debStagingDir dv = distroVersionDir dv </> debPackageName dv debPackageFileName dv = debPackageName dv <.> debExt debPackageName dv = stackProgName ++ "_" ++ debPackageVersionStr dv ++ "_amd64" debPackageVersionStr DistroVersion{..} = stackVersionStr global ++ "-0~" ++ dvCodeName rpmStagedDocDir dv = rpmStagingDir dv </> "usr/share/doc" </> (stackProgName ++ "-" ++ rpmPackageVersionStr dv) rpmStagedBashCompletionFile dv = rpmStagingDir dv </> "etc/bash_completion.d/stack" rpmStagedExeFile dv = rpmStagingDir dv </> "usr/bin/stack" rpmStagingDir dv = distroVersionDir dv </> rpmPackageName dv rpmPackageFileName dv = rpmPackageName dv <.> rpmExt rpmPackageName dv = stackProgName ++ "-" ++ rpmPackageVersionStr dv ++ "-" ++ rpmPackageIterationStr dv ++ ".x86_64" rpmPackageIterationStr DistroVersion{..} = "0." ++ dvCodeName rpmPackageVersionStr _ = stackVersionStr global ubuntuVersions = [ ("12.04", "precise") , ("14.04", "trusty") , ("14.10", "utopic") , ("15.04", "vivid") , ("15.10", "wily") , ("16.04", "xenial") , ("16.10", "yakkety") ] debianVersions = [ ("7", "wheezy") , ("8", "jessie") ] centosVersions = [ ("7", "el7") , ("6", "el6") ] fedoraVersions = [ ("22", "fc22") , ("23", "fc23") , ("24", "fc24") ] ubuntuDistro = "ubuntu" debianDistro = "debian" centosDistro = "centos" fedoraDistro = "fedora" anyDistroVersion distro = DistroVersion distro "*" "*" zipExt = ".zip" tarGzExt = tarExt <.> gzExt gzExt = ".gz" tarExt = ".tar" ascExt = ".asc" uploadExt = ".upload" debExt = ".deb" rpmExt = ".rpm" -- | Upload file to Github release. uploadToGithubRelease :: Global -> FilePath -> Maybe String -> Action () uploadToGithubRelease global@Global{..} file mUploadLabel = do need [file] putNormal $ "Uploading to Github: " ++ file GithubRelease{..} <- getGithubRelease resp <- liftIO $ callGithubApi global [(CI.mk $ S8.pack "Content-Type", defaultMimeLookup (T.pack file))] (Just file) (replace "{?name,label}" ("?name=" ++ urlEncodeStr (takeFileName file) ++ (case mUploadLabel of Nothing -> "" Just uploadLabel -> "&label=" ++ urlEncodeStr uploadLabel)) relUploadUrl) case eitherDecode resp of Left e -> error ("Could not parse Github asset upload response (" ++ e ++ "):\n" ++ L8.unpack resp ++ "\n") Right (GithubReleaseAsset{..}) -> when (assetState /= "uploaded") $ error ("Invalid asset state after Github asset upload: " ++ assetState) where urlEncodeStr = S8.unpack . urlEncode True . S8.pack getGithubRelease = do releases <- getGithubReleases let tag = fromMaybe ("v" ++ stackVersionStr global) gGithubReleaseTag return $ fromMaybe (error ("Could not find Github release with tag '" ++ tag ++ "'.\n" ++ "Use --" ++ githubReleaseTagOptName ++ " option to specify a different tag.")) (find (\r -> relTagName r == tag) releases) getGithubReleases :: Action [GithubRelease] getGithubReleases = do resp <- liftIO $ callGithubApi global [] Nothing "https://api.github.com/repos/commercialhaskell/stack/releases" case eitherDecode resp of Left e -> error ("Could not parse Github releases (" ++ e ++ "):\n" ++ L8.unpack resp ++ "\n") Right r -> return r -- | Make a request to the Github API and return the response. callGithubApi :: Global -> RequestHeaders -> Maybe FilePath -> String -> IO L8.ByteString callGithubApi Global{..} headers mpostFile url = do req0 <- parseUrlThrow url let authToken = fromMaybe (error $ "Github auth token required.\n" ++ "Use " ++ githubAuthTokenEnvVar ++ " environment variable\n" ++ "or --" ++ githubAuthTokenOptName ++ " option to specify.") gGithubAuthToken req1 = req0 { requestHeaders = [ (CI.mk $ S8.pack "Authorization", S8.pack $ "token " ++ authToken) , (CI.mk $ S8.pack "User-Agent", S8.pack "commercialhaskell/stack") ] ++ headers } req <- case mpostFile of Nothing -> return req1 Just postFile -> do lbs <- L8.readFile postFile return $ req1 { method = S8.pack "POST" , requestBody = RequestBodyLBS lbs } manager <- newManager tlsManagerSettings runResourceT $ do res <- http req manager responseBody res $$+- CC.sinkLazy -- | Create a .tar.gz files from files. The paths should be absolute, and will -- be made relative to the base directory in the tarball. writeTarGz :: FilePath -> FilePath -> [FilePath] -> Action () writeTarGz out baseDir inputFiles = liftIO $ do content <- Tar.pack baseDir $ map (dropDirectoryPrefix baseDir) inputFiles L8.writeFile out $ GZip.compress $ Tar.write content -- | Drops a directory prefix from a path. The prefix automatically has a path -- separator character appended. Fails if the path does not begin with the prefix. dropDirectoryPrefix :: FilePath -> FilePath -> FilePath dropDirectoryPrefix prefix path = case stripPrefix (toStandard prefix ++ "/") (toStandard path) of Nothing -> error ("dropDirectoryPrefix: cannot drop " ++ show prefix ++ " from " ++ show path) Just stripped -> stripped -- | String representation of stack package version. stackVersionStr :: Global -> String stackVersionStr = display . pkgVersion . package . gStackPackageDescription -- | Current operating system. platformOS :: OS platformOS = let Platform _ os = buildPlatform in os -- | Directory in which to store build and intermediate files. releaseDir :: FilePath releaseDir = "_release" -- | @GITHUB_AUTH_TOKEN@ environment variale name. githubAuthTokenEnvVar :: String githubAuthTokenEnvVar = "GITHUB_AUTH_TOKEN" -- | @--github-auth-token@ command-line option name. githubAuthTokenOptName :: String githubAuthTokenOptName = "github-auth-token" -- | @--github-release-tag@ command-line option name. githubReleaseTagOptName :: String githubReleaseTagOptName = "github-release-tag" -- | @--gpg-key@ command-line option name. gpgKeyOptName :: String gpgKeyOptName = "gpg-key" -- | @--allow-dirty@ command-line option name. allowDirtyOptName :: String allowDirtyOptName = "allow-dirty" -- | @--arch@ command-line option name. archOptName :: String archOptName = "arch" -- | @--binary-variant@ command-line option name. binaryVariantOptName :: String binaryVariantOptName = "binary-variant" -- | @--upload-label@ command-line option name. uploadLabelOptName :: String uploadLabelOptName = "upload-label" -- | @--no-test-haddocks@ command-line option name. noTestHaddocksOptName :: String noTestHaddocksOptName = "no-test-haddocks" -- | @--build-args@ command-line option name. buildArgsOptName :: String buildArgsOptName = "build-args" -- | @--static@ command-line option name. staticOptName :: String staticOptName = "static" -- | Arguments to pass to all 'stack' invocations. stackArgs :: Global -> [String] stackArgs Global{..} = ["--install-ghc", "--arch=" ++ display gArch] -- | Name of the 'stack' program. stackProgName :: FilePath stackProgName = "stack" -- | Options to pass to invocations of gpg gpgOptions :: String gpgOptions = "--digest-algo=sha512" -- | Linux distribution/version combination. data DistroVersion = DistroVersion { dvDistro :: !String , dvVersion :: !String , dvCodeName :: !String } -- | A Github release, as returned by the Github API. data GithubRelease = GithubRelease { relUploadUrl :: !String , relTagName :: !String } deriving (Show) instance FromJSON GithubRelease where parseJSON = withObject "GithubRelease" $ \o -> GithubRelease <$> o .: T.pack "upload_url" <*> o .: T.pack "tag_name" -- | A Github release asset, as returned by the Github API. data GithubReleaseAsset = GithubReleaseAsset { assetState :: !String } deriving (Show) instance FromJSON GithubReleaseAsset where parseJSON = withObject "GithubReleaseAsset" $ \o -> GithubReleaseAsset <$> o .: T.pack "state" -- | Global values and options. data Global = Global { gStackPackageDescription :: !PackageDescription , gGpgKey :: !String , gAllowDirty :: !Bool , gGithubAuthToken :: !(Maybe String) , gGithubReleaseTag :: !(Maybe String) , gGitRevCount :: !Int , gGitSha :: !String , gProjectRoot :: !FilePath , gHomeDir :: !FilePath , gArch :: !Arch , gBinarySuffix :: !String , gUploadLabel :: (Maybe String) , gTestHaddocks :: !Bool , gBuildArgs :: [String] } deriving (Show)
mrkkrp/stack
etc/scripts/release.hs
bsd-3-clause
28,148
91
56
7,861
6,187
3,177
3,010
592
7
{-# LANGUAGE TypeFamilies #-} module Oracles.ModuleFiles ( decodeModule, encodeModule, findGenerator, hsSources, hsObjects, moduleFilesOracle ) where import qualified Data.HashMap.Strict as Map import Hadrian.Haskell.Cabal.Type as PD import Base import Builder import Context import Expression import Packages type ModuleName = String newtype ModuleFiles = ModuleFiles (Stage, Package) deriving (Binary, Eq, Hashable, NFData, Show, Typeable) type instance RuleResult ModuleFiles = [Maybe FilePath] newtype Generator = Generator (Stage, Package, FilePath) deriving (Binary, Eq, Hashable, NFData, Show, Typeable) type instance RuleResult Generator = Maybe FilePath -- | We scan for the following Haskell source extensions when looking for module -- files. Note, we do not list "*.(l)hs-boot" files here, as they can never -- appear by themselves and always have accompanying "*.(l)hs" master files. haskellExtensions :: [String] haskellExtensions = [".hs", ".lhs"] -- | Non-Haskell source extensions and corresponding builders. otherExtensions :: Stage -> [(String, Builder)] otherExtensions stage = [ (".x" , Alex ) , (".y" , Happy ) , (".ly" , Happy ) , (".hsc", Hsc2Hs stage) ] -- | We match the following file patterns when looking for module files. moduleFilePatterns :: Stage -> [FilePattern] moduleFilePatterns stage = map ("*" ++) $ haskellExtensions ++ map fst (otherExtensions stage) -- | Given a FilePath determine the corresponding builder. determineBuilder :: Stage -> FilePath -> Maybe Builder determineBuilder stage file = lookup (takeExtension file) (otherExtensions stage) -- | Given a non-empty module name extract the directory and file name, e.g.: -- -- > decodeModule "Data.Functor.Identity" == ("Data/Functor", "Identity") -- > decodeModule "Prelude" == ("", "Prelude") decodeModule :: ModuleName -> (FilePath, String) decodeModule moduleName = (intercalate "/" (init xs), last xs) where xs = words $ replaceEq '.' ' ' moduleName -- | Given the directory and file name find the corresponding module name, e.g.: -- -- > encodeModule "Data/Functor" "Identity.hs" == "Data.Functor.Identity" -- > encodeModule "" "Prelude" == "Prelude" -- > uncurry encodeModule (decodeModule name) == name encodeModule :: FilePath -> String -> ModuleName encodeModule dir file | dir == "" = takeBaseName file | otherwise = replaceEq '/' '.' dir ++ '.' : takeBaseName file -- | Find the generator for a given 'Context' and a source file. For example: -- findGenerator (Context Stage1 compiler vanilla) -- "_build/stage1/compiler/build/Lexer.hs" -- == Just ("compiler/parser/Lexer.x", Alex) -- findGenerator (Context Stage1 base vanilla) -- "_build/stage1/base/build/Prelude.hs" -- == Nothing findGenerator :: Context -> FilePath -> Action (Maybe (FilePath, Builder)) findGenerator Context {..} file = do maybeSource <- askOracle $ Generator (stage, package, file) return $ do source <- maybeSource builder <- determineBuilder stage source return (source, builder) -- | Find all Haskell source files for a given 'Context'. hsSources :: Context -> Action [FilePath] hsSources context = do let modFile (m, Nothing ) = generatedFile context m modFile (m, Just file ) | takeExtension file `elem` haskellExtensions = return file | otherwise = generatedFile context m mapM modFile =<< contextFiles context -- | Find all Haskell object files for a given 'Context'. Note: this is a much -- simpler function compared to 'hsSources', because all object files live in -- the build directory regardless of whether they are generated or not. hsObjects :: Context -> Action [FilePath] hsObjects context = do modules <- interpretInContext context (getContextData PD.modules) mapM (objectPath context . moduleSource) modules -- | Generated module files live in the 'Context' specific build directory. generatedFile :: Context -> ModuleName -> Action FilePath generatedFile context moduleName = buildPath context <&> (-/- moduleSource moduleName) -- | Turn a module name (e.g. @Data.Functor@) to a path (e.g. @Data/Functor.hs@). moduleSource :: ModuleName -> FilePath moduleSource moduleName = replaceEq '.' '/' moduleName <.> "hs" -- | Module files for a given 'Context'. contextFiles :: Context -> Action [(ModuleName, Maybe FilePath)] contextFiles context@Context {..} = do modules <- fmap sort . interpretInContext context $ getContextData PD.modules zip modules <$> askOracle (ModuleFiles (stage, package)) -- | This is an important oracle whose role is to find and cache module source -- files. It takes a 'Stage' and a 'Package', looks up corresponding source -- directories @dirs@ and a sorted list of module names @modules@, and for each -- module, e.g. @A.B.C@, returns a 'FilePath' of the form @dir/A/B/C.extension@, -- such that @dir@ belongs to @dirs@, and file @dir/A/B/C.extension@ exists, or -- 'Nothing' if there is no such file. If more than one matching file is found -- an error is raised. For example, for 'Stage1' and 'compiler', @dirs@ will -- contain ["compiler/codeGen", "compiler/parser"], and @modules@ will contain -- ["CodeGen.Platform.ARM", "Config", "Lexer"]; the oracle will produce a list -- containing [Just "compiler/codeGen/CodeGen/Platform/ARM.hs", Nothing, -- Just "compiler/parser/Lexer.x"]. The oracle ignores @.(l)hs-boot@ files. moduleFilesOracle :: Rules () moduleFilesOracle = void $ do void . addOracleCache $ \(ModuleFiles (stage, package)) -> do let context = vanillaContext stage package srcDirs <- interpretInContext context (getContextData PD.srcDirs) mainIs <- interpretInContext context (getContextData PD.mainIs) let removeMain = case mainIs of Just (mod, _) -> delete mod Nothing -> id modules <- fmap sort $ interpretInContext context (getContextData PD.modules) autogen <- autogenPath context let dirs = autogen : map (pkgPath package -/-) srcDirs -- Don't resolve the file path for module `Main` twice. modDirFiles = groupSort $ map decodeModule $ removeMain modules result <- concatForM dirs $ \dir -> do todo <- filterM (doesDirectoryExist . (dir -/-) . fst) modDirFiles forM todo $ \(mDir, mFiles) -> do let fullDir = unifyPath $ dir -/- mDir files <- getDirectoryFiles fullDir (moduleFilePatterns stage) let cmp f = compare (dropExtension f) found = intersectOrd cmp files mFiles return (map (fullDir -/-) found, mDir) -- For a BuildInfo, it may be a library, which doesn't have the @Main@ -- module, or an executable, which must have the @Main@ module and the -- file path of @Main@ module is indicated by the @main-is@ field in its -- Cabal file. -- -- For the Main module, the file name may not be @Main.hs@, unlike other -- exposed modules. We could get the file path by the module name for -- other exposed modules, but for @Main@ we must resolve the file path -- via the @main-is@ field in the Cabal file. mainpairs <- case mainIs of Just (mod, filepath) -> concatForM dirs $ \dir -> do found <- doesFileExist (dir -/- filepath) return [(mod, unifyPath $ dir -/- filepath) | found] Nothing -> return [] let pairs = sort $ mainpairs ++ [ (encodeModule d f, f) | (fs, d) <- result, f <- fs ] multi = [ (m, f1, f2) | (m, f1):(n, f2):_ <- tails pairs, m == n ] unless (null multi) $ do let (m, f1, f2) = head multi error $ "Module " ++ m ++ " has more than one source file: " ++ f1 ++ " and " ++ f2 ++ "." return $ lookupAll modules pairs -- Optimisation: we discard Haskell files here, because they are never used -- as generators, and hence would be discarded in 'findGenerator' anyway. generators <- newCache $ \(stage, package) -> do let context = vanillaContext stage package files <- contextFiles context list <- sequence [ (,src) <$> generatedFile context modName | (modName, Just src) <- files , takeExtension src `notElem` haskellExtensions ] return $ Map.fromList list addOracleCache $ \(Generator (stage, package, file)) -> Map.lookup file <$> generators (stage, package)
snowleopard/shaking-up-ghc
src/Oracles/ModuleFiles.hs
bsd-3-clause
8,759
0
26
2,124
1,780
935
845
-1
-1
module Test0 () where {-@ type GeNum a N = {v: a | N <= v} @-} {-@ type PosInt = GeNum Int {0} @-} {-@ myabs :: Int -> PosInt @-} myabs :: Int -> Int myabs x = if (x > 0) then x else (0 - x) {-@ incr :: x:Int -> GeNum Int {x} @-} incr :: Int -> Int incr x = x + 1
mightymoose/liquidhaskell
tests/pos/alias01.hs
bsd-3-clause
269
0
7
75
71
42
29
5
2
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} -- ---------------------------------------------------------------------------- -- -- (c) The University of Glasgow 2006 -- -- Fingerprints for recompilation checking and ABI versioning, and -- implementing fast comparison of Typeable. -- -- ---------------------------------------------------------------------------- module GHC.Fingerprint.Type (Fingerprint(..)) where import GHC.Base import GHC.List (length, replicate) import GHC.Num import GHC.Show import GHC.Word import Numeric (showHex) -- Using 128-bit MD5 fingerprints for now. data Fingerprint = Fingerprint {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64 deriving ( Eq -- ^ @since 4.4.0.0 , Ord -- ^ @since 4.4.0.0 ) -- | @since 4.7.0.0 instance Show Fingerprint where show (Fingerprint w1 w2) = hex16 w1 ++ hex16 w2 where -- | Formats a 64 bit number as 16 digits hex. hex16 :: Word64 -> String hex16 i = let hex = showHex i "" in replicate (16 - length hex) '0' ++ hex
sdiehl/ghc
libraries/base/GHC/Fingerprint/Type.hs
bsd-3-clause
1,068
0
14
215
186
107
79
17
0
{-# LANGUAGE GeneralizedNewtypeDeriving, TypeFamilies, FlexibleContexts, TupleSections, FlexibleInstances, MultiParamTypeClasses #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Futhark.Pass.ExplicitAllocations ( explicitAllocations , simplifiable , arraySizeInBytesExp ) where import Control.Applicative import Control.Monad.State import Control.Monad.Writer import Control.Monad.Reader import Control.Monad.RWS.Strict import qualified Data.Map.Strict as M import qualified Data.Set as S import Data.Maybe import Prelude hiding (div, mod, quot, rem) import Futhark.Representation.Kernels import Futhark.Optimise.Simplifier.Lore (mkWiseBody, mkWiseLetStm, removeExpWisdom, removeScopeWisdom) import Futhark.MonadFreshNames import Futhark.Representation.ExplicitMemory import qualified Futhark.Representation.ExplicitMemory.IndexFunction as IxFun import Futhark.Tools import qualified Futhark.Analysis.SymbolTable as ST import Futhark.Optimise.Simplifier.Engine (SimpleOps (..)) import qualified Futhark.Optimise.Simplifier.Engine as Engine import Futhark.Pass import Futhark.Util (splitFromEnd) type InInKernel = Futhark.Representation.Kernels.InKernel type OutInKernel = Futhark.Representation.ExplicitMemory.InKernel data AllocStm = SizeComputation VName (PrimExp VName) | Allocation VName SubExp Space | ArrayCopy VName Bindage VName deriving (Eq, Ord, Show) bindAllocStm :: (MonadBinder m, Op (Lore m) ~ MemOp inner) => AllocStm -> m () bindAllocStm (SizeComputation name pe) = letBindNames'_ [name] =<< toExp (coerceIntPrimExp Int64 pe) bindAllocStm (Allocation name size space) = letBindNames'_ [name] $ Op $ Alloc size space bindAllocStm (ArrayCopy name bindage src) = letBindNames_ [(name,bindage)] $ BasicOp $ Copy src class (MonadFreshNames m, HasScope lore m, ExplicitMemorish lore) => Allocator lore m where addAllocStm :: AllocStm -> m () -- | The subexpression giving the number of elements we should -- allocate space for. See 'ChunkMap' comment. dimAllocationSize :: SubExp -> m SubExp expHints :: Exp lore -> m [ExpHint] expHints e = return $ replicate (expExtTypeSize e) NoHint allocateMemory :: Allocator lore m => String -> SubExp -> Space -> m VName allocateMemory desc size space = do v <- newVName desc addAllocStm $ Allocation v size space return v computeSize :: Allocator lore m => String -> PrimExp VName -> m SubExp computeSize desc se = do v <- newVName desc addAllocStm $ SizeComputation v se return $ Var v type Allocable fromlore tolore = (ExplicitMemorish tolore, SameScope fromlore Kernels, RetType fromlore ~ RetType Kernels, BranchType fromlore ~ BranchType Kernels, BodyAttr fromlore ~ (), BodyAttr tolore ~ (), ExpAttr tolore ~ (), SizeSubst (Op tolore)) -- | A mapping from chunk names to their maximum size. XXX FIXME -- HACK: This is part of a hack to add loop-invariant allocations to -- reduce kernels, because memory expansion does not use range -- analysis yet (it should). type ChunkMap = M.Map VName SubExp data AllocEnv fromlore tolore = AllocEnv { chunkMap :: ChunkMap , allocInOp :: Op fromlore -> AllocM fromlore tolore (Op tolore) } boundDims :: ChunkMap -> AllocEnv fromlore tolore -> AllocEnv fromlore tolore boundDims m env = env { chunkMap = m <> chunkMap env } boundDim :: VName -> SubExp -> AllocEnv fromlore tolore -> AllocEnv fromlore tolore boundDim name se = boundDims $ M.singleton name se -- | Monad for adding allocations to an entire program. newtype AllocM fromlore tolore a = AllocM (BinderT tolore (ReaderT (AllocEnv fromlore tolore) (State VNameSource)) a) deriving (Applicative, Functor, Monad, MonadFreshNames, HasScope tolore, LocalScope tolore, MonadReader (AllocEnv fromlore tolore)) instance (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => MonadBinder (AllocM fromlore tolore) where type Lore (AllocM fromlore tolore) = tolore mkExpAttrM _ _ = return () mkLetNamesM names e = do pat <- patternWithAllocations names e return $ Let pat (defAux ()) e mkBodyM bnds res = return $ Body () bnds res addStm binding = AllocM $ addBinderStm binding collectStms (AllocM m) = AllocM $ collectBinderStms m certifying cs (AllocM m) = AllocM $ certifyingBinder cs m instance Allocable fromlore OutInKernel => Allocator ExplicitMemory (AllocM fromlore ExplicitMemory) where addAllocStm (SizeComputation name se) = letBindNames'_ [name] =<< toExp (coerceIntPrimExp Int64 se) addAllocStm (Allocation name size space) = letBindNames'_ [name] $ Op $ Alloc size space addAllocStm (ArrayCopy name bindage src) = letBindNames_ [(name, bindage)] $ BasicOp $ Copy src dimAllocationSize (Var v) = -- It is important to recurse here, as the substitution may itself -- be a chunk size. maybe (return $ Var v) dimAllocationSize =<< asks (M.lookup v . chunkMap) dimAllocationSize size = return size expHints = kernelExpHints instance Allocable fromlore OutInKernel => Allocator OutInKernel (AllocM fromlore OutInKernel) where addAllocStm (SizeComputation name se) = letBindNames'_ [name] =<< toExp (coerceIntPrimExp Int64 se) addAllocStm (Allocation name size space) = letBindNames'_ [name] $ Op $ Alloc size space addAllocStm (ArrayCopy name bindage src) = letBindNames_ [(name, bindage)] $ BasicOp $ Copy src dimAllocationSize (Var v) = -- It is important to recurse here, as the substitution may itself -- be a chunk size. maybe (return $ Var v) dimAllocationSize =<< asks (M.lookup v . chunkMap) dimAllocationSize size = return size expHints = inKernelExpHints runAllocM :: (MonadFreshNames m, BinderOps tolore) => (Op fromlore -> AllocM fromlore tolore (Op tolore)) -> AllocM fromlore tolore a -> m a runAllocM handleOp (AllocM m) = fmap fst $ modifyNameSource $ runState $ runReaderT (runBinderT m mempty) env where env = AllocEnv mempty handleOp subAllocM :: (SameScope tolore1 tolore2, ExplicitMemorish tolore2, BinderOps tolore1) => (Op fromlore1 -> AllocM fromlore1 tolore1 (Op tolore1)) -> AllocM fromlore1 tolore1 a -> AllocM fromlore2 tolore2 a subAllocM handleOp (AllocM m) = do scope <- castScope <$> askScope chunks <- asks chunkMap let env = AllocEnv chunks handleOp fmap fst $ modifyNameSource $ runState $ runReaderT (runBinderT m scope) env -- | Monad for adding allocations to a single pattern. newtype PatAllocM lore a = PatAllocM (RWS (Scope lore) [AllocStm] VNameSource a) deriving (Applicative, Functor, Monad, HasScope lore, MonadWriter [AllocStm], MonadFreshNames) instance Allocator ExplicitMemory (PatAllocM ExplicitMemory) where addAllocStm = tell . pure dimAllocationSize = return instance Allocator OutInKernel (PatAllocM OutInKernel) where addAllocStm = tell . pure dimAllocationSize = return runPatAllocM :: MonadFreshNames m => PatAllocM lore a -> Scope lore -> m (a, [AllocStm]) runPatAllocM (PatAllocM m) mems = modifyNameSource $ frob . runRWS m mems where frob (a,s,w) = ((a,w),s) arraySizeInBytesExp :: Type -> PrimExp VName arraySizeInBytesExp t = product [ toInt64 $ product $ map (primExpFromSubExp int32) (arrayDims t) , ValueExp $ IntValue $ Int64Value $ primByteSize $ elemType t ] where toInt64 = ConvOpExp $ SExt Int32 Int64 arraySizeInBytesExpM :: Allocator lore m => Type -> m (PrimExp VName) arraySizeInBytesExpM t = do dims <- mapM dimAllocationSize (arrayDims t) let dim_prod_i32 = product $ map (primExpFromSubExp int32) dims let elm_size_i64 = ValueExp $ IntValue $ Int64Value $ primByteSize $ elemType t return $ product [ toInt64 dim_prod_i32, elm_size_i64 ] where toInt64 = ConvOpExp $ SExt Int32 Int64 arraySizeInBytes :: Allocator lore m => Type -> m SubExp arraySizeInBytes = computeSize "bytes" <=< arraySizeInBytesExpM allocForArray :: Allocator lore m => Type -> Space -> m (SubExp, VName) allocForArray t space = do size <- arraySizeInBytes t m <- allocateMemory "mem" size space return (size, m) allocsForStm :: (Allocator lore m, ExpAttr lore ~ ()) => [Ident] -> [(Ident,Bindage)] -> Exp lore -> m (Stm lore, [AllocStm]) allocsForStm sizeidents validents e = do rts <- expReturns e hints <- expHints e (ctxElems, valElems, postbnds) <- allocsForPattern sizeidents validents rts hints return (Let (Pattern ctxElems valElems) (defAux ()) e, postbnds) patternWithAllocations :: (Allocator lore m, ExpAttr lore ~ ()) => [(VName, Bindage)] -> Exp lore -> m (Pattern lore) patternWithAllocations names e = do (ts',sizes) <- instantiateShapes' =<< expExtType e let identForBindage name t BindVar = pure (Ident name t, BindVar) identForBindage name _ bindage@(BindInPlace src _) = do t <- lookupType src pure (Ident name t, bindage) vals <- sequence [ identForBindage name t bindage | ((name,bindage), t) <- zip names ts' ] (Let pat _ _, extrabnds) <- allocsForStm sizes vals e case extrabnds of [] -> return pat _ -> fail $ "Cannot make allocations for pattern of " ++ pretty e allocsForPattern :: Allocator lore m => [Ident] -> [(Ident,Bindage)] -> [ExpReturns] -> [ExpHint] -> m ([PatElem ExplicitMemory], [PatElem ExplicitMemory], [AllocStm]) allocsForPattern sizeidents validents rts hints = do let sizes' = [ PatElem size BindVar $ MemPrim int32 | size <- map identName sizeidents ] (vals,(mems_and_sizes, postbnds)) <- runWriterT $ forM (zip3 validents rts hints) $ \((ident,bindage), rt, hint) -> do let shape = arrayShape $ identType ident case rt of MemPrim _ -> do summary <- lift $ summaryForBindage (identType ident) bindage hint return $ PatElem (identName ident) bindage summary MemMem (Free size) space -> return $ PatElem (identName ident) bindage $ MemMem size space MemMem Ext{} space -> return $ PatElem (identName ident) bindage $ MemMem (intConst Int32 0) space MemArray bt _ u (Just (ReturnsInBlock mem ixfun)) -> do ixfun' <- instantiateIxFun ixfun case bindage of BindVar -> return $ PatElem (identName ident) bindage $ MemArray bt shape u $ ArrayIn mem ixfun' BindInPlace src slice -> do (destmem,destixfun) <- lift $ lookupArraySummary src if destmem == mem && destixfun == ixfun' then return $ PatElem (identName ident) bindage $ MemArray bt shape u $ ArrayIn mem ixfun' else do -- The expression returns at some specific memory -- location, but we want to put the result somewhere -- else. This means we need to store it in the memory -- it wants to first, then copy it to our intended -- destination in an extra binding. tmp_buffer <- lift $ newIdent (baseString (identName ident)<>"_ext_buffer") (identType ident `setArrayDims` sliceDims slice) tell ([], [ArrayCopy (identName ident) bindage $ identName tmp_buffer]) return $ PatElem (identName tmp_buffer) BindVar $ MemArray bt (arrayShape $ identType tmp_buffer) u $ ArrayIn mem ixfun' MemArray _ extshape _ Nothing | Just _ <- knownShape extshape -> do summary <- lift $ summaryForBindage (identType ident) bindage hint return $ PatElem (identName ident) bindage summary MemArray bt _ u (Just ReturnsNewBlock{}) | BindInPlace _ slice <- bindage -> do -- The expression returns its own memory, but the pattern -- wants to store it somewhere else. We first let it -- store the value where it wants, then we copy it to the -- intended destination. In some cases, the copy may be -- optimised away later, but in some cases it may not be -- possible (e.g. function calls). tmp_buffer <- lift $ newIdent (baseString (identName ident)<>"_ext_buffer") (identType ident `setArrayDims` sliceDims slice) (memsize,mem,(_,ixfun)) <- lift $ memForBindee tmp_buffer tell ([PatElem (identName memsize) BindVar $ MemPrim int64, PatElem (identName mem) BindVar $ MemMem (Var $ identName memsize) DefaultSpace], [ArrayCopy (identName ident) bindage $ identName tmp_buffer]) return $ PatElem (identName tmp_buffer) BindVar $ MemArray bt (arrayShape $ identType tmp_buffer) u $ ArrayIn (identName mem) ixfun MemArray bt _ u _ -> do (memsize,mem,(ident',ixfun)) <- lift $ memForBindee ident tell ([PatElem (identName memsize) BindVar $ MemPrim int64, PatElem (identName mem) BindVar $ MemMem (Var $ identName memsize) DefaultSpace], []) return $ PatElem (identName ident') bindage $ MemArray bt shape u $ ArrayIn (identName mem) ixfun return (sizes' <> mems_and_sizes, vals, postbnds) where knownShape = mapM known . shapeDims known (Free v) = Just v known Ext{} = Nothing instantiateIxFun :: Monad m => ExtIxFun -> m IxFun instantiateIxFun = traverse $ traverse inst where inst Ext{} = fail "instantiateIxFun: not yet" inst (Free x) = return x summaryForBindage :: (ExplicitMemorish lore, Allocator lore m) => Type -> Bindage -> ExpHint -> m (MemBound NoUniqueness) summaryForBindage (Prim bt) BindVar _ = return $ MemPrim bt summaryForBindage (Mem size space) BindVar _ = return $ MemMem size space summaryForBindage t@(Array bt shape u) BindVar NoHint = do (_, m) <- allocForArray t DefaultSpace return $ directIndexFunction bt shape u m t summaryForBindage t BindVar (Hint ixfun space) = do let bt = elemType t bytes <- computeSize "bytes" $ product $ fromIntegral (primByteSize (elemType t)::Int64) : map (ConvOpExp (SExt Int32 Int64)) (IxFun.base ixfun) m <- allocateMemory "mem" bytes space return $ MemArray bt (arrayShape t) NoUniqueness $ ArrayIn m ixfun summaryForBindage _ (BindInPlace src _) _ = lookupMemInfo src memForBindee :: (MonadFreshNames m) => Ident -> m (Ident, Ident, (Ident, IxFun)) memForBindee ident = do size <- newIdent (memname <> "_size") (Prim int64) mem <- newIdent memname $ Mem (Var $ identName size) DefaultSpace return (size, mem, (ident, IxFun.iota $ map (primExpFromSubExp int32) $ arrayDims t)) where memname = baseString (identName ident) <> "_mem" t = identType ident directIndexFunction :: PrimType -> Shape -> u -> VName -> Type -> MemBound u directIndexFunction bt shape u mem t = MemArray bt shape u $ ArrayIn mem $ IxFun.iota $ map (primExpFromSubExp int32) $ arrayDims t allocInFParams :: (Allocable fromlore tolore) => [FParam fromlore] -> ([FParam tolore] -> AllocM fromlore tolore a) -> AllocM fromlore tolore a allocInFParams params m = do (valparams, memparams) <- runWriterT $ mapM allocInFParam params let params' = memparams <> valparams summary = scopeOfFParams params' localScope summary $ m params' allocInFParam :: (Allocable fromlore tolore) => FParam fromlore -> WriterT [FParam tolore] (AllocM fromlore tolore) (FParam tolore) allocInFParam param = case paramDeclType param of Array bt shape u -> do let memname = baseString (paramName param) <> "_mem" ixfun = IxFun.iota $ map (primExpFromSubExp int32) $ shapeDims shape memsize <- lift $ newVName (memname <> "_size") mem <- lift $ newVName memname tell [ Param memsize $ MemPrim int64 , Param mem $ MemMem (Var memsize) DefaultSpace] return param { paramAttr = MemArray bt shape u $ ArrayIn mem ixfun } Prim bt -> return param { paramAttr = MemPrim bt } Mem size space -> return param { paramAttr = MemMem size space } allocInMergeParams :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => [VName] -> [(FParam fromlore,SubExp)] -> ([FParam tolore] -> [FParam tolore] -> ([SubExp] -> AllocM fromlore tolore ([SubExp], [SubExp])) -> AllocM fromlore tolore a) -> AllocM fromlore tolore a allocInMergeParams variant merge m = do ((valparams, handle_loop_subexps), mem_and_size_params) <- runWriterT $ unzip <$> mapM allocInMergeParam merge let mergeparams' = mem_and_size_params <> valparams summary = scopeOfFParams mergeparams' mk_loop_res ses = do (valargs, memargs) <- runWriterT $ zipWithM ($) handle_loop_subexps ses return (memargs, valargs) localScope summary $ m mem_and_size_params valparams mk_loop_res where allocInMergeParam (mergeparam, Var v) | Array bt shape Unique <- paramDeclType mergeparam, loopInvariantShape mergeparam = do (mem, ixfun) <- lift $ lookupArraySummary v if IxFun.isDirect ixfun then return (mergeparam { paramAttr = MemArray bt shape Unique $ ArrayIn mem ixfun }, lift . ensureArrayIn (paramType mergeparam) mem ixfun) else doDefault mergeparam allocInMergeParam (mergeparam, _) = doDefault mergeparam doDefault mergeparam = do mergeparam' <- allocInFParam mergeparam return (mergeparam', linearFuncallArg $ paramType mergeparam) variant_names = variant ++ map (paramName . fst) merge loopInvariantShape = not . any (`elem` variant_names) . subExpVars . arrayDims . paramType ensureArrayIn :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => Type -> VName -> IxFun -> SubExp -> AllocM fromlore tolore SubExp ensureArrayIn _ _ _ (Constant v) = fail $ "ensureArrayIn: " ++ pretty v ++ " cannot be an array." ensureArrayIn t mem ixfun (Var v) = do (src_mem, src_ixfun) <- lookupArraySummary v if src_mem == mem && src_ixfun == ixfun then return $ Var v else do copy <- newIdent (baseString v ++ "_ensure_copy") t let summary = MemArray (elemType t) (arrayShape t) NoUniqueness $ ArrayIn mem ixfun pat = Pattern [] [PatElem (identName copy) BindVar summary] letBind_ pat $ BasicOp $ Copy v return $ Var $ identName copy ensureDirectArray :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => VName -> AllocM fromlore tolore (SubExp, VName, SubExp) ensureDirectArray v = do res <- lookupMemInfo v case res of MemArray _ shape _ (ArrayIn mem ixfun) | fullyDirect shape ixfun -> do memt <- lookupType mem case memt of Mem size _ -> return (size, mem, Var v) _ -> fail $ pretty mem ++ " should be a memory block but has type " ++ pretty memt _ -> -- We need to do a new allocation, copy 'v', and make a new -- binding for the size of the memory block. allocLinearArray (baseString v) v allocLinearArray :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => String -> VName -> AllocM fromlore tolore (SubExp, VName, SubExp) allocLinearArray s v = do t <- lookupType v (size, mem) <- allocForArray t DefaultSpace v' <- newIdent s t let pat = Pattern [] [PatElem (identName v') BindVar $ directIndexFunction (elemType t) (arrayShape t) NoUniqueness mem t] addStm $ Let pat (defAux ()) $ BasicOp $ Copy v return (size, mem, Var $ identName v') funcallArgs :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => [(SubExp,Diet)] -> AllocM fromlore tolore [(SubExp,Diet)] funcallArgs args = do (valargs, mem_and_size_args) <- runWriterT $ forM args $ \(arg,d) -> do t <- lift $ subExpType arg arg' <- linearFuncallArg t arg return (arg', d) return $ map (,Observe) mem_and_size_args <> valargs linearFuncallArg :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => Type -> SubExp -> WriterT [SubExp] (AllocM fromlore tolore) SubExp linearFuncallArg Array{} (Var v) = do (size, mem, arg') <- lift $ ensureDirectArray v tell [size, Var mem] return arg' linearFuncallArg _ arg = return arg explicitAllocations :: Pass Kernels ExplicitMemory explicitAllocations = simplePass "explicit allocations" "Transform program to explicit memory representation" $ intraproceduralTransformation allocInFun memoryInRetType :: [RetType Kernels] -> [RetType ExplicitMemory] memoryInRetType ts = evalState (mapM addAttr ts) $ startOfFreeIDRange ts where addAttr (Prim t) = return $ MemPrim t addAttr Mem{} = fail "memoryInRetType: too much memory" addAttr (Array bt shape u) = do i <- get <* modify (+2) return $ MemArray bt shape u $ ReturnsNewBlock DefaultSpace (i+1) (Ext i) $ IxFun.iota $ map convert $ shapeDims shape convert (Ext i) = LeafExp (Ext i) int32 convert (Free v) = Free <$> primExpFromSubExp int32 v startOfFreeIDRange :: [TypeBase ExtShape u] -> Int startOfFreeIDRange = S.size . shapeContext allocInFun :: MonadFreshNames m => FunDef Kernels -> m (FunDef ExplicitMemory) allocInFun (FunDef entry fname rettype params fbody) = runAllocM handleOp $ allocInFParams params $ \params' -> do fbody' <- insertStmsM $ allocInFunBody (length rettype) fbody return $ FunDef entry fname (memoryInRetType rettype) params' fbody' where handleOp GroupSize = return $ Inner GroupSize handleOp NumGroups = return $ Inner NumGroups handleOp TileSize = return $ Inner TileSize handleOp (SufficientParallelism se) = return $ Inner $ SufficientParallelism se handleOp (Kernel desc space ts kbody) = subAllocM handleKernelExp $ Inner . Kernel desc space ts <$> localScope (scopeOfKernelSpace space) (allocInKernelBody kbody) handleKernelExp (SplitSpace o w i elems_per_thread) = return $ Inner $ SplitSpace o w i elems_per_thread handleKernelExp (Combine cspace ts active body) = Inner . Combine cspace ts active <$> allocInBodyNoDirect body handleKernelExp (GroupReduce w lam input) = do summaries <- mapM lookupArraySummary arrs lam' <- allocInReduceLambda lam summaries return $ Inner $ GroupReduce w lam' input where arrs = map snd input handleKernelExp (GroupScan w lam input) = do summaries <- mapM lookupArraySummary arrs lam' <- allocInReduceLambda lam summaries return $ Inner $ GroupScan w lam' input where arrs = map snd input handleKernelExp (GroupStream w maxchunk lam accs arrs) = do acc_summaries <- mapM accSummary accs arr_summaries <- mapM lookupArraySummary arrs lam' <- allocInGroupStreamLambda maxchunk lam acc_summaries arr_summaries return $ Inner $ GroupStream w maxchunk lam' accs arrs where accSummary (Constant v) = return $ MemPrim $ primValueType v accSummary (Var v) = lookupMemInfo v allocInBodyNoDirect :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => Body fromlore -> AllocM fromlore tolore (Body tolore) allocInBodyNoDirect (Body _ bnds res) = allocInStms bnds $ \bnds' -> return $ Body () bnds' res bodyReturnMemCtx :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => SubExp -> AllocM fromlore tolore [SubExp] bodyReturnMemCtx Constant{} = return [] bodyReturnMemCtx (Var v) = do info <- lookupMemInfo v case info of MemPrim{} -> return [] MemMem{} -> return [] -- should not happen MemArray _ _ _ (ArrayIn mem _) -> do size <- lookupMemSize mem return [size, Var mem] allocInFunBody :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => Int -> Body fromlore -> AllocM fromlore tolore (Body tolore) allocInFunBody num_vals (Body _ bnds res) = allocInStms bnds $ \bnds' -> do (res'', allocs) <- collectStms $ do res' <- mapM ensureDirect res let (ctx_res, val_res) = splitFromEnd num_vals res' mem_ctx_res <- concat <$> mapM bodyReturnMemCtx val_res return $ ctx_res <> mem_ctx_res <> val_res return $ Body () (bnds'<>allocs) res'' where ensureDirect se@Constant{} = return se ensureDirect (Var v) = do bt <- primType <$> lookupType v if bt then return $ Var v else do (_, _, v') <- ensureDirectArray v return v' allocInStms :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => [Stm fromlore] -> ([Stm tolore] -> AllocM fromlore tolore a) -> AllocM fromlore tolore a allocInStms origbnds m = allocInStms' origbnds [] where allocInStms' [] bnds' = m bnds' allocInStms' (x:xs) bnds' = do allocbnds <- allocInStm' x let summaries = scopeOf allocbnds localScope summaries $ local (boundDims $ mconcat $ map sizeSubst allocbnds) $ allocInStms' xs (bnds'++allocbnds) allocInStm' bnd = do ((),bnds') <- collectStms $ certifying (stmCerts bnd) $ allocInStm bnd return bnds' allocInStm :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => Stm fromlore -> AllocM fromlore tolore () allocInStm (Let (Pattern sizeElems valElems) _ e) = do e' <- allocInExp e let sizeidents = map patElemIdent sizeElems validents = [ (Ident name t, bindage) | PatElem name bindage t <- valElems ] (bnd, bnds) <- allocsForStm sizeidents validents e' addStm bnd mapM_ addAllocStm bnds allocInExp :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => Exp fromlore -> AllocM fromlore tolore (Exp tolore) allocInExp (DoLoop ctx val form (Body () bodybnds bodyres)) = allocInMergeParams mempty ctx $ \_ ctxparams' _ -> allocInMergeParams (map paramName ctxparams') val $ \new_ctx_params valparams' mk_loop_val -> do form' <- allocInLoopForm form localScope (scopeOf form') $ do (valinit_ctx, valinit') <- mk_loop_val valinit body' <- insertStmsM $ allocInStms bodybnds $ \bodybnds' -> do ((val_ses,valres'),val_retbnds) <- collectStms $ mk_loop_val valres return $ Body () (bodybnds'<>val_retbnds) (ctxres++val_ses++valres') return $ DoLoop (zip (ctxparams'++new_ctx_params) (ctxinit++valinit_ctx)) (zip valparams' valinit') form' body' where (_ctxparams, ctxinit) = unzip ctx (_valparams, valinit) = unzip val (ctxres, valres) = splitAt (length ctx) bodyres allocInExp (Apply fname args rettype loc) = do args' <- funcallArgs args return $ Apply fname args' (memoryInRetType rettype) loc allocInExp (If cond tbranch fbranch (IfAttr rets ifsort)) = do tbranch' <- allocInFunBody (length rets) tbranch fbranch' <- allocInFunBody (length rets) fbranch let rets' = createBodyReturns rets return $ If cond tbranch' fbranch' $ IfAttr rets' ifsort allocInExp e = mapExpM alloc e where alloc = identityMapper { mapOnBody = fail "Unhandled Body in ExplicitAllocations" , mapOnRetType = fail "Unhandled RetType in ExplicitAllocations" , mapOnBranchType = fail "Unhandled BranchType in ExplicitAllocations" , mapOnFParam = fail "Unhandled FParam in ExplicitAllocations" , mapOnLParam = fail "Unhandled LParam in ExplicitAllocations" , mapOnOp = \op -> do handle <- asks allocInOp handle op } createBodyReturns :: [ExtType] -> [BodyReturns] createBodyReturns ts = evalState (mapM inspect ts) $ S.size $ shapeContext ts where inspect (Array pt shape u) = do i <- get <* modify (+2) return $ MemArray pt shape u $ ReturnsNewBlock DefaultSpace (i+1) (Ext i) $ IxFun.iota $ map convert $ shapeDims shape inspect (Prim pt) = return $ MemPrim pt inspect (Mem size space) = return $ MemMem (Free size) space convert (Ext i) = LeafExp (Ext i) int32 convert (Free v) = Free <$> primExpFromSubExp int32 v allocInLoopForm :: (Allocable fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => LoopForm fromlore -> AllocM fromlore tolore (LoopForm tolore) allocInLoopForm (WhileLoop v) = return $ WhileLoop v allocInLoopForm (ForLoop i it n loopvars) = ForLoop i it n <$> mapM allocInLoopVar loopvars where allocInLoopVar (p,a) = do (mem, ixfun) <- lookupArraySummary a case paramType p of Array bt shape u -> let ixfun' = IxFun.slice ixfun $ fullSliceNum (IxFun.shape ixfun) [DimFix $ LeafExp i int32] in return (p { paramAttr = MemArray bt shape u $ ArrayIn mem ixfun' }, a) Prim bt -> return (p { paramAttr = MemPrim bt }, a) Mem size space -> return (p { paramAttr = MemMem size space }, a) allocInReduceLambda :: Lambda InInKernel -> [(VName, IxFun)] -> AllocM InInKernel OutInKernel (Lambda OutInKernel) allocInReduceLambda lam input_summaries = do let (i, other_offset_param, actual_params) = partitionChunkedKernelLambdaParameters $ lambdaParams lam (acc_params, arr_params) = splitAt (length input_summaries) actual_params this_index = LeafExp i int32 other_offset = LeafExp (paramName other_offset_param) int32 acc_params' <- allocInReduceParameters this_index 0 $ zip acc_params input_summaries arr_params' <- allocInReduceParameters this_index other_offset $ zip arr_params input_summaries allocInLambda (Param i (MemPrim int32) : other_offset_param { paramAttr = MemPrim int32 } : acc_params' ++ arr_params') (lambdaBody lam) (lambdaReturnType lam) allocInReduceParameters :: PrimExp VName -> PrimExp VName -> [(LParam InInKernel, (VName, IxFun))] -> AllocM InInKernel OutInKernel [LParam ExplicitMemory] allocInReduceParameters my_id offset = mapM allocInReduceParameter where allocInReduceParameter (p, (mem, ixfun)) = case paramType p of (Array bt shape u) -> let ixfun' = IxFun.slice ixfun $ fullSliceNum (IxFun.shape ixfun) [DimFix $ my_id + offset] in return p { paramAttr = MemArray bt shape u $ ArrayIn mem ixfun' } Prim bt -> return p { paramAttr = MemPrim bt } Mem size space -> return p { paramAttr = MemMem size space } allocInChunkedParameters :: PrimExp VName -> [(LParam InInKernel, (VName, IxFun))] -> AllocM InInKernel OutInKernel [LParam OutInKernel] allocInChunkedParameters offset = mapM allocInChunkedParameter where allocInChunkedParameter (p, (mem, ixfun)) = case paramType p of Array bt shape u -> let ixfun' = IxFun.offsetIndex ixfun offset in return p { paramAttr = MemArray bt shape u $ ArrayIn mem ixfun' } Prim bt -> return p { paramAttr = MemPrim bt } Mem size space -> return p { paramAttr = MemMem size space } allocInLambda :: [LParam OutInKernel] -> Body InInKernel -> [Type] -> AllocM InInKernel OutInKernel (Lambda OutInKernel) allocInLambda params body rettype = do body' <- localScope (scopeOfLParams params) $ allocInStms (bodyStms body) $ \bnds' -> return $ Body () bnds' $ bodyResult body return $ Lambda params body' rettype allocInKernelBody :: KernelBody InInKernel -> AllocM InInKernel OutInKernel (KernelBody OutInKernel) allocInKernelBody (KernelBody () stms res) = allocInStms stms $ \stms' -> return $ KernelBody () stms' res class SizeSubst op where opSizeSubst :: PatternT attr -> op -> ChunkMap instance SizeSubst (Kernel lore) where opSizeSubst _ _ = mempty instance SizeSubst op => SizeSubst (MemOp op) where opSizeSubst pat (Inner op) = opSizeSubst pat op opSizeSubst _ _ = mempty instance SizeSubst (KernelExp lore) where opSizeSubst (Pattern _ [size]) (SplitSpace _ _ _ elems_per_thread) = M.singleton (patElemName size) elems_per_thread opSizeSubst _ _ = mempty sizeSubst :: SizeSubst (Op lore) => Stm lore -> ChunkMap sizeSubst (Let pat _ (Op op)) = opSizeSubst pat op sizeSubst _ = mempty allocInGroupStreamLambda :: SubExp -> GroupStreamLambda InInKernel -> [MemBound NoUniqueness] -> [(VName, IxFun)] -> AllocM InInKernel OutInKernel (GroupStreamLambda OutInKernel) allocInGroupStreamLambda maxchunk lam acc_summaries arr_summaries = do let GroupStreamLambda block_size block_offset acc_params arr_params body = lam acc_params' <- allocInAccParameters acc_params acc_summaries arr_params' <- allocInChunkedParameters (LeafExp block_offset int32) $ zip arr_params arr_summaries body' <- localScope (M.insert block_size (IndexInfo Int32) $ M.insert block_offset (IndexInfo Int32) $ scopeOfLParams $ acc_params' ++ arr_params') $ local (boundDim block_size maxchunk) $ do body' <- allocInBodyNoDirect body insertStmsM $ do -- We copy the result of the body to whereever the accumulators are stored. mapM_ addStm (bodyStms body') let maybeCopyResult r p = case paramAttr p of MemArray _ _ _ (ArrayIn mem ixfun) -> ensureArrayIn (paramType p) mem ixfun r _ -> return r resultBodyM =<< zipWithM maybeCopyResult (bodyResult body') acc_params' return $ GroupStreamLambda block_size block_offset acc_params' arr_params' body' allocInAccParameters :: [LParam InInKernel] -> [MemBound NoUniqueness] -> AllocM InInKernel OutInKernel [LParam OutInKernel] allocInAccParameters = zipWithM allocInAccParameter where allocInAccParameter p attr = return p { paramAttr = attr } mkLetNamesB' :: (ExpAttr (Lore m) ~ (), Op (Lore m) ~ MemOp inner, MonadBinder m, Allocator (Lore m) (PatAllocM (Lore m))) => [(VName, Bindage)] -> Exp (Lore m) -> m (Stm (Lore m)) mkLetNamesB' names e = do scope <- askScope pat <- bindPatternWithAllocations scope names e return $ Let pat (defAux ()) e instance BinderOps ExplicitMemory where mkExpAttrB _ _ = return () mkBodyB stms res = return $ Body () stms res mkLetNamesB = mkLetNamesB' instance BinderOps OutInKernel where mkExpAttrB _ _ = return () mkBodyB stms res = return $ Body () stms res mkLetNamesB = mkLetNamesB' simplifiable :: (Engine.SimplifiableLore lore, ExpAttr lore ~ (), BodyAttr lore ~ (), Op lore ~ MemOp inner, Allocator lore (PatAllocM lore)) => (inner -> Engine.SimpleM lore (Engine.OpWithWisdom inner)) -> SimpleOps lore simplifiable simplifyInnerOp = SimpleOps mkExpAttrS' mkBodyS' mkLetNamesS' simplifyOp where mkExpAttrS' _ pat e = return $ Engine.mkWiseExpAttr pat () e mkBodyS' _ bnds res = return $ mkWiseBody () bnds res mkLetNamesS' vtable names e = do pat' <- bindPatternWithAllocations env names $ removeExpWisdom e return $ mkWiseLetStm pat' (defAux ()) e where env = removeScopeWisdom $ ST.toScope vtable simplifyOp (Alloc size space) = Alloc <$> Engine.simplify size <*> pure space simplifyOp (Inner k) = Inner <$> simplifyInnerOp k bindPatternWithAllocations :: (MonadBinder m, ExpAttr lore ~ (), Op (Lore m) ~ MemOp inner, Allocator lore (PatAllocM lore)) => Scope lore -> [(VName, Bindage)] -> Exp lore -> m (Pattern lore) bindPatternWithAllocations types names e = do (pat,prebnds) <- runPatAllocM (patternWithAllocations names e) types mapM_ bindAllocStm prebnds return pat data ExpHint = NoHint | Hint IxFun Space kernelExpHints :: (Allocator lore m, Op lore ~ MemOp (Kernel somelore)) => Exp lore -> m [ExpHint] kernelExpHints (BasicOp (Manifest perm v)) = do dims <- arrayDims <$> lookupType v let perm_inv = rearrangeInverse perm dims' = rearrangeShape perm dims ixfun = IxFun.permute (IxFun.iota $ map (primExpFromSubExp int32) dims') perm_inv return [Hint ixfun DefaultSpace] kernelExpHints (Op (Inner (Kernel _ space rets kbody))) = zipWithM hint rets $ kernelBodyResult kbody where num_threads = spaceNumThreads space spacy AllThreads = Just [num_threads] spacy ThreadsInSpace = Just $ map snd $ spaceDimensions space spacy _ = Nothing -- Heuristic: do not rearrange for returned arrays that are -- sufficiently small. coalesceReturnOfShape _ [] = False coalesceReturnOfShape bs [Constant (IntValue (Int32Value d))] = bs * d > 4 coalesceReturnOfShape _ _ = True innermost space_dims t_dims = let r = length t_dims dims = space_dims ++ t_dims perm = [length space_dims..length space_dims+r-1] ++ [0..length space_dims-1] perm_inv = rearrangeInverse perm dims_perm = rearrangeShape perm dims ixfun_base = IxFun.iota $ map (primExpFromSubExp int32) dims_perm ixfun_rearranged = IxFun.permute ixfun_base perm_inv in ixfun_rearranged hint t (ThreadsReturn threads _) | coalesceReturnOfShape (primByteSize (elemType t)) $ arrayDims t, Just space_dims <- spacy threads = do t_dims <- mapM dimAllocationSize $ arrayDims t return $ Hint (innermost space_dims t_dims) DefaultSpace hint t (ConcatReturns SplitStrided{} w _ _ _) = do t_dims <- mapM dimAllocationSize $ arrayDims t return $ Hint (innermost [w] t_dims) DefaultSpace -- TODO: Can we make hint for ConcatRetuns when it has an offset? hint Prim{} (ConcatReturns SplitContiguous w elems_per_thread Nothing _) = do let ixfun_base = IxFun.iota $ map (primExpFromSubExp int32) [num_threads,elems_per_thread] ixfun_tr = IxFun.permute ixfun_base [1,0] ixfun = IxFun.reshape ixfun_tr $ map (DimNew . primExpFromSubExp int32) [w] return $ Hint ixfun DefaultSpace hint _ _ = return NoHint kernelExpHints e = return $ replicate (expExtTypeSize e) NoHint inKernelExpHints :: (Allocator lore m, Op lore ~ MemOp (KernelExp somelore)) => Exp lore -> m [ExpHint] inKernelExpHints (Op (Inner (Combine cspace ts _ _))) = forM ts $ \t -> do alloc_dims <- mapM dimAllocationSize $ dims ++ arrayDims t let ixfun = IxFun.iota $ map (primExpFromSubExp int32) alloc_dims return $ Hint ixfun $ Space "local" where dims = map snd cspace inKernelExpHints e = return $ replicate (expExtTypeSize e) NoHint
ihc/futhark
src/Futhark/Pass/ExplicitAllocations.hs
isc
41,764
0
32
12,100
12,792
6,291
6,501
840
10
module Smips where {- a very simplified MIPS just for the purpose of playing around with pipelining and scheduling and other things. I'm definitely not caring about layout of bits and the like here, just data flow to help me understand scheduling and assembly optimizations -} type Register = Int type Label = String data Smips = Add Register Register Register | AddI Register Register Int | Sub Register Register Register | SubI Register Register Int | Load Register Register Int | Store Register Register Int | And Register Register Register | AndI Register Register Int | Or Register Register Register | OrI Register Register Int | Label Label | Jmp Label | JEq Register Register Label | JNEq Register Register Label | AddD Register Register Register | MultD Register Register Register | SubD Register Register Register | DivD Register Register Register deriving (Eq,Show) -- we'll give it a proper show instance later but by default lets just use this one
clarissalittler/mipsy
Smips.hs
mit
1,165
0
6
366
187
107
80
22
0
{-# LANGUAGE QuasiQuotes #-} module Core.FreeVarsSpec where import Test.Tasty import Test.Tasty.HUnit import Data.Generics.Fixplate (Mu(..)) import qualified Data.Set as Set import qualified Data.Map as Map import qualified Syntax.Type as Type import qualified Syntax.Term as Term import qualified Core.FreeVars as FreeVars import IR.DSL tests :: TestTree tests = testGroup "FreeVaes" [ testGroup "freeVars" [ testCase "retrieves none from a constant" $ do let res = FreeVars.freeVars ([termDSL| (constant (numeric (integer 32 -1))) |] :: Term.Term Type.Identifier Term.Identifier) res @?= Set.fromList [] , testCase "retrieves one from a variable" $ do let res = FreeVars.freeVars ([termDSL| (variable "foo") |] :: Term.Term Type.Identifier Term.Identifier) res @?= Set.fromList [Term.Identifier "foo"] , testCase "retrieves none when shadowed by an abstraction" $ do let res = FreeVars.freeVars ([termDSL| (abstraction "foo" (variable "foo")) |] :: Term.Term Type.Identifier Term.Identifier) res @?= Set.fromList [] , testCase "retrieves one when not shadowed by an abstraction" $ do let res = FreeVars.freeVars ([termDSL| (abstraction "foo" (variable "bar")) |] :: Term.Term Type.Identifier Term.Identifier) res @?= Set.fromList [Term.Identifier "bar"] , testCase "retrieves two from an application" $ do let res = FreeVars.freeVars ([termDSL| (application (variable "foo") (variable "bar")) |] :: Term.Term Type.Identifier Term.Identifier) res @?= Set.fromList [Term.Identifier "foo", Term.Identifier "bar"] , testCase "retrieves many from a record introduction" $ do let res = FreeVars.freeVars ( Fix ( Term.RecordIntroduction ( Map.fromList [ ( "1" , Fix ( Term.Variable ( Term.Identifier "bar" ) ) ) , ( "2" , Fix ( Term.Variable ( Term.Identifier "foo" ) ) ) ] ) ) ) res @?= Set.fromList [Term.Identifier "foo", Term.Identifier "bar"] , testCase "retrieves one from a record elimination" $ do let res = FreeVars.freeVars ( Fix ( Term.RecordElimination ( Fix ( Term.Variable ( Term.Identifier "bar" ) ) ) "foo" ) ) res @?= Set.fromList [Term.Identifier "bar"] ] , testGroup "freeVarsType" [ testCase "retrieves none from a type constant" $ do let res = FreeVars.freeVarsType ( Fix ( Type.Constant ( Type.PrimitiveConstant Type.StringPrimitive ) ) :: Type.Type Type.Identifier ) res @?= Set.fromList [] , testCase "retrieves one from a type variable" $ do let res = FreeVars.freeVarsType ( Fix ( Type.Variable ( Type.Identifier "foo" ) ) :: Type.Type Type.Identifier ) res @?= Set.fromList [Type.Identifier "foo"] , testCase "retrieves two from a function" $ do let res = FreeVars.freeVarsType ( Fix ( Type.Function [ Fix ( Type.Variable ( Type.Identifier "foo" ) ) ] ( Fix ( Type.Variable ( Type.Identifier "bar" ) ) ) ) :: Type.Type Type.Identifier ) res @?= Set.fromList [Type.Identifier "foo", Type.Identifier "bar"] ] ]
fredun/compiler
test/Core/FreeVarsSpec.hs
mit
4,366
0
29
1,942
912
467
445
89
1
module Main where import System.IO import System.Environment import System.Console.GetOpt import Control.Applicative data Opts = Opts { numberNoneBlank , displayNonePrint , displayEndDollar , numberOutLines , squeezeEmptyLines , displayTab , disableOutputBuffer , displayControl :: Bool } options:: [OptDescr (Opts -> Opts)] options = [ Option ['b'] ["number non-blank"] (NoArg (\o -> o {numberNoneBlank = True})) "Number the non-blank output lines, starting at 1." , Option ['e'] ["end dollar"] (NoArg (\o -> o {displayNonePrint = True, displayEndDollar = True})) "Display non-printing characters (see the -v option), and display a dollar sign (`$') at the end of each line." , Option ['n'] ["number lines"] (NoArg (\o -> o {numberOutLines = True})) "Number the output lines, starting at 1." , Option ['s'] ["squeeze"] (NoArg (\o -> o {squeezeEmptyLines = True})) "Squeeze multiple adjacent empty lines, causing the output to be single spaced." , Option ['t'] ["diplay tabs"] (NoArg (\o -> o {displayNonePrint = True, displayTab = True})) "Display non-printing characters (see the -v option), and display tab characters as `^I'." , Option ['u'] ["disable ob"] (NoArg (\o -> o {disableOutputBuffer = True})) "Disable output buffering." , Option ['v'] ["visible"] (NoArg (\o -> o {disableOutputBuffer = True})) "Display non-printing characters so they are visible." ] printContent::Opts -> String -> IO () printContent opts text = putStr text cat::[String] -> IO (String) cat [] = cat ["-"] cat ["-"] = getContents cat fs = foldr (\f text -> (++) <$> readFile f <*> text) (return "") fs parseOpts :: [String] -> IO ([Opts -> Opts], [String]) parseOpts args = case getOpt RequireOrder options args of (opts, files, []) -> return (opts, files) (_, _, errs) -> fail (concat errs ++ header) where header = "usage: cat [-benstuv] [file ...]" allOpts :: Bool -> Opts allOpts b = Opts { numberNoneBlank = b , displayNonePrint = b , displayEndDollar = b , numberOutLines = b , squeezeEmptyLines= b , displayTab = b , disableOutputBuffer = b , displayControl = b } processOpts :: [Opts -> Opts] -> Opts processOpts [] = allOpts False processOpts opts = foldl (flip ($)) (allOpts False) opts main = do args <- getArgs (optList, files) <- parseOpts args let opts = processOpts optList cat files >>= printContent opts
reeze/coreutils.hs
cat.hs
mit
2,456
38
12
516
817
459
358
65
2
import System.IO import Control.Monad import Data.List.Extra import Data.Maybe import qualified Data.Char as C import qualified Data.Map as Map import Debug.Trace ------ iread :: String -> Int iread = read --answer :: (Show a) => (String -> a) -> IO () answer f = interact $ (++"\n") . show . f --answer f = interact $ (++"\n") . intercalate "\n" . map show . f ord0 c = C.ord c - C.ord 'a' chr0 i = C.chr (i + C.ord 'a') incletter c i = chr0 ((ord0 c + i) `mod` 26) splitOn1 a b = fromJust $ stripInfix a b rsplitOn1 a b = fromJust $ stripInfixEnd a b -- pull out every part of a String that can be read in -- for some Read a and ignore the rest readOut :: Read a => String -> [a] readOut "" = [] readOut s = case reads s of [] -> readOut $ tail s [(x, s')] -> x : readOut s' _ -> error "ambiguous parse" ireadOut :: String -> [Int] ireadOut = readOut -------- type Seen = Map.Map ((Int, Int), (Int, Int)) () type Grid = (Map.Map (Int, Int) (Int, Int, Int), (Int, Int), (Int, Int)) loadGrid :: [((Int, Int), (Int, Int, Int))] -> Grid loadGrid xs = let [open] = nub $ map (fst . snd) $ getallviable xs in (Map.fromList xs, (maximum $ map (fst . fst) xs, 0), open) munge [a,b,c,d,e,f] = ((a,b), (c,d,e)) tryMove :: Seen -> Grid -> (Int,Int) -> (Int,Int) -> Maybe Grid tryMove seen (grid, goal, open) from to = do let goal' = if goal == from then to else goal let open' = from -- XXXXX: guard $ Map.notMember (goal', open') seen (ftot, fused, favail) <- Map.lookup from grid (ttot, tused, tavail) <- Map.lookup to grid guard $ tavail >= fused let grid' = Map.insert from (ftot, 0, ftot) $ Map.insert to (ttot, tused + fused, tavail - fused) grid return $ (grid', goal', open') getMoves :: Seen -> Grid -> (Int,Int) -> [Grid] getMoves seen grid (to@(x,y)) = do (dx,dy) <- [(-1,0),(1,0),(0,-1),(0,1)] maybeToList $ tryMove seen grid (x+dx,y+dy) (x,y) viable (c, (_, used, _)) (c', (_, _, avail)) = c /= c' && avail >= used && used > 0 findMatch stuff c = map (\x -> (c,x)) $ filter (viable c) stuff getallviable ls = concatMap (findMatch ls) ls maybeTrace b s v = if b then traceShow s v else v --lol :: Grid -> [Grid] {- lol (grid@(rgrid, _, spot)) = getMoves grid spot step state grids = grids : let next = filter (\(_,x,y) -> not (Map.member (x,y) state)) $ concatMap lol grids state' = foldr (\(_,x,y) m -> Map.insert (x,y) () m) state next in traceShow (Map.size state') (step state' next) -} search :: Seen -> [(Int,Grid)] -> Int search seen ((k,grid@(_,goal,open)) : rest) = if (0,0) == goal' then k else search seen'' $ rest ++ new where trans = case rest of [] -> True ((k',_):_) -> k /= k' goal' = maybeTrace trans (k, length rest, Map.size seen) goal seen' = (Map.insert (goal,open) () seen) seen'' = foldr (\(_,(_,g,o)) seen -> Map.insert (g,o) () seen) seen new new = do state <- getMoves seen grid open return (k+1, state) {- step state grids = grids : let next = filter (not . (flip Map.member) state) $ concatMap (nub . lol) grids state' = foldr (\k m -> Map.insert k () m) state next in step state' next -} -- solve grid = search Map.empty [(0,grid)] {- solve grid = let ass = step Map.empty [grid] in zip [0..] $ map (\x -> (length x, isJust $ find (\(_,s,_) -> s == (0,0)) x)) ass -} {- solve grid = let ass = iterate (concatMap (nub . lol)) [grid] in zip [0..] $ map (\x -> (length x, isJust $ find (\(_,s,_) -> s == (0,0)) x)) ass -} load = loadGrid . map (munge . ireadOut) . lines main = do hSetBuffering stdout NoBuffering answer $ solve . load --main = answer $ length $ map (munge . ireadOut) . lines
msullivan/advent-of-code
2016/A22b.hs
mit
3,718
0
13
877
1,425
789
636
65
3
module Main where import Examples.TranslationExample import Examples.SampleContracts import qualified ContractTranslation as CT import qualified Contract as C import qualified Examples.PayoffToHaskell as H import qualified Examples.PayoffToFuthark as F import HOAS import PrettyPrinting import Data.List main :: IO () main = do putStrLn "European option:" putStrLn $ show $ fromHoas european putStrLn "-----------------" putStrLn "Corresponding payoff expression:" putStrLn $ show $ translateEuropean -- generating Futhark code for the simple barrer contract paramEnv = F.Params ["DJ_Eurostoxx_50"] ["maturity"] barrierInFuthark = putStrLn $ F.ppFutharkCode paramEnv $ transC (fromHoas barrier) barrierInFutharkCutPayoff = putStrLn $ F.ppFutharkCode paramEnv $ CT.cutPayoff $ transC (fromHoas barrier) writeBarrierCode = F.compileAndWrite "./src/Examples/Futhark/" paramEnv (CT.cutPayoff $ transC (fromHoas barrier)) compositeInFutharkCutPayoff = putStrLn $ F.ppFutharkCode paramEnv $ CT.cutPayoff $ transC (fromHoas composite) -- reindexing according to the order of days. eo = fromHoas european' obsDays = C.obsDays eo (\_ -> error "Empty template env") transDays = C.transfDays eo (\_ -> error "Empty template env") lookInd t = maybe err id . findIndex (\x -> x == t) where err = error $ "Could not find time value: " ++ show t reindexEo = F.IndT (\t -> lookInd t obsDays) (\t -> lookInd t transDays) europeanOptInFuthark = putStrLn $ F.ppFutharkCode paramEnv $ CT.cutPayoff $ CT.simp_loopif $ transC (fromHoas european') reindexedEuropeanOptInFuthark cut modName = (putStrLn . F.wrapInModule modName . F.ppFutharkCode paramEnv . (if cut then CT.cutPayoff else id) . F.reindex reindexEo . CT.simp_loopif . transC) (fromHoas european') -- a contract example from the PPDP paper reindexEx = F.IndT (\t -> lookInd t od) (\t -> lookInd t td) where c = fromHoas templateEx od = C.obsDays c F.empty_tenv td = C.transfDays c F.empty_tenv paramEnv' = F.Params ["AAPL"] ["t0", "t1"] templateExInFuthark = putStrLn $ F.ppFutharkCode paramEnv $ CT.cutPayoff $ F.reindex reindexEx $ CT.simp_loopif $ transC (fromHoas european') -- twoOptions is a contract consisting of two european options on different observables and with different maturity reindexTwo = F.IndT (\t -> lookInd t od) (\t -> lookInd t td) where c = fromHoas twoOptions od = C.obsDays c F.empty_tenv td = C.transfDays c F.empty_tenv paramEnv2 = F.Params ["DJ_Eurostoxx_50", "AAPL"] [] -- corresponding payoff expression (simp_loopif used to replace "loopif" with zero iterations by ordinary "if") twoOptPayoff = CT.simp_loopif $ transC (fromHoas twoOptions) reindexedTwoOptInFuthark = F.ppFutharkCode paramEnv2 $ CT.cutPayoff $ F.reindex reindexTwo $ twoOptPayoff -- wrapping the whole thing to the module asFutharkModule = F.wrapInModule "PayoffLang" reindexedTwoOptInFuthark -- just testing how it works the Medium contract (FinPar) paramEnv3 = F.Params ["DJ_Eurostoxx_50", "Nikkei_225", "SP_500"] [] reindexWo = F.IndT (\t -> lookInd t od) (\t -> lookInd t td) where c = fromHoas worstOff od = C.obsDays c F.empty_tenv td = C.transfDays c F.empty_tenv worstOffInFuthark cut modName = (putStrLn . F.wrapInModule modName . F.ppFutharkCode paramEnv3 . (if cut then CT.cutPayoff else id) . F.reindex reindexWo . CT.simp_loopif . transC) (fromHoas worstOff)
annenkov/contracts
Coq/Extraction/contracts-haskell/src/Main.hs
mit
3,453
0
14
599
995
515
480
55
2
-- | A representation of a subset of the Go Programming Language, based on -- https://golang.org/ref/spec. Constructs not needed in Oden are excluded. module Oden.Go.AST where import Oden.Go.Identifier import Oden.Go.Type data Comment = CompilerDirective String | Comment String deriving (Show, Eq) data StringLiteral = RawStringLiteral String | InterpretedStringLiteral String deriving (Show, Eq) data BasicLiteral = IntLiteral Integer | FloatLiteral Double | RuneLiteral Char | StringLiteral StringLiteral deriving (Show, Eq) data LiteralKey = LiteralKeyName Identifier | LiteralKeyExpression Expression | LiteralKeyValue LiteralValueElements deriving (Show, Eq) data LiteralElement = UnkeyedElement Expression | KeyedElement LiteralKey Expression | LiteralComment Comment deriving (Show, Eq) data LiteralValueElements = LiteralValueElements [LiteralElement] deriving (Show, Eq) data FunctionParameter = FunctionParameter Identifier Type | VariadicFunctionParameter Identifier Type deriving (Show, Eq) data FunctionSignature = FunctionSignature [FunctionParameter] [Type] deriving (Show, Eq) data Literal = BasicLiteral BasicLiteral | CompositeLiteral Type LiteralValueElements | FunctionLiteral FunctionSignature Block deriving (Show, Eq) data Operand = Literal Literal | OperandName Identifier | QualifiedOperandName Identifier Identifier | GroupedExpression Expression deriving (Show, Eq) data SliceExpression = ClosedSlice Expression Expression | LowerBoundSlice Expression | UpperBoundSlice Expression deriving (Show, Eq) data Argument = Argument Expression | VariadicSliceArgument Expression deriving (Show, Eq) data PrimaryExpression = Operand Operand | Conversion Type Expression | Selector PrimaryExpression Identifier | Index PrimaryExpression Expression | Slice PrimaryExpression SliceExpression | Application PrimaryExpression [Argument] deriving (Show, Eq) data UnaryOperator = UnaryPlus | UnaryNegation | Not | BitwiseComplement | AddressOf deriving (Show, Eq) data BinaryOperator = Or | And | EQ | NEQ | LT | LTE | GT | GTE | Sum | Difference | Product | Quotient | Remainder | BitwiseOR | BitwiseXOR | BitwiseAND | BitwiseClear | LeftShift | RightShift deriving (Show, Eq) data Expression = Expression PrimaryExpression | UnaryOp UnaryOperator PrimaryExpression | BinaryOp BinaryOperator Expression Expression deriving (Show, Eq) data AssignOp = Assign | AssignSum | AssignProduct deriving (Show, Eq) data SimpleStmt = ExpressionStmt Expression | Assignment [Expression] AssignOp [Expression] | SendStmt Expression Expression deriving (Show, Eq) data ElseBranch = ElseBlock Block | ElseIf IfStmt deriving (Show, Eq) data IfStmt = If Expression Block | IfElse Expression Block ElseBranch deriving (Show, Eq) data Stmt = DeclarationStmt (Maybe Comment) Declaration | IfStmt IfStmt | ReturnStmt [Expression] | BlockStmt Block | GoStmt Expression | SimpleStmt SimpleStmt | StmtComment Comment deriving (Show, Eq) data Block = Block [Stmt] deriving (Show, Eq) data VarDeclaration = VarDeclZeroValue Identifier Type | VarDeclInitializer Identifier Type Expression deriving (Show, Eq) data Declaration = TypeDecl Identifier Type | ConstDecl Identifier Type Expression | VarDecl VarDeclaration deriving (Show, Eq) data TopLevelDeclaration = Decl Declaration | FunctionDecl Identifier FunctionSignature Block | TopLevelComment Comment deriving (Show, Eq) data PackageClause = PackageClause Identifier deriving (Show, Eq) data ImportDecl = ImportDecl Identifier StringLiteral deriving (Show, Eq) data SourceFile = SourceFile PackageClause [ImportDecl] [TopLevelDeclaration] deriving (Show, Eq)
oden-lang/oden
src/Oden/Go/AST.hs
mit
5,176
0
8
2,028
951
545
406
120
0
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} module Network.BitFunctor2.Platform.Blockchain where import Network.BitFunctor2.Platform.Blockchain.Types import Network.BitFunctor.Crypto.Hash import Control.Monad.Reader import Control.Monad.Except import Network.BitFunctor2.Platform.Blockchain.Consensus newtype BlockchainApp a = BlockchainApp { unBlockchain :: ReaderT BlockchainConfig (ExceptT BlockchainError IO) a } deriving ( Monad , Functor , Applicative , MonadReader BlockchainConfig , MonadIO , MonadError BlockchainError ) instance Blockchain BlockchainApp where newBlock = handleNewBlock height bid = return $ Just 3 -- TODO tips = return [] -- TODO runBlockchain :: BlockchainApp a -> BlockchainConfig -> IO (Either BlockchainError a) runBlockchain b c = runExceptT $ runReaderT (unBlockchain b) c null :: Blockchain m => m () null = return () handleNewBlock :: Blockchain m => NewBlockFullInfo -> m () handleNewBlock nbfi = do let block = nbfiBlock nbfi structuralValidity nbfi -- atomic (read-wise) transactionalValidity nbfi newTip <- checkConsensus nbfi >>= either consensusErr return apply nbfi newTip -- atomic end return () where consensusErr e = throwError $ NewBlockError "Consensus error" structuralValidity :: Blockchain m => NewBlockFullInfo -> m () structuralValidity nbfi = return () transactionalValidity :: Blockchain m => NewBlockFullInfo -> m () transactionalValidity nbfi = return () apply :: Blockchain m => NewBlockFullInfo -> BlockchainBlockInfo -> m () apply nbfi tip = do let block = nbfiBlock nbfi let txs = nbfiTxs nbfi -- atomic (write-wise) applyTxs txs applyBlock block tip -- atomic end applyBlock :: Blockchain m => Block -> BlockchainBlockInfo -> m () applyBlock blockToAdd newTipToSet = return () -- TODO applyTxs :: (Blockchain m, Traversable t) => t Transaction -> m () applyTxs txsToAdd = return () -- TODO
BitFunctor/bitfunctor
src/Network/BitFunctor2/Platform/Blockchain.hs
mit
2,083
0
10
396
563
283
280
49
1
{-# LANGUAGE OverloadedStrings #-} import Control.Exception (SomeException) import Control.Exception.Lifted (handle) import Control.Monad.IO.Class (liftIO) import Controllers.RecordFave import Data.Aeson (Value, encode, object, (.=), FromJSON, ToJSON) import Data.Aeson.Parser (json) import Data.Aeson.Types import qualified Data.HashMap.Lazy as M import Data.Conduit (($$)) import Data.Conduit.Attoparsec (sinkParser) import Network.HTTP.Types (status200, status400) import Network.Wai import Network.Wai.Conduit (sourceRequestBody) import Network.Wai.Handler.Warp (run) import qualified Data.Text as T main :: IO () main = run 3000 app app :: Application app req sendResponse = handle (sendResponse . invalidJson) $ do value <- sourceRequestBody req $$ sinkParser json let (m,p) = (requestMethod req, pathInfo req) let handler = case (m, p) of ("POST", ["faves"]) -> postFaveRecord ("POST", ["follows"]) -> postFollowRecord ("GET", (_ : "recommendations" : _)) -> getRecommendation respContent <- liftIO $ handler value p sendResponse $ responseLBS status200 [("Content-Type", "application/json")] respContent invalidJson :: SomeException -> Response invalidJson ex = responseLBS status400 [("Content-Type", "application/json")] $ encode $ object [ ("message" .= show ex) ]
kailuowang/BeautifulMinds
api/Server.hs
mit
1,635
0
17
510
426
244
182
37
3
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UnicodeSyntax #-} module TT.Monad ( MT , runMT ) where import Abt.Class import Abt.Concrete.LocallyNameless import Control.Applicative import Control.Monad.Catch import Control.Monad.Trans import Control.Monad.Trans.State newtype MT m α = MT { _runMT ∷ StateT Int m α } deriving (Functor, Applicative, Monad, MonadIO, MonadThrow, MonadCatch) runMT ∷ Monad m ⇒ MT m α → m α runMT = flip evalStateT 0 . _runMT gen ∷ ( Monad m , Functor m ) ⇒ StateT Int m Int gen = do i ← (+1) <$> get put i return i instance (Functor m, Monad m) ⇒ MonadVar Var (MT m) where fresh = MT $ Var Nothing <$> gen named str = MT $ Var (Just str) <$> gen
jonsterling/tt-singletons
src/TT/Monad.hs
mit
786
0
10
167
270
146
124
32
1
module Api.MatCalcApi (resource) where import Control.Monad.Reader (ReaderT) import Control.Monad.Trans (liftIO) import qualified MatCalc as S hiding (Calc, Shape) import qualified Api.Type.Calc as T import qualified Api.Type.Shape as T import Rest (Handler, Resource, Void, mkResourceReader, mkResourceId, xmlJson, xmlJsonO, xmlJsonE) import qualified Rest.Resource as R import Rest.Handler (mkInputHandler) import Control.Monad.Error (ErrorT, throwError, strMsg) import Rest.Schema (unnamedSingle, noListing) import Control.Monad (liftM) import qualified Data.Text as Text -- | Defines the /customer api end-point. resource :: Resource IO IO () Void Void resource = mkResourceId { R.name = "matcalc" -- Name of the HTTP path segment. , R.schema = noListing $ unnamedSingle $ \_ -> () , R.list = undefined -- requested by GET /customer, gives a paginated listing of customers. , R.create = Just post } post :: Handler IO post = mkInputHandler xmlJson $ \s -> liftIO $ runCalc s runCalc :: T.Shape -> IO T.Calc runCalc = S.calc S.Interior S.Paint . S.Surface
tinkerthaler/matcalc
src/Api/MatCalcApi.hs
mit
1,105
0
9
197
309
188
121
24
1
module Factory.User ( withDB , withUsers , withUsersNotFound , dbName , collectionName ) where import Control.Monad.Trans import Control.Exception(bracket_) import Database.MongoDB import Settings import Prelude -- DB withDB :: MonadIO m => Database -> Action m a -> m (Either Failure a) withDB name action = do (host', _port') <- liftIO mongoSettings pipe <- liftIO $ runIOE $ connect (host host') access pipe master name action dbName :: Database dbName = "test" collectionName :: Collection collectionName = "user" -- setup/teardown withUsers :: IO a -> IO a withUsers = bracket_ setup teardown where setup = withDB dbName $ insertMany collectionName [ [ "name" =: "test user1" , "email" =: ["mail1" =: "test@example.com", "mail2" =: "test@test.jp"]], [ "name" =: "test user2" , "email" =: ["mail1" =: "example@test.com", "mail2" =: "example@test.net"]]] teardown = withDB dbName $ delete (select [] $ collectionName) -- setup/teardown withUsersNotFound :: IO a -> IO a withUsersNotFound = bracket_ setup teardown where setup = withDB dbName $ insertMany collectionName [ [ "name" =: "test user" , "email" =: ["mail1" =: "test@example.com", "mail2" =: "test@test.jp"]], [ "name" =: "some user" , "email" =: ["mail1" =: "example@test.com", "mail2" =: "example@test.net"]]] teardown = withDB dbName $ delete (select [] $ collectionName)
cosmo0920/hs-mongo
tests/Factory/User.hs
mit
1,436
0
13
297
437
233
204
36
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} module Ambiguity where import System.Random import Control.Monad.Random.Class hiding (fromList) import Data.ReinterpretCast import Data.IntMap hiding (map, split, foldl) import Data.Bits import Data.Fixed type AmbiGenReal = Double -- | Draw a value from the cauchy distribution. cauchyDraw :: Floating a => a -> a -> a -> a cauchyDraw offset scale y = scale * tan (pi * (y - 1/2)) + offset cauchyDrawM :: (MonadRandom m, Random a, Floating a) => a -> a -> m a cauchyDrawM offset scale = do y <- getRandomR (0, 1) return $ cauchyDraw offset scale y -- | State for an ambiguous number generator. Mostly this includes -- parameters for the Cauchy distribution that we draw from at each -- step (the offset, and scale). There are other parametrs for how -- the scale changes over time, and some state for previous draws, -- which are used as seeds for the ambiguity generator. data AmbiGenState = AmbiGenState { genOffset :: !AmbiGenReal -- ^ Offset for the cauchy distribution ("location"). , genScale :: !AmbiGenReal -- ^ Scale for the cauchy distribution. , genPhi :: !AmbiGenReal -- ^ Small multiplicative scaling factor for adjusting the scale. , genPsi :: !AmbiGenReal -- ^ Small additive scaling factor for adjusting the scale. , genSeed1 :: !AmbiGenReal -- ^ Last draw. , genSeed2 :: !AmbiGenReal -- ^ Second last draw. , genSeed3 :: !AmbiGenReal -- ^ Third last draw. , genSeed4 :: !AmbiGenReal -- ^ Fourth last draw. , genDraws :: !Integer -- ^ Number of draws. } instance Show AmbiGenState where show (AmbiGenState offset scale phi psi seed1 seed2 seed3 seed4 numDraws) = concat ["offset: ", show offset, ", scale: ", show scale, " seeds: ", show (seed1, seed2, seed3, seed4), " draw: ", show numDraws] -- | Initialize the ambiguity generator. -- This will also run the first couple of steps to get the seeds. mkAmbiGen :: MonadRandom m => AmbiGenReal -> AmbiGenReal -> AmbiGenReal -> AmbiGenReal -> m AmbiGenState mkAmbiGen phi psi startOffLow startOffHigh = do offset <- getRandomR (startOffLow, startOffHigh) seed4 <- cauchyDrawM offset scale seed3 <- cauchyDrawM seed4 scale seed2 <- cauchyDrawM seed3 scale seed1 <- cauchyDrawM seed2 scale return $ AmbiGenState seed1 scale phi psi seed1 seed2 seed3 seed4 5 where scale = 1 data ContinuousState = ContinuousState { contAmbiGen :: !AmbiGenState , contPrevRealizations :: ![AmbiGenReal] } mkContinuousState :: MonadRandom m => AmbiGenReal -> AmbiGenReal -> AmbiGenReal -> AmbiGenReal -> m ContinuousState mkContinuousState phi psi startOffLow startOffHigh = do initGen <- mkAmbiGen phi psi startOffLow startOffHigh (prevDraws, states) <- unzip <$> generateWithStates initGen 100 return $ ContinuousState (last states) prevDraws nextContinuous :: MonadRandom m => ContinuousState -> m (Double, ContinuousState) nextContinuous (ContinuousState gen prev) = do let maxReal = maximum prev let minReal = minimum prev (draw, newGen) <- nextAmbi gen let newPrev = take 100 $ (draw : prev) let value = if maxReal == minReal then maxReal - fromInteger (floor maxReal) else if draw < maxReal && draw > minReal then (draw - minReal) / (maxReal - minReal) else ((toContinuous (minReal, maxReal) draw) - minReal) / (maxReal - minReal) return (value, ContinuousState newGen newPrev) nextBit :: MonadRandom m => ContinuousState -> m (Int, ContinuousState) nextBit (ContinuousState gen prev) = do index <- getRandomR (0, length prev - 1) let pivot = prev !! index (draw, newGen) <- nextAmbi gen let newPrev = take 100 $ (draw : prev) let value = if draw > pivot then 1 else 0 return (value, ContinuousState newGen newPrev) -- | Generate an ambiguous AmbiGenReal, and the next state of the ambiguity generator. nextAmbi :: MonadRandom m => AmbiGenState -> m (AmbiGenReal, AmbiGenState) nextAmbi (AmbiGenState offset scale phi psi seed1 seed2 seed3 seed4 numDraws) = do draw <- cauchyDrawM offset scale let offset' = draw let scale' = phi * seed1 + psi let nextGen = AmbiGenState offset' scale' phi psi draw seed1 seed2 seed3 (numDraws+1) return (draw, nextGen) randomShuffle :: forall m a. MonadRandom m => [a] -> m [a] randomShuffle l = map (l !!) <$> selectSequence where selectSequence :: m [Int] selectSequence = do rs <- getRandomRs (0, length l - 1) return $ take (length l) rs generateWithStates :: MonadRandom m => AmbiGenState -> Int -> m [(AmbiGenReal, AmbiGenState)] generateWithStates ambi 0 = return [] generateWithStates ambi n = do s@(v, ambi') <- nextAmbi ambi rest <- generateWithStates ambi' (n-1) return $ s : rest generate :: MonadRandom m => AmbiGenState -> Int -> m [AmbiGenReal] generate ambi n = map fst <$> generateWithStates ambi n generateR :: (Integral a, MonadRandom m) => AmbiGenState -> Int -> (a, a) -> m [a] generateR ambi n range = map (toRange range) <$> generate ambi n generateContinuousR :: (RealFrac a, MonadRandom m) => AmbiGenState -> Int -> (a, a) -> m [a] generateContinuousR ambi n range = map (toContinuous range) <$> generate ambi n ambiSkip :: MonadRandom m => Int -> AmbiGenState -> m AmbiGenState ambiSkip skipAmount ambi = do states <- generateWithStates ambi (skipAmount+1) return $ snd (states !! skipAmount) generateContinuousState :: MonadRandom m => ContinuousState -> Int -> m [(AmbiGenReal, ContinuousState)] generateContinuousState gen 0 = return [] generateContinuousState gen n = do s@(r, gen') <- nextContinuous gen rest <- generateContinuousState gen' (n-1) return $ s : rest generateContinuous :: MonadRandom m => ContinuousState -> Int -> m [AmbiGenReal] generateContinuous gen n = map fst <$> generateContinuousState gen n generateBitsState :: MonadRandom m => ContinuousState -> Int -> m [(Int, ContinuousState)] generateBitsState gen 0 = return [] generateBitsState gen n = do s@(r, gen') <- nextBit gen rest <- generateBitsState gen' (n-1) return $ s : rest generateBits :: MonadRandom m => ContinuousState -> Int -> m [Int] generateBits gen n = map fst <$> generateBitsState gen n toRange :: (Integral a, Num b, RealFrac b) => (a, a) -> b -> a toRange (lo, hi) x | lo > hi = toRange (hi, lo) x | otherwise = floor x `mod` (hi - lo + 1) + lo toContinuous :: (RealFrac a, Num b, RealFrac b) => (a, a) -> b -> a toContinuous (lo, hi) x | lo > hi = toContinuous (hi, lo) x | otherwise = (realToFrac x) `mod'` (hi - lo + 1) + lo zeroMap :: Integer -> IntMap Int zeroMap range = fromList [(x, 0) | x <- [1 .. fromIntegral range]] countMap :: Integer -> [Int] -> IntMap Int countMap range ls = Prelude.foldr (adjust (+1)) (zeroMap range) ls drawCount :: Integer -> Integer -> (StdGen -> Integer -> Integer -> [Integer]) -> IO (IntMap Int) drawCount range num generator = do source <- newStdGen let draw = generator source num range return (countMap range (map fromIntegral draw)) countToHistogram :: IntMap Int -> [Int] countToHistogram = map snd . toAscList drawHistogram :: Integer -> Integer -> (StdGen -> Integer -> Integer -> [Integer]) -> IO [Int] drawHistogram range num generator = fmap countToHistogram (drawCount range num generator) proportion :: Integer -> [Int] -> Float proportion y (x : xs) = fromIntegral x / fromIntegral y
HaskellAmbiguity/AmbiguityGenerator
src/Ambiguity.hs
mit
7,881
0
17
1,938
2,524
1,291
1,233
164
3
{-| = Secret-key One-time authentication == Security model The 'authenticate' function, viewed as a function of the message for a uniform random key, is designed to meet the standard notion of unforgeability after a single message. After the sender authenticates one message, an attacker cannot find authenticators for any other messages. The sender must not use 'authenticate' to authenticate more than one message under the same key. Authenticators for two messages under the same key should be expected to reveal enough information to allow forgeries of authenticators on other messages. == Selected primitive 'authenticate' is 'crypto_onetimeauth_poly1305', an authenticator specified in <http://nacl.cr.yp.to/valid.html, Cryptography in NaCl>, Section 9. This authenticator is proven to meet the standard notion of unforgeability after a single message. == Example >>> :set -XOverloadedStrings >>> k <- randomKey >>> let msg = "some data" >>> let tag = authenticate k msg >>> verify k msg tag True >>> k <- randomKey >>> verify k msg tag False -} module Crypto.Sodium.OnetimeAuth ( -- * Constants keyBytes -- | Number of bytes in an authentication 'Key'. , tagBytes -- | Number of bytes in an authentication 'Tag'. -- * Types , Key -- | Authentication 'Key' , mkKey -- | Smart constructor for 'Key'. Verifies that the length of the -- parameter is 'keyBytes'. , unKey -- | Returns the contents of a 'Key' , Tag -- | Authentication 'Tag' , mkTag -- | Smart constructor for 'Tag'. Verifies thta the length of the -- parameter is 'tagBytes' , unTag -- | Returns the contents of a 'Tag' -- * Key Generation , randomKey -- | Randomly generates a 'Key' for authentication. -- * Authentication/Verification , authenticate -- | Authenticates a message using a secret 'Key' , verify -- | Returns 'True' if 'Tag' is a correct authenticator -- of a message under a secret 'Key'. Otherwise it returns -- 'False'. ) where import Crypto.Sodium.OnetimeAuth.Poly1305
dnaq/crypto-sodium
src/Crypto/Sodium/OnetimeAuth.hs
mit
2,156
0
4
515
69
53
16
14
0
{- | Module : $Header$ Description : parser for CASL 'Id's based on "Common.Lexer" Copyright : (c) Christian Maeder and Uni Bremen 2002-2004 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable Parser for CASL 'Id's based on "Common.Lexer" -} {- http://www.cofi.info/Documents/CASL/Summary/ from 25 March 2001 C.2.1 Basic Specifications with Subsorts SIMPLE-ID ::= WORDS ID ::= TOKEN-ID | MIXFIX-ID TOKEN-ID ::= TOKEN MIXFIX-ID ::= TOKEN-ID PLACE-TOKEN-ID ... PLACE-TOKEN-ID | PLACE-TOKEN-ID ... PLACE-TOKEN-ID PLACE-TOKEN-ID ::= PLACE TOKEN-ID | PLACE PLACE ::= __ TOKEN ::= WORDS | DOT-WORDS | DIGIT | QUOTED-CHAR | SIGNS SIGNS are adapted here and more permissive as in the summary WORDS and NO-BRACKET-SIGNS are treated equally legal are, ie. "{a}", "{+}", "a{}=" illegal is "a=" (no two SIMPLE-TOKEN stay beside each other) SIMPLE-TOKEN ::= WORDS | DOT-WORDS | DIGIT | QUOTED-CHAR | NO-BRACKET-SIGNS STB ::= SIMPLE-TOKEN BRACKETS BST ::= BRACKETS SIMPLE-TOKEN SIGNS ::= BRACKETS | BRACKETS STB ... STB | BRACKETS STB ... STB SIMPLE-TOKEN | SIMPLE-TOKEN | SIMPLE-TOKEN BST ... BST | SIMPLE-TOKEN BST ... BST BRACKETS A SIMPLE-TOKEN followed by "[" outside nested brackets will be taken as the beginning of a compound list. Within SIGNS brackets need not be balanced, only after their composition to a MIXFIX-ID. BRACKETS = BRACKET ... BRACKET BRACKET ::= [ | ] | { | } 2.4 Identifiers brackets/braces within MIXFIX-ID must be balanced C.2.2 Structured Specifications TOKEN-ID ::= ... | TOKEN [ ID ,..., ID ] A compound list must follow the last TOKEN within MIXFIX-ID, so a compound list is never nested within (balanced) mixfix BRACKETS. Only PLACEs may follow a compound list. The IDs within the compound list may surely be compound IDs again. -} module Common.Token where import Common.Id import Common.Keywords import Common.Lexer import Common.Parsec import Text.ParserCombinators.Parsec -- * Casl keyword lists -- | reserved signs casl_reserved_ops :: [String] casl_reserved_ops = [colonS, colonQuMark, defnS, dotS, cDot, mapsTo] -- | these formula signs are legal in terms, but illegal in declarations formula_ops :: [String] formula_ops = [equalS, implS, equivS, lOr, lAnd, negS] -- | all reseverd signs casl_reserved_fops :: [String] casl_reserved_fops = formula_ops ++ casl_reserved_ops -- | reserved keywords casl_basic_reserved_words :: [String] casl_basic_reserved_words = [axiomS, axiomS ++ sS, cogeneratedS, cotypeS, cotypeS ++ sS, esortS, esortS ++ sS, etypeS, etypeS ++ sS, existsS, forallS, freeS, generatedS, opS, opS ++ sS, predS, predS ++ sS, sortS, sortS ++ sS, typeS, typeS ++ sS, varS, varS ++ sS] -- | reserved keywords casl_structured_reserved_words :: [String] casl_structured_reserved_words = libraryS : continuationKeywords ++ otherStartKeywords ++ criticalKeywords -- | keywords terminating a basic spec or starting a new library item criticalKeywords :: [String] criticalKeywords = terminatingKeywords ++ startingKeywords -- | keywords terminating a basic spec terminatingKeywords :: [String] terminatingKeywords = [andS, endS, fitS, hideS, revealS, thenS, withS, withinS] -- | keywords starting a library item startingKeywords :: [String] startingKeywords = [archS, fromS, logicS, newlogicS, refinementS, specS, unitS, viewS] -- | keywords that may follow a defining equal sign otherStartKeywords :: [String] otherStartKeywords = [closedS, cofreeS, freeS, localS, unitS ++ sS] -- | other intermediate keywords continuationKeywords :: [String] continuationKeywords = [behaviourallyS, getS, givenS, lambdaS, refinedS, resultS, toS, versionS] -- | reserved keywords casl_reserved_words :: [String] casl_reserved_words = casl_basic_reserved_words ++ casl_structured_reserved_words -- | these formula words are legal in terms, but illegal in declarations formula_words :: [String] formula_words = [asS, defS, elseS, ifS, inS, whenS, falseS, notS, trueS] -- | all reserved words casl_reserved_fwords :: [String] casl_reserved_fwords = formula_words ++ casl_reserved_words -- * a single 'Token' parser taking lists of key symbols and words as parameter {- | a simple 'Token' parser depending on reserved signs and words (including a quoted char, dot-words or a single digit) -} sid :: ([String], [String]) -> GenParser Char st Token sid (kOps, kWords) = pToken (scanQuotedChar <|> scanDotWords <|> scanDigit <|> reserved kOps scanAnySigns <|> reserved kWords scanAnyWords <?> "simple-id") -- * 'Token' lists parsers -- | balanced mixfix components within braces braceP :: GenParser Char st [Token] -> GenParser Char st [Token] braceP p = oBraceT <:> p <++> single cBraceT <|> try (oBracketT <:> single cBracketT) -- | balanced mixfix components within square brackets bracketP :: GenParser Char st [Token] -> GenParser Char st [Token] bracketP p = oBracketT <:> p <++> single cBracketT {- | an 'sid' optionally followed by other mixfix components (without no two consecutive 'sid's) -} innerMix1 :: ([String], [String]) -> GenParser Char st [Token] innerMix1 l = sid l <:> optionL (innerMix2 l) -- | mixfix components not starting with a 'sid' (possibly places) innerMix2 :: ([String], [String]) -> GenParser Char st [Token] innerMix2 l = let p = innerList l in flat (many1 (braceP p <|> bracketP p <|> many1 placeT)) <++> optionL (innerMix1 l) -- | any mixfix components within braces or brackets innerList :: ([String], [String]) -> GenParser Char st [Token] innerList l = optionL (innerMix1 l <|> innerMix2 l <?> "token") -- | mixfix components starting with a 'sid' (outside 'innerList') topMix1 :: ([String], [String]) -> GenParser Char st [Token] topMix1 l = sid l <:> optionL (topMix2 l) {- | mixfix components starting with braces ('braceP') that may follow 'sid' outside 'innerList'. (Square brackets after a 'sid' will be taken as a compound list.) -} topMix2 :: ([String], [String]) -> GenParser Char st [Token] topMix2 l = flat (many1 (braceP $ innerList l)) <++> optionL (topMix1 l) {- | mixfix components starting with square brackets ('bracketP') that may follow a place ('placeT') (outside 'innerList') -} topMix3 :: ([String], [String]) -> GenParser Char st [Token] topMix3 l = let p = innerList l in bracketP p <++> flat (many (braceP p)) <++> optionL (topMix1 l) {- | any ('topMix1', 'topMix2', 'topMix3') mixfix components that may follow a place ('placeT') at the top level -} afterPlace :: ([String], [String]) -> GenParser Char st [Token] afterPlace l = topMix1 l <|> topMix2 l <|> topMix3 l -- | places possibly followed by other ('afterPlace') mixfix components middle :: ([String], [String]) -> GenParser Char st [Token] middle l = many1 placeT <++> optionL (afterPlace l) {- | many (balanced, top-level) mixfix components ('afterPlace') possibly interspersed with multiple places ('placeT') -} tokStart :: ([String], [String]) -> GenParser Char st [Token] tokStart l = afterPlace l <++> flat (many (middle l)) {- | any (balanced, top-level) mixfix components possibly starting with places but no single 'placeT' only. -} start :: ([String], [String]) -> GenParser Char st [Token] start l = tokStart l <|> placeT <:> (tokStart l <|> many1 placeT <++> optionL (tokStart l)) <?> "id" -- * parser for mixfix and compound 'Id's -- | parsing a compound list comps :: ([String], [String]) -> GenParser Char st ([Id], Range) comps keys = do o <- oBracketT (ts, ps) <- mixId keys keys `separatedBy` commaT c <- cBracketT return (ts, toRange o ps c) {- | parse mixfix components ('start') and an optional compound list ('comps') if the last token was no place. Accept possibly further places. Key strings (second argument) within compound list may differ from top-level key strings (first argument)! -} mixId :: ([String], [String]) -> ([String], [String]) -> GenParser Char st Id mixId keys idKeys = do l <- start keys if isPlace (last l) then return (Id l [] nullRange) else do (c, p) <- option ([], nullRange) (comps idKeys) u <- many placeT return (Id (l ++ u) c p) -- | the Casl key strings (signs first) with additional keywords casl_keys :: [String] -> ([String], [String]) casl_keys ks = (ks ++ casl_reserved_fops, ks ++ casl_reserved_fwords) -- | Casl ids for operations and predicates parseId :: [String] -> GenParser Char st Id parseId ks = mixId (casl_keys ks) (casl_keys ks) -- | disallow 'barS' within the top-level of constructor names consId :: [String] -> GenParser Char st Id consId ks = mixId (barS : ks ++ casl_reserved_fops, ks ++ casl_reserved_fwords) $ casl_keys ks {- | Casl sorts are simple words ('varId'), but may have a compound list ('comps') -} sortId :: [String] -> GenParser Char st Id sortId ks = do s <- varId ks (c, p) <- option ([], nullRange) (comps $ casl_keys ks) return (Id [s] c p) -- * parser for simple 'Id's -- | parse a simple word not in 'casl_reserved_fwords' varId :: [String] -> GenParser Char st Token varId ks = pToken (reserved (ks ++ casl_reserved_fwords) scanAnyWords) -- | non-skipping version for simple ids nonSkippingSimpleId :: GenParser Char st Token nonSkippingSimpleId = parseToken $ reserved casl_reserved_words scanAnyWords -- | like 'varId'. 'Common.Id.SIMPLE_ID' for spec- and view names simpleId :: GenParser Char st Token simpleId = nonSkippingSimpleId << skipSmart -- * parser for key 'Token's -- | parse a question mark key sign ('quMark') quMarkT :: GenParser Char st Token quMarkT = pToken $ toKey quMark -- | parse a 'colonS' possibly immediately followed by a 'quMark' colonST :: GenParser Char st Token colonST = pToken $ try $ string colonS << notFollowedBy (satisfy $ \ c -> c /= '?' && isSignChar c) -- | parse the product key sign ('prodS' or 'timesS') crossT :: GenParser Char st Token crossT = pToken (toKey prodS <|> toKey timesS) <?> show prodS
nevrenato/Hets_Fork
Common/Token.hs
gpl-2.0
10,488
0
14
2,256
2,117
1,163
954
118
2
module GraphTheory.Terms where import Notes makeDefs [ "graph" , "vertex" , "edge" ]
NorfairKing/the-notes
src/GraphTheory/Terms.hs
gpl-2.0
117
0
6
45
24
14
10
-1
-1
{-# LANGUAGE OverloadedStrings #-} module MarXup.Beamer where import Control.Applicative import Data.Monoid import MarXup.Tex import MarXup.Latex (itemize,enumerate,item,color) import Data.List (intercalate) usetheme = cmd "usetheme" . tex frame tit bod = env "frame" $ do cmd "frametitle" tit bod framesubtitle = cmd "framesubtitle" note = cmd "note" hide = color "white" ----------------------------------- -- Discouraged commands -- (it's usually better to generate the various frames using Haskell code) pause :: TeX pause = cmd0 "pause" frameCmd :: String -> [Int] -> TeX -> TeX frameCmd cmd frames body = do tex $ "\\ " ++ cmd ++ "<" tex $ intercalate "," $ map show frames tex ">" braces body only :: [Int] -> TeX -> TeX only = frameCmd "only" uncover :: [Int] -> TeX -> TeX uncover = frameCmd "uncover"
jyp/MarXup
MarXup/Beamer.hs
gpl-2.0
832
0
9
150
257
134
123
26
1
{-# LANGUAGE ExtendedDefaultRules, QuasiQuotes #-} module Nirum.Cli (main, writeFiles) where import Control.Concurrent (threadDelay) import Control.Monad (forM_, forever, when) import GHC.Exts (IsList (toList)) import System.IO import qualified Data.ByteString as B import qualified Data.Map.Strict as M import qualified Data.Set as S import qualified Data.Text as T import Control.Concurrent.STM (atomically, newTVar, readTVar, TVar, writeTVar) import Data.Monoid ((<>)) import qualified Options.Applicative as OPT import System.Directory (createDirectoryIfMissing) import System.Exit (die) import System.FilePath (takeDirectory, takeExtension, (</>)) import System.FSNotify import Text.InterpolatedString.Perl6 (qq) import Text.Megaparsec.Error (errorPos, parseErrorPretty) import Text.Megaparsec.Pos (SourcePos (sourceLine, sourceColumn), unPos) import Nirum.Constructs (Construct (toCode)) import Nirum.Constructs.Identifier (toText) import Nirum.Constructs.ModulePath (ModulePath) import Nirum.Package ( PackageError ( ImportError , MetadataError , ParseError , ScanError ) , ParseError , scanModules ) import Nirum.Package.ModuleSet ( ImportError ( CircularImportError , MissingImportError , MissingModulePathError ) ) import Nirum.Targets ( BuildError (CompileError, PackageError, TargetNameError) , BuildResult , buildPackage , targetNames ) import Nirum.Version (versionString) type TFlag = TVar Bool type Nanosecond = Int data Opts = Opts { outDirectory :: !String , targetOption :: !String , watch :: !Bool , packageDirectory :: !String } data AppOptions = AppOptions { outputPath :: FilePath , packagePath :: FilePath , targetLanguage :: T.Text , watching :: Bool , building :: TFlag , changed :: TFlag } debounceDelay :: Nanosecond debounceDelay = 1 * 1000 * 1000 parseErrortoPrettyMessage :: ParseError -> FilePath -> IO String parseErrortoPrettyMessage parseError' filePath' = do sourceCode <- readFile filePath' let sourceLines = lines sourceCode sl = if length sourceLines < errorLine then "" else sourceLines !! (errorLine - 1) return [qq| {parseErrorPretty $ parseError'} $sl {arrow} |] where error' :: SourcePos error' = head $ toList $ errorPos parseError' errorLine :: Int errorLine = fromEnum $ unPos $ sourceLine error' errorColumn :: Int errorColumn = fromEnum $ unPos $ sourceColumn error' arrow :: T.Text arrow = T.snoc (T.concat (replicate (errorColumn - 1) (T.pack " "))) '^' toModuleNameText :: T.Text -> T.Text toModuleNameText t = [qq|'{t}'|] modulePathToRepr :: ModulePath -> T.Text modulePathToRepr = toModuleNameText . toCode importErrorToPrettyMessage :: ImportError -> T.Text importErrorToPrettyMessage (CircularImportError modulePaths) = [qq|Circular import detected in following orders: $order|] where circularModulesText :: [ModulePath] -> [T.Text] circularModulesText = map modulePathToRepr order :: T.Text order = T.intercalate " > " $ circularModulesText modulePaths importErrorToPrettyMessage (MissingModulePathError path path') = [qq|No module named $dataName in $moduleName|] where moduleName :: T.Text moduleName = modulePathToRepr path dataName :: T.Text dataName = modulePathToRepr path' importErrorToPrettyMessage (MissingImportError path path' identifier) = [qq|Cannot import $importText from $attrText in $foundText|] where importText :: T.Text importText = (toModuleNameText . toText) identifier foundText :: T.Text foundText = modulePathToRepr path attrText :: T.Text attrText = modulePathToRepr path' importErrorsToMessageList :: S.Set ImportError -> [T.Text] importErrorsToMessageList importErrors = S.toList $ S.map importErrorToPrettyMessage importErrors importErrorsToPrettyMessage :: S.Set ImportError -> String importErrorsToPrettyMessage importErrors = T.unpack $ T.intercalate "\n" withListStyleText where withListStyleText :: [T.Text] withListStyleText = map (T.append "- ") (importErrorsToMessageList importErrors) targetNamesText :: T.Text targetNamesText = T.intercalate ", " $ S.toAscList targetNames build :: AppOptions -> IO () build options@AppOptions { packagePath = src , outputPath = outDir , targetLanguage = target } = do result <- buildPackage target src case result of Left (TargetNameError targetName') -> tryDie' [qq|Couldn't find "$targetName'" target. Available targets: $targetNamesText|] Left (PackageError (ParseError modulePath error')) -> do {- FIXME: find more efficient way to determine filename from the given module path -} filePaths <- scanModules src case M.lookup modulePath filePaths of Just filePath' -> do m <- parseErrortoPrettyMessage error' filePath' tryDie' m Nothing -> tryDie' [qq|$modulePath not found|] Left (PackageError (ImportError importErrors)) -> tryDie' [qq|Import error: {importErrorsToPrettyMessage importErrors} |] Left (PackageError (ScanError _ error')) -> tryDie' [qq|Scan error: $error'|] Left (PackageError (MetadataError error')) -> tryDie' [qq|Metadata error: $error'|] Left (CompileError errors) -> forM_ (M.toList errors) $ \ (filePath, compileError) -> tryDie' [qq|error: $filePath: $compileError|] Right buildResult -> writeFiles outDir buildResult where tryDie' = tryDie options writeFiles :: FilePath -> BuildResult -> IO () writeFiles outDir files = forM_ (M.toAscList files) $ \ (filePath, code) -> do let outPath = outDir </> filePath createDirectoryIfMissing True $ takeDirectory outPath putStrLn outPath B.writeFile outPath code onFileChanged :: AppOptions -> Event -> IO () onFileChanged options@AppOptions { building = building' , changed = changed' } event | takeExtension path == ".nrm" = do atomically $ writeTVar changed' True buildable <- atomically $ do b <- readTVar building' writeTVar building' True return $ not b when buildable $ do threadDelay debounceDelay reactiveBuild options | otherwise = return () where path :: FilePath path = eventPath event reactiveBuild :: AppOptions -> IO () reactiveBuild options@AppOptions { building = building' , changed = changed' } = do changed'' <- atomically $ readTVar changed' when changed'' $ do atomically $ writeTVar changed' False build options atomically $ writeTVar building' False changedDuringBuild <- atomically $ readTVar changed' when changedDuringBuild $ reactiveBuild options tryDie :: AppOptions -> String -> IO () tryDie AppOptions { watching = watching' } errorMessage | watching' = hPutStrLn stderr errorMessage | otherwise = die errorMessage main :: IO () main = withManager $ \ mgr -> do opts <- OPT.execParser optsParser building' <- atomically $ newTVar False changed' <- atomically $ newTVar True let watch' = watch opts packagePath' = packageDirectory opts options = AppOptions { outputPath = outDirectory opts , packagePath = packagePath' , targetLanguage = T.pack $ targetOption opts , watching = watch' , building = building' , changed = changed' } when watch' $ do _ <- watchDir mgr packagePath' (const True) (onFileChanged options) return () reactiveBuild options -- sleep forever (until interrupted) when watch' $ forever $ threadDelay 1000000 where -- CHECK: When the CLI options changes, update the CLI examples of docs -- and README.md file. optsParser :: OPT.ParserInfo Opts optsParser = OPT.info (OPT.helper <*> versionOption <*> programOptions) (OPT.fullDesc <> OPT.progDesc ("Nirum compiler " ++ versionString) <> OPT.header header) header :: String header = "Nirum: The IDL compiler and RPC/distributed object framework" versionOption :: OPT.Parser (Opts -> Opts) versionOption = OPT.infoOption versionString (OPT.long "version" <> OPT.short 'v' <> OPT.help "Show version") programOptions :: OPT.Parser Opts programOptions = Opts <$> OPT.strOption (OPT.long "output-dir" <> OPT.short 'o' <> OPT.metavar "DIR" <> OPT.help "Output directory") <*> OPT.strOption (OPT.long "target" <> OPT.short 't' <> OPT.metavar "TARGET" <> OPT.help [qq|Target language name. Available: $targetNamesText|]) <*> OPT.switch (OPT.long "watch" <> OPT.short 'w' <> OPT.help "Watch files for change and rebuild") <*> OPT.strArgument (OPT.metavar "DIR" <> OPT.help "Package directory")
dahlia/nirum
src/Nirum/Cli.hs
gpl-3.0
9,972
0
18
3,031
2,335
1,237
1,098
223
8
module Main where import Graphics.UI.Gtk import Graphics.UI.Gtk.Gdk.EventM import Graphics.UI.Gtk.ModelView as Model import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.State import System.Glib (glibTypeInit) import Text.ParserCombinators.Parsec import Data.Set as Set import Data.Map as Map import Data.Foldable as Fold import Control.Concurrent.MVar import Control.Concurrent.MVar import DrawGraph import OpenGraph import TypeHierarchy import TypeDatabase import SemanticScheme import Paths_yanker import Data.List as List -- The type of an entry in the type list, -- storing its number of occurrences, visibility -- and the index of the first skeleton matching it data TypeEntry = TypeEntry { nbOccurrences :: Int , lambekType :: LambekFun , currentlyVisible :: Bool , firstSkelIndex :: Int } defaultGraphState :: GraphState defaultGraphState = let initSkel = LSVar 1 in createGraphState (emptyGraphFromSkel initSkel) Map.empty initSkel loadTypeDatabase :: IO [TypeEntry] loadTypeDatabase = do typePath <- getDataFileName "data/types.db" typeFile <- readFile typePath typeLines <- return $ lines typeFile let typeDB = sequence . List.map (parse parserWithEof "") $ typeLines case typeDB of Left error -> do print error return [] Right db -> do -- putStrLn (show db) return db where parserWithEof = do (a,b) <- parserLineDB eof return $ TypeEntry a b True 0 -- True is the default visibility createAddDialog builder skelStore typeStore = do -- skelUniqueId = do dialogPath <- getDataFileName "gui/add-skeleton-dialog.glade" builderAddFromFile builder dialogPath addSkeletonDialog <- builderGetObject builder castToDialog "dialog1" cancelButton <- builderGetObject builder castToButton "buttoncancel" addButton <- builderGetObject builder castToButton "buttonadd" lineEntry <- builderGetObject builder castToEntry "entry1" -- Connect signals to callbacks (add dialog) on addSkeletonDialog objectDestroy (widgetHide addSkeletonDialog) on cancelButton buttonActivated (widgetHide addSkeletonDialog) on addButton buttonActivated (tryAdd addSkeletonDialog lineEntry) on lineEntry entryActivated (tryAdd addSkeletonDialog lineEntry) widgetShowAll addSkeletonDialog where tryAdd dialog lineEntry = do contents <- entryGetText lineEntry let parseResult = parse parserLS "(unknown)" contents case parseResult of Left error -> print error Right lambekSkel -> do appendToStore (defaultSkelEntry lambekSkel) widgetHide dialog appendToStore lambekSkel = do listStorePrepend skelStore lambekSkel updateSkelIndices typeStore skelStore createFileDialog :: FileChooserAction -> Window -> (String -> IO ()) -> IO () createFileDialog action parent callBack = do let (title,name) = case action of FileChooserActionOpen -> (Just "Open a scheme","Open") FileChooserActionSave -> (Just "Save the scheme","Save") _ -> (Nothing,"Accept") dialog <- fileChooserDialogNew title (Just parent) action [(name,ResponseAccept),("Cancel",ResponseCancel)] fileChooserSetSelectMultiple dialog False widgetShow dialog response <- dialogRun dialog case response of ResponseAccept -> do Just fname <- fileChooserGetFilename dialog callBack fname _ -> return () widgetHide dialog reportError :: Window -> String -> IO () reportError mainWindow msg = do dialog <- messageDialogNew (Just mainWindow) [] MessageError ButtonsOk msg dialogRun dialog widgetHide dialog return () tryLoadSemScheme :: Window -> ListStore SkelEntry -> String -> IO () tryLoadSemScheme mainWindow skelStore fname = do newScheme <- loadSemanticScheme fname case newScheme of Right scheme -> do listStoreClear skelStore Fold.for_ scheme (listStoreAppend skelStore) Left error -> reportError mainWindow error trySaveSemScheme :: Window -> ListStore SkelEntry -> String -> IO () trySaveSemScheme mainWindow skelStore fname = do currentScheme <- listStoreToList skelStore error <- saveSemanticScheme fname currentScheme case error of Just error -> reportError mainWindow error Nothing -> return () createAboutDialog builder = do dialogPath <- getDataFileName "gui/about-dialog.glade" builderAddFromFile builder dialogPath aboutDialog <- builderGetObject builder castToDialog "aboutdialog" widgetShowAll aboutDialog -- This function actually does 2 things: -- Update the list of types matching the selected skeleton -- Update the graphical editor with the corresponding graph updateTypesAndEditor modelTypes modelSkel viewSkel (readGS,setGS) drawWidget = do selection <- treeViewGetSelection viewSkel selected <- treeSelectionGetSelected selection Fold.forM_ selected $ \treeIter -> do -- Update the current types let idx = listStoreIterToIndex treeIter skelEntry <- listStoreGetValue modelSkel idx nbTypes <- listStoreGetSize modelTypes forNTimes nbTypes $ \i -> do entry <- listStoreGetValue modelTypes i let newVis = firstSkelIndex entry == idx listStoreSetValue modelTypes i $ entry { currentlyVisible = newVis } -- Update the graphical editor let newGs = createGraphStateFromEntry skelEntry setGS newGs widgetQueueDraw drawWidget forNTimes n = Fold.for_ [0..(n-1)] updateSkelIndices :: ListStore TypeEntry -> ListStore SkelEntry -> IO () updateSkelIndices modelTypes modelSkel = do nbSkels <- listStoreGetSize modelSkel nbTypes <- listStoreGetSize modelTypes -- for each type forNTimes nbTypes $ \i -> do entry <- listStoreGetValue modelTypes i -- reset its current skeleton listStoreSetValue modelTypes i (entry { firstSkelIndex = -1 }) -- for each skeleton forNTimes nbSkels $ \j -> do skelEntry <- listStoreGetValue modelSkel j let skel = skeleton skelEntry -- for each type forNTimes nbTypes $ \i -> do entry <- listStoreGetValue modelTypes i if firstSkelIndex entry == -1 && lambekType entry `isMatchedBy` skel then listStoreSetValue modelTypes i (entry { firstSkelIndex = j }) else return () deleteCurrentSkel skelStore skelView = do selection <- treeViewGetSelection skelView selected <- treeSelectionGetSelected selection Fold.forM_ selected $ \treeIter -> do listStoreRemove skelStore $ listStoreIterToIndex treeIter visCol :: ColumnId TypeEntry Bool visCol = makeColumnIdBool 0 -- Update the graph state and update the corresponding entry in the skeleton list setGraphState gsM skelStore skelView newGs = do modifyMVar_ gsM (\_ -> return newGs) selection <- treeViewGetSelection skelView selected <- treeSelectionGetSelected selection Fold.forM_ selected $ \treeIter -> do let idx = listStoreIterToIndex treeIter listStoreSetValue skelStore idx (SkelEntry (originalTypeSkeleton newGs) (totalGraph newGs) (presentation newGs)) -- Sets the global state to that of a default semantic scheme. resetSemanticScheme gs typeStore skelStore skelView drawWidget = do listStoreClear skelStore Fold.mapM_ (listStoreAppend skelStore) defaultSemanticScheme selection <- treeViewGetSelection skelView treeSelectionSelectPath selection [0] updateTypesAndEditor typeStore skelStore skelView gs drawWidget main :: IO () main = do glibTypeInit -- State of the interface graphState <- newMVar defaultGraphState -- will be overridden later in updateTypesAndEditor drawState <- newMVar DSelect -- Create stores and lists skelStore <- listStoreNew defaultSemanticScheme typeList <- loadTypeDatabase typeStore <- listStoreNew typeList -- GUI setup initGUI builder <- builderNew interfacePath <- getDataFileName "gui/interface.glade" builderAddFromFile builder interfacePath -- Cursors for the drawing area crossCursor <- cursorNew Crosshair pencilCursor <- cursorNew Pencil let cursors = [crossCursor,pencilCursor] -- Get interesting widgets (main window) window <- builderGetObject builder castToWindow "window1" drawWidget <- builderGetObject builder castToDrawingArea "drawingarea1" [selectButton, nodeButton, edgeButton, delElemButton] <- sequence . (List.map (builderGetObject builder castToToolButton)) $ ["selectbutton", "nodebutton", "edgebutton", "deleteelement"] treeViewTypes <- builderGetObject builder castToTreeView "treeview2" treeViewSkels <- builderGetObject builder castToTreeView "treeview1" addSkelButton <- builderGetObject builder castToButton "buttonaddrule" delSkelButton <- builderGetObject builder castToButton "buttondelrule" [openButton, saveButton, saveAsButton, quitButton, aboutButton, newSchemeButton] <- sequence (List.map (\x -> builderGetObject builder castToImageMenuItem ("imagemenuitem-"++x)) ["open","save","save-as","quit","about", "new"]) -- Graph state manipulation helpers let readGS = readMVar graphState let setGS = setGraphState graphState skelStore treeViewSkels let gs = (readGS,setGS) -- Draw state manipulation helper let changeState = changeDrawingState graphState drawState cursors drawWidget -- Connect signals to callbacks (main window) on window objectDestroy mainQuit widgetAddEvents drawWidget [PointerMotionMask, ButtonPressMask] on drawWidget draw (drawScene drawState graphState) on drawWidget motionNotifyEvent (updateScene drawState gs drawWidget) on drawWidget buttonPressEvent (handleClick drawState gs drawWidget) on drawWidget buttonReleaseEvent (handleRelease drawState gs drawWidget) -- on drawWidget leaveNotify (\_ -> return ()) on treeViewSkels cursorChanged (updateTypesAndEditor typeStore skelStore treeViewSkels gs drawWidget) on skelStore rowsReordered (\ _ _ _ -> updateSkelIndices typeStore skelStore) on skelStore rowInserted (\ _ _ -> updateSkelIndices typeStore skelStore) on skelStore rowDeleted (\ _ -> updateSkelIndices typeStore skelStore) -- Buttons selectButton `onToolButtonClicked` (changeState DSelect) nodeButton `onToolButtonClicked` (changeState DNode) edgeButton `onToolButtonClicked` (changeState DEdge) delElemButton `onToolButtonClicked` (changeState DDelete) on addSkelButton buttonActivated (createAddDialog builder skelStore typeStore) on delSkelButton buttonActivated (deleteCurrentSkel skelStore treeViewSkels) -- Menu items on openButton menuItemActivated (createFileDialog FileChooserActionOpen window (tryLoadSemScheme window skelStore)) on saveButton menuItemActivated (createFileDialog FileChooserActionSave window (trySaveSemScheme window skelStore)) on quitButton menuItemActivated (exitApplication window) on aboutButton menuItemActivated (createAboutDialog builder) on newSchemeButton menuItemActivated (resetSemanticScheme gs typeStore skelStore treeViewSkels drawWidget) -- Load type database colOccur <- Model.treeViewColumnNew Model.treeViewColumnSetTitle colOccur "Num" renderer <- Model.cellRendererTextNew Model.cellLayoutPackStart colOccur renderer False Model.cellLayoutSetAttributes colOccur renderer typeStore $ (\entry -> [Model.cellText := show . nbOccurrences $ entry]) Model.treeViewAppendColumn treeViewTypes colOccur col <- Model.treeViewColumnNew Model.treeViewColumnSetTitle col "Type" renderer <- Model.cellRendererTextNew Model.cellLayoutPackStart col renderer False Model.cellLayoutSetAttributes col renderer typeStore $ (\entry -> [Model.cellText := renderLF . lambekType $ entry]) Model.treeViewAppendColumn treeViewTypes col fModel <- treeModelFilterNew typeStore [] customStoreSetColumn typeStore visCol currentlyVisible treeModelFilterSetVisibleColumn fModel visCol treeViewSetModel treeViewTypes fModel -- Add skeleton list treeViewSetModel treeViewSkels skelStore colSkel <- Model.treeViewColumnNew Model.treeViewColumnSetTitle colSkel "Pattern" Model.cellLayoutPackStart colSkel renderer False Model.cellLayoutSetAttributes colSkel renderer skelStore $ (\tp -> [Model.cellText := renderLS . skeleton $ tp]) Model.treeViewAppendColumn treeViewSkels colSkel -- Synchronize UI with the default semantic scheme resetSemanticScheme gs typeStore skelStore treeViewSkels drawWidget widgetShowAll window mainGUI where exitApplication window = do widgetHide window mainQuit
wetneb/yanker
src/Main.hs
gpl-3.0
12,912
0
19
2,618
3,064
1,458
1,606
-1
-1
{- Clumpiness By Gregory W. Schwartz Contains an easier to use version of the clumpiness function. -} module Clumpiness ( getClumpiness ) where -- Cabal import Data.Tree (Tree) import Math.Clumpiness.Algorithms (generateClumpMap) import Math.Clumpiness.Types (ClumpList) -- Local import TreeTransform import Types getClumpiness :: Exclusivity -- ^ How to look at vertices with multiple labels. -> Bool -- ^ Whether the unique node IDs are predefined (recommended False unless you know what you are doing) -> Bool -- ^ Whether to look at labels in inner vertices. -> Tree NodeLabel -> ClumpList Label getClumpiness exclusivity predefinedIDs excludeInner tree = generateClumpMap (const True) propertyMap superTree where superTree = convertToSuperTree . filterExclusiveTree exclusivity . (\ x -> if excludeInner then x else innerToLeaves x ) . (\ x -> if predefinedIDs then x else addUniqueNodeIDs x ) $ tree propertyMap = getPropertyMap superTree
GregorySchwartz/find-clumpiness
src/Clumpiness.hs
gpl-3.0
1,246
0
13
440
179
101
78
24
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.Analytics.Management.Experiments.Get -- 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 an experiment to which the user has access. -- -- /See:/ <https://developers.google.com/analytics/ Google Analytics API Reference> for @analytics.management.experiments.get@. module Network.Google.Resource.Analytics.Management.Experiments.Get ( -- * REST Resource ManagementExperimentsGetResource -- * Creating a Request , managementExperimentsGet , ManagementExperimentsGet -- * Request Lenses , megWebPropertyId , megProFileId , megAccountId , megExperimentId ) where import Network.Google.Analytics.Types import Network.Google.Prelude -- | A resource alias for @analytics.management.experiments.get@ method which the -- 'ManagementExperimentsGet' request conforms to. type ManagementExperimentsGetResource = "analytics" :> "v3" :> "management" :> "accounts" :> Capture "accountId" Text :> "webproperties" :> Capture "webPropertyId" Text :> "profiles" :> Capture "profileId" Text :> "experiments" :> Capture "experimentId" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Experiment -- | Returns an experiment to which the user has access. -- -- /See:/ 'managementExperimentsGet' smart constructor. data ManagementExperimentsGet = ManagementExperimentsGet' { _megWebPropertyId :: !Text , _megProFileId :: !Text , _megAccountId :: !Text , _megExperimentId :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ManagementExperimentsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'megWebPropertyId' -- -- * 'megProFileId' -- -- * 'megAccountId' -- -- * 'megExperimentId' managementExperimentsGet :: Text -- ^ 'megWebPropertyId' -> Text -- ^ 'megProFileId' -> Text -- ^ 'megAccountId' -> Text -- ^ 'megExperimentId' -> ManagementExperimentsGet managementExperimentsGet pMegWebPropertyId_ pMegProFileId_ pMegAccountId_ pMegExperimentId_ = ManagementExperimentsGet' { _megWebPropertyId = pMegWebPropertyId_ , _megProFileId = pMegProFileId_ , _megAccountId = pMegAccountId_ , _megExperimentId = pMegExperimentId_ } -- | Web property ID to retrieve the experiment for. megWebPropertyId :: Lens' ManagementExperimentsGet Text megWebPropertyId = lens _megWebPropertyId (\ s a -> s{_megWebPropertyId = a}) -- | View (Profile) ID to retrieve the experiment for. megProFileId :: Lens' ManagementExperimentsGet Text megProFileId = lens _megProFileId (\ s a -> s{_megProFileId = a}) -- | Account ID to retrieve the experiment for. megAccountId :: Lens' ManagementExperimentsGet Text megAccountId = lens _megAccountId (\ s a -> s{_megAccountId = a}) -- | Experiment ID to retrieve the experiment for. megExperimentId :: Lens' ManagementExperimentsGet Text megExperimentId = lens _megExperimentId (\ s a -> s{_megExperimentId = a}) instance GoogleRequest ManagementExperimentsGet where type Rs ManagementExperimentsGet = Experiment type Scopes ManagementExperimentsGet = '["https://www.googleapis.com/auth/analytics", "https://www.googleapis.com/auth/analytics.edit", "https://www.googleapis.com/auth/analytics.readonly"] requestClient ManagementExperimentsGet'{..} = go _megAccountId _megWebPropertyId _megProFileId _megExperimentId (Just AltJSON) analyticsService where go = buildClient (Proxy :: Proxy ManagementExperimentsGetResource) mempty
brendanhay/gogol
gogol-analytics/gen/Network/Google/Resource/Analytics/Management/Experiments/Get.hs
mpl-2.0
4,573
0
19
1,058
550
326
224
92
1
import Control.Monad import Control.Concurrent import Control.Concurrent.STM main = do ops <- atomically $ newTVar 0 forM_ [0..49] $ \_ -> do forkIO . forever $ do atomically $ modifyTVar ops (+1) threadDelay 100 threadDelay 1000000 opsFinal <- atomically $ readTVar ops putStrLn $ "ops: " ++ show opsFinal
daewon/til
haskell/haskell_by_example/atomic_counter.hs
mpl-2.0
361
0
16
102
123
58
65
12
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Run.Types.Sum -- 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) -- module Network.Google.Run.Types.Sum where import Network.Google.Prelude hiding (Bytes) -- | The mode of the certificate. data DomainMAppingSpecCertificateMode = CertificateModeUnspecified -- ^ @CERTIFICATE_MODE_UNSPECIFIED@ | None -- ^ @NONE@ -- Do not provision an HTTPS certificate. | Automatic -- ^ @AUTOMATIC@ -- Automatically provisions an HTTPS certificate via GoogleCA or -- LetsEncrypt. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DomainMAppingSpecCertificateMode instance FromHttpApiData DomainMAppingSpecCertificateMode where parseQueryParam = \case "CERTIFICATE_MODE_UNSPECIFIED" -> Right CertificateModeUnspecified "NONE" -> Right None "AUTOMATIC" -> Right Automatic x -> Left ("Unable to parse DomainMAppingSpecCertificateMode from: " <> x) instance ToHttpApiData DomainMAppingSpecCertificateMode where toQueryParam = \case CertificateModeUnspecified -> "CERTIFICATE_MODE_UNSPECIFIED" None -> "NONE" Automatic -> "AUTOMATIC" instance FromJSON DomainMAppingSpecCertificateMode where parseJSON = parseJSONText "DomainMAppingSpecCertificateMode" instance ToJSON DomainMAppingSpecCertificateMode where toJSON = toJSONText -- | Resource record type. Example: \`AAAA\`. data ResourceRecordType = RecordTypeUnspecified -- ^ @RECORD_TYPE_UNSPECIFIED@ -- An unknown resource record. | A -- ^ @A@ -- An A resource record. Data is an IPv4 address. | Aaaa -- ^ @AAAA@ -- An AAAA resource record. Data is an IPv6 address. | Cname -- ^ @CNAME@ -- A CNAME resource record. Data is a domain name to be aliased. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ResourceRecordType instance FromHttpApiData ResourceRecordType where parseQueryParam = \case "RECORD_TYPE_UNSPECIFIED" -> Right RecordTypeUnspecified "A" -> Right A "AAAA" -> Right Aaaa "CNAME" -> Right Cname x -> Left ("Unable to parse ResourceRecordType from: " <> x) instance ToHttpApiData ResourceRecordType where toQueryParam = \case RecordTypeUnspecified -> "RECORD_TYPE_UNSPECIFIED" A -> "A" Aaaa -> "AAAA" Cname -> "CNAME" instance FromJSON ResourceRecordType where parseJSON = parseJSONText "ResourceRecordType" instance ToJSON ResourceRecordType where toJSON = toJSONText -- | The log type that this config enables. data AuditLogConfigLogType = LogTypeUnspecified -- ^ @LOG_TYPE_UNSPECIFIED@ -- Default case. Should never be this. | AdminRead -- ^ @ADMIN_READ@ -- Admin reads. Example: CloudIAM getIamPolicy | DataWrite -- ^ @DATA_WRITE@ -- Data writes. Example: CloudSQL Users create | DataRead -- ^ @DATA_READ@ -- Data reads. Example: CloudSQL Users list deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AuditLogConfigLogType instance FromHttpApiData AuditLogConfigLogType where parseQueryParam = \case "LOG_TYPE_UNSPECIFIED" -> Right LogTypeUnspecified "ADMIN_READ" -> Right AdminRead "DATA_WRITE" -> Right DataWrite "DATA_READ" -> Right DataRead x -> Left ("Unable to parse AuditLogConfigLogType from: " <> x) instance ToHttpApiData AuditLogConfigLogType where toQueryParam = \case LogTypeUnspecified -> "LOG_TYPE_UNSPECIFIED" AdminRead -> "ADMIN_READ" DataWrite -> "DATA_WRITE" DataRead -> "DATA_READ" instance FromJSON AuditLogConfigLogType where parseJSON = parseJSONText "AuditLogConfigLogType" instance ToJSON AuditLogConfigLogType where toJSON = toJSONText -- | V1 error format. data Xgafv = X1 -- ^ @1@ -- v1 error format | X2 -- ^ @2@ -- v2 error format deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable Xgafv instance FromHttpApiData Xgafv where parseQueryParam = \case "1" -> Right X1 "2" -> Right X2 x -> Left ("Unable to parse Xgafv from: " <> x) instance ToHttpApiData Xgafv where toQueryParam = \case X1 -> "1" X2 -> "2" instance FromJSON Xgafv where parseJSON = parseJSONText "Xgafv" instance ToJSON Xgafv where toJSON = toJSONText
brendanhay/gogol
gogol-run/gen/Network/Google/Run/Types/Sum.hs
mpl-2.0
4,914
0
11
1,152
783
424
359
95
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.YouTube.AbuseReports.Insert -- 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) -- -- Inserts a new resource into this collection. -- -- /See:/ <https://developers.google.com/youtube/ YouTube Data API v3 Reference> for @youtube.abuseReports.insert@. module Network.Google.Resource.YouTube.AbuseReports.Insert ( -- * REST Resource AbuseReportsInsertResource -- * Creating a Request , abuseReportsInsert , AbuseReportsInsert -- * Request Lenses , ariXgafv , ariPart , ariUploadProtocol , ariAccessToken , ariUploadType , ariPayload , ariCallback ) where import Network.Google.Prelude import Network.Google.YouTube.Types -- | A resource alias for @youtube.abuseReports.insert@ method which the -- 'AbuseReportsInsert' request conforms to. type AbuseReportsInsertResource = "youtube" :> "v3" :> "abuseReports" :> QueryParams "part" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] AbuseReport :> Post '[JSON] AbuseReport -- | Inserts a new resource into this collection. -- -- /See:/ 'abuseReportsInsert' smart constructor. data AbuseReportsInsert = AbuseReportsInsert' { _ariXgafv :: !(Maybe Xgafv) , _ariPart :: ![Text] , _ariUploadProtocol :: !(Maybe Text) , _ariAccessToken :: !(Maybe Text) , _ariUploadType :: !(Maybe Text) , _ariPayload :: !AbuseReport , _ariCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AbuseReportsInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ariXgafv' -- -- * 'ariPart' -- -- * 'ariUploadProtocol' -- -- * 'ariAccessToken' -- -- * 'ariUploadType' -- -- * 'ariPayload' -- -- * 'ariCallback' abuseReportsInsert :: [Text] -- ^ 'ariPart' -> AbuseReport -- ^ 'ariPayload' -> AbuseReportsInsert abuseReportsInsert pAriPart_ pAriPayload_ = AbuseReportsInsert' { _ariXgafv = Nothing , _ariPart = _Coerce # pAriPart_ , _ariUploadProtocol = Nothing , _ariAccessToken = Nothing , _ariUploadType = Nothing , _ariPayload = pAriPayload_ , _ariCallback = Nothing } -- | V1 error format. ariXgafv :: Lens' AbuseReportsInsert (Maybe Xgafv) ariXgafv = lens _ariXgafv (\ s a -> s{_ariXgafv = a}) -- | The *part* parameter serves two purposes in this operation. It -- identifies the properties that the write operation will set as well as -- the properties that the API response will include. ariPart :: Lens' AbuseReportsInsert [Text] ariPart = lens _ariPart (\ s a -> s{_ariPart = a}) . _Coerce -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ariUploadProtocol :: Lens' AbuseReportsInsert (Maybe Text) ariUploadProtocol = lens _ariUploadProtocol (\ s a -> s{_ariUploadProtocol = a}) -- | OAuth access token. ariAccessToken :: Lens' AbuseReportsInsert (Maybe Text) ariAccessToken = lens _ariAccessToken (\ s a -> s{_ariAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ariUploadType :: Lens' AbuseReportsInsert (Maybe Text) ariUploadType = lens _ariUploadType (\ s a -> s{_ariUploadType = a}) -- | Multipart request metadata. ariPayload :: Lens' AbuseReportsInsert AbuseReport ariPayload = lens _ariPayload (\ s a -> s{_ariPayload = a}) -- | JSONP ariCallback :: Lens' AbuseReportsInsert (Maybe Text) ariCallback = lens _ariCallback (\ s a -> s{_ariCallback = a}) instance GoogleRequest AbuseReportsInsert where type Rs AbuseReportsInsert = AbuseReport type Scopes AbuseReportsInsert = '["https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.force-ssl"] requestClient AbuseReportsInsert'{..} = go _ariPart _ariXgafv _ariUploadProtocol _ariAccessToken _ariUploadType _ariCallback (Just AltJSON) _ariPayload youTubeService where go = buildClient (Proxy :: Proxy AbuseReportsInsertResource) mempty
brendanhay/gogol
gogol-youtube/gen/Network/Google/Resource/YouTube/AbuseReports/Insert.hs
mpl-2.0
5,186
0
18
1,254
804
469
335
116
1
module Adhoc (adhocBotSession, commandList, queryCommandList) where import Prelude () import BasicPrelude hiding (log) import Control.Concurrent (myThreadId, killThread) import Control.Concurrent.STM import Control.Error (hush, ExceptT, runExceptT, throwE, justZ) import Data.XML.Types as XML (Element(..), Node(NodeContent, NodeElement), Content(ContentText), isNamed, elementText, elementChildren, attributeText) import qualified Data.XML.Types as XML import Network.Protocol.XMPP (JID(..), parseJID, formatJID, IQ(..), IQType(..), emptyIQ, Message(..)) import qualified Network.Protocol.XMPP as XMPP import qualified Data.CaseInsensitive as CI import qualified Control.Concurrent.STM.Delay as Delay import qualified Data.Attoparsec.Text as Atto import qualified Data.Bool.HT as HT import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.UUID as UUID ( toString, toText ) import qualified Data.UUID.V1 as UUID ( nextUUID ) import qualified UnexceptionalIO.Trans () import qualified UnexceptionalIO as UIO import StanzaRec import UniquePrefix import Util import qualified ConfigureDirectMessageRoute import qualified DB sessionLifespan :: Int sessionLifespan = 60 * 60 * seconds where seconds = 1000000 addOriginUUID :: (UIO.Unexceptional m) => XMPP.Message -> m XMPP.Message addOriginUUID msg = maybe msg (addTag msg) <$> fromIO_ UUID.nextUUID where addTag msg uuid = msg { messagePayloads = Element (s"{urn:xmpp:sid:0}origin-id") [(s"id", [ContentText $ UUID.toText uuid])] [] : messagePayloads msg } botHelp :: Maybe Text -> IQ -> Maybe Message botHelp header (IQ { iqTo = Just to, iqFrom = Just from, iqPayload = Just payload }) = Just $ mkSMS from to $ maybe mempty (++ s"\n") header ++ (s"Help:\n\t") ++ intercalate (s"\n\t") (map (\item -> fromMaybe mempty (attributeText (s"node") item) ++ s": " ++ fromMaybe mempty (attributeText (s"name") item) ) items) where items = isNamed (s"{http://jabber.org/protocol/disco#items}item") =<< elementChildren payload botHelp _ _ = Nothing commandList :: JID -> Maybe Text -> JID -> JID -> [Element] -> IQ commandList componentJid qid from to extras = (emptyIQ IQResult) { iqTo = Just to, iqFrom = Just from, iqID = qid, iqPayload = Just $ Element (s"{http://jabber.org/protocol/disco#items}query") [(s"{http://jabber.org/protocol/disco#items}node", [ContentText $ s"http://jabber.org/protocol/commands"])] (extraItems ++ [ NodeElement $ Element (s"{http://jabber.org/protocol/disco#items}item") [ (s"jid", [ContentText $ formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName]), (s"node", [ContentText $ ConfigureDirectMessageRoute.nodeName]), (s"name", [ContentText $ s"Register with backend"]) ] [] ]) } where extraItems = map (\el -> NodeElement $ el { elementAttributes = map (\(aname, acontent) -> if aname == s"{http://jabber.org/protocol/disco#items}jid" || aname == s"jid" then (aname, [ContentText $ formatJID componentJid]) else (aname, acontent) ) (elementAttributes el) } ) $ filter (\el -> attributeText (s"node") el /= Just (s"jabber:iq:register") ) extras withNext :: (UIO.Unexceptional m) => m XMPP.Message -> Element -> (ExceptT [Element] m XMPP.Message -> ExceptT [Element] m [Element]) -> m [Element] withNext getMessage field answerField | isRequired field && T.null (mconcat $ fieldValue field) = do either return return =<< runExceptT (answerField $ lift getMessage) | otherwise = either return return =<< runExceptT (answerField suspension) where suspension = do m <- lift getMessage if fmap CI.mk (getBody (s"jabber:component:accept") m) == Just (s"next") then throwE [field] else return m withCancel :: (UIO.Unexceptional m) => Int -> (Text -> m ()) -> m () -> STM XMPP.Message -> m XMPP.Message withCancel sessionLength sendText cancelSession getMessage = do delay <- fromIO_ $ Delay.newDelay sessionLength maybeMsg <- atomicUIO $ (Delay.waitDelay delay *> pure Nothing) <|> Just <$> getMessage case maybeMsg of Just msg | (CI.mk <$> getBody (s"jabber:component:accept") msg) == Just (s"cancel") -> cancel $ s"cancelled" Just msg -> return msg Nothing -> cancel $ s"expired" where cancel t = do sendText t cancelSession fromIO_ $ myThreadId >>= killThread return $ error "Unreachable" queryCommandList :: JID -> JID -> IO [StanzaRec] queryCommandList to from = do uuid <- (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID return [mkStanzaRec $ (queryCommandList' to from) {iqID = uuid}] untilParse :: (UIO.Unexceptional m) => m Message -> m () -> (Text -> Maybe b) -> m b untilParse getText onFail parser = do text <- (fromMaybe mempty . getBody "jabber:component:accept") <$> getText maybe parseFail return $ parser text where parseFail = do onFail untilParse getText onFail parser formatLabel :: (Text -> Maybe Text) -> Element -> Text formatLabel valueFormatter field = lbl ++ value ++ descSuffix where lbl = maybe (fromMaybe mempty $ attributeText (s"var") field) T.toTitle $ label field value = maybe mempty (\v -> s" [Current value " ++ v ++ s"]") $ valueFormatter <=< mfilter (not . T.null) $ Just $ intercalate (s", ") (fieldValue field) descSuffix = maybe mempty (\dsc -> s"\n(" ++ dsc ++ s")") $ desc field adhocBotAnswerFixed :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m [Element] adhocBotAnswerFixed sendText _getMessage field = do let values = fmap (mconcat . elementText) $ isNamed (s"{jabber:x:data}value") =<< elementChildren field sendText $ formatLabel (const Nothing) field sendText $ unlines values return [] adhocBotAnswerBoolean :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m [Element] adhocBotAnswerBoolean sendText getMessage field = do case attributeText (s"var") field of Just var -> do sendText $ formatLabel (fmap formatBool . hush . Atto.parseOnly parser) field ++ s"\nYes or No?" value <- untilParse getMessage (sendText helperText) $ hush . Atto.parseOnly parser return [Element (s"{jabber:x:data}field") [(s"var", [ContentText var])] [ NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ ContentText $ HT.if' value (s"true") (s"false")] ]] _ -> log "ADHOC BOT FIELD WITHOUT VAR" field >> return [] where helperText = s"I didn't understand your answer. Please send yes or no" parser = Atto.skipMany Atto.space *> ( (True <$ Atto.choice (Atto.asciiCI <$> [s"true", s"t", s"1", s"yes", s"y", s"enable", s"enabled"])) <|> (False <$ Atto.choice (Atto.asciiCI <$> [s"false", s"f", s"0", s"no", s"n", s"disable", s"disabled"])) ) <* Atto.skipMany Atto.space <* Atto.endOfInput formatBool True = s"Yes" formatBool False = s"No" adhocBotAnswerTextSingle :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m [Element] adhocBotAnswerTextSingle sendText getMessage field = do case attributeText (s"var") field of Just var -> do sendText $ s"Enter " ++ formatLabel Just field value <- getMessage case getBody "jabber:component:accept" value of Just body -> return [Element (s"{jabber:x:data}field") [(s"var", [ContentText var])] [ NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ ContentText body] ]] Nothing -> return [] _ -> log "ADHOC BOT FIELD WITHOUT VAR" field >> return [] listOptionText :: (Foldable t) => t Text -> Text -> (Int, Element) -> Text listOptionText currentValues currentValueText (n, v) = tshow n ++ s". " ++ optionText v ++ selectedText v where selectedText option | mconcat (fieldValue option) `elem` currentValues = currentValueText | otherwise = mempty adhocBotAnswerJidSingle :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m [Element] adhocBotAnswerJidSingle sendText getMessage field = do case attributeText (s"var") field of Just var -> do sendText $ s"Enter " ++ formatLabel Just field value <- untilParse getMessage (sendText helperText) XMPP.parseJID return [Element (s"{jabber:x:data}field") [(s"var", [ContentText var])] [ NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ ContentText $ formatJID value] ]] _ -> log "ADHOC BOT FIELD WITHOUT VAR" field >> return [] where helperText = s"I didn't understand your answer. Please send only a valid JID like person@example.com or perhaps just example.com" adhocBotAnswerListMulti :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m [Element] adhocBotAnswerListMulti sendText getMessage field = do case attributeText (s"var") field of Just var -> do let options = zip [1..] $ isNamed(s"{jabber:x:data}option") =<< elementChildren field let currentValues = fieldValue field let optionsText = fmap (listOptionText currentValues (s" [Currently Selected]")) options sendText $ unlines $ [formatLabel (const Nothing) field] ++ optionsText ++ [s"Which numbers?"] values <- untilParse getMessage (sendText helperText) (hush . Atto.parseOnly parser) let selectedOptions = fmap snd $ filter (\(x, _) -> x `elem` values) options return [Element (s"{jabber:x:data}field") [(s"var", [ContentText var])] $ flip fmap selectedOptions $ \option -> NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ ContentText $ mconcat $ fieldValue option] ] _ -> log "ADHOC BOT FIELD WITHOUT VAR" field >> return [] where parser = Atto.skipMany Atto.space *> Atto.sepBy Atto.decimal (Atto.skipMany $ Atto.choice [Atto.space, Atto.char ',']) <* Atto.skipMany Atto.space <* Atto.endOfInput helperText = s"I didn't understand your answer. Please send the numbers you want, separated by commas or spaces like \"1, 3\" or \"1 3\". Blank (or just spaces) to pick nothing." adhocBotAnswerListSingle :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m [Element] adhocBotAnswerListSingle sendText getMessage field = do case attributeText (s"var") field of Just var -> do let open = isOpenValidation (fieldValidation field) let options = zip [1..] $ isNamed(s"{jabber:x:data}option") =<< elementChildren field let currentValue = listToMaybe $ elementText =<< isNamed(s"{jabber:x:data}value") =<< elementChildren field let optionsText = fmap (listOptionText currentValue (s" [Current Value]")) options let currentValueText = fromMaybe (s"") $ currentValue >>= \value -> if open && value `notElem` (map (mconcat . fieldValue . snd) options) then Just $ s"[Current Value: " ++ value ++ s"]\n" else Nothing let prompt = s"Please enter a number from the list above" ++ if open then s", or enter a custom option" else s"" sendText $ unlines $ [formatLabel (const Nothing) field] ++ optionsText ++ [currentValueText ++ prompt] maybeOption <- if open then do value <- untilParse getMessage (sendText helperText) (hush . Atto.parseOnly openParser) return $ case value of Left openValue -> Just [openValue] Right itemNumber -> fmap (fieldValue . snd) $ find (\(x, _) -> x == itemNumber) options else do value <- untilParse getMessage (sendText helperText) (hush . Atto.parseOnly parser) return $ fmap (fieldValue . snd) $ find (\(x, _) -> x == value) options case maybeOption of Just option -> return [Element (s"{jabber:x:data}field") [(s"var", [ContentText var])] [ NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ ContentText $ mconcat option] ]] Nothing -> do sendText $ s"Please pick one of the given options" adhocBotAnswerListSingle sendText getMessage field _ -> log "ADHOC BOT FIELD WITHOUT VAR" field >> return [] where helperText = s"I didn't understand your answer. Please just send the number of the one item you want to pick, like \"1\"" parser = Atto.skipMany Atto.space *> Atto.decimal <* Atto.skipMany Atto.space openParser = (Right <$> parser) <|> (Left <$> Atto.takeText) adhocBotAnswerForm :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m Element adhocBotAnswerForm sendText getMessage form = do fields <- forM (filter (uncurry (||) . (isField &&& isInstructions)) $ elementChildren form) $ \field -> let sendText' = lift . sendText in withNext getMessage field $ \getMessage' -> HT.select ( -- The spec says a field type we don't understand should be treated as text-single log "ADHOC BOT UNKNOWN FIELD" field >> adhocBotAnswerTextSingle sendText' getMessage' field ) [ (isInstructions field, sendText' (mconcat $ elementText field) >> return []), (attributeText (s"type") field == Just (s"list-single"), adhocBotAnswerListSingle sendText' getMessage' field), (attributeText (s"type") field == Just (s"list-multi"), adhocBotAnswerListMulti sendText' getMessage' field), (attributeText (s"type") field == Just (s"jid-single"), adhocBotAnswerJidSingle sendText' getMessage' field), (attributeText (s"type") field == Just (s"hidden"), return [field]), (attributeText (s"type") field == Just (s"fixed"), adhocBotAnswerFixed sendText' getMessage' field), (attributeText (s"type") field == Just (s"boolean"), adhocBotAnswerBoolean sendText' getMessage' field), (attributeText (s"type") field `elem` [Just (s"text-single"), Nothing], -- The default if a type isn't specified is text-single adhocBotAnswerTextSingle sendText' getMessage' field) ] return $ Element (s"{jabber:x:data}x") [(s"type", [ContentText $ s"submit"])] $ NodeElement <$> mconcat fields formatReported :: Element -> (Text, [Text]) formatReported = first (intercalate (s"\t")) . unzip . map (\field -> ( formatLabel (const Nothing) field, fromMaybe mempty (attributeText (s"var") field) ) ) . filter isField . elementChildren formatItem :: [Text] -> Element -> Text formatItem reportedVars item = intercalate (s"\t") $ map (\var -> intercalate (s", ") $ findFieldValue var ) reportedVars where findFieldValue var = maybe [] fieldValue $ find (\field -> attributeText (s"var") field == Just var ) fields fields = filter isField $ elementChildren item renderResultForm :: Element -> Text renderResultForm form = intercalate (s"\n") $ catMaybes $ snd $ forAccumL [] (elementChildren form) $ \reportedVars el -> HT.select (reportedVars, Nothing) $ map (second $ second Just) [ (isInstructions el, (reportedVars, mconcat $ elementText el)), (isField el && attributeText (s"type") el == Just (s"hidden"), (reportedVars, mempty)), (isField el, (reportedVars, formatLabel (const Nothing) el ++ s": " ++ unlines (fieldValue el))), (isReported el, swap $ formatReported el), (isItem el, (reportedVars, formatItem reportedVars el)) ] where forAccumL z xs f = mapAccumL f z xs data Action = ActionNext | ActionPrev | ActionCancel | ActionComplete actionContent :: Action -> Content actionContent ActionNext = ContentText $ s"next" actionContent ActionPrev = ContentText $ s"prev" actionContent ActionCancel = ContentText $ s"cancel" actionContent ActionComplete = ContentText $ s"complete" actionCmd :: Action -> Text actionCmd ActionNext = s"next" actionCmd ActionPrev = s"back" actionCmd ActionCancel = s"cancel" actionCmd ActionComplete = s"finish" actionFromXMPP :: Text -> Maybe Action actionFromXMPP xmpp | xmpp == s"next" = Just ActionNext | xmpp == s"prev" = Just ActionPrev | xmpp == s"complete" = Just ActionComplete | otherwise = Nothing waitForAction :: (UIO.Unexceptional m) => [Action] -> (Text -> m ()) -> m XMPP.Message -> m Action waitForAction actions sendText getMessage = do m <- getMessage let ciBody = CI.mk <$> getBody (s"jabber:component:accept") m HT.select whatWasThat [ (ciBody == Just (s"next"), return ActionNext), (ciBody == Just (s"back"), return ActionPrev), (ciBody == Just (s"cancel"), return ActionCancel), (ciBody == Just (s"finish"), return ActionComplete) ] where allowedCmds = map actionCmd (ActionCancel : actions) whatWasThat = do sendText $ s"I didn't understand that. You can say one of: " ++ intercalate (s", ") allowedCmds waitForAction actions sendText getMessage label :: Element -> Maybe Text label = attributeText (s"label") optionText :: Element -> Text optionText element = fromMaybe (mconcat $ fieldValue element) (label element) fieldValue :: Element -> [Text] fieldValue = fmap (mconcat . elementText) . isNamed (s"{jabber:x:data}value") <=< elementChildren fieldValidation :: Element -> Maybe Element fieldValidation = listToMaybe . (isNamed (s"{http://jabber.org/protocol/xdata-validate}validate") <=< elementChildren) isOpenValidation :: Maybe Element -> Bool isOpenValidation (Just el) = not $ null $ isNamed (s"{http://jabber.org/protocol/xdata-validate}open") =<< elementChildren el isOpenValidation _ = False desc :: Element -> Maybe Text desc = mfilter (not . T.null) . Just . mconcat . (elementText <=< isNamed(s"{jabber:x:data}desc") <=< elementChildren) isField :: Element -> Bool isField el = elementName el == s"{jabber:x:data}field" isInstructions :: Element -> Bool isInstructions el = elementName el == s"{jabber:x:data}instructions" isReported :: Element -> Bool isReported el = elementName el == s"{jabber:x:data}reported" isItem :: Element -> Bool isItem el = elementName el == s"{jabber:x:data}item" isRequired :: Element -> Bool isRequired = not . null . (isNamed (s"{jabber:x:data}required") <=< elementChildren) registerShorthand :: Text -> Maybe JID registerShorthand body = do gatewayJID <- hush $ Atto.parseOnly (Atto.asciiCI (s"register") *> Atto.many1 Atto.space *> Atto.takeText) body parseJID gatewayJID getServerInfoForm :: [XML.Element] -> Maybe XML.Element getServerInfoForm = find (\el -> attributeText (s"type") el == Just (s"result") && getFormField el (s"FORM_TYPE") == Just (s"http://jabber.org/network/serverinfo") ) . (isNamed (s"{jabber:x:data}x") =<<) sendHelp :: (UIO.Unexceptional m) => DB.DB -> JID -> (XMPP.Message -> m ()) -> (XMPP.IQ -> UIO.UIO (STM (Maybe XMPP.IQ))) -> JID -> JID -> m () sendHelp db componentJid sendMessage sendIQ from routeFrom = do maybeRoute <- (parseJID =<<) . (join . hush) <$> UIO.fromIO (DB.get db (DB.byJid from ["direct-message-route"])) case maybeRoute of Just route -> do replySTM <- UIO.lift $ sendIQ $ queryCommandList' route routeFrom discoInfoSTM <- UIO.lift $ sendIQ $ queryDiscoWithNode' Nothing route routeFrom (mreply, mDiscoInfo) <- atomicUIO $ (,) <$> replySTM <*> discoInfoSTM let helpMessage = botHelp (renderResultForm <$> (getServerInfoForm . elementChildren =<< iqPayload =<< mDiscoInfo)) $ commandList componentJid Nothing componentJid from $ isNamed (s"{http://jabber.org/protocol/disco#items}item") =<< elementChildren =<< maybeToList (XMPP.iqPayload =<< mfilter ((== XMPP.IQResult) . XMPP.iqType) mreply) case helpMessage of Just msg -> sendMessage msg Nothing -> log "INVALID HELP MESSAGE" mreply Nothing -> case botHelp Nothing $ commandList componentJid Nothing componentJid from [] of Just msg -> sendMessage msg Nothing -> log "INVALID HELP MESSAGE" () adhocBotRunCommand :: (UIO.Unexceptional m) => DB.DB -> JID -> JID -> (XMPP.Message -> m ()) -> (XMPP.IQ -> UIO.UIO (STM (Maybe XMPP.IQ))) -> STM XMPP.Message -> JID -> Text -> [Element] -> m () adhocBotRunCommand db componentJid routeFrom sendMessage sendIQ getMessage from body cmdEls = do let (nodes, cmds) = unzip $ mapMaybe (\el -> (,) <$> attributeText (s"node") el <*> pure el) cmdEls case (snd <$> find (\(prefixes, _) -> Set.member (CI.mk body) prefixes) (zip (uniquePrefix nodes) cmds), registerShorthand body) of (_, Just gatewayJID) -> do mResult <- (atomicUIO =<<) $ UIO.lift $ sendIQ $ (emptyIQ IQSet) { iqFrom = Just routeFrom, iqTo = Just componentJid, iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [(s"node", [ContentText ConfigureDirectMessageRoute.nodeName])] [] } case attributeText (s"sessionid") =<< iqPayload =<< mResult of Just sessionid -> startWithIntro $ (emptyIQ IQSet) { iqFrom = Just routeFrom, iqTo = iqFrom =<< mResult, iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [(s"node", [ContentText ConfigureDirectMessageRoute.nodeName]), (s"sessionid", [ContentText sessionid]), (s"action", [ContentText $ s"next"])] [ NodeElement $ Element (fromString "{jabber:x:data}x") [ (fromString "{jabber:x:data}type", [ContentText $ s"submit"]) ] [ NodeElement $ Element (fromString "{jabber:x:data}field") [ (fromString "{jabber:x:data}type", [ContentText $ s"jid-single"]), (fromString "{jabber:x:data}var", [ContentText $ s"gateway-jid"]) ] [ NodeElement $ Element (fromString "{jabber:x:data}value") [] [NodeContent $ ContentText $ formatJID gatewayJID] ] ] ] } Nothing -> sendHelp db componentJid sendMessage sendIQ from routeFrom (Just cmd, Nothing) -> startWithIntro $ (emptyIQ IQSet) { iqFrom = Just routeFrom, iqTo = parseJID =<< attributeText (s"jid") cmd, iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [(s"node", [ContentText $ fromMaybe mempty $ attributeText (s"node") cmd])] [] } (Nothing, Nothing) -> sendHelp db componentJid sendMessage sendIQ from routeFrom where startWithIntro cmdIQ = sendAndRespondTo (Just $ intercalate (s"\n") [ s"You can leave something at the current value by saying 'next'.", s"You can return to the main menu by saying 'cancel' at any time." ]) cmdIQ threadedMessage Nothing msg = msg threadedMessage (Just sessionid) msg = msg { messagePayloads = (Element (s"thread") [] [NodeContent $ ContentText sessionid]) : messagePayloads msg } sendAndRespondTo intro cmdIQ = do mcmdResult <- atomicUIO =<< UIO.lift (sendIQ cmdIQ) case mcmdResult of Just resultIQ | IQResult == iqType resultIQ, Just payload <- iqPayload resultIQ, [form] <- isNamed (s"{jabber:x:data}x") =<< elementChildren payload, attributeText (s"type") form == Just (s"result") -> do let sendText = sendMessage . threadedMessage (attributeText (s"sessionid") payload) . mkSMS componentJid from sendText $ renderResultForm form | IQResult == iqType resultIQ, Just payload <- iqPayload resultIQ, Just sessionid <- attributeText (s"sessionid") payload, Just cmd <- attributeText (s"node") payload, [form] <- isNamed (s"{jabber:x:data}x") =<< elementChildren payload -> do let cancelIQ = (emptyIQ IQSet) { iqFrom = Just routeFrom, iqTo = iqFrom resultIQ, iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [(s"node", [ContentText cmd]), (s"sessionid", [ContentText sessionid]), (s"action", [ContentText $ s"cancel"])] [] } let cancel = void . atomicUIO =<< UIO.lift (sendIQ cancelIQ) let sendText = sendMessage . threadedMessage (Just sessionid) . mkSMS componentJid from let cancelText = sendText . ((cmd ++ s" ") ++) forM_ intro sendText returnForm <- adhocBotAnswerForm sendText (withCancel sessionLifespan cancelText cancel getMessage) form let actions = listToMaybe $ isNamed(s"{http://jabber.org/protocol/commands}actions") =<< elementChildren payload -- The standard says if actions is present, with no "execute" attribute, that the default is "next" -- But if there is no actions, the default is "execute" let defaultAction = maybe (s"execute") (fromMaybe (s"next") . attributeText (s"execute")) actions let cmdIQ' = (emptyIQ IQSet) { iqFrom = Just routeFrom, iqTo = iqFrom resultIQ, iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [(s"node", [ContentText $ fromMaybe mempty $ attributeText (s"node") payload]), (s"sessionid", [ContentText sessionid]), (s"action", [ContentText defaultAction])] [NodeElement returnForm] } sendAndRespondTo Nothing cmdIQ' | IQResult == iqType resultIQ, Just payload <- iqPayload resultIQ, notes@(_:_) <- isNamed (s"{http://jabber.org/protocol/commands}note") =<< elementChildren payload -> do let sendText = sendMessage . threadedMessage (attributeText (s"sessionid") payload) . mkSMS componentJid from forM_ notes $ sendText . mconcat . elementText if (attributeText (s"status") payload == Just (s"executing")) then do let actions = mapMaybe (actionFromXMPP . XML.nameLocalName . elementName) $ elementChildren =<< isNamed (s"{http://jabber.org/protocol/commands}actions") =<< elementChildren payload let sessionid = maybe [] (\sessid -> [(s"sessionid", [ContentText sessid])]) $ attributeText (s"sessionid") payload sendText $ s"You can say one of: " ++ (intercalate (s", ") $ map actionCmd (ActionCancel : actions)) action <- waitForAction actions sendText (atomicUIO getMessage) let cmdIQ' = (emptyIQ IQSet) { iqFrom = Just routeFrom, iqTo = iqFrom resultIQ, iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") ([(s"node", [ContentText $ fromMaybe mempty $ attributeText (s"node") payload]), (s"action", [actionContent action])] ++ sessionid) [] } sendAndRespondTo Nothing cmdIQ' else when ( attributeText (s"status") payload == Just (s"completed") && attributeText (s"node") payload == Just ConfigureDirectMessageRoute.nodeName && all (\n -> attributeText (s"type") n /= Just (s"error")) notes ) $ sendHelp db componentJid sendMessage sendIQ from routeFrom | IQResult == iqType resultIQ, [cmd] <- isNamed (s"{http://jabber.org/protocol/commands}command") =<< (justZ $ iqPayload resultIQ), attributeText (s"status") cmd `elem` [Just (s"completed"), Just (s"canceled")] -> return () | otherwise -> sendMessage $ mkSMS componentJid from (s"Command error") Nothing -> sendMessage $ mkSMS componentJid from (s"Command timed out") adhocBotSession :: (UIO.Unexceptional m) => DB.DB -> JID -> (XMPP.Message -> m ()) -> (XMPP.IQ -> UIO.UIO (STM (Maybe XMPP.IQ))) -> STM XMPP.Message -> XMPP.Message-> m () adhocBotSession db componentJid sendMessage sendIQ getMessage message@(XMPP.Message { XMPP.messageFrom = Just from }) | Just body <- getBody "jabber:component:accept" message = do maybeRoute <- (parseJID =<<) . (join . hush) <$> UIO.fromIO (DB.get db (DB.byJid from ["direct-message-route"])) case maybeRoute of Just route -> do mreply <- atomicUIO =<< (UIO.lift . sendIQ) (queryCommandList' route routeFrom) case iqPayload =<< mfilter ((==IQResult) . iqType) mreply of Just reply -> adhocBotRunCommand db componentJid routeFrom sendMessage' sendIQ getMessage from body $ elementChildren reply ++ internalCommands Nothing -> adhocBotRunCommand db componentJid routeFrom sendMessage' sendIQ getMessage from body internalCommands Nothing -> adhocBotRunCommand db componentJid routeFrom sendMessage' sendIQ getMessage from body internalCommands | otherwise = sendHelp db componentJid sendMessage' sendIQ from routeFrom where internalCommands = elementChildren =<< maybeToList (iqPayload $ commandList componentJid Nothing componentJid from []) Just routeFrom = parseJID $ escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid ++ s"/adhocbot" sendMessage' = sendMessage <=< addOriginUUID adhocBotSession _ _ _ _ _ m = log "BAD ADHOC BOT MESSAGE" m
singpolyma/cheogram
Adhoc.hs
agpl-3.0
27,565
443
32
4,883
9,845
5,005
4,840
-1
-1
module RayCaster.Render where import Data.Maybe (Maybe, mapMaybe) import RayCaster.Color (Color (..), colorAdd, colorMult) import RayCaster.DataTypes (Config (..), Light (..), Material (..), Object (..), Scene (..)) import RayCaster.Intersection (Intersection (..)) import RayCaster.Ray (Ray (..)) import qualified RayCaster.Ray as Ray import RayCaster.Shapes (Shape) import qualified RayCaster.Shapes as Shapes import RayCaster.Vector (Vector) import qualified RayCaster.Vector as Vector getCoordColor :: Scene -> Int -> Int -> Color getCoordColor scene@(Scene _ _ camera config) x y = let ray = Ray.generate camera (sceneWidth config) (sceneHeight config) x y in traceRay scene ray traceRay :: Scene -> Ray -> Color traceRay scene ray = traceRayReflect scene ray 0 traceRayReflect :: Scene -> Ray -> Int -> Color traceRayReflect scene@(Scene objects _ _ config) ray reflections = let bgColor = defaultColor config intersectedObject = closestObject ray objects in maybe bgColor (getIntersectionColor ray scene reflections) intersectedObject closestObject :: Ray -> [Object] -> Maybe Intersection closestObject ray objects = let intersections = mapMaybe (objectIntersection ray) objects in if null intersections then Nothing else Just $ minimum intersections objectIntersection :: Ray -> Object -> Maybe Intersection objectIntersection ray obj@(Object s _) = Intersection obj <$> Shapes.rayIntersection ray s getIntersectionColor :: Ray -> Scene -> Int -> Intersection -> Color getIntersectionColor ray scene@(Scene objects lights _ _) reflections (Intersection hitObject hitDistance) = let hitPoint = Ray.pointAlongRay ray hitDistance otherObjects = filter (/= hitObject) objects visibleLights = filter (isLightVisible otherObjects hitPoint) lights lambertVal = lambertColor hitPoint hitObject visibleLights reflectionLight = reflectionColor scene ray hitPoint hitObject reflections in lambertVal `colorAdd` (0.2 `colorMult` reflectionLight) reflectionColor :: Scene -> Ray -> Vector -> Object -> Int -> Color reflectionColor scene (Ray origin direction) hitPoint (Object shape _) reflections = let maxReflections = 2 reflectionDirection = Vector.reflect (Shapes.normalAtPoint hitPoint shape) direction reflectionRay = Ray hitPoint reflectionDirection in if reflections == maxReflections then Color 0 0 0 else traceRayReflect scene reflectionRay (reflections + 1) isLightVisible :: [Object] -> Vector -> Light -> Bool isLightVisible objects point light = let toLightVector = center light `Vector.sub` point distanceToLight = Vector.magnitude toLightVector direction = Vector.normalize toLightVector ray = Ray point direction shapes = map (\(Object shape _) -> shape) objects objIntersections = mapMaybe (Shapes.rayIntersection ray) shapes in all (>= distanceToLight) objIntersections -- Should also include light color lambertColor :: Vector -> Object -> [Light] -> Color lambertColor hitPoint (Object shape (Material color)) lights = let normal = Shapes.normalAtPoint hitPoint shape lightIlluminations = fmap (lambertIllumination hitPoint normal) lights totalIllumination = sum lightIlluminations in totalIllumination `colorMult` color lambertIllumination :: Vector -> Vector -> Light -> Double lambertIllumination hitPoint normal light = let lv = lambertValue hitPoint normal light illumination = lv * intensity light -- When lights have colors, they'll be multiplied here in illumination lambertValue :: Vector -> Vector -> Light -> Double lambertValue point normal light = let lightDirection = Vector.normalize $ center light `Vector.sub` point in max 0 (normal `Vector.dot` lightDirection)
bkach/HaskellRaycaster
src/RayCaster/Render.hs
apache-2.0
3,973
0
13
849
1,124
595
529
76
2
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>GraalVM JavaScript</title> <maps> <homeID>graaljs</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
secdec/zap-extensions
addOns/graaljs/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs
apache-2.0
967
77
66
156
407
206
201
-1
-1
{-# LANGUAGE OverloadedStrings, TupleSections #-} module Podcast ( module Podcast.Types , downloadEpisode , fetchPodcast , newPodcast ) where import Control.Error (note, partitionEithers) import Control.Monad (unless) import Data.Bifunctor (first) import qualified Data.ByteString as B import Data.Char (isAlphaNum, isSpace) import Data.Semigroup ((<>)) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8', encodeUtf8) import Data.Time.Calendar (fromGregorian) import Data.Time.Clock (UTCTime(..), getCurrentTime) import Data.Time.Format (defaultTimeLocale, formatTime, iso8601DateFormat) import qualified Data.Map.Strict as M import Data.Maybe (isJust) import Network.Http.Client import System.Directory (createDirectoryIfMissing) import System.FilePath (FilePath, (</>)) import qualified System.IO.Streams as Streams import Logging import Podcast.Rss import Podcast.Types -- | This function just cleans up a string so it passes as a slug. textToSlug :: Text -> Text textToSlug = T.toLower . T.foldr (\c a -> if T.null a then T.singleton c else let lc = T.last a in if lc == '-' && lc == c then a else T.cons c a) "" . T.map (\c -> if isSpace c then '-' else c) . T.filter (\c -> isAlphaNum c || isSpace c) . T.strip -- | Create a new podcast newPodcast :: Text -> Podcast newPodcast url = Podcast "" url M.empty (UTCTime (fromGregorian 1970 1 1) 0) -- epoch -- | Download a podcast RSS/Atom file from the internet. fetchPodcast :: (IsString msg, ToLogStr msg) => SugarLogger msg -> Podcast -> IO (Either String Podcast) fetchPodcast logger p = get (encodeUtf8 $ pcUrl p) $ \r i -> do case getStatusCode r of 200 -> do (pct, es) <- parseRss . B.concat <$> Streams.toList i let (ls, rs) = partitionEithers es unless (null ls) $ do logger "These episodes returned errors:" mapM_ (logger . fromString . show) ls let pct' = note "Got no podcast title from parseRss" pct >>= (first show . decodeUtf8') now <- getCurrentTime return $ either Left (\t -> Right $ p { pcTitle = t, episodes = foldr (\e m -> M.insertWith (\_ old -> old) (epUrl e) e m) (episodes p) rs, lastChecked = now }) pct' s -> return $ Left $ show s -- | Download an episode downloadEpisode :: FilePath -> Podcast -> Episode -> IO (Either String Episode) downloadEpisode basePath p e | isJust $ downloaded e = return $ Left "Episode already downloaded." | otherwise = get (encodeUtf8 $ epUrl e) $ \r i -> do case getStatusCode r of 200 -> do let [prefix, suffix] = (T.splitOn "." . T.takeWhileEnd (/='/') . epUrl) e let filename = formatTime defaultTimeLocale (iso8601DateFormat Nothing) (pubDate e) <> "-" <> T.unpack (textToSlug (epTitle e) <> "-" <> textToSlug prefix <> "." <> suffix) let relativeEpisodePath = ((T.unpack . textToSlug . pcTitle) p) createDirectoryIfMissing True (basePath </> relativeEpisodePath) Streams.withFileAsOutput (basePath </> relativeEpisodePath </> filename) (\o -> Streams.connect i o) now <- getCurrentTime return $ Right $ e { localFilename = Just $ T.pack (relativeEpisodePath </> filename), downloaded = Just now } s -> return $ Left $ "Got weird statuscode: " <> (show s)
Rembane/hpod
src/Podcast.hs
apache-2.0
3,398
0
27
769
1,155
611
544
62
4
-- Copyright 2020-2021 Google LLC -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. module WordErrors where import Data.Word (Word8, Word16, Word) -- Want -Woverflowed-literals warnings for all of these. x1, x2, x3 :: Word8 x1 = -1 x2 = -256 x3 = 256 x4, x5, x6 :: Word16 x4 = -1 x5 = -65536 x6 = 65536 x7, x8, x9 :: Word x7 = -1 x8 = -18446744073709551616 x9 = 18446744073709551616
google/hs-dependent-literals
dependent-literals-plugin/tests/WordErrors.hs
apache-2.0
898
0
5
164
118
81
37
14
1
module Main (main) where import Control.Arrow import Network.HTTP.Client.TLS (newTlsManager) import Control.Exception (try, SomeException) import Control.Monad import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Except import Data.Either import Data.List import qualified Distribution.Hackage.DB as DB import Distribution.Text import Distribution.Types.Version import Network.Socket (withSocketsDo) import Paths_codex (version) import System.Console.AsciiProgress (displayConsoleRegions) import System.Directory import System.Environment import System.Exit import System.FilePath import System.Process (shell, readCreateProcessWithExitCode) import Codex import Codex.Project import Codex.Internal (Builder(..), hackagePathOf, readStackPath) import Main.Config -- TODO Add 'cache dump' to dump all tags in stdout (usecase: pipe to grep) -- TODO Use a mergesort algorithm for `assembly` -- TODO Better error handling and fine grained retry retrying :: Int -> IO (Either a b) -> IO (Either [a] b) retrying n x = retrying' n $ fmap (left (:[])) x where retrying' 0 x' = x' retrying' n' x' = retrying' (n' - 1) $ x' >>= \res -> case res of Left ls -> fmap (left (++ ls)) x' Right r -> return $ Right r hashFile :: Codex -> FilePath hashFile cx = hackagePath cx </> "codex.hash" cleanCache :: (Builder, Codex) -> IO () cleanCache (bldr, cx) = do -- TODO Delete hash file! xs <- listDirectory hp ys <- builderOp bldr =<< traverseDirectories xs _ <- removeTagFiles $ concat ys return () where hp = hackagePath cx safe = (try :: IO a -> IO (Either SomeException a)) removeTagFiles = traverse (safe . removeFile) . fmap (</> "tags") traverseDirectories = fmap rights . traverse (safe . listDirectory) builderOp (Stack _) = traverseDirectories . concat builderOp Cabal = return readCacheHash :: Codex -> IO (Maybe String) readCacheHash cx = do fileExist <- doesFileExist $ hashFile cx if not fileExist then return Nothing else do content <- readFile $ hashFile cx return $ Just content writeCacheHash :: Codex -> String -> IO () writeCacheHash cx = writeFile $ hashFile cx update :: Bool -> Codex -> Builder -> IO () update force cx bldr = displayConsoleRegions $ do (mpid, dependencies, workspaceProjects') <- case bldr of Cabal -> do tb <- DB.hackageTarball resolveCurrentProjectDependencies bldr tb Stack _ -> resolveCurrentProjectDependencies bldr $ hackagePath cx projectHash <- computeCurrentProjectHash cx shouldUpdate <- if null workspaceProjects' then either (const True) id <$> (runExceptT $ isUpdateRequired cx dependencies projectHash) else return True if force || shouldUpdate then do let workspaceProjects = if currentProjectIncluded cx then workspaceProjects' else filter (("." /=) . workspaceProjectPath) workspaceProjects' fileExist <- doesFileExist tagsFile when fileExist $ removeFile tagsFile putStrLn ("Updating: " ++ displayPackages mpid workspaceProjects) s <- newTlsManager tick' <- newProgressBar' "Loading tags" (length dependencies) results <- traverse (retrying 3 . runExceptT . getTags tick' s) dependencies _ <- traverse print . concat $ lefts results res <- runExceptT $ assembly bldr cx dependencies projectHash workspaceProjects tagsFile case res of Left e -> do print e exitFailure Right _ -> pure () else putStrLn "Nothing to update." where tagsFile = tagsFileName cx hp = hackagePathOf bldr cx getTags tick' s i = status hp i >>= \x -> case x of Source Tagged -> tick' >> return () Source Untagged -> tags bldr cx i >> tick' >> getTags tick' s i Archive -> extract hp i >> tick' >> getTags tick' s i Remote -> liftIO $ either ignore return <=< runExceptT $ fetch s hp i >> tick' >> getTags tick' s i where ignore msg = do putStrLn $ concat ["codex: *warning* unable to fetch an archive for ", display i] putStrLn msg return () displayPackages mpid workspaceProjects = case mpid of Just p -> display p Nothing -> unwords (fmap (display . workspaceProjectIdentifier) workspaceProjects) help :: IO () help = putStrLn $ unlines [ "Usage: codex [update] [cache clean] [set tagger [hasktags|ctags]] [set format [vim|emacs|sublime]]" , " [--help]" , " [--version]" , "" , " update Synchronize the tags file in the current cabal project directory" , " update --force Discard tags file hash and force regeneration" , " cache clean Remove all `tags` file from the local hackage cache]" , " set tagger <tagger> Update the `~/.codex` configuration file for the given tagger (hasktags|ctags)." , " set format <format> Update the `~/.codex` configuration file for the given format (vim|emacs|sublime)." , "" , "By default `hasktags` will be used, and need to be in the `PATH`, the tagger command can be fully customized in `~/.codex`." , "" , "Note: codex will browse the parent directory for cabal projects and use them as dependency over hackage when possible." ] main :: IO () main = withSocketsDo $ do cx <- loadConfig args <- getArgs run cx args where run cx ["cache", "clean"] = toBuilderConfig cx >>= cleanCache run cx ["update"] = withConfig cx (update False) run cx ["update", "--force"] = withConfig cx (update True) run cx ["set", "tagger", "ctags"] = encodeConfig $ cx { tagsCmd = taggerCmd Ctags } run cx ["set", "tagger", "hasktags"] = encodeConfig $ cx { tagsCmd = taggerCmd Hasktags } run cx ["set", "format", "emacs"] = encodeConfig $ cx { tagsCmd = taggerCmd HasktagsEmacs, tagsFileHeader = False, tagsFileSorted = False, tagsFileName = "TAGS" } run cx ["set", "format", "sublime"] = encodeConfig $ cx { tagsCmd = taggerCmd HasktagsExtended, tagsFileHeader = True, tagsFileSorted = True } run cx ["set", "format", "vim"] = encodeConfig $ cx { tagsFileHeader = True, tagsFileSorted = True } run _ ["--version"] = putStrLn $ concat ["codex: ", display (mkVersion' version)] run _ ["--help"] = help run _ [] = help run _ args = fail' $ concat ["codex: '", intercalate " " args,"' is not a codex command. See 'codex --help'."] toBuilderConfig cx' = checkConfig cx' >>= \state -> case state of TaggerNotFound -> fail' $ "codex: tagger not found." Ready -> do stackFileExists <- doesFileExist $ "." </> "stack.yaml" stackWorkExists <- doesDirectoryExist $ "." </> ".stack-work" if stackFileExists && stackWorkExists then do (ec, _, _) <- readCreateProcessWithExitCode (shell "which stack") "" case ec of ExitSuccess -> do let opts = stackOpts cx' globalPath <- readStackPath opts "stack-root" binPath <- readStackPath opts "bin-path" path <- getEnv "PATH" setEnv "PATH" $ concat [path, ":", binPath] return (Stack opts, cx' { hackagePath = globalPath </> "indices" </> "Hackage" }) _ -> return (Cabal, cx') else return (Cabal, cx') withConfig cx' f = do (bldr, cx) <- toBuilderConfig cx' cacheHash' <- readCacheHash cx case cacheHash' of Just cacheHash -> when (cacheHash /= codexHash cx) $ do putStrLn "codex: configuration has been updated, cleaning cache ..." cleanCache (bldr, cx) Nothing -> return () res <- f cx bldr writeCacheHash cx $ codexHash cx return res fail' msg = do putStrLn $ msg exitWith (ExitFailure 1)
aloiscochard/codex
codex/Main.hs
apache-2.0
7,992
0
27
2,115
2,221
1,121
1,100
163
16
{-# LANGUAGE ForeignFunctionInterface #-} module Network.Libre.TLS.FFI.Internal where import Control.Monad.Primitive import Data.Word(Word32(..), Word8(..)) import Foreign.C.Types import Foreign.C.String import Foreign.Ptr import System.Posix.Types {- -- #define TLS_WANT_POLLIN -2 -- #define TLS_WANT_POLLOUT -3 RETURN VALUES The tls_peer_cert_provided() and tls_peer_cert_contains_name() functions return 1 if the check succeeds, and 0 if it does not. Functions that return a time_t will return a time in epoch-seconds on success, and -1 on error. Functions that return a ssize_t will return a size on success, and -1 on error. All other functions that return int will return 0 on success and -1 on error. Functions that return a pointer will return NULL on error, which indicates an out of memory condition. The tls_handshake(), tls_read(), tls_write(), and tls_close() functions have two special return values: TLS_WANT_POLLIN The underlying read file descriptor needs to be readable in order to continue. TLS_WANT_POLLOUT The underlying write file descriptor needs to be writeable in order to continue. In the case of blocking file descriptors, the same function call should be repeated immediately. In the case of non-blocking file descriptors, the same function call should be repeated when the required condition has been met. Callers of these functions cannot rely on the value of the global errno. To prevent mishandling of error conditions, tls_handshake(), tls_read(), tls_write(), and tls_close() all explicitly clear errno. -} {- #define TLS_API 20170126 #define TLS_PROTOCOL_TLSv1_0 (1 << 1) #define TLS_PROTOCOL_TLSv1_1 (1 << 2) #define TLS_PROTOCOL_TLSv1_2 (1 << 3) #define TLS_PROTOCOL_TLSv1 \ (TLS_PROTOCOL_TLSv1_0|TLS_PROTOCOL_TLSv1_1|TLS_PROTOCOL_TLSv1_2) #define TLS_PROTOCOLS_ALL TLS_PROTOCOL_TLSv1 #define TLS_PROTOCOLS_DEFAULT TLS_PROTOCOL_TLSv1_2 #define TLS_WANT_POLLIN -2 #define TLS_WANT_POLLOUT -3 /* RFC 6960 Section 2.3 */ #define TLS_OCSP_RESPONSE_SUCCESSFUL 0 #define TLS_OCSP_RESPONSE_MALFORMED 1 #define TLS_OCSP_RESPONSE_INTERNALERROR 2 #define TLS_OCSP_RESPONSE_TRYLATER 3 #define TLS_OCSP_RESPONSE_SIGREQUIRED 4 #define TLS_OCSP_RESPONSE_UNAUTHORIZED 5 /* RFC 6960 Section 2.2 */ #define TLS_OCSP_CERT_GOOD 0 #define TLS_OCSP_CERT_REVOKED 1 #define TLS_OCSP_CERT_UNKNOWN 2 /* RFC 5280 Section 5.3.1 */ #define TLS_CRL_REASON_UNSPECIFIED 0 #define TLS_CRL_REASON_KEY_COMPROMISE 1 #define TLS_CRL_REASON_CA_COMPROMISE 2 #define TLS_CRL_REASON_AFFILIATION_CHANGED 3 #define TLS_CRL_REASON_SUPERSEDED 4 #define TLS_CRL_REASON_CESSATION_OF_OPERATION 5 #define TLS_CRL_REASON_CERTIFICATE_HOLD 6 #define TLS_CRL_REASON_REMOVE_FROM_CRL 8 #define TLS_CRL_REASON_PRIVILEGE_WITHDRAWN 9 #define TLS_CRL_REASON_AA_COMPROMISE 10 #define TLS_MAX_SESSION_ID_LENGTH 32 #define TLS_TICKET_KEY_SIZE 48 -} {- define TLS_API 20160904 define TLS_PROTOCOL_TLSv1_0 (1 << 1) define TLS_PROTOCOL_TLSv1_1 (1 << 2) define TLS_PROTOCOL_TLSv1_2 (1 << 3) define TLS_PROTOCOL_TLSv1 \ (TLS_PROTOCOL_TLSv1_0|TLS_PROTOCOL_TLSv1_1|TLS_PROTOCOL_TLSv1_2) define TLS_PROTOCOLS_ALL TLS_PROTOCOL_TLSv1 define TLS_PROTOCOLS_DEFAULT TLS_PROTOCOL_TLSv1_2 define TLS_WANT_POLLIN -2 define TLS_WANT_POLLOUT -3 struct tls; struct tls_config; typedef ssize_t (*tls_read_cb)(struct tls *_ctx, void *_buf, size_t _buflen, void *_cb_arg); typedef ssize_t (*tls_write_cb)(struct tls *_ctx, const void *_buf, size_t _buflen, void *_cb_arg); -} -- this is for passing information to and from C land callbacks newtype CastedStablePtr a = CastedStablePtr ( Ptr ()) newtype TlsReadCallback b = TLSReadCB (TLSPtr -> {-Ptr a-} Ptr Word8 {-CString-} -> CSize -> CastedStablePtr b -> IO CSsize) foreign import ccall "wrapper" mkReadCB :: (TLSPtr -> {-Ptr a-} Ptr Word8 {-CString-} -> CSize -> CastedStablePtr b -> IO CSsize) -> IO (FunPtr (TlsReadCallback b)) newtype TlsWriteCallback b = TLSWriteCB (TLSPtr -> {-Ptr a-} CString -> CSize -> CastedStablePtr b -> IO CSsize) foreign import ccall "wrapper" mkWriteCB :: (TLSPtr -> {-Ptr a-} CString -> CSize -> CastedStablePtr b -> IO CSsize) -> IO (FunPtr (TlsWriteCallback b)) primWriteCallback :: (TLSPtr -> {-Ptr a-} CString -> CSize -> CastedStablePtr b -> IO CSsize) -> IO (FunPtr (TlsWriteCallback b)) primWriteCallback = \ f -> ( mkWriteCB $! (\tl buf buflen arg -> f tl buf buflen arg )) primReadCallback :: (TLSPtr -> {-Ptr a-} Ptr Word8 {-CString-} -> CSize -> CastedStablePtr b -> IO CSsize) -> IO (FunPtr (TlsReadCallback b)) primReadCallback = \ f -> ( mkReadCB $! (\tl buf buflen arg -> f tl buf buflen arg )) --struct tls; data LibTLSContext newtype TLSPtr = TheTLSPTR (Ptr LibTLSContext) --struct tls_config; data LibTLSConfig newtype TLSConfigPtr = TheTLSConfigPtr (Ptr LibTLSConfig) newtype LibreFD = LibreFD { unLibreFD :: CInt } newtype LibreSocket = LibreSocket { unLibreSocket :: CInt } newtype FilePathPtr = FilePathPtr (CString) -- null terminated string??! -- | tls_accept_cbs(struct tls *_ctx, struct tls **_cctx, tls_read_cb _read_cb, tls_write_cb _write_cb, void *_cb_arg) -> int ; foreign import ccall safe "tls_accept_cbs" tls_accept_cbs_c :: TLSPtr -> Ptr (TLSPtr) -> (FunPtr (TlsReadCallback a)) -> (FunPtr (TlsWriteCallback a)) -> Ptr a -> IO CInt -- | tls_accept_fds(struct tls *_ctx, struct tls **_cctx, int _fd_read, int _fd_write)-> int ; foreign import ccall safe "tls_accept_fds" tls_accept_fds_c :: TLSPtr -> Ptr TLSPtr -> LibreFD -> LibreFD -> IO CInt -- | tls_accept_socket(struct tls *_ctx, struct tls **_cctx, int _socket)-> int ; foreign import ccall safe "tls_accept_socket" tls_accept_socket_c :: TLSPtr -> Ptr (Ptr LibTLSContext) -> LibreSocket -> IO CInt -- | tls_client(void)-> struct tls *; foreign import ccall safe "tls_client" allocate_fresh_tls_client_context_c :: IO TLSPtr -- | tls_close(struct tls *_ctx)-> int ; foreign import ccall safe "tls_close" tls_close_c :: TLSPtr -> IO CInt -- | tls_config_add_keypair_file(struct tls_config *_config, const char *_cert_file, const char*_key_file ) -> int ; foreign import ccall safe "tls_config_add_keypair_file" tls_config_add_keypair_file_c :: TLSConfigPtr -> FilePathPtr -> FilePathPtr -> IO CInt -- | tls_config_add_keypair_mem(struct tls_config *_config, const uint8_t *_cert, size_t _cert_len, const uint8_t *_key, size_t _key_len) -> int ; foreign import ccall safe "tls_config_add_keypair_mem" tls_config_add_keypair_mem_c :: TLSConfigPtr -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize->IO CInt -- | tls_config_add_keypair_ocsp_file(struct tls_config *_config, const char *_cert_file, const char *_key_file, const char *_ocsp_staple_file) -> int ; foreign import ccall safe "tls_config_add_keypair_ocsp_file" tls_config_add_keypair_ocsp_file_c :: TLSConfigPtr -> FilePathPtr -> FilePathPtr -> FilePathPtr -> IO CInt -- | tls_config_add_keypair_ocsp_mem(struct tls_config *_config, const uint8_t *_cert, size_t _cert_len, -- const uint8_t *_key, size_t _key_len, const uint8_t *_staple, size_t _staple_len) -> int ; foreign import ccall safe "tls_config_add_keypair_ocsp_mem" tls_config_add_keypair_ocsp_mem_c :: TLSConfigPtr -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize->IO CInt -- | tls_config_add_ticket_key(struct tls_config *_config, uint32_t _keyrev, unsigned char *_key, size_t _keylen) -> int ; foreign import ccall safe "tls_config_add_ticket_key" tls_config_add_ticket_key_c :: TLSPtr -> Word32 -> Ptr Word8 -> CSize -> IO Int -- | tls_config_clear_keys(struct tls_config *_config)-> void ; foreign import ccall safe "tls_config_clear_keys" tls_config_clear_keys_c :: TLSConfigPtr -> IO () -- | tls_config_error(struct tls_config *_config) -> const char *; foreign import ccall safe "tls_config_free" tls_config_free_c :: TLSConfigPtr -> IO () -- | these given foot gun at the end in mutually inconsistent styles because you shouldn't use them outside of testing foreign import ccall safe "tls_config_insecure_noverifycert" tls_config_insecure_noverifycert_foot_gun_testingOnly_c :: TLSConfigPtr -> IO () foreign import ccall safe "tls_config_insecure_noverifyname" tls_config_insecure_noverifyname_Foot_gun_testingOnly_c :: TLSConfigPtr -> IO () foreign import ccall safe "tls_config_insecure_noverifytime" tls_config_insecure_noverifytime_footGun_testing_only_C :: TLSConfigPtr -> IO () -- | tls_config_new(void) -> struct tls_config * ; foreign import ccall safe "tls_config_new" tls_config_new_c :: IO TLSConfigPtr -- | tls_config_ocsp_require_stapling(struct tls_config *_config)-> void ; foreign import ccall safe "tls_config_ocsp_require_stapling" tls_config_ocsp_require_stapling_c :: TLSConfigPtr -> IO () -- | tls_config_parse_protocols(uint32_t *_protocols, const char *_protostr) -> int ; foreign import ccall safe "tls_config_parse_protocols" tls_config_parse_protocols_c :: CString -> CString -> IO CInt -- | tls_config_prefer_ciphers_client(struct tls_config *_config)-> void ; foreign import ccall safe "tls_config_prefer_ciphers_client" tls_config_prefer_ciphers_client_c :: TLSConfigPtr -> IO () -- | tls_config_prefer_ciphers_server(struct tls_config *_config)-> void ; foreign import ccall safe "tls_config_prefer_ciphers_server" tls_config_prefer_ciphers_server_c :: TLSConfigPtr -> IO () -- | tls_config_set_alpn(struct tls_config *_config, const char *_alpn) -> int ; foreign import ccall safe "tls_config_set_alpn" tls_config_set_alpn_c :: TLSConfigPtr -> CString -> IO CInt -- | tls_config_set_ca_file(struct tls_config *_config, const char *_ca_file) -> int ; foreign import ccall safe "tls_config_set_ca_file" tls_config_set_ca_file_c :: TLSConfigPtr -> CString -> IO CInt -- | tls_config_set_ca_mem(struct tls_config *_config, const uint8_t *_ca, size_t _len) -> int ; foreign import ccall safe "tls_config_set_ca_mem" tls_config_set_ca_mem_c :: TLSConfigPtr -> Ptr Word8 -> CSize -> IO CInt -- | tls_config_set_ca_path(struct tls_config *_config, const char *_ca_path) -> int ; foreign import ccall safe "tls_config_set_ca_path" tls_config_set_ca_path_c :: TLSConfigPtr -> CString -> IO CInt -- | tls_config_set_cert_file(struct tls_config *_config, const char *_cert_file) -> int ; foreign import ccall safe "tls_config_set_cert_file" tls_config_set_cert_file_c :: TLSConfigPtr -> CString -> IO CInt -- | tls_config_set_cert_mem(struct tls_config *_config, const uint8_t *_cert, size_t _len) -> int ; foreign import ccall safe "tls_config_set_cert_mem" tls_config_set_cert_mem_c :: TLSConfigPtr -> Ptr Word8 -> CSize -> IO CInt -- | tls_config_set_ciphers(struct tls_config *_config, const char *_ciphers) -> int ; foreign import ccall safe "tls_config_set_ciphers" tls_config_set_ciphers_c :: TLSConfigPtr -> CString -> IO CInt --tls_config_set_crl_file(struct tls_config *_config, const char *_crl_file) -> int ; -- tls_config_set_crl_mem(struct tls_config *_config, const uint8_t *_crl, size_t _len) -> int ; -- | tls_config_set_dheparams(struct tls_config *_config, const char *_params) -> int ; foreign import ccall safe "tls_config_set_dheparams" tls_config_set_dheparams_c :: TLSConfigPtr -> CString -> IO CInt -- | tls_config_set_ecdhecurve(struct tls_config *_config, const char *_curve) -> int ; foreign import ccall safe "tls_config_set_ecdhecurve" tls_config_set_ecdhecurve_c :: TLSConfigPtr -> CString -> IO CInt -- | tls_config_set_ecdhecurves(struct tls_config *_config, const char *_curves) -> int ; foreign import ccall safe "tls_config_set_key_file" tls_config_set_key_file_c :: TLSConfigPtr -> CString -> IO CInt -- | tls_config_set_key_mem(struct tls_config *_config, const uint8_t *_key, size_t _len) -> int ; foreign import ccall safe "tls_config_set_key_mem" tls_config_set_key_mem_c :: TLSConfigPtr -> Ptr CChar -> CSize -> IO CInt -- | tls_config_set_keypair_file(struct tls_config *_config, const char *_cert_file, const char *_key_file) -> int ; foreign import ccall safe "tls_config_set_keypair_file" tls_config_set_keypair_file_c :: TLSConfigPtr -> CString -> CString -> IO CInt --tls_config_set_keypair_mem(struct tls_config *_config, const uint8_t *_cert, size_t _cert_len, const uint8_t *_key, size_t _key_len) -> int ; --tls_config_set_keypair_ocsp_file(struct tls_config *_config, const char *_cert_file, const char *_key_file, const char *_staple_file) -> int ; --tls_config_set_keypair_ocsp_mem(struct tls_config *_config, const uint8_t *_cert, size_t _cert_len, const uint8_t *_key, size_t _key_len, const uint8_t *_staple, size_t staple_len) -> int ; foreign import ccall safe "tls_config_set_protocols" tls_config_set_protocols_c :: TLSConfigPtr -> Word32 -> IO () foreign import ccall safe "tls_config_set_verify_depth" tls_config_set_verify_depth_c :: TLSConfigPtr -> CInt -> IO () foreign import ccall safe "tls_config_verify" tls_config_verify_c :: TLSConfigPtr -> IO () foreign import ccall safe "tls_config_verify_client" tls_config_verify_client_c :: TLSConfigPtr -> IO () foreign import ccall safe "tls_config_verify_client_optional" tls_config_verify_client_optional_c :: TLSConfigPtr -> IO () foreign import ccall safe "tls_configure" tls_configure_c :: TLSPtr -> TLSConfigPtr -> IO CInt foreign import ccall safe "tls_conn_alpn_selected" tls_conn_alpn_selected_c :: TLSPtr -> CString foreign import ccall safe "tls_conn_cipher" tls_conn_cipher_c :: TLSPtr -> IO CString --tls_conn_servername foreign import ccall safe "tls_conn_version" tls_conn_version_c :: TLSPtr -> IO CString foreign import ccall safe "tls_connect" tls_connect_c :: TLSPtr -> CString -> CString -> IO CInt --tls_connect_cbs foreign import ccall safe "tls_connect_fds" tls_connect_fds_c :: TLSPtr -> LibreFD -> LibreFD -> CString -> IO CInt foreign import ccall safe "tls_connect_servername" tls_connect_servername_c :: TLSPtr -> CString -> CString -> CString -> IO CInt foreign import ccall safe "tls_connect_socket" tls_connect_socket_c :: TLSPtr -> LibreSocket -> CString -> IO CInt foreign import ccall safe "tls_error" tls_error_c :: TLSPtr -> IO CString foreign import ccall safe "tls_free" tls_free_c :: TLSPtr -> IO () foreign import ccall safe "tls_handshake" tls_handshake_c :: TLSPtr -> IO CInt foreign import ccall safe "tls_init" tls_init_c :: IO CInt foreign import ccall safe "tls_load_file" tls_load_file_c :: CString -> CSize -> CString -> IO CString foreign import ccall safe "tls_peer_cert_contains_name" tls_peer_cert_contains_name_c :: TLSPtr -> CString -> IO CInt foreign import ccall safe "tls_peer_cert_hash" tls_peer_cert_hash_c :: TLSPtr -> IO CString foreign import ccall safe "tls_peer_cert_issuer" tls_peer_cert_issuer_c :: TLSPtr -> IO CString foreign import ccall safe "tls_peer_cert_notafter" tls_peer_cert_notafter_c :: TLSPtr -> IO CTime foreign import ccall safe "tls_peer_cert_notbefore" tls_peer_cert_notbefore_c :: TLSPtr -> IO CTime foreign import ccall safe "tls_peer_cert_provided" tls_peer_cert_provided_c :: TLSPtr -> IO CInt foreign import ccall safe "tls_peer_cert_subject" tls_peer_cert_subject_c :: TLSPtr -> IO CString --tls_peer_ocsp_cert_status(struct tls *_ctx)-> int ; --tls_peer_ocsp_crl_reason(struct tls *_ctx)-> int ; --tls_peer_ocsp_next_update(struct tls *_ctx) -> time_t ; --tls_peer_ocsp_response_status(struct tls *_ctx)-> int ; --tls_peer_ocsp_result(struct tls *_ctx) -> const char *; --tls_peer_ocsp_revocation_time(struct tls *_ctx) -> time_t ; --tls_peer_ocsp_this_update(struct tls *_ctx) -> time_t ; --tls_peer_ocsp_url(struct tls *_ctx) -> const char *; foreign import ccall safe "tls_write" tls_read_c :: TLSPtr -> CString -> CSize -> IO CSsize --tls_reset foreign import ccall safe "tls_server" allocate_fresh_tls_server_context_c :: IO TLSPtr -- not sure if thats a good name foreign import ccall safe "tls_write" tls_write_c :: TLSPtr -> CString -> CSize -> IO CSsize
cartazio/libressl-hs
src/Network/Libre/TLS/FFI/Internal.hs
bsd-2-clause
15,890
0
13
2,153
2,176
1,170
1,006
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-| Unittests for the job queue functionality. -} {- Copyright (C) 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.JQueue (testJQueue) where import Control.Monad (when) import Control.Monad.Fail (MonadFail) import Data.Char (isAscii) import Data.List (nub, sort) import System.Directory import System.FilePath import System.IO.Temp import System.Posix.Files import Test.HUnit import Test.QuickCheck as QuickCheck import Test.QuickCheck.Monadic import Text.JSON import Test.Ganeti.TestCommon import Test.Ganeti.TestHelper import Test.Ganeti.Types () import Ganeti.BasicTypes import qualified Ganeti.Constants as C import Ganeti.JQueue import Ganeti.OpCodes import Ganeti.Path import Ganeti.Types as Types import Test.Ganeti.JQueue.Objects (justNoTs, genQueuedOpCode, emptyJob, genJobId) {-# ANN module "HLint: ignore Use camelCase" #-} -- * Test cases -- | Tests default priority value. case_JobPriorityDef :: Assertion case_JobPriorityDef = do ej <- emptyJob assertEqual "for default priority" C.opPrioDefault $ calcJobPriority ej -- | Test arbitrary priorities. prop_JobPriority :: Property prop_JobPriority = forAll (listOf1 (genQueuedOpCode `suchThat` (not . opStatusFinalized . qoStatus))) $ \ops -> property $ do jid0 <- makeJobId 0 let job = QueuedJob jid0 ops justNoTs justNoTs justNoTs Nothing Nothing return $ calcJobPriority job ==? minimum (map qoPriority ops) :: Gen Property -- | Tests default job status. case_JobStatusDef :: Assertion case_JobStatusDef = do ej <- emptyJob assertEqual "for job status" JOB_STATUS_SUCCESS $ calcJobStatus ej -- | Test some job status properties. prop_JobStatus :: Property prop_JobStatus = forAll genJobId $ \jid -> forAll genQueuedOpCode $ \op -> let job1 = QueuedJob jid [op] justNoTs justNoTs justNoTs Nothing Nothing st1 = calcJobStatus job1 op_succ = op { qoStatus = OP_STATUS_SUCCESS } op_err = op { qoStatus = OP_STATUS_ERROR } op_cnl = op { qoStatus = OP_STATUS_CANCELING } op_cnd = op { qoStatus = OP_STATUS_CANCELED } -- computes status for a job with an added opcode before st_pre_op pop = calcJobStatus (job1 { qjOps = pop:qjOps job1 }) -- computes status for a job with an added opcode after st_post_op pop = calcJobStatus (job1 { qjOps = qjOps job1 ++ [pop] }) in conjoin [ counterexample "pre-success doesn't change status" (st_pre_op op_succ ==? st1) , counterexample "post-success doesn't change status" (st_post_op op_succ ==? st1) , counterexample "pre-error is error" (st_pre_op op_err ==? JOB_STATUS_ERROR) , counterexample "pre-canceling is canceling" (st_pre_op op_cnl ==? JOB_STATUS_CANCELING) , counterexample "pre-canceled is canceled" (st_pre_op op_cnd ==? JOB_STATUS_CANCELED) ] -- | Tests job status equivalence with Python. Very similar to OpCodes test. case_JobStatusPri_py_equiv :: Assertion case_JobStatusPri_py_equiv = do let num_jobs = 2000::Int jobs <- genSample (vectorOf num_jobs $ do num_ops <- choose (1, 5) ops <- vectorOf num_ops genQueuedOpCode jid <- genJobId return $ QueuedJob jid ops justNoTs justNoTs justNoTs Nothing Nothing) let serialized = encode jobs -- check for non-ASCII fields, usually due to 'arbitrary :: String' mapM_ (\job -> when (any (not . isAscii) (encode job)) . assertFailure $ "Job has non-ASCII fields: " ++ show job ) jobs py_stdout <- runPython "from ganeti import jqueue\n\ \from ganeti import serializer\n\ \import sys\n\ \job_data = serializer.Load(sys.stdin.read())\n\ \decoded = [jqueue._QueuedJob.Restore(None, o, False, False)\n\ \ for o in job_data]\n\ \encoded = [(job.CalcStatus(), job.CalcPriority())\n\ \ for job in decoded]\n\ \sys.stdout.buffer.write(serializer.Dump(encoded))" serialized >>= checkPythonResult let deserialised = decode py_stdout::Text.JSON.Result [(String, Int)] decoded <- case deserialised of Text.JSON.Ok jobs' -> return jobs' Error msg -> assertFailure ("Unable to decode jobs: " ++ msg) -- this already raised an exception, but we need it -- for proper types >> fail "Unable to decode jobs" assertEqual "Mismatch in number of returned jobs" (length decoded) (length jobs) mapM_ (\(py_sp, job) -> let hs_sp = (jobStatusToRaw $ calcJobStatus job, calcJobPriority job) in assertEqual ("Different result after encoding/decoding for " ++ show job) hs_sp py_sp ) $ zip decoded jobs -- | Tests listing of Job ids. prop_ListJobIDs :: Property prop_ListJobIDs = monadicIO $ do let extractJobIDs :: (Show e, MonadFail m) => m (GenericResult e a) -> m a extractJobIDs = (>>= genericResult (fail . show) return) jobs <- pick $ resize 10 (listOf1 genJobId `suchThat` (\l -> l == nub l)) (e, f, g) <- run . withSystemTempDirectory "jqueue-test-ListJobIDs." $ \tempdir -> do empty_dir <- extractJobIDs $ getJobIDs [tempdir] mapM_ (\jid -> writeFile (tempdir </> jobFileName jid) "") jobs full_dir <- extractJobIDs $ getJobIDs [tempdir] invalid_dir <- getJobIDs [tempdir </> "no-such-dir"] return (empty_dir, sortJobIDs full_dir, invalid_dir) _ <- stop $ conjoin [ counterexample "empty directory" $ e ==? [] , counterexample "directory with valid names" $ f ==? sortJobIDs jobs , counterexample "invalid directory" $ isBad g ] return () -- | Tests loading jobs from disk. prop_LoadJobs :: Property prop_LoadJobs = monadicIO $ do ops <- pick $ resize 5 (listOf1 genQueuedOpCode) jid <- pick genJobId let job = QueuedJob jid ops justNoTs justNoTs justNoTs Nothing Nothing job_s = encode job -- check that jobs in the right directories are parsed correctly (missing, current, archived, missing_current, broken) <- run . withSystemTempDirectory "jqueue-test-LoadJobs." $ \tempdir -> do let load a = loadJobFromDisk tempdir a jid live_path = liveJobFile tempdir jid arch_path = archivedJobFile tempdir jid createDirectory $ tempdir </> jobQueueArchiveSubDir createDirectory $ dropFileName arch_path -- missing job missing <- load True writeFile live_path job_s -- this should exist current <- load False removeFile live_path writeFile arch_path job_s -- this should exist (archived) archived <- load True -- this should be missing missing_current <- load False removeFile arch_path writeFile live_path "invalid job" broken <- load True return (missing, current, archived, missing_current, broken) _ <- stop $ conjoin [ missing ==? noSuchJob , current ==? Ganeti.BasicTypes.Ok (job, False) , archived ==? Ganeti.BasicTypes.Ok (job, True) , missing_current ==? noSuchJob , counterexample "broken job" (isBad broken) ] return () -- | Tests computing job directories. Creates random directories, -- files and stale symlinks in a directory, and checks that we return -- \"the right thing\". prop_DetermineDirs :: Property prop_DetermineDirs = monadicIO $ do count <- pick $ choose (2, 10) nums <- pick $ genUniquesList count (arbitrary::Gen (QuickCheck.Positive Int)) let (valid, invalid) = splitAt (count `div` 2) $ map (\(QuickCheck.Positive i) -> show i) nums (tempdir, non_arch, with_arch, invalid_root) <- run . withSystemTempDirectory "jqueue-test-DetermineDirs." $ \tempdir -> do let arch_dir = tempdir </> jobQueueArchiveSubDir createDirectory arch_dir mapM_ (createDirectory . (arch_dir </>)) valid mapM_ (\p -> writeFile (arch_dir </> p) "") invalid mapM_ (\p -> createSymbolicLink "/dev/null/no/such/file" (arch_dir </> p <.> "missing")) invalid non_arch <- determineJobDirectories tempdir False with_arch <- determineJobDirectories tempdir True invalid_root <- determineJobDirectories (tempdir </> "no-such-subdir") True return (tempdir, non_arch, with_arch, invalid_root) let arch_dir = tempdir </> jobQueueArchiveSubDir _ <- stop $ conjoin [ non_arch ==? [tempdir] , sort with_arch ==? sort (tempdir:map (arch_dir </>) valid) , invalid_root ==? [tempdir </> "no-such-subdir"] ] return () -- | Tests the JSON serialisation for 'InputOpCode'. prop_InputOpCode :: MetaOpCode -> Int -> Property prop_InputOpCode meta i = conjoin [ readJSON (showJSON valid) ==? Text.JSON.Ok valid , readJSON (showJSON invalid) ==? Text.JSON.Ok invalid ] where valid = ValidOpCode meta invalid = InvalidOpCode (showJSON i) -- | Tests 'extractOpSummary'. prop_extractOpSummary :: MetaOpCode -> Int -> Property prop_extractOpSummary meta i = conjoin [ counterexample "valid opcode" $ extractOpSummary (ValidOpCode meta) ==? summary , counterexample "invalid opcode, correct object" $ extractOpSummary (InvalidOpCode jsobj) ==? summary , counterexample "invalid opcode, empty object" $ extractOpSummary (InvalidOpCode emptyo) ==? invalid , counterexample "invalid opcode, object with invalid OP_ID" $ extractOpSummary (InvalidOpCode invobj) ==? invalid , counterexample "invalid opcode, not jsobject" $ extractOpSummary (InvalidOpCode jsinval) ==? invalid ] where summary = opSummary (metaOpCode meta) jsobj = showJSON $ toJSObject [("OP_ID", showJSON ("OP_" ++ summary))] emptyo = showJSON $ toJSObject ([]::[(String, JSValue)]) invobj = showJSON $ toJSObject [("OP_ID", showJSON False)] jsinval = showJSON i invalid = "INVALID_OP" testSuite "JQueue" [ 'case_JobPriorityDef , 'prop_JobPriority , 'case_JobStatusDef , 'prop_JobStatus , 'case_JobStatusPri_py_equiv , 'prop_ListJobIDs , 'prop_LoadJobs , 'prop_DetermineDirs , 'prop_InputOpCode , 'prop_extractOpSummary ]
ganeti/ganeti
test/hs/Test/Ganeti/JQueue.hs
bsd-2-clause
12,058
0
19
3,124
2,516
1,296
1,220
204
2
{-# LANGUAGE TemplateHaskell #-} module Cloud.AWS.ELB.Types where import Data.Text (Text) import Data.Time (UTCTime) import Cloud.AWS.Lib.FromText (deriveFromText) data LoadBalancer = LoadBalancer { loadBalancerSecurityGroups :: [Text] , loadBalancerCreatedTime :: UTCTime , loadBalancerLoadBalancerName :: Text , loadBalancerHealthCheck :: HealthCheck , loadBalancerVPCId :: Maybe Text , loadBalancerListenerDescriptions :: [ListenerDescription] , loadBalancerInstances :: [Instance] , loadBalancerPolicies :: Policies , loadBalancerAvailabilityZones :: [Text] , loadBalancerCanonicalHostedZoneName :: Maybe Text , loadBalancerCanonicalHostedZoneNameID :: Maybe Text , loadBalancerScheme :: Text , loadBalancerSourceSecurityGroup :: Maybe SourceSecurityGroup , loadBalancerDNSName :: Text , loadBalancerBackendServerDescriptions :: [BackendServerDescription] , loadBalancerSubnets :: [Text] } deriving (Show, Eq) data BackendServerDescription = BackendServerDescription { backendServerInstancePort :: Int , backendServerPolicyNames :: [Text] } deriving (Show, Eq) data HealthCheck = HealthCheck { healthCheckInterval :: Int , healthCheckTarget :: Text , healthCheckHealthyThreshold :: Int , healthCheckTimeout :: Int , healthCheckUnhealthyThreshold :: Int } deriving (Show, Eq) data Instance = Instance { instanceId :: Text } deriving (Show, Eq) data ListenerDescription = ListenerDescription { listenerDescriptionPolicyNames :: [Text] , listenerDescriptionListener :: Listener } deriving (Show, Eq) data Listener = Listener { listenerProtocol :: Text , listenerLoadBalancerPort :: Int , listenerInstanceProtocol :: Text , listenerSSLCertificateId :: Maybe Text , listenerInstancePort :: Int } deriving (Show, Eq) data Policies = Policies { policiesAppCookieStickinessPolicies :: [AppCookieStickinessPolicy] , policiesOtherPolicies :: [Text] , policiesLBCookieStickinessPolicies :: [LBCookieStickinessPolicy] } deriving (Show, Eq) data AppCookieStickinessPolicy = AppCookieStickinessPolicy { appCookieStickinessPolicyCookieName :: Text , appCookieStickinessPolicyPolicyName :: Text } deriving (Show, Eq) data LBCookieStickinessPolicy = LBCookieStickinessPolicy { lbCookieStickinessPolicyPolicyName :: Text , lbCookieStickinessPolicyCookieExpirationPeriod :: Maybe Integer } deriving (Show, Eq) data SourceSecurityGroup = SourceSecurityGroup { sourceSecurityGroupOwnerAlias :: Text , sourceSecurityGroupGroupName :: Text } deriving (Show, Eq) data PolicyDescription = PolicyDescription { policyName :: Text , policyTypeName :: Text , policyAttributes :: [PolicyAttribute] } deriving (Show, Eq) data PolicyAttribute = PolicyAttribute { policyAttributeName :: Text , policyAttributeValue :: Text } deriving (Show, Eq) data PolicyType = PolicyType { policyTypeAttributeTypes :: [PolicyAttributeType] , policyTypeTypeName :: Text , policyTypeDescription :: Text } deriving (Show, Eq) data PolicyAttributeType = PolicyAttributeType { policyAttributeTypeAttributeName :: Text , policyAttributeTypeAttributeType :: Text , policyAttributeTypeDefaultValue :: Maybe Text , policyAttributeTypeCardinality :: PolicyAttributeCardinality , policyAttributeTypeDescription :: Maybe Text } deriving (Show, Eq) data PolicyAttributeCardinality = PolicyAttributeCardinalityOne | PolicyAttributeCardinalityZeroOrOne | PolicyAttributeCardinalityZeroOrMore | PolicyAttributeCardinalityOneOrMore deriving (Show, Eq, Read) deriveFromText "PolicyAttributeCardinality" ["ONE", "ZERO_OR_ONE", "ZERO_OR_MORE", "ONE_OR_MORE"] data InstanceState = InstanceState { instanceStateDescription :: Text , instanceStateInstanceId :: Text , instanceStateState :: InstanceStateState , instanceStateReasonCode :: Maybe Text } deriving (Show, Eq) data InstanceStateState = InstanceStateInService | InstanceStateOutOfService deriving (Show, Eq, Read) deriveFromText "InstanceStateState" ["InService", "OutOfService"]
worksap-ate/aws-sdk
Cloud/AWS/ELB/Types.hs
bsd-3-clause
4,254
0
9
787
839
505
334
105
0
{-# LANGUAGE KindSignatures, GADTs #-} module MIPs.Types where import Data.Word data MInstruction :: * where R :: Address -> Address -> Address -> Shamt -> Func -> MInstruction I :: OP -> Address -> Address -> Immediate -> MInstruction J :: OP -> JumpAddress -> MInstruction deriving (Show) data OP :: * where -- all MIPS opcodes emulated -- R-Type (OP field = 0) R_op :: OP -- hate this name -- J-Type (OP Field = 1 or 2) J_op :: OP -- this one too JAL :: OP -- I-Type (OP Field >= 3) -- if *all* I-types have constructors in order then we can use toEnum here when decoding BEQ :: OP BNE :: OP deriving (Eq, Ord, Show, Enum) data Func :: * where -- all R-Type Functions emulated {- SLL :: FUNC -- if *all* functions have constructors in order then we can use toEnum here when decoding SRL :: FUNC SRA :: FUNC SLLV :: FUNC SRLV :: FUNC SRAV :: FUNC JR :: FUNC JALR :: FUNC --two forms (JALR $rd $rs and JALR $rs)-} SLL :: Func -- 0X00, uses SHAMT SRL :: Func -- 0x02, uses SHAMT SRA :: Func -- 0x03, uses SHAMT JR :: Func -- 0x08 MFHI :: Func -- 0x10 MFLO :: Func -- 0x12 MULT :: Func -- 0x18 MULTU :: Func -- 0x19 DIV :: Func -- 0x1A DIVU :: Func -- 0x1B ADD :: Func -- 0X20 ADDU :: Func -- 0X21 SUB :: Func -- 0x22 SUBU :: Func -- 0x23 AND :: Func -- 0X24 OR :: Func -- 0X25 XOR :: Func -- 0X26 NOR :: Func -- 0x27 SLT :: Func -- 0X2A SLTU :: Func -- 0X2B deriving (Eq, Ord, Show, Enum) -- hopefully this is replaceable with toEnum later toOP :: Word8 -> OP toOP n | n == 0 = R_op | n == 2 = J_op | n == 3 = JAL | n == 4 = BEQ | n == 5 = BNE -- hopefully this is easily replaceable with toEnum later -- this could also be reorderded to account for common usages (reduce branch checks) toFunc :: Word8 -> Func toFunc n | n == 0x00 = SLL | n == 0x02 = SRL | n == 0x03 = SRA | n == 0x08 = JR | n == 0x10 = MFHI | n == 0x12 = MFLO | n == 0x18 = MULT | n == 0x19 = MULTU | n == 0x1A = DIV | n == 0x1B = DIVU | n == 0x20 = ADD | n == 0x21 = ADDU | n == 0x22 = SUB | n == 0x23 = SUBU | n == 0x24 = AND | n == 0x25 = OR | n == 0x26 = XOR | n == 0x27 = NOR | n == 0x2A = SLT | n == 0x2B = SLTU type InstrWidth = Word32 type Address = Word8 type Shamt = Word8 type Immediate = Word16 type JumpAddress = Word32
jhstanton/haskellator
examples/MIPs/MIPs/Types.hs
bsd-3-clause
2,576
0
10
881
676
368
308
69
1
module PfeDepCmds where import Prelude hiding (print) import List(nub,intersect) import Monad(unless) import HsName(HsName(..)) import HsIdent(getHSName) --import HsConstants(main_name) import SourceNames(SN(..)) import SrcLoc1(loc0,srcLoc,srcLine,srcColumn) import PFEdeps(runPFE5,depModules',tdepModules') import Pfe0Cmds(mainModules) import PfeParse import PFE0(allModules,pput,epput,getCurrentModuleGraph,getSubGraph,preparseModule) import PFE2(getModuleExports) import AbstractIO import MUtils import QualNames(getQualified) import HasBaseName(getBaseName) import DefinedNames(definedNames) import UniqueNames(HasOrig(..),PN(..),Orig(..),noSrcLoc,origModule) import PNT(PNT(..)) import TiPNT() -- instances for PNT --import TiNames(instName) import TypedIds(IdTy(..),idTy,NameSpace(..),namespace) import Ents(Ent(..)) import Relations(applyRel) import SimpleGraphs(graph,nodes,reachable,isReachable,listReachable,reverseGraph) --import OrdGraph --slower than Graph! import PrettyPrint import PFE3(refsModule) --import RefsTypes(isDef,shPos) --import ConvRefsTypes(simplifyRefsTypes') runPFE5Cmds ext = runCmds (runPFE5 ext) pfeDepCmds = [("deps" , (tModuleArgs deps, "compute dependency graph for definitions")), ("needed", (tQualIds needed',"needed definitions")), ("neededmodules",(tQualIds neededmodules', "names of modules containing needed definitions")), ("dead", (tQualIds dead',"dead code (default: Main.main)")), -- ("refs", (moduleArgs refs,"list what idenfifiers refer to")), ("uses", (entityId uses,"find uses of an entity"))] tModuleArgs = moduleArgs' opts . uncurry where opts = (,) #@ dot <@ untyped dot = kwOption "-dot" tQualIds cmd = f #@ untyped <@ many (arg "<M.x>") where f depM = cmd depM @@ parseQualIds untyped = depM #@ kwOption "-untyped" where depM untyped optms = pick # depM' untyped optms where pick = maybe id (\ms -> filter(\ d@(m,ds)->m `elem` ms)) optms depM' untyped = if untyped then depModules' else tdepModules' --needed = needed' depModules' --tneeded = needed' tdepModules' needed' dm qids = do (_,_,used) <- snd # depgraph' dm qids pput $ ppOrigs (listReachable used) --neededmodules = neededmodules' depModules' --tneededmodules = neededmodules' tdepModules' neededmodules' dm qids = do (_,_,used) <- snd # depgraph' dm qids pput $ fsep (nub $ map origModule (listReachable used)) --dead = dead' depModules' --tdead = dead' tdepModules' dead' dm [] = do mains <- mainModules dead'' dm [(m,"main")|m<-mains] dead' dm qids = dead'' dm qids dead'' dm qids = do (g,ids,used) <- snd # depgraph' dm qids let unused = [n|n<-nodes g,not (isReachable used n)] pput $ fsep (map ppOrig unused) uses (optns,q@(m,n)) = do pnts <- definedPNTs m let ppq = m<>"."<>n case pnts of [] -> fail.pp $ "No such"<+>ppns optns<>":"<+>ppq _ -> do let n=length pnts unless (n<2) $ epput$ ppq<+>"matches"<+>n<+>"entities, showing uses of all" findUses pnts where ppns = maybe (pp "entity") ppns' ppns' ValueNames = pp "value" ppns' ClassOrTypeNames = "class or type" findUses pnts = mapM_ (usesIn pnts) . flip reachable [m] . reverseGraph . map snd =<< getCurrentModuleGraph definedPNTs = map pnt . filter same . definedNames #. preparseModule same (i,ty) = getQualified (getBaseName (getHSName i)) == n && maybe True (namespace ty ==) optns pnt (i,ty) = pnt' (getQualified # ty) m n refs ms = mapM_ ref1 ms where ref1 = pput.ppRefs @@ refsModule ppRefs = vcat . map ppRef ppRef (_,r,os) = r<+>"at"<+>srcLoc r<>":" $$ nest 4 (vcat [pp (srcLoc o)|(o,_)<-os]) usesIn pnts m = do refs <- refsModule m let qs = sp pnts uses = [ppLineCol (srcLoc r)|(_,r,origs)<-refs, --not (isDef r), let os = sp (origs2PNT origs), os `intersects` qs] unless (null uses) $ pput (m<>":"<+>fsep uses) where sp xs = [(x,namespace (idTy x))|x<-xs] origs2PNT origs = [PNT (getHSName pn) ty noSrcLoc|(pn,ty)<-origs] ppLineCol p = srcLine p<>","<>srcColumn p intersects xs ys = not . null $ intersect xs ys depgraph = depgraph' depModules' tdepgraph = depgraph' tdepModules' depgraph' depModules' qids = do let ms = nub (map fst qids) deps <- depModules' . Just . map (fst.snd) =<< getSubGraph (Just ms) ids <- concatMapM origpnt qids let g = depGraph [(n,ns)|(m,(t,ds))<-deps,(ns1,(ns,h))<-ds,n<-ns1] always = [n|(m,(t,ds))<-deps,([],(ns,h))<-ds,n<-ns] used = reachable g (nub (ids++always)) return (deps,(g,ids,used)) depGraph = graph . mapSnd concat . collectByFst -- because of names from typesigs... origpnt (m,n) = do (t,rel) <- getModuleExports m return $ case map ent2pnt (applyRel rel (SN n loc0)) of [] -> [pnt m n] ns -> ns where ent2pnt (Ent m i ty) = pnt' ty m n where SN n _ = getHSName i pnt = pnt' Value pnt' ty m n = PNT (PN (Qual m n) (g m n)) (conv # ty) noSrcLoc where conv (SN n s) = PN n (S s) g m n = G m n noSrcLoc --dotdeps depM = pput.pdotdeps @@ depM . just --tdotdeps = pput.pdotdeps @@ tdepModules' . just pdotdeps deps = "digraph DepGraph"$$ braces ("size=\"7.5,10.5\";ratio=fill;"$$ vcat [p d<>"->"<>braces (fsep [p f<>";"|f<-fs]) |(m,(t,mdeps))<-deps,(ds,(fs,h))<-mdeps,d<-ds]) where p = doubleQuotes . ppOrig --tdeps = pput.vcat.map pdeps @@ tdepModules' . just deps dot depM = pput.fmt @@ depM . just where fmt = if dot then pdotdeps else vcat.map pdeps pdeps (m,(t,deps)) = sep ["module"<+>m<>":",nest 2 (vcat $ map pdep deps)] where pdep (ds,(fs,h)) = sep [fsep ds <> ":",nest 2 (fsep (map ppOrig fs))] ppOrig = ppOrig' (Just m) ppOrig = ppOrig' Nothing ppOrig' optm n = if Just m'==optm then ppi x else m'<>"."<>x where (m',x) = origId n origId n = case orig n of G m' n' _ -> (m', n') -- I m' loc -> (m',instName m' loc) _ -> error ("Bug: PfeDepCmds.origId "++show n) ppOrigs qs = vcat [m<>":"<+>fsep xs|(m,xs)<-collectByFst (map origId qs)]
forste/haReFork
tools/pfe/PfeDepCmds.hs
bsd-3-clause
6,329
20
21
1,472
2,482
1,331
1,151
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} module ClientProxyApi where import System.Random import Control.Monad.Trans.Except import Control.Monad.Trans.Resource import Control.Monad.IO.Class import Data.Aeson import Data.Aeson.TH import Data.Bson.Generic import GHC.Generics import Network.Wai hiding(Response) import Network.Wai.Handler.Warp import Network.Wai.Logger import Servant import Servant.API import Servant.Client import System.IO import System.Directory import System.Environment (getArgs, getProgName, lookupEnv) import System.Log.Formatter import System.Log.Handler (setFormatter) import System.Log.Handler.Simple import System.Log.Handler.Syslog import System.Log.Logger import Data.Bson.Generic import qualified Data.List as DL import Data.Maybe (catMaybes) import Data.Text (pack, unpack) import Data.Time.Clock (UTCTime, getCurrentTime) import Data.Time.Format (defaultTimeLocale, formatTime) import Control.Monad (when) import Network.HTTP.Client (newManager, defaultManagerSettings) import System.Process data File = File { fileName :: FilePath, fileContent :: String } deriving (Eq, Show, Generic) instance ToJSON File instance FromJSON File data Response = Response{ response :: String } deriving (Eq, Show, Generic) instance ToJSON Response instance FromJSON Response type ApiHandler = ExceptT ServantErr IO serverport :: String serverport = "8080" serverhost :: String serverhost = "localhost" type DirectoryApi = "open" :> Capture "fileName" String :> Get '[JSON] File :<|> "close" :> ReqBody '[JSON] File :> Post '[JSON] Response directoryApi :: Proxy DirectoryApi directoryApi = Proxy open :: String -> ClientM File close :: File -> ClientM Response open :<|> close = client directoryApi openQuery:: String -> ClientM File openQuery filename = do openquery <- open filename return openquery closeQuery:: File -> ClientM Response closeQuery file = do closequery <- close file return closequery --type ClientApi = -- "get" :> Capture "fileName" String :> Get '[JSON] File :<|> -- "put" :> ReqBody '[JSON] File :> Post '[JSON] Response --clientApi :: Proxy ClientApi --clientApi = Proxy --server :: Server ClientApi --server = -- getFile :<|> -- putFile --clientApp :: Application --clientApp = serve clientApi server mkApp :: IO() mkApp = do createDirectoryIfMissing True ("tmp/") setCurrentDirectory ("tmp/") putStrLn $ "Enter one of the following commands: UPLOAD/DOWNLOAD/CLOSE" cmd <- getLine case cmd of "UPLOAD" -> uploadFile "DOWNLOAD" -> downloadFile "CLOSE" -> putStrLn $ "Closing service!" _ -> do putStrLn $ "Invalid Command. Try Again" mkApp uploadFile :: IO() uploadFile = do putStrLn "Please enter the name of the file to upload" fileName <- getLine putStrLn "Please enter the contents of the file to upload" fileContent <- getLine let file = File fileName fileContent response <- putFile file putStrLn $ "Response: " ++ show response mkApp downloadFile :: IO() downloadFile = do putStrLn "Please enter the name of the file to download" fileName <- getLine getFile fileName mkApp getFile:: String -> IO() getFile filename = do manager <- newManager defaultManagerSettings res <- runClientM (openQuery filename) (ClientEnv manager (BaseUrl Http "localhost" 7008 "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right response -> do liftIO (writeFile (fileName response) (fileContent response)) let cmd = shell ("vim " ++ (fileName response)) createProcess cmd putStrLn $ "Would you like to re-upload this file? yes/no" yesorno <- getLine case yesorno of "yes" -> do fileContent <- readFile (fileName response) let file = File filename fileContent putFile file mkApp _ -> mkApp putFile:: File -> IO () putFile file = do manager <- newManager defaultManagerSettings res <- runClientM (closeQuery file) (ClientEnv manager (BaseUrl Http "localhost" 7008 "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right response -> putStrLn $ show response
Garygunn94/DFS
ClientProxy/.stack-work/intero/intero133126fF.hs
bsd-3-clause
5,317
22
14
1,688
1,131
596
535
126
4
module Hastings.Config where -- Client configuration backendHostAddress = "hastings.tejp.xyz" backendHostPort = 24601 :: Int
DATx02-16-14/Hastings
src/Hastings/Config.hs
bsd-3-clause
129
0
4
18
20
13
7
3
1
{-# LANGUAGE ScopedTypeVariables, UndecidableInstances, TemplateHaskell, DeriveDataTypeable, EmptyDataDecls, GeneralizedNewtypeDeriving, FlexibleContexts, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, KindSignatures #-} -- STM as a transactional incremental computation framework that just recomputes output thunks from scratch module Control.Concurrent.Transactional.STM where import Control.Concurrent.Transactional import Control.Monad.Incremental import Control.Exception import qualified Control.Concurrent.STM as STM import Data.IORef import Control.Monad import Control.Applicative import Prelude hiding (new,read) import Data.Typeable import Data.Derive.Memo import Data.WithClass.Derive.DeepTypeable import Data.DeriveTH import Data.DeepTypeable import Language.Haskell.TH.Syntax import Data.WithClass.MGenerics.Instances import Data.Memo import System.Mem.MemoTable import System.Mem.StableName.Exts import System.IO.Unsafe import System.Mem.Weak import qualified GHC.Conc.Sync as STM import Control.Monad.IO.Class import Control.Monad.Catch -- ** STM bindings -- | @STM@ as an incremental computation class data STM deriving Typeable type instance IncK STM a = () instance Incremental STM where newtype Outside STM a = OutsideSTM { unOutsideSTM :: STM.STM a } deriving (Monad,Applicative,Functor) newtype Inside STM a = InsideSTM { unInsideSTM :: STM.STM a } deriving (Monad,Applicative,Functor) world = OutsideSTM . unInsideSTM -- | this function is actually safe in this context, since we support no incrementality unsafeWorld = InsideSTM . unOutsideSTM runIncrementalWithParams params stm = STM.atomically (unOutsideSTM $ outside stm) data IncParams STM = STMParams defaultIncParams = STMParams unsafeIOToInc = inside . InsideSTM . STM.unsafeIOToSTM -- just an encapsulator for @TVar@s newtype STMVar (l :: * -> * -> *) inc a = STMVar { unSTMVar :: STM.TVar a } deriving (Eq,Typeable) -- STM does not use @IORef@s, but we nonetheless need to pass them as a witness that @IO@ supports references instance Transactional STM where retry = OutsideSTM STM.retry orElse (OutsideSTM stm1) (OutsideSTM stm2) = OutsideSTM $ STM.orElse stm1 stm2 instance MonadThrow (Outside STM) where throwM e = OutsideSTM $ STM.throwSTM e instance MonadCatch (Outside STM) where catch (OutsideSTM stm) f = OutsideSTM $ STM.catchSTM stm (unOutsideSTM . f) -- @TVar@s can be explicitly created and read, but they don't store lazy computations instance Layer l STM => Thunk STMVar l STM where new m = m >>= newc newc x = inside $ InsideSTM $ liftM STMVar $ STM.newTVar x read (STMVar t) = inside $ InsideSTM $ STM.readTVar t -- @TVar@s can mutated and be used as the inputs of incremental computations instance Layer l STM => Input STMVar l STM where ref x = inside $ InsideSTM $ liftM STMVar $ STM.newTVar x get (STMVar t) = inside $ InsideSTM $ STM.readTVar t set (STMVar t) x = inside $ InsideSTM $ STM.writeTVar t x $(deriveMemo ''STMVar) instance DeepTypeable STMVar where typeTree _ = MkTypeTree (mkName "Control.Concurrent.Transactional.STM.STMVar") [] [] instance (DeepTypeable l,DeepTypeable inc,DeepTypeable a) => DeepTypeable (STMVar l inc a) where typeTree (_ :: Proxy (STMVar l inc a)) = MkTypeTree (mkName "Control.Concurrent.Transactional.STM.STMVar") args [MkConTree (mkName "Control.Concurrent.Transactional.STM.STMVar") [typeTree (Proxy::Proxy (STM.TVar a))]] where args = [typeTree (Proxy::Proxy l),typeTree (Proxy::Proxy inc),typeTree (Proxy::Proxy a)] $(derive makeDeepTypeableAbstract ''STM)
cornell-pl/HsAdapton
src/Control/Concurrent/Transactional/STM.hs
bsd-3-clause
3,560
104
15
502
947
522
425
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} {-# LANGUAGE DeriveGeneric #-} module Penny.Polar where import qualified Control.Lens as Lens import GHC.Generics (Generic) import Text.Show.Pretty (PrettyVal) -- | Something is polar if it must occupy one of two poles. 'Pole' is -- used in a variety of contexts and arguably 'Bool' would have -- performed the task equally well. Arbitrarily, a 'debit' is -- 'North', a 'credit' is 'South', a 'positive' is 'North', and a -- 'negative' is 'South'. This allows a 'Penny.Decimal.Decimal' to -- stand in for a debit, credit, or neutral, depending on its 'Pole'. data Pole = North | South deriving (Eq, Ord, Show, Generic) instance PrettyVal Pole opposite :: Pole -> Pole opposite North = South opposite South = North -- | An object that is polar. data Polarized a = Polarized { _charged :: a , _charge :: Pole } deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic) instance PrettyVal a => PrettyVal (Polarized a) Lens.makeLenses ''Polarized oppositePolarized :: Polarized a -> Polarized a oppositePolarized = Lens.over charge opposite -- | An object that might be polar. data Moderated n o = Moderate n | Extreme (Polarized o) deriving (Show, Generic) instance (PrettyVal n, PrettyVal o) => PrettyVal (Moderated n o) Lens.makePrisms ''Moderated oppositeModerated :: Moderated n o -> Moderated n o oppositeModerated = Lens.over _Extreme oppositePolarized pole'Moderated :: Moderated n o -> Maybe Pole pole'Moderated (Moderate _) = Nothing pole'Moderated (Extreme (Polarized _ p)) = Just p debit :: Pole debit = North credit :: Pole credit = South positive :: Pole positive = North negative :: Pole negative = South integerPole :: Integer -> Maybe Pole integerPole i | i < 0 = Just negative | i == 0 = Nothing | otherwise = Just positive
massysett/penny
penny/lib/Penny/Polar.hs
bsd-3-clause
1,887
0
9
337
475
252
223
45
1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} module Sequence.Alignment.Matrix ( ScoringMatrix (..) , BLOSUM62 (..), PAM250 (..), NUC44 (..) , blosum62, pam250, nuc44 , matrix ) where import Sequence.Alignment.Matrix.Scoring import Sequence.Alignment.Matrix.Template [matrix|BLOSUM62 # Matrix made by matblas from blosum62.iij # * column uses minimum score # BLOSUM Clustered Scoring Matrix in 1/2 Bit Units # Blocks Database = /data/blocks_5.0/blocks.dat # Cluster Percentage: >= 62 # Entropy = 0.6979, Expected = -0.5209 A R N D C Q E G H I L K M F P S T W Y V B Z X * A 4 -1 -2 -2 0 -1 -1 0 -2 -1 -1 -1 -1 -2 -1 1 0 -3 -2 0 -2 -1 0 -4 R -1 5 0 -2 -3 1 0 -2 0 -3 -2 2 -1 -3 -2 -1 -1 -3 -2 -3 -1 0 -1 -4 N -2 0 6 1 -3 0 0 0 1 -3 -3 0 -2 -3 -2 1 0 -4 -2 -3 3 0 -1 -4 D -2 -2 1 6 -3 0 2 -1 -1 -3 -4 -1 -3 -3 -1 0 -1 -4 -3 -3 4 1 -1 -4 C 0 -3 -3 -3 9 -3 -4 -3 -3 -1 -1 -3 -1 -2 -3 -1 -1 -2 -2 -1 -3 -3 -2 -4 Q -1 1 0 0 -3 5 2 -2 0 -3 -2 1 0 -3 -1 0 -1 -2 -1 -2 0 3 -1 -4 E -1 0 0 2 -4 2 5 -2 0 -3 -3 1 -2 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4 G 0 -2 0 -1 -3 -2 -2 6 -2 -4 -4 -2 -3 -3 -2 0 -2 -2 -3 -3 -1 -2 -1 -4 H -2 0 1 -1 -3 0 0 -2 8 -3 -3 -1 -2 -1 -2 -1 -2 -2 2 -3 0 0 -1 -4 I -1 -3 -3 -3 -1 -3 -3 -4 -3 4 2 -3 1 0 -3 -2 -1 -3 -1 3 -3 -3 -1 -4 L -1 -2 -3 -4 -1 -2 -3 -4 -3 2 4 -2 2 0 -3 -2 -1 -2 -1 1 -4 -3 -1 -4 K -1 2 0 -1 -3 1 1 -2 -1 -3 -2 5 -1 -3 -1 0 -1 -3 -2 -2 0 1 -1 -4 M -1 -1 -2 -3 -1 0 -2 -3 -2 1 2 -1 5 0 -2 -1 -1 -1 -1 1 -3 -1 -1 -4 F -2 -3 -3 -3 -2 -3 -3 -3 -1 0 0 -3 0 6 -4 -2 -2 1 3 -1 -3 -3 -1 -4 P -1 -2 -2 -1 -3 -1 -1 -2 -2 -3 -3 -1 -2 -4 7 -1 -1 -4 -3 -2 -2 -1 -2 -4 S 1 -1 1 0 -1 0 0 0 -1 -2 -2 0 -1 -2 -1 4 1 -3 -2 -2 0 0 0 -4 T 0 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1 1 5 -2 -2 0 -1 -1 0 -4 W -3 -3 -4 -4 -2 -2 -3 -2 -2 -3 -2 -3 -1 1 -4 -3 -2 11 2 -3 -4 -3 -2 -4 Y -2 -2 -2 -3 -2 -1 -2 -3 2 -1 -1 -2 -1 3 -3 -2 -2 2 7 -1 -3 -2 -1 -4 V 0 -3 -3 -3 -1 -2 -2 -3 -3 3 1 -2 1 -1 -2 -2 0 -3 -1 4 -3 -2 -1 -4 B -2 -1 3 4 -3 0 1 -1 0 -3 -4 0 -3 -3 -2 0 -1 -4 -3 -3 4 1 -1 -4 Z -1 0 0 1 -3 3 4 -2 0 -3 -3 1 -1 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4 X 0 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 0 0 -2 -1 -1 -1 -1 -1 -4 * -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 1 |] [matrix|PAM250 # # This matrix was produced by "pam" Version 1.0.6 [28-Jul-93] # # PAM 250 substitution matrix, scale = ln(2)/3 = 0.231049 # # Expected score = -0.844, Entropy = 0.354 bits # # Lowest score = -8, Highest score = 17 # A R N D C Q E G H I L K M F P S T W Y V B Z X * A 2 -2 0 0 -2 0 0 1 -1 -1 -2 -1 -1 -3 1 1 1 -6 -3 0 0 0 0 -8 R -2 6 0 -1 -4 1 -1 -3 2 -2 -3 3 0 -4 0 0 -1 2 -4 -2 -1 0 -1 -8 N 0 0 2 2 -4 1 1 0 2 -2 -3 1 -2 -3 0 1 0 -4 -2 -2 2 1 0 -8 D 0 -1 2 4 -5 2 3 1 1 -2 -4 0 -3 -6 -1 0 0 -7 -4 -2 3 3 -1 -8 C -2 -4 -4 -5 12 -5 -5 -3 -3 -2 -6 -5 -5 -4 -3 0 -2 -8 0 -2 -4 -5 -3 -8 Q 0 1 1 2 -5 4 2 -1 3 -2 -2 1 -1 -5 0 -1 -1 -5 -4 -2 1 3 -1 -8 E 0 -1 1 3 -5 2 4 0 1 -2 -3 0 -2 -5 -1 0 0 -7 -4 -2 3 3 -1 -8 G 1 -3 0 1 -3 -1 0 5 -2 -3 -4 -2 -3 -5 0 1 0 -7 -5 -1 0 0 -1 -8 H -1 2 2 1 -3 3 1 -2 6 -2 -2 0 -2 -2 0 -1 -1 -3 0 -2 1 2 -1 -8 I -1 -2 -2 -2 -2 -2 -2 -3 -2 5 2 -2 2 1 -2 -1 0 -5 -1 4 -2 -2 -1 -8 L -2 -3 -3 -4 -6 -2 -3 -4 -2 2 6 -3 4 2 -3 -3 -2 -2 -1 2 -3 -3 -1 -8 K -1 3 1 0 -5 1 0 -2 0 -2 -3 5 0 -5 -1 0 0 -3 -4 -2 1 0 -1 -8 M -1 0 -2 -3 -5 -1 -2 -3 -2 2 4 0 6 0 -2 -2 -1 -4 -2 2 -2 -2 -1 -8 F -3 -4 -3 -6 -4 -5 -5 -5 -2 1 2 -5 0 9 -5 -3 -3 0 7 -1 -4 -5 -2 -8 P 1 0 0 -1 -3 0 -1 0 0 -2 -3 -1 -2 -5 6 1 0 -6 -5 -1 -1 0 -1 -8 S 1 0 1 0 0 -1 0 1 -1 -1 -3 0 -2 -3 1 2 1 -2 -3 -1 0 0 0 -8 T 1 -1 0 0 -2 -1 0 0 -1 0 -2 0 -1 -3 0 1 3 -5 -3 0 0 -1 0 -8 W -6 2 -4 -7 -8 -5 -7 -7 -3 -5 -2 -3 -4 0 -6 -2 -5 17 0 -6 -5 -6 -4 -8 Y -3 -4 -2 -4 0 -4 -4 -5 0 -1 -1 -4 -2 7 -5 -3 -3 0 10 -2 -3 -4 -2 -8 V 0 -2 -2 -2 -2 -2 -2 -1 -2 4 2 -2 2 -1 -1 -1 0 -6 -2 4 -2 -2 -1 -8 B 0 -1 2 3 -4 1 3 0 1 -2 -3 1 -2 -4 -1 0 0 -5 -3 -2 3 2 -1 -8 Z 0 0 1 3 -5 3 3 0 2 -2 -3 0 -2 -5 0 0 -1 -6 -4 -2 2 3 -1 -8 X 0 -1 0 -1 -3 -1 -1 -1 -1 -1 -1 -1 -1 -2 -1 0 0 -4 -2 -1 -1 -1 -1 -8 * -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 1 |] [matrix|NUC44 # # This matrix was created by Todd Lowe 12/10/92 # # Uses ambiguous nucleotide codes, probabilities rounded to # nearest integer # # Lowest score = -4, Highest score = 5 # A T G C S W R Y K M B V H D N A 5 -4 -4 -4 -4 1 1 -4 -4 1 -4 -1 -1 -1 -2 T -4 5 -4 -4 -4 1 -4 1 1 -4 -1 -4 -1 -1 -2 G -4 -4 5 -4 1 -4 1 -4 1 -4 -1 -1 -4 -1 -2 C -4 -4 -4 5 1 -4 -4 1 -4 1 -1 -1 -1 -4 -2 S -4 -4 1 1 -1 -4 -2 -2 -2 -2 -1 -1 -3 -3 -1 W 1 1 -4 -4 -4 -1 -2 -2 -2 -2 -3 -3 -1 -1 -1 R 1 -4 1 -4 -2 -2 -1 -4 -2 -2 -3 -1 -3 -1 -1 Y -4 1 -4 1 -2 -2 -4 -1 -2 -2 -1 -3 -1 -3 -1 K -4 1 1 -4 -2 -2 -2 -2 -1 -4 -1 -3 -3 -1 -1 M 1 -4 -4 1 -2 -2 -2 -2 -4 -1 -3 -1 -1 -3 -1 B -4 -1 -1 -1 -1 -3 -3 -1 -1 -3 -1 -2 -2 -2 -1 V -1 -4 -1 -1 -1 -3 -1 -3 -3 -1 -2 -1 -2 -2 -1 H -1 -1 -4 -1 -3 -1 -3 -1 -3 -1 -2 -2 -1 -2 -1 D -1 -1 -1 -4 -3 -1 -1 -3 -1 -3 -2 -2 -2 -1 -1 N -2 -2 -2 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 |]
zmactep/zero-aligner
src/Sequence/Alignment/Matrix.hs
bsd-3-clause
5,701
0
5
2,398
86
61
25
12
0
import System.Smartcard.Lowlevel.WinSCard ( establishContext , releaseContext , listReaders , listReaderGroups , transmit , status , getAttribute , connect) import System.Smartcard.Lowlevel.PCSCLite ( SCardScope (UserScope) , SCardStatus (..) , SCardShare (..) , SCardContext (..) , SCardProtocol (..)) import System.Smartcard.Lowlevel.Reader ( AttrTag (..) , mkRequest ) import Control.Monad tryConnection c r'@(r:rs) = do printShow r' "Found readers: " x <- connect c r Shared [T0, T1] either print f x where f (p, h) = do printShow p "Connected, Protocol is: " rt <- transmit h [0xff, 0x00, 0x40, 0x50, 0x04, 0x05, 0x05, 0x03, 0x01] 200 T0 either print (`printShow` "Answer is: ") rt rt' <- status h 200 200 either print (`printShow` "Queriying the status: ") rt' rt'' <- listReaderGroups c 200 either print (`printShow` "Listing the reader groups: ") rt'' rt''' <- getAttribute h (mkRequest VendorName) 200 either print (`printShow` "Got attribute \"VendorName\"=") rt''' return () printShow :: Show a => a -> String -> IO () printShow s = putStrLn . (flip (++) . show) s withContext :: SCardScope -> (SCardContext -> IO a) -> IO (Either String SCardStatus) withContext s f = establishContext s >>= \r -> either (return . Left . show) (\c -> f c >> liftM Right (releaseContext c)) r main = withContext UserScope $ \c -> do rs <- listReaders c either print (tryConnection c) rs return ()
mfischer/haskell-smartcard
Test.hs
bsd-3-clause
2,454
0
13
1,286
550
293
257
-1
-1
-- | Re-exports module CoreFoundation.Types( module CoreFoundation.Types.Array, module CoreFoundation.Types.Boolean, module CoreFoundation.Types.Data, module CoreFoundation.Types.Date, module CoreFoundation.Types.Dictionary, module CoreFoundation.Types.Number, module CoreFoundation.Types.PropertyList, module CoreFoundation.Types.String, module CoreFoundation.Types.Type, ) where import CoreFoundation.Types.Array import CoreFoundation.Types.Boolean import CoreFoundation.Types.Data import CoreFoundation.Types.Date import CoreFoundation.Types.Dictionary import CoreFoundation.Types.Number import CoreFoundation.Types.PropertyList import CoreFoundation.Types.String import CoreFoundation.Types.Type
reinerp/CoreFoundation
CoreFoundation/Types.hs
bsd-3-clause
720
0
5
63
127
88
39
19
0
module Game.Simulation.Camera.IsometricCamera ( isometricCamera ) where import Linear import Framework import Control.Lens import Game.Simulation.Input import Reactive.Banana import Reactive.Banana.Frameworks import qualified SDL.Event as SDL import qualified SDL.Input.Keyboard as SDL type InitialPos = V3 Float type InitialRot = V2 Float -- ^ X and Y rotation angle in degrees type NearVal = Float type FOV = Float type Aspect = Float -- | An isometric camera isometricCamera :: InputEvent -> TickEvent -> InitialPos -> MomentIO (Behavior (M44 Float)) isometricCamera eInput eTick initialPos = do let projection = ortho (-10.0) 10.0 (-10.0) 10.0 (-1000.0) 1000.0 let camRot = cameraRotation (V2 (-45.0) 45.0) let bCamRot = pure camRot bCamPos <- camPosition eInput eTick initialPos bCamRot let bViewMatrix = viewMatrix <$> bCamPos <*> bCamRot let bMvpMatrix = (!*!) projection <$> bViewMatrix return $ bMvpMatrix -- | Convert a translation matrix and a quaternion to a view matrix viewMatrix :: V3 Float -> Quaternion Float -> M44 Float viewMatrix camTranslation camOrientation = -- Camera translation is negated since view matrix = inverse of camera matrix let mTranslation = identity & translation .~ (-camTranslation) mRotation = m33_to_m44 . fromQuaternion $ camOrientation in mRotation !*! mTranslation -- | A behavior describing the camera position camPosition :: InputEvent -> TickEvent -> V3 Float -> Behavior (Quaternion Float) -> MomentIO (Behavior (V3 Float)) camPosition eInput eTick initialPos bCamRot = do let speed = 0.1 left <- keyDown eInput SDL.ScancodeA right <- keyDown eInput SDL.ScancodeD down <- keyDown eInput SDL.ScancodeS up <- keyDown eInput SDL.ScancodeW bMBDown <- mouseButtonDown eInput SDL.ButtonLeft let eMouseMoved = mouseMoved eInput Absolute let bVelocity = (camVelocity speed <$> bCamRot <*> left <*> right <*> down <*> up) let bAddVelocity = (+) <$> bVelocity let eAddVelocity = bAddVelocity <@ eTick bCamPos <- accumB initialPos eAddVelocity return bCamPos -- | Calculates the camera velocity based on speed and inputs -- The (bool, bool, bool, bool) is (up, down, left, right) camVelocity :: Float -> Quaternion Float -> Bool -> Bool -> Bool -> Bool -> V3 Float camVelocity speed camRot left right down up = let horzVel True False = -speed horzVel False True = speed horzVel _ _ = 0 vertVel True False = speed vertVel False True = -speed vertVel _ _ = 0 in V3 (horzVel left right) (vertVel up down) (0.0) *! fromQuaternion camRot -- | Update camera orientation quaternion based on a mouse movement -- It basically converts from eulers to axisAngle, and could be abstracted cameraRotation :: V2 Float -> Quaternion Float cameraRotation (V2 yaw pitch) = axisAngle (V3 1 0 0) (pitch) * axisAngle (V3 0 1 0) (yaw)
Catchouli/tyke
src/Game/Simulation/Camera/IsometricCamera.hs
bsd-3-clause
3,081
0
16
757
815
411
404
65
5
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Main where import Control.Monad (replicateM) import Data.Aeson (FromJSON, ToJSON, eitherDecode) import Data.Aeson.Encode.Pretty (encodePretty) import qualified Data.ByteString.Lazy as BSL import Data.Proxy (Proxy (..)) import Data.Swagger (Schema, ToSchema, toSchema) import GHC.Generics (Generic) import Test.QuickCheck (arbitrary, generate) import Verdict import Verdict.DB import Verdict.JSON () import Verdict.QuickCheck () -- Datatype definitions {{{--------------------------------------------------- ------------------------------------------------------------------------------ type Age = Validated (Minimum 0 :&& Maximum 200) Integer data Person = Person { name :: String , age :: Age } deriving (Eq, Show, Read, Generic, ToSchema, ToJSON, FromJSON) examplePerson :: Person examplePerson = Person "Julian" (unsafeValidated 15) --}}}------------------------------------------------------------------------- -- Do it once {{{------------------------------------------------------------- ------------------------------------------------------------------------------ -- Read {{{------------------------------------------------------------------- readExample :: Person readExample = read "Person {name = \"Julian K. Arni\", age = 300}" --}}} -- FromJSON {{{--------------------------------------------------------------- fromJSONExample :: Either String Person fromJSONExample = eitherDecode "{ \"name\": \"Julian K. Arni\", \"age\": -20 }" --}}} -- JSON Schema {{{------------------------------------------------------------ jsonSchemaExample :: Schema jsonSchemaExample = toSchema (Proxy :: Proxy Person) jsonSchemaExample' :: IO () jsonSchemaExample' = BSL.writeFile "jsonSchemaExample.json" $ encodePretty jsonSchemaExample --}}} -- QuickCheck {{{------------------------------------------------------------- arbitraryExample :: IO [Validated (Maximum 100) Integer] arbitraryExample = generate $ replicateM 20 arbitrary --}}} -- DB {{{--------------------------------------------------------------------- db :: DB '[Length 5, Length 10] [Int] db = insert [1..10] $ insert [2..6] $ insert [1..5] empty query1 :: [Validated (Length 5) [Int]] query1 = query db query2 :: [Validated (Length 10) [Int]] query2 = query db {- - Won't typecheck: query3 :: [Validated (Length 7) [Int]] query3 = query db -} db2 :: DB '[Length 5, Length 3] [Int] db2 = insert [1..5] $ insert [1..10] $ insert [1..3] empty query4 :: [Joined [Int] [Int]] query4 = crossJoin db db2 -- }}} --}}}------------------------------------------------------------------------- -- As a type {{{-------------------------------------------------------------- ------------------------------------------------------------------------------ -- Implication {{{------------------------------------------------------------ safeDiv :: (c `Implies` (Not (Equals 0))) => Integer -> Validated c Integer -> Integer safeDiv n d = n `div` getVal d -- }}} -- Inference {{{-------------------------------------------------------------- -- From Oleg Kiselyov class Sum2 a b c | a b -> c, a c -> b instance Sum2 Z a a instance Sum2 a b c => Sum2 (S a) b (S c) class Sum a b c | a b -> c, a c -> b, b c -> a instance (Sum2 a b c, Sum2 b a c) => Sum a b c type VInt c = Validated (Equals c) Int type Three = S (S (S Z)) type Five = S (S Three) add :: Sum c1 c2 c3 => VInt c1 -> VInt c2 -> VInt c3 add x y = unsafeValidated $ getVal x + getVal y addExample :: IO () addExample = do x <- readLn let v = add x (read "3" :: VInt Three) :: VInt Five print v -- }}} -- }}}------------------------------------------------------------------------ -- Main {{{------------------------------------------------------------------- ------------------------------------------------------------------------------ main :: IO () main = return () -- }}}
jkarni/bobkonf
src/Main.hs
bsd-3-clause
4,530
0
12
858
989
548
441
-1
-1
{-# LANGUAGE CPP #-} ------------------------------------------------------------------------------- -- -- | Dynamic flags -- -- Most flags are dynamic flags, which means they can change from compilation -- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each -- session can be using different dynamic flags. Dynamic flags can also be set -- at the prompt in GHCi. -- -- (c) The University of Glasgow 2005 -- ------------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-cse #-} -- -fno-cse is needed for GLOBAL_VAR's to behave properly module DynFlags ( -- * Dynamic flags and associated configuration types DumpFlag(..), GeneralFlag(..), WarningFlag(..), ExtensionFlag(..), Language(..), PlatformConstants(..), FatalMessager, LogAction, FlushOut(..), FlushErr(..), ProfAuto(..), glasgowExtsFlags, dopt, dopt_set, dopt_unset, gopt, gopt_set, gopt_unset, wopt, wopt_set, wopt_unset, xopt, xopt_set, xopt_unset, lang_set, useUnicodeSyntax, whenGeneratingDynamicToo, ifGeneratingDynamicToo, whenCannotGenerateDynamicToo, dynamicTooMkDynamicDynFlags, DynFlags(..), FlagSpec(..), HasDynFlags(..), ContainsDynFlags(..), RtsOptsEnabled(..), HscTarget(..), isObjectTarget, defaultObjectTarget, targetRetainsAllBindings, GhcMode(..), isOneShot, GhcLink(..), isNoLink, PackageFlag(..), PackageArg(..), ModRenaming(..), PkgConfRef(..), Option(..), showOpt, DynLibLoader(..), fFlags, fWarningFlags, fLangFlags, xFlags, dynFlagDependencies, tablesNextToCode, mkTablesNextToCode, SigOf, getSigOf, checkOptLevel, Way(..), mkBuildTag, wayRTSOnly, addWay', updateWays, wayGeneralFlags, wayUnsetGeneralFlags, -- ** Safe Haskell SafeHaskellMode(..), safeHaskellOn, safeImportsOn, safeLanguageOn, safeInferOn, packageTrustOn, safeDirectImpsReq, safeImplicitImpsReq, unsafeFlags, unsafeFlagsForInfer, -- ** System tool settings and locations Settings(..), targetPlatform, programName, projectVersion, ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings, versionedAppDir, extraGccViaCFlags, systemPackageConfig, pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T, pgm_sysman, pgm_windres, pgm_libtool, pgm_lo, pgm_lc, opt_L, opt_P, opt_F, opt_c, opt_a, opt_l, opt_windres, opt_lo, opt_lc, -- ** Manipulating DynFlags defaultDynFlags, -- Settings -> DynFlags defaultWays, interpWays, initDynFlags, -- DynFlags -> IO DynFlags defaultFatalMessager, defaultLogAction, defaultLogActionHPrintDoc, defaultLogActionHPutStrDoc, defaultFlushOut, defaultFlushErr, getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a] getVerbFlags, updOptLevel, setTmpDir, setPackageKey, interpretPackageEnv, -- ** Parsing DynFlags parseDynamicFlagsCmdLine, parseDynamicFilePragma, parseDynamicFlagsFull, -- ** Available DynFlags allFlags, flagsAll, flagsDynamic, flagsPackage, flagsForCompletion, supportedLanguagesAndExtensions, languageExtensions, -- ** DynFlags C compiler options picCCOpts, picPOpts, -- * Configuration of the stg-to-stg passes StgToDo(..), getStgToDo, -- * Compiler configuration suitable for display to the user compilerInfo, #ifdef GHCI rtsIsProfiled, #endif dynamicGhc, #include "../includes/dist-derivedconstants/header/GHCConstantsHaskellExports.hs" bLOCK_SIZE_W, wORD_SIZE_IN_BITS, tAG_MASK, mAX_PTR_TAG, tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD, unsafeGlobalDynFlags, setUnsafeGlobalDynFlags, -- * SSE and AVX isSseEnabled, isSse2Enabled, isSse4_2Enabled, isAvxEnabled, isAvx2Enabled, isAvx512cdEnabled, isAvx512erEnabled, isAvx512fEnabled, isAvx512pfEnabled, -- * Linker/compiler information LinkerInfo(..), CompilerInfo(..), ) where #include "HsVersions.h" import Platform import PlatformConstants import Module import PackageConfig import {-# SOURCE #-} Hooks import {-# SOURCE #-} PrelNames ( mAIN ) import {-# SOURCE #-} Packages (PackageState, emptyPackageState) import DriverPhases ( Phase(..), phaseInputExt ) import Config import CmdLineParser import Constants import Panic import Util import Maybes import MonadUtils import qualified Pretty import SrcLoc import BasicTypes ( IntWithInf, treatZeroAsInf ) import FastString import Outputable #ifdef GHCI import Foreign.C ( CInt(..) ) import System.IO.Unsafe ( unsafeDupablePerformIO ) #endif import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessage ) import System.IO.Unsafe ( unsafePerformIO ) import Data.IORef import Control.Arrow ((&&&)) import Control.Monad import Control.Exception (throwIO) import Data.Bits import Data.Char import Data.Int import Data.List import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Data.Word import System.FilePath import System.Directory import System.Environment (getEnv) import System.IO import System.IO.Error import Text.ParserCombinators.ReadP hiding (char) import Text.ParserCombinators.ReadP as R import Data.IntSet (IntSet) import qualified Data.IntSet as IntSet import GHC.Foreign (withCString, peekCString) -- Note [Updating flag description in the User's Guide] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- If you modify anything in this file please make sure that your changes are -- described in the User's Guide. Usually at least two sections need to be -- updated: -- -- * Flag Reference section in docs/users-guide/flags.xml lists all available -- flags together with a short description -- -- * Flag description in docs/users_guide/using.xml provides a detailed -- explanation of flags' usage. -- Note [Supporting CLI completion] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- The command line interface completion (in for example bash) is an easy way -- for the developer to learn what flags are available from GHC. -- GHC helps by separating which flags are available when compiling with GHC, -- and which flags are available when using GHCi. -- A flag is assumed to either work in both these modes, or only in one of them. -- When adding or changing a flag, please consider for which mode the flag will -- have effect, and annotate it accordingly. For Flags use defFlag, defGhcFlag, -- defGhciFlag, and for FlagSpec use flagSpec or flagGhciSpec. -- ----------------------------------------------------------------------------- -- DynFlags data DumpFlag -- See Note [Updating flag description in the User's Guide] -- debugging flags = Opt_D_dump_cmm | Opt_D_dump_cmm_raw -- All of the cmm subflags (there are a lot!) Automatically -- enabled if you run -ddump-cmm | Opt_D_dump_cmm_cfg | Opt_D_dump_cmm_cbe | Opt_D_dump_cmm_switch | Opt_D_dump_cmm_proc | Opt_D_dump_cmm_sink | Opt_D_dump_cmm_sp | Opt_D_dump_cmm_procmap | Opt_D_dump_cmm_split | Opt_D_dump_cmm_info | Opt_D_dump_cmm_cps -- end cmm subflags | Opt_D_dump_asm | Opt_D_dump_asm_native | Opt_D_dump_asm_liveness | Opt_D_dump_asm_regalloc | Opt_D_dump_asm_regalloc_stages | Opt_D_dump_asm_conflicts | Opt_D_dump_asm_stats | Opt_D_dump_asm_expanded | Opt_D_dump_llvm | Opt_D_dump_core_stats | Opt_D_dump_deriv | Opt_D_dump_ds | Opt_D_dump_foreign | Opt_D_dump_inlinings | Opt_D_dump_rule_firings | Opt_D_dump_rule_rewrites | Opt_D_dump_simpl_trace | Opt_D_dump_occur_anal | Opt_D_dump_parsed | Opt_D_dump_rn | Opt_D_dump_simpl | Opt_D_dump_simpl_iterations | Opt_D_dump_spec | Opt_D_dump_prep | Opt_D_dump_stg | Opt_D_dump_call_arity | Opt_D_dump_stranal | Opt_D_dump_strsigs | Opt_D_dump_tc | Opt_D_dump_types | Opt_D_dump_rules | Opt_D_dump_cse | Opt_D_dump_worker_wrapper | Opt_D_dump_rn_trace | Opt_D_dump_rn_stats | Opt_D_dump_opt_cmm | Opt_D_dump_simpl_stats | Opt_D_dump_cs_trace -- Constraint solver in type checker | Opt_D_dump_tc_trace | Opt_D_dump_if_trace | Opt_D_dump_vt_trace | Opt_D_dump_splices | Opt_D_th_dec_file | Opt_D_dump_BCOs | Opt_D_dump_vect | Opt_D_dump_ticked | Opt_D_dump_rtti | Opt_D_source_stats | Opt_D_verbose_stg2stg | Opt_D_dump_hi | Opt_D_dump_hi_diffs | Opt_D_dump_mod_cycles | Opt_D_dump_mod_map | Opt_D_dump_view_pattern_commoning | Opt_D_verbose_core2core | Opt_D_dump_debug deriving (Eq, Show, Enum) -- | Enumerates the simple on-or-off dynamic flags data GeneralFlag -- See Note [Updating flag description in the User's Guide] = Opt_DumpToFile -- ^ Append dump output to files instead of stdout. | Opt_D_faststring_stats | Opt_D_dump_minimal_imports | Opt_DoCoreLinting | Opt_DoStgLinting | Opt_DoCmmLinting | Opt_DoAsmLinting | Opt_DoAnnotationLinting | Opt_NoLlvmMangler -- hidden flag | Opt_WarnIsError -- -Werror; makes warnings fatal | Opt_PrintExplicitForalls | Opt_PrintExplicitKinds | Opt_PrintUnicodeSyntax -- optimisation opts | Opt_CallArity | Opt_Strictness | Opt_LateDmdAnal | Opt_KillAbsence | Opt_KillOneShot | Opt_FullLaziness | Opt_FloatIn | Opt_Specialise | Opt_SpecialiseAggressively | Opt_CrossModuleSpecialise | Opt_StaticArgumentTransformation | Opt_CSE | Opt_LiberateCase | Opt_SpecConstr | Opt_DoLambdaEtaExpansion | Opt_IgnoreAsserts | Opt_DoEtaReduction | Opt_CaseMerge | Opt_UnboxStrictFields | Opt_UnboxSmallStrictFields | Opt_DictsCheap | Opt_EnableRewriteRules -- Apply rewrite rules during simplification | Opt_Vectorise | Opt_VectorisationAvoidance | Opt_RegsGraph -- do graph coloring register allocation | Opt_RegsIterative -- do iterative coalescing graph coloring register allocation | Opt_PedanticBottoms -- Be picky about how we treat bottom | Opt_LlvmTBAA -- Use LLVM TBAA infastructure for improving AA (hidden flag) | Opt_LlvmPassVectorsInRegisters -- Pass SIMD vectors in registers (requires a patched LLVM) (hidden flag) | Opt_IrrefutableTuples | Opt_CmmSink | Opt_CmmElimCommonBlocks | Opt_OmitYields | Opt_SimpleListLiterals | Opt_FunToThunk -- allow WwLib.mkWorkerArgs to remove all value lambdas | Opt_DictsStrict -- be strict in argument dictionaries | Opt_DmdTxDictSel -- use a special demand transformer for dictionary selectors | Opt_Loopification -- See Note [Self-recursive tail calls] -- Interface files | Opt_IgnoreInterfacePragmas | Opt_OmitInterfacePragmas | Opt_ExposeAllUnfoldings | Opt_WriteInterface -- forces .hi files to be written even with -fno-code -- profiling opts | Opt_AutoSccsOnIndividualCafs | Opt_ProfCountEntries -- misc opts | Opt_Pp | Opt_ForceRecomp | Opt_ExcessPrecision | Opt_EagerBlackHoling | Opt_NoHsMain | Opt_SplitObjs | Opt_StgStats | Opt_HideAllPackages | Opt_PrintBindResult | Opt_Haddock | Opt_HaddockOptions | Opt_BreakOnException | Opt_BreakOnError | Opt_PrintEvldWithShow | Opt_PrintBindContents | Opt_GenManifest | Opt_EmbedManifest | Opt_SharedImplib | Opt_BuildingCabalPackage | Opt_IgnoreDotGhci | Opt_GhciSandbox | Opt_GhciHistory | Opt_HelpfulErrors | Opt_DeferTypeErrors | Opt_DeferTypedHoles | Opt_PIC | Opt_SccProfilingOn | Opt_Ticky | Opt_Ticky_Allocd | Opt_Ticky_LNE | Opt_Ticky_Dyn_Thunk | Opt_Static | Opt_RPath | Opt_RelativeDynlibPaths | Opt_Hpc | Opt_FlatCache -- PreInlining is on by default. The option is there just to see how -- bad things get if you turn it off! | Opt_SimplPreInlining -- output style opts | Opt_ErrorSpans -- Include full span info in error messages, -- instead of just the start position. | Opt_PprCaseAsLet | Opt_PprShowTicks -- Suppress all coercions, them replacing with '...' | Opt_SuppressCoercions | Opt_SuppressVarKinds -- Suppress module id prefixes on variables. | Opt_SuppressModulePrefixes -- Suppress type applications. | Opt_SuppressTypeApplications -- Suppress info such as arity and unfoldings on identifiers. | Opt_SuppressIdInfo -- Suppress separate type signatures in core, but leave types on -- lambda bound vars | Opt_SuppressTypeSignatures -- Suppress unique ids on variables. -- Except for uniques, as some simplifier phases introduce new -- variables that have otherwise identical names. | Opt_SuppressUniques -- temporary flags | Opt_AutoLinkPackages | Opt_ImplicitImportQualified -- keeping stuff | Opt_KeepHiDiffs | Opt_KeepHcFiles | Opt_KeepSFiles | Opt_KeepTmpFiles | Opt_KeepRawTokenStream | Opt_KeepLlvmFiles | Opt_BuildDynamicToo -- safe haskell flags | Opt_DistrustAllPackages | Opt_PackageTrust -- debugging flags | Opt_Debug deriving (Eq, Show, Enum) data WarningFlag = -- See Note [Updating flag description in the User's Guide] Opt_WarnDuplicateExports | Opt_WarnDuplicateConstraints | Opt_WarnRedundantConstraints | Opt_WarnHiShadows | Opt_WarnImplicitPrelude | Opt_WarnIncompletePatterns | Opt_WarnIncompleteUniPatterns | Opt_WarnIncompletePatternsRecUpd | Opt_WarnOverflowedLiterals | Opt_WarnEmptyEnumerations | Opt_WarnMissingFields | Opt_WarnMissingImportList | Opt_WarnMissingMethods | Opt_WarnMissingSigs | Opt_WarnMissingLocalSigs | Opt_WarnNameShadowing | Opt_WarnOverlappingPatterns | Opt_WarnTypeDefaults | Opt_WarnMonomorphism | Opt_WarnUnusedTopBinds | Opt_WarnUnusedLocalBinds | Opt_WarnUnusedPatternBinds | Opt_WarnUnusedImports | Opt_WarnUnusedMatches | Opt_WarnContextQuantification | Opt_WarnWarningsDeprecations | Opt_WarnDeprecatedFlags | Opt_WarnAMP | Opt_WarnDodgyExports | Opt_WarnDodgyImports | Opt_WarnOrphans | Opt_WarnAutoOrphans | Opt_WarnIdentities | Opt_WarnTabs | Opt_WarnUnrecognisedPragmas | Opt_WarnDodgyForeignImports | Opt_WarnUnusedDoBind | Opt_WarnWrongDoBind | Opt_WarnAlternativeLayoutRuleTransitional | Opt_WarnUnsafe | Opt_WarnSafe | Opt_WarnTrustworthySafe | Opt_WarnPointlessPragmas | Opt_WarnUnsupportedCallingConventions | Opt_WarnUnsupportedLlvmVersion | Opt_WarnInlineRuleShadowing | Opt_WarnTypedHoles | Opt_WarnPartialTypeSignatures | Opt_WarnMissingExportedSigs | Opt_WarnUntickedPromotedConstructors | Opt_WarnDerivingTypeable | Opt_WarnDeferredTypeErrors deriving (Eq, Show, Enum) data Language = Haskell98 | Haskell2010 deriving Enum -- | The various Safe Haskell modes data SafeHaskellMode = Sf_None | Sf_Unsafe | Sf_Trustworthy | Sf_Safe deriving (Eq) instance Show SafeHaskellMode where show Sf_None = "None" show Sf_Unsafe = "Unsafe" show Sf_Trustworthy = "Trustworthy" show Sf_Safe = "Safe" instance Outputable SafeHaskellMode where ppr = text . show data ExtensionFlag -- See Note [Updating flag description in the User's Guide] = Opt_Cpp | Opt_OverlappingInstances | Opt_UndecidableInstances | Opt_IncoherentInstances | Opt_MonomorphismRestriction | Opt_MonoPatBinds | Opt_MonoLocalBinds | Opt_RelaxedPolyRec -- Deprecated | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting | Opt_ForeignFunctionInterface | Opt_UnliftedFFITypes | Opt_InterruptibleFFI | Opt_CApiFFI | Opt_GHCForeignImportPrim | Opt_JavaScriptFFI | Opt_ParallelArrays -- Syntactic support for parallel arrays | Opt_Arrows -- Arrow-notation syntax | Opt_TemplateHaskell | Opt_QuasiQuotes | Opt_ImplicitParams | Opt_ImplicitPrelude | Opt_ScopedTypeVariables | Opt_AllowAmbiguousTypes | Opt_UnboxedTuples | Opt_BangPatterns | Opt_TypeFamilies | Opt_OverloadedStrings | Opt_OverloadedLists | Opt_NumDecimals | Opt_DisambiguateRecordFields | Opt_RecordWildCards | Opt_RecordPuns | Opt_ViewPatterns | Opt_GADTs | Opt_GADTSyntax | Opt_NPlusKPatterns | Opt_DoAndIfThenElse | Opt_RebindableSyntax | Opt_ConstraintKinds | Opt_PolyKinds -- Kind polymorphism | Opt_DataKinds -- Datatype promotion | Opt_InstanceSigs | Opt_StandaloneDeriving | Opt_DeriveDataTypeable | Opt_AutoDeriveTypeable -- Automatic derivation of Typeable | Opt_DeriveFunctor | Opt_DeriveTraversable | Opt_DeriveFoldable | Opt_DeriveGeneric -- Allow deriving Generic/1 | Opt_DefaultSignatures -- Allow extra signatures for defmeths | Opt_DeriveAnyClass -- Allow deriving any class | Opt_TypeSynonymInstances | Opt_FlexibleContexts | Opt_FlexibleInstances | Opt_ConstrainedClassMethods | Opt_MultiParamTypeClasses | Opt_NullaryTypeClasses | Opt_FunctionalDependencies | Opt_UnicodeSyntax | Opt_ExistentialQuantification | Opt_MagicHash | Opt_EmptyDataDecls | Opt_KindSignatures | Opt_RoleAnnotations | Opt_ParallelListComp | Opt_TransformListComp | Opt_MonadComprehensions | Opt_GeneralizedNewtypeDeriving | Opt_RecursiveDo | Opt_PostfixOperators | Opt_TupleSections | Opt_PatternGuards | Opt_LiberalTypeSynonyms | Opt_RankNTypes | Opt_ImpredicativeTypes | Opt_TypeOperators | Opt_ExplicitNamespaces | Opt_PackageImports | Opt_ExplicitForAll | Opt_AlternativeLayoutRule | Opt_AlternativeLayoutRuleTransitional | Opt_DatatypeContexts | Opt_NondecreasingIndentation | Opt_RelaxedLayout | Opt_TraditionalRecordSyntax | Opt_LambdaCase | Opt_MultiWayIf | Opt_BinaryLiterals | Opt_NegativeLiterals | Opt_EmptyCase | Opt_PatternSynonyms | Opt_PartialTypeSignatures | Opt_NamedWildCards | Opt_StaticPointers deriving (Eq, Enum, Show) type SigOf = Map ModuleName Module getSigOf :: DynFlags -> ModuleName -> Maybe Module getSigOf dflags n = Map.lookup n (sigOf dflags) -- | Contains not only a collection of 'GeneralFlag's but also a plethora of -- information relating to the compilation of a single file or GHC session data DynFlags = DynFlags { ghcMode :: GhcMode, ghcLink :: GhcLink, hscTarget :: HscTarget, settings :: Settings, -- See Note [Signature parameters in TcGblEnv and DynFlags] sigOf :: SigOf, -- ^ Compiling an hs-boot against impl. verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels] optLevel :: Int, -- ^ Optimisation level simplPhases :: Int, -- ^ Number of simplifier phases maxSimplIterations :: Int, -- ^ Max simplifier iterations ruleCheck :: Maybe String, strictnessBefore :: [Int], -- ^ Additional demand analysis parMakeCount :: Maybe Int, -- ^ The number of modules to compile in parallel -- in --make mode, where Nothing ==> compile as -- many in parallel as there are CPUs. enableTimeStats :: Bool, -- ^ Enable RTS timing statistics? ghcHeapSize :: Maybe Int, -- ^ The heap size to set. maxRelevantBinds :: Maybe Int, -- ^ Maximum number of bindings from the type envt -- to show in type error messages simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types -- Not optional; otherwise ForceSpecConstr can diverge. liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating -- See CoreMonad.FloatOutSwitches historySize :: Int, cmdlineHcIncludes :: [String], -- ^ @\-\#includes@ importPaths :: [FilePath], mainModIs :: Module, mainFunIs :: Maybe String, reductionDepth :: IntWithInf, -- ^ Typechecker maximum stack depth solverIterations :: IntWithInf, -- ^ Number of iterations in the constraints solver -- Typically only 1 is needed thisPackage :: PackageKey, -- ^ name of package currently being compiled -- ways ways :: [Way], -- ^ Way flags from the command line buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof) rtsBuildTag :: String, -- ^ The RTS \"way\" -- For object splitting splitInfo :: Maybe (String,Int), -- paths etc. objectDir :: Maybe String, dylibInstallName :: Maybe String, hiDir :: Maybe String, stubDir :: Maybe String, dumpDir :: Maybe String, objectSuf :: String, hcSuf :: String, hiSuf :: String, canGenerateDynamicToo :: IORef Bool, dynObjectSuf :: String, dynHiSuf :: String, -- Packages.isDllName needs to know whether a call is within a -- single DLL or not. Normally it does this by seeing if the call -- is to the same package, but for the ghc package, we split the -- package between 2 DLLs. The dllSplit tells us which sets of -- modules are in which package. dllSplitFile :: Maybe FilePath, dllSplit :: Maybe [Set String], outputFile :: Maybe String, dynOutputFile :: Maybe String, outputHi :: Maybe String, dynLibLoader :: DynLibLoader, -- | This is set by 'DriverPipeline.runPipeline' based on where -- its output is going. dumpPrefix :: Maybe FilePath, -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'. -- Set by @-ddump-file-prefix@ dumpPrefixForce :: Maybe FilePath, ldInputs :: [Option], includePaths :: [String], libraryPaths :: [String], frameworkPaths :: [String], -- used on darwin only cmdlineFrameworks :: [String], -- ditto rtsOpts :: Maybe String, rtsOptsEnabled :: RtsOptsEnabled, rtsOptsSuggestions :: Bool, hpcDir :: String, -- ^ Path to store the .mix files -- Plugins pluginModNames :: [ModuleName], pluginModNameOpts :: [(ModuleName,String)], -- GHC API hooks hooks :: Hooks, -- For ghc -M depMakefile :: FilePath, depIncludePkgDeps :: Bool, depExcludeMods :: [ModuleName], depSuffixes :: [String], -- Package flags extraPkgConfs :: [PkgConfRef] -> [PkgConfRef], -- ^ The @-package-db@ flags given on the command line, in the order -- they appeared. packageFlags :: [PackageFlag], -- ^ The @-package@ and @-hide-package@ flags from the command-line packageEnv :: Maybe FilePath, -- ^ Filepath to the package environment file (if overriding default) -- Package state -- NB. do not modify this field, it is calculated by -- Packages.initPackages pkgDatabase :: Maybe [PackageConfig], pkgState :: PackageState, -- Temporary files -- These have to be IORefs, because the defaultCleanupHandler needs to -- know what to clean when an exception happens filesToClean :: IORef [FilePath], dirsToClean :: IORef (Map FilePath FilePath), filesToNotIntermediateClean :: IORef [FilePath], -- The next available suffix to uniquely name a temp file, updated atomically nextTempSuffix :: IORef Int, -- Names of files which were generated from -ddump-to-file; used to -- track which ones we need to truncate because it's our first run -- through generatedDumps :: IORef (Set FilePath), -- hsc dynamic flags dumpFlags :: IntSet, generalFlags :: IntSet, warningFlags :: IntSet, -- Don't change this without updating extensionFlags: language :: Maybe Language, -- | Safe Haskell mode safeHaskell :: SafeHaskellMode, safeInfer :: Bool, safeInferred :: Bool, -- We store the location of where some extension and flags were turned on so -- we can produce accurate error messages when Safe Haskell fails due to -- them. thOnLoc :: SrcSpan, newDerivOnLoc :: SrcSpan, overlapInstLoc :: SrcSpan, incoherentOnLoc :: SrcSpan, pkgTrustOnLoc :: SrcSpan, warnSafeOnLoc :: SrcSpan, warnUnsafeOnLoc :: SrcSpan, trustworthyOnLoc :: SrcSpan, -- Don't change this without updating extensionFlags: extensions :: [OnOff ExtensionFlag], -- extensionFlags should always be equal to -- flattenExtensionFlags language extensions extensionFlags :: IntSet, -- Unfolding control -- See Note [Discounts and thresholds] in CoreUnfold ufCreationThreshold :: Int, ufUseThreshold :: Int, ufFunAppDiscount :: Int, ufDictDiscount :: Int, ufKeenessFactor :: Float, ufDearOp :: Int, maxWorkerArgs :: Int, ghciHistSize :: Int, -- | MsgDoc output action: use "ErrUtils" instead of this if you can log_action :: LogAction, flushOut :: FlushOut, flushErr :: FlushErr, haddockOptions :: Maybe String, -- | GHCi scripts specified by -ghci-script, in reverse order ghciScripts :: [String], -- Output style options pprUserLength :: Int, pprCols :: Int, traceLevel :: Int, -- Standard level is 1. Less verbose is 0. useUnicode :: Bool, -- | what kind of {-# SCC #-} to add automatically profAuto :: ProfAuto, interactivePrint :: Maybe String, llvmVersion :: IORef Int, nextWrapperNum :: IORef (ModuleEnv Int), -- | Machine dependant flags (-m<blah> stuff) sseVersion :: Maybe SseVersion, avx :: Bool, avx2 :: Bool, avx512cd :: Bool, -- Enable AVX-512 Conflict Detection Instructions. avx512er :: Bool, -- Enable AVX-512 Exponential and Reciprocal Instructions. avx512f :: Bool, -- Enable AVX-512 instructions. avx512pf :: Bool, -- Enable AVX-512 PreFetch Instructions. -- | Run-time linker information (what options we need, etc.) rtldInfo :: IORef (Maybe LinkerInfo), -- | Run-time compiler information rtccInfo :: IORef (Maybe CompilerInfo), -- Constants used to control the amount of optimization done. -- | Max size, in bytes, of inline array allocations. maxInlineAllocSize :: Int, -- | Only inline memcpy if it generates no more than this many -- pseudo (roughly: Cmm) instructions. maxInlineMemcpyInsns :: Int, -- | Only inline memset if it generates no more than this many -- pseudo (roughly: Cmm) instructions. maxInlineMemsetInsns :: Int } class HasDynFlags m where getDynFlags :: m DynFlags class ContainsDynFlags t where extractDynFlags :: t -> DynFlags replaceDynFlags :: t -> DynFlags -> t data ProfAuto = NoProfAuto -- ^ no SCC annotations added | ProfAutoAll -- ^ top-level and nested functions are annotated | ProfAutoTop -- ^ top-level functions annotated only | ProfAutoExports -- ^ exported functions annotated only | ProfAutoCalls -- ^ annotate call-sites deriving (Eq,Enum) data Settings = Settings { sTargetPlatform :: Platform, -- Filled in by SysTools sGhcUsagePath :: FilePath, -- Filled in by SysTools sGhciUsagePath :: FilePath, -- ditto sTopDir :: FilePath, sTmpDir :: String, -- no trailing '/' sProgramName :: String, sProjectVersion :: String, -- You shouldn't need to look things up in rawSettings directly. -- They should have their own fields instead. sRawSettings :: [(String, String)], sExtraGccViaCFlags :: [String], sSystemPackageConfig :: FilePath, sLdSupportsCompactUnwind :: Bool, sLdSupportsBuildId :: Bool, sLdSupportsFilelist :: Bool, sLdIsGnuLd :: Bool, -- commands for particular phases sPgm_L :: String, sPgm_P :: (String,[Option]), sPgm_F :: String, sPgm_c :: (String,[Option]), sPgm_s :: (String,[Option]), sPgm_a :: (String,[Option]), sPgm_l :: (String,[Option]), sPgm_dll :: (String,[Option]), sPgm_T :: String, sPgm_sysman :: String, sPgm_windres :: String, sPgm_libtool :: String, sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler -- options for particular phases sOpt_L :: [String], sOpt_P :: [String], sOpt_F :: [String], sOpt_c :: [String], sOpt_a :: [String], sOpt_l :: [String], sOpt_windres :: [String], sOpt_lo :: [String], -- LLVM: llvm optimiser sOpt_lc :: [String], -- LLVM: llc static compiler sPlatformConstants :: PlatformConstants } targetPlatform :: DynFlags -> Platform targetPlatform dflags = sTargetPlatform (settings dflags) programName :: DynFlags -> String programName dflags = sProgramName (settings dflags) projectVersion :: DynFlags -> String projectVersion dflags = sProjectVersion (settings dflags) ghcUsagePath :: DynFlags -> FilePath ghcUsagePath dflags = sGhcUsagePath (settings dflags) ghciUsagePath :: DynFlags -> FilePath ghciUsagePath dflags = sGhciUsagePath (settings dflags) topDir :: DynFlags -> FilePath topDir dflags = sTopDir (settings dflags) tmpDir :: DynFlags -> String tmpDir dflags = sTmpDir (settings dflags) rawSettings :: DynFlags -> [(String, String)] rawSettings dflags = sRawSettings (settings dflags) extraGccViaCFlags :: DynFlags -> [String] extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags) systemPackageConfig :: DynFlags -> FilePath systemPackageConfig dflags = sSystemPackageConfig (settings dflags) pgm_L :: DynFlags -> String pgm_L dflags = sPgm_L (settings dflags) pgm_P :: DynFlags -> (String,[Option]) pgm_P dflags = sPgm_P (settings dflags) pgm_F :: DynFlags -> String pgm_F dflags = sPgm_F (settings dflags) pgm_c :: DynFlags -> (String,[Option]) pgm_c dflags = sPgm_c (settings dflags) pgm_s :: DynFlags -> (String,[Option]) pgm_s dflags = sPgm_s (settings dflags) pgm_a :: DynFlags -> (String,[Option]) pgm_a dflags = sPgm_a (settings dflags) pgm_l :: DynFlags -> (String,[Option]) pgm_l dflags = sPgm_l (settings dflags) pgm_dll :: DynFlags -> (String,[Option]) pgm_dll dflags = sPgm_dll (settings dflags) pgm_T :: DynFlags -> String pgm_T dflags = sPgm_T (settings dflags) pgm_sysman :: DynFlags -> String pgm_sysman dflags = sPgm_sysman (settings dflags) pgm_windres :: DynFlags -> String pgm_windres dflags = sPgm_windres (settings dflags) pgm_libtool :: DynFlags -> String pgm_libtool dflags = sPgm_libtool (settings dflags) pgm_lo :: DynFlags -> (String,[Option]) pgm_lo dflags = sPgm_lo (settings dflags) pgm_lc :: DynFlags -> (String,[Option]) pgm_lc dflags = sPgm_lc (settings dflags) opt_L :: DynFlags -> [String] opt_L dflags = sOpt_L (settings dflags) opt_P :: DynFlags -> [String] opt_P dflags = concatMap (wayOptP (targetPlatform dflags)) (ways dflags) ++ sOpt_P (settings dflags) opt_F :: DynFlags -> [String] opt_F dflags = sOpt_F (settings dflags) opt_c :: DynFlags -> [String] opt_c dflags = concatMap (wayOptc (targetPlatform dflags)) (ways dflags) ++ sOpt_c (settings dflags) opt_a :: DynFlags -> [String] opt_a dflags = sOpt_a (settings dflags) opt_l :: DynFlags -> [String] opt_l dflags = concatMap (wayOptl (targetPlatform dflags)) (ways dflags) ++ sOpt_l (settings dflags) opt_windres :: DynFlags -> [String] opt_windres dflags = sOpt_windres (settings dflags) opt_lo :: DynFlags -> [String] opt_lo dflags = sOpt_lo (settings dflags) opt_lc :: DynFlags -> [String] opt_lc dflags = sOpt_lc (settings dflags) -- | The directory for this version of ghc in the user's app directory -- (typically something like @~/.ghc/x86_64-linux-7.6.3@) -- versionedAppDir :: DynFlags -> IO FilePath versionedAppDir dflags = do appdir <- getAppUserDataDirectory (programName dflags) return $ appdir </> (TARGET_ARCH ++ '-':TARGET_OS ++ '-':projectVersion dflags) -- | The target code type of the compilation (if any). -- -- Whenever you change the target, also make sure to set 'ghcLink' to -- something sensible. -- -- 'HscNothing' can be used to avoid generating any output, however, note -- that: -- -- * If a program uses Template Haskell the typechecker may try to run code -- from an imported module. This will fail if no code has been generated -- for this module. You can use 'GHC.needsTemplateHaskell' to detect -- whether this might be the case and choose to either switch to a -- different target or avoid typechecking such modules. (The latter may be -- preferable for security reasons.) -- data HscTarget = HscC -- ^ Generate C code. | HscAsm -- ^ Generate assembly using the native code generator. | HscLlvm -- ^ Generate assembly using the llvm code generator. | HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory') | HscNothing -- ^ Don't generate any code. See notes above. deriving (Eq, Show) -- | Will this target result in an object file on the disk? isObjectTarget :: HscTarget -> Bool isObjectTarget HscC = True isObjectTarget HscAsm = True isObjectTarget HscLlvm = True isObjectTarget _ = False -- | Does this target retain *all* top-level bindings for a module, -- rather than just the exported bindings, in the TypeEnv and compiled -- code (if any)? In interpreted mode we do this, so that GHCi can -- call functions inside a module. In HscNothing mode we also do it, -- so that Haddock can get access to the GlobalRdrEnv for a module -- after typechecking it. targetRetainsAllBindings :: HscTarget -> Bool targetRetainsAllBindings HscInterpreted = True targetRetainsAllBindings HscNothing = True targetRetainsAllBindings _ = False -- | The 'GhcMode' tells us whether we're doing multi-module -- compilation (controlled via the "GHC" API) or one-shot -- (single-module) compilation. This makes a difference primarily to -- the "Finder": in one-shot mode we look for interface files for -- imported modules, but in multi-module mode we look for source files -- in order to check whether they need to be recompiled. data GhcMode = CompManager -- ^ @\-\-make@, GHCi, etc. | OneShot -- ^ @ghc -c Foo.hs@ | MkDepend -- ^ @ghc -M@, see "Finder" for why we need this deriving Eq instance Outputable GhcMode where ppr CompManager = ptext (sLit "CompManager") ppr OneShot = ptext (sLit "OneShot") ppr MkDepend = ptext (sLit "MkDepend") isOneShot :: GhcMode -> Bool isOneShot OneShot = True isOneShot _other = False -- | What to do in the link step, if there is one. data GhcLink = NoLink -- ^ Don't link at all | LinkBinary -- ^ Link object code into a binary | LinkInMemory -- ^ Use the in-memory dynamic linker (works for both -- bytecode and object code). | LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms) | LinkStaticLib -- ^ Link objects into a static lib deriving (Eq, Show) isNoLink :: GhcLink -> Bool isNoLink NoLink = True isNoLink _ = False -- | We accept flags which make packages visible, but how they select -- the package varies; this data type reflects what selection criterion -- is used. data PackageArg = PackageArg String -- ^ @-package@, by 'PackageName' | PackageIdArg String -- ^ @-package-id@, by 'SourcePackageId' | PackageKeyArg String -- ^ @-package-key@, by 'InstalledPackageId' deriving (Eq, Show) -- | Represents the renaming that may be associated with an exposed -- package, e.g. the @rns@ part of @-package "foo (rns)"@. -- -- Here are some example parsings of the package flags (where -- a string literal is punned to be a 'ModuleName': -- -- * @-package foo@ is @ModRenaming True []@ -- * @-package foo ()@ is @ModRenaming False []@ -- * @-package foo (A)@ is @ModRenaming False [("A", "A")]@ -- * @-package foo (A as B)@ is @ModRenaming False [("A", "B")]@ -- * @-package foo with (A as B)@ is @ModRenaming True [("A", "B")]@ data ModRenaming = ModRenaming { modRenamingWithImplicit :: Bool, -- ^ Bring all exposed modules into scope? modRenamings :: [(ModuleName, ModuleName)] -- ^ Bring module @m@ into scope -- under name @n@. } deriving (Eq) -- | Flags for manipulating packages. data PackageFlag = ExposePackage PackageArg ModRenaming -- ^ @-package@, @-package-id@ -- and @-package-key@ | HidePackage String -- ^ @-hide-package@ | IgnorePackage String -- ^ @-ignore-package@ | TrustPackage String -- ^ @-trust-package@ | DistrustPackage String -- ^ @-distrust-package@ deriving (Eq) defaultHscTarget :: Platform -> HscTarget defaultHscTarget = defaultObjectTarget -- | The 'HscTarget' value corresponding to the default way to create -- object files on the current platform. defaultObjectTarget :: Platform -> HscTarget defaultObjectTarget platform | platformUnregisterised platform = HscC | cGhcWithNativeCodeGen == "YES" = HscAsm | otherwise = HscLlvm tablesNextToCode :: DynFlags -> Bool tablesNextToCode dflags = mkTablesNextToCode (platformUnregisterised (targetPlatform dflags)) -- Determines whether we will be compiling -- info tables that reside just before the entry code, or with an -- indirection to the entry code. See TABLES_NEXT_TO_CODE in -- includes/rts/storage/InfoTables.h. mkTablesNextToCode :: Bool -> Bool mkTablesNextToCode unregisterised = not unregisterised && cGhcEnableTablesNextToCode == "YES" data DynLibLoader = Deployable | SystemDependent deriving Eq data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll deriving (Show) ----------------------------------------------------------------------------- -- Ways -- The central concept of a "way" is that all objects in a given -- program must be compiled in the same "way". Certain options change -- parameters of the virtual machine, eg. profiling adds an extra word -- to the object header, so profiling objects cannot be linked with -- non-profiling objects. -- After parsing the command-line options, we determine which "way" we -- are building - this might be a combination way, eg. profiling+threaded. -- We then find the "build-tag" associated with this way, and this -- becomes the suffix used to find .hi files and libraries used in -- this compilation. data Way = WayCustom String -- for GHC API clients building custom variants | WayThreaded | WayDebug | WayProf | WayEventLog | WayDyn deriving (Eq, Ord, Show) allowed_combination :: [Way] -> Bool allowed_combination way = and [ x `allowedWith` y | x <- way, y <- way, x < y ] where -- Note ordering in these tests: the left argument is -- <= the right argument, according to the Ord instance -- on Way above. -- dyn is allowed with everything _ `allowedWith` WayDyn = True WayDyn `allowedWith` _ = True -- debug is allowed with everything _ `allowedWith` WayDebug = True WayDebug `allowedWith` _ = True (WayCustom {}) `allowedWith` _ = True WayThreaded `allowedWith` WayProf = True WayThreaded `allowedWith` WayEventLog = True _ `allowedWith` _ = False mkBuildTag :: [Way] -> String mkBuildTag ways = concat (intersperse "_" (map wayTag ways)) wayTag :: Way -> String wayTag (WayCustom xs) = xs wayTag WayThreaded = "thr" wayTag WayDebug = "debug" wayTag WayDyn = "dyn" wayTag WayProf = "p" wayTag WayEventLog = "l" wayRTSOnly :: Way -> Bool wayRTSOnly (WayCustom {}) = False wayRTSOnly WayThreaded = True wayRTSOnly WayDebug = True wayRTSOnly WayDyn = False wayRTSOnly WayProf = False wayRTSOnly WayEventLog = True wayDesc :: Way -> String wayDesc (WayCustom xs) = xs wayDesc WayThreaded = "Threaded" wayDesc WayDebug = "Debug" wayDesc WayDyn = "Dynamic" wayDesc WayProf = "Profiling" wayDesc WayEventLog = "RTS Event Logging" -- Turn these flags on when enabling this way wayGeneralFlags :: Platform -> Way -> [GeneralFlag] wayGeneralFlags _ (WayCustom {}) = [] wayGeneralFlags _ WayThreaded = [] wayGeneralFlags _ WayDebug = [] wayGeneralFlags _ WayDyn = [Opt_PIC] -- We could get away without adding -fPIC when compiling the -- modules of a program that is to be linked with -dynamic; the -- program itself does not need to be position-independent, only -- the libraries need to be. HOWEVER, GHCi links objects into a -- .so before loading the .so using the system linker. Since only -- PIC objects can be linked into a .so, we have to compile even -- modules of the main program with -fPIC when using -dynamic. wayGeneralFlags _ WayProf = [Opt_SccProfilingOn] wayGeneralFlags _ WayEventLog = [] -- Turn these flags off when enabling this way wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag] wayUnsetGeneralFlags _ (WayCustom {}) = [] wayUnsetGeneralFlags _ WayThreaded = [] wayUnsetGeneralFlags _ WayDebug = [] wayUnsetGeneralFlags _ WayDyn = [-- There's no point splitting objects -- when we're going to be dynamically -- linking. Plus it breaks compilation -- on OSX x86. Opt_SplitObjs] wayUnsetGeneralFlags _ WayProf = [] wayUnsetGeneralFlags _ WayEventLog = [] wayExtras :: Platform -> Way -> DynFlags -> DynFlags wayExtras _ (WayCustom {}) dflags = dflags wayExtras _ WayThreaded dflags = dflags wayExtras _ WayDebug dflags = dflags wayExtras _ WayDyn dflags = dflags wayExtras _ WayProf dflags = dflags wayExtras _ WayEventLog dflags = dflags wayOptc :: Platform -> Way -> [String] wayOptc _ (WayCustom {}) = [] wayOptc platform WayThreaded = case platformOS platform of OSOpenBSD -> ["-pthread"] OSNetBSD -> ["-pthread"] _ -> [] wayOptc _ WayDebug = [] wayOptc _ WayDyn = [] wayOptc _ WayProf = ["-DPROFILING"] wayOptc _ WayEventLog = ["-DTRACING"] wayOptl :: Platform -> Way -> [String] wayOptl _ (WayCustom {}) = [] wayOptl platform WayThreaded = case platformOS platform of -- FreeBSD's default threading library is the KSE-based M:N libpthread, -- which GHC has some problems with. It's currently not clear whether -- the problems are our fault or theirs, but it seems that using the -- alternative 1:1 threading library libthr works around it: OSFreeBSD -> ["-lthr"] OSOpenBSD -> ["-pthread"] OSNetBSD -> ["-pthread"] _ -> [] wayOptl _ WayDebug = [] wayOptl _ WayDyn = [] wayOptl _ WayProf = [] wayOptl _ WayEventLog = [] wayOptP :: Platform -> Way -> [String] wayOptP _ (WayCustom {}) = [] wayOptP _ WayThreaded = [] wayOptP _ WayDebug = [] wayOptP _ WayDyn = [] wayOptP _ WayProf = ["-DPROFILING"] wayOptP _ WayEventLog = ["-DTRACING"] whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m () whenGeneratingDynamicToo dflags f = ifGeneratingDynamicToo dflags f (return ()) ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a ifGeneratingDynamicToo dflags f g = generateDynamicTooConditional dflags f g g whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m () whenCannotGenerateDynamicToo dflags f = ifCannotGenerateDynamicToo dflags f (return ()) ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a ifCannotGenerateDynamicToo dflags f g = generateDynamicTooConditional dflags g f g generateDynamicTooConditional :: MonadIO m => DynFlags -> m a -> m a -> m a -> m a generateDynamicTooConditional dflags canGen cannotGen notTryingToGen = if gopt Opt_BuildDynamicToo dflags then do let ref = canGenerateDynamicToo dflags b <- liftIO $ readIORef ref if b then canGen else cannotGen else notTryingToGen dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags dynamicTooMkDynamicDynFlags dflags0 = let dflags1 = addWay' WayDyn dflags0 dflags2 = dflags1 { outputFile = dynOutputFile dflags1, hiSuf = dynHiSuf dflags1, objectSuf = dynObjectSuf dflags1 } dflags3 = updateWays dflags2 dflags4 = gopt_unset dflags3 Opt_BuildDynamicToo in dflags4 ----------------------------------------------------------------------------- -- | Used by 'GHC.runGhc' to partially initialize a new 'DynFlags' value initDynFlags :: DynFlags -> IO DynFlags initDynFlags dflags = do let -- We can't build with dynamic-too on Windows, as labels before -- the fork point are different depending on whether we are -- building dynamically or not. platformCanGenerateDynamicToo = platformOS (targetPlatform dflags) /= OSMinGW32 refCanGenerateDynamicToo <- newIORef platformCanGenerateDynamicToo refNextTempSuffix <- newIORef 0 refFilesToClean <- newIORef [] refDirsToClean <- newIORef Map.empty refFilesToNotIntermediateClean <- newIORef [] refGeneratedDumps <- newIORef Set.empty refLlvmVersion <- newIORef 28 refRtldInfo <- newIORef Nothing refRtccInfo <- newIORef Nothing wrapperNum <- newIORef emptyModuleEnv canUseUnicode <- do let enc = localeEncoding str = "‘’" (withCString enc str $ \cstr -> do str' <- peekCString enc cstr return (str == str')) `catchIOError` \_ -> return False return dflags{ canGenerateDynamicToo = refCanGenerateDynamicToo, nextTempSuffix = refNextTempSuffix, filesToClean = refFilesToClean, dirsToClean = refDirsToClean, filesToNotIntermediateClean = refFilesToNotIntermediateClean, generatedDumps = refGeneratedDumps, llvmVersion = refLlvmVersion, nextWrapperNum = wrapperNum, useUnicode = canUseUnicode, rtldInfo = refRtldInfo, rtccInfo = refRtccInfo } -- | The normal 'DynFlags'. Note that they are not suitable for use in this form -- and must be fully initialized by 'GHC.runGhc' first. defaultDynFlags :: Settings -> DynFlags defaultDynFlags mySettings = -- See Note [Updating flag description in the User's Guide] DynFlags { ghcMode = CompManager, ghcLink = LinkBinary, hscTarget = defaultHscTarget (sTargetPlatform mySettings), sigOf = Map.empty, verbosity = 0, optLevel = 0, simplPhases = 2, maxSimplIterations = 4, ruleCheck = Nothing, maxRelevantBinds = Just 6, simplTickFactor = 100, specConstrThreshold = Just 2000, specConstrCount = Just 3, specConstrRecursive = 3, liberateCaseThreshold = Just 2000, floatLamArgs = Just 0, -- Default: float only if no fvs historySize = 20, strictnessBefore = [], parMakeCount = Just 1, enableTimeStats = False, ghcHeapSize = Nothing, cmdlineHcIncludes = [], importPaths = ["."], mainModIs = mAIN, mainFunIs = Nothing, reductionDepth = treatZeroAsInf mAX_REDUCTION_DEPTH, solverIterations = treatZeroAsInf mAX_SOLVER_ITERATIONS, thisPackage = mainPackageKey, objectDir = Nothing, dylibInstallName = Nothing, hiDir = Nothing, stubDir = Nothing, dumpDir = Nothing, objectSuf = phaseInputExt StopLn, hcSuf = phaseInputExt HCc, hiSuf = "hi", canGenerateDynamicToo = panic "defaultDynFlags: No canGenerateDynamicToo", dynObjectSuf = "dyn_" ++ phaseInputExt StopLn, dynHiSuf = "dyn_hi", dllSplitFile = Nothing, dllSplit = Nothing, pluginModNames = [], pluginModNameOpts = [], hooks = emptyHooks, outputFile = Nothing, dynOutputFile = Nothing, outputHi = Nothing, dynLibLoader = SystemDependent, dumpPrefix = Nothing, dumpPrefixForce = Nothing, ldInputs = [], includePaths = [], libraryPaths = [], frameworkPaths = [], cmdlineFrameworks = [], rtsOpts = Nothing, rtsOptsEnabled = RtsOptsSafeOnly, rtsOptsSuggestions = True, hpcDir = ".hpc", extraPkgConfs = id, packageFlags = [], packageEnv = Nothing, pkgDatabase = Nothing, -- This gets filled in with GHC.setSessionDynFlags pkgState = emptyPackageState, ways = defaultWays mySettings, buildTag = mkBuildTag (defaultWays mySettings), rtsBuildTag = mkBuildTag (defaultWays mySettings), splitInfo = Nothing, settings = mySettings, -- ghc -M values depMakefile = "Makefile", depIncludePkgDeps = False, depExcludeMods = [], depSuffixes = [], -- end of ghc -M values nextTempSuffix = panic "defaultDynFlags: No nextTempSuffix", filesToClean = panic "defaultDynFlags: No filesToClean", dirsToClean = panic "defaultDynFlags: No dirsToClean", filesToNotIntermediateClean = panic "defaultDynFlags: No filesToNotIntermediateClean", generatedDumps = panic "defaultDynFlags: No generatedDumps", haddockOptions = Nothing, dumpFlags = IntSet.empty, generalFlags = IntSet.fromList (map fromEnum (defaultFlags mySettings)), warningFlags = IntSet.fromList (map fromEnum standardWarnings), ghciScripts = [], language = Nothing, safeHaskell = Sf_None, safeInfer = True, safeInferred = True, thOnLoc = noSrcSpan, newDerivOnLoc = noSrcSpan, overlapInstLoc = noSrcSpan, incoherentOnLoc = noSrcSpan, pkgTrustOnLoc = noSrcSpan, warnSafeOnLoc = noSrcSpan, warnUnsafeOnLoc = noSrcSpan, trustworthyOnLoc = noSrcSpan, extensions = [], extensionFlags = flattenExtensionFlags Nothing [], -- The ufCreationThreshold threshold must be reasonably high to -- take account of possible discounts. -- E.g. 450 is not enough in 'fulsom' for Interval.sqr to inline -- into Csg.calc (The unfolding for sqr never makes it into the -- interface file.) ufCreationThreshold = 750, ufUseThreshold = 60, ufFunAppDiscount = 60, -- Be fairly keen to inline a fuction if that means -- we'll be able to pick the right method from a dictionary ufDictDiscount = 30, ufKeenessFactor = 1.5, ufDearOp = 40, maxWorkerArgs = 10, ghciHistSize = 50, -- keep a log of length 50 by default log_action = defaultLogAction, flushOut = defaultFlushOut, flushErr = defaultFlushErr, pprUserLength = 5, pprCols = 100, useUnicode = False, traceLevel = 1, profAuto = NoProfAuto, llvmVersion = panic "defaultDynFlags: No llvmVersion", interactivePrint = Nothing, nextWrapperNum = panic "defaultDynFlags: No nextWrapperNum", sseVersion = Nothing, avx = False, avx2 = False, avx512cd = False, avx512er = False, avx512f = False, avx512pf = False, rtldInfo = panic "defaultDynFlags: no rtldInfo", rtccInfo = panic "defaultDynFlags: no rtccInfo", maxInlineAllocSize = 128, maxInlineMemcpyInsns = 32, maxInlineMemsetInsns = 32 } defaultWays :: Settings -> [Way] defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings) then [WayDyn] else [] interpWays :: [Way] interpWays = if dynamicGhc then [WayDyn] else [] -------------------------------------------------------------------------- type FatalMessager = String -> IO () type LogAction = DynFlags -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO () defaultFatalMessager :: FatalMessager defaultFatalMessager = hPutStrLn stderr defaultLogAction :: LogAction defaultLogAction dflags severity srcSpan style msg = case severity of SevOutput -> printSDoc msg style SevDump -> printSDoc (msg $$ blankLine) style SevInteractive -> putStrSDoc msg style SevInfo -> printErrs msg style SevFatal -> printErrs msg style _ -> do hPutChar stderr '\n' printErrs (mkLocMessage severity srcSpan msg) style -- careful (#2302): printErrs prints in UTF-8, -- whereas converting to string first and using -- hPutStr would just emit the low 8 bits of -- each unicode char. where printSDoc = defaultLogActionHPrintDoc dflags stdout printErrs = defaultLogActionHPrintDoc dflags stderr putStrSDoc = defaultLogActionHPutStrDoc dflags stdout defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO () defaultLogActionHPrintDoc dflags h d sty = defaultLogActionHPutStrDoc dflags h (d $$ text "") sty -- Adds a newline defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO () defaultLogActionHPutStrDoc dflags h d sty = Pretty.printDoc_ Pretty.PageMode (pprCols dflags) h doc where -- Don't add a newline at the end, so that successive -- calls to this log-action can output all on the same line doc = runSDoc d (initSDocContext dflags sty) newtype FlushOut = FlushOut (IO ()) defaultFlushOut :: FlushOut defaultFlushOut = FlushOut $ hFlush stdout newtype FlushErr = FlushErr (IO ()) defaultFlushErr :: FlushErr defaultFlushErr = FlushErr $ hFlush stderr {- Note [Verbosity levels] ~~~~~~~~~~~~~~~~~~~~~~~ 0 | print errors & warnings only 1 | minimal verbosity: print "compiling M ... done." for each module. 2 | equivalent to -dshow-passes 3 | equivalent to existing "ghc -v" 4 | "ghc -v -ddump-most" 5 | "ghc -v -ddump-all" -} data OnOff a = On a | Off a -- OnOffs accumulate in reverse order, so we use foldr in order to -- process them in the right order flattenExtensionFlags :: Maybe Language -> [OnOff ExtensionFlag] -> IntSet flattenExtensionFlags ml = foldr f defaultExtensionFlags where f (On f) flags = IntSet.insert (fromEnum f) flags f (Off f) flags = IntSet.delete (fromEnum f) flags defaultExtensionFlags = IntSet.fromList (map fromEnum (languageExtensions ml)) languageExtensions :: Maybe Language -> [ExtensionFlag] languageExtensions Nothing -- Nothing => the default case = Opt_NondecreasingIndentation -- This has been on by default for some time : delete Opt_DatatypeContexts -- The Haskell' committee decided to -- remove datatype contexts from the -- language: -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html (languageExtensions (Just Haskell2010)) -- NB: MonoPatBinds is no longer the default languageExtensions (Just Haskell98) = [Opt_ImplicitPrelude, Opt_MonomorphismRestriction, Opt_NPlusKPatterns, Opt_DatatypeContexts, Opt_TraditionalRecordSyntax, Opt_NondecreasingIndentation -- strictly speaking non-standard, but we always had this -- on implicitly before the option was added in 7.1, and -- turning it off breaks code, so we're keeping it on for -- backwards compatibility. Cabal uses -XHaskell98 by -- default unless you specify another language. ] languageExtensions (Just Haskell2010) = [Opt_ImplicitPrelude, Opt_MonomorphismRestriction, Opt_DatatypeContexts, Opt_TraditionalRecordSyntax, Opt_EmptyDataDecls, Opt_ForeignFunctionInterface, Opt_PatternGuards, Opt_DoAndIfThenElse, Opt_RelaxedPolyRec] -- | Test whether a 'DumpFlag' is set dopt :: DumpFlag -> DynFlags -> Bool dopt f dflags = (fromEnum f `IntSet.member` dumpFlags dflags) || (verbosity dflags >= 4 && enableIfVerbose f) where enableIfVerbose Opt_D_dump_tc_trace = False enableIfVerbose Opt_D_dump_rn_trace = False enableIfVerbose Opt_D_dump_cs_trace = False enableIfVerbose Opt_D_dump_if_trace = False enableIfVerbose Opt_D_dump_vt_trace = False enableIfVerbose Opt_D_dump_tc = False enableIfVerbose Opt_D_dump_rn = False enableIfVerbose Opt_D_dump_rn_stats = False enableIfVerbose Opt_D_dump_hi_diffs = False enableIfVerbose Opt_D_verbose_core2core = False enableIfVerbose Opt_D_verbose_stg2stg = False enableIfVerbose Opt_D_dump_splices = False enableIfVerbose Opt_D_th_dec_file = False enableIfVerbose Opt_D_dump_rule_firings = False enableIfVerbose Opt_D_dump_rule_rewrites = False enableIfVerbose Opt_D_dump_simpl_trace = False enableIfVerbose Opt_D_dump_rtti = False enableIfVerbose Opt_D_dump_inlinings = False enableIfVerbose Opt_D_dump_core_stats = False enableIfVerbose Opt_D_dump_asm_stats = False enableIfVerbose Opt_D_dump_types = False enableIfVerbose Opt_D_dump_simpl_iterations = False enableIfVerbose Opt_D_dump_ticked = False enableIfVerbose Opt_D_dump_view_pattern_commoning = False enableIfVerbose Opt_D_dump_mod_cycles = False enableIfVerbose Opt_D_dump_mod_map = False enableIfVerbose _ = True -- | Set a 'DumpFlag' dopt_set :: DynFlags -> DumpFlag -> DynFlags dopt_set dfs f = dfs{ dumpFlags = IntSet.insert (fromEnum f) (dumpFlags dfs) } -- | Unset a 'DumpFlag' dopt_unset :: DynFlags -> DumpFlag -> DynFlags dopt_unset dfs f = dfs{ dumpFlags = IntSet.delete (fromEnum f) (dumpFlags dfs) } -- | Test whether a 'GeneralFlag' is set gopt :: GeneralFlag -> DynFlags -> Bool gopt f dflags = fromEnum f `IntSet.member` generalFlags dflags -- | Set a 'GeneralFlag' gopt_set :: DynFlags -> GeneralFlag -> DynFlags gopt_set dfs f = dfs{ generalFlags = IntSet.insert (fromEnum f) (generalFlags dfs) } -- | Unset a 'GeneralFlag' gopt_unset :: DynFlags -> GeneralFlag -> DynFlags gopt_unset dfs f = dfs{ generalFlags = IntSet.delete (fromEnum f) (generalFlags dfs) } -- | Test whether a 'WarningFlag' is set wopt :: WarningFlag -> DynFlags -> Bool wopt f dflags = fromEnum f `IntSet.member` warningFlags dflags -- | Set a 'WarningFlag' wopt_set :: DynFlags -> WarningFlag -> DynFlags wopt_set dfs f = dfs{ warningFlags = IntSet.insert (fromEnum f) (warningFlags dfs) } -- | Unset a 'WarningFlag' wopt_unset :: DynFlags -> WarningFlag -> DynFlags wopt_unset dfs f = dfs{ warningFlags = IntSet.delete (fromEnum f) (warningFlags dfs) } -- | Test whether a 'ExtensionFlag' is set xopt :: ExtensionFlag -> DynFlags -> Bool xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags -- | Set a 'ExtensionFlag' xopt_set :: DynFlags -> ExtensionFlag -> DynFlags xopt_set dfs f = let onoffs = On f : extensions dfs in dfs { extensions = onoffs, extensionFlags = flattenExtensionFlags (language dfs) onoffs } -- | Unset a 'ExtensionFlag' xopt_unset :: DynFlags -> ExtensionFlag -> DynFlags xopt_unset dfs f = let onoffs = Off f : extensions dfs in dfs { extensions = onoffs, extensionFlags = flattenExtensionFlags (language dfs) onoffs } lang_set :: DynFlags -> Maybe Language -> DynFlags lang_set dflags lang = dflags { language = lang, extensionFlags = flattenExtensionFlags lang (extensions dflags) } -- | Check whether to use unicode syntax for output useUnicodeSyntax :: DynFlags -> Bool useUnicodeSyntax = gopt Opt_PrintUnicodeSyntax -- | Set the Haskell language standard to use setLanguage :: Language -> DynP () setLanguage l = upd (`lang_set` Just l) -- | Some modules have dependencies on others through the DynFlags rather than textual imports dynFlagDependencies :: DynFlags -> [ModuleName] dynFlagDependencies = pluginModNames -- | Is the -fpackage-trust mode on packageTrustOn :: DynFlags -> Bool packageTrustOn = gopt Opt_PackageTrust -- | Is Safe Haskell on in some way (including inference mode) safeHaskellOn :: DynFlags -> Bool safeHaskellOn dflags = safeHaskell dflags /= Sf_None || safeInferOn dflags -- | Is the Safe Haskell safe language in use safeLanguageOn :: DynFlags -> Bool safeLanguageOn dflags = safeHaskell dflags == Sf_Safe -- | Is the Safe Haskell safe inference mode active safeInferOn :: DynFlags -> Bool safeInferOn = safeInfer -- | Test if Safe Imports are on in some form safeImportsOn :: DynFlags -> Bool safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe || safeHaskell dflags == Sf_Trustworthy || safeHaskell dflags == Sf_Safe -- | Set a 'Safe Haskell' flag setSafeHaskell :: SafeHaskellMode -> DynP () setSafeHaskell s = updM f where f dfs = do let sf = safeHaskell dfs safeM <- combineSafeFlags sf s case s of Sf_Safe -> return $ dfs { safeHaskell = safeM, safeInfer = False } -- leave safe inferrence on in Trustworthy mode so we can warn -- if it could have been inferred safe. Sf_Trustworthy -> do l <- getCurLoc return $ dfs { safeHaskell = safeM, trustworthyOnLoc = l } -- leave safe inference on in Unsafe mode as well. _ -> return $ dfs { safeHaskell = safeM } -- | Are all direct imports required to be safe for this Safe Haskell mode? -- Direct imports are when the code explicitly imports a module safeDirectImpsReq :: DynFlags -> Bool safeDirectImpsReq d = safeLanguageOn d -- | Are all implicit imports required to be safe for this Safe Haskell mode? -- Implicit imports are things in the prelude. e.g System.IO when print is used. safeImplicitImpsReq :: DynFlags -> Bool safeImplicitImpsReq d = safeLanguageOn d -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags. -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't -- want to export this functionality from the module but do want to export the -- type constructors. combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode combineSafeFlags a b | a == Sf_None = return b | b == Sf_None = return a | a == b = return a | otherwise = addErr errm >> return (panic errm) where errm = "Incompatible Safe Haskell flags! (" ++ show a ++ ", " ++ show b ++ ")" -- | A list of unsafe flags under Safe Haskell. Tuple elements are: -- * name of the flag -- * function to get srcspan that enabled the flag -- * function to test if the flag is on -- * function to turn the flag off unsafeFlags, unsafeFlagsForInfer :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)] unsafeFlags = [ ("-XGeneralizedNewtypeDeriving", newDerivOnLoc, xopt Opt_GeneralizedNewtypeDeriving, flip xopt_unset Opt_GeneralizedNewtypeDeriving) , ("-XTemplateHaskell", thOnLoc, xopt Opt_TemplateHaskell, flip xopt_unset Opt_TemplateHaskell) ] unsafeFlagsForInfer = unsafeFlags -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors -> [a] -- ^ Correctly ordered extracted options getOpts dflags opts = reverse (opts dflags) -- We add to the options from the front, so we need to reverse the list -- | Gets the verbosity flag for the current verbosity level. This is fed to -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included getVerbFlags :: DynFlags -> [String] getVerbFlags dflags | verbosity dflags >= 4 = ["-v"] | otherwise = [] setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir, setDynObjectSuf, setDynHiSuf, setDylibInstallName, setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode, setPgmP, addOptl, addOptc, addOptP, addCmdlineFramework, addHaddockOpts, addGhciScript, setInteractivePrint :: String -> DynFlags -> DynFlags setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce :: Maybe String -> DynFlags -> DynFlags setObjectDir f d = d{ objectDir = Just f} setHiDir f d = d{ hiDir = Just f} setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d } -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file -- \#included from the .hc file when compiling via C (i.e. unregisterised -- builds). setDumpDir f d = d{ dumpDir = Just f} setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f setDylibInstallName f d = d{ dylibInstallName = Just f} setObjectSuf f d = d{ objectSuf = f} setDynObjectSuf f d = d{ dynObjectSuf = f} setHiSuf f d = d{ hiSuf = f} setDynHiSuf f d = d{ dynHiSuf = f} setHcSuf f d = d{ hcSuf = f} setOutputFile f d = d{ outputFile = f} setDynOutputFile f d = d{ dynOutputFile = f} setOutputHi f d = d{ outputHi = f} parseSigOf :: String -> SigOf parseSigOf str = case filter ((=="").snd) (readP_to_S parse str) of [(r, "")] -> r _ -> throwGhcException $ CmdLineError ("Can't parse -sig-of: " ++ str) where parse = Map.fromList <$> sepBy parseEntry (R.char ',') parseEntry = do n <- tok $ parseModuleName -- ToDo: deprecate this 'is' syntax? tok $ ((string "is" >> return ()) +++ (R.char '=' >> return ())) m <- tok $ parseModule return (n, m) parseModule = do pk <- munch1 (\c -> isAlphaNum c || c `elem` "-_") _ <- R.char ':' m <- parseModuleName return (mkModule (stringToPackageKey pk) m) tok m = skipSpaces >> m setSigOf :: String -> DynFlags -> DynFlags setSigOf s d = d { sigOf = parseSigOf s } addPluginModuleName :: String -> DynFlags -> DynFlags addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) } addPluginModuleNameOption :: String -> DynFlags -> DynFlags addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) } where (m, rest) = break (== ':') optflag option = case rest of [] -> "" -- should probably signal an error (_:plug_opt) -> plug_opt -- ignore the ':' from break parseDynLibLoaderMode f d = case splitAt 8 f of ("deploy", "") -> d{ dynLibLoader = Deployable } ("sysdep", "") -> d{ dynLibLoader = SystemDependent } _ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f)) setDumpPrefixForce f d = d { dumpPrefixForce = f} -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"] -- Config.hs should really use Option. setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)}) addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s}) addOptc f = alterSettings (\s -> s { sOpt_c = f : sOpt_c s}) addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s}) setDepMakefile :: FilePath -> DynFlags -> DynFlags setDepMakefile f d = d { depMakefile = f } setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags setDepIncludePkgDeps b d = d { depIncludePkgDeps = b } addDepExcludeMod :: String -> DynFlags -> DynFlags addDepExcludeMod m d = d { depExcludeMods = mkModuleName m : depExcludeMods d } addDepSuffix :: FilePath -> DynFlags -> DynFlags addDepSuffix s d = d { depSuffixes = s : depSuffixes d } addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d} addHaddockOpts f d = d{ haddockOptions = Just f} addGhciScript f d = d{ ghciScripts = f : ghciScripts d} setInteractivePrint f d = d{ interactivePrint = Just f} -- ----------------------------------------------------------------------------- -- Command-line options -- | When invoking external tools as part of the compilation pipeline, we -- pass these a sequence of options on the command-line. Rather than -- just using a list of Strings, we use a type that allows us to distinguish -- between filepaths and 'other stuff'. The reason for this is that -- this type gives us a handle on transforming filenames, and filenames only, -- to whatever format they're expected to be on a particular platform. data Option = FileOption -- an entry that _contains_ filename(s) / filepaths. String -- a non-filepath prefix that shouldn't be -- transformed (e.g., "/out=") String -- the filepath/filename portion | Option String deriving ( Eq ) showOpt :: Option -> String showOpt (FileOption pre f) = pre ++ f showOpt (Option s) = s ----------------------------------------------------------------------------- -- Setting the optimisation level updOptLevel :: Int -> DynFlags -> DynFlags -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level updOptLevel n dfs = dfs2{ optLevel = final_n } where final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2 dfs1 = foldr (flip gopt_unset) dfs remove_gopts dfs2 = foldr (flip gopt_set) dfs1 extra_gopts extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ] remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ] -- ----------------------------------------------------------------------------- -- StgToDo: abstraction of stg-to-stg passes to run. data StgToDo = StgDoMassageForProfiling -- should be (next to) last -- There's also setStgVarInfo, but its absolute "lastness" -- is so critical that it is hardwired in (no flag). | D_stg_stats getStgToDo :: DynFlags -> [StgToDo] getStgToDo dflags = todo2 where stg_stats = gopt Opt_StgStats dflags todo1 = if stg_stats then [D_stg_stats] else [] todo2 | WayProf `elem` ways dflags = StgDoMassageForProfiling : todo1 | otherwise = todo1 {- ********************************************************************** %* * DynFlags parser %* * %********************************************************************* -} -- ----------------------------------------------------------------------------- -- Parsing the dynamic flags. -- | Parse dynamic flags from a list of command line arguments. Returns the -- the parsed 'DynFlags', the left-over arguments, and a list of warnings. -- Throws a 'UsageError' if errors occurred during parsing (such as unknown -- flags or missing arguments). parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String] -> m (DynFlags, [Located String], [Located String]) -- ^ Updated 'DynFlags', left-over arguments, and -- list of warnings. parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db). -- Used to parse flags set in a modules pragma. parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String] -> m (DynFlags, [Located String], [Located String]) -- ^ Updated 'DynFlags', left-over arguments, and -- list of warnings. parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False -- | Parses the dynamically set flags for GHC. This is the most general form of -- the dynamic flag parser that the other methods simply wrap. It allows -- saying which flags are valid flags and indicating if we are parsing -- arguments from the command line or from a file pragma. parseDynamicFlagsFull :: MonadIO m => [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against -> Bool -- ^ are the arguments from the command line? -> DynFlags -- ^ current dynamic flags -> [Located String] -- ^ arguments to parse -> m (DynFlags, [Located String], [Located String]) parseDynamicFlagsFull activeFlags cmdline dflags0 args = do let ((leftover, errs, warns), dflags1) = runCmdLine (processArgs activeFlags args) dflags0 -- See Note [Handling errors when parsing commandline flags] unless (null errs) $ liftIO $ throwGhcExceptionIO $ errorsToGhcException . map (showPpr dflags0 . getLoc &&& unLoc) $ errs -- check for disabled flags in safe haskell let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1 dflags3 = updateWays dflags2 theWays = ways dflags3 unless (allowed_combination theWays) $ liftIO $ throwGhcExceptionIO (CmdLineError ("combination not supported: " ++ intercalate "/" (map wayDesc theWays))) let chooseOutput | isJust (outputFile dflags3) -- Only iff user specified -o ... , not (isJust (dynOutputFile dflags3)) -- but not -dyno = return $ dflags3 { dynOutputFile = Just $ dynOut (fromJust $ outputFile dflags3) } | otherwise = return dflags3 where dynOut = flip addExtension (dynObjectSuf dflags3) . dropExtension dflags4 <- ifGeneratingDynamicToo dflags3 chooseOutput (return dflags3) let (dflags5, consistency_warnings) = makeDynFlagsConsistent dflags4 dflags6 <- case dllSplitFile dflags5 of Nothing -> return (dflags5 { dllSplit = Nothing }) Just f -> case dllSplit dflags5 of Just _ -> -- If dllSplit is out of date then it would have -- been set to Nothing. As it's a Just, it must be -- up-to-date. return dflags5 Nothing -> do xs <- liftIO $ readFile f let ss = map (Set.fromList . words) (lines xs) return $ dflags5 { dllSplit = Just ss } -- Set timer stats & heap size when (enableTimeStats dflags6) $ liftIO enableTimingStats case (ghcHeapSize dflags6) of Just x -> liftIO (setHeapSize x) _ -> return () liftIO $ setUnsafeGlobalDynFlags dflags6 return (dflags6, leftover, consistency_warnings ++ sh_warns ++ warns) updateWays :: DynFlags -> DynFlags updateWays dflags = let theWays = sort $ nub $ ways dflags f = if WayDyn `elem` theWays then unSetGeneralFlag' else setGeneralFlag' in f Opt_Static $ dflags { ways = theWays, buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays), rtsBuildTag = mkBuildTag theWays } -- | Check (and potentially disable) any extensions that aren't allowed -- in safe mode. -- -- The bool is to indicate if we are parsing command line flags (false means -- file pragma). This allows us to generate better warnings. safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String]) safeFlagCheck _ dflags | safeLanguageOn dflags = (dflagsUnset, warns) where -- Handle illegal flags under safe language. (dflagsUnset, warns) = foldl check_method (dflags, []) unsafeFlags check_method (df, warns) (str,loc,test,fix) | test df = (fix df, warns ++ safeFailure (loc df) str) | otherwise = (df, warns) safeFailure loc str = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring " ++ str] safeFlagCheck cmdl dflags = case (safeInferOn dflags) of True | safeFlags -> (dflags', warn) True -> (dflags' { safeInferred = False }, warn) False -> (dflags', warn) where -- dynflags and warn for when -fpackage-trust by itself with no safe -- haskell flag (dflags', warn) | safeHaskell dflags == Sf_None && not cmdl && packageTrustOn dflags = (gopt_unset dflags Opt_PackageTrust, pkgWarnMsg) | otherwise = (dflags, []) pkgWarnMsg = [L (pkgTrustOnLoc dflags') $ "-fpackage-trust ignored;" ++ " must be specified with a Safe Haskell flag"] -- Have we inferred Unsafe? See Note [HscMain . Safe Haskell Inference] safeFlags = all (\(_,_,t,_) -> not $ t dflags) unsafeFlagsForInfer {- ********************************************************************** %* * DynFlags specifications %* * %********************************************************************* -} -- | All dynamic flags option strings. These are the user facing strings for -- enabling and disabling options. allFlags :: [String] allFlags = [ '-':flagName flag | flag <- flagsAll , ok (flagOptKind flag) ] where ok (PrefixPred _ _) = False ok _ = True {- - Below we export user facing symbols for GHC dynamic flags for use with the - GHC API. -} -- All dynamic flags present in GHC. flagsAll :: [Flag (CmdLineP DynFlags)] flagsAll = package_flags ++ dynamic_flags -- All dynamic flags, minus package flags, present in GHC. flagsDynamic :: [Flag (CmdLineP DynFlags)] flagsDynamic = dynamic_flags -- ALl package flags present in GHC. flagsPackage :: [Flag (CmdLineP DynFlags)] flagsPackage = package_flags --------------- The main flags themselves ------------------ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] dynamic_flags :: [Flag (CmdLineP DynFlags)] dynamic_flags = [ defFlag "n" (NoArg (addWarn "The -n flag is deprecated and no longer has any effect")) , defFlag "cpp" (NoArg (setExtensionFlag Opt_Cpp)) , defFlag "F" (NoArg (setGeneralFlag Opt_Pp)) , defFlag "#include" (HasArg (\s -> do addCmdlineHCInclude s addWarn ("-#include and INCLUDE pragmas are " ++ "deprecated: They no longer have any effect"))) , defFlag "v" (OptIntSuffix setVerbosity) , defGhcFlag "j" (OptIntSuffix (\n -> upd (\d -> d {parMakeCount = n}))) , defFlag "sig-of" (sepArg setSigOf) -- RTS options ------------------------------------------------------------- , defFlag "H" (HasArg (\s -> upd (\d -> d { ghcHeapSize = Just $ fromIntegral (decodeSize s)}))) , defFlag "Rghc-timing" (NoArg (upd (\d -> d { enableTimeStats = True }))) ------- ways --------------------------------------------------------------- , defGhcFlag "prof" (NoArg (addWay WayProf)) , defGhcFlag "eventlog" (NoArg (addWay WayEventLog)) , defGhcFlag "smp" (NoArg (addWay WayThreaded >> deprecate "Use -threaded instead")) , defGhcFlag "debug" (NoArg (addWay WayDebug)) , defGhcFlag "threaded" (NoArg (addWay WayThreaded)) , defGhcFlag "ticky" (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug)) -- -ticky enables ticky-ticky code generation, and also implies -debug which -- is required to get the RTS ticky support. ----- Linker -------------------------------------------------------- , defGhcFlag "static" (NoArg removeWayDyn) , defGhcFlag "dynamic" (NoArg (addWay WayDyn)) , defGhcFlag "rdynamic" $ noArg $ #ifdef linux_HOST_OS addOptl "-rdynamic" #elif defined (mingw32_HOST_OS) addOptl "-export-all-symbols" #else -- ignored for compat w/ gcc: id #endif , defGhcFlag "relative-dynlib-paths" (NoArg (setGeneralFlag Opt_RelativeDynlibPaths)) ------- Specific phases -------------------------------------------- -- need to appear before -pgmL to be parsed as LLVM flags. , defFlag "pgmlo" (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])}))) , defFlag "pgmlc" (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])}))) , defFlag "pgmL" (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f}))) , defFlag "pgmP" (hasArg setPgmP) , defFlag "pgmF" (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f}))) , defFlag "pgmc" (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])}))) , defFlag "pgms" (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])}))) , defFlag "pgma" (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])}))) , defFlag "pgml" (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])}))) , defFlag "pgmdll" (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])}))) , defFlag "pgmwindres" (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f}))) , defFlag "pgmlibtool" (hasArg (\f -> alterSettings (\s -> s { sPgm_libtool = f}))) -- need to appear before -optl/-opta to be parsed as LLVM flags. , defFlag "optlo" (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s}))) , defFlag "optlc" (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s}))) , defFlag "optL" (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s}))) , defFlag "optP" (hasArg addOptP) , defFlag "optF" (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s}))) , defFlag "optc" (hasArg addOptc) , defFlag "opta" (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s}))) , defFlag "optl" (hasArg addOptl) , defFlag "optwindres" (hasArg (\f -> alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s}))) , defGhcFlag "split-objs" (NoArg (if can_split then setGeneralFlag Opt_SplitObjs else addWarn "ignoring -fsplit-objs")) -------- ghc -M ----------------------------------------------------- , defGhcFlag "dep-suffix" (hasArg addDepSuffix) , defGhcFlag "dep-makefile" (hasArg setDepMakefile) , defGhcFlag "include-pkg-deps" (noArg (setDepIncludePkgDeps True)) , defGhcFlag "exclude-module" (hasArg addDepExcludeMod) -------- Linking ---------------------------------------------------- , defGhcFlag "no-link" (noArg (\d -> d{ ghcLink=NoLink })) , defGhcFlag "shared" (noArg (\d -> d{ ghcLink=LinkDynLib })) , defGhcFlag "staticlib" (noArg (\d -> d{ ghcLink=LinkStaticLib })) , defGhcFlag "dynload" (hasArg parseDynLibLoaderMode) , defGhcFlag "dylib-install-name" (hasArg setDylibInstallName) -- -dll-split is an internal flag, used only during the GHC build , defHiddenFlag "dll-split" (hasArg (\f d -> d{ dllSplitFile = Just f, dllSplit = Nothing })) ------- Libraries --------------------------------------------------- , defFlag "L" (Prefix addLibraryPath) , defFlag "l" (hasArg (addLdInputs . Option . ("-l" ++))) ------- Frameworks -------------------------------------------------- -- -framework-path should really be -F ... , defFlag "framework-path" (HasArg addFrameworkPath) , defFlag "framework" (hasArg addCmdlineFramework) ------- Output Redirection ------------------------------------------ , defGhcFlag "odir" (hasArg setObjectDir) , defGhcFlag "o" (sepArg (setOutputFile . Just)) , defGhcFlag "dyno" (sepArg (setDynOutputFile . Just)) , defGhcFlag "ohi" (hasArg (setOutputHi . Just )) , defGhcFlag "osuf" (hasArg setObjectSuf) , defGhcFlag "dynosuf" (hasArg setDynObjectSuf) , defGhcFlag "hcsuf" (hasArg setHcSuf) , defGhcFlag "hisuf" (hasArg setHiSuf) , defGhcFlag "dynhisuf" (hasArg setDynHiSuf) , defGhcFlag "hidir" (hasArg setHiDir) , defGhcFlag "tmpdir" (hasArg setTmpDir) , defGhcFlag "stubdir" (hasArg setStubDir) , defGhcFlag "dumpdir" (hasArg setDumpDir) , defGhcFlag "outputdir" (hasArg setOutputDir) , defGhcFlag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just)) , defGhcFlag "dynamic-too" (NoArg (setGeneralFlag Opt_BuildDynamicToo)) ------- Keeping temporary files ------------------------------------- -- These can be singular (think ghc -c) or plural (think ghc --make) , defGhcFlag "keep-hc-file" (NoArg (setGeneralFlag Opt_KeepHcFiles)) , defGhcFlag "keep-hc-files" (NoArg (setGeneralFlag Opt_KeepHcFiles)) , defGhcFlag "keep-s-file" (NoArg (setGeneralFlag Opt_KeepSFiles)) , defGhcFlag "keep-s-files" (NoArg (setGeneralFlag Opt_KeepSFiles)) , defGhcFlag "keep-llvm-file" (NoArg (do setObjTarget HscLlvm setGeneralFlag Opt_KeepLlvmFiles)) , defGhcFlag "keep-llvm-files" (NoArg (do setObjTarget HscLlvm setGeneralFlag Opt_KeepLlvmFiles)) -- This only makes sense as plural , defGhcFlag "keep-tmp-files" (NoArg (setGeneralFlag Opt_KeepTmpFiles)) ------- Miscellaneous ---------------------------------------------- , defGhcFlag "no-auto-link-packages" (NoArg (unSetGeneralFlag Opt_AutoLinkPackages)) , defGhcFlag "no-hs-main" (NoArg (setGeneralFlag Opt_NoHsMain)) , defGhcFlag "with-rtsopts" (HasArg setRtsOpts) , defGhcFlag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll)) , defGhcFlag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll)) , defGhcFlag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly)) , defGhcFlag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone)) , defGhcFlag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone)) , defGhcFlag "no-rtsopts-suggestions" (noArg (\d -> d {rtsOptsSuggestions = False} )) , defGhcFlag "main-is" (SepArg setMainIs) , defGhcFlag "haddock" (NoArg (setGeneralFlag Opt_Haddock)) , defGhcFlag "haddock-opts" (hasArg addHaddockOpts) , defGhcFlag "hpcdir" (SepArg setOptHpcDir) , defGhciFlag "ghci-script" (hasArg addGhciScript) , defGhciFlag "interactive-print" (hasArg setInteractivePrint) , defGhcFlag "ticky-allocd" (NoArg (setGeneralFlag Opt_Ticky_Allocd)) , defGhcFlag "ticky-LNE" (NoArg (setGeneralFlag Opt_Ticky_LNE)) , defGhcFlag "ticky-dyn-thunk" (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk)) ------- recompilation checker -------------------------------------- , defGhcFlag "recomp" (NoArg (do unSetGeneralFlag Opt_ForceRecomp deprecate "Use -fno-force-recomp instead")) , defGhcFlag "no-recomp" (NoArg (do setGeneralFlag Opt_ForceRecomp deprecate "Use -fforce-recomp instead")) ------ HsCpp opts --------------------------------------------------- , defFlag "D" (AnySuffix (upd . addOptP)) , defFlag "U" (AnySuffix (upd . addOptP)) ------- Include/Import Paths ---------------------------------------- , defFlag "I" (Prefix addIncludePath) , defFlag "i" (OptPrefix addImportPath) ------ Output style options ----------------------------------------- , defFlag "dppr-user-length" (intSuffix (\n d -> d{ pprUserLength = n })) , defFlag "dppr-cols" (intSuffix (\n d -> d{ pprCols = n })) , defGhcFlag "dtrace-level" (intSuffix (\n d -> d{ traceLevel = n })) -- Suppress all that is suppressable in core dumps. -- Except for uniques, as some simplifier phases introduce new varibles that -- have otherwise identical names. , defGhcFlag "dsuppress-all" (NoArg $ do setGeneralFlag Opt_SuppressCoercions setGeneralFlag Opt_SuppressVarKinds setGeneralFlag Opt_SuppressModulePrefixes setGeneralFlag Opt_SuppressTypeApplications setGeneralFlag Opt_SuppressIdInfo setGeneralFlag Opt_SuppressTypeSignatures) ------ Debugging ---------------------------------------------------- , defGhcFlag "dstg-stats" (NoArg (setGeneralFlag Opt_StgStats)) , defGhcFlag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm) , defGhcFlag "ddump-cmm-raw" (setDumpFlag Opt_D_dump_cmm_raw) , defGhcFlag "ddump-cmm-cfg" (setDumpFlag Opt_D_dump_cmm_cfg) , defGhcFlag "ddump-cmm-cbe" (setDumpFlag Opt_D_dump_cmm_cbe) , defGhcFlag "ddump-cmm-switch" (setDumpFlag Opt_D_dump_cmm_switch) , defGhcFlag "ddump-cmm-proc" (setDumpFlag Opt_D_dump_cmm_proc) , defGhcFlag "ddump-cmm-sink" (setDumpFlag Opt_D_dump_cmm_sink) , defGhcFlag "ddump-cmm-sp" (setDumpFlag Opt_D_dump_cmm_sp) , defGhcFlag "ddump-cmm-procmap" (setDumpFlag Opt_D_dump_cmm_procmap) , defGhcFlag "ddump-cmm-split" (setDumpFlag Opt_D_dump_cmm_split) , defGhcFlag "ddump-cmm-info" (setDumpFlag Opt_D_dump_cmm_info) , defGhcFlag "ddump-cmm-cps" (setDumpFlag Opt_D_dump_cmm_cps) , defGhcFlag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats) , defGhcFlag "ddump-asm" (setDumpFlag Opt_D_dump_asm) , defGhcFlag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native) , defGhcFlag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness) , defGhcFlag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc) , defGhcFlag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts) , defGhcFlag "ddump-asm-regalloc-stages" (setDumpFlag Opt_D_dump_asm_regalloc_stages) , defGhcFlag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats) , defGhcFlag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded) , defGhcFlag "ddump-llvm" (NoArg (do setObjTarget HscLlvm setDumpFlag' Opt_D_dump_llvm)) , defGhcFlag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv) , defGhcFlag "ddump-ds" (setDumpFlag Opt_D_dump_ds) , defGhcFlag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign) , defGhcFlag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings) , defGhcFlag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings) , defGhcFlag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites) , defGhcFlag "ddump-simpl-trace" (setDumpFlag Opt_D_dump_simpl_trace) , defGhcFlag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal) , defGhcFlag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed) , defGhcFlag "ddump-rn" (setDumpFlag Opt_D_dump_rn) , defGhcFlag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl) , defGhcFlag "ddump-simpl-iterations" (setDumpFlag Opt_D_dump_simpl_iterations) , defGhcFlag "ddump-spec" (setDumpFlag Opt_D_dump_spec) , defGhcFlag "ddump-prep" (setDumpFlag Opt_D_dump_prep) , defGhcFlag "ddump-stg" (setDumpFlag Opt_D_dump_stg) , defGhcFlag "ddump-call-arity" (setDumpFlag Opt_D_dump_call_arity) , defGhcFlag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal) , defGhcFlag "ddump-strsigs" (setDumpFlag Opt_D_dump_strsigs) , defGhcFlag "ddump-tc" (setDumpFlag Opt_D_dump_tc) , defGhcFlag "ddump-types" (setDumpFlag Opt_D_dump_types) , defGhcFlag "ddump-rules" (setDumpFlag Opt_D_dump_rules) , defGhcFlag "ddump-cse" (setDumpFlag Opt_D_dump_cse) , defGhcFlag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper) , defGhcFlag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace) , defGhcFlag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace) , defGhcFlag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace) , defGhcFlag "ddump-tc-trace" (NoArg (do setDumpFlag' Opt_D_dump_tc_trace setDumpFlag' Opt_D_dump_cs_trace)) , defGhcFlag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace) , defGhcFlag "ddump-splices" (setDumpFlag Opt_D_dump_splices) , defGhcFlag "dth-dec-file" (setDumpFlag Opt_D_th_dec_file) , defGhcFlag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats) , defGhcFlag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm) , defGhcFlag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats) , defGhcFlag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs) , defGhcFlag "dsource-stats" (setDumpFlag Opt_D_source_stats) , defGhcFlag "dverbose-core2core" (NoArg (do setVerbosity (Just 2) setVerboseCore2Core)) , defGhcFlag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg) , defGhcFlag "ddump-hi" (setDumpFlag Opt_D_dump_hi) , defGhcFlag "ddump-minimal-imports" (NoArg (setGeneralFlag Opt_D_dump_minimal_imports)) , defGhcFlag "ddump-vect" (setDumpFlag Opt_D_dump_vect) , defGhcFlag "ddump-hpc" (setDumpFlag Opt_D_dump_ticked) -- back compat , defGhcFlag "ddump-ticked" (setDumpFlag Opt_D_dump_ticked) , defGhcFlag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles) , defGhcFlag "ddump-mod-map" (setDumpFlag Opt_D_dump_mod_map) , defGhcFlag "ddump-view-pattern-commoning" (setDumpFlag Opt_D_dump_view_pattern_commoning) , defGhcFlag "ddump-to-file" (NoArg (setGeneralFlag Opt_DumpToFile)) , defGhcFlag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs) , defGhcFlag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti) , defGhcFlag "dcore-lint" (NoArg (setGeneralFlag Opt_DoCoreLinting)) , defGhcFlag "dstg-lint" (NoArg (setGeneralFlag Opt_DoStgLinting)) , defGhcFlag "dcmm-lint" (NoArg (setGeneralFlag Opt_DoCmmLinting)) , defGhcFlag "dasm-lint" (NoArg (setGeneralFlag Opt_DoAsmLinting)) , defGhcFlag "dannot-lint" (NoArg (setGeneralFlag Opt_DoAnnotationLinting)) , defGhcFlag "dshow-passes" (NoArg (do forceRecompile setVerbosity $ Just 2)) , defGhcFlag "dfaststring-stats" (NoArg (setGeneralFlag Opt_D_faststring_stats)) , defGhcFlag "dno-llvm-mangler" (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag , defGhcFlag "ddump-debug" (setDumpFlag Opt_D_dump_debug) ------ Machine dependant (-m<blah>) stuff --------------------------- , defGhcFlag "msse" (noArg (\d -> d{ sseVersion = Just SSE1 })) , defGhcFlag "msse2" (noArg (\d -> d{ sseVersion = Just SSE2 })) , defGhcFlag "msse3" (noArg (\d -> d{ sseVersion = Just SSE3 })) , defGhcFlag "msse4" (noArg (\d -> d{ sseVersion = Just SSE4 })) , defGhcFlag "msse4.2" (noArg (\d -> d{ sseVersion = Just SSE42 })) , defGhcFlag "mavx" (noArg (\d -> d{ avx = True })) , defGhcFlag "mavx2" (noArg (\d -> d{ avx2 = True })) , defGhcFlag "mavx512cd" (noArg (\d -> d{ avx512cd = True })) , defGhcFlag "mavx512er" (noArg (\d -> d{ avx512er = True })) , defGhcFlag "mavx512f" (noArg (\d -> d{ avx512f = True })) , defGhcFlag "mavx512pf" (noArg (\d -> d{ avx512pf = True })) ------ Warning opts ------------------------------------------------- , defFlag "W" (NoArg (mapM_ setWarningFlag minusWOpts)) , defFlag "Werror" (NoArg (setGeneralFlag Opt_WarnIsError)) , defFlag "Wwarn" (NoArg (unSetGeneralFlag Opt_WarnIsError)) , defFlag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts)) , defFlag "Wnot" (NoArg (do upd (\dfs -> dfs {warningFlags = IntSet.empty}) deprecate "Use -w instead")) , defFlag "w" (NoArg (upd (\dfs -> dfs {warningFlags = IntSet.empty}))) ------ Plugin flags ------------------------------------------------ , defGhcFlag "fplugin-opt" (hasArg addPluginModuleNameOption) , defGhcFlag "fplugin" (hasArg addPluginModuleName) ------ Optimisation flags ------------------------------------------ , defGhcFlag "O" (noArgM (setOptLevel 1)) , defGhcFlag "Onot" (noArgM (\dflags -> do deprecate "Use -O0 instead" setOptLevel 0 dflags)) , defGhcFlag "Odph" (noArgM setDPHOpt) , defGhcFlag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1))) -- If the number is missing, use 1 , defFlag "fmax-relevant-binds" (intSuffix (\n d -> d{ maxRelevantBinds = Just n })) , defFlag "fno-max-relevant-binds" (noArg (\d -> d{ maxRelevantBinds = Nothing })) , defFlag "fsimplifier-phases" (intSuffix (\n d -> d{ simplPhases = n })) , defFlag "fmax-simplifier-iterations" (intSuffix (\n d -> d{ maxSimplIterations = n })) , defFlag "fsimpl-tick-factor" (intSuffix (\n d -> d{ simplTickFactor = n })) , defFlag "fspec-constr-threshold" (intSuffix (\n d -> d{ specConstrThreshold = Just n })) , defFlag "fno-spec-constr-threshold" (noArg (\d -> d{ specConstrThreshold = Nothing })) , defFlag "fspec-constr-count" (intSuffix (\n d -> d{ specConstrCount = Just n })) , defFlag "fno-spec-constr-count" (noArg (\d -> d{ specConstrCount = Nothing })) , defFlag "fspec-constr-recursive" (intSuffix (\n d -> d{ specConstrRecursive = n })) , defFlag "fliberate-case-threshold" (intSuffix (\n d -> d{ liberateCaseThreshold = Just n })) , defFlag "fno-liberate-case-threshold" (noArg (\d -> d{ liberateCaseThreshold = Nothing })) , defFlag "frule-check" (sepArg (\s d -> d{ ruleCheck = Just s })) , defFlag "freduction-depth" (intSuffix (\n d -> d{ reductionDepth = treatZeroAsInf n })) , defFlag "fconstraint-solver-iterations" (intSuffix (\n d -> d{ solverIterations = treatZeroAsInf n })) , defFlag "fcontext-stack" (intSuffixM (\n d -> do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead" ; return $ d{ reductionDepth = treatZeroAsInf n } })) , defFlag "ftype-function-depth" (intSuffixM (\n d -> do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead" ; return $ d{ reductionDepth = treatZeroAsInf n } })) , defFlag "fstrictness-before" (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d })) , defFlag "ffloat-lam-args" (intSuffix (\n d -> d{ floatLamArgs = Just n })) , defFlag "ffloat-all-lams" (noArg (\d -> d{ floatLamArgs = Nothing })) , defFlag "fhistory-size" (intSuffix (\n d -> d{ historySize = n })) , defFlag "funfolding-creation-threshold" (intSuffix (\n d -> d {ufCreationThreshold = n})) , defFlag "funfolding-use-threshold" (intSuffix (\n d -> d {ufUseThreshold = n})) , defFlag "funfolding-fun-discount" (intSuffix (\n d -> d {ufFunAppDiscount = n})) , defFlag "funfolding-dict-discount" (intSuffix (\n d -> d {ufDictDiscount = n})) , defFlag "funfolding-keeness-factor" (floatSuffix (\n d -> d {ufKeenessFactor = n})) , defFlag "fmax-worker-args" (intSuffix (\n d -> d {maxWorkerArgs = n})) , defGhciFlag "fghci-hist-size" (intSuffix (\n d -> d {ghciHistSize = n})) , defGhcFlag "fmax-inline-alloc-size" (intSuffix (\n d -> d{ maxInlineAllocSize = n })) , defGhcFlag "fmax-inline-memcpy-insns" (intSuffix (\n d -> d{ maxInlineMemcpyInsns = n })) , defGhcFlag "fmax-inline-memset-insns" (intSuffix (\n d -> d{ maxInlineMemsetInsns = n })) ------ Profiling ---------------------------------------------------- -- OLD profiling flags , defGhcFlag "auto-all" (noArg (\d -> d { profAuto = ProfAutoAll } )) , defGhcFlag "no-auto-all" (noArg (\d -> d { profAuto = NoProfAuto } )) , defGhcFlag "auto" (noArg (\d -> d { profAuto = ProfAutoExports } )) , defGhcFlag "no-auto" (noArg (\d -> d { profAuto = NoProfAuto } )) , defGhcFlag "caf-all" (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs)) , defGhcFlag "no-caf-all" (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs)) -- NEW profiling flags , defGhcFlag "fprof-auto" (noArg (\d -> d { profAuto = ProfAutoAll } )) , defGhcFlag "fprof-auto-top" (noArg (\d -> d { profAuto = ProfAutoTop } )) , defGhcFlag "fprof-auto-exported" (noArg (\d -> d { profAuto = ProfAutoExports } )) , defGhcFlag "fprof-auto-calls" (noArg (\d -> d { profAuto = ProfAutoCalls } )) , defGhcFlag "fno-prof-auto" (noArg (\d -> d { profAuto = NoProfAuto } )) ------ Compiler flags ----------------------------------------------- , defGhcFlag "fasm" (NoArg (setObjTarget HscAsm)) , defGhcFlag "fvia-c" (NoArg (addWarn $ "The -fvia-c flag does nothing; " ++ "it will be removed in a future GHC release")) , defGhcFlag "fvia-C" (NoArg (addWarn $ "The -fvia-C flag does nothing; " ++ "it will be removed in a future GHC release")) , defGhcFlag "fllvm" (NoArg (setObjTarget HscLlvm)) , defFlag "fno-code" (NoArg (do upd $ \d -> d{ ghcLink=NoLink } setTarget HscNothing)) , defFlag "fbyte-code" (NoArg (setTarget HscInterpreted)) , defFlag "fobject-code" (NoArg (setTargetWithPlatform defaultHscTarget)) , defFlag "fglasgow-exts" (NoArg (do enableGlasgowExts deprecate "Use individual extensions instead")) , defFlag "fno-glasgow-exts" (NoArg (do disableGlasgowExts deprecate "Use individual extensions instead")) , defFlag "fwarn-unused-binds" (NoArg enableUnusedBinds) , defFlag "fno-warn-unused-binds" (NoArg disableUnusedBinds) ------ Safe Haskell flags ------------------------------------------- , defFlag "fpackage-trust" (NoArg setPackageTrust) , defFlag "fno-safe-infer" (noArg (\d -> d { safeInfer = False } )) , defGhcFlag "fPIC" (NoArg (setGeneralFlag Opt_PIC)) , defGhcFlag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC)) ------ Debugging flags ---------------------------------------------- , defGhcFlag "g" (NoArg (setGeneralFlag Opt_Debug)) ] ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlags ++ map (mkFlag turnOff "no-" unSetGeneralFlag) negatableFlags ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlags ++ map (mkFlag turnOff "dno-" unSetGeneralFlag) dFlags ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlags ++ map (mkFlag turnOff "fno-" unSetGeneralFlag) fFlags ++ map (mkFlag turnOn "f" setWarningFlag ) fWarningFlags ++ map (mkFlag turnOff "fno-" unSetWarningFlag) fWarningFlags ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlags ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlags ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlags ++ map (mkFlag turnOn "X" setLanguage) languageFlags ++ map (mkFlag turnOn "X" setSafeHaskell) safeHaskellFlags ++ [ defFlag "XGenerics" (NoArg (deprecate $ "it does nothing; look into -XDefaultSignatures " ++ "and -XDeriveGeneric for generic programming support.")) , defFlag "XNoGenerics" (NoArg (deprecate $ "it does nothing; look into -XDefaultSignatures and " ++ "-XDeriveGeneric for generic programming support.")) ] -- See Note [Supporting CLI completion] package_flags :: [Flag (CmdLineP DynFlags)] package_flags = [ ------- Packages ---------------------------------------------------- defFlag "package-db" (HasArg (addPkgConfRef . PkgConfFile)) , defFlag "clear-package-db" (NoArg clearPkgConf) , defFlag "no-global-package-db" (NoArg removeGlobalPkgConf) , defFlag "no-user-package-db" (NoArg removeUserPkgConf) , defFlag "global-package-db" (NoArg (addPkgConfRef GlobalPkgConf)) , defFlag "user-package-db" (NoArg (addPkgConfRef UserPkgConf)) -- backwards compat with GHC<=7.4 : , defFlag "package-conf" (HasArg $ \path -> do addPkgConfRef (PkgConfFile path) deprecate "Use -package-db instead") , defFlag "no-user-package-conf" (NoArg $ do removeUserPkgConf deprecate "Use -no-user-package-db instead") , defGhcFlag "package-name" (HasArg $ \name -> do upd (setPackageKey name) deprecate "Use -this-package-key instead") , defGhcFlag "this-package-key" (hasArg setPackageKey) , defFlag "package-id" (HasArg exposePackageId) , defFlag "package" (HasArg exposePackage) , defFlag "package-key" (HasArg exposePackageKey) , defFlag "hide-package" (HasArg hidePackage) , defFlag "hide-all-packages" (NoArg (setGeneralFlag Opt_HideAllPackages)) , defFlag "package-env" (HasArg setPackageEnv) , defFlag "ignore-package" (HasArg ignorePackage) , defFlag "syslib" (HasArg (\s -> do exposePackage s deprecate "Use -package instead")) , defFlag "distrust-all-packages" (NoArg (setGeneralFlag Opt_DistrustAllPackages)) , defFlag "trust" (HasArg trustPackage) , defFlag "distrust" (HasArg distrustPackage) ] where setPackageEnv env = upd $ \s -> s { packageEnv = Just env } -- | Make a list of flags for shell completion. -- Filter all available flags into two groups, for interactive GHC vs all other. flagsForCompletion :: Bool -> [String] flagsForCompletion isInteractive = [ '-':flagName flag | flag <- flagsAll , modeFilter (flagGhcMode flag) ] where modeFilter AllModes = True modeFilter OnlyGhci = isInteractive modeFilter OnlyGhc = not isInteractive modeFilter HiddenFlag = False type TurnOnFlag = Bool -- True <=> we are turning the flag on -- False <=> we are turning the flag off turnOn :: TurnOnFlag; turnOn = True turnOff :: TurnOnFlag; turnOff = False data FlagSpec flag = FlagSpec { flagSpecName :: String -- ^ Flag in string form , flagSpecFlag :: flag -- ^ Flag in internal form , flagSpecAction :: (TurnOnFlag -> DynP ()) -- ^ Extra action to run when the flag is found -- Typically, emit a warning or error , flagSpecGhcMode :: GhcFlagMode -- ^ In which ghc mode the flag has effect } -- | Define a new flag. flagSpec :: String -> flag -> FlagSpec flag flagSpec name flag = flagSpec' name flag nop -- | Define a new flag with an effect. flagSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> FlagSpec flag flagSpec' name flag act = FlagSpec name flag act AllModes -- | Define a new flag for GHCi. flagGhciSpec :: String -> flag -> FlagSpec flag flagGhciSpec name flag = flagGhciSpec' name flag nop -- | Define a new flag for GHCi with an effect. flagGhciSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> FlagSpec flag flagGhciSpec' name flag act = FlagSpec name flag act OnlyGhci -- | Define a new flag invisible to CLI completion. flagHiddenSpec :: String -> flag -> FlagSpec flag flagHiddenSpec name flag = flagHiddenSpec' name flag nop -- | Define a new flag invisible to CLI completion with an effect. flagHiddenSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> FlagSpec flag flagHiddenSpec' name flag act = FlagSpec name flag act HiddenFlag mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on -> String -- ^ The flag prefix -> (flag -> DynP ()) -- ^ What to do when the flag is found -> FlagSpec flag -- ^ Specification of this particular flag -> Flag (CmdLineP DynFlags) mkFlag turn_on flagPrefix f (FlagSpec name flag extra_action mode) = Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on)) mode deprecatedForExtension :: String -> TurnOnFlag -> DynP () deprecatedForExtension lang turn_on = deprecate ("use -X" ++ flag ++ " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead") where flag | turn_on = lang | otherwise = "No"++lang useInstead :: String -> TurnOnFlag -> DynP () useInstead flag turn_on = deprecate ("Use -f" ++ no ++ flag ++ " instead") where no = if turn_on then "" else "no-" nop :: TurnOnFlag -> DynP () nop _ = return () -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@ fWarningFlags :: [FlagSpec WarningFlag] fWarningFlags = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] -- Please keep the list of flags below sorted alphabetically flagSpec "warn-alternative-layout-rule-transitional" Opt_WarnAlternativeLayoutRuleTransitional, flagSpec' "warn-amp" Opt_WarnAMP (\_ -> deprecate "it has no effect, and will be removed in GHC 7.12"), flagSpec "warn-auto-orphans" Opt_WarnAutoOrphans, flagSpec "warn-deferred-type-errors" Opt_WarnDeferredTypeErrors, flagSpec "warn-deprecations" Opt_WarnWarningsDeprecations, flagSpec "warn-deprecated-flags" Opt_WarnDeprecatedFlags, flagSpec "warn-deriving-typeable" Opt_WarnDerivingTypeable, flagSpec "warn-dodgy-exports" Opt_WarnDodgyExports, flagSpec "warn-dodgy-foreign-imports" Opt_WarnDodgyForeignImports, flagSpec "warn-dodgy-imports" Opt_WarnDodgyImports, flagSpec "warn-empty-enumerations" Opt_WarnEmptyEnumerations, flagSpec "warn-context-quantification" Opt_WarnContextQuantification, flagSpec' "warn-duplicate-constraints" Opt_WarnDuplicateConstraints (\_ -> deprecate "it is subsumed by -fwarn-redundant-constraints"), flagSpec "warn-redundant-constraints" Opt_WarnRedundantConstraints, flagSpec "warn-duplicate-exports" Opt_WarnDuplicateExports, flagSpec "warn-hi-shadowing" Opt_WarnHiShadows, flagSpec "warn-implicit-prelude" Opt_WarnImplicitPrelude, flagSpec "warn-incomplete-patterns" Opt_WarnIncompletePatterns, flagSpec "warn-incomplete-record-updates" Opt_WarnIncompletePatternsRecUpd, flagSpec "warn-incomplete-uni-patterns" Opt_WarnIncompleteUniPatterns, flagSpec "warn-inline-rule-shadowing" Opt_WarnInlineRuleShadowing, flagSpec "warn-identities" Opt_WarnIdentities, flagSpec "warn-missing-fields" Opt_WarnMissingFields, flagSpec "warn-missing-import-lists" Opt_WarnMissingImportList, flagSpec "warn-missing-local-sigs" Opt_WarnMissingLocalSigs, flagSpec "warn-missing-methods" Opt_WarnMissingMethods, flagSpec "warn-missing-signatures" Opt_WarnMissingSigs, flagSpec "warn-missing-exported-sigs" Opt_WarnMissingExportedSigs, flagSpec "warn-monomorphism-restriction" Opt_WarnMonomorphism, flagSpec "warn-name-shadowing" Opt_WarnNameShadowing, flagSpec "warn-orphans" Opt_WarnOrphans, flagSpec "warn-overflowed-literals" Opt_WarnOverflowedLiterals, flagSpec "warn-overlapping-patterns" Opt_WarnOverlappingPatterns, flagSpec "warn-pointless-pragmas" Opt_WarnPointlessPragmas, flagSpec' "warn-safe" Opt_WarnSafe setWarnSafe, flagSpec "warn-trustworthy-safe" Opt_WarnTrustworthySafe, flagSpec "warn-tabs" Opt_WarnTabs, flagSpec "warn-type-defaults" Opt_WarnTypeDefaults, flagSpec "warn-typed-holes" Opt_WarnTypedHoles, flagSpec "warn-partial-type-signatures" Opt_WarnPartialTypeSignatures, flagSpec "warn-unrecognised-pragmas" Opt_WarnUnrecognisedPragmas, flagSpec' "warn-unsafe" Opt_WarnUnsafe setWarnUnsafe, flagSpec "warn-unsupported-calling-conventions" Opt_WarnUnsupportedCallingConventions, flagSpec "warn-unsupported-llvm-version" Opt_WarnUnsupportedLlvmVersion, flagSpec "warn-unticked-promoted-constructors" Opt_WarnUntickedPromotedConstructors, flagSpec "warn-unused-do-bind" Opt_WarnUnusedDoBind, flagSpec "warn-unused-imports" Opt_WarnUnusedImports, flagSpec "warn-unused-local-binds" Opt_WarnUnusedLocalBinds, flagSpec "warn-unused-matches" Opt_WarnUnusedMatches, flagSpec "warn-unused-pattern-binds" Opt_WarnUnusedPatternBinds, flagSpec "warn-unused-top-binds" Opt_WarnUnusedTopBinds, flagSpec "warn-warnings-deprecations" Opt_WarnWarningsDeprecations, flagSpec "warn-wrong-do-bind" Opt_WarnWrongDoBind] -- | These @-\<blah\>@ flags can all be reversed with @-no-\<blah\>@ negatableFlags :: [FlagSpec GeneralFlag] negatableFlags = [ flagGhciSpec "ignore-dot-ghci" Opt_IgnoreDotGhci ] -- | These @-d\<blah\>@ flags can all be reversed with @-dno-\<blah\>@ dFlags :: [FlagSpec GeneralFlag] dFlags = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] -- Please keep the list of flags below sorted alphabetically flagSpec "ppr-case-as-let" Opt_PprCaseAsLet, flagSpec "ppr-ticks" Opt_PprShowTicks, flagSpec "suppress-coercions" Opt_SuppressCoercions, flagSpec "suppress-idinfo" Opt_SuppressIdInfo, flagSpec "suppress-module-prefixes" Opt_SuppressModulePrefixes, flagSpec "suppress-type-applications" Opt_SuppressTypeApplications, flagSpec "suppress-type-signatures" Opt_SuppressTypeSignatures, flagSpec "suppress-uniques" Opt_SuppressUniques, flagSpec "suppress-var-kinds" Opt_SuppressVarKinds] -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@ fFlags :: [FlagSpec GeneralFlag] fFlags = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] -- Please keep the list of flags below sorted alphabetically flagGhciSpec "break-on-error" Opt_BreakOnError, flagGhciSpec "break-on-exception" Opt_BreakOnException, flagSpec "building-cabal-package" Opt_BuildingCabalPackage, flagSpec "call-arity" Opt_CallArity, flagSpec "case-merge" Opt_CaseMerge, flagSpec "cmm-elim-common-blocks" Opt_CmmElimCommonBlocks, flagSpec "cmm-sink" Opt_CmmSink, flagSpec "cse" Opt_CSE, flagSpec "defer-type-errors" Opt_DeferTypeErrors, flagSpec "defer-typed-holes" Opt_DeferTypedHoles, flagSpec "dicts-cheap" Opt_DictsCheap, flagSpec "dicts-strict" Opt_DictsStrict, flagSpec "dmd-tx-dict-sel" Opt_DmdTxDictSel, flagSpec "do-eta-reduction" Opt_DoEtaReduction, flagSpec "do-lambda-eta-expansion" Opt_DoLambdaEtaExpansion, flagSpec "eager-blackholing" Opt_EagerBlackHoling, flagSpec "embed-manifest" Opt_EmbedManifest, flagSpec "enable-rewrite-rules" Opt_EnableRewriteRules, flagSpec "error-spans" Opt_ErrorSpans, flagSpec "excess-precision" Opt_ExcessPrecision, flagSpec "expose-all-unfoldings" Opt_ExposeAllUnfoldings, flagSpec "flat-cache" Opt_FlatCache, flagSpec "float-in" Opt_FloatIn, flagSpec "force-recomp" Opt_ForceRecomp, flagSpec "full-laziness" Opt_FullLaziness, flagSpec "fun-to-thunk" Opt_FunToThunk, flagSpec "gen-manifest" Opt_GenManifest, flagSpec "ghci-history" Opt_GhciHistory, flagSpec "ghci-sandbox" Opt_GhciSandbox, flagSpec "helpful-errors" Opt_HelpfulErrors, flagSpec "hpc" Opt_Hpc, flagSpec "ignore-asserts" Opt_IgnoreAsserts, flagSpec "ignore-interface-pragmas" Opt_IgnoreInterfacePragmas, flagGhciSpec "implicit-import-qualified" Opt_ImplicitImportQualified, flagSpec "irrefutable-tuples" Opt_IrrefutableTuples, flagSpec "kill-absence" Opt_KillAbsence, flagSpec "kill-one-shot" Opt_KillOneShot, flagSpec "late-dmd-anal" Opt_LateDmdAnal, flagSpec "liberate-case" Opt_LiberateCase, flagHiddenSpec "llvm-pass-vectors-in-regs" Opt_LlvmPassVectorsInRegisters, flagHiddenSpec "llvm-tbaa" Opt_LlvmTBAA, flagSpec "loopification" Opt_Loopification, flagSpec "omit-interface-pragmas" Opt_OmitInterfacePragmas, flagSpec "omit-yields" Opt_OmitYields, flagSpec "pedantic-bottoms" Opt_PedanticBottoms, flagSpec "pre-inlining" Opt_SimplPreInlining, flagGhciSpec "print-bind-contents" Opt_PrintBindContents, flagGhciSpec "print-bind-result" Opt_PrintBindResult, flagGhciSpec "print-evld-with-show" Opt_PrintEvldWithShow, flagSpec "print-explicit-foralls" Opt_PrintExplicitForalls, flagSpec "print-explicit-kinds" Opt_PrintExplicitKinds, flagSpec "print-unicode-syntax" Opt_PrintUnicodeSyntax, flagSpec "prof-cafs" Opt_AutoSccsOnIndividualCafs, flagSpec "prof-count-entries" Opt_ProfCountEntries, flagSpec "regs-graph" Opt_RegsGraph, flagSpec "regs-iterative" Opt_RegsIterative, flagSpec' "rewrite-rules" Opt_EnableRewriteRules (useInstead "enable-rewrite-rules"), flagSpec "shared-implib" Opt_SharedImplib, flagSpec "simple-list-literals" Opt_SimpleListLiterals, flagSpec "spec-constr" Opt_SpecConstr, flagSpec "specialise" Opt_Specialise, flagSpec "specialise-aggressively" Opt_SpecialiseAggressively, flagSpec "cross-module-specialise" Opt_CrossModuleSpecialise, flagSpec "static-argument-transformation" Opt_StaticArgumentTransformation, flagSpec "strictness" Opt_Strictness, flagSpec "use-rpaths" Opt_RPath, flagSpec "write-interface" Opt_WriteInterface, flagSpec "unbox-small-strict-fields" Opt_UnboxSmallStrictFields, flagSpec "unbox-strict-fields" Opt_UnboxStrictFields, flagSpec "vectorisation-avoidance" Opt_VectorisationAvoidance, flagSpec "vectorise" Opt_Vectorise ] -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@ fLangFlags :: [FlagSpec ExtensionFlag] fLangFlags = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] flagSpec' "th" Opt_TemplateHaskell (\on -> deprecatedForExtension "TemplateHaskell" on >> setTemplateHaskellLoc on), flagSpec' "fi" Opt_ForeignFunctionInterface (deprecatedForExtension "ForeignFunctionInterface"), flagSpec' "ffi" Opt_ForeignFunctionInterface (deprecatedForExtension "ForeignFunctionInterface"), flagSpec' "arrows" Opt_Arrows (deprecatedForExtension "Arrows"), flagSpec' "implicit-prelude" Opt_ImplicitPrelude (deprecatedForExtension "ImplicitPrelude"), flagSpec' "bang-patterns" Opt_BangPatterns (deprecatedForExtension "BangPatterns"), flagSpec' "monomorphism-restriction" Opt_MonomorphismRestriction (deprecatedForExtension "MonomorphismRestriction"), flagSpec' "mono-pat-binds" Opt_MonoPatBinds (deprecatedForExtension "MonoPatBinds"), flagSpec' "extended-default-rules" Opt_ExtendedDefaultRules (deprecatedForExtension "ExtendedDefaultRules"), flagSpec' "implicit-params" Opt_ImplicitParams (deprecatedForExtension "ImplicitParams"), flagSpec' "scoped-type-variables" Opt_ScopedTypeVariables (deprecatedForExtension "ScopedTypeVariables"), flagSpec' "parr" Opt_ParallelArrays (deprecatedForExtension "ParallelArrays"), flagSpec' "PArr" Opt_ParallelArrays (deprecatedForExtension "ParallelArrays"), flagSpec' "allow-overlapping-instances" Opt_OverlappingInstances (deprecatedForExtension "OverlappingInstances"), flagSpec' "allow-undecidable-instances" Opt_UndecidableInstances (deprecatedForExtension "UndecidableInstances"), flagSpec' "allow-incoherent-instances" Opt_IncoherentInstances (deprecatedForExtension "IncoherentInstances") ] supportedLanguages :: [String] supportedLanguages = map flagSpecName languageFlags supportedLanguageOverlays :: [String] supportedLanguageOverlays = map flagSpecName safeHaskellFlags supportedExtensions :: [String] supportedExtensions = concatMap (\name -> [name, "No" ++ name]) (map flagSpecName xFlags) supportedLanguagesAndExtensions :: [String] supportedLanguagesAndExtensions = supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions -- | These -X<blah> flags cannot be reversed with -XNo<blah> languageFlags :: [FlagSpec Language] languageFlags = [ flagSpec "Haskell98" Haskell98, flagSpec "Haskell2010" Haskell2010 ] -- | These -X<blah> flags cannot be reversed with -XNo<blah> -- They are used to place hard requirements on what GHC Haskell language -- features can be used. safeHaskellFlags :: [FlagSpec SafeHaskellMode] safeHaskellFlags = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe] where mkF flag = flagSpec (show flag) flag -- | These -X<blah> flags can all be reversed with -XNo<blah> xFlags :: [FlagSpec ExtensionFlag] xFlags = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] -- Please keep the list of flags below sorted alphabetically flagSpec "AllowAmbiguousTypes" Opt_AllowAmbiguousTypes, flagSpec "AlternativeLayoutRule" Opt_AlternativeLayoutRule, flagSpec "AlternativeLayoutRuleTransitional" Opt_AlternativeLayoutRuleTransitional, flagSpec "Arrows" Opt_Arrows, flagSpec "AutoDeriveTypeable" Opt_AutoDeriveTypeable, flagSpec "BangPatterns" Opt_BangPatterns, flagSpec "BinaryLiterals" Opt_BinaryLiterals, flagSpec "CApiFFI" Opt_CApiFFI, flagSpec "CPP" Opt_Cpp, flagSpec "ConstrainedClassMethods" Opt_ConstrainedClassMethods, flagSpec "ConstraintKinds" Opt_ConstraintKinds, flagSpec "DataKinds" Opt_DataKinds, flagSpec' "DatatypeContexts" Opt_DatatypeContexts (\ turn_on -> when turn_on $ deprecate $ "It was widely considered a misfeature, " ++ "and has been removed from the Haskell language."), flagSpec "DefaultSignatures" Opt_DefaultSignatures, flagSpec "DeriveAnyClass" Opt_DeriveAnyClass, flagSpec "DeriveDataTypeable" Opt_DeriveDataTypeable, flagSpec "DeriveFoldable" Opt_DeriveFoldable, flagSpec "DeriveFunctor" Opt_DeriveFunctor, flagSpec "DeriveGeneric" Opt_DeriveGeneric, flagSpec "DeriveTraversable" Opt_DeriveTraversable, flagSpec "DisambiguateRecordFields" Opt_DisambiguateRecordFields, flagSpec "DoAndIfThenElse" Opt_DoAndIfThenElse, flagSpec' "DoRec" Opt_RecursiveDo (deprecatedForExtension "RecursiveDo"), flagSpec "EmptyCase" Opt_EmptyCase, flagSpec "EmptyDataDecls" Opt_EmptyDataDecls, flagSpec "ExistentialQuantification" Opt_ExistentialQuantification, flagSpec "ExplicitForAll" Opt_ExplicitForAll, flagSpec "ExplicitNamespaces" Opt_ExplicitNamespaces, flagSpec "ExtendedDefaultRules" Opt_ExtendedDefaultRules, flagSpec "FlexibleContexts" Opt_FlexibleContexts, flagSpec "FlexibleInstances" Opt_FlexibleInstances, flagSpec "ForeignFunctionInterface" Opt_ForeignFunctionInterface, flagSpec "FunctionalDependencies" Opt_FunctionalDependencies, flagSpec "GADTSyntax" Opt_GADTSyntax, flagSpec "GADTs" Opt_GADTs, flagSpec "GHCForeignImportPrim" Opt_GHCForeignImportPrim, flagSpec' "GeneralizedNewtypeDeriving" Opt_GeneralizedNewtypeDeriving setGenDeriving, flagSpec "ImplicitParams" Opt_ImplicitParams, flagSpec "ImplicitPrelude" Opt_ImplicitPrelude, flagSpec "ImpredicativeTypes" Opt_ImpredicativeTypes, flagSpec' "IncoherentInstances" Opt_IncoherentInstances setIncoherentInsts, flagSpec "InstanceSigs" Opt_InstanceSigs, flagSpec "InterruptibleFFI" Opt_InterruptibleFFI, flagSpec "JavaScriptFFI" Opt_JavaScriptFFI, flagSpec "KindSignatures" Opt_KindSignatures, flagSpec "LambdaCase" Opt_LambdaCase, flagSpec "LiberalTypeSynonyms" Opt_LiberalTypeSynonyms, flagSpec "MagicHash" Opt_MagicHash, flagSpec "MonadComprehensions" Opt_MonadComprehensions, flagSpec "MonoLocalBinds" Opt_MonoLocalBinds, flagSpec' "MonoPatBinds" Opt_MonoPatBinds (\ turn_on -> when turn_on $ deprecate "Experimental feature now removed; has no effect"), flagSpec "MonomorphismRestriction" Opt_MonomorphismRestriction, flagSpec "MultiParamTypeClasses" Opt_MultiParamTypeClasses, flagSpec "MultiWayIf" Opt_MultiWayIf, flagSpec "NPlusKPatterns" Opt_NPlusKPatterns, flagSpec "NamedFieldPuns" Opt_RecordPuns, flagSpec "NamedWildCards" Opt_NamedWildCards, flagSpec "NegativeLiterals" Opt_NegativeLiterals, flagSpec "NondecreasingIndentation" Opt_NondecreasingIndentation, flagSpec' "NullaryTypeClasses" Opt_NullaryTypeClasses (deprecatedForExtension "MultiParamTypeClasses"), flagSpec "NumDecimals" Opt_NumDecimals, flagSpec' "OverlappingInstances" Opt_OverlappingInstances setOverlappingInsts, flagSpec "OverloadedLists" Opt_OverloadedLists, flagSpec "OverloadedStrings" Opt_OverloadedStrings, flagSpec "PackageImports" Opt_PackageImports, flagSpec "ParallelArrays" Opt_ParallelArrays, flagSpec "ParallelListComp" Opt_ParallelListComp, flagSpec "PartialTypeSignatures" Opt_PartialTypeSignatures, flagSpec "PatternGuards" Opt_PatternGuards, flagSpec' "PatternSignatures" Opt_ScopedTypeVariables (deprecatedForExtension "ScopedTypeVariables"), flagSpec "PatternSynonyms" Opt_PatternSynonyms, flagSpec "PolyKinds" Opt_PolyKinds, flagSpec "PolymorphicComponents" Opt_RankNTypes, flagSpec "PostfixOperators" Opt_PostfixOperators, flagSpec "QuasiQuotes" Opt_QuasiQuotes, flagSpec "Rank2Types" Opt_RankNTypes, flagSpec "RankNTypes" Opt_RankNTypes, flagSpec "RebindableSyntax" Opt_RebindableSyntax, flagSpec' "RecordPuns" Opt_RecordPuns (deprecatedForExtension "NamedFieldPuns"), flagSpec "RecordWildCards" Opt_RecordWildCards, flagSpec "RecursiveDo" Opt_RecursiveDo, flagSpec "RelaxedLayout" Opt_RelaxedLayout, flagSpec' "RelaxedPolyRec" Opt_RelaxedPolyRec (\ turn_on -> unless turn_on $ deprecate "You can't turn off RelaxedPolyRec any more"), flagSpec "RoleAnnotations" Opt_RoleAnnotations, flagSpec "ScopedTypeVariables" Opt_ScopedTypeVariables, flagSpec "StandaloneDeriving" Opt_StandaloneDeriving, flagSpec "StaticPointers" Opt_StaticPointers, flagSpec' "TemplateHaskell" Opt_TemplateHaskell setTemplateHaskellLoc, flagSpec "TraditionalRecordSyntax" Opt_TraditionalRecordSyntax, flagSpec "TransformListComp" Opt_TransformListComp, flagSpec "TupleSections" Opt_TupleSections, flagSpec "TypeFamilies" Opt_TypeFamilies, flagSpec "TypeOperators" Opt_TypeOperators, flagSpec "TypeSynonymInstances" Opt_TypeSynonymInstances, flagSpec "UnboxedTuples" Opt_UnboxedTuples, flagSpec "UndecidableInstances" Opt_UndecidableInstances, flagSpec "UnicodeSyntax" Opt_UnicodeSyntax, flagSpec "UnliftedFFITypes" Opt_UnliftedFFITypes, flagSpec "ViewPatterns" Opt_ViewPatterns ] defaultFlags :: Settings -> [GeneralFlag] defaultFlags settings -- See Note [Updating flag description in the User's Guide] = [ Opt_AutoLinkPackages, Opt_EmbedManifest, Opt_FlatCache, Opt_GenManifest, Opt_GhciHistory, Opt_GhciSandbox, Opt_HelpfulErrors, Opt_OmitYields, Opt_PrintBindContents, Opt_ProfCountEntries, Opt_RPath, Opt_SharedImplib, Opt_SimplPreInlining ] ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns] -- The default -O0 options ++ default_PIC platform ++ (if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings) then wayGeneralFlags platform WayDyn else []) where platform = sTargetPlatform settings default_PIC :: Platform -> [GeneralFlag] default_PIC platform = case (platformOS platform, platformArch platform) of (OSDarwin, ArchX86_64) -> [Opt_PIC] (OSOpenBSD, ArchX86_64) -> [Opt_PIC] -- Due to PIE support in -- OpenBSD since 5.3 release -- (1 May 2013) we need to -- always generate PIC. See -- #10597 for more -- information. _ -> [] impliedGFlags :: [(GeneralFlag, TurnOnFlag, GeneralFlag)] impliedGFlags = [(Opt_DeferTypeErrors, turnOn, Opt_DeferTypedHoles)] impliedXFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)] impliedXFlags -- See Note [Updating flag description in the User's Guide] = [ (Opt_RankNTypes, turnOn, Opt_ExplicitForAll) , (Opt_ScopedTypeVariables, turnOn, Opt_ExplicitForAll) , (Opt_LiberalTypeSynonyms, turnOn, Opt_ExplicitForAll) , (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll) , (Opt_FlexibleInstances, turnOn, Opt_TypeSynonymInstances) , (Opt_FunctionalDependencies, turnOn, Opt_MultiParamTypeClasses) , (Opt_MultiParamTypeClasses, turnOn, Opt_ConstrainedClassMethods) -- c.f. Trac #7854 , (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude) -- NB: turn off! , (Opt_GADTs, turnOn, Opt_GADTSyntax) , (Opt_GADTs, turnOn, Opt_MonoLocalBinds) , (Opt_TypeFamilies, turnOn, Opt_MonoLocalBinds) , (Opt_TypeFamilies, turnOn, Opt_KindSignatures) -- Type families use kind signatures , (Opt_PolyKinds, turnOn, Opt_KindSignatures) -- Ditto polymorphic kinds -- AutoDeriveTypeable is not very useful without DeriveDataTypeable , (Opt_AutoDeriveTypeable, turnOn, Opt_DeriveDataTypeable) -- We turn this on so that we can export associated type -- type synonyms in subordinates (e.g. MyClass(type AssocType)) , (Opt_TypeFamilies, turnOn, Opt_ExplicitNamespaces) , (Opt_TypeOperators, turnOn, Opt_ExplicitNamespaces) , (Opt_ImpredicativeTypes, turnOn, Opt_RankNTypes) -- Record wild-cards implies field disambiguation -- Otherwise if you write (C {..}) you may well get -- stuff like " 'a' not in scope ", which is a bit silly -- if the compiler has just filled in field 'a' of constructor 'C' , (Opt_RecordWildCards, turnOn, Opt_DisambiguateRecordFields) , (Opt_ParallelArrays, turnOn, Opt_ParallelListComp) , (Opt_JavaScriptFFI, turnOn, Opt_InterruptibleFFI) , (Opt_DeriveTraversable, turnOn, Opt_DeriveFunctor) , (Opt_DeriveTraversable, turnOn, Opt_DeriveFoldable) ] -- Note [Documenting optimisation flags] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- If you change the list of flags enabled for particular optimisation levels -- please remember to update the User's Guide. The relevant files are: -- -- * docs/users_guide/flags.xml -- * docs/users_guide/using.xml -- -- The first contains the Flag Refrence section, which breifly lists all -- available flags. The second contains a detailed description of the -- flags. Both places should contain information whether a flag is implied by -- -O0, -O or -O2. optLevelFlags :: [([Int], GeneralFlag)] optLevelFlags -- see Note [Documenting optimisation flags] = [ ([0,1,2], Opt_DoLambdaEtaExpansion) , ([0,1,2], Opt_DmdTxDictSel) , ([0,1,2], Opt_LlvmTBAA) , ([0,1,2], Opt_VectorisationAvoidance) -- This one is important for a tiresome reason: -- we want to make sure that the bindings for data -- constructors are eta-expanded. This is probably -- a good thing anyway, but it seems fragile. , ([0], Opt_IgnoreInterfacePragmas) , ([0], Opt_OmitInterfacePragmas) , ([1,2], Opt_CallArity) , ([1,2], Opt_CaseMerge) , ([1,2], Opt_CmmElimCommonBlocks) , ([1,2], Opt_CmmSink) , ([1,2], Opt_CSE) , ([1,2], Opt_DoEtaReduction) , ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules] -- in PrelRules , ([1,2], Opt_FloatIn) , ([1,2], Opt_FullLaziness) , ([1,2], Opt_IgnoreAsserts) , ([1,2], Opt_Loopification) , ([1,2], Opt_Specialise) , ([1,2], Opt_CrossModuleSpecialise) , ([1,2], Opt_Strictness) , ([1,2], Opt_UnboxSmallStrictFields) , ([2], Opt_LiberateCase) , ([2], Opt_SpecConstr) -- , ([2], Opt_RegsGraph) -- RegsGraph suffers performance regression. See #7679 -- , ([2], Opt_StaticArgumentTransformation) -- Static Argument Transformation needs investigation. See #9374 ] -- ----------------------------------------------------------------------------- -- Standard sets of warning options -- Note [Documenting warning flags] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- If you change the list of warning enabled by default -- please remember to update the User's Guide. The relevant file is: -- -- * docs/users_guide/using.xml standardWarnings :: [WarningFlag] standardWarnings -- see Note [Documenting warning flags] = [ Opt_WarnOverlappingPatterns, Opt_WarnWarningsDeprecations, Opt_WarnDeprecatedFlags, Opt_WarnDeferredTypeErrors, Opt_WarnTypedHoles, Opt_WarnPartialTypeSignatures, Opt_WarnUnrecognisedPragmas, Opt_WarnPointlessPragmas, Opt_WarnRedundantConstraints, Opt_WarnDuplicateExports, Opt_WarnOverflowedLiterals, Opt_WarnEmptyEnumerations, Opt_WarnMissingFields, Opt_WarnMissingMethods, Opt_WarnWrongDoBind, Opt_WarnUnsupportedCallingConventions, Opt_WarnDodgyForeignImports, Opt_WarnInlineRuleShadowing, Opt_WarnAlternativeLayoutRuleTransitional, Opt_WarnUnsupportedLlvmVersion, Opt_WarnContextQuantification, Opt_WarnTabs ] minusWOpts :: [WarningFlag] -- Things you get with -W minusWOpts = standardWarnings ++ [ Opt_WarnUnusedTopBinds, Opt_WarnUnusedLocalBinds, Opt_WarnUnusedPatternBinds, Opt_WarnUnusedMatches, Opt_WarnUnusedImports, Opt_WarnIncompletePatterns, Opt_WarnDodgyExports, Opt_WarnDodgyImports ] minusWallOpts :: [WarningFlag] -- Things you get with -Wall minusWallOpts = minusWOpts ++ [ Opt_WarnTypeDefaults, Opt_WarnNameShadowing, Opt_WarnMissingSigs, Opt_WarnHiShadows, Opt_WarnOrphans, Opt_WarnUnusedDoBind, Opt_WarnTrustworthySafe, Opt_WarnUntickedPromotedConstructors ] enableUnusedBinds :: DynP () enableUnusedBinds = mapM_ setWarningFlag unusedBindsFlags disableUnusedBinds :: DynP () disableUnusedBinds = mapM_ unSetWarningFlag unusedBindsFlags -- Things you get with -fwarn-unused-binds unusedBindsFlags :: [WarningFlag] unusedBindsFlags = [ Opt_WarnUnusedTopBinds , Opt_WarnUnusedLocalBinds , Opt_WarnUnusedPatternBinds ] enableGlasgowExts :: DynP () enableGlasgowExts = do setGeneralFlag Opt_PrintExplicitForalls mapM_ setExtensionFlag glasgowExtsFlags disableGlasgowExts :: DynP () disableGlasgowExts = do unSetGeneralFlag Opt_PrintExplicitForalls mapM_ unSetExtensionFlag glasgowExtsFlags glasgowExtsFlags :: [ExtensionFlag] glasgowExtsFlags = [ Opt_ConstrainedClassMethods , Opt_DeriveDataTypeable , Opt_DeriveFoldable , Opt_DeriveFunctor , Opt_DeriveGeneric , Opt_DeriveTraversable , Opt_EmptyDataDecls , Opt_ExistentialQuantification , Opt_ExplicitNamespaces , Opt_FlexibleContexts , Opt_FlexibleInstances , Opt_ForeignFunctionInterface , Opt_FunctionalDependencies , Opt_GeneralizedNewtypeDeriving , Opt_ImplicitParams , Opt_KindSignatures , Opt_LiberalTypeSynonyms , Opt_MagicHash , Opt_MultiParamTypeClasses , Opt_ParallelListComp , Opt_PatternGuards , Opt_PostfixOperators , Opt_RankNTypes , Opt_RecursiveDo , Opt_ScopedTypeVariables , Opt_StandaloneDeriving , Opt_TypeOperators , Opt_TypeSynonymInstances , Opt_UnboxedTuples , Opt_UnicodeSyntax , Opt_UnliftedFFITypes ] #ifdef GHCI -- Consult the RTS to find whether GHC itself has been built profiled -- If so, you can't use Template Haskell foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt rtsIsProfiled :: Bool rtsIsProfiled = unsafeDupablePerformIO rtsIsProfiledIO /= 0 #endif #ifdef GHCI -- Consult the RTS to find whether GHC itself has been built with -- dynamic linking. This can't be statically known at compile-time, -- because we build both the static and dynamic versions together with -- -dynamic-too. foreign import ccall unsafe "rts_isDynamic" rtsIsDynamicIO :: IO CInt dynamicGhc :: Bool dynamicGhc = unsafeDupablePerformIO rtsIsDynamicIO /= 0 #else dynamicGhc :: Bool dynamicGhc = False #endif setWarnSafe :: Bool -> DynP () setWarnSafe True = getCurLoc >>= \l -> upd (\d -> d { warnSafeOnLoc = l }) setWarnSafe False = return () setWarnUnsafe :: Bool -> DynP () setWarnUnsafe True = getCurLoc >>= \l -> upd (\d -> d { warnUnsafeOnLoc = l }) setWarnUnsafe False = return () setPackageTrust :: DynP () setPackageTrust = do setGeneralFlag Opt_PackageTrust l <- getCurLoc upd $ \d -> d { pkgTrustOnLoc = l } setGenDeriving :: TurnOnFlag -> DynP () setGenDeriving True = getCurLoc >>= \l -> upd (\d -> d { newDerivOnLoc = l }) setGenDeriving False = return () setOverlappingInsts :: TurnOnFlag -> DynP () setOverlappingInsts False = return () setOverlappingInsts True = do l <- getCurLoc upd (\d -> d { overlapInstLoc = l }) deprecate "instead use per-instance pragmas OVERLAPPING/OVERLAPPABLE/OVERLAPS" setIncoherentInsts :: TurnOnFlag -> DynP () setIncoherentInsts False = return () setIncoherentInsts True = do l <- getCurLoc upd (\d -> d { incoherentOnLoc = l }) setTemplateHaskellLoc :: TurnOnFlag -> DynP () setTemplateHaskellLoc _ = getCurLoc >>= \l -> upd (\d -> d { thOnLoc = l }) {- ********************************************************************** %* * DynFlags constructors %* * %********************************************************************* -} type DynP = EwM (CmdLineP DynFlags) upd :: (DynFlags -> DynFlags) -> DynP () upd f = liftEwM (do dflags <- getCmdLineState putCmdLineState $! f dflags) updM :: (DynFlags -> DynP DynFlags) -> DynP () updM f = do dflags <- liftEwM getCmdLineState dflags' <- f dflags liftEwM $ putCmdLineState $! dflags' --------------- Constructor functions for OptKind ----------------- noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) noArg fn = NoArg (upd fn) noArgM :: (DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags) noArgM fn = NoArg (updM fn) hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) hasArg fn = HasArg (upd . fn) sepArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) sepArg fn = SepArg (upd . fn) intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) intSuffix fn = IntSuffix (\n -> upd (fn n)) intSuffixM :: (Int -> DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags) intSuffixM fn = IntSuffix (\n -> updM (fn n)) floatSuffix :: (Float -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) floatSuffix fn = FloatSuffix (\n -> upd (fn n)) optIntSuffixM :: (Maybe Int -> DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags) optIntSuffixM fn = OptIntSuffix (\mi -> updM (fn mi)) setDumpFlag :: DumpFlag -> OptKind (CmdLineP DynFlags) setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag) -------------------------- addWay :: Way -> DynP () addWay w = upd (addWay' w) addWay' :: Way -> DynFlags -> DynFlags addWay' w dflags0 = let platform = targetPlatform dflags0 dflags1 = dflags0 { ways = w : ways dflags0 } dflags2 = wayExtras platform w dflags1 dflags3 = foldr setGeneralFlag' dflags2 (wayGeneralFlags platform w) dflags4 = foldr unSetGeneralFlag' dflags3 (wayUnsetGeneralFlags platform w) in dflags4 removeWayDyn :: DynP () removeWayDyn = upd (\dfs -> dfs { ways = filter (WayDyn /=) (ways dfs) }) -------------------------- setGeneralFlag, unSetGeneralFlag :: GeneralFlag -> DynP () setGeneralFlag f = upd (setGeneralFlag' f) unSetGeneralFlag f = upd (unSetGeneralFlag' f) setGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags setGeneralFlag' f dflags = foldr ($) (gopt_set dflags f) deps where deps = [ if turn_on then setGeneralFlag' d else unSetGeneralFlag' d | (f', turn_on, d) <- impliedGFlags, f' == f ] -- When you set f, set the ones it implies -- NB: use setGeneralFlag recursively, in case the implied flags -- implies further flags unSetGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags unSetGeneralFlag' f dflags = gopt_unset dflags f -- When you un-set f, however, we don't un-set the things it implies -------------------------- setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP () setWarningFlag f = upd (\dfs -> wopt_set dfs f) unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f) -------------------------- setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP () setExtensionFlag f = upd (setExtensionFlag' f) unSetExtensionFlag f = upd (unSetExtensionFlag' f) setExtensionFlag', unSetExtensionFlag' :: ExtensionFlag -> DynFlags -> DynFlags setExtensionFlag' f dflags = foldr ($) (xopt_set dflags f) deps where deps = [ if turn_on then setExtensionFlag' d else unSetExtensionFlag' d | (f', turn_on, d) <- impliedXFlags, f' == f ] -- When you set f, set the ones it implies -- NB: use setExtensionFlag recursively, in case the implied flags -- implies further flags unSetExtensionFlag' f dflags = xopt_unset dflags f -- When you un-set f, however, we don't un-set the things it implies -- (except for -fno-glasgow-exts, which is treated specially) -------------------------- alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags alterSettings f dflags = dflags { settings = f (settings dflags) } -------------------------- setDumpFlag' :: DumpFlag -> DynP () setDumpFlag' dump_flag = do upd (\dfs -> dopt_set dfs dump_flag) when want_recomp forceRecompile where -- Certain dumpy-things are really interested in what's going -- on during recompilation checking, so in those cases we -- don't want to turn it off. want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace, Opt_D_dump_hi_diffs] forceRecompile :: DynP () -- Whenver we -ddump, force recompilation (by switching off the -- recompilation checker), else you don't see the dump! However, -- don't switch it off in --make mode, else *everything* gets -- recompiled which probably isn't what you want forceRecompile = do dfs <- liftEwM getCmdLineState when (force_recomp dfs) (setGeneralFlag Opt_ForceRecomp) where force_recomp dfs = isOneShot (ghcMode dfs) setVerboseCore2Core :: DynP () setVerboseCore2Core = setDumpFlag' Opt_D_verbose_core2core setVerbosity :: Maybe Int -> DynP () setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 }) addCmdlineHCInclude :: String -> DynP () addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s}) data PkgConfRef = GlobalPkgConf | UserPkgConf | PkgConfFile FilePath addPkgConfRef :: PkgConfRef -> DynP () addPkgConfRef p = upd $ \s -> s { extraPkgConfs = (p:) . extraPkgConfs s } removeUserPkgConf :: DynP () removeUserPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotUser . extraPkgConfs s } where isNotUser UserPkgConf = False isNotUser _ = True removeGlobalPkgConf :: DynP () removeGlobalPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotGlobal . extraPkgConfs s } where isNotGlobal GlobalPkgConf = False isNotGlobal _ = True clearPkgConf :: DynP () clearPkgConf = upd $ \s -> s { extraPkgConfs = const [] } parseModuleName :: ReadP ModuleName parseModuleName = fmap mkModuleName $ munch1 (\c -> isAlphaNum c || c `elem` ".") parsePackageFlag :: (String -> PackageArg) -- type of argument -> String -- string to parse -> PackageFlag parsePackageFlag constr str = case filter ((=="").snd) (readP_to_S parse str) of [(r, "")] -> r _ -> throwGhcException $ CmdLineError ("Can't parse package flag: " ++ str) where parse = do pkg <- tok $ munch1 (\c -> isAlphaNum c || c `elem` ":-_.") ( do _ <- tok $ string "with" fmap (ExposePackage (constr pkg) . ModRenaming True) parseRns <++ fmap (ExposePackage (constr pkg) . ModRenaming False) parseRns <++ return (ExposePackage (constr pkg) (ModRenaming True []))) parseRns = do _ <- tok $ R.char '(' rns <- tok $ sepBy parseItem (tok $ R.char ',') _ <- tok $ R.char ')' return rns parseItem = do orig <- tok $ parseModuleName (do _ <- tok $ string "as" new <- tok $ parseModuleName return (orig, new) +++ return (orig, orig)) tok m = m >>= \x -> skipSpaces >> return x exposePackage, exposePackageId, exposePackageKey, hidePackage, ignorePackage, trustPackage, distrustPackage :: String -> DynP () exposePackage p = upd (exposePackage' p) exposePackageId p = upd (\s -> s{ packageFlags = parsePackageFlag PackageIdArg p : packageFlags s }) exposePackageKey p = upd (\s -> s{ packageFlags = parsePackageFlag PackageKeyArg p : packageFlags s }) hidePackage p = upd (\s -> s{ packageFlags = HidePackage p : packageFlags s }) ignorePackage p = upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s }) trustPackage p = exposePackage p >> -- both trust and distrust also expose a package upd (\s -> s{ packageFlags = TrustPackage p : packageFlags s }) distrustPackage p = exposePackage p >> upd (\s -> s{ packageFlags = DistrustPackage p : packageFlags s }) exposePackage' :: String -> DynFlags -> DynFlags exposePackage' p dflags = dflags { packageFlags = parsePackageFlag PackageArg p : packageFlags dflags } setPackageKey :: String -> DynFlags -> DynFlags setPackageKey p s = s{ thisPackage = stringToPackageKey p } -- ----------------------------------------------------------------------------- -- | Find the package environment (if one exists) -- -- We interpret the package environment as a set of package flags; to be -- specific, if we find a package environment -- -- > id1 -- > id2 -- > .. -- > idn -- -- we interpret this as -- -- > [ -hide-all-packages -- > , -package-id id1 -- > , -package-id id2 -- > , .. -- > , -package-id idn -- > ] interpretPackageEnv :: DynFlags -> IO DynFlags interpretPackageEnv dflags = do mPkgEnv <- runMaybeT $ msum $ [ getCmdLineArg >>= \env -> msum [ loadEnvFile env , loadEnvName env , cmdLineError env ] , getEnvVar >>= \env -> msum [ loadEnvFile env , loadEnvName env , envError env ] , loadEnvFile localEnvFile , loadEnvName defaultEnvName ] case mPkgEnv of Nothing -> -- No environment found. Leave DynFlags unchanged. return dflags Just ids -> do let setFlags :: DynP () setFlags = do setGeneralFlag Opt_HideAllPackages mapM_ exposePackageId (lines ids) (_, dflags') = runCmdLine (runEwM setFlags) dflags return dflags' where -- Loading environments (by name or by location) namedEnvPath :: String -> MaybeT IO FilePath namedEnvPath name = do appdir <- liftMaybeT $ versionedAppDir dflags return $ appdir </> "environments" </> name loadEnvName :: String -> MaybeT IO String loadEnvName name = loadEnvFile =<< namedEnvPath name loadEnvFile :: String -> MaybeT IO String loadEnvFile path = do guard =<< liftMaybeT (doesFileExist path) liftMaybeT $ readFile path -- Various ways to define which environment to use getCmdLineArg :: MaybeT IO String getCmdLineArg = MaybeT $ return $ packageEnv dflags getEnvVar :: MaybeT IO String getEnvVar = do mvar <- liftMaybeT $ try $ getEnv "GHC_ENVIRONMENT" case mvar of Right var -> return var Left err -> if isDoesNotExistError err then mzero else liftMaybeT $ throwIO err defaultEnvName :: String defaultEnvName = "default" localEnvFile :: FilePath localEnvFile = "./.ghc.environment" -- Error reporting cmdLineError :: String -> MaybeT IO a cmdLineError env = liftMaybeT . throwGhcExceptionIO . CmdLineError $ "Package environment " ++ show env ++ " not found" envError :: String -> MaybeT IO a envError env = liftMaybeT . throwGhcExceptionIO . CmdLineError $ "Package environment " ++ show env ++ " (specified in GHC_ENVIRIONMENT) not found" -- If we're linking a binary, then only targets that produce object -- code are allowed (requests for other target types are ignored). setTarget :: HscTarget -> DynP () setTarget l = setTargetWithPlatform (const l) setTargetWithPlatform :: (Platform -> HscTarget) -> DynP () setTargetWithPlatform f = upd set where set dfs = let l = f (targetPlatform dfs) in if ghcLink dfs /= LinkBinary || isObjectTarget l then dfs{ hscTarget = l } else dfs -- Changes the target only if we're compiling object code. This is -- used by -fasm and -fllvm, which switch from one to the other, but -- not from bytecode to object-code. The idea is that -fasm/-fllvm -- can be safely used in an OPTIONS_GHC pragma. setObjTarget :: HscTarget -> DynP () setObjTarget l = updM set where set dflags | isObjectTarget (hscTarget dflags) = return $ dflags { hscTarget = l } | otherwise = return dflags setOptLevel :: Int -> DynFlags -> DynP DynFlags setOptLevel n dflags = return (updOptLevel n dflags) checkOptLevel :: Int -> DynFlags -> Either String DynFlags checkOptLevel n dflags | hscTarget dflags == HscInterpreted && n > 0 = Left "-O conflicts with --interactive; -O ignored." | otherwise = Right dflags -- -Odph is equivalent to -- -- -O2 optimise as much as possible -- -fmax-simplifier-iterations20 this is necessary sometimes -- -fsimplifier-phases=3 we use an additional simplifier phase for fusion -- setDPHOpt :: DynFlags -> DynP DynFlags setDPHOpt dflags = setOptLevel 2 (dflags { maxSimplIterations = 20 , simplPhases = 3 }) setMainIs :: String -> DynP () setMainIs arg | not (null main_fn) && isLower (head main_fn) -- The arg looked like "Foo.Bar.baz" = upd $ \d -> d{ mainFunIs = Just main_fn, mainModIs = mkModule mainPackageKey (mkModuleName main_mod) } | isUpper (head arg) -- The arg looked like "Foo" or "Foo.Bar" = upd $ \d -> d{ mainModIs = mkModule mainPackageKey (mkModuleName arg) } | otherwise -- The arg looked like "baz" = upd $ \d -> d{ mainFunIs = Just arg } where (main_mod, main_fn) = splitLongestPrefix arg (== '.') addLdInputs :: Option -> DynFlags -> DynFlags addLdInputs p dflags = dflags{ldInputs = ldInputs dflags ++ [p]} ----------------------------------------------------------------------------- -- Paths & Libraries addImportPath, addLibraryPath, addIncludePath, addFrameworkPath :: FilePath -> DynP () -- -i on its own deletes the import paths addImportPath "" = upd (\s -> s{importPaths = []}) addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p}) addLibraryPath p = upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p}) addIncludePath p = upd (\s -> s{includePaths = includePaths s ++ splitPathList p}) addFrameworkPath p = upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p}) #ifndef mingw32_TARGET_OS split_marker :: Char split_marker = ':' -- not configurable (ToDo) #endif splitPathList :: String -> [String] splitPathList s = filter notNull (splitUp s) -- empty paths are ignored: there might be a trailing -- ':' in the initial list, for example. Empty paths can -- cause confusion when they are translated into -I options -- for passing to gcc. where #ifndef mingw32_TARGET_OS splitUp xs = split split_marker xs #else -- Windows: 'hybrid' support for DOS-style paths in directory lists. -- -- That is, if "foo:bar:baz" is used, this interpreted as -- consisting of three entries, 'foo', 'bar', 'baz'. -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar" -- -- Notice that no attempt is made to fully replace the 'standard' -- split marker ':' with the Windows / DOS one, ';'. The reason being -- that this will cause too much breakage for users & ':' will -- work fine even with DOS paths, if you're not insisting on being silly. -- So, use either. splitUp [] = [] splitUp (x:':':div:xs) | div `elem` dir_markers = ((x:':':div:p): splitUp rs) where (p,rs) = findNextPath xs -- we used to check for existence of the path here, but that -- required the IO monad to be threaded through the command-line -- parser which is quite inconvenient. The splitUp xs = cons p (splitUp rs) where (p,rs) = findNextPath xs cons "" xs = xs cons x xs = x:xs -- will be called either when we've consumed nought or the -- "<Drive>:/" part of a DOS path, so splitting is just a Q of -- finding the next split marker. findNextPath xs = case break (`elem` split_markers) xs of (p, _:ds) -> (p, ds) (p, xs) -> (p, xs) split_markers :: [Char] split_markers = [':', ';'] dir_markers :: [Char] dir_markers = ['/', '\\'] #endif -- ----------------------------------------------------------------------------- -- tmpDir, where we store temporary files. setTmpDir :: FilePath -> DynFlags -> DynFlags setTmpDir dir = alterSettings (\s -> s { sTmpDir = normalise dir }) -- we used to fix /cygdrive/c/.. on Windows, but this doesn't -- seem necessary now --SDM 7/2/2008 ----------------------------------------------------------------------------- -- RTS opts setRtsOpts :: String -> DynP () setRtsOpts arg = upd $ \ d -> d {rtsOpts = Just arg} setRtsOptsEnabled :: RtsOptsEnabled -> DynP () setRtsOptsEnabled arg = upd $ \ d -> d {rtsOptsEnabled = arg} ----------------------------------------------------------------------------- -- Hpc stuff setOptHpcDir :: String -> DynP () setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg} ----------------------------------------------------------------------------- -- Via-C compilation stuff -- There are some options that we need to pass to gcc when compiling -- Haskell code via C, but are only supported by recent versions of -- gcc. The configure script decides which of these options we need, -- and puts them in the "settings" file in $topdir. The advantage of -- having these in a separate file is that the file can be created at -- install-time depending on the available gcc version, and even -- re-generated later if gcc is upgraded. -- -- The options below are not dependent on the version of gcc, only the -- platform. picCCOpts :: DynFlags -> [String] picCCOpts dflags = case platformOS (targetPlatform dflags) of OSDarwin -- Apple prefers to do things the other way round. -- PIC is on by default. -- -mdynamic-no-pic: -- Turn off PIC code generation. -- -fno-common: -- Don't generate "common" symbols - these are unwanted -- in dynamic libraries. | gopt Opt_PIC dflags -> ["-fno-common", "-U__PIC__", "-D__PIC__"] | otherwise -> ["-mdynamic-no-pic"] OSMinGW32 -- no -fPIC for Windows | gopt Opt_PIC dflags -> ["-U__PIC__", "-D__PIC__"] | otherwise -> [] _ -- we need -fPIC for C files when we are compiling with -dynamic, -- otherwise things like stub.c files don't get compiled -- correctly. They need to reference data in the Haskell -- objects, but can't without -fPIC. See -- http://ghc.haskell.org/trac/ghc/wiki/Commentary/PositionIndependentCode | gopt Opt_PIC dflags || not (gopt Opt_Static dflags) -> ["-fPIC", "-U__PIC__", "-D__PIC__"] | otherwise -> [] picPOpts :: DynFlags -> [String] picPOpts dflags | gopt Opt_PIC dflags = ["-U__PIC__", "-D__PIC__"] | otherwise = [] -- ----------------------------------------------------------------------------- -- Splitting can_split :: Bool can_split = cSupportsSplitObjs == "YES" -- ----------------------------------------------------------------------------- -- Compiler Info compilerInfo :: DynFlags -> [(String, String)] compilerInfo dflags = -- We always make "Project name" be first to keep parsing in -- other languages simple, i.e. when looking for other fields, -- you don't have to worry whether there is a leading '[' or not ("Project name", cProjectName) -- Next come the settings, so anything else can be overridden -- in the settings file (as "lookup" uses the first match for the -- key) : rawSettings dflags ++ [("Project version", projectVersion dflags), ("Project Git commit id", cProjectGitCommitId), ("Booter version", cBooterVersion), ("Stage", cStage), ("Build platform", cBuildPlatformString), ("Host platform", cHostPlatformString), ("Target platform", cTargetPlatformString), ("Have interpreter", cGhcWithInterpreter), ("Object splitting supported", cSupportsSplitObjs), ("Have native code generator", cGhcWithNativeCodeGen), ("Support SMP", cGhcWithSMP), ("Tables next to code", cGhcEnableTablesNextToCode), ("RTS ways", cGhcRTSWays), ("Support dynamic-too", if isWindows then "NO" else "YES"), ("Support parallel --make", "YES"), ("Support reexported-modules", "YES"), ("Support thinning and renaming package flags", "YES"), ("Uses package keys", "YES"), ("Dynamic by default", if dYNAMIC_BY_DEFAULT dflags then "YES" else "NO"), ("GHC Dynamic", if dynamicGhc then "YES" else "NO"), ("Leading underscore", cLeadingUnderscore), ("Debug on", show debugIsOn), ("LibDir", topDir dflags), ("Global Package DB", systemPackageConfig dflags) ] where isWindows = platformOS (targetPlatform dflags) == OSMinGW32 #include "../includes/dist-derivedconstants/header/GHCConstantsHaskellWrappers.hs" bLOCK_SIZE_W :: DynFlags -> Int bLOCK_SIZE_W dflags = bLOCK_SIZE dflags `quot` wORD_SIZE dflags wORD_SIZE_IN_BITS :: DynFlags -> Int wORD_SIZE_IN_BITS dflags = wORD_SIZE dflags * 8 tAG_MASK :: DynFlags -> Int tAG_MASK dflags = (1 `shiftL` tAG_BITS dflags) - 1 mAX_PTR_TAG :: DynFlags -> Int mAX_PTR_TAG = tAG_MASK -- Might be worth caching these in targetPlatform? tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD :: DynFlags -> Integer tARGET_MIN_INT dflags = case platformWordSize (targetPlatform dflags) of 4 -> toInteger (minBound :: Int32) 8 -> toInteger (minBound :: Int64) w -> panic ("tARGET_MIN_INT: Unknown platformWordSize: " ++ show w) tARGET_MAX_INT dflags = case platformWordSize (targetPlatform dflags) of 4 -> toInteger (maxBound :: Int32) 8 -> toInteger (maxBound :: Int64) w -> panic ("tARGET_MAX_INT: Unknown platformWordSize: " ++ show w) tARGET_MAX_WORD dflags = case platformWordSize (targetPlatform dflags) of 4 -> toInteger (maxBound :: Word32) 8 -> toInteger (maxBound :: Word64) w -> panic ("tARGET_MAX_WORD: Unknown platformWordSize: " ++ show w) -- Whenever makeDynFlagsConsistent does anything, it starts over, to -- ensure that a later change doesn't invalidate an earlier check. -- Be careful not to introduce potential loops! makeDynFlagsConsistent :: DynFlags -> (DynFlags, [Located String]) makeDynFlagsConsistent dflags -- Disable -dynamic-too on Windows (#8228, #7134, #5987) | os == OSMinGW32 && gopt Opt_BuildDynamicToo dflags = let dflags' = gopt_unset dflags Opt_BuildDynamicToo warn = "-dynamic-too is not supported on Windows" in loop dflags' warn | hscTarget dflags == HscC && not (platformUnregisterised (targetPlatform dflags)) = if cGhcWithNativeCodeGen == "YES" then let dflags' = dflags { hscTarget = HscAsm } warn = "Compiler not unregisterised, so using native code generator rather than compiling via C" in loop dflags' warn else let dflags' = dflags { hscTarget = HscLlvm } warn = "Compiler not unregisterised, so using LLVM rather than compiling via C" in loop dflags' warn | hscTarget dflags == HscAsm && platformUnregisterised (targetPlatform dflags) = loop (dflags { hscTarget = HscC }) "Compiler unregisterised, so compiling via C" | hscTarget dflags == HscAsm && cGhcWithNativeCodeGen /= "YES" = let dflags' = dflags { hscTarget = HscLlvm } warn = "No native code generator, so using LLVM" in loop dflags' warn | hscTarget dflags == HscLlvm && not ((arch == ArchX86_64) && (os == OSLinux || os == OSDarwin || os == OSFreeBSD)) && not ((isARM arch) && (os == OSLinux)) && (not (gopt Opt_Static dflags) || gopt Opt_PIC dflags) = if cGhcWithNativeCodeGen == "YES" then let dflags' = dflags { hscTarget = HscAsm } warn = "Using native code generator rather than LLVM, as LLVM is incompatible with -fPIC and -dynamic on this platform" in loop dflags' warn else throwGhcException $ CmdLineError "Can't use -fPIC or -dynamic on this platform" | os == OSDarwin && arch == ArchX86_64 && not (gopt Opt_PIC dflags) = loop (gopt_set dflags Opt_PIC) "Enabling -fPIC as it is always on for this platform" | otherwise = (dflags, []) where loc = mkGeneralSrcSpan (fsLit "when making flags consistent") loop updated_dflags warning = case makeDynFlagsConsistent updated_dflags of (dflags', ws) -> (dflags', L loc warning : ws) platform = targetPlatform dflags arch = platformArch platform os = platformOS platform -------------------------------------------------------------------------- -- Do not use unsafeGlobalDynFlags! -- -- unsafeGlobalDynFlags is a hack, necessary because we need to be able -- to show SDocs when tracing, but we don't always have DynFlags -- available. -- -- Do not use it if you can help it. You may get the wrong value, or this -- panic! GLOBAL_VAR(v_unsafeGlobalDynFlags, panic "v_unsafeGlobalDynFlags: not initialised", DynFlags) unsafeGlobalDynFlags :: DynFlags unsafeGlobalDynFlags = unsafePerformIO $ readIORef v_unsafeGlobalDynFlags setUnsafeGlobalDynFlags :: DynFlags -> IO () setUnsafeGlobalDynFlags = writeIORef v_unsafeGlobalDynFlags -- ----------------------------------------------------------------------------- -- SSE and AVX -- TODO: Instead of using a separate predicate (i.e. isSse2Enabled) to -- check if SSE is enabled, we might have x86-64 imply the -msse2 -- flag. data SseVersion = SSE1 | SSE2 | SSE3 | SSE4 | SSE42 deriving (Eq, Ord) isSseEnabled :: DynFlags -> Bool isSseEnabled dflags = case platformArch (targetPlatform dflags) of ArchX86_64 -> True ArchX86 -> sseVersion dflags >= Just SSE1 _ -> False isSse2Enabled :: DynFlags -> Bool isSse2Enabled dflags = case platformArch (targetPlatform dflags) of ArchX86_64 -> -- SSE2 is fixed on for x86_64. It would be -- possible to make it optional, but we'd need to -- fix at least the foreign call code where the -- calling convention specifies the use of xmm regs, -- and possibly other places. True ArchX86 -> sseVersion dflags >= Just SSE2 _ -> False isSse4_2Enabled :: DynFlags -> Bool isSse4_2Enabled dflags = sseVersion dflags >= Just SSE42 isAvxEnabled :: DynFlags -> Bool isAvxEnabled dflags = avx dflags || avx2 dflags || avx512f dflags isAvx2Enabled :: DynFlags -> Bool isAvx2Enabled dflags = avx2 dflags || avx512f dflags isAvx512cdEnabled :: DynFlags -> Bool isAvx512cdEnabled dflags = avx512cd dflags isAvx512erEnabled :: DynFlags -> Bool isAvx512erEnabled dflags = avx512er dflags isAvx512fEnabled :: DynFlags -> Bool isAvx512fEnabled dflags = avx512f dflags isAvx512pfEnabled :: DynFlags -> Bool isAvx512pfEnabled dflags = avx512pf dflags -- ----------------------------------------------------------------------------- -- Linker/compiler information -- LinkerInfo contains any extra options needed by the system linker. data LinkerInfo = GnuLD [Option] | GnuGold [Option] | DarwinLD [Option] | SolarisLD [Option] | UnknownLD deriving Eq -- CompilerInfo tells us which C compiler we're using data CompilerInfo = GCC | Clang | AppleClang | AppleClang51 | UnknownCC deriving Eq -- ----------------------------------------------------------------------------- -- RTS hooks -- Convert sizes like "3.5M" into integers decodeSize :: String -> Integer decodeSize str | c == "" = truncate n | c == "K" || c == "k" = truncate (n * 1000) | c == "M" || c == "m" = truncate (n * 1000 * 1000) | c == "G" || c == "g" = truncate (n * 1000 * 1000 * 1000) | otherwise = throwGhcException (CmdLineError ("can't decode size: " ++ str)) where (m, c) = span pred str n = readRational m pred c = isDigit c || c == '.' foreign import ccall unsafe "setHeapSize" setHeapSize :: Int -> IO () foreign import ccall unsafe "enableTimingStats" enableTimingStats :: IO ()
urbanslug/ghc
compiler/main/DynFlags.hs
bsd-3-clause
176,190
0
34
47,514
32,379
17,803
14,576
-1
-1
{-# LANGUAGE BangPatterns, DefaultSignatures, FlexibleContexts, OverloadedStrings, GeneralizedNewtypeDeriving #-} module Data.Text.Serialize.Read.Class where import Control.Monad.Reader import Control.Monad import Data.Attoparsec.Text import GHC.Generics import Control.Applicative import Prelude hiding (Read(..)) import Data.Text.Serialize.Read.Lex import qualified Data.Text as T class Read a where parsePrec :: ParserPrec a default parsePrec :: (Generic a, GRead (Rep a)) => ParserPrec a parsePrec = \n -> to <$> gparsePrec n {-# INLINE parsePrec #-} parsePrefix :: Parser a default parsePrefix :: (Generic a, GRead (Rep a)) => Parser a parsePrefix = to <$> gparsePrefix class GRead f where gparsePrec :: ParserPrec (f x) gparsePrefix :: Parser (f x) ---------------------------------------------------------------------------------------------------- -- ParserPrec and friends -- | An attoparsec 'Parser' together with parenthesis information. type ParserPrec a = Int -> Parser a atto :: Parser a -> ParserPrec a atto p = const p {-# INLINE atto #-} -- | Consumes all whitespace and parens before p, and just the matching parens after p. parens_ :: ParserPrec a -> ParserPrec a parens_ p n = do np <- openParens_ a <- p (if np > 0 then 0 else n) closeParens np return a {-# INLINE parens_ #-} -- | Consumes all the open parens and whitespace, returning how many open parens there were. openParens_ :: Parser Int openParens_ = skipSpace *> go 0 where go !acc = (char '(' *> skipSpace *> go (acc + 1)) <|> return acc closeParens :: Int -> Parser () closeParens 0 = return () closeParens n = skipSpace *> char ')' *> closeParens (n-1) paren :: Parser a -> Parser a paren p = do skipSpace char '(' a <- p skipSpace char ')' return a prec :: Int -> ParserPrec a -> ParserPrec a prec n p n' = if n' <= n then p n else empty {-# INLINE prec #-}
reinerp/text-serialise
Data/Text/Serialize/Read/Class.hs
bsd-3-clause
1,915
0
12
369
552
285
267
50
2
module Network.MtGoxAPI.TickerMonitor ( initTickerMonitor , getTickerStatus , updateTickerStatus , TickerStatus(..) , TickerMonitorHandle ) where import Control.Applicative import Control.Concurrent import Control.Watchdog import Data.Time.Clock import Network.MtGoxAPI.Types newtype TickerMonitorHandle = TickerMonitorHandle { unTMH :: MVar (Maybe TickerStatus) } data TickerStatus = TickerStatus { tsTimestamp :: UTCTime , tsBid :: Integer , tsAsk :: Integer , tsLast :: Integer , tsPrecision :: Integer } | TickerUnavailable deriving (Show) expectedPrecision :: Integer expectedPrecision = 5 maximumAgeInSeconds :: NominalDiffTime maximumAgeInSeconds = 300 watchdogSettings :: WatchdogAction () watchdogSettings = do setLoggingAction silentLogger setInitialDelay 250000 -- 250 ms setMaximumRetries 6 -- will fail after: -- 0.25 + 0.5 + 1 + 2 + 4 + 8 seconds = 15.75 seconds -- | Access latest ticker status in a safe way. It will be checked, whether -- fresh data is available (never older than 300 seconds) and if not, re-try a -- few times before giving up. The function will not block for longer than -- about 20 seconds. getTickerStatus :: TickerMonitorHandle -> IO TickerStatus getTickerStatus TickerMonitorHandle { unTMH = store } = do let task = getTickerStatus' store result <- watchdog $ do watchdogSettings watchImpatiently task return $ case result of Left _ -> TickerUnavailable Right status -> status getTickerStatus' :: MVar (Maybe TickerStatus) -> IO (Either String TickerStatus) getTickerStatus' store = do tickerStatusM <- readMVar store case tickerStatusM of Nothing -> return $ Left "No ticker data present" Just tickerStatus -> do now <- getCurrentTime let age = diffUTCTime now (tsTimestamp tickerStatus) return $ if age < maximumAgeInSeconds then Right tickerStatus else Left "Data stale" -- | Update ticker with new data. updateTickerStatus :: TickerMonitorHandle -> StreamMessage -> IO () updateTickerStatus TickerMonitorHandle { unTMH = tickerStore } (update@TickerUpdateUSD {}) = do now <- getCurrentTime let tickerStatus = TickerStatus { tsTimestamp = now , tsBid = tuBid update , tsAsk = tuAsk update , tsLast = tuLast update , tsPrecision = expectedPrecision } _ <- swapMVar tickerStore (Just tickerStatus) return () updateTickerStatus _ _ = return () -- | Initializes ticker monitor and returns a handle for it. initTickerMonitor :: IO TickerMonitorHandle initTickerMonitor = TickerMonitorHandle <$> newMVar Nothing
javgh/mtgoxapi
Network/MtGoxAPI/TickerMonitor.hs
bsd-3-clause
3,143
0
17
1,044
571
299
272
63
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} -- | The Github Repos API, as documented at -- <http://developer.github.com/v3/repos/> module Github.Repos ( -- * Querying repositories userRepos ,userRepos' ,userRepo ,userRepo' ,organizationRepos ,organizationRepos' ,organizationRepo ,organizationRepo' ,contributors ,contributors' ,contributorsWithAnonymous ,contributorsWithAnonymous' ,languagesFor ,languagesFor' ,tagsFor ,tagsFor' ,branchesFor ,branchesFor' ,contentsFor ,contentsFor' ,module Github.Data ,RepoPublicity(..) -- ** Create ,createRepo ,createOrganizationRepo ,newRepo ,NewRepo(..) -- ** Edit ,editRepo ,def ,Edit(..) -- ** Delete ,deleteRepo ) where import Data.Default import Data.Aeson.Types import Github.Data import Github.Private import Network.HTTP.Conduit import Control.Applicative import qualified Control.Exception as E import Network.HTTP.Types -- | Filter the list of the user's repos using any of these constructors. data RepoPublicity = All -- ^ All repos accessible to the user. | Owner -- ^ Only repos owned by the user. | Public -- ^ Only public repos. | Private -- ^ Only private repos. | Member -- ^ Only repos to which the user is a member but not an owner. deriving (Show, Eq) -- | The repos for a user, by their login. Can be restricted to just repos they -- own, are a member of, or publicize. Private repos are currently not -- supported. -- -- > userRepos "mike-burns" All userRepos :: String -> RepoPublicity -> IO (Either Error [Repo]) userRepos = userRepos' Nothing -- | The repos for a user, by their login. -- With authentication, but note that private repos are currently not supported. -- -- > userRepos' (Just (GithubBasicAuth (user, password))) "mike-burns" All userRepos' :: Maybe GithubAuth -> String -> RepoPublicity -> IO (Either Error [Repo]) userRepos' auth userName All = githubGetWithQueryString' auth ["users", userName, "repos"] "type=all" userRepos' auth userName Owner = githubGetWithQueryString' auth ["users", userName, "repos"] "type=owner" userRepos' auth userName Member = githubGetWithQueryString' auth ["users", userName, "repos"] "type=member" userRepos' auth userName Public = githubGetWithQueryString' auth ["users", userName, "repos"] "type=public" userRepos' _auth _userName Private = return $ Left $ UserError "Cannot access private repos using userRepos" -- | The repos for an organization, by the organization name. -- -- > organizationRepos "thoughtbot" organizationRepos :: String -> IO (Either Error [Repo]) organizationRepos = organizationRepos' Nothing -- | The repos for an organization, by the organization name. -- With authentication. -- -- > organizationRepos (Just (GithubBasicAuth (user, password))) "thoughtbot" organizationRepos' :: Maybe GithubAuth -> String -> IO (Either Error [Repo]) organizationRepos' auth orgName = githubGet' auth ["orgs", orgName, "repos"] -- | A specific organization repo, by the organization name. -- -- > organizationRepo "thoughtbot" "github" organizationRepo :: String -> String -> IO (Either Error Repo) organizationRepo = organizationRepo' Nothing -- | A specific organization repo, by the organization name. -- With authentication. -- -- > organizationRepo (Just (GithubBasicAuth (user, password))) "thoughtbot" "github" organizationRepo' :: Maybe GithubAuth -> String -> String -> IO (Either Error Repo) organizationRepo' auth orgName reqRepoName = githubGet' auth ["orgs", orgName, reqRepoName] -- | Details on a specific repo, given the owner and repo name. -- -- > userRepo "mike-burns" "github" userRepo :: String -> String -> IO (Either Error Repo) userRepo = userRepo' Nothing -- | Details on a specific repo, given the owner and repo name. -- With authentication. -- -- > userRepo' (Just (GithubBasicAuth (user, password))) "mike-burns" "github" userRepo' :: Maybe GithubAuth -> String -> String -> IO (Either Error Repo) userRepo' auth userName reqRepoName = githubGet' auth ["repos", userName, reqRepoName] -- | The contributors to a repo, given the owner and repo name. -- -- > contributors "thoughtbot" "paperclip" contributors :: String -> String -> IO (Either Error [Contributor]) contributors = contributors' Nothing -- | The contributors to a repo, given the owner and repo name. -- With authentication. -- -- > contributors' (Just (GithubBasicAuth (user, password))) "thoughtbot" "paperclip" contributors' :: Maybe GithubAuth -> String -> String -> IO (Either Error [Contributor]) contributors' auth userName reqRepoName = githubGet' auth ["repos", userName, reqRepoName, "contributors"] -- | The contributors to a repo, including anonymous contributors (such as -- deleted users or git commits with unknown email addresses), given the owner -- and repo name. -- -- > contributorsWithAnonymous "thoughtbot" "paperclip" contributorsWithAnonymous :: String -> String -> IO (Either Error [Contributor]) contributorsWithAnonymous = contributorsWithAnonymous' Nothing -- | The contributors to a repo, including anonymous contributors (such as -- deleted users or git commits with unknown email addresses), given the owner -- and repo name. -- With authentication. -- -- > contributorsWithAnonymous' (Just (GithubBasicAuth (user, password))) "thoughtbot" "paperclip" contributorsWithAnonymous' :: Maybe GithubAuth -> String -> String -> IO (Either Error [Contributor]) contributorsWithAnonymous' auth userName reqRepoName = githubGetWithQueryString' auth ["repos", userName, reqRepoName, "contributors"] "anon=true" -- | The programming languages used in a repo along with the number of -- characters written in that language. Takes the repo owner and name. -- -- > languagesFor "mike-burns" "ohlaunch" languagesFor :: String -> String -> IO (Either Error [Language]) languagesFor = languagesFor' Nothing -- | The programming languages used in a repo along with the number of -- characters written in that language. Takes the repo owner and name. -- With authentication. -- -- > languagesFor' (Just (GithubBasicAuth (user, password))) "mike-burns" "ohlaunch" languagesFor' :: Maybe GithubAuth -> String -> String -> IO (Either Error [Language]) languagesFor' auth userName reqRepoName = do result <- githubGet' auth ["repos", userName, reqRepoName, "languages"] return $ either Left (Right . getLanguages) result -- | The git tags on a repo, given the repo owner and name. -- -- > tagsFor "thoughtbot" "paperclip" tagsFor :: String -> String -> IO (Either Error [Tag]) tagsFor = tagsFor' Nothing -- | The git tags on a repo, given the repo owner and name. -- With authentication. -- -- > tagsFor' (Just (GithubBasicAuth (user, password))) "thoughtbot" "paperclip" tagsFor' :: Maybe GithubAuth -> String -> String -> IO (Either Error [Tag]) tagsFor' auth userName reqRepoName = githubGet' auth ["repos", userName, reqRepoName, "tags"] -- | The git branches on a repo, given the repo owner and name. -- -- > branchesFor "thoughtbot" "paperclip" branchesFor :: String -> String -> IO (Either Error [Branch]) branchesFor = branchesFor' Nothing -- | The git branches on a repo, given the repo owner and name. -- With authentication. -- -- > branchesFor' (Just (GithubBasicAuth (user, password))) "thoughtbot" "paperclip" branchesFor' :: Maybe GithubAuth -> String -> String -> IO (Either Error [Branch]) branchesFor' auth userName reqRepoName = githubGet' auth ["repos", userName, reqRepoName, "branches"] -- | The contents of a file or directory in a repo, given the repo owner, name, and path to the file -- -- > contentsFor "thoughtbot" "paperclip" "README.md" contentsFor :: String -> String -> String -> Maybe String -> IO (Either Error Content) contentsFor = contentsFor' Nothing -- | The contents of a file or directory in a repo, given the repo owner, name, and path to the file -- With Authentication -- -- > contentsFor' (Just (GithubBasicAuth (user, password))) "thoughtbot" "paperclip" "README.md" contentsFor' :: Maybe GithubAuth -> String -> String -> String -> Maybe String -> IO (Either Error Content) contentsFor' auth userName reqRepoName reqContentPath ref = githubGetWithQueryString' auth ["repos", userName, reqRepoName, "contents", reqContentPath] $ maybe "" ("ref="++) ref data NewRepo = NewRepo { newRepoName :: String , newRepoDescription :: (Maybe String) , newRepoHomepage :: (Maybe String) , newRepoPrivate :: (Maybe Bool) , newRepoHasIssues :: (Maybe Bool) , newRepoHasWiki :: (Maybe Bool) , newRepoAutoInit :: (Maybe Bool) } deriving Show instance ToJSON NewRepo where toJSON (NewRepo { newRepoName = name , newRepoDescription = description , newRepoHomepage = homepage , newRepoPrivate = private , newRepoHasIssues = hasIssues , newRepoHasWiki = hasWiki , newRepoAutoInit = autoInit }) = object [ "name" .= name , "description" .= description , "homepage" .= homepage , "private" .= private , "has_issues" .= hasIssues , "has_wiki" .= hasWiki , "auto_init" .= autoInit ] newRepo :: String -> NewRepo newRepo name = NewRepo name Nothing Nothing Nothing Nothing Nothing Nothing -- | -- Create a new repository. -- -- > createRepo (GithubBasicAuth (user, password)) (newRepo "some_repo") {newRepoHasIssues = Just False} createRepo :: GithubAuth -> NewRepo -> IO (Either Error Repo) createRepo auth = githubPost auth ["user", "repos"] -- | -- Create a new repository for an organization. -- -- > createOrganizationRepo (GithubBasicAuth (user, password)) "thoughtbot" (newRepo "some_repo") {newRepoHasIssues = Just False} createOrganizationRepo :: GithubAuth -> String -> NewRepo -> IO (Either Error Repo) createOrganizationRepo auth org = githubPost auth ["orgs", org, "repos"] data Edit = Edit { editName :: Maybe String , editDescription :: Maybe String , editHomepage :: Maybe String , editPublic :: Maybe Bool , editHasIssues :: Maybe Bool , editHasWiki :: Maybe Bool , editHasDownloads :: Maybe Bool } deriving Show instance Default Edit where def = Edit def def def def def def def instance ToJSON Edit where toJSON (Edit { editName = name , editDescription = description , editHomepage = homepage , editPublic = public , editHasIssues = hasIssues , editHasWiki = hasWiki , editHasDownloads = hasDownloads }) = object [ "name" .= name , "description" .= description , "homepage" .= homepage , "public" .= public , "has_issues" .= hasIssues , "has_wiki" .= hasWiki , "has_downloads" .= hasDownloads ] -- | -- Edit an existing repository. -- -- > editRepo (GithubBasicAuth (user, password)) "some_user" "some_repo" def {editDescription = Just "some description"} editRepo :: GithubAuth -> String -- ^ owner -> String -- ^ repository name -> Edit -> IO (Either Error Repo) editRepo auth user repo body = githubPatch auth ["repos", user, repo] b where -- if no name is given, use curent name b = body {editName = editName body <|> Just repo} -- | -- Delete an existing repository. -- -- > deleteRepo (GithubBasicAuth (user, password)) "thoughtbot" "some_repo" deleteRepo :: GithubAuth -> String -- ^ owner -> String -- ^ repository name -> IO (Either Error ()) deleteRepo auth owner repo = do result <- doHttps "DELETE" url (Just auth) Nothing case result of Left e -> return (Left (HTTPConnectionError e)) Right resp -> let status = responseStatus resp headers = responseHeaders resp in if status == notFound404 -- doHttps silently absorbs 404 errors, but for this operation -- we want the user to know if they've tried to delete a -- non-existent repository then return (Left (HTTPConnectionError (E.toException (StatusCodeException status headers #if MIN_VERSION_http_conduit(1, 9, 0) (responseCookieJar resp) #endif )))) else return (Right ()) where url = "https://api.github.com/repos/" ++ owner ++ "/" ++ repo
thoughtbot/github
Github/Repos.hs
bsd-3-clause
12,755
0
23
2,856
2,276
1,275
1,001
190
3
-- | Server and client game state types and operations. module Game.LambdaHack.Server.ServerOptions ( ServerOptions(..), RNGs(..), defServerOptions ) where import Prelude () import Game.LambdaHack.Core.Prelude import Data.Binary import qualified System.Random.SplitMix32 as SM import Game.LambdaHack.Common.ClientOptions import Game.LambdaHack.Common.Faction import Game.LambdaHack.Content.ModeKind import Game.LambdaHack.Definition.Defs -- | Options that affect the behaviour of the server (including game rules). data ServerOptions = ServerOptions { sknowMap :: Bool , sknowEvents :: Bool , sknowItems :: Bool , sniff :: Bool , sallClear :: Bool , sboostRandomItem :: Bool , sgameMode :: Maybe (GroupName ModeKind) , sautomateAll :: Bool , skeepAutomated :: Bool , sdungeonRng :: Maybe SM.SMGen , smainRng :: Maybe SM.SMGen , snewGameSer :: Bool , scurChalSer :: Challenge , sdumpInitRngs :: Bool , ssavePrefixSer :: String , sdbgMsgSer :: Bool , sassertExplored :: Maybe Int , sshowItemSamples :: Bool , sstopAfterGameOver :: Bool , sclientOptions :: ClientOptions -- The client debug inside server debug only holds the client commandline -- options and is never updated with config options, etc. } deriving Show data RNGs = RNGs { dungeonRandomGenerator :: Maybe SM.SMGen , startingRandomGenerator :: Maybe SM.SMGen } instance Show RNGs where show RNGs{..} = let args = [ maybe "" (\gen -> "--setDungeonRng \"" ++ show gen ++ "\"") dungeonRandomGenerator , maybe "" (\gen -> "--setMainRng \"" ++ show gen ++ "\"") startingRandomGenerator ] in unwords args instance Binary ServerOptions where put ServerOptions{..} = do put sknowMap put sknowEvents put sknowItems put sniff put sallClear put sboostRandomItem put sgameMode put sautomateAll put skeepAutomated put scurChalSer put ssavePrefixSer put sdbgMsgSer put sassertExplored put sshowItemSamples put sclientOptions get = do sknowMap <- get sknowEvents <- get sknowItems <- get sniff <- get sallClear <- get sboostRandomItem <- get sgameMode <- get sautomateAll <- get skeepAutomated <- get scurChalSer <- get ssavePrefixSer <- get sdbgMsgSer <- get sassertExplored <- get sshowItemSamples <- get sclientOptions <- get let sdungeonRng = Nothing smainRng = Nothing snewGameSer = False sdumpInitRngs = False sstopAfterGameOver = False return $! ServerOptions{..} instance Binary RNGs where put RNGs{..} = do put (show dungeonRandomGenerator) put (show startingRandomGenerator) get = do dg <- get sg <- get let dungeonRandomGenerator = read dg startingRandomGenerator = read sg return $! RNGs{..} -- | Default value of server options. defServerOptions :: ServerOptions defServerOptions = ServerOptions { sknowMap = False , sknowEvents = False , sknowItems = False , sniff = False , sallClear = False , sboostRandomItem = False , sgameMode = Nothing , sautomateAll = False , skeepAutomated = False , sdungeonRng = Nothing , smainRng = Nothing , snewGameSer = False , scurChalSer = defaultChallenge , sdumpInitRngs = False , ssavePrefixSer = "" , sdbgMsgSer = False , sassertExplored = Nothing , sshowItemSamples = False , sstopAfterGameOver = False , sclientOptions = defClientOptions }
LambdaHack/LambdaHack
engine-src/Game/LambdaHack/Server/ServerOptions.hs
bsd-3-clause
3,664
0
16
979
858
466
392
-1
-1
{-# LANGUAGE FlexibleContexts #-} module Karamaan.Opaleye.SQL where import Database.HaskellDB.Optimize (optimize) import Database.HaskellDB.Sql.Generate (sqlQuery) import Database.HaskellDB.Sql.Print (ppSql) import Database.HaskellDB.Sql.Default (defaultSqlGenerator) import Database.HaskellDB.PrimQuery (PrimQuery) import Karamaan.Opaleye.QueryArr (Query, runQueryArrPrim) import Karamaan.Opaleye.Unpackspec (Unpackspec) import Karamaan.Plankton ((.:)) import Data.Profunctor.Product (PPOfContravariant, unPPOfContravariant) import Data.Profunctor.Product.Default (Default, def) -- Currently we only support SQL generation for Postgres because, -- for example, 'cat' is implemented as '||' and the hackery we do -- in, for example, Values.hs, may be Postgres specific. -- -- Support for other DBMSes can be added if required. showSqlForPostgres :: Unpackspec wires -> Query wires -> String showSqlForPostgres = optimizeFormatAndShowSQL .: runQueryArrPrim formatAndShowSQL :: PrimQuery -> String formatAndShowSQL = show . ppSql . sqlQuery defaultSqlGenerator optimizeFormatAndShowSQL :: PrimQuery -> String optimizeFormatAndShowSQL = formatAndShowSQL . optimize -- TODO: the other "Default" functions are called "...Def". I think we -- should standardize on the latter. showSqlForPostgresDefault :: Default (PPOfContravariant Unpackspec) wires wires => Query wires -> String showSqlForPostgresDefault = showSqlForPostgres (unPPOfContravariant def)
karamaan/karamaan-opaleye
Karamaan/Opaleye/SQL.hs
bsd-3-clause
1,484
0
8
191
253
152
101
21
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} module Test.ZM.ADT.AbsRef.K4bbd38587b9e (AbsRef(..)) where import qualified Prelude(Eq,Ord,Show) import qualified GHC.Generics import qualified Flat import qualified Data.Model import qualified Test.ZM.ADT.SHAKE128_48.K9f214799149b import qualified Test.ZM.ADT.ADT.K3e8257255cbf import qualified Test.ZM.ADT.Identifier.Kdc26e9d90047 import qualified Test.ZM.ADT.ADTRef.K07b1b045ac3c newtype AbsRef = AbsRef (Test.ZM.ADT.SHAKE128_48.K9f214799149b.SHAKE128_48 (Test.ZM.ADT.ADT.K3e8257255cbf.ADT Test.ZM.ADT.Identifier.Kdc26e9d90047.Identifier Test.ZM.ADT.Identifier.Kdc26e9d90047.Identifier (Test.ZM.ADT.ADTRef.K07b1b045ac3c.ADTRef Test.ZM.ADT.AbsRef.K4bbd38587b9e.AbsRef))) deriving (Prelude.Eq, Prelude.Ord, Prelude.Show, GHC.Generics.Generic, Flat.Flat) instance Data.Model.Model AbsRef
tittoassini/typed
test/Test/ZM/ADT/AbsRef/K4bbd38587b9e.hs
bsd-3-clause
1,081
0
12
285
197
133
64
16
0
{-# LANGUAGE RecordWildCards #-} module LessWrong.COC.Check where import Prelude hiding (lookup) import LessWrong.COC.Context import LessWrong.COC.Error import LessWrong.COC.Eval (reduce, substitute) import LessWrong.COC.Type import Control.Monad import Control.Monad.Trans.Except typeOf :: Term -> Except CalculusError Term typeOf = typeWith empty typeWith :: Context Term -> Term -> Except CalculusError Term typeWith _ Uni{..} = pure $ Uni (axiom uni) typeWith ctx Var{..} = case lookup var ctx of Just tpe -> pure tpe Nothing -> throwE $ UnknownVariable var typeWith ctx Lam{..} = do let ctx' = insert var tpe ctx bodyTpe <- typeWith ctx' body let lamTpe = Pi var tpe bodyTpe _ <- typeWith ctx lamTpe -- check that type is well-typed pure lamTpe typeWith ctx Pi{..} = do aTpe <- (reduce <$> typeWith ctx tpe) >>= typeConst bTpe <- (reduce <$> typeWith (insert var tpe ctx) body) >>= typeConst pure $ Uni (typeRule aTpe bTpe) typeWith ctx App{..} = do let inctx = inclusion ctx algTpe <- reduce <$> typeWith ctx (reduce alg) case algTpe of Pi{..} -> pure () _ -> throwE $ InvalidType algTpe "not a Pi-type in application algo" datTpe <- reduce <$> typeWith ctx dat unless (datTpe `inctx` tpe algTpe) $ throwE $ CannotEqualize datTpe (tpe algTpe) pure $ substitute (body algTpe) (var algTpe) dat -- |Every object of 'Star' is an object of 'Box'{i} -- and every object of 'Box'{i} is an object of 'Box'{j} for every i <= j inclusion :: Context Term -> Term -> Term -> Bool inclusion _ (Uni x) (Uni y) = x <= y inclusion _ (Var x) (Var y) = x == y inclusion ctx (Var x) u@Uni{} = case lookup x ctx of Just k -> inclusion ctx k u Nothing -> False inclusion ctx (App e1 d1) (App e2 d2) = inclusion ctx e1 e2 && inclusion ctx d1 d2 inclusion ctx (Pi v t b) (Pi v' t' b') = inclusion ctx t t' && inclusion ctx b (substitute b' v' (Var v)) inclusion ctx (Lam v t b) (Lam v' t' b') = inclusion ctx t t' && inclusion ctx b (substitute b' v' (Var v)) inclusion _ _ _ = False typeConst :: Term -> Except CalculusError Uni typeConst (Uni x) = pure x typeConst a = throwE $ InvalidType a "non-universe type" typeRule :: Uni -> Uni -> Uni typeRule _ Star = Star typeRule Star uni = uni typeRule (Box i) (Box j) = Box (max i j)
zmactep/less-wrong
src/LessWrong/COC/Check.hs
bsd-3-clause
2,972
0
13
1,163
958
470
488
50
3
-- | Convenient common interface for command line Futhark compilers. -- Using this module ensures that all compilers take the same options. -- A small amount of flexibility is provided for backend-specific -- options. module Futhark.Compiler.CLI ( compilerMain, CompilerOption, CompilerMode (..), module Futhark.Pipeline, module Futhark.Compiler, ) where import Control.Monad import Data.Maybe import Futhark.Compiler import Futhark.IR (Name, Prog, nameFromString) import Futhark.IR.SOACS (SOACS) import Futhark.Pipeline import Futhark.Util.Options import System.FilePath -- | Run a parameterised Futhark compiler, where @cfg@ is a user-given -- configuration type. Call this from @main@. compilerMain :: -- | Initial configuration. cfg -> -- | Options that affect the configuration. [CompilerOption cfg] -> -- | The short action name (e.g. "compile to C"). String -> -- | The longer action description. String -> -- | The pipeline to use. Pipeline SOACS rep -> -- | The action to take on the result of the pipeline. ( FutharkConfig -> cfg -> CompilerMode -> FilePath -> Prog rep -> FutharkM () ) -> -- | Program name String -> -- | Command line arguments. [String] -> IO () compilerMain cfg cfg_opts name desc pipeline doIt = mainWithOptions (newCompilerConfig cfg) (commandLineOptions ++ map wrapOption cfg_opts) "options... <program.fut>" inspectNonOptions where inspectNonOptions [file] config = Just $ compile config file inspectNonOptions _ _ = Nothing compile config filepath = runCompilerOnProgram (futharkConfig config) pipeline (action config filepath) filepath action config filepath = Action { actionName = name, actionDescription = desc, actionProcedure = doIt (futharkConfig config) (compilerConfig config) (compilerMode config) (outputFilePath filepath config) } -- | An option that modifies the configuration of type @cfg@. type CompilerOption cfg = OptDescr (Either (IO ()) (cfg -> cfg)) type CoreCompilerOption cfg = OptDescr ( Either (IO ()) (CompilerConfig cfg -> CompilerConfig cfg) ) commandLineOptions :: [CoreCompilerOption cfg] commandLineOptions = [ Option "o" [] ( ReqArg (\filename -> Right $ \config -> config {compilerOutput = Just filename}) "FILE" ) "Name of the compiled binary.", Option "v" ["verbose"] (OptArg (Right . incVerbosity) "FILE") "Print verbose output on standard error; wrong program to FILE.", Option [] ["library"] (NoArg $ Right $ \config -> config {compilerMode = ToLibrary}) "Generate a library instead of an executable.", Option [] ["executable"] (NoArg $ Right $ \config -> config {compilerMode = ToExecutable}) "Generate an executable instead of a library (set by default).", Option [] ["server"] (NoArg $ Right $ \config -> config {compilerMode = ToServer}) "Generate a server executable instead of a library.", Option "w" [] (NoArg $ Right $ \config -> config {compilerWarn = False}) "Disable all warnings.", Option [] ["Werror"] (NoArg $ Right $ \config -> config {compilerWerror = True}) "Treat warnings as errors.", Option [] ["safe"] (NoArg $ Right $ \config -> config {compilerSafe = True}) "Ignore 'unsafe' in code.", Option [] ["entry-point"] ( ReqArg ( \arg -> Right $ \config -> config { compilerEntryPoints = nameFromString arg : compilerEntryPoints config } ) "NAME" ) "Treat this function as an additional entry point." ] wrapOption :: CompilerOption cfg -> CoreCompilerOption cfg wrapOption = fmap wrap where wrap f = do g <- f return $ \cfg -> cfg {compilerConfig = g (compilerConfig cfg)} incVerbosity :: Maybe FilePath -> CompilerConfig cfg -> CompilerConfig cfg incVerbosity file cfg = cfg {compilerVerbose = (v, file `mplus` snd (compilerVerbose cfg))} where v = case fst $ compilerVerbose cfg of NotVerbose -> Verbose Verbose -> VeryVerbose VeryVerbose -> VeryVerbose data CompilerConfig cfg = CompilerConfig { compilerOutput :: Maybe FilePath, compilerVerbose :: (Verbosity, Maybe FilePath), compilerMode :: CompilerMode, compilerWerror :: Bool, compilerSafe :: Bool, compilerWarn :: Bool, compilerConfig :: cfg, compilerEntryPoints :: [Name] } -- | Are we compiling a library or an executable? data CompilerMode = ToLibrary | ToExecutable | ToServer deriving (Eq, Ord, Show) -- | The configuration of the compiler. newCompilerConfig :: cfg -> CompilerConfig cfg newCompilerConfig x = CompilerConfig { compilerOutput = Nothing, compilerVerbose = (NotVerbose, Nothing), compilerMode = ToExecutable, compilerWerror = False, compilerSafe = False, compilerWarn = True, compilerConfig = x, compilerEntryPoints = mempty } outputFilePath :: FilePath -> CompilerConfig cfg -> FilePath outputFilePath srcfile = fromMaybe (srcfile `replaceExtension` "") . compilerOutput futharkConfig :: CompilerConfig cfg -> FutharkConfig futharkConfig config = newFutharkConfig { futharkVerbose = compilerVerbose config, futharkWerror = compilerWerror config, futharkSafe = compilerSafe config, futharkWarn = compilerWarn config, futharkEntryPoints = compilerEntryPoints config }
diku-dk/futhark
src/Futhark/Compiler/CLI.hs
isc
5,786
0
18
1,553
1,295
718
577
161
3
module Nirum.Constructs (Construct, toCode) where import Data.Text (Text) class (Eq a, Ord a) => Construct a where toCode :: a -> Text
dahlia/nirum
src/Nirum/Constructs.hs
gpl-3.0
141
0
7
28
57
32
25
4
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CloudFormation.DeleteStack -- Copyright : (c) 2013-2015 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) -- -- Deletes a specified stack. Once the call completes successfully, stack -- deletion starts. Deleted stacks do not show up in the DescribeStacks API -- if the deletion has been completed successfully. -- -- /See:/ <http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeleteStack.html AWS API Reference> for DeleteStack. module Network.AWS.CloudFormation.DeleteStack ( -- * Creating a Request deleteStack , DeleteStack -- * Request Lenses , dsStackName -- * Destructuring the Response , deleteStackResponse , DeleteStackResponse ) where import Network.AWS.CloudFormation.Types import Network.AWS.CloudFormation.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | The input for DeleteStack action. -- -- /See:/ 'deleteStack' smart constructor. newtype DeleteStack = DeleteStack' { _dsStackName :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteStack' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dsStackName' deleteStack :: Text -- ^ 'dsStackName' -> DeleteStack deleteStack pStackName_ = DeleteStack' { _dsStackName = pStackName_ } -- | The name or the unique stack ID that is associated with the stack. dsStackName :: Lens' DeleteStack Text dsStackName = lens _dsStackName (\ s a -> s{_dsStackName = a}); instance AWSRequest DeleteStack where type Rs DeleteStack = DeleteStackResponse request = postQuery cloudFormation response = receiveNull DeleteStackResponse' instance ToHeaders DeleteStack where toHeaders = const mempty instance ToPath DeleteStack where toPath = const "/" instance ToQuery DeleteStack where toQuery DeleteStack'{..} = mconcat ["Action" =: ("DeleteStack" :: ByteString), "Version" =: ("2010-05-15" :: ByteString), "StackName" =: _dsStackName] -- | /See:/ 'deleteStackResponse' smart constructor. data DeleteStackResponse = DeleteStackResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteStackResponse' with the minimum fields required to make a request. -- deleteStackResponse :: DeleteStackResponse deleteStackResponse = DeleteStackResponse'
fmapfmapfmap/amazonka
amazonka-cloudformation/gen/Network/AWS/CloudFormation/DeleteStack.hs
mpl-2.0
3,114
0
9
633
367
226
141
51
1
{-# LANGUAGE OverloadedStrings, TypeSynonymInstances, FlexibleInstances #-} module Data.Text.PrettyHtml (unlinesHtml, prettyHtml, prettyThings) where import Import import Data.Attoparsec.Text import qualified Text.Blaze.Html5.Attributes as Attr import qualified Text.Blaze.Html5 as Html import Data.List as L import Data.String import Data.Text as T import Control.Applicative unlinesHtml :: [Html] -> Html unlinesHtml = sequence_ . L.intersperse Html.br -- | Single step of a 'Data.List.foldr' to concatenate 'Right's in an 'Either' -- and remove empty 'Right's. concatRights :: Either a T.Text -> [Either a T.Text] -> [Either a T.Text] concatRights (Right y) xs | T.null y = xs concatRights (Right y) (Right x : xs) = Right (y `T.append` x) : xs concatRights y xs = y : xs prettyHtml :: (Monad m, HasGithubRepo (HandlerT site m)) => [Parser Pretty] -> Text -> HandlerT site m Html prettyHtml filters text = case parseOnly (many $ (Left <$> choice filters) <|> (Right . T.singleton <$> anyChar)) text of Right result -> do let pieces = L.foldr concatRights [] result fmap sequence_ $ forM pieces $ either renderPretty (return . toHtml) Left err -> error err renderPretty :: (Monad m, HasGithubRepo (HandlerT site m)) => Pretty -> HandlerT site m Html renderPretty pretty = case pretty of RawHtml html -> return html GithubTicket int -> do maybe_github_repo_link <- getGithubRepo let github_issue = toHtml $ "Github issue " ++ show int return $ case maybe_github_repo_link of Just github_repo_link -> Html.a github_issue Html.! Attr.href (fromString $ "https://github.com/" ++ T.unpack github_repo_link ++ "/issues/" ++ show int) Nothing -> github_issue data Pretty = GithubTicket Int | RawHtml Html githubTicketRef :: Parser Pretty githubTicketRef = GithubTicket <$> (asciiCI "GH-" *> decimal) prettyThings :: [Parser Pretty] prettyThings = [githubTicketRef]
chreekat/snowdrift
Data/Text/PrettyHtml.hs
agpl-3.0
2,028
0
21
440
626
324
302
-1
-1
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-} -- Module: Data.Csv.Encoding -- Copyright: (c) 2011 MailRank, Inc. -- (c) 2012 Johan Tibell -- License: BSD3 -- Maintainer: Johan Tibell <johan.tibell@gmail.com> -- Stability: experimental -- Portability: portable -- -- Encoding and decoding of data types into CSV. module Data.Csv.Encoding ( -- * Encoding and decoding HasHeader(..) , decode , decodeByName , Quoting(..) , encode , encodeByName , encodeDefaultOrderedByName -- ** Encoding and decoding options , DecodeOptions(..) , defaultDecodeOptions , decodeWith , decodeByNameWith , EncodeOptions(..) , defaultEncodeOptions , encodeWith , encodeByNameWith , encodeDefaultOrderedByNameWith -- ** Encoding and decoding single records , encodeRecord , encodeNamedRecord , recordSep ) where import Blaze.ByteString.Builder (Builder, fromByteString, fromWord8, toLazyByteString, toByteString) import Blaze.ByteString.Builder.Char8 (fromString) import Control.Applicative as AP (Applicative(..), (<|>), optional) import Data.Attoparsec.ByteString.Char8 (endOfInput) import qualified Data.Attoparsec.ByteString.Lazy as AL import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Char8 as BL8 import qualified Data.HashMap.Strict as HM import Data.Vector (Vector) import qualified Data.Vector as V import Data.Word (Word8) import Data.Monoid import Prelude hiding (unlines) import qualified Data.Csv.Conversion as Conversion import Data.Csv.Conversion (FromNamedRecord, FromRecord, ToNamedRecord, ToRecord, parseNamedRecord, parseRecord, runParser, toNamedRecord, toRecord) import Data.Csv.Parser hiding (csv, csvWithHeader) import qualified Data.Csv.Parser as Parser import Data.Csv.Types hiding (toNamedRecord) import qualified Data.Csv.Types as Types import Data.Csv.Util (blankLine, endOfLine) -- TODO: 'encode' isn't as efficient as it could be. ------------------------------------------------------------------------ -- * Encoding and decoding -- | Efficiently deserialize CSV records from a lazy 'L.ByteString'. -- If this fails due to incomplete or invalid input, @'Left' msg@ is -- returned. Equivalent to @'decodeWith' 'defaultDecodeOptions'@. decode :: FromRecord a => HasHeader -- ^ Data contains header that should be -- skipped -> L.ByteString -- ^ CSV data -> Either String (Vector a) decode = decodeWith defaultDecodeOptions {-# INLINE decode #-} -- | Efficiently deserialize CSV records from a lazy 'L.ByteString'. -- If this fails due to incomplete or invalid input, @'Left' msg@ is -- returned. The data is assumed to be preceeded by a header. -- Equivalent to @'decodeByNameWith' 'defaultDecodeOptions'@. decodeByName :: FromNamedRecord a => L.ByteString -- ^ CSV data -> Either String (Header, Vector a) decodeByName = decodeByNameWith defaultDecodeOptions {-# INLINE decodeByName #-} -- | Efficiently serialize CSV records as a lazy 'L.ByteString'. encode :: ToRecord a => [a] -> L.ByteString encode = encodeWith defaultEncodeOptions {-# INLINE encode #-} -- | Efficiently serialize CSV records as a lazy 'L.ByteString'. The -- header is written before any records and dictates the field order. encodeByName :: ToNamedRecord a => Header -> [a] -> L.ByteString encodeByName = encodeByNameWith defaultEncodeOptions {-# INLINE encodeByName #-} -- | Like 'encodeByName', but header and field order is dictated by -- the 'Conversion.header' method. encodeDefaultOrderedByName :: (Conversion.DefaultOrdered a, ToNamedRecord a) => [a] -> L.ByteString encodeDefaultOrderedByName = encodeDefaultOrderedByNameWith defaultEncodeOptions {-# INLINE encodeDefaultOrderedByName #-} ------------------------------------------------------------------------ -- ** Encoding and decoding options -- | Like 'decode', but lets you customize how the CSV data is parsed. decodeWith :: FromRecord a => DecodeOptions -- ^ Decoding options -> HasHeader -- ^ Data contains header that should be -- skipped -> L.ByteString -- ^ CSV data -> Either String (Vector a) decodeWith = decodeWithC csv {-# INLINE [1] decodeWith #-} {-# RULES "idDecodeWith" decodeWith = idDecodeWith #-} -- | Same as 'decodeWith', but more efficient as no type -- conversion is performed. idDecodeWith :: DecodeOptions -> HasHeader -> L.ByteString -> Either String (Vector (Vector B.ByteString)) idDecodeWith = decodeWithC Parser.csv -- | Decode CSV data using the provided parser, skipping a leading -- header if 'hasHeader' is 'HasHeader'. Returns 'Left' @errMsg@ on -- failure. decodeWithC :: (DecodeOptions -> AL.Parser a) -> DecodeOptions -> HasHeader -> BL8.ByteString -> Either String a decodeWithC p !opts hasHeader = decodeWithP parser where parser = case hasHeader of HasHeader -> header (decDelimiter opts) *> p opts NoHeader -> p opts {-# INLINE decodeWithC #-} -- | Like 'decodeByName', but lets you customize how the CSV data is -- parsed. decodeByNameWith :: FromNamedRecord a => DecodeOptions -- ^ Decoding options -> L.ByteString -- ^ CSV data -> Either String (Header, Vector a) decodeByNameWith !opts = decodeWithP (csvWithHeader opts) -- | Should quoting be applied to fields, and at which level? data Quoting = QuoteNone -- ^ No quotes. | QuoteMinimal -- ^ Quotes according to RFC 4180. | QuoteAll -- ^ Always quote. deriving (Eq, Show) -- | Options that controls how data is encoded. These options can be -- used to e.g. encode data in a tab-separated format instead of in a -- comma-separated format. -- -- To avoid having your program stop compiling when new fields are -- added to 'EncodeOptions', create option records by overriding -- values in 'defaultEncodeOptions'. Example: -- -- > myOptions = defaultEncodeOptions { -- > encDelimiter = fromIntegral (ord '\t') -- > } -- -- /N.B./ The 'encDelimiter' must /not/ be the quote character (i.e. -- @\"@) or one of the record separator characters (i.e. @\\n@ or -- @\\r@). data EncodeOptions = EncodeOptions { -- | Field delimiter. encDelimiter :: {-# UNPACK #-} !Word8 -- | Record separator selection. @True@ for CRLF (@\\r\\n@) and -- @False@ for LF (@\\n@). , encUseCrLf :: !Bool -- | Include a header row when encoding @ToNamedRecord@ -- instances. , encIncludeHeader :: !Bool -- | What kind of quoting should be applied to text fields. , encQuoting :: !Quoting } deriving (Eq, Show) -- | Encoding options for CSV files. defaultEncodeOptions :: EncodeOptions defaultEncodeOptions = EncodeOptions { encDelimiter = 44 -- comma , encUseCrLf = True , encIncludeHeader = True , encQuoting = QuoteMinimal } -- | Like 'encode', but lets you customize how the CSV data is -- encoded. encodeWith :: ToRecord a => EncodeOptions -> [a] -> L.ByteString encodeWith opts | validDelim (encDelimiter opts) = toLazyByteString . unlines (recordSep (encUseCrLf opts)) . map (encodeRecord (encQuoting opts) (encDelimiter opts) . toRecord) | otherwise = encodeOptionsError {-# INLINE encodeWith #-} -- | Check if the delimiter is valid. validDelim :: Word8 -> Bool validDelim delim = delim `notElem` [cr, nl, dquote] where nl = 10 cr = 13 dquote = 34 -- | Raises an exception indicating that the provided delimiter isn't -- valid. See 'validDelim'. -- -- Keep this message consistent with the documentation of -- 'EncodeOptions'. encodeOptionsError :: a encodeOptionsError = error $ "Data.Csv: " ++ "The 'encDelimiter' must /not/ be the quote character (i.e. " ++ "\") or one of the record separator characters (i.e. \\n or " ++ "\\r)" -- | Encode a single record, without the trailing record separator -- (i.e. newline). encodeRecord :: Quoting -> Word8 -> Record -> Builder encodeRecord qtng delim = mconcat . intersperse (fromWord8 delim) . map fromByteString . map (escape qtng delim) . V.toList {-# INLINE encodeRecord #-} -- | Encode a single named record, without the trailing record -- separator (i.e. newline), using the given field order. encodeNamedRecord :: Header -> Quoting -> Word8 -> NamedRecord -> Builder encodeNamedRecord hdr qtng delim = encodeRecord qtng delim . namedRecordToRecord hdr -- TODO: Optimize escape :: Quoting -> Word8 -> B.ByteString -> B.ByteString escape !qtng !delim !s | (qtng == QuoteMinimal && B.any (\ b -> b == dquote || b == delim || b == nl || b == cr || b == sp) s ) || qtng == QuoteAll = toByteString $ fromWord8 dquote <> B.foldl (\ acc b -> acc <> if b == dquote then fromByteString "\"\"" else fromWord8 b) mempty s <> fromWord8 dquote | otherwise = s where dquote = 34 nl = 10 cr = 13 sp = 32 -- | Like 'encodeByName', but lets you customize how the CSV data is -- encoded. encodeByNameWith :: ToNamedRecord a => EncodeOptions -> Header -> [a] -> L.ByteString encodeByNameWith opts hdr v | validDelim (encDelimiter opts) = toLazyByteString (rows (encIncludeHeader opts)) | otherwise = encodeOptionsError where rows False = records rows True = encodeRecord (encQuoting opts) (encDelimiter opts) hdr <> recordSep (encUseCrLf opts) <> records records = unlines (recordSep (encUseCrLf opts)) . map (encodeNamedRecord hdr (encQuoting opts) (encDelimiter opts) . toNamedRecord) $ v {-# INLINE encodeByNameWith #-} -- | Like 'encodeDefaultOrderedByNameWith', but lets you customize how -- the CSV data is encoded. encodeDefaultOrderedByNameWith :: forall a. (Conversion.DefaultOrdered a, ToNamedRecord a) => EncodeOptions -> [a] -> L.ByteString encodeDefaultOrderedByNameWith opts v | validDelim (encDelimiter opts) = toLazyByteString (rows (encIncludeHeader opts)) | otherwise = encodeOptionsError where hdr = (Conversion.headerOrder (undefined :: a)) rows False = records rows True = encodeRecord (encQuoting opts) (encDelimiter opts) hdr <> recordSep (encUseCrLf opts) <> records records = unlines (recordSep (encUseCrLf opts)) . map (encodeNamedRecord hdr (encQuoting opts) (encDelimiter opts) . toNamedRecord) $ v {-# INLINE encodeDefaultOrderedByNameWith #-} namedRecordToRecord :: Header -> NamedRecord -> Record namedRecordToRecord hdr nr = V.map find hdr where find n = case HM.lookup n nr of Nothing -> moduleError "namedRecordToRecord" $ "header contains name " ++ show (B8.unpack n) ++ " which is not present in the named record" Just v -> v moduleError :: String -> String -> a moduleError func msg = error $ "Data.Csv.Encoding." ++ func ++ ": " ++ msg {-# NOINLINE moduleError #-} recordSep :: Bool -> Builder recordSep False = fromWord8 10 -- new line (\n) recordSep True = fromString "\r\n" unlines :: Builder -> [Builder] -> Builder unlines _ [] = mempty unlines sep (b:bs) = b <> sep <> unlines sep bs intersperse :: Builder -> [Builder] -> [Builder] intersperse _ [] = [] intersperse sep (x:xs) = x : prependToAll sep xs prependToAll :: Builder -> [Builder] -> [Builder] prependToAll _ [] = [] prependToAll sep (x:xs) = sep <> x : prependToAll sep xs decodeWithP :: AL.Parser a -> L.ByteString -> Either String a decodeWithP p s = case AL.parse p s of AL.Done _ v -> Right v AL.Fail left _ msg -> Left errMsg where errMsg = "parse error (" ++ msg ++ ") at " ++ (if BL8.length left > 100 then (take 100 $ BL8.unpack left) ++ " (truncated)" else show (BL8.unpack left)) {-# INLINE decodeWithP #-} -- These alternative implementation of the 'csv' and 'csvWithHeader' -- parsers from the 'Parser' module performs the -- 'FromRecord'/'FromNamedRecord' conversions on-the-fly, thereby -- avoiding the need to hold a big 'CSV' value in memory. The 'CSV' -- type has a quite large memory overhead due to high constant -- overheads of 'B.ByteString' and 'V.Vector'. -- TODO: Check that the error messages don't duplicate prefixes, as in -- "parse error: conversion error: ...". -- | Parse a CSV file that does not include a header. csv :: FromRecord a => DecodeOptions -> AL.Parser (V.Vector a) csv !opts = do vals <- records _ <- optional endOfLine endOfInput return $! V.fromList vals where records = do !r <- record (decDelimiter opts) if blankLine r then (endOfLine *> records) <|> pure [] else case runParser (parseRecord r) of Left msg -> fail $ "conversion error: " ++ msg Right val -> do !vals <- (endOfLine *> records) <|> AP.pure [] return (val : vals) {-# INLINE csv #-} -- | Parse a CSV file that includes a header. csvWithHeader :: FromNamedRecord a => DecodeOptions -> AL.Parser (Header, V.Vector a) csvWithHeader !opts = do !hdr <- header (decDelimiter opts) vals <- records hdr _ <- optional endOfLine endOfInput let !v = V.fromList vals return (hdr, v) where records hdr = do !r <- record (decDelimiter opts) if blankLine r then (endOfLine *> records hdr) <|> pure [] else case runParser (convert hdr r) of Left msg -> fail $ "conversion error: " ++ msg Right val -> do !vals <- (endOfLine *> records hdr) <|> pure [] return (val : vals) convert hdr = parseNamedRecord . Types.toNamedRecord hdr
tibbe/cassava
Data/Csv/Encoding.hs
bsd-3-clause
14,401
0
23
3,604
2,874
1,550
1,324
257
3
{-# LANGUAGE OverloadedStrings #-} import Control.Concurrent import Sound.Pd -- MAIN REFERENCE FOR METAPATCHING: -- https://puredata.info/docs/tutorials/TipsAndTricks#undocumented-pd-internal-messages main :: IO () main = withPd $ \pd -> do _patch <- makePatch pd "test/test-meta-empty" -- This is how we talk to a subpatch, in this case [pd $0contents] -- (assuming [pd $0contents] already exists in the patch!) -- let receiver = "pd-" ++ local patch "contents" -- This is how we talk to the patch file itself. If it's open multiple times, the edits -- will take place in all open copies! -- NOTE: That's fixable using namecanvas if desired, see link above. let receiver = "pd-test/test-meta-empty.pd" putStrLn "Adding osc~" sendGlobal pd receiver (Message "obj" [50, 50, "osc~", 330]) putStrLn "Adding dac~" sendGlobal pd receiver (Message "obj" [50, 50, "dac~", 1, 2]) putStrLn "Connecting" sendGlobal pd receiver (Message "connect" [0, 0, 1, 0]) threadDelay 1000000 putStrLn "Adding second osc~" sendGlobal pd receiver (Message "obj" [50, 50, "osc~", 550]) sendGlobal pd receiver (Message "connect" [2, 0, 1, 1]) threadDelay 5000000
lukexi/pd-hs
test/test-meta.hs
bsd-3-clause
1,226
0
12
255
254
131
123
18
1
{- Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE PackageImports #-} {-# LANGUAGE NoImplicitPrelude #-} module GHC.Constants (module M) where import "base" GHC.Constants as M
xwysp/codeworld
codeworld-base/src/GHC/Constants.hs
apache-2.0
741
0
4
136
23
17
6
4
0
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>Надстройка событий, отправленных сервером</title> <maps> <homeID>sse.introduction</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Содержание</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Избранное</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/sse/src/main/javahelp/org/zaproxy/zap/extension/sse/resources/help_ru_RU/helpset_ru_RU.hs
apache-2.0
1,068
79
66
158
537
269
268
-1
-1
import StackTest import Control.Monad (unless) import System.Directory (doesFileExist) main :: IO () main = do stack ["--version"] stack ["--help"] removeDirIgnore "acme-missiles-0.2" removeDirIgnore "acme-missiles-0.3" stack ["unpack", "acme-missiles-0.2"] stack ["unpack", "acme-missiles"] stackErr ["command-does-not-exist"] stackErr ["unpack", "invalid-package-name-"] -- When running outside of IntegrationSpec.hs, this will use the -- stack.yaml from Stack itself exists <- doesFileExist "../../../../../stack.yaml" unless exists $ stackErr ["build"] doesNotExist "stack.yaml" if isWindows then stack [defaultResolverArg, "exec", "./foo.bat"] else stack [defaultResolverArg, "exec", "./foo.sh"]
juhp/stack
test/integration/tests/sanity/Main.hs
bsd-3-clause
777
0
9
148
183
91
92
19
2
{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} #ifndef MIN_VERSION_profunctors #define MIN_VERSION_profunctors(x,y,z) 1 #endif #if __GLASGOW_HASKELL__ < 708 || !(MIN_VERSION_profunctors(4,4,0)) {-# LANGUAGE Trustworthy #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Lens.Setter -- Copyright : (C) 2012-15 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : provisional -- Portability : Rank2Types -- -- A @'Setter' s t a b@ is a generalization of 'fmap' from 'Functor'. It allows you to map into a -- structure and change out the contents, but it isn't strong enough to allow you to -- enumerate those contents. Starting with @'fmap' :: 'Functor' f => (a -> b) -> f a -> f b@ -- we monomorphize the type to obtain @(a -> b) -> s -> t@ and then decorate it with 'Data.Functor.Identity.Identity' to obtain: -- -- @ -- type 'Setter' s t a b = (a -> 'Data.Functor.Identity.Identity' b) -> s -> 'Data.Functor.Identity.Identity' t -- @ -- -- Every 'Traversal' is a valid 'Setter', since 'Data.Functor.Identity.Identity' is 'Applicative'. -- -- Everything you can do with a 'Functor', you can do with a 'Setter'. There -- are combinators that generalize 'fmap' and ('<$'). ---------------------------------------------------------------------------- module Control.Lens.Setter ( -- * Setters Setter, Setter' , IndexedSetter, IndexedSetter' , ASetter, ASetter' , AnIndexedSetter, AnIndexedSetter' , Setting, Setting' -- * Building Setters , sets, setting , cloneSetter , cloneIndexPreservingSetter , cloneIndexedSetter -- * Common Setters , mapped, lifted , contramapped , argument -- * Functional Combinators , over , set , (.~), (%~) , (+~), (-~), (*~), (//~), (^~), (^^~), (**~), (||~), (<>~), (&&~), (<.~), (?~), (<?~) -- * State Combinators , assign , (.=), (%=) , (+=), (-=), (*=), (//=), (^=), (^^=), (**=), (||=), (<>=), (&&=), (<.=), (?=), (<?=) , (<~) -- * Writer Combinators , scribe , passing, ipassing , censoring, icensoring -- * Simplified State Setting , set' -- * Indexed Setters , imapOf, iover, iset , isets , (%@~), (.@~), (%@=), (.@=) -- * Arrow operators , assignA -- * Exported for legible error messages , Settable , Identity(..) -- * Deprecated , mapOf ) where import Control.Applicative import Control.Arrow import Control.Comonad import Control.Lens.Internal.Indexed import Control.Lens.Internal.Setter import Control.Lens.Type import Control.Monad (liftM) import Control.Monad.State.Class as State import Control.Monad.Writer.Class as Writer import Data.Functor.Contravariant import Data.Functor.Identity import Data.Monoid import Data.Profunctor import Data.Profunctor.Rep import Data.Profunctor.Sieve import Data.Profunctor.Unsafe import Prelude #ifdef HLINT {-# ANN module "HLint: ignore Avoid lambda" #-} #endif -- $setup -- >>> import Control.Lens -- >>> import Control.Monad.State -- >>> import Data.Char -- >>> import Data.Map as Map -- >>> import Debug.SimpleReflect.Expr as Expr -- >>> import Debug.SimpleReflect.Vars as Vars -- >>> let f :: Expr -> Expr; f = Vars.f -- >>> let g :: Expr -> Expr; g = Vars.g -- >>> let h :: Expr -> Expr -> Expr; h = Vars.h -- >>> let getter :: Expr -> Expr; getter = fun "getter" -- >>> let setter :: Expr -> Expr -> Expr; setter = fun "setter" -- >>> :set -XNoOverloadedStrings infixr 4 %@~, .@~, .~, +~, *~, -~, //~, ^~, ^^~, **~, &&~, <>~, ||~, %~, <.~, ?~, <?~ infix 4 %@=, .@=, .=, +=, *=, -=, //=, ^=, ^^=, **=, &&=, <>=, ||=, %=, <.=, ?=, <?= infixr 2 <~ ------------------------------------------------------------------------------ -- Setters ------------------------------------------------------------------------------ -- | Running a 'Setter' instantiates it to a concrete type. -- -- When consuming a setter directly to perform a mapping, you can use this type, but most -- user code will not need to use this type. type ASetter s t a b = (a -> Identity b) -> s -> Identity t -- | This is a useful alias for use when consuming a 'Setter''. -- -- Most user code will never have to use this type. -- -- @ -- type 'ASetter'' = 'Simple' 'ASetter' -- @ type ASetter' s a = ASetter s s a a -- | Running an 'IndexedSetter' instantiates it to a concrete type. -- -- When consuming a setter directly to perform a mapping, you can use this type, but most -- user code will not need to use this type. type AnIndexedSetter i s t a b = Indexed i a (Identity b) -> s -> Identity t -- | @ -- type 'AnIndexedSetter'' i = 'Simple' ('AnIndexedSetter' i) -- @ type AnIndexedSetter' i s a = AnIndexedSetter i s s a a -- | This is a convenient alias when defining highly polymorphic code that takes both -- 'ASetter' and 'AnIndexedSetter' as appropriate. If a function takes this it is -- expecting one of those two things based on context. type Setting p s t a b = p a (Identity b) -> s -> Identity t -- | This is a convenient alias when defining highly polymorphic code that takes both -- 'ASetter'' and 'AnIndexedSetter'' as appropriate. If a function takes this it is -- expecting one of those two things based on context. type Setting' p s a = Setting p s s a a ----------------------------------------------------------------------------- -- Setters ----------------------------------------------------------------------------- -- | This 'Setter' can be used to map over all of the values in a 'Functor'. -- -- @ -- 'fmap' ≡ 'over' 'mapped' -- 'Data.Traversable.fmapDefault' ≡ 'over' 'Data.Traversable.traverse' -- ('<$') ≡ 'set' 'mapped' -- @ -- -- >>> over mapped f [a,b,c] -- [f a,f b,f c] -- -- >>> over mapped (+1) [1,2,3] -- [2,3,4] -- -- >>> set mapped x [a,b,c] -- [x,x,x] -- -- >>> [[a,b],[c]] & mapped.mapped +~ x -- [[a + x,b + x],[c + x]] -- -- >>> over (mapped._2) length [("hello","world"),("leaders","!!!")] -- [("hello",5),("leaders",3)] -- -- @ -- 'mapped' :: 'Functor' f => 'Setter' (f a) (f b) a b -- @ -- -- If you want an 'IndexPreservingSetter' use @'setting' 'fmap'@. mapped :: Functor f => Setter (f a) (f b) a b mapped = sets fmap {-# INLINE mapped #-} -- | This 'setter' can be used to modify all of the values in a 'Monad'. -- -- You sometimes have to use this rather than 'mapped' -- due to -- temporary insanity 'Functor' is not a superclass of 'Monad'. -- -- @ -- 'liftM' ≡ 'over' 'lifted' -- @ -- -- >>> over lifted f [a,b,c] -- [f a,f b,f c] -- -- >>> set lifted b (Just a) -- Just b -- -- If you want an 'IndexPreservingSetter' use @'setting' 'liftM'@. lifted :: Monad m => Setter (m a) (m b) a b lifted = sets liftM {-# INLINE lifted #-} -- | This 'Setter' can be used to map over all of the inputs to a 'Contravariant'. -- -- @ -- 'contramap' ≡ 'over' 'contramapped' -- @ -- -- >>> getPredicate (over contramapped (*2) (Predicate even)) 5 -- True -- -- >>> getOp (over contramapped (*5) (Op show)) 100 -- "500" -- -- >>> Prelude.map ($ 1) $ over (mapped . _Unwrapping' Op . contramapped) (*12) [(*2),(+1),(^3)] -- [24,13,1728] -- contramapped :: Contravariant f => Setter (f b) (f a) a b contramapped = sets contramap {-# INLINE contramapped #-} -- | This 'Setter' can be used to map over the input of a 'Profunctor'. -- -- The most common 'Profunctor' to use this with is @(->)@. -- -- >>> (argument %~ f) g x -- g (f x) -- -- >>> (argument %~ show) length [1,2,3] -- 7 -- -- >>> (argument %~ f) h x y -- h (f x) y -- -- Map over the argument of the result of a function -- i.e., its second -- argument: -- -- >>> (mapped.argument %~ f) h x y -- h x (f y) -- -- @ -- 'argument' :: 'Setter' (b -> r) (a -> r) a b -- @ argument :: Profunctor p => Setter (p b r) (p a r) a b argument = sets lmap {-# INLINE argument #-} -- | Build an index-preserving 'Setter' from a map-like function. -- -- Your supplied function @f@ is required to satisfy: -- -- @ -- f 'id' ≡ 'id' -- f g '.' f h ≡ f (g '.' h) -- @ -- -- Equational reasoning: -- -- @ -- 'setting' '.' 'over' ≡ 'id' -- 'over' '.' 'setting' ≡ 'id' -- @ -- -- Another way to view 'sets' is that it takes a \"semantic editor combinator\" -- and transforms it into a 'Setter'. -- -- @ -- 'setting' :: ((a -> b) -> s -> t) -> 'Setter' s t a b -- @ setting :: ((a -> b) -> s -> t) -> IndexPreservingSetter s t a b setting l pafb = cotabulate $ \ws -> pure $ l (\a -> untainted (cosieve pafb (a <$ ws))) (extract ws) {-# INLINE setting #-} -- | Build a 'Setter', 'IndexedSetter' or 'IndexPreservingSetter' depending on your choice of 'Profunctor'. -- -- @ -- 'sets' :: ((a -> b) -> s -> t) -> 'Setter' s t a b -- @ sets :: (Profunctor p, Profunctor q, Settable f) => (p a b -> q s t) -> Optical p q f s t a b sets f g = taintedDot (f (untaintedDot g)) {-# INLINE sets #-} -- | Restore 'ASetter' to a full 'Setter'. cloneSetter :: ASetter s t a b -> Setter s t a b cloneSetter l afb = taintedDot $ runIdentity #. l (Identity #. untaintedDot afb) {-# INLINE cloneSetter #-} -- | Build an 'IndexPreservingSetter' from any 'Setter'. cloneIndexPreservingSetter :: ASetter s t a b -> IndexPreservingSetter s t a b cloneIndexPreservingSetter l pafb = cotabulate $ \ws -> taintedDot runIdentity $ l (\a -> Identity (untainted (cosieve pafb (a <$ ws)))) (extract ws) {-# INLINE cloneIndexPreservingSetter #-} -- | Clone an 'IndexedSetter'. cloneIndexedSetter :: AnIndexedSetter i s t a b -> IndexedSetter i s t a b cloneIndexedSetter l pafb = taintedDot (runIdentity #. l (Indexed $ \i -> Identity #. untaintedDot (indexed pafb i))) {-# INLINE cloneIndexedSetter #-} ----------------------------------------------------------------------------- -- Using Setters ----------------------------------------------------------------------------- -- | Modify the target of a 'Lens' or all the targets of a 'Setter' or 'Traversal' -- with a function. -- -- @ -- 'fmap' ≡ 'over' 'mapped' -- 'Data.Traversable.fmapDefault' ≡ 'over' 'Data.Traversable.traverse' -- 'sets' '.' 'over' ≡ 'id' -- 'over' '.' 'sets' ≡ 'id' -- @ -- -- Given any valid 'Setter' @l@, you can also rely on the law: -- -- @ -- 'over' l f '.' 'over' l g = 'over' l (f '.' g) -- @ -- -- /e.g./ -- -- >>> over mapped f (over mapped g [a,b,c]) == over mapped (f . g) [a,b,c] -- True -- -- Another way to view 'over' is to say that it transforms a 'Setter' into a -- \"semantic editor combinator\". -- -- >>> over mapped f (Just a) -- Just (f a) -- -- >>> over mapped (*10) [1,2,3] -- [10,20,30] -- -- >>> over _1 f (a,b) -- (f a,b) -- -- >>> over _1 show (10,20) -- ("10",20) -- -- @ -- 'over' :: 'Setter' s t a b -> (a -> b) -> s -> t -- 'over' :: 'ASetter' s t a b -> (a -> b) -> s -> t -- @ over :: Profunctor p => Setting p s t a b -> p a b -> s -> t over l f = runIdentity #. l (Identity #. f) {-# INLINE over #-} -- | Replace the target of a 'Lens' or all of the targets of a 'Setter' -- or 'Traversal' with a constant value. -- -- @ -- ('<$') ≡ 'set' 'mapped' -- @ -- -- >>> set _2 "hello" (1,()) -- (1,"hello") -- -- >>> set mapped () [1,2,3,4] -- [(),(),(),()] -- -- Note: Attempting to 'set' a 'Fold' or 'Getter' will fail at compile time with an -- relatively nice error message. -- -- @ -- 'set' :: 'Setter' s t a b -> b -> s -> t -- 'set' :: 'Iso' s t a b -> b -> s -> t -- 'set' :: 'Lens' s t a b -> b -> s -> t -- 'set' :: 'Traversal' s t a b -> b -> s -> t -- @ set :: ASetter s t a b -> b -> s -> t set l b = runIdentity #. l (\_ -> Identity b) {-# INLINE set #-} -- | Replace the target of a 'Lens' or all of the targets of a 'Setter'' -- or 'Traversal' with a constant value, without changing its type. -- -- This is a type restricted version of 'set', which retains the type of the original. -- -- >>> set' mapped x [a,b,c,d] -- [x,x,x,x] -- -- >>> set' _2 "hello" (1,"world") -- (1,"hello") -- -- >>> set' mapped 0 [1,2,3,4] -- [0,0,0,0] -- -- Note: Attempting to adjust 'set'' a 'Fold' or 'Getter' will fail at compile time with an -- relatively nice error message. -- -- @ -- 'set'' :: 'Setter'' s a -> a -> s -> s -- 'set'' :: 'Iso'' s a -> a -> s -> s -- 'set'' :: 'Lens'' s a -> a -> s -> s -- 'set'' :: 'Traversal'' s a -> a -> s -> s -- @ set' :: ASetter' s a -> a -> s -> s set' l b = runIdentity #. l (\_ -> Identity b) {-# INLINE set' #-} -- | Modifies the target of a 'Lens' or all of the targets of a 'Setter' or -- 'Traversal' with a user supplied function. -- -- This is an infix version of 'over'. -- -- @ -- 'fmap' f ≡ 'mapped' '%~' f -- 'Data.Traversable.fmapDefault' f ≡ 'Data.Traversable.traverse' '%~' f -- @ -- -- >>> (a,b,c) & _3 %~ f -- (a,b,f c) -- -- >>> (a,b) & both %~ f -- (f a,f b) -- -- >>> _2 %~ length $ (1,"hello") -- (1,5) -- -- >>> traverse %~ f $ [a,b,c] -- [f a,f b,f c] -- -- >>> traverse %~ even $ [1,2,3] -- [False,True,False] -- -- >>> traverse.traverse %~ length $ [["hello","world"],["!!!"]] -- [[5,5],[3]] -- -- @ -- ('%~') :: 'Setter' s t a b -> (a -> b) -> s -> t -- ('%~') :: 'Iso' s t a b -> (a -> b) -> s -> t -- ('%~') :: 'Lens' s t a b -> (a -> b) -> s -> t -- ('%~') :: 'Traversal' s t a b -> (a -> b) -> s -> t -- @ (%~) :: Profunctor p => Setting p s t a b -> p a b -> s -> t (%~) = over {-# INLINE (%~) #-} -- | Replace the target of a 'Lens' or all of the targets of a 'Setter' -- or 'Traversal' with a constant value. -- -- This is an infix version of 'set', provided for consistency with ('.='). -- -- @ -- f '<$' a ≡ 'mapped' '.~' f '$' a -- @ -- -- >>> (a,b,c,d) & _4 .~ e -- (a,b,c,e) -- -- >>> (42,"world") & _1 .~ "hello" -- ("hello","world") -- -- >>> (a,b) & both .~ c -- (c,c) -- -- @ -- ('.~') :: 'Setter' s t a b -> b -> s -> t -- ('.~') :: 'Iso' s t a b -> b -> s -> t -- ('.~') :: 'Lens' s t a b -> b -> s -> t -- ('.~') :: 'Traversal' s t a b -> b -> s -> t -- @ (.~) :: ASetter s t a b -> b -> s -> t (.~) = set {-# INLINE (.~) #-} -- | Set the target of a 'Lens', 'Traversal' or 'Setter' to 'Just' a value. -- -- @ -- l '?~' t ≡ 'set' l ('Just' t) -- @ -- -- >>> Nothing & id ?~ a -- Just a -- -- >>> Map.empty & at 3 ?~ x -- fromList [(3,x)] -- -- @ -- ('?~') :: 'Setter' s t a ('Maybe' b) -> b -> s -> t -- ('?~') :: 'Iso' s t a ('Maybe' b) -> b -> s -> t -- ('?~') :: 'Lens' s t a ('Maybe' b) -> b -> s -> t -- ('?~') :: 'Traversal' s t a ('Maybe' b) -> b -> s -> t -- @ (?~) :: ASetter s t a (Maybe b) -> b -> s -> t l ?~ b = set l (Just b) {-# INLINE (?~) #-} -- | Set with pass-through. -- -- This is mostly present for consistency, but may be useful for chaining assignments. -- -- If you do not need a copy of the intermediate result, then using @l '.~' t@ directly is a good idea. -- -- >>> (a,b) & _1 <.~ c -- (c,(c,b)) -- -- >>> ("good","morning","vietnam") & _3 <.~ "world" -- ("world",("good","morning","world")) -- -- >>> (42,Map.fromList [("goodnight","gracie")]) & _2.at "hello" <.~ Just "world" -- (Just "world",(42,fromList [("goodnight","gracie"),("hello","world")])) -- -- @ -- ('<.~') :: 'Setter' s t a b -> b -> s -> (b, t) -- ('<.~') :: 'Iso' s t a b -> b -> s -> (b, t) -- ('<.~') :: 'Lens' s t a b -> b -> s -> (b, t) -- ('<.~') :: 'Traversal' s t a b -> b -> s -> (b, t) -- @ (<.~) :: ASetter s t a b -> b -> s -> (b, t) l <.~ b = \s -> (b, set l b s) {-# INLINE (<.~) #-} -- | Set to 'Just' a value with pass-through. -- -- This is mostly present for consistency, but may be useful for for chaining assignments. -- -- If you do not need a copy of the intermediate result, then using @l '?~' d@ directly is a good idea. -- -- >>> import Data.Map as Map -- >>> _2.at "hello" <?~ "world" $ (42,Map.fromList [("goodnight","gracie")]) -- ("world",(42,fromList [("goodnight","gracie"),("hello","world")])) -- -- @ -- ('<?~') :: 'Setter' s t a ('Maybe' b) -> b -> s -> (b, t) -- ('<?~') :: 'Iso' s t a ('Maybe' b) -> b -> s -> (b, t) -- ('<?~') :: 'Lens' s t a ('Maybe' b) -> b -> s -> (b, t) -- ('<?~') :: 'Traversal' s t a ('Maybe' b) -> b -> s -> (b, t) -- @ (<?~) :: ASetter s t a (Maybe b) -> b -> s -> (b, t) l <?~ b = \s -> (b, set l (Just b) s) {-# INLINE (<?~) #-} -- | Increment the target(s) of a numerically valued 'Lens', 'Setter' or 'Traversal'. -- -- >>> (a,b) & _1 +~ c -- (a + c,b) -- -- >>> (a,b) & both +~ c -- (a + c,b + c) -- -- >>> (1,2) & _2 +~ 1 -- (1,3) -- -- >>> [(a,b),(c,d)] & traverse.both +~ e -- [(a + e,b + e),(c + e,d + e)] -- -- @ -- ('+~') :: 'Num' a => 'Setter'' s a -> a -> s -> s -- ('+~') :: 'Num' a => 'Iso'' s a -> a -> s -> s -- ('+~') :: 'Num' a => 'Lens'' s a -> a -> s -> s -- ('+~') :: 'Num' a => 'Traversal'' s a -> a -> s -> s -- @ (+~) :: Num a => ASetter s t a a -> a -> s -> t l +~ n = over l (+ n) {-# INLINE (+~) #-} -- | Multiply the target(s) of a numerically valued 'Lens', 'Iso', 'Setter' or 'Traversal'. -- -- >>> (a,b) & _1 *~ c -- (a * c,b) -- -- >>> (a,b) & both *~ c -- (a * c,b * c) -- -- >>> (1,2) & _2 *~ 4 -- (1,8) -- -- >>> Just 24 & mapped *~ 2 -- Just 48 -- -- @ -- ('*~') :: 'Num' a => 'Setter'' s a -> a -> s -> s -- ('*~') :: 'Num' a => 'Iso'' s a -> a -> s -> s -- ('*~') :: 'Num' a => 'Lens'' s a -> a -> s -> s -- ('*~') :: 'Num' a => 'Traversal'' s a -> a -> s -> s -- @ (*~) :: Num a => ASetter s t a a -> a -> s -> t l *~ n = over l (* n) {-# INLINE (*~) #-} -- | Decrement the target(s) of a numerically valued 'Lens', 'Iso', 'Setter' or 'Traversal'. -- -- >>> (a,b) & _1 -~ c -- (a - c,b) -- -- >>> (a,b) & both -~ c -- (a - c,b - c) -- -- >>> _1 -~ 2 $ (1,2) -- (-1,2) -- -- >>> mapped.mapped -~ 1 $ [[4,5],[6,7]] -- [[3,4],[5,6]] -- -- @ -- ('-~') :: 'Num' a => 'Setter'' s a -> a -> s -> s -- ('-~') :: 'Num' a => 'Iso'' s a -> a -> s -> s -- ('-~') :: 'Num' a => 'Lens'' s a -> a -> s -> s -- ('-~') :: 'Num' a => 'Traversal'' s a -> a -> s -> s -- @ (-~) :: Num a => ASetter s t a a -> a -> s -> t l -~ n = over l (subtract n) {-# INLINE (-~) #-} -- | Divide the target(s) of a numerically valued 'Lens', 'Iso', 'Setter' or 'Traversal'. -- -- >>> (a,b) & _1 //~ c -- (a / c,b) -- -- >>> (a,b) & both //~ c -- (a / c,b / c) -- -- >>> ("Hawaii",10) & _2 //~ 2 -- ("Hawaii",5.0) -- -- @ -- ('//~') :: 'Fractional' a => 'Setter'' s a -> a -> s -> s -- ('//~') :: 'Fractional' a => 'Iso'' s a -> a -> s -> s -- ('//~') :: 'Fractional' a => 'Lens'' s a -> a -> s -> s -- ('//~') :: 'Fractional' a => 'Traversal'' s a -> a -> s -> s -- @ (//~) :: Fractional a => ASetter s t a a -> a -> s -> t l //~ n = over l (/ n) {-# INLINE (//~) #-} -- | Raise the target(s) of a numerically valued 'Lens', 'Setter' or 'Traversal' to a non-negative integral power. -- -- >>> (1,3) & _2 ^~ 2 -- (1,9) -- -- @ -- ('^~') :: ('Num' a, 'Integral' e) => 'Setter'' s a -> e -> s -> s -- ('^~') :: ('Num' a, 'Integral' e) => 'Iso'' s a -> e -> s -> s -- ('^~') :: ('Num' a, 'Integral' e) => 'Lens'' s a -> e -> s -> s -- ('^~') :: ('Num' a, 'Integral' e) => 'Traversal'' s a -> e -> s -> s -- @ (^~) :: (Num a, Integral e) => ASetter s t a a -> e -> s -> t l ^~ n = over l (^ n) {-# INLINE (^~) #-} -- | Raise the target(s) of a fractionally valued 'Lens', 'Setter' or 'Traversal' to an integral power. -- -- >>> (1,2) & _2 ^^~ (-1) -- (1,0.5) -- -- @ -- ('^^~') :: ('Fractional' a, 'Integral' e) => 'Setter'' s a -> e -> s -> s -- ('^^~') :: ('Fractional' a, 'Integral' e) => 'Iso'' s a -> e -> s -> s -- ('^^~') :: ('Fractional' a, 'Integral' e) => 'Lens'' s a -> e -> s -> s -- ('^^~') :: ('Fractional' a, 'Integral' e) => 'Traversal'' s a -> e -> s -> s -- @ -- (^^~) :: (Fractional a, Integral e) => ASetter s t a a -> e -> s -> t l ^^~ n = over l (^^ n) {-# INLINE (^^~) #-} -- | Raise the target(s) of a floating-point valued 'Lens', 'Setter' or 'Traversal' to an arbitrary power. -- -- >>> (a,b) & _1 **~ c -- (a**c,b) -- -- >>> (a,b) & both **~ c -- (a**c,b**c) -- -- >>> _2 **~ 10 $ (3,2) -- (3,1024.0) -- -- @ -- ('**~') :: 'Floating' a => 'Setter'' s a -> a -> s -> s -- ('**~') :: 'Floating' a => 'Iso'' s a -> a -> s -> s -- ('**~') :: 'Floating' a => 'Lens'' s a -> a -> s -> s -- ('**~') :: 'Floating' a => 'Traversal'' s a -> a -> s -> s -- @ (**~) :: Floating a => ASetter s t a a -> a -> s -> t l **~ n = over l (** n) {-# INLINE (**~) #-} -- | Logically '||' the target(s) of a 'Bool'-valued 'Lens' or 'Setter'. -- -- >>> both ||~ True $ (False,True) -- (True,True) -- -- >>> both ||~ False $ (False,True) -- (False,True) -- -- @ -- ('||~') :: 'Setter'' s 'Bool' -> 'Bool' -> s -> s -- ('||~') :: 'Iso'' s 'Bool' -> 'Bool' -> s -> s -- ('||~') :: 'Lens'' s 'Bool' -> 'Bool' -> s -> s -- ('||~') :: 'Traversal'' s 'Bool' -> 'Bool' -> s -> s -- @ (||~):: ASetter s t Bool Bool -> Bool -> s -> t l ||~ n = over l (|| n) {-# INLINE (||~) #-} -- | Logically '&&' the target(s) of a 'Bool'-valued 'Lens' or 'Setter'. -- -- >>> both &&~ True $ (False, True) -- (False,True) -- -- >>> both &&~ False $ (False, True) -- (False,False) -- -- @ -- ('&&~') :: 'Setter'' s 'Bool' -> 'Bool' -> s -> s -- ('&&~') :: 'Iso'' s 'Bool' -> 'Bool' -> s -> s -- ('&&~') :: 'Lens'' s 'Bool' -> 'Bool' -> s -> s -- ('&&~') :: 'Traversal'' s 'Bool' -> 'Bool' -> s -> s -- @ (&&~) :: ASetter s t Bool Bool -> Bool -> s -> t l &&~ n = over l (&& n) {-# INLINE (&&~) #-} ------------------------------------------------------------------------------ -- Using Setters with State ------------------------------------------------------------------------------ -- | Replace the target of a 'Lens' or all of the targets of a 'Setter' or 'Traversal' in our monadic -- state with a new value, irrespective of the old. -- -- This is an alias for ('.='). -- -- >>> execState (do assign _1 c; assign _2 d) (a,b) -- (c,d) -- -- >>> execState (both .= c) (a,b) -- (c,c) -- -- @ -- 'assign' :: 'MonadState' s m => 'Iso'' s a -> a -> m () -- 'assign' :: 'MonadState' s m => 'Lens'' s a -> a -> m () -- 'assign' :: 'MonadState' s m => 'Traversal'' s a -> a -> m () -- 'assign' :: 'MonadState' s m => 'Setter'' s a -> a -> m () -- @ assign :: MonadState s m => ASetter s s a b -> b -> m () assign l b = State.modify (set l b) {-# INLINE assign #-} -- | Replace the target of a 'Lens' or all of the targets of a 'Setter' -- or 'Traversal' in our monadic state with a new value, irrespective of the -- old. -- -- This is an infix version of 'assign'. -- -- >>> execState (do _1 .= c; _2 .= d) (a,b) -- (c,d) -- -- >>> execState (both .= c) (a,b) -- (c,c) -- -- @ -- ('.=') :: 'MonadState' s m => 'Iso'' s a -> a -> m () -- ('.=') :: 'MonadState' s m => 'Lens'' s a -> a -> m () -- ('.=') :: 'MonadState' s m => 'Traversal'' s a -> a -> m () -- ('.=') :: 'MonadState' s m => 'Setter'' s a -> a -> m () -- @ -- -- /It puts the state in the monad or it gets the hose again./ (.=) :: MonadState s m => ASetter s s a b -> b -> m () l .= b = State.modify (l .~ b) {-# INLINE (.=) #-} -- | Map over the target of a 'Lens' or all of the targets of a 'Setter' or 'Traversal' in our monadic state. -- -- >>> execState (do _1 %= f;_2 %= g) (a,b) -- (f a,g b) -- -- >>> execState (do both %= f) (a,b) -- (f a,f b) -- -- @ -- ('%=') :: 'MonadState' s m => 'Iso'' s a -> (a -> a) -> m () -- ('%=') :: 'MonadState' s m => 'Lens'' s a -> (a -> a) -> m () -- ('%=') :: 'MonadState' s m => 'Traversal'' s a -> (a -> a) -> m () -- ('%=') :: 'MonadState' s m => 'Setter'' s a -> (a -> a) -> m () -- @ -- -- @ -- ('%=') :: 'MonadState' s m => 'ASetter' s s a b -> (a -> b) -> m () -- @ (%=) :: (Profunctor p, MonadState s m) => Setting p s s a b -> p a b -> m () l %= f = State.modify (l %~ f) {-# INLINE (%=) #-} -- | Replace the target of a 'Lens' or all of the targets of a 'Setter' or 'Traversal' in our monadic -- state with 'Just' a new value, irrespective of the old. -- -- >>> execState (do at 1 ?= a; at 2 ?= b) Map.empty -- fromList [(1,a),(2,b)] -- -- >>> execState (do _1 ?= b; _2 ?= c) (Just a, Nothing) -- (Just b,Just c) -- -- @ -- ('?=') :: 'MonadState' s m => 'Iso'' s ('Maybe' a) -> a -> m () -- ('?=') :: 'MonadState' s m => 'Lens'' s ('Maybe' a) -> a -> m () -- ('?=') :: 'MonadState' s m => 'Traversal'' s ('Maybe' a) -> a -> m () -- ('?=') :: 'MonadState' s m => 'Setter'' s ('Maybe' a) -> a -> m () -- @ (?=) :: MonadState s m => ASetter s s a (Maybe b) -> b -> m () l ?= b = State.modify (l ?~ b) {-# INLINE (?=) #-} -- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by adding a value. -- -- Example: -- -- @ -- 'fresh' :: 'MonadState' 'Int' m => m 'Int' -- 'fresh' = do -- 'id' '+=' 1 -- 'Control.Lens.Getter.use' 'id' -- @ -- -- >>> execState (do _1 += c; _2 += d) (a,b) -- (a + c,b + d) -- -- >>> execState (do _1.at 1.non 0 += 10) (Map.fromList [(2,100)],"hello") -- (fromList [(1,10),(2,100)],"hello") -- -- @ -- ('+=') :: ('MonadState' s m, 'Num' a) => 'Setter'' s a -> a -> m () -- ('+=') :: ('MonadState' s m, 'Num' a) => 'Iso'' s a -> a -> m () -- ('+=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m () -- ('+=') :: ('MonadState' s m, 'Num' a) => 'Traversal'' s a -> a -> m () -- @ (+=) :: (MonadState s m, Num a) => ASetter' s a -> a -> m () l += b = State.modify (l +~ b) {-# INLINE (+=) #-} -- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by subtracting a value. -- -- >>> execState (do _1 -= c; _2 -= d) (a,b) -- (a - c,b - d) -- -- @ -- ('-=') :: ('MonadState' s m, 'Num' a) => 'Setter'' s a -> a -> m () -- ('-=') :: ('MonadState' s m, 'Num' a) => 'Iso'' s a -> a -> m () -- ('-=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m () -- ('-=') :: ('MonadState' s m, 'Num' a) => 'Traversal'' s a -> a -> m () -- @ (-=) :: (MonadState s m, Num a) => ASetter' s a -> a -> m () l -= b = State.modify (l -~ b) {-# INLINE (-=) #-} -- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by multiplying by value. -- -- >>> execState (do _1 *= c; _2 *= d) (a,b) -- (a * c,b * d) -- -- @ -- ('*=') :: ('MonadState' s m, 'Num' a) => 'Setter'' s a -> a -> m () -- ('*=') :: ('MonadState' s m, 'Num' a) => 'Iso'' s a -> a -> m () -- ('*=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m () -- ('*=') :: ('MonadState' s m, 'Num' a) => 'Traversal'' s a -> a -> m () -- @ (*=) :: (MonadState s m, Num a) => ASetter' s a -> a -> m () l *= b = State.modify (l *~ b) {-# INLINE (*=) #-} -- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by dividing by a value. -- -- >>> execState (do _1 //= c; _2 //= d) (a,b) -- (a / c,b / d) -- -- @ -- ('//=') :: ('MonadState' s m, 'Fractional' a) => 'Setter'' s a -> a -> m () -- ('//=') :: ('MonadState' s m, 'Fractional' a) => 'Iso'' s a -> a -> m () -- ('//=') :: ('MonadState' s m, 'Fractional' a) => 'Lens'' s a -> a -> m () -- ('//=') :: ('MonadState' s m, 'Fractional' a) => 'Traversal'' s a -> a -> m () -- @ (//=) :: (MonadState s m, Fractional a) => ASetter' s a -> a -> m () l //= a = State.modify (l //~ a) {-# INLINE (//=) #-} -- | Raise the target(s) of a numerically valued 'Lens', 'Setter' or 'Traversal' to a non-negative integral power. -- -- @ -- ('^=') :: ('MonadState' s m, 'Num' a, 'Integral' e) => 'Setter'' s a -> e -> m () -- ('^=') :: ('MonadState' s m, 'Num' a, 'Integral' e) => 'Iso'' s a -> e -> m () -- ('^=') :: ('MonadState' s m, 'Num' a, 'Integral' e) => 'Lens'' s a -> e -> m () -- ('^=') :: ('MonadState' s m, 'Num' a, 'Integral' e) => 'Traversal'' s a -> e -> m () -- @ (^=) :: (MonadState s m, Num a, Integral e) => ASetter' s a -> e -> m () l ^= e = State.modify (l ^~ e) {-# INLINE (^=) #-} -- | Raise the target(s) of a numerically valued 'Lens', 'Setter' or 'Traversal' to an integral power. -- -- @ -- ('^^=') :: ('MonadState' s m, 'Fractional' a, 'Integral' e) => 'Setter'' s a -> e -> m () -- ('^^=') :: ('MonadState' s m, 'Fractional' a, 'Integral' e) => 'Iso'' s a -> e -> m () -- ('^^=') :: ('MonadState' s m, 'Fractional' a, 'Integral' e) => 'Lens'' s a -> e -> m () -- ('^^=') :: ('MonadState' s m, 'Fractional' a, 'Integral' e) => 'Traversal'' s a -> e -> m () -- @ (^^=) :: (MonadState s m, Fractional a, Integral e) => ASetter' s a -> e -> m () l ^^= e = State.modify (l ^^~ e) {-# INLINE (^^=) #-} -- | Raise the target(s) of a numerically valued 'Lens', 'Setter' or 'Traversal' to an arbitrary power -- -- >>> execState (do _1 **= c; _2 **= d) (a,b) -- (a**c,b**d) -- -- @ -- ('**=') :: ('MonadState' s m, 'Floating' a) => 'Setter'' s a -> a -> m () -- ('**=') :: ('MonadState' s m, 'Floating' a) => 'Iso'' s a -> a -> m () -- ('**=') :: ('MonadState' s m, 'Floating' a) => 'Lens'' s a -> a -> m () -- ('**=') :: ('MonadState' s m, 'Floating' a) => 'Traversal'' s a -> a -> m () -- @ (**=) :: (MonadState s m, Floating a) => ASetter' s a -> a -> m () l **= a = State.modify (l **~ a) {-# INLINE (**=) #-} -- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by taking their logical '&&' with a value. -- -- >>> execState (do _1 &&= True; _2 &&= False; _3 &&= True; _4 &&= False) (True,True,False,False) -- (True,False,False,False) -- -- @ -- ('&&=') :: 'MonadState' s m => 'Setter'' s 'Bool' -> 'Bool' -> m () -- ('&&=') :: 'MonadState' s m => 'Iso'' s 'Bool' -> 'Bool' -> m () -- ('&&=') :: 'MonadState' s m => 'Lens'' s 'Bool' -> 'Bool' -> m () -- ('&&=') :: 'MonadState' s m => 'Traversal'' s 'Bool' -> 'Bool' -> m () -- @ (&&=):: MonadState s m => ASetter' s Bool -> Bool -> m () l &&= b = State.modify (l &&~ b) {-# INLINE (&&=) #-} -- | Modify the target(s) of a 'Lens'', 'Iso, 'Setter' or 'Traversal' by taking their logical '||' with a value. -- -- >>> execState (do _1 ||= True; _2 ||= False; _3 ||= True; _4 ||= False) (True,True,False,False) -- (True,True,True,False) -- -- @ -- ('||=') :: 'MonadState' s m => 'Setter'' s 'Bool' -> 'Bool' -> m () -- ('||=') :: 'MonadState' s m => 'Iso'' s 'Bool' -> 'Bool' -> m () -- ('||=') :: 'MonadState' s m => 'Lens'' s 'Bool' -> 'Bool' -> m () -- ('||=') :: 'MonadState' s m => 'Traversal'' s 'Bool' -> 'Bool' -> m () -- @ (||=) :: MonadState s m => ASetter' s Bool -> Bool -> m () l ||= b = State.modify (l ||~ b) {-# INLINE (||=) #-} -- | Run a monadic action, and set all of the targets of a 'Lens', 'Setter' or 'Traversal' to its result. -- -- @ -- ('<~') :: 'MonadState' s m => 'Iso' s s a b -> m b -> m () -- ('<~') :: 'MonadState' s m => 'Lens' s s a b -> m b -> m () -- ('<~') :: 'MonadState' s m => 'Traversal' s s a b -> m b -> m () -- ('<~') :: 'MonadState' s m => 'Setter' s s a b -> m b -> m () -- @ -- -- As a reasonable mnemonic, this lets you store the result of a monadic action in a 'Lens' rather than -- in a local variable. -- -- @ -- do foo <- bar -- ... -- @ -- -- will store the result in a variable, while -- -- @ -- do foo '<~' bar -- ... -- @ -- -- will store the result in a 'Lens', 'Setter', or 'Traversal'. (<~) :: MonadState s m => ASetter s s a b -> m b -> m () l <~ mb = mb >>= (l .=) {-# INLINE (<~) #-} -- | Set with pass-through -- -- This is useful for chaining assignment without round-tripping through your 'Monad' stack. -- -- @ -- do x <- 'Control.Lens.Tuple._2' '<.=' ninety_nine_bottles_of_beer_on_the_wall -- @ -- -- If you do not need a copy of the intermediate result, then using @l '.=' d@ will avoid unused binding warnings. -- -- @ -- ('<.=') :: 'MonadState' s m => 'Setter' s s a b -> b -> m b -- ('<.=') :: 'MonadState' s m => 'Iso' s s a b -> b -> m b -- ('<.=') :: 'MonadState' s m => 'Lens' s s a b -> b -> m b -- ('<.=') :: 'MonadState' s m => 'Traversal' s s a b -> b -> m b -- @ (<.=) :: MonadState s m => ASetter s s a b -> b -> m b l <.= b = do l .= b return b {-# INLINE (<.=) #-} -- | Set 'Just' a value with pass-through -- -- This is useful for chaining assignment without round-tripping through your 'Monad' stack. -- -- @ -- do x <- 'Control.Lens.At.at' "foo" '<?=' ninety_nine_bottles_of_beer_on_the_wall -- @ -- -- If you do not need a copy of the intermediate result, then using @l '?=' d@ will avoid unused binding warnings. -- -- @ -- ('<?=') :: 'MonadState' s m => 'Setter' s s a ('Maybe' b) -> b -> m b -- ('<?=') :: 'MonadState' s m => 'Iso' s s a ('Maybe' b) -> b -> m b -- ('<?=') :: 'MonadState' s m => 'Lens' s s a ('Maybe' b) -> b -> m b -- ('<?=') :: 'MonadState' s m => 'Traversal' s s a ('Maybe' b) -> b -> m b -- @ (<?=) :: MonadState s m => ASetter s s a (Maybe b) -> b -> m b l <?= b = do l ?= b return b {-# INLINE (<?=) #-} -- | Modify the target of a monoidally valued by 'mappend'ing another value. -- -- >>> (Sum a,b) & _1 <>~ Sum c -- (Sum {getSum = a + c},b) -- -- >>> (Sum a,Sum b) & both <>~ Sum c -- (Sum {getSum = a + c},Sum {getSum = b + c}) -- -- >>> both <>~ "!!!" $ ("hello","world") -- ("hello!!!","world!!!") -- -- @ -- ('<>~') :: 'Monoid' a => 'Setter' s t a a -> a -> s -> t -- ('<>~') :: 'Monoid' a => 'Iso' s t a a -> a -> s -> t -- ('<>~') :: 'Monoid' a => 'Lens' s t a a -> a -> s -> t -- ('<>~') :: 'Monoid' a => 'Traversal' s t a a -> a -> s -> t -- @ (<>~) :: Monoid a => ASetter s t a a -> a -> s -> t l <>~ n = over l (`mappend` n) {-# INLINE (<>~) #-} -- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by 'mappend'ing a value. -- -- >>> execState (do _1 <>= Sum c; _2 <>= Product d) (Sum a,Product b) -- (Sum {getSum = a + c},Product {getProduct = b * d}) -- -- >>> execState (both <>= "!!!") ("hello","world") -- ("hello!!!","world!!!") -- -- @ -- ('<>=') :: ('MonadState' s m, 'Monoid' a) => 'Setter'' s a -> a -> m () -- ('<>=') :: ('MonadState' s m, 'Monoid' a) => 'Iso'' s a -> a -> m () -- ('<>=') :: ('MonadState' s m, 'Monoid' a) => 'Lens'' s a -> a -> m () -- ('<>=') :: ('MonadState' s m, 'Monoid' a) => 'Traversal'' s a -> a -> m () -- @ (<>=) :: (MonadState s m, Monoid a) => ASetter' s a -> a -> m () l <>= a = State.modify (l <>~ a) {-# INLINE (<>=) #-} ----------------------------------------------------------------------------- -- Writer Operations ---------------------------------------------------------------------------- -- | Write to a fragment of a larger 'Writer' format. scribe :: (MonadWriter t m, Monoid s) => ASetter s t a b -> b -> m () scribe l b = tell (set l b mempty) {-# INLINE scribe #-} -- | This is a generalization of 'pass' that alows you to modify just a -- portion of the resulting 'MonadWriter'. passing :: MonadWriter w m => Setter w w u v -> m (a, u -> v) -> m a passing l m = pass $ do (a, uv) <- m return (a, over l uv) {-# INLINE passing #-} -- | This is a generalization of 'pass' that alows you to modify just a -- portion of the resulting 'MonadWriter' with access to the index of an -- 'IndexedSetter'. ipassing :: MonadWriter w m => IndexedSetter i w w u v -> m (a, i -> u -> v) -> m a ipassing l m = pass $ do (a, uv) <- m return (a, iover l uv) {-# INLINE ipassing #-} -- | This is a generalization of 'censor' that alows you to 'censor' just a -- portion of the resulting 'MonadWriter'. censoring :: MonadWriter w m => Setter w w u v -> (u -> v) -> m a -> m a censoring l uv = censor (over l uv) {-# INLINE censoring #-} -- | This is a generalization of 'censor' that alows you to 'censor' just a -- portion of the resulting 'MonadWriter', with access to the index of an -- 'IndexedSetter'. icensoring :: MonadWriter w m => IndexedSetter i w w u v -> (i -> u -> v) -> m a -> m a icensoring l uv = censor (iover l uv) {-# INLINE icensoring #-} ----------------------------------------------------------------------------- -- Indexed Setters ---------------------------------------------------------------------------- -- | Map with index. This is an alias for 'imapOf'. -- -- When you do not need access to the index, then 'over' is more liberal in what it can accept. -- -- @ -- 'over' l ≡ 'iover' l '.' 'const' -- 'iover' l ≡ 'over' l '.' 'Indexed' -- @ -- -- @ -- 'iover' :: 'IndexedSetter' i s t a b -> (i -> a -> b) -> s -> t -- 'iover' :: 'IndexedLens' i s t a b -> (i -> a -> b) -> s -> t -- 'iover' :: 'IndexedTraversal' i s t a b -> (i -> a -> b) -> s -> t -- @ iover :: AnIndexedSetter i s t a b -> (i -> a -> b) -> s -> t iover l = over l .# Indexed {-# INLINE iover #-} -- | Set with index. Equivalent to 'iover' with the current value ignored. -- -- When you do not need access to the index, then 'set' is more liberal in what it can accept. -- -- @ -- 'set' l ≡ 'iset' l '.' 'const' -- @ -- -- @ -- 'iset' :: 'IndexedSetter' i s t a b -> (i -> b) -> s -> t -- 'iset' :: 'IndexedLens' i s t a b -> (i -> b) -> s -> t -- 'iset' :: 'IndexedTraversal' i s t a b -> (i -> b) -> s -> t -- @ iset :: AnIndexedSetter i s t a b -> (i -> b) -> s -> t iset l = iover l . (const .) {-# INLINE iset #-} -- | Build an 'IndexedSetter' from an 'Control.Lens.Indexed.imap'-like function. -- -- Your supplied function @f@ is required to satisfy: -- -- @ -- f 'id' ≡ 'id' -- f g '.' f h ≡ f (g '.' h) -- @ -- -- Equational reasoning: -- -- @ -- 'isets' '.' 'iover' ≡ 'id' -- 'iover' '.' 'isets' ≡ 'id' -- @ -- -- Another way to view 'sets' is that it takes a \"semantic editor combinator\" -- and transforms it into a 'Setter'. isets :: ((i -> a -> b) -> s -> t) -> IndexedSetter i s t a b isets f = sets (f . indexed) {-# INLINE isets #-} -- | Adjust every target of an 'IndexedSetter', 'IndexedLens' or 'IndexedTraversal' -- with access to the index. -- -- @ -- ('%@~') ≡ 'iover' -- @ -- -- When you do not need access to the index then ('%~') is more liberal in what it can accept. -- -- @ -- l '%~' f ≡ l '%@~' 'const' f -- @ -- -- @ -- ('%@~') :: 'IndexedSetter' i s t a b -> (i -> a -> b) -> s -> t -- ('%@~') :: 'IndexedLens' i s t a b -> (i -> a -> b) -> s -> t -- ('%@~') :: 'IndexedTraversal' i s t a b -> (i -> a -> b) -> s -> t -- @ (%@~) :: AnIndexedSetter i s t a b -> (i -> a -> b) -> s -> t l %@~ f = l %~ Indexed f {-# INLINE (%@~) #-} -- | Replace every target of an 'IndexedSetter', 'IndexedLens' or 'IndexedTraversal' -- with access to the index. -- -- @ -- ('.@~') ≡ 'iset' -- @ -- -- When you do not need access to the index then ('.~') is more liberal in what it can accept. -- -- @ -- l '.~' b ≡ l '.@~' 'const' b -- @ -- -- @ -- ('.@~') :: 'IndexedSetter' i s t a b -> (i -> b) -> s -> t -- ('.@~') :: 'IndexedLens' i s t a b -> (i -> b) -> s -> t -- ('.@~') :: 'IndexedTraversal' i s t a b -> (i -> b) -> s -> t -- @ (.@~) :: AnIndexedSetter i s t a b -> (i -> b) -> s -> t l .@~ f = l %~ Indexed (const . f) {-# INLINE (.@~) #-} -- | Adjust every target in the current state of an 'IndexedSetter', 'IndexedLens' or 'IndexedTraversal' -- with access to the index. -- -- When you do not need access to the index then ('%=') is more liberal in what it can accept. -- -- @ -- l '%=' f ≡ l '%@=' 'const' f -- @ -- -- @ -- ('%@=') :: 'MonadState' s m => 'IndexedSetter' i s s a b -> (i -> a -> b) -> m () -- ('%@=') :: 'MonadState' s m => 'IndexedLens' i s s a b -> (i -> a -> b) -> m () -- ('%@=') :: 'MonadState' s m => 'IndexedTraversal' i s t a b -> (i -> a -> b) -> m () -- @ (%@=) :: MonadState s m => AnIndexedSetter i s s a b -> (i -> a -> b) -> m () l %@= f = State.modify (l %@~ f) {-# INLINE (%@=) #-} -- | Replace every target in the current state of an 'IndexedSetter', 'IndexedLens' or 'IndexedTraversal' -- with access to the index. -- -- When you do not need access to the index then ('.=') is more liberal in what it can accept. -- -- @ -- l '.=' b ≡ l '.@=' 'const' b -- @ -- -- @ -- ('.@=') :: 'MonadState' s m => 'IndexedSetter' i s s a b -> (i -> b) -> m () -- ('.@=') :: 'MonadState' s m => 'IndexedLens' i s s a b -> (i -> b) -> m () -- ('.@=') :: 'MonadState' s m => 'IndexedTraversal' i s t a b -> (i -> b) -> m () -- @ (.@=) :: MonadState s m => AnIndexedSetter i s s a b -> (i -> b) -> m () l .@= f = State.modify (l .@~ f) {-# INLINE (.@=) #-} ------------------------------------------------------------------------------ -- Arrows ------------------------------------------------------------------------------ -- | Run an arrow command and use the output to set all the targets of -- a 'Lens', 'Setter' or 'Traversal' to the result. -- -- 'assignA' can be used very similarly to ('<~'), except that the type of -- the object being modified can change; for example: -- -- @ -- runKleisli action ((), (), ()) where -- action = assignA _1 (Kleisli (const getVal1)) -- \>>> assignA _2 (Kleisli (const getVal2)) -- \>>> assignA _3 (Kleisli (const getVal3)) -- getVal1 :: Either String Int -- getVal1 = ... -- getVal2 :: Either String Bool -- getVal2 = ... -- getVal3 :: Either String Char -- getVal3 = ... -- @ -- -- has the type @'Either' 'String' ('Int', 'Bool', 'Char')@ -- -- @ -- 'assignA' :: 'Arrow' p => 'Iso' s t a b -> p s b -> p s t -- 'assignA' :: 'Arrow' p => 'Lens' s t a b -> p s b -> p s t -- 'assignA' :: 'Arrow' p => 'Traversal' s t a b -> p s b -> p s t -- 'assignA' :: 'Arrow' p => 'Setter' s t a b -> p s b -> p s t -- @ assignA :: Arrow p => ASetter s t a b -> p s b -> p s t assignA l p = arr (flip $ set l) &&& p >>> arr (uncurry id) {-# INLINE assignA #-} ------------------------------------------------------------------------------ -- Deprecated ------------------------------------------------------------------------------ -- | 'mapOf' is a deprecated alias for 'over'. mapOf :: Profunctor p => Setting p s t a b -> p a b -> s -> t mapOf = over {-# INLINE mapOf #-} {-# DEPRECATED mapOf "Use `over`" #-} -- | Map with index. (Deprecated alias for 'iover'). -- -- When you do not need access to the index, then 'mapOf' is more liberal in what it can accept. -- -- @ -- 'mapOf' l ≡ 'imapOf' l '.' 'const' -- @ -- -- @ -- 'imapOf' :: 'IndexedSetter' i s t a b -> (i -> a -> b) -> s -> t -- 'imapOf' :: 'IndexedLens' i s t a b -> (i -> a -> b) -> s -> t -- 'imapOf' :: 'IndexedTraversal' i s t a b -> (i -> a -> b) -> s -> t -- @ imapOf :: AnIndexedSetter i s t a b -> (i -> a -> b) -> s -> t imapOf = iover {-# INLINE imapOf #-} {-# DEPRECATED imapOf "Use `iover`" #-}
rpglover64/lens
src/Control/Lens/Setter.hs
bsd-3-clause
42,243
0
17
9,620
5,400
3,353
2,047
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ja-JP"> <title>動的スキャンルール - ベータ | ZAP 拡張</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>コンテンツ</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>インデックス</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>検索</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>お気に入り</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/ascanrulesBeta/src/main/javahelp/org/zaproxy/zap/extension/ascanrulesBeta/resources/help_ja_JP/helpset_ja_JP.hs
apache-2.0
1,023
90
61
160
401
205
196
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ms-MY"> <title>Passive Scan Rules | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/pscanrules/src/main/javahelp/org/zaproxy/zap/extension/pscanrules/resources/help_ms_MY/helpset_ms_MY.hs
apache-2.0
979
78
66
160
415
210
205
-1
-1
{-# LANGUAGE CPP #-} import Control.Concurrent import Control.Monad import GHC.Clock import System.Environment import System.Exit import System.IO import System.Process import System.Timeout -- IMPORTANT: Re-run this test _manually_ on windows if/when you change -- the code in `libraries/base/cbits/inputReady.c` that mentions -- `FILE_TYPE_CHAR`. Only when you run the code manually, in cmd.exe -- or PowerShell, does this code path get activated. -- Running this code in mintty does not count. main :: IO () main = do args <- getArgs case args of [] -> do let cp = (shell ((if isLinuxHost then ("./" ++) else id) "hWaitForInput-accurate-stdin --read-from-stdin")) {std_in = CreatePipe} (_, _, _, ph) <- createProcess cp waitForProcess ph >>= exitWith ("--read-from-stdin":_) -> do let nanoSecondsPerSecond = 1000 * 1000 * 1000 let milliSecondsPerSecond = 1000 let timeToSpend = 1 let timeToSpendNano = timeToSpend * nanoSecondsPerSecond let timeToSpendMilli = timeToSpend * milliSecondsPerSecond start <- getMonotonicTimeNSec b <- hWaitForInput stdin timeToSpendMilli end <- getMonotonicTimeNSec let timeSpentNano = fromIntegral $ end - start let delta = timeSpentNano - timeToSpendNano -- We can never wait for a shorter amount of time than specified putStrLn $ "delta >= 0: " ++ show (delta >= 0) _ -> error "should not happen." isLinuxHost :: Bool #if defined(mingw32_HOST_OS) isLinuxHost = False #else isLinuxHost = True #endif
sdiehl/ghc
libraries/base/tests/hWaitForInput-accurate-stdin.hs
bsd-3-clause
1,811
0
22
585
334
173
161
38
4
-- -- Copyright (c) 2014 Joachim Breitner -- module CallArity ( callArityAnalProgram , callArityRHS -- for testing ) where import VarSet import VarEnv import DynFlags ( DynFlags ) import BasicTypes import CoreSyn import Id import CoreArity ( typeArity ) import CoreUtils ( exprIsHNF ) --import Outputable import UnVarGraph import Control.Arrow ( first, second ) {- %************************************************************************ %* * Call Arity Analyis %* * %************************************************************************ Note [Call Arity: The goal] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The goal of this analysis is to find out if we can eta-expand a local function, based on how it is being called. The motivating example is code this this, which comes up when we implement foldl using foldr, and do list fusion: let go = \x -> let d = case ... of False -> go (x+1) True -> id in \z -> d (x + z) in go 1 0 If we do not eta-expand `go` to have arity 2, we are going to allocate a lot of partial function applications, which would be bad. The function `go` has a type of arity two, but only one lambda is manifest. Further more, an analysis that only looks at the RHS of go cannot be sufficient to eta-expand go: If `go` is ever called with one argument (and the result used multiple times), we would be doing the work in `...` multiple times. So `callArityAnalProgram` looks at the whole let expression to figure out if all calls are nice, i.e. have a high enough arity. It then stores the result in the `calledArity` field of the `IdInfo` of `go`, which the next simplifier phase will eta-expand. The specification of the `calledArity` field is: No work will be lost if you eta-expand me to the arity in `calledArity`. What we want to know for a variable ----------------------------------- For every let-bound variable we'd like to know: 1. A lower bound on the arity of all calls to the variable, and 2. whether the variable is being called at most once or possible multiple times. It is always ok to lower the arity, or pretend that there are multiple calls. In particular, "Minimum arity 0 and possible called multiple times" is always correct. What we want to know from an expression --------------------------------------- In order to obtain that information for variables, we analyize expression and obtain bits of information: I. The arity analysis: For every variable, whether it is absent, or called, and if called, which what arity. II. The Co-Called analysis: For every two variables, whether there is a possibility that both are being called. We obtain as a special case: For every variables, whether there is a possibility that it is being called twice. For efficiency reasons, we gather this information only for a set of *interesting variables*, to avoid spending time on, e.g., variables from pattern matches. The two analysis are not completely independent, as a higher arity can improve the information about what variables are being called once or multiple times. Note [Analysis I: The arity analyis] ------------------------------------ The arity analysis is quite straight forward: The information about an expression is an VarEnv Arity where absent variables are bound to Nothing and otherwise to a lower bound to their arity. When we analyize an expression, we analyize it with a given context arity. Lambdas decrease and applications increase the incoming arity. Analysizing a variable will put that arity in the environment. In lets or cases all the results from the various subexpressions are lubed, which takes the point-wise minimum (considering Nothing an infinity). Note [Analysis II: The Co-Called analysis] ------------------------------------------ The second part is more sophisticated. For reasons explained below, it is not sufficient to simply know how often an expression evalutes a variable. Instead we need to know which variables are possibly called together. The data structure here is an undirected graph of variables, which is provided by the abstract UnVarGraph It is safe to return a larger graph, i.e. one with more edges. The worst case (i.e. the least useful and always correct result) is the complete graph on all free variables, which means that anything can be called together with anything (including itself). Notation for the following: C(e) is the co-called result for e. G₁∪G₂ is the union of two graphs fv is the set of free variables (conveniently the domain of the arity analysis result) S₁×S₂ is the complete bipartite graph { {a,b} | a ∈ S₁, b ∈ S₂ } S² is the complete graph on the set of variables S, S² = S×S C'(e) is a variant for bound expression: If e is called at most once, or it is and stays a thunk (after the analysis), it is simply C(e). Otherwise, the expression can be called multiple times and we return (fv e)² The interesting cases of the analysis: * Var v: No other variables are being called. Return {} (the empty graph) * Lambda v e, under arity 0: This means that e can be evaluated many times and we cannot get any useful co-call information. Return (fv e)² * Case alternatives alt₁,alt₂,...: Only one can be execuded, so Return (alt₁ ∪ alt₂ ∪...) * App e₁ e₂ (and analogously Case scrut alts): We get the results from both sides. Additionally, anything called by e₁ can possibly called with anything from e₂. Return: C(e₁) ∪ C(e₂) ∪ (fv e₁) × (fv e₂) * Let v = rhs in body: In addition to the results from the subexpressions, add all co-calls from everything that the body calls together with v to everthing that is called by v. Return: C'(rhs) ∪ C(body) ∪ (fv rhs) × {v'| {v,v'} ∈ C(body)} * Letrec v₁ = rhs₁ ... vₙ = rhsₙ in body Tricky. We assume that it is really mutually recursive, i.e. that every variable calls one of the others, and that this is strongly connected (otherwise we return an over-approximation, so that's ok), see note [Recursion and fixpointing]. Let V = {v₁,...vₙ}. Assume that the vs have been analysed with an incoming demand and cardinality consistent with the final result (this is the fixed-pointing). Again we can use the results from all subexpressions. In addition, for every variable vᵢ, we need to find out what it is called with (call this set Sᵢ). There are two cases: * If vᵢ is a function, we need to go through all right-hand-sides and bodies, and collect every variable that is called together with any variable from V: Sᵢ = {v' | j ∈ {1,...,n}, {v',vⱼ} ∈ C'(rhs₁) ∪ ... ∪ C'(rhsₙ) ∪ C(body) } * If vᵢ is a thunk, then its rhs is evaluated only once, so we need to exclude it from this set: Sᵢ = {v' | j ∈ {1,...,n}, j≠i, {v',vⱼ} ∈ C'(rhs₁) ∪ ... ∪ C'(rhsₙ) ∪ C(body) } Finally, combine all this: Return: C(body) ∪ C'(rhs₁) ∪ ... ∪ C'(rhsₙ) ∪ (fv rhs₁) × S₁) ∪ ... ∪ (fv rhsₙ) × Sₙ) Using the result: Eta-Expansion ------------------------------- We use the result of these two analyses to decide whether we can eta-expand the rhs of a let-bound variable. If the variable is already a function (exprIsHNF), and all calls to the variables have a higher arity than the current manifest arity (i.e. the number of lambdas), expand. If the variable is a thunk we must be careful: Eta-Expansion will prevent sharing of work, so this is only safe if there is at most one call to the function. Therefore, we check whether {v,v} ∈ G. Example: let n = case .. of .. -- A thunk! in n 0 + n 1 vs. let n = case .. of .. in case .. of T -> n 0 F -> n 1 We are only allowed to eta-expand `n` if it is going to be called at most once in the body of the outer let. So we need to know, for each variable individually, that it is going to be called at most once. Why the co-call graph? ---------------------- Why is it not sufficient to simply remember which variables are called once and which are called multiple times? It would be in the previous example, but consider let n = case .. of .. in case .. of True -> let go = \y -> case .. of True -> go (y + n 1) False > n in go 1 False -> n vs. let n = case .. of .. in case .. of True -> let go = \y -> case .. of True -> go (y+1) False > n in go 1 False -> n In both cases, the body and the rhs of the inner let call n at most once. But only in the second case that holds for the whole expression! The crucial difference is that in the first case, the rhs of `go` can call *both* `go` and `n`, and hence can call `n` multiple times as it recurses, while in the second case find out that `go` and `n` are not called together. Why co-call information for functions? -------------------------------------- Although for eta-expansion we need the information only for thunks, we still need to know whether functions are being called once or multiple times, and together with what other functions. Example: let n = case .. of .. f x = n (x+1) in f 1 + f 2 vs. let n = case .. of .. f x = n (x+1) in case .. of T -> f 0 F -> f 1 Here, the body of f calls n exactly once, but f itself is being called multiple times, so eta-expansion is not allowed. Note [Analysis type signature] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The work-hourse of the analysis is the function `callArityAnal`, with the following type: type CallArityRes = (UnVarGraph, VarEnv Arity) callArityAnal :: Arity -> -- The arity this expression is called with VarSet -> -- The set of interesting variables CoreExpr -> -- The expression to analyse (CallArityRes, CoreExpr) and the following specification: ((coCalls, callArityEnv), expr') = callArityEnv arity interestingIds expr <=> Assume the expression `expr` is being passed `arity` arguments. Then it holds that * The domain of `callArityEnv` is a subset of `interestingIds`. * Any variable from `interestingIds` that is not mentioned in the `callArityEnv` is absent, i.e. not called at all. * Every call from `expr` to a variable bound to n in `callArityEnv` has at least n value arguments. * For two interesting variables `v1` and `v2`, they are not adjacent in `coCalls`, then in no execution of `expr` both are being called. Furthermore, expr' is expr with the callArity field of the `IdInfo` updated. Note [Which variables are interesting] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The analysis would quickly become prohibitive expensive if we would analyse all variables; for most variables we simply do not care about how often they are called, i.e. variables bound in a pattern match. So interesting are variables that are * top-level or let bound * and possibly functions (typeArity > 0) Note [Information about boring variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we decide that the variable bound in `let x = e1 in e2` is not interesting, the analysis of `e2` will not report anything about `x`. To ensure that `callArityBind` does still do the right thing we have to extend the result from `e2` with a safe approximation. This is done using `fakeBoringCalls` and has the effect of analysing x `seq` x `seq` e2 instead, i.e. with `both` the result from `e2` with the most conservative result about the uninteresting value. Note [Recursion and fixpointing] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For a mutually recursive let, we begin by 1. analysing the body, using the same incoming arity as for the whole expression. 2. Then we iterate, memoizing for each of the bound variables the last analysis call, i.e. incoming arity, whether it is called once, and the CallArityRes. 3. We combine the analysis result from the body and the memoized results for the arguments (if already present). 4. For each variable, we find out the incoming arity and whether it is called once, based on the the current analysis result. If this differs from the memoized results, we re-analyse the rhs and update the memoized table. 5. If nothing had to be reanalized, we are done. Otherwise, repeat from step 3. Note [Thunks in recursive groups] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We never eta-expand a thunk in a recursive group, on the grounds that if it is part of a recursive group, then it will be called multipe times. This is not necessarily true, e.g. it would be safe to eta-expand t2 (but not t1) in the follwing code: let go x = t1 t1 = if ... then t2 else ... t2 = if ... then go 1 else ... in go 0 Detecting this would reqiure finding out what variables are only ever called from thunks. While this is certainly possible, we yet have to see this to be relevant in the wild. Note [Analysing top-level binds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We can eta-expand top-level-binds if they are not exported, as we see all calls to them. The plan is as follows: Treat the top-level binds as nested lets around a body representing “all external calls”, which returns a pessimistic CallArityRes (the co-call graph is the complete graph, all arityies 0). -} -- Main entry point callArityAnalProgram :: DynFlags -> CoreProgram -> CoreProgram callArityAnalProgram _dflags binds = binds' where (_, binds') = callArityTopLvl [] emptyVarSet binds -- See Note [Analysing top-level-binds] callArityTopLvl :: [Var] -> VarSet -> [CoreBind] -> (CallArityRes, [CoreBind]) callArityTopLvl exported _ [] = ( calledMultipleTimes $ (emptyUnVarGraph, mkVarEnv $ [(v, 0) | v <- exported]) , [] ) callArityTopLvl exported int1 (b:bs) = (ae2, b':bs') where int2 = bindersOf b exported' = filter isExportedId int2 ++ exported int' = int1 `addInterestingBinds` b (ae1, bs') = callArityTopLvl exported' int' bs ae1' = fakeBoringCalls int' b ae1 -- See Note [Information about boring variables] (ae2, b') = callArityBind ae1' int1 b callArityRHS :: CoreExpr -> CoreExpr callArityRHS = snd . callArityAnal 0 emptyVarSet -- The main analysis function. See Note [Analysis type signature] callArityAnal :: Arity -> -- The arity this expression is called with VarSet -> -- The set of interesting variables CoreExpr -> -- The expression to analyse (CallArityRes, CoreExpr) -- How this expression uses its interesting variables -- and the expression with IdInfo updated -- The trivial base cases callArityAnal _ _ e@(Lit _) = (emptyArityRes, e) callArityAnal _ _ e@(Type _) = (emptyArityRes, e) callArityAnal _ _ e@(Coercion _) = (emptyArityRes, e) -- The transparent cases callArityAnal arity int (Tick t e) = second (Tick t) $ callArityAnal arity int e callArityAnal arity int (Cast e co) = second (\e -> Cast e co) $ callArityAnal arity int e -- The interesting case: Variables, Lambdas, Lets, Applications, Cases callArityAnal arity int e@(Var v) | v `elemVarSet` int = (unitArityRes v arity, e) | otherwise = (emptyArityRes, e) -- Non-value lambdas are ignored callArityAnal arity int (Lam v e) | not (isId v) = second (Lam v) $ callArityAnal arity (int `delVarSet` v) e -- We have a lambda that may be called multiple times, so its free variables -- can all be co-called. callArityAnal 0 int (Lam v e) = (ae', Lam v e') where (ae, e') = callArityAnal 0 (int `delVarSet` v) e ae' = calledMultipleTimes ae -- We have a lambda that we are calling. decrease arity. callArityAnal arity int (Lam v e) = (ae, Lam v e') where (ae, e') = callArityAnal (arity - 1) (int `delVarSet` v) e -- Application. Increase arity for the called expresion, nothing to know about -- the second callArityAnal arity int (App e (Type t)) = second (\e -> App e (Type t)) $ callArityAnal arity int e callArityAnal arity int (App e1 e2) = (final_ae, App e1' e2') where (ae1, e1') = callArityAnal (arity + 1) int e1 (ae2, e2') = callArityAnal 0 int e2 -- See Note [Case and App: Which side to take?] final_ae = ae1 `both` ae2 -- Case expression. callArityAnal arity int (Case scrut bndr ty alts) = -- pprTrace "callArityAnal:Case" -- (vcat [ppr scrut, ppr final_ae]) (final_ae, Case scrut' bndr ty alts') where (alt_aes, alts') = unzip $ map go alts go (dc, bndrs, e) = let (ae, e') = callArityAnal arity int e in (ae, (dc, bndrs, e')) alt_ae = lubRess alt_aes (scrut_ae, scrut') = callArityAnal 0 int scrut -- See Note [Case and App: Which side to take?] final_ae = scrut_ae `both` alt_ae -- For lets, use callArityBind callArityAnal arity int (Let bind e) = -- pprTrace "callArityAnal:Let" -- (vcat [ppr v, ppr arity, ppr n, ppr final_ae ]) (final_ae, Let bind' e') where int_body = int `addInterestingBinds` bind (ae_body, e') = callArityAnal arity int_body e ae_body' = fakeBoringCalls int_body bind ae_body -- See Note [Information about boring variables] (final_ae, bind') = callArityBind ae_body' int bind -- Which bindings should we look at? -- See Note [Which variables are interesting] interestingBinds :: CoreBind -> [Var] interestingBinds = filter go . bindersOf where go v = 0 < length (typeArity (idType v)) addInterestingBinds :: VarSet -> CoreBind -> VarSet addInterestingBinds int bind = int `delVarSetList` bindersOf bind -- Possible shadowing `extendVarSetList` interestingBinds bind -- For every boring variable in the binder, add a safe approximation -- See Note [Information about boring variables] fakeBoringCalls :: VarSet -> CoreBind -> CallArityRes -> CallArityRes fakeBoringCalls int bind res = boring `both` res where boring = calledMultipleTimes $ ( emptyUnVarGraph , mkVarEnv [ (v, 0) | v <- bindersOf bind, not (v `elemVarSet` int)]) -- Used for both local and top-level binds -- First argument is the demand from the body callArityBind :: CallArityRes -> VarSet -> CoreBind -> (CallArityRes, CoreBind) -- Non-recursive let callArityBind ae_body int (NonRec v rhs) | otherwise = -- pprTrace "callArityBind:NonRec" -- (vcat [ppr v, ppr ae_body, ppr int, ppr ae_rhs, ppr safe_arity]) (final_ae, NonRec v' rhs') where is_thunk = not (exprIsHNF rhs) (arity, called_once) = lookupCallArityRes ae_body v safe_arity | called_once = arity | is_thunk = 0 -- A thunk! Do not eta-expand | otherwise = arity (ae_rhs, rhs') = callArityAnal safe_arity int rhs ae_rhs'| called_once = ae_rhs | safe_arity == 0 = ae_rhs -- If it is not a function, its body is evaluated only once | otherwise = calledMultipleTimes ae_rhs final_ae = callArityNonRecEnv v ae_rhs' ae_body v' = v `setIdCallArity` safe_arity -- Recursive let. See Note [Recursion and fixpointing] callArityBind ae_body int b@(Rec binds) = -- pprTrace "callArityBind:Rec" -- (vcat [ppr (Rec binds'), ppr ae_body, ppr int, ppr ae_rhs]) $ (final_ae, Rec binds') where int_body = int `addInterestingBinds` b (ae_rhs, binds') = fix initial_binds final_ae = bindersOf b `resDelList` ae_rhs initial_binds = [(i,Nothing,e) | (i,e) <- binds] fix :: [(Id, Maybe (Bool, Arity, CallArityRes), CoreExpr)] -> (CallArityRes, [(Id, CoreExpr)]) fix ann_binds | -- pprTrace "callArityBind:fix" (vcat [ppr ann_binds, ppr any_change, ppr ae]) $ any_change = fix ann_binds' | otherwise = (ae, map (\(i, _, e) -> (i, e)) ann_binds') where aes_old = [ (i,ae) | (i, Just (_,_,ae), _) <- ann_binds ] ae = callArityRecEnv aes_old ae_body rerun (i, mbLastRun, rhs) | i `elemVarSet` int_body && not (i `elemUnVarSet` domRes ae) -- No call to this yet, so do nothing = (False, (i, Nothing, rhs)) | Just (old_called_once, old_arity, _) <- mbLastRun , called_once == old_called_once , new_arity == old_arity -- No change, no need to re-analize = (False, (i, mbLastRun, rhs)) | otherwise -- We previously analized this with a different arity (or not at all) = let is_thunk = not (exprIsHNF rhs) safe_arity | is_thunk = 0 -- See Note [Thunks in recursive groups] | otherwise = new_arity (ae_rhs, rhs') = callArityAnal safe_arity int_body rhs ae_rhs' | called_once = ae_rhs | safe_arity == 0 = ae_rhs -- If it is not a function, its body is evaluated only once | otherwise = calledMultipleTimes ae_rhs in (True, (i `setIdCallArity` safe_arity, Just (called_once, new_arity, ae_rhs'), rhs')) where (new_arity, called_once) = lookupCallArityRes ae i (changes, ann_binds') = unzip $ map rerun ann_binds any_change = or changes -- Combining the results from body and rhs, non-recursive case -- See Note [Analysis II: The Co-Called analysis] callArityNonRecEnv :: Var -> CallArityRes -> CallArityRes -> CallArityRes callArityNonRecEnv v ae_rhs ae_body = addCrossCoCalls called_by_v called_with_v $ ae_rhs `lubRes` resDel v ae_body where called_by_v = domRes ae_rhs called_with_v = calledWith ae_body v `delUnVarSet` v -- Combining the results from body and rhs, (mutually) recursive case -- See Note [Analysis II: The Co-Called analysis] callArityRecEnv :: [(Var, CallArityRes)] -> CallArityRes -> CallArityRes callArityRecEnv ae_rhss ae_body = -- pprTrace "callArityRecEnv" (vcat [ppr ae_rhss, ppr ae_body, ppr ae_new]) ae_new where vars = map fst ae_rhss ae_combined = lubRess (map snd ae_rhss) `lubRes` ae_body cross_calls = unionUnVarGraphs $ map cross_call ae_rhss cross_call (v, ae_rhs) = completeBipartiteGraph called_by_v called_with_v where is_thunk = idCallArity v == 0 -- What rhs are relevant as happening before (or after) calling v? -- If v is a thunk, everything from all the _other_ variables -- If v is not a thunk, everything can happen. ae_before_v | is_thunk = lubRess (map snd $ filter ((/= v) . fst) ae_rhss) `lubRes` ae_body | otherwise = ae_combined -- What do we want to know from these? -- Which calls can happen next to any recursive call. called_with_v = unionUnVarSets $ map (calledWith ae_before_v) vars called_by_v = domRes ae_rhs ae_new = first (cross_calls `unionUnVarGraph`) ae_combined --------------------------------------- -- Functions related to CallArityRes -- --------------------------------------- -- Result type for the two analyses. -- See Note [Analysis I: The arity analyis] -- and Note [Analysis II: The Co-Called analysis] type CallArityRes = (UnVarGraph, VarEnv Arity) emptyArityRes :: CallArityRes emptyArityRes = (emptyUnVarGraph, emptyVarEnv) unitArityRes :: Var -> Arity -> CallArityRes unitArityRes v arity = (emptyUnVarGraph, unitVarEnv v arity) resDelList :: [Var] -> CallArityRes -> CallArityRes resDelList vs ae = foldr resDel ae vs resDel :: Var -> CallArityRes -> CallArityRes resDel v (g, ae) = (g `delNode` v, ae `delVarEnv` v) domRes :: CallArityRes -> UnVarSet domRes (_, ae) = varEnvDom ae -- In the result, find out the minimum arity and whether the variable is called -- at most once. lookupCallArityRes :: CallArityRes -> Var -> (Arity, Bool) lookupCallArityRes (g, ae) v = case lookupVarEnv ae v of Just a -> (a, not (v `elemUnVarSet` (neighbors g v))) Nothing -> (0, False) calledWith :: CallArityRes -> Var -> UnVarSet calledWith (g, _) v = neighbors g v addCrossCoCalls :: UnVarSet -> UnVarSet -> CallArityRes -> CallArityRes addCrossCoCalls set1 set2 = first (completeBipartiteGraph set1 set2 `unionUnVarGraph`) -- Replaces the co-call graph by a complete graph (i.e. no information) calledMultipleTimes :: CallArityRes -> CallArityRes calledMultipleTimes res = first (const (completeGraph (domRes res))) res -- Used for application and cases both :: CallArityRes -> CallArityRes -> CallArityRes both r1 r2 = addCrossCoCalls (domRes r1) (domRes r2) $ r1 `lubRes` r2 -- Used when combining results from alternative cases; take the minimum lubRes :: CallArityRes -> CallArityRes -> CallArityRes lubRes (g1, ae1) (g2, ae2) = (g1 `unionUnVarGraph` g2, ae1 `lubArityEnv` ae2) lubArityEnv :: VarEnv Arity -> VarEnv Arity -> VarEnv Arity lubArityEnv = plusVarEnv_C min lubRess :: [CallArityRes] -> CallArityRes lubRess = foldl lubRes emptyArityRes
lukexi/ghc
compiler/simplCore/CallArity.hs
bsd-3-clause
25,421
0
17
6,041
3,034
1,666
1,368
194
2
{-# LANGUAGE GADTs #-} -- | Torn from the internals of digestive-functors module SimpleForm.Digestive.Internal ( SimpleForm(..), SimpleFormEnv, input', getField, subView', fieldInputChoiceGroup', underRef ) where import Data.Monoid import Control.Applicative import Control.Monad import Control.Monad.Fix import Text.Blaze.Html (Html) import Control.Monad.Trans.Reader import Control.Monad.Trans.Writer import Data.List (isPrefixOf) import Data.Functor.Identity (Identity) import Control.Arrow (second) import Data.Text (Text) import qualified Data.Text as T import Text.Digestive.Form.Internal import Text.Digestive.Form.Internal.Field import Text.Digestive.Types import Text.Digestive.View import SimpleForm import SimpleForm.Render type SimpleFormEnv r = (Maybe r, View Html, (RenderOptions -> Html)) -- | A form for producing something of type r newtype SimpleForm r a = SimpleForm (ReaderT (SimpleFormEnv r) (Writer Html) a) instance Functor (SimpleForm r) where fmap = liftM instance Applicative (SimpleForm r) where pure = return (<*>) = ap instance Monad (SimpleForm r) where return = SimpleForm . return (SimpleForm x) >>= f = SimpleForm (x >>= (\v -> let SimpleForm r = f v in r)) fail = SimpleForm . fail instance MonadFix (SimpleForm r) where mfix f = SimpleForm (mfix $ unSimpleForm . f) where unSimpleForm (SimpleForm form) = form instance (Monoid a) => Monoid (SimpleForm r a) where mempty = SimpleForm $ ReaderT (\_ -> tell mempty >> return mempty) (SimpleForm a) `mappend` (SimpleForm b) = SimpleForm $ ReaderT $ \env -> do a' <- runReaderT a env b' <- runReaderT b env return (a' `mappend` b') input' :: Text -- ^ Form element name -> (r -> Maybe a) -- ^ Get value from parsed data -> Widget a -- ^ Widget to use (such as 'SimpleForm.wdef') -> InputOptions -- ^ Other options -> SimpleFormEnv r -> Html input' n sel w opt (env, view@(View {viewForm = form}), render) = render $ renderOptions (maybe Nothing sel env) unparsed (pathToText apth) w errors $ opt { label = defaultLabel (label opt), disabled = disabled opt || Disabled `elem` metadata } where defaultLabel (Just DefaultLabel) = Just $ Label $ humanize n defaultLabel x = x apth = case absolutePath n view of (p:ps) | T.null p -> ps | otherwise -> p:ps _ -> [] metadata = concatMap snd $ lookupFormMetadata [n] form errors = map snd $ filter ((==[n]) . fst) $ viewErrors view unparsed = getField [n] view -- | Format form paths just like PHP/Rails pathToText :: [Text] -> Text pathToText [] = mempty pathToText [p] = p pathToText (p:ps) = mconcat (p : concatMap fragment ps) where fragment n = [ T.singleton '[', n, T.singleton ']' ] getField :: Path -> View v -> Maybe Text getField pth (View _ _ form input _ method) = queryField pth form (getField' method givenInput) where givenInput = lookupInput pth input lookupInput :: Path -> [(Path, FormInput)] -> [FormInput] lookupInput path = map snd . filter ((== path) . fst) -- This function is why we need GADTs turned on :( getField' :: Method -- ^ Get/Post -> [FormInput] -- ^ Given input -> Field v a -- ^ Field -> Maybe Text -- ^ Result getField' _ _ (Singleton _) = Nothing getField' _ (TextInput x : _) (Text _) = Just x getField' _ _ (Text x) = Just x getField' _ (TextInput x : _) (Choice _ _) = Just x getField' _ _ (Choice ls' x) = Just $ fst (concatMap snd ls' !! x) getField' Get _ (Bool x) | x = Just (T.pack "on") | otherwise = Nothing getField' Post (TextInput x : _) (Bool _) = Just x getField' Post _ (Bool _) = Nothing getField' Post (FileInput x : _) File = Just (T.pack x) getField' _ _ File = Nothing fieldInputChoiceGroup' :: Path -> View v -> [(Text, [(Text, v)])] fieldInputChoiceGroup' path (View _ _ form input _ method) = map (second $ map (\(v,l,_) -> (v,l))) (queryField path form eval') where givenInput = lookupInput path input eval' :: Field v b -> [(Text, [(Text, v, Bool)])] eval' field = case field of Choice xs didx -> let idx = snd $ evalField method givenInput (Choice xs didx) in merge idx xs [0..] f -> error $ show path ++ ": expected (Choice _ _), " ++ "but got: (" ++ show f ++ ")" merge :: Int -> [(Text, [(Text, (a, v))])] -> [Int] -> [(Text, [(Text, v, Bool)])] merge _ [] _ = [] merge idx (g:gs) is = cur : merge idx gs b where (a,b) = splitAt (length $ snd g) is cur = (fst g, map (\(i, (k, (_, v))) -> (k, v, i == idx)) $ zip a (snd g)) subView' :: Path -> View v -> View v subView' path (View name ctx form input errs method) = case lookupForm path form of [] -> View name (ctx ++ path) notFound (strip input) (strip errs) method (SomeForm f : _) -> View name (ctx ++ path) f (strip input) (strip errs) method where lpath = length path strip :: [(Path, a)] -> [(Path, a)] strip xs = [(drop lpath p, x) | (p, x) <- xs, path `isPrefixOf` p] notFound :: FormTree Identity v Identity a notFound = error $ "Text.Digestive.View.subView: " ++ "No such subView: " ++ show path underRef :: (Form v m a -> Form v m b) -> Form v m a -> Form v m b underRef f (Ref r x) = Ref r (f x) underRef f form = f form
singpolyma/simple-form-haskell
SimpleForm/Digestive/Internal.hs
isc
5,193
272
15
1,107
2,279
1,253
1,026
139
3
{-# LANGUAGE MultiParamTypeClasses #-} {-| Module : Eve.Internal.Types.Character Description : The module contains the data and related functions to the Characters Copyright : (c) Alex Gagné, 2017 License : MIT Stability : experimental -} module Eve.Internal.Types.Character (Characters(..), Character(..)) where import Data.Text (Text) import Data.Time (UTCTime) import Eve.Internal.Types.CachedUntil (CachedUntil, cachedUntil) -- | 'Characters' represents all the character events with the cached timer data Characters = Characters { characters :: [Character] , _characterCachedUntil :: UTCTime } deriving Show -- | 'cachedUntil' will fetch the cache timer on the characters instance CachedUntil Characters UTCTime where cachedUntil = _characterCachedUntil -- | 'Character' represents the Character data from EVE's XML API. data Character = Character { name :: Text , characterID :: Int , corporationName :: Text , corporationID :: Int , allianceName :: Text , allianceID :: Int , factionName :: Text , factionID :: Int } deriving Show
AlexGagne/evecalendar
src/Eve/Internal/Types/Character.hs
mit
1,125
0
9
231
166
108
58
20
0
{-| Module: Flaw.UI.PileBox Description: Container element allowing user to resize child elements. License: MIT -} module Flaw.UI.PileBox ( PileBox(..) , PileBoxItem(..) , PileBoxItemDesc(..) , newPileBox ) where import Control.Concurrent.STM import Control.Monad import Control.Monad.Fix import Flaw.Input.Mouse import Flaw.Math import Flaw.UI import Flaw.UI.Metrics import Flaw.UI.Panel data PileBox = PileBox { pileBoxPanel :: !Panel , pileBoxElementsPanel :: !Panel , pileBoxItems :: ![PileBoxItem] , pileBoxItemsChildren :: ![FreeContainerChild Panel] , pileBoxGripWidth :: {-# UNPACK #-} !Metric , pileBoxHeightVar :: {-# UNPACK #-} !(TVar Metric) } data PileBoxItem = PileBoxItem { pileBoxItemParent :: !PileBox , pileBoxItemElement :: !SomeElement , pileBoxItemElementChild :: !(FreeContainerChild Panel) , pileBoxItemWidthVar :: {-# UNPACK #-} !(TVar Metric) , pileBoxItemLastMousePositionVar :: {-# UNPACK #-} !(TVar (Maybe Position)) , pileBoxItemPressedVar :: {-# UNPACK #-} !(TVar Bool) } data PileBoxItemDesc = PileBoxItemDesc { pileBoxItemDescElement :: !SomeElement , pileBoxItemDescWidth :: {-# UNPACK #-} !Metric } newPileBox :: Metrics -> [PileBoxItemDesc] -> STM PileBox newPileBox Metrics { metricsPileBoxGripWidth = gripWidth } itemDescs = mfix $ \pileBox -> do -- create main panel panel <- newPanel False -- create elements panel and add elements to it elementsPanel <- newPanel False (items, itemsChildren) <- (unzip <$>) . forM itemDescs $ \PileBoxItemDesc { pileBoxItemDescElement = e@(SomeElement element) , pileBoxItemDescWidth = itemWidth }-> do elementChild <- addFreeChild elementsPanel element widthVar <- newTVar itemWidth lastMousePositionVar <- newTVar Nothing pressedVar <- newTVar False let item = PileBoxItem { pileBoxItemParent = pileBox , pileBoxItemElement = e , pileBoxItemElementChild = elementChild , pileBoxItemWidthVar = widthVar , pileBoxItemLastMousePositionVar = lastMousePositionVar , pileBoxItemPressedVar = pressedVar } -- add item to main panel itemChild <- addFreeChild panel item return (item, itemChild) -- add elements panel to main panel void $ addFreeChild panel elementsPanel -- set layout handler setLayoutHandler panel $ layoutElement elementsPanel heightVar <- newTVar 0 return PileBox { pileBoxPanel = panel , pileBoxElementsPanel = elementsPanel , pileBoxItems = items , pileBoxItemsChildren = itemsChildren , pileBoxGripWidth = gripWidth , pileBoxHeightVar = heightVar } instance Element PileBox where layoutElement pileBox@PileBox { pileBoxPanel = panel , pileBoxHeightVar = heightVar } size@(Vec2 _sx sy) = do layoutElement panel size writeTVar heightVar sy relayoutPileBox pileBox dabElement = dabElement . pileBoxPanel elementMouseCursor = elementMouseCursor . pileBoxPanel renderElement = renderElement . pileBoxPanel processInputEvent = processInputEvent . pileBoxPanel focusElement = focusElement . pileBoxPanel unfocusElement = unfocusElement . pileBoxPanel instance Element PileBoxItem where layoutElement _ _ = return () dabElement PileBoxItem { pileBoxItemParent = PileBox { pileBoxGripWidth = gripWidth , pileBoxHeightVar = heightVar } } (Vec2 x y) = if x < 0 || y < 0 || x >= gripWidth then return False else do height <- readTVar heightVar return $ y < height elementMouseCursor _ = return MouseCursorSizeWE renderElement _ _ _ = return $ return () processInputEvent PileBoxItem { pileBoxItemParent = parent , pileBoxItemWidthVar = widthVar , pileBoxItemLastMousePositionVar = lastMousePositionVar , pileBoxItemPressedVar = pressedVar } inputEvent _inputState = case inputEvent of MouseInputEvent mouseEvent -> case mouseEvent of MouseDownEvent LeftMouseButton -> do writeTVar pressedVar True return True MouseUpEvent LeftMouseButton -> do writeTVar pressedVar False return True CursorMoveEvent x y -> do let writeLastMousePosition = writeTVar lastMousePositionVar $ Just $ Vec2 x y pressed <- readTVar pressedVar if pressed then do maybeLastMousePosition <- readTVar lastMousePositionVar case maybeLastMousePosition of Just (Vec2 lx _ly) -> do oldWidth <- readTVar widthVar let newWidth = max 0 $ oldWidth + x - lx writeTVar widthVar newWidth writeTVar lastMousePositionVar $ Just $ Vec2 (x - (newWidth - oldWidth)) y relayoutPileBox parent Nothing -> writeLastMousePosition else writeLastMousePosition return True _ -> return False MouseLeaveEvent -> do writeTVar lastMousePositionVar Nothing return True _ -> return False relayoutPileBox :: PileBox -> STM () relayoutPileBox PileBox { pileBoxPanel = panel , pileBoxElementsPanel = elementsPanel , pileBoxItems = items , pileBoxItemsChildren = itemsChildren , pileBoxGripWidth = gripWidth , pileBoxHeightVar = heightVar } = do height <- readTVar heightVar let foldWidth totalWidth (PileBoxItem { pileBoxItemElement = SomeElement element , pileBoxItemElementChild = elementChild , pileBoxItemWidthVar = widthVar }, itemChild) = do width <- readTVar widthVar layoutElement element $ Vec2 width height placeFreeChild elementsPanel elementChild $ Vec2 totalWidth 0 placeFreeChild panel itemChild $ Vec2 (totalWidth + width - gripWidth `quot` 2) 0 return $ totalWidth + width foldM_ foldWidth 0 $ zip items itemsChildren
quyse/flaw
flaw-ui/Flaw/UI/PileBox.hs
mit
5,799
0
28
1,336
1,391
716
675
162
1
----------------------------------------------------------------------------- -- -- Module : Language.PureScript.AST.Traversals -- Copyright : (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors -- License : MIT -- -- Maintainer : Phil Freeman <paf31@cantab.net> -- Stability : experimental -- Portability : -- -- | AST traversal helpers -- ----------------------------------------------------------------------------- module Language.PureScript.AST.Traversals where import Prelude () import Prelude.Compat import Data.Maybe (mapMaybe) import Control.Monad import Control.Arrow ((***), (+++), second) import Language.PureScript.AST.Binders import Language.PureScript.AST.Declarations import Language.PureScript.Types import Language.PureScript.Traversals everywhereOnValues :: (Declaration -> Declaration) -> (Expr -> Expr) -> (Binder -> Binder) -> (Declaration -> Declaration, Expr -> Expr, Binder -> Binder) everywhereOnValues f g h = (f', g', h') where f' :: Declaration -> Declaration f' (DataBindingGroupDeclaration ds) = f (DataBindingGroupDeclaration (map f' ds)) f' (ValueDeclaration name nameKind bs val) = f (ValueDeclaration name nameKind (map h' bs) ((map (g' *** g') +++ g') val)) f' (BindingGroupDeclaration ds) = f (BindingGroupDeclaration (map (\(name, nameKind, val) -> (name, nameKind, g' val)) ds)) f' (TypeClassDeclaration name args implies ds) = f (TypeClassDeclaration name args implies (map f' ds)) f' (TypeInstanceDeclaration name cs className args ds) = f (TypeInstanceDeclaration name cs className args (mapTypeInstanceBody (map f') ds)) f' (PositionedDeclaration pos com d) = f (PositionedDeclaration pos com (f' d)) f' other = f other g' :: Expr -> Expr g' (UnaryMinus v) = g (UnaryMinus (g' v)) g' (BinaryNoParens op v1 v2) = g (BinaryNoParens (g' op) (g' v1) (g' v2)) g' (Parens v) = g (Parens (g' v)) g' (OperatorSection op (Left v)) = g (OperatorSection (g' op) (Left $ g' v)) g' (OperatorSection op (Right v)) = g (OperatorSection (g' op) (Right $ g' v)) g' (ArrayLiteral vs) = g (ArrayLiteral (map g' vs)) g' (ObjectLiteral vs) = g (ObjectLiteral (map (fmap g') vs)) g' (ObjectConstructor vs) = g (ObjectConstructor (map (second (fmap g')) vs)) g' (TypeClassDictionaryConstructorApp name v) = g (TypeClassDictionaryConstructorApp name (g' v)) g' (Accessor prop v) = g (Accessor prop (g' v)) g' (ObjectUpdate obj vs) = g (ObjectUpdate (g' obj) (map (fmap g') vs)) g' (ObjectUpdater obj vs) = g (ObjectUpdater (fmap g' obj) (map (second (fmap g')) vs)) g' (Abs name v) = g (Abs name (g' v)) g' (App v1 v2) = g (App (g' v1) (g' v2)) g' (IfThenElse v1 v2 v3) = g (IfThenElse (g' v1) (g' v2) (g' v3)) g' (Case vs alts) = g (Case (map g' vs) (map handleCaseAlternative alts)) g' (TypedValue check v ty) = g (TypedValue check (g' v) ty) g' (Let ds v) = g (Let (map f' ds) (g' v)) g' (Do es) = g (Do (map handleDoNotationElement es)) g' (PositionedValue pos com v) = g (PositionedValue pos com (g' v)) g' other = g other h' :: Binder -> Binder h' (ConstructorBinder ctor bs) = h (ConstructorBinder ctor (map h' bs)) h' (ObjectBinder bs) = h (ObjectBinder (map (fmap h') bs)) h' (ArrayBinder bs) = h (ArrayBinder (map h' bs)) h' (NamedBinder name b) = h (NamedBinder name (h' b)) h' (PositionedBinder pos com b) = h (PositionedBinder pos com (h' b)) h' (TypedBinder t b) = h (TypedBinder t (h' b)) h' other = h other handleCaseAlternative :: CaseAlternative -> CaseAlternative handleCaseAlternative ca = ca { caseAlternativeBinders = map h' (caseAlternativeBinders ca) , caseAlternativeResult = (map (g' *** g') +++ g') (caseAlternativeResult ca) } handleDoNotationElement :: DoNotationElement -> DoNotationElement handleDoNotationElement (DoNotationValue v) = DoNotationValue (g' v) handleDoNotationElement (DoNotationBind b v) = DoNotationBind (h' b) (g' v) handleDoNotationElement (DoNotationLet ds) = DoNotationLet (map f' ds) handleDoNotationElement (PositionedDoNotationElement pos com e) = PositionedDoNotationElement pos com (handleDoNotationElement e) everywhereOnValuesTopDownM :: (Functor m, Applicative m, Monad m) => (Declaration -> m Declaration) -> (Expr -> m Expr) -> (Binder -> m Binder) -> (Declaration -> m Declaration, Expr -> m Expr, Binder -> m Binder) everywhereOnValuesTopDownM f g h = (f' <=< f, g' <=< g, h' <=< h) where f' (DataBindingGroupDeclaration ds) = DataBindingGroupDeclaration <$> traverse (f' <=< f) ds f' (ValueDeclaration name nameKind bs val) = ValueDeclaration name nameKind <$> traverse (h' <=< h) bs <*> eitherM (traverse (pairM (g' <=< g) (g' <=< g))) (g' <=< g) val f' (BindingGroupDeclaration ds) = BindingGroupDeclaration <$> traverse (\(name, nameKind, val) -> (,,) name nameKind <$> (g val >>= g')) ds f' (TypeClassDeclaration name args implies ds) = TypeClassDeclaration name args implies <$> traverse (f' <=< f) ds f' (TypeInstanceDeclaration name cs className args ds) = TypeInstanceDeclaration name cs className args <$> traverseTypeInstanceBody (traverse (f' <=< f)) ds f' (PositionedDeclaration pos com d) = PositionedDeclaration pos com <$> (f d >>= f') f' other = f other g' (UnaryMinus v) = UnaryMinus <$> (g v >>= g') g' (BinaryNoParens op v1 v2) = BinaryNoParens <$> (g op >>= g') <*> (g v1 >>= g') <*> (g v2 >>= g') g' (Parens v) = Parens <$> (g v >>= g') g' (OperatorSection op (Left v)) = OperatorSection <$> (g op >>= g') <*> (Left <$> (g v >>= g')) g' (OperatorSection op (Right v)) = OperatorSection <$> (g op >>= g') <*> (Right <$> (g v >>= g')) g' (ArrayLiteral vs) = ArrayLiteral <$> traverse (g' <=< g) vs g' (ObjectLiteral vs) = ObjectLiteral <$> traverse (sndM (g' <=< g)) vs g' (ObjectConstructor vs) = ObjectConstructor <$> traverse (sndM $ maybeM (g' <=< g)) vs g' (TypeClassDictionaryConstructorApp name v) = TypeClassDictionaryConstructorApp name <$> (g v >>= g') g' (Accessor prop v) = Accessor prop <$> (g v >>= g') g' (ObjectUpdate obj vs) = ObjectUpdate <$> (g obj >>= g') <*> traverse (sndM (g' <=< g)) vs g' (ObjectUpdater obj vs) = ObjectUpdater <$> (maybeM g obj >>= maybeM g') <*> traverse (sndM $ maybeM (g' <=< g)) vs g' (Abs name v) = Abs name <$> (g v >>= g') g' (App v1 v2) = App <$> (g v1 >>= g') <*> (g v2 >>= g') g' (IfThenElse v1 v2 v3) = IfThenElse <$> (g v1 >>= g') <*> (g v2 >>= g') <*> (g v3 >>= g') g' (Case vs alts) = Case <$> traverse (g' <=< g) vs <*> traverse handleCaseAlternative alts g' (TypedValue check v ty) = TypedValue check <$> (g v >>= g') <*> pure ty g' (Let ds v) = Let <$> traverse (f' <=< f) ds <*> (g v >>= g') g' (Do es) = Do <$> traverse handleDoNotationElement es g' (PositionedValue pos com v) = PositionedValue pos com <$> (g v >>= g') g' other = g other h' (ConstructorBinder ctor bs) = ConstructorBinder ctor <$> traverse (h' <=< h) bs h' (ObjectBinder bs) = ObjectBinder <$> traverse (sndM (h' <=< h)) bs h' (ArrayBinder bs) = ArrayBinder <$> traverse (h' <=< h) bs h' (NamedBinder name b) = NamedBinder name <$> (h b >>= h') h' (PositionedBinder pos com b) = PositionedBinder pos com <$> (h b >>= h') h' (TypedBinder t b) = TypedBinder t <$> (h b >>= h') h' other = h other handleCaseAlternative (CaseAlternative bs val) = CaseAlternative <$> traverse (h' <=< h) bs <*> eitherM (traverse (pairM (g' <=< g) (g' <=< g))) (g' <=< g) val handleDoNotationElement (DoNotationValue v) = DoNotationValue <$> (g' <=< g) v handleDoNotationElement (DoNotationBind b v) = DoNotationBind <$> (h' <=< h) b <*> (g' <=< g) v handleDoNotationElement (DoNotationLet ds) = DoNotationLet <$> traverse (f' <=< f) ds handleDoNotationElement (PositionedDoNotationElement pos com e) = PositionedDoNotationElement pos com <$> handleDoNotationElement e everywhereOnValuesM :: (Functor m, Applicative m, Monad m) => (Declaration -> m Declaration) -> (Expr -> m Expr) -> (Binder -> m Binder) -> (Declaration -> m Declaration, Expr -> m Expr, Binder -> m Binder) everywhereOnValuesM f g h = (f', g', h') where f' (DataBindingGroupDeclaration ds) = (DataBindingGroupDeclaration <$> traverse f' ds) >>= f f' (ValueDeclaration name nameKind bs val) = (ValueDeclaration name nameKind <$> traverse h' bs <*> eitherM (traverse (pairM g' g')) g' val) >>= f f' (BindingGroupDeclaration ds) = (BindingGroupDeclaration <$> traverse (\(name, nameKind, val) -> (,,) name nameKind <$> g' val) ds) >>= f f' (TypeClassDeclaration name args implies ds) = (TypeClassDeclaration name args implies <$> traverse f' ds) >>= f f' (TypeInstanceDeclaration name cs className args ds) = (TypeInstanceDeclaration name cs className args <$> traverseTypeInstanceBody (traverse f') ds) >>= f f' (PositionedDeclaration pos com d) = (PositionedDeclaration pos com <$> f' d) >>= f f' other = f other g' (UnaryMinus v) = (UnaryMinus <$> g' v) >>= g g' (BinaryNoParens op v1 v2) = (BinaryNoParens <$> g' op <*> g' v1 <*> g' v2) >>= g g' (Parens v) = (Parens <$> g' v) >>= g g' (OperatorSection op (Left v)) = (OperatorSection <$> g' op <*> (Left <$> g' v)) >>= g g' (OperatorSection op (Right v)) = (OperatorSection <$> g' op <*> (Right <$> g' v)) >>= g g' (ArrayLiteral vs) = (ArrayLiteral <$> traverse g' vs) >>= g g' (ObjectLiteral vs) = (ObjectLiteral <$> traverse (sndM g') vs) >>= g g' (ObjectConstructor vs) = (ObjectConstructor <$> traverse (sndM $ maybeM g') vs) >>= g g' (TypeClassDictionaryConstructorApp name v) = (TypeClassDictionaryConstructorApp name <$> g' v) >>= g g' (Accessor prop v) = (Accessor prop <$> g' v) >>= g g' (ObjectUpdate obj vs) = (ObjectUpdate <$> g' obj <*> traverse (sndM g') vs) >>= g g' (ObjectUpdater obj vs) = (ObjectUpdater <$> maybeM g' obj <*> traverse (sndM $ maybeM g') vs) >>= g g' (Abs name v) = (Abs name <$> g' v) >>= g g' (App v1 v2) = (App <$> g' v1 <*> g' v2) >>= g g' (IfThenElse v1 v2 v3) = (IfThenElse <$> g' v1 <*> g' v2 <*> g' v3) >>= g g' (Case vs alts) = (Case <$> traverse g' vs <*> traverse handleCaseAlternative alts) >>= g g' (TypedValue check v ty) = (TypedValue check <$> g' v <*> pure ty) >>= g g' (Let ds v) = (Let <$> traverse f' ds <*> g' v) >>= g g' (Do es) = (Do <$> traverse handleDoNotationElement es) >>= g g' (PositionedValue pos com v) = (PositionedValue pos com <$> g' v) >>= g g' other = g other h' (ConstructorBinder ctor bs) = (ConstructorBinder ctor <$> traverse h' bs) >>= h h' (ObjectBinder bs) = (ObjectBinder <$> traverse (sndM h') bs) >>= h h' (ArrayBinder bs) = (ArrayBinder <$> traverse h' bs) >>= h h' (NamedBinder name b) = (NamedBinder name <$> h' b) >>= h h' (PositionedBinder pos com b) = (PositionedBinder pos com <$> h' b) >>= h h' (TypedBinder t b) = (TypedBinder t <$> h' b) >>= h h' other = h other handleCaseAlternative (CaseAlternative bs val) = CaseAlternative <$> traverse h' bs <*> eitherM (traverse (pairM g' g')) g' val handleDoNotationElement (DoNotationValue v) = DoNotationValue <$> g' v handleDoNotationElement (DoNotationBind b v) = DoNotationBind <$> h' b <*> g' v handleDoNotationElement (DoNotationLet ds) = DoNotationLet <$> traverse f' ds handleDoNotationElement (PositionedDoNotationElement pos com e) = PositionedDoNotationElement pos com <$> handleDoNotationElement e everythingOnValues :: (r -> r -> r) -> (Declaration -> r) -> (Expr -> r) -> (Binder -> r) -> (CaseAlternative -> r) -> (DoNotationElement -> r) -> (Declaration -> r, Expr -> r, Binder -> r, CaseAlternative -> r, DoNotationElement -> r) everythingOnValues (<>) f g h i j = (f', g', h', i', j') where f' d@(DataBindingGroupDeclaration ds) = foldl (<>) (f d) (map f' ds) f' d@(ValueDeclaration _ _ bs (Right val)) = foldl (<>) (f d) (map h' bs) <> g' val f' d@(ValueDeclaration _ _ bs (Left gs)) = foldl (<>) (f d) (map h' bs ++ concatMap (\(grd, val) -> [g' grd, g' val]) gs) f' d@(BindingGroupDeclaration ds) = foldl (<>) (f d) (map (\(_, _, val) -> g' val) ds) f' d@(TypeClassDeclaration _ _ _ ds) = foldl (<>) (f d) (map f' ds) f' d@(TypeInstanceDeclaration _ _ _ _ (ExplicitInstance ds)) = foldl (<>) (f d) (map f' ds) f' d@(PositionedDeclaration _ _ d1) = f d <> f' d1 f' d = f d g' v@(UnaryMinus v1) = g v <> g' v1 g' v@(BinaryNoParens op v1 v2) = g v <> g' op <> g' v1 <> g' v2 g' v@(Parens v1) = g v <> g' v1 g' v@(OperatorSection op (Left v1)) = g v <> g' op <> g' v1 g' v@(OperatorSection op (Right v1)) = g v <> g' op <> g' v1 g' v@(ArrayLiteral vs) = foldl (<>) (g v) (map g' vs) g' v@(ObjectLiteral vs) = foldl (<>) (g v) (map (g' . snd) vs) g' v@(ObjectConstructor vs) = foldl (<>) (g v) (map g' (mapMaybe snd vs)) g' v@(TypeClassDictionaryConstructorApp _ v1) = g v <> g' v1 g' v@(Accessor _ v1) = g v <> g' v1 g' v@(ObjectUpdate obj vs) = foldl (<>) (g v <> g' obj) (map (g' . snd) vs) g' v@(ObjectUpdater obj vs) = foldl (<>) (maybe (g v) (\x -> g v <> g' x) obj) (map g' (mapMaybe snd vs)) g' v@(Abs _ v1) = g v <> g' v1 g' v@(App v1 v2) = g v <> g' v1 <> g' v2 g' v@(IfThenElse v1 v2 v3) = g v <> g' v1 <> g' v2 <> g' v3 g' v@(Case vs alts) = foldl (<>) (foldl (<>) (g v) (map g' vs)) (map i' alts) g' v@(TypedValue _ v1 _) = g v <> g' v1 g' v@(Let ds v1) = foldl (<>) (g v) (map f' ds) <> g' v1 g' v@(Do es) = foldl (<>) (g v) (map j' es) g' v@(PositionedValue _ _ v1) = g v <> g' v1 g' v = g v h' b@(ConstructorBinder _ bs) = foldl (<>) (h b) (map h' bs) h' b@(ObjectBinder bs) = foldl (<>) (h b) (map (h' . snd) bs) h' b@(ArrayBinder bs) = foldl (<>) (h b) (map h' bs) h' b@(NamedBinder _ b1) = h b <> h' b1 h' b@(PositionedBinder _ _ b1) = h b <> h' b1 h' b@(TypedBinder _ b1) = h b <> h' b1 h' b = h b i' ca@(CaseAlternative bs (Right val)) = foldl (<>) (i ca) (map h' bs) <> g' val i' ca@(CaseAlternative bs (Left gs)) = foldl (<>) (i ca) (map h' bs ++ concatMap (\(grd, val) -> [g' grd, g' val]) gs) j' e@(DoNotationValue v) = j e <> g' v j' e@(DoNotationBind b v) = j e <> h' b <> g' v j' e@(DoNotationLet ds) = foldl (<>) (j e) (map f' ds) j' e@(PositionedDoNotationElement _ _ e1) = j e <> j' e1 everythingWithContextOnValues :: s -> r -> (r -> r -> r) -> (s -> Declaration -> (s, r)) -> (s -> Expr -> (s, r)) -> (s -> Binder -> (s, r)) -> (s -> CaseAlternative -> (s, r)) -> (s -> DoNotationElement -> (s, r)) -> ( Declaration -> r , Expr -> r , Binder -> r , CaseAlternative -> r , DoNotationElement -> r) everythingWithContextOnValues s0 r0 (<>) f g h i j = (f'' s0, g'' s0, h'' s0, i'' s0, j'' s0) where f'' s d = let (s', r) = f s d in r <> f' s' d f' s (DataBindingGroupDeclaration ds) = foldl (<>) r0 (map (f'' s) ds) f' s (ValueDeclaration _ _ bs (Right val)) = foldl (<>) r0 (map (h'' s) bs) <> g'' s val f' s (ValueDeclaration _ _ bs (Left gs)) = foldl (<>) r0 (map (h'' s) bs ++ concatMap (\(grd, val) -> [g'' s grd, g'' s val]) gs) f' s (BindingGroupDeclaration ds) = foldl (<>) r0 (map (\(_, _, val) -> g'' s val) ds) f' s (TypeClassDeclaration _ _ _ ds) = foldl (<>) r0 (map (f'' s) ds) f' s (TypeInstanceDeclaration _ _ _ _ (ExplicitInstance ds)) = foldl (<>) r0 (map (f'' s) ds) f' s (PositionedDeclaration _ _ d1) = f'' s d1 f' _ _ = r0 g'' s v = let (s', r) = g s v in r <> g' s' v g' s (UnaryMinus v1) = g'' s v1 g' s (BinaryNoParens op v1 v2) = g'' s op <> g'' s v1 <> g'' s v2 g' s (Parens v1) = g'' s v1 g' s (OperatorSection op (Left v)) = g'' s op <> g'' s v g' s (OperatorSection op (Right v)) = g'' s op <> g'' s v g' s (ArrayLiteral vs) = foldl (<>) r0 (map (g'' s) vs) g' s (ObjectLiteral vs) = foldl (<>) r0 (map (g'' s . snd) vs) g' s (ObjectConstructor vs) = foldl (<>) r0 (map (g'' s) (mapMaybe snd vs)) g' s (TypeClassDictionaryConstructorApp _ v1) = g'' s v1 g' s (Accessor _ v1) = g'' s v1 g' s (ObjectUpdate obj vs) = foldl (<>) (g'' s obj) (map (g'' s . snd) vs) g' s (ObjectUpdater obj vs) = foldl (<>) (maybe r0 (g'' s) obj) (map (g'' s) (mapMaybe snd vs)) g' s (Abs _ v1) = g'' s v1 g' s (App v1 v2) = g'' s v1 <> g'' s v2 g' s (IfThenElse v1 v2 v3) = g'' s v1 <> g'' s v2 <> g'' s v3 g' s (Case vs alts) = foldl (<>) (foldl (<>) r0 (map (g'' s) vs)) (map (i'' s) alts) g' s (TypedValue _ v1 _) = g'' s v1 g' s (Let ds v1) = foldl (<>) r0 (map (f'' s) ds) <> g'' s v1 g' s (Do es) = foldl (<>) r0 (map (j'' s) es) g' s (PositionedValue _ _ v1) = g'' s v1 g' _ _ = r0 h'' s b = let (s', r) = h s b in r <> h' s' b h' s (ConstructorBinder _ bs) = foldl (<>) r0 (map (h'' s) bs) h' s (ObjectBinder bs) = foldl (<>) r0 (map (h'' s . snd) bs) h' s (ArrayBinder bs) = foldl (<>) r0 (map (h'' s) bs) h' s (NamedBinder _ b1) = h'' s b1 h' s (PositionedBinder _ _ b1) = h'' s b1 h' s (TypedBinder _ b1) = h'' s b1 h' _ _ = r0 i'' s ca = let (s', r) = i s ca in r <> i' s' ca i' s (CaseAlternative bs (Right val)) = foldl (<>) r0 (map (h'' s) bs) <> g'' s val i' s (CaseAlternative bs (Left gs)) = foldl (<>) r0 (map (h'' s) bs ++ concatMap (\(grd, val) -> [g'' s grd, g'' s val]) gs) j'' s e = let (s', r) = j s e in r <> j' s' e j' s (DoNotationValue v) = g'' s v j' s (DoNotationBind b v) = h'' s b <> g'' s v j' s (DoNotationLet ds) = foldl (<>) r0 (map (f'' s) ds) j' s (PositionedDoNotationElement _ _ e1) = j'' s e1 everywhereWithContextOnValuesM :: (Functor m, Applicative m, Monad m) => s -> (s -> Declaration -> m (s, Declaration)) -> (s -> Expr -> m (s, Expr)) -> (s -> Binder -> m (s, Binder)) -> (s -> CaseAlternative -> m (s, CaseAlternative)) -> (s -> DoNotationElement -> m (s, DoNotationElement)) -> ( Declaration -> m Declaration , Expr -> m Expr , Binder -> m Binder , CaseAlternative -> m CaseAlternative , DoNotationElement -> m DoNotationElement) everywhereWithContextOnValuesM s0 f g h i j = (f'' s0, g'' s0, h'' s0, i'' s0, j'' s0) where f'' s = uncurry f' <=< f s f' s (DataBindingGroupDeclaration ds) = DataBindingGroupDeclaration <$> traverse (f'' s) ds f' s (ValueDeclaration name nameKind bs val) = ValueDeclaration name nameKind <$> traverse (h'' s) bs <*> eitherM (traverse (pairM (g'' s) (g'' s))) (g'' s) val f' s (BindingGroupDeclaration ds) = BindingGroupDeclaration <$> traverse (thirdM (g'' s)) ds f' s (TypeClassDeclaration name args implies ds) = TypeClassDeclaration name args implies <$> traverse (f'' s) ds f' s (TypeInstanceDeclaration name cs className args ds) = TypeInstanceDeclaration name cs className args <$> traverseTypeInstanceBody (traverse (f'' s)) ds f' s (PositionedDeclaration pos com d1) = PositionedDeclaration pos com <$> f'' s d1 f' _ other = return other g'' s = uncurry g' <=< g s g' s (UnaryMinus v) = UnaryMinus <$> g'' s v g' s (BinaryNoParens op v1 v2) = BinaryNoParens <$> g'' s op <*> g'' s v1 <*> g'' s v2 g' s (Parens v) = Parens <$> g'' s v g' s (OperatorSection op (Left v)) = OperatorSection <$> g'' s op <*> (Left <$> g'' s v) g' s (OperatorSection op (Right v)) = OperatorSection <$> g'' s op <*> (Right <$> g'' s v) g' s (ArrayLiteral vs) = ArrayLiteral <$> traverse (g'' s) vs g' s (ObjectLiteral vs) = ObjectLiteral <$> traverse (sndM (g'' s)) vs g' s (ObjectConstructor vs) = ObjectConstructor <$> traverse (sndM $ maybeM (g'' s)) vs g' s (TypeClassDictionaryConstructorApp name v) = TypeClassDictionaryConstructorApp name <$> g'' s v g' s (Accessor prop v) = Accessor prop <$> g'' s v g' s (ObjectUpdate obj vs) = ObjectUpdate <$> g'' s obj <*> traverse (sndM (g'' s)) vs g' s (ObjectUpdater obj vs) = ObjectUpdater <$> maybeM (g'' s) obj <*> traverse (sndM $ maybeM (g'' s)) vs g' s (Abs name v) = Abs name <$> g'' s v g' s (App v1 v2) = App <$> g'' s v1 <*> g'' s v2 g' s (IfThenElse v1 v2 v3) = IfThenElse <$> g'' s v1 <*> g'' s v2 <*> g'' s v3 g' s (Case vs alts) = Case <$> traverse (g'' s) vs <*> traverse (i'' s) alts g' s (TypedValue check v ty) = TypedValue check <$> g'' s v <*> pure ty g' s (Let ds v) = Let <$> traverse (f'' s) ds <*> g'' s v g' s (Do es) = Do <$> traverse (j'' s) es g' s (PositionedValue pos com v) = PositionedValue pos com <$> g'' s v g' _ other = return other h'' s = uncurry h' <=< h s h' s (ConstructorBinder ctor bs) = ConstructorBinder ctor <$> traverse (h'' s) bs h' s (ObjectBinder bs) = ObjectBinder <$> traverse (sndM (h'' s)) bs h' s (ArrayBinder bs) = ArrayBinder <$> traverse (h'' s) bs h' s (NamedBinder name b) = NamedBinder name <$> h'' s b h' s (PositionedBinder pos com b) = PositionedBinder pos com <$> h'' s b h' s (TypedBinder t b) = TypedBinder t <$> h'' s b h' _ other = return other i'' s = uncurry i' <=< i s i' s (CaseAlternative bs val) = CaseAlternative <$> traverse (h'' s) bs <*> eitherM (traverse (pairM (g'' s) (g'' s))) (g'' s) val j'' s = uncurry j' <=< j s j' s (DoNotationValue v) = DoNotationValue <$> g'' s v j' s (DoNotationBind b v) = DoNotationBind <$> h'' s b <*> g'' s v j' s (DoNotationLet ds) = DoNotationLet <$> traverse (f'' s) ds j' s (PositionedDoNotationElement pos com e1) = PositionedDoNotationElement pos com <$> j'' s e1 accumTypes :: (Monoid r) => (Type -> r) -> (Declaration -> r, Expr -> r, Binder -> r, CaseAlternative -> r, DoNotationElement -> r) accumTypes f = everythingOnValues mappend forDecls forValues (const mempty) (const mempty) (const mempty) where forDecls (DataDeclaration _ _ _ dctors) = mconcat (concatMap (map f . snd) dctors) forDecls (ExternDeclaration _ ty) = f ty forDecls (TypeClassDeclaration _ _ implies _) = mconcat (concatMap (map f . snd) implies) forDecls (TypeInstanceDeclaration _ cs _ tys _) = mconcat (concatMap (map f . snd) cs) `mappend` mconcat (map f tys) forDecls (TypeSynonymDeclaration _ _ ty) = f ty forDecls (TypeDeclaration _ ty) = f ty forDecls _ = mempty forValues (TypeClassDictionary (_, cs) _) = mconcat (map f cs) forValues (SuperClassDictionary _ tys) = mconcat (map f tys) forValues (TypedValue _ _ ty) = f ty forValues _ = mempty
michaelficarra/purescript
src/Language/PureScript/AST/Traversals.hs
mit
22,465
0
16
5,121
11,189
5,589
5,600
339
38
module Discussion.Context where import Control.Applicative ((<$>)) import qualified Data.Map.Lazy as ML import Data.Map.Lazy (Map) import Discussion.Data import Discussion.Converter -------------------------------------------------------------------------------- type Context = Map Var Func data Func = Func Rank Term deriving (Eq, Show) type Rank = Int -------------------------------------------------------------------------------- emptyContext :: Context emptyContext = ML.empty -------------------------------------------------------------------------------- createFunc :: Args -> Term -> Func createFunc args t = Func (length args) (compact $ Lambda args t) register :: Context -> [(Var,Func)] -> Context register c fs = foldl insert c fs where c `insert` (v, f) = ML.insert v f c -------------------------------------------------------------------------------- isDefined :: Context -> Var -> Bool isDefined c v = ML.member v c isUndefined :: Context -> Var -> Bool isUndefined c v = not $ isDefined c v -------------------------------------------------------------------------------- getRank :: Context -> Var -> Maybe Rank getRank c v = getRank' <$> ML.lookup v c where getRank' (Func r _) = r resolve :: Context -> Var -> Maybe Term resolve c v = getTerm <$> ML.lookup v c where getTerm (Func _ t) = t
todays-mitsui/discussion
src/Discussion/Context.hs
mit
1,406
0
9
265
391
211
180
26
1
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies , RecordWildCards #-} {-| Module : HSat.Solution.Instances.CNF Description : Solution instances for CNF data type Copyright : (c) Andrew Burnett 2014-2015 Maintainer : andyburnett88@gmail.com Stability : experimental Portability : Unknown Exports functionality for a solution type for CNF -} module HSat.Solution.Instances.CNF ( checkCNFSolution , -- :: CNF -> BoolSolution -> Bool emptySolution , -- :: BoolSolution BoolSolution(..) , mkTrueSet , -- :: (MonadRandom m) => Word -> BoolSolution lookup , -- :: Variable -> BoolSolution -> Maybe Sign varsEvalToTrue ,-- :: Clause -> BoolSolution -> Word clausesEvalToTrue,-- :: Clauses -> BoolSolution -> Word solutionFromList ,-- :: [Bool] -> BoolSolution ) where import Prelude hiding (lookup) import Data.Map (Map) import qualified Data.Map as M import HSat.Problem.Instances.CNF import HSat.Problem.Instances.Common import HSat.Problem.Instances.Common.Clause.Internal import HSat.Problem.Instances.CNF.Internal import HSat.Problem.Instances.Common.Clauses.Internal import HSat.Solution.Class import Control.Monad.Random import Control.Monad (replicateM) import qualified Data.Vector as V instance Solution CNF where type SolInstance CNF = BoolSolution checkSolution = checkCNFSolution {-| Checks a CNF against a solution and returns whether it is satisfied or not -} checkCNFSolution :: CNF -> BoolSolution -> Bool checkCNFSolution CNF{..} bs = clausesEvalToTrue getClauses bs == getClauseNumb {-| A 'BoolSolution' consists of an internal 'Map' from 'Variable's to 'Sign's -} data BoolSolution = BoolSolution { solution :: Map Variable Sign } deriving (Eq,Show) {-| Returns an empty Solution -} emptySolution :: BoolSolution emptySolution = BoolSolution M.empty mkTrueSet :: (MonadRandom m) => Word -> m BoolSolution mkTrueSet w = do BoolSolution . M.fromList . zip varList <$> (replicateM (fromEnum w) getRandom) where varList = if w == 0 then [] else map mkVariable [1 .. w] lookup :: Variable -> BoolSolution -> Maybe Sign lookup w b = M.lookup w $ solution b clausesEvalToTrue :: Clauses -> BoolSolution -> Word clausesEvalToTrue Clauses{..} bs = V.foldl' clausesEvalToTrue' 0 getVectClause where clausesEvalToTrue' :: Word -> Clause -> Word clausesEvalToTrue' w clause = if varsEvalToTrue clause bs > 0 then (w+1) else w varsEvalToTrue :: Clause -> BoolSolution -> Word varsEvalToTrue Clause{..} BoolSolution{..} = V.foldl' varsEvalToTrue' 0 getVectLiteral where varsEvalToTrue' :: Word -> Literal -> Word varsEvalToTrue' w Literal{..} = let looked = M.lookup getVariable solution in case (isPos getSign,looked) of (True,Just i) -> if isPos i then (w+1) else w (False, Just i) -> if isNeg i then (w+1) else w _ -> error "HOWAH: varsEvalToTrue" solutionFromList :: [Bool] -> BoolSolution solutionFromList list = BoolSolution $ solutionFromList' (zip [1..] list) M.empty where solutionFromList' :: [(Int,Bool)] -> Map Variable Sign -> Map Variable Sign solutionFromList' [] m = m solutionFromList' ((i,b):xs) m = solutionFromList' xs $ M.insert (mkVariable $ toEnum i) (mkSign b) m
aburnett88/HSat
src/HSat/Solution/Instances/CNF.hs
mit
3,346
0
14
686
798
442
356
65
5
module PipesCerealPlus ( -- ** API for \"pipes\" serializingProducer, deserializingPipe, -- ** Reexports of \"cereal-plus\" types Serializable(..), Serialize, Deserialize, ) where import PipesCerealPlus.Prelude import qualified CerealPlus.Serializable as Serializable import qualified CerealPlus.Serialize as Serialize import qualified CerealPlus.Deserialize as Deserialize import qualified Pipes.ByteString deserializingPipe :: (Monad m, Applicative m, Serializable m a) => Pipe ByteString a (EitherT Text m) () deserializingPipe = await >>= processBS where processBS = liftRunPartial (Deserialize.runPartial Serializable.deserialize) where liftRunPartial runPartial = lift . lift . runPartial >=> \case Deserialize.Fail m bs -> lift $ left $ m Deserialize.Partial runPartial' -> await >>= liftRunPartial runPartial' Deserialize.Done a bs -> yield a >> processBS bs serializingProducer :: (Monad m, Applicative m, Serializable m a) => a -> Producer ByteString m () serializingProducer a = do (r, bs) <- lift $ Serialize.runLazy $ Serializable.serialize a Pipes.ByteString.fromLazy bs return r
nikita-volkov/pipes-cereal-plus
src/PipesCerealPlus.hs
mit
1,222
0
14
266
317
169
148
-1
-1
module Shrimp.Helpers where import Data.ByteString.Lazy (ByteString) import Text.StringTemplate import Maybe (fromJust) renderTemplate dir template attrs = do templates <- directoryGroup dir :: IO (STGroup ByteString) let t = fromJust $ getStringTemplate template templates return render (setManyAttrib attrs t)
aconbere/shrimp
Helpers.hs
mit
320
0
11
46
98
50
48
8
1
{-# LANGUAGE Arrows #-} module Main where import FRP.Yampa import FFI import Types import Control.Monad import Control.Concurrent import Data.Time.Clock.POSIX main :: IO () main = reactimate (return 'a') sense action sigFun sense :: Bool -> IO (DTime, Maybe Char) sense _ = do startT <- getPOSIXTime --threadDelay 100000 --x <- pullOneCharInput x <- getHiddenChar endT <- liftM2 (-) getPOSIXTime (return startT) return (fromRational $ toRational endT, Just x) action :: Bool -> Out -> IO Bool action _ x = putStrLn x >> return False sigFunDelay :: SF Char Out sigFunDelay = proc i -> do t <- time -< i s <- delay 1 'a' -< i o <- arr (\(i,s) -> if i==s then '!' else i) -< (i,s) returnA -< ([o]++ " "++[s]++" "++show t) sigFun :: SF Char Out sigFun = proc i -> do totalTime <- time -< i lastTime <- iPre 0 -< totalTime rec d <- iPre 'a' -< o o <- arr (\(i,s,tDelta) -> if i==s && tDelta<0.5 then '!' else i) -< (i,d,totalTime-lastTime) returnA -< ([o]++ " "++[d]++" "++show (totalTime-lastTime))
santolucito/Euterpea_Projects
reactiveSynth/test.hs
mit
1,076
2
18
260
488
252
236
36
2
{-# LANGUAGE CPP #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} -- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings where import ClassyPrelude.Yesod import Data.Aeson (Result(..), fromJSON, withObject, (.!=), (.:?)) import Data.FileEmbed (embedFile) import Data.Yaml (decodeEither', Parser) import Data.Yaml.Config import Language.Haskell.TH.Syntax (Exp, Name, Q) import Network.Wai.Handler.Warp (HostPreference) import Text.Hamlet import Yesod.Default.Config2 (configSettingsYml) import Yesod.Default.Util (WidgetFileSettings, wfsHamletSettings, widgetFileNoReload, widgetFileReload) -- | Runtime settings to configure this application. These settings can be -- loaded from various sources: defaults, environment variables, config files, -- theoretically even a database. data AppSettings = AppSettings { appStaticDir :: String -- ^ Directory from which to serve static files. , appRoot :: Maybe Text -- ^ Base for all generated URLs. If @Nothing@, determined -- from the request headers. , appHost :: HostPreference -- ^ Host/interface the server should bind to. , appPort :: Int -- ^ Port to listen on , appIpFromHeader :: Bool -- ^ Get the IP address from the header when logging. Useful when sitting -- behind a reverse proxy. , appDatabase :: !DatabaseSettings , appDetailedRequestLogging :: Bool -- ^ Use detailed request logging system , appShouldLogAll :: Bool -- ^ Should all log messages be displayed? , appReloadTemplates :: Bool -- ^ Use the reload version of templates , appMutableStatic :: Bool -- ^ Assume that files in the static dir may change after compilation , appSkipCombining :: Bool -- ^ Perform no stylesheet/script combining , appForceSsl :: Bool -- ^ Force redirect to SSL , appDevDownload :: Bool -- ^ Controls how Git and database resources are downloaded (True means less downloading) } data DatabaseSettings = DSPostgres !Text !(Maybe Int) | DSSqlite !Text !Int parseDatabase :: Bool -- ^ is this dev? if so, allow default of SQLite -> HashMap Text Value -> Parser DatabaseSettings parseDatabase isDev o = if isDev then postgres else sqlite <|> postgres where postgres = DSPostgres <$> o .: "postgres-string" <*> o .: "postgres-poolsize" sqlite = do True <- o .: "sqlite" pure $ DSSqlite "test.sqlite3" 1 instance FromJSON AppSettings where parseJSON = withObject "AppSettings" $ \o -> do let defaultDev = #if DEVELOPMENT True #else False #endif appStaticDir <- o .: "static-dir" appRoot <- (\t -> if null t then Nothing else Just t) <$> o .:? "approot" .!= "" appHost <- fromString <$> o .: "host" appPort <- o .: "port" appIpFromHeader <- o .: "ip-from-header" dev <- o .:? "development" .!= defaultDev appDatabase <- if dev then pure (DSSqlite "test.sqlite3" 7) else parseDatabase dev o appDetailedRequestLogging <- o .:? "detailed-logging" .!= dev appShouldLogAll <- o .:? "should-log-all" .!= dev appReloadTemplates <- o .:? "reload-templates" .!= dev appMutableStatic <- o .:? "mutable-static" .!= dev appSkipCombining <- o .:? "skip-combining" .!= dev appForceSsl <- o .:? "force-ssl" .!= not dev appDevDownload <- o .:? "dev-download" .!= dev return AppSettings {..} -- | Settings for 'widgetFile', such as which template languages to support and -- default Hamlet settings. -- -- For more information on modifying behavior, see: -- -- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile widgetFileSettings :: WidgetFileSettings widgetFileSettings = def { wfsHamletSettings = defaultHamletSettings { hamletNewlines = AlwaysNewlines } } -- | How static files should be combined. combineSettings :: CombineSettings combineSettings = def -- The rest of this file contains settings which rarely need changing by a -- user. widgetFile :: String -> Q Exp widgetFile = (if appReloadTemplates compileTimeAppSettings then widgetFileReload else widgetFileNoReload) widgetFileSettings -- | Raw bytes at compile time of @config/settings.yml@ configSettingsYmlBS :: ByteString configSettingsYmlBS = $(embedFile configSettingsYml) -- | @config/settings.yml@, parsed to a @Value@. configSettingsYmlValue :: Value configSettingsYmlValue = either impureThrow id $ decodeEither' configSettingsYmlBS -- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@. compileTimeAppSettings :: AppSettings compileTimeAppSettings = case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of Error e -> error e Success settings -> settings -- The following two functions can be used to combine multiple CSS or JS files -- at compile time to decrease the number of http requests. -- Sample usage (inside a Widget): -- -- > $(combineStylesheets 'StaticR [style1_css, style2_css]) combineStylesheets :: Name -> [Route Static] -> Q Exp combineStylesheets = combineStylesheets' (appSkipCombining compileTimeAppSettings) combineSettings combineScripts :: Name -> [Route Static] -> Q Exp combineScripts = combineScripts' (appSkipCombining compileTimeAppSettings) combineSettings getAppSettings :: IO AppSettings getAppSettings = loadYamlSettings [configSettingsYml] [] useEnv
fpco/stackage-server
src/Settings.hs
mit
6,261
0
17
1,650
938
523
415
107
2
module CSPMTypeChecker.TCMonad (module Control.Monad.Error, TypeCheckError(..), TypeCheckMonad, readTypeRef, writeTypeRef, freshTypeVar, freshTypeVarWithConstraints, getType, safeGetType, setType, local, getEnvironment, compress, compressTypeScheme, errorIfFalseM, errorIfFalse, getUserOperators, runTypeChecker, setUserOperators ) where import Control.Monad.Error import Control.Monad.State import Data.List (nub, (\\), intersect, group, sort) import Text.PrettyPrint.HughesPJ import Data.Graph import Data.IORef import CSPMDataStructures import {-# SOURCE #-} CSPMPrettyPrinter import qualified OpSemDataStructures as OpSem import Util -- ************************************************************************* -- Type Checker Monad -- ************************************************************************* data TypeCheckError = ErrorWithExp PExp TypeCheckError | ErrorWithPat PPat TypeCheckError | ErrorWithMatch PMatch TypeCheckError | ErrorWithDataTypeClause PDataTypeClause TypeCheckError | ErrorWithDecl PDecl TypeCheckError | ErrorWithModule PModule TypeCheckError | UnificationError (Name, Type) (Name, Type) | UnknownUnificationError Type Type | InfiniteUnificationError TypeVar Type | DuplicatedDefinitions [Name] -- ns is not the duplicates - we calc these | IncorrectNumberOfArguments PExp Int | InvalidSetPattern [PPat] | UnknownError String | VariableNotInScope Name instance Error TypeCheckError where strMsg = UnknownError -- TODO: improve error messages instance Show TypeCheckError where show (ErrorWithPat (Annotated srcloc _ pat) err) = show err++ "in pattern:\n"++ indentEveryLine (show (prettyPrint pat)) show (ErrorWithDecl (Annotated srcloc _ (FunBind (Name n) ms _)) err) = show err++ "in the declaration of "++n++".\n" show (ErrorWithDecl (Annotated srcloc _ (PatBind p e)) err) = show err++ "in the declaration of "++show (prettyPrint p)++".\n" show (ErrorWithMatch (Annotated srcloc _ m) err) = show err -- TODO show (ErrorWithDataTypeClause (Annotated srcloc _ m) err) = show err -- TODO show (ErrorWithDecl (Annotated srcloc _ d) err) = show err++ "in the declaration of:"++ show (prettyPrint d) show (ErrorWithExp (Annotated srcloc _ exp) err) = show err++ "in the expression at "++show srcloc++":\n"++ indentEveryLine (show (prettyPrint exp)) show (ErrorWithModule (Annotated srcloc _ exp) err) = show err show (InfiniteUnificationError tv typ) = "Cannot construct the infinite type: "++ show tv++" = "++show (prettyPrintType [] typ)++" " show (UnknownUnificationError t1 t2) = "Could not match the types:\n"++ "\t"++show (prettyPrintType [] t1)++ "\nand\n"++ "\t"++show (prettyPrintType [] t2)++"\n" show (DuplicatedDefinitions ns) = "The variables: "++ show (hsep (punctuate comma (map (\ (Name n) -> text n) dupedVars)))++ " have multiple definitions." where dupedVars = (map head . filter (\ l -> length l > 1) . group . sort) ns show (IncorrectNumberOfArguments exp correct) = "An incorrect number (correct number: "++show correct++ ") of arguments was supplied to :\n"++ indentEveryLine (show (prettyPrint exp)) show (InvalidSetPattern ps) = "You may only pattern match on set patterns of length 0 or 1." show (VariableNotInScope (Name n)) = "Name "++n++" is not in scope\n" show (UnknownError s) = "An unknown error occured: "++s type Environment = [PartialFunction Name TypeScheme] type UserOperators = PartialFunction Name [Type] data TypeInferenceState = TypeInferenceState { -- map from names to arbitrary types environment :: Environment, -- Next TypeVar to be allocated nextTypeId :: Int, -- map from operator name to types of args operatorSymbolTable :: UserOperators } type TypeCheckMonad = ErrorT TypeCheckError (StateT TypeInferenceState Tyger) runTypeChecker :: TypeCheckMonad a -> Tyger a runTypeChecker prog = do (errOrVal,state)<- runStateT (runErrorT prog) (TypeInferenceState [[]] 0 []) case errOrVal of Left err -> throwError $ CSPMTypeCheckError (show err) Right val -> return val getEnvironment :: TypeCheckMonad Environment getEnvironment = gets environment getUserOperators :: TypeCheckMonad UserOperators getUserOperators = gets operatorSymbolTable setUserOperators :: UserOperators -> TypeCheckMonad () setUserOperators ops = modify (\ s -> s { operatorSymbolTable = ops}) errorIfFalse :: Bool -> TypeCheckError -> TypeCheckMonad () errorIfFalse True e = return () errorIfFalse False e = throwError e errorIfFalseM :: TypeCheckMonad Bool -> TypeCheckError -> TypeCheckMonad () errorIfFalseM m e = do res <- m errorIfFalse res e -- ************************************************************************* -- Type Operations -- ************************************************************************* readTypeRef :: TypeVarRef -> TypeCheckMonad (Either (TypeVar, [Constraint]) Type) readTypeRef (TypeVarRef tv cs ioref) = do mtyp <- readPType ioref case mtyp of Just t -> return (Right t) Nothing -> return (Left (tv, cs)) writeTypeRef :: TypeVarRef -> Type -> TypeCheckMonad () writeTypeRef (TypeVarRef tv cs ioref) t = setPType ioref t freshTypeVar :: TypeCheckMonad Type freshTypeVar = freshTypeVarWithConstraints [] freshTypeVarWithConstraints :: [Constraint] -> TypeCheckMonad Type freshTypeVarWithConstraints cs = do nextId <- gets nextTypeId modify (\s -> s { nextTypeId = nextId+1 }) ioRef <- freshPType return $ TVar (TypeVarRef (TypeVar nextId) cs ioRef) safeGetType_ :: [PartialFunction Name TypeScheme] -> Name -> Maybe TypeScheme safeGetType_ [] n = Nothing safeGetType_ (pf:pfs) n = case safeApply pf n of Just t -> Just t Nothing -> safeGetType_ pfs n getType :: Name -> TypeCheckMonad TypeScheme getType name = do envs <- gets environment case safeGetType_ envs name of Just t -> return t Nothing -> throwError $ VariableNotInScope name safeGetType :: Name -> TypeCheckMonad (Maybe TypeScheme) safeGetType n = do envs <- gets environment return $ safeGetType_ envs n -- Sets the type of n to be t in the current scope only. No unification is -- performed. setType :: Name -> TypeScheme -> TypeCheckMonad () setType n t = do res <- safeGetType n (env:envs) <- gets environment let env' = updatePF env n t modify (\ s -> s { environment = env':envs }) local :: [Name] -> TypeCheckMonad a -> TypeCheckMonad a local ns m = do env <- gets environment newArgs <- replicateM (length ns) freshTypeVar modify (\s -> s { environment = (zip ns (map (ForAll []) newArgs)):env }) res <- m env <- gets environment modify (\ s -> s { environment = tail env }) return res compressTypeScheme :: TypeScheme -> TypeCheckMonad TypeScheme compressTypeScheme (ForAll ts t) = do t' <- compress t return $ ForAll ts t' compress :: Type -> TypeCheckMonad Type compress (tr @ (TVar typeRef)) = do res <- readTypeRef typeRef case res of Left tv -> return tr Right t -> compress t compress (TFunction targs tr) = do targs' <- mapM compress targs tr' <- compress tr return $ TFunction targs' tr' compress (TSeq t) = do t' <- compress t return $ TSeq t' compress (TSet t) = do t' <- compress t return $ TSet t' compress (TTuple ts) = do ts' <- mapM compress ts return $ TTuple ts' compress (TDotable t1 t2)= do t1' <- compress t1 t2' <- compress t2 return $ TDotable t1' t2' compress (TDatatypeClause n ts) = do ts' <- mapM compress ts return $ TDatatypeClause n ts' compress (TChannel tl) = do tl' <- compress tl return $ TChannel tl' compress (TList t1 t2) = do t1 <- compress t1 t2 <- compress t2 return $ TList t1 t2 compress (tr @ (TPolyList typeref)) = do res <- readTypeRef typeref case res of Left tv -> return tr Right t -> compress t compress t = return t
tomgr/tyger
src/CSPMTypeChecker/TCMonad.hs
mit
7,853
156
19
1,416
2,718
1,354
1,364
216
3
import Data.List -- Problem 11 data ListItem a = Single a | Multiple Int a deriving (Show) encode :: Eq a => [a] -> [(Int,a)] encode xs = [(length x, head x) | x <- group xs] encodeModified :: Eq a => [a] -> [ListItem a] encodeModified = map encodeHelper . encode where encodeHelper (1,x) = Single x encodeHelper (n,x) = Multiple n x -- Problem 12 decodeModified :: Eq a => [ListItem a] -> [a] decodeModified [] = [] decodeModified (Single x : xs) = x : (decodeModified xs) decodeModified ((Multiple i x):xs) = (replicate i x) ++ (decodeModified xs) -- Problem 13 encode' :: Eq a => [a] -> [(Int,a)] encode' = foldr helper [] where helper x [] = [(1,x)] helper x (y@(a,b):ys) | x == b = (a+1,b):ys | otherwise = (1,x):y:ys encodeDirect :: Eq a => [a] -> [ListItem a] encodeDirect = map helper . encode' where helper (1,x) = Single x helper (n,x) = Multiple n x -- Problem 14 dupli :: [a] -> [a] dupli [] = [] dupli (x:xs) = x:x:(dupli xs) -- Problem 15 repli :: [a] -> Int -> [a] repli xs count = xs >>= replicate count -- Problem 16 dropEvery :: [a] -> Int -> [a] dropEvery xs n = helper xs n where helper [] _ = [] helper (x:xs) 1 = helper xs n helper (x:xs) k = x : helper xs (k-1)
raphaelmor/99HaskellProblems
11-20.hs
mit
1,229
2
11
281
689
366
323
33
3
module Paths_arduino_webserver ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version [0,1,0,0] [] bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/home/rewrite/Documents/Personal-Repository/Haskell/arduino-webserver/.stack-work/install/x86_64-linux/lts-3.14/7.10.2/bin" libdir = "/home/rewrite/Documents/Personal-Repository/Haskell/arduino-webserver/.stack-work/install/x86_64-linux/lts-3.14/7.10.2/lib/x86_64-linux-ghc-7.10.2/arduino-webserver-0.1.0.0-1uSC0RWgU5TDTHA72qz9Jz" datadir = "/home/rewrite/Documents/Personal-Repository/Haskell/arduino-webserver/.stack-work/install/x86_64-linux/lts-3.14/7.10.2/share/x86_64-linux-ghc-7.10.2/arduino-webserver-0.1.0.0" libexecdir = "/home/rewrite/Documents/Personal-Repository/Haskell/arduino-webserver/.stack-work/install/x86_64-linux/lts-3.14/7.10.2/libexec" sysconfdir = "/home/rewrite/Documents/Personal-Repository/Haskell/arduino-webserver/.stack-work/install/x86_64-linux/lts-3.14/7.10.2/etc" getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "arduino_webserver_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "arduino_webserver_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "arduino_webserver_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "arduino_webserver_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "arduino_webserver_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
cirquit/Personal-Repository
Haskell/arduino-webserver/.stack-work/dist/x86_64-linux/Cabal-1.22.4.0/build/autogen/Paths_arduino_webserver.hs
mit
1,910
0
10
177
362
206
156
28
1
module Tests.PGConnectionString (pgConnectionStringTests) where import Data.Text.Encoding (decodeUtf8) import Database.Selda import Database.Selda.PostgreSQL import Test.HUnit import Tables pgConnectionStringTests :: PGConnectInfo -> Test pgConnectionStringTests s@(PGConnectionString _ _) = test [ "setup" ~: withPostgreSQL s (teardown >> setup :: SeldaM PG ()) ] pgConnectionStringTests ci = pgConnectionStringTests (PGConnectionString (decodeUtf8 $ pgConnString ci) Nothing)
valderman/selda
selda-tests/test/Tests/PGConnectionString.hs
mit
483
0
11
54
130
71
59
11
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.TransitionEvent (js_getPropertyName, getPropertyName, js_getElapsedTime, getElapsedTime, js_getPseudoElement, getPseudoElement, TransitionEvent, castToTransitionEvent, gTypeTransitionEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"propertyName\"]" js_getPropertyName :: JSRef TransitionEvent -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent.propertyName Mozilla TransitionEvent.propertyName documentation> getPropertyName :: (MonadIO m, FromJSString result) => TransitionEvent -> m result getPropertyName self = liftIO (fromJSString <$> (js_getPropertyName (unTransitionEvent self))) foreign import javascript unsafe "$1[\"elapsedTime\"]" js_getElapsedTime :: JSRef TransitionEvent -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent.elapsedTime Mozilla TransitionEvent.elapsedTime documentation> getElapsedTime :: (MonadIO m) => TransitionEvent -> m Double getElapsedTime self = liftIO (js_getElapsedTime (unTransitionEvent self)) foreign import javascript unsafe "$1[\"pseudoElement\"]" js_getPseudoElement :: JSRef TransitionEvent -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent.pseudoElement Mozilla TransitionEvent.pseudoElement documentation> getPseudoElement :: (MonadIO m, FromJSString result) => TransitionEvent -> m result getPseudoElement self = liftIO (fromJSString <$> (js_getPseudoElement (unTransitionEvent self)))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/TransitionEvent.hs
mit
2,405
18
11
313
534
320
214
38
1
module BST ( BST, bstLeft, bstRight, bstValue, empty, singleton, insert, fromList, toList ) where import Data.Foldable (foldl', toList) data BST a = Tip | Node (BST a) a (BST a) deriving (Show, Eq) -- This allows us to use the toList from Foldable. -- This may be seen as gratuitous for just one toList function, -- but keep in mind now this BST could use other Foldable functions too, -- not just toList. instance Foldable BST where foldMap _f Tip = mempty foldMap f (Node l v r) = foldMap f l `mappend` f v `mappend` foldMap f r bstValue :: BST a -> Maybe a bstValue Tip = Nothing bstValue (Node _ v _) = Just v bstLeft :: BST a -> Maybe (BST a) bstLeft Tip = Nothing bstLeft (Node l _ _) = Just l bstRight :: BST a -> Maybe (BST a) bstRight Tip = Nothing bstRight (Node _ _ r) = Just r empty :: BST a empty = Tip singleton :: a -> BST a singleton x = Node empty x empty insert :: Ord a => a -> BST a -> BST a insert x Tip = singleton x insert x (Node l v r) = if v >= x then Node (insert x l) v r else Node l v (insert x r) fromList :: Ord a => [a] -> BST a fromList = foldl' (flip insert) empty
exercism/xhaskell
exercises/practice/binary-search-tree/.meta/examples/success-standard/src/BST.hs
mit
1,165
0
8
302
476
245
231
30
2
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.Element (hasAttributes, hasAttributes_, getAttributeNames, getAttributeNames_, getAttribute, getAttribute_, getAttributeUnsafe, getAttributeUnchecked, getAttributeNS, getAttributeNS_, getAttributeNSUnsafe, getAttributeNSUnchecked, setAttribute, setAttributeNS, removeAttribute, removeAttributeNS, hasAttribute, hasAttribute_, hasAttributeNS, hasAttributeNS_, getAttributeNode, getAttributeNode_, getAttributeNodeUnsafe, getAttributeNodeUnchecked, getAttributeNodeNS, getAttributeNodeNS_, getAttributeNodeNSUnsafe, getAttributeNodeNSUnchecked, setAttributeNode, setAttributeNode_, setAttributeNodeUnsafe, setAttributeNodeUnchecked, setAttributeNodeNS, setAttributeNodeNS_, setAttributeNodeNSUnsafe, setAttributeNodeNSUnchecked, removeAttributeNode, removeAttributeNode_, attachShadow, attachShadow_, closest, closest_, closestUnsafe, closestUnchecked, matches, matches_, webkitMatchesSelector, webkitMatchesSelector_, getElementsByTagName, getElementsByTagName_, getElementsByTagNameNS, getElementsByTagNameNS_, getElementsByClassName, getElementsByClassName_, insertAdjacentElement, insertAdjacentElement_, insertAdjacentElementUnsafe, insertAdjacentElementUnchecked, insertAdjacentText, getClientRects, getClientRects_, getBoundingClientRect, getBoundingClientRect_, scrollIntoView, scrollOpt, scroll, scrollToOpt, scrollTo, scrollByOpt, scrollBy, insertAdjacentHTML, webkitRequestFullScreen, webkitRequestFullscreen, requestPointerLock, webkitGetRegionFlowRanges, webkitGetRegionFlowRanges_, scrollIntoViewIfNeeded, getNamespaceURI, getNamespaceURIUnsafe, getNamespaceURIUnchecked, getPrefix, getPrefixUnsafe, getPrefixUnchecked, getLocalName, getTagName, setId, getId, setClassName, getClassName, getClassList, setSlot, getSlot, getAttributes, getShadowRoot, getShadowRootUnsafe, getShadowRootUnchecked, setScrollTop, getScrollTop, setScrollLeft, getScrollLeft, getScrollWidth, getScrollHeight, getClientTop, getClientLeft, getClientWidth, getClientHeight, setInnerHTML, getInnerHTML, setOuterHTML, getOuterHTML, getWebkitRegionOverset, selectStart, gestureChange, gestureEnd, gestureStart, webKitAnimationEnd, webKitAnimationIteration, webKitAnimationStart, webKitTransitionEnd, webKitFullscreenChange, webKitFullscreenError, focusin, focusout, beforeload, webKitNeedKey, webKitPresentationModeChanged, webKitCurrentPlaybackTargetIsWirelessChanged, webKitPlaybackTargetAvailabilityChanged, Element(..), gTypeElement, IsElement, toElement) 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/Element.hasAttributes Mozilla Element.hasAttributes documentation> hasAttributes :: (MonadDOM m, IsElement self) => self -> m Bool hasAttributes self = liftDOM (((toElement self) ^. jsf "hasAttributes" ()) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.hasAttributes Mozilla Element.hasAttributes documentation> hasAttributes_ :: (MonadDOM m, IsElement self) => self -> m () hasAttributes_ self = liftDOM (void ((toElement self) ^. jsf "hasAttributes" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNames Mozilla Element.getAttributeNames documentation> getAttributeNames :: (MonadDOM m, IsElement self, FromJSString result) => self -> m [result] getAttributeNames self = liftDOM (((toElement self) ^. jsf "getAttributeNames" ()) >>= fromJSArrayUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNames Mozilla Element.getAttributeNames documentation> getAttributeNames_ :: (MonadDOM m, IsElement self) => self -> m () getAttributeNames_ self = liftDOM (void ((toElement self) ^. jsf "getAttributeNames" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute Mozilla Element.getAttribute documentation> getAttribute :: (MonadDOM m, IsElement self, ToJSString qualifiedName, FromJSString result) => self -> qualifiedName -> m (Maybe result) getAttribute self qualifiedName = liftDOM (((toElement self) ^. jsf "getAttribute" [toJSVal qualifiedName]) >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute Mozilla Element.getAttribute documentation> getAttribute_ :: (MonadDOM m, IsElement self, ToJSString qualifiedName) => self -> qualifiedName -> m () getAttribute_ self qualifiedName = liftDOM (void ((toElement self) ^. jsf "getAttribute" [toJSVal qualifiedName])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute Mozilla Element.getAttribute documentation> getAttributeUnsafe :: (MonadDOM m, IsElement self, ToJSString qualifiedName, HasCallStack, FromJSString result) => self -> qualifiedName -> m result getAttributeUnsafe self qualifiedName = liftDOM ((((toElement self) ^. jsf "getAttribute" [toJSVal qualifiedName]) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute Mozilla Element.getAttribute documentation> getAttributeUnchecked :: (MonadDOM m, IsElement self, ToJSString qualifiedName, FromJSString result) => self -> qualifiedName -> m result getAttributeUnchecked self qualifiedName = liftDOM (((toElement self) ^. jsf "getAttribute" [toJSVal qualifiedName]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNS Mozilla Element.getAttributeNS documentation> getAttributeNS :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName, FromJSString result) => self -> Maybe namespaceURI -> localName -> m (Maybe result) getAttributeNS self namespaceURI localName = liftDOM (((toElement self) ^. jsf "getAttributeNS" [toJSVal namespaceURI, toJSVal localName]) >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNS Mozilla Element.getAttributeNS documentation> getAttributeNS_ :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m () getAttributeNS_ self namespaceURI localName = liftDOM (void ((toElement self) ^. jsf "getAttributeNS" [toJSVal namespaceURI, toJSVal localName])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNS Mozilla Element.getAttributeNS documentation> getAttributeNSUnsafe :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName, HasCallStack, FromJSString result) => self -> Maybe namespaceURI -> localName -> m result getAttributeNSUnsafe self namespaceURI localName = liftDOM ((((toElement self) ^. jsf "getAttributeNS" [toJSVal namespaceURI, toJSVal localName]) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNS Mozilla Element.getAttributeNS documentation> getAttributeNSUnchecked :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName, FromJSString result) => self -> Maybe namespaceURI -> localName -> m result getAttributeNSUnchecked self namespaceURI localName = liftDOM (((toElement self) ^. jsf "getAttributeNS" [toJSVal namespaceURI, toJSVal localName]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttribute Mozilla Element.setAttribute documentation> setAttribute :: (MonadDOM m, IsElement self, ToJSString qualifiedName, ToJSString value) => self -> qualifiedName -> value -> m () setAttribute self qualifiedName value = liftDOM (void ((toElement self) ^. jsf "setAttribute" [toJSVal qualifiedName, toJSVal value])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttributeNS Mozilla Element.setAttributeNS documentation> setAttributeNS :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString qualifiedName, ToJSString value) => self -> Maybe namespaceURI -> qualifiedName -> value -> m () setAttributeNS self namespaceURI qualifiedName value = liftDOM (void ((toElement self) ^. jsf "setAttributeNS" [toJSVal namespaceURI, toJSVal qualifiedName, toJSVal value])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.removeAttribute Mozilla Element.removeAttribute documentation> removeAttribute :: (MonadDOM m, IsElement self, ToJSString qualifiedName) => self -> qualifiedName -> m () removeAttribute self qualifiedName = liftDOM (void ((toElement self) ^. jsf "removeAttribute" [toJSVal qualifiedName])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.removeAttributeNS Mozilla Element.removeAttributeNS documentation> removeAttributeNS :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m () removeAttributeNS self namespaceURI localName = liftDOM (void ((toElement self) ^. jsf "removeAttributeNS" [toJSVal namespaceURI, toJSVal localName])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.hasAttribute Mozilla Element.hasAttribute documentation> hasAttribute :: (MonadDOM m, IsElement self, ToJSString qualifiedName) => self -> qualifiedName -> m Bool hasAttribute self qualifiedName = liftDOM (((toElement self) ^. jsf "hasAttribute" [toJSVal qualifiedName]) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.hasAttribute Mozilla Element.hasAttribute documentation> hasAttribute_ :: (MonadDOM m, IsElement self, ToJSString qualifiedName) => self -> qualifiedName -> m () hasAttribute_ self qualifiedName = liftDOM (void ((toElement self) ^. jsf "hasAttribute" [toJSVal qualifiedName])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.hasAttributeNS Mozilla Element.hasAttributeNS documentation> hasAttributeNS :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m Bool hasAttributeNS self namespaceURI localName = liftDOM (((toElement self) ^. jsf "hasAttributeNS" [toJSVal namespaceURI, toJSVal localName]) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.hasAttributeNS Mozilla Element.hasAttributeNS documentation> hasAttributeNS_ :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m () hasAttributeNS_ self namespaceURI localName = liftDOM (void ((toElement self) ^. jsf "hasAttributeNS" [toJSVal namespaceURI, toJSVal localName])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNode Mozilla Element.getAttributeNode documentation> getAttributeNode :: (MonadDOM m, IsElement self, ToJSString qualifiedName) => self -> qualifiedName -> m (Maybe Attr) getAttributeNode self qualifiedName = liftDOM (((toElement self) ^. jsf "getAttributeNode" [toJSVal qualifiedName]) >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNode Mozilla Element.getAttributeNode documentation> getAttributeNode_ :: (MonadDOM m, IsElement self, ToJSString qualifiedName) => self -> qualifiedName -> m () getAttributeNode_ self qualifiedName = liftDOM (void ((toElement self) ^. jsf "getAttributeNode" [toJSVal qualifiedName])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNode Mozilla Element.getAttributeNode documentation> getAttributeNodeUnsafe :: (MonadDOM m, IsElement self, ToJSString qualifiedName, HasCallStack) => self -> qualifiedName -> m Attr getAttributeNodeUnsafe self qualifiedName = liftDOM ((((toElement self) ^. jsf "getAttributeNode" [toJSVal qualifiedName]) >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNode Mozilla Element.getAttributeNode documentation> getAttributeNodeUnchecked :: (MonadDOM m, IsElement self, ToJSString qualifiedName) => self -> qualifiedName -> m Attr getAttributeNodeUnchecked self qualifiedName = liftDOM (((toElement self) ^. jsf "getAttributeNode" [toJSVal qualifiedName]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNodeNS Mozilla Element.getAttributeNodeNS documentation> getAttributeNodeNS :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m (Maybe Attr) getAttributeNodeNS self namespaceURI localName = liftDOM (((toElement self) ^. jsf "getAttributeNodeNS" [toJSVal namespaceURI, toJSVal localName]) >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNodeNS Mozilla Element.getAttributeNodeNS documentation> getAttributeNodeNS_ :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m () getAttributeNodeNS_ self namespaceURI localName = liftDOM (void ((toElement self) ^. jsf "getAttributeNodeNS" [toJSVal namespaceURI, toJSVal localName])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNodeNS Mozilla Element.getAttributeNodeNS documentation> getAttributeNodeNSUnsafe :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName, HasCallStack) => self -> Maybe namespaceURI -> localName -> m Attr getAttributeNodeNSUnsafe self namespaceURI localName = liftDOM ((((toElement self) ^. jsf "getAttributeNodeNS" [toJSVal namespaceURI, toJSVal localName]) >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNodeNS Mozilla Element.getAttributeNodeNS documentation> getAttributeNodeNSUnchecked :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m Attr getAttributeNodeNSUnchecked self namespaceURI localName = liftDOM (((toElement self) ^. jsf "getAttributeNodeNS" [toJSVal namespaceURI, toJSVal localName]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttributeNode Mozilla Element.setAttributeNode documentation> setAttributeNode :: (MonadDOM m, IsElement self) => self -> Attr -> m (Maybe Attr) setAttributeNode self attr = liftDOM (((toElement self) ^. jsf "setAttributeNode" [toJSVal attr]) >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttributeNode Mozilla Element.setAttributeNode documentation> setAttributeNode_ :: (MonadDOM m, IsElement self) => self -> Attr -> m () setAttributeNode_ self attr = liftDOM (void ((toElement self) ^. jsf "setAttributeNode" [toJSVal attr])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttributeNode Mozilla Element.setAttributeNode documentation> setAttributeNodeUnsafe :: (MonadDOM m, IsElement self, HasCallStack) => self -> Attr -> m Attr setAttributeNodeUnsafe self attr = liftDOM ((((toElement self) ^. jsf "setAttributeNode" [toJSVal attr]) >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttributeNode Mozilla Element.setAttributeNode documentation> setAttributeNodeUnchecked :: (MonadDOM m, IsElement self) => self -> Attr -> m Attr setAttributeNodeUnchecked self attr = liftDOM (((toElement self) ^. jsf "setAttributeNode" [toJSVal attr]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttributeNodeNS Mozilla Element.setAttributeNodeNS documentation> setAttributeNodeNS :: (MonadDOM m, IsElement self) => self -> Attr -> m (Maybe Attr) setAttributeNodeNS self attr = liftDOM (((toElement self) ^. jsf "setAttributeNodeNS" [toJSVal attr]) >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttributeNodeNS Mozilla Element.setAttributeNodeNS documentation> setAttributeNodeNS_ :: (MonadDOM m, IsElement self) => self -> Attr -> m () setAttributeNodeNS_ self attr = liftDOM (void ((toElement self) ^. jsf "setAttributeNodeNS" [toJSVal attr])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttributeNodeNS Mozilla Element.setAttributeNodeNS documentation> setAttributeNodeNSUnsafe :: (MonadDOM m, IsElement self, HasCallStack) => self -> Attr -> m Attr setAttributeNodeNSUnsafe self attr = liftDOM ((((toElement self) ^. jsf "setAttributeNodeNS" [toJSVal attr]) >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttributeNodeNS Mozilla Element.setAttributeNodeNS documentation> setAttributeNodeNSUnchecked :: (MonadDOM m, IsElement self) => self -> Attr -> m Attr setAttributeNodeNSUnchecked self attr = liftDOM (((toElement self) ^. jsf "setAttributeNodeNS" [toJSVal attr]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.removeAttributeNode Mozilla Element.removeAttributeNode documentation> removeAttributeNode :: (MonadDOM m, IsElement self) => self -> Attr -> m Attr removeAttributeNode self attr = liftDOM (((toElement self) ^. jsf "removeAttributeNode" [toJSVal attr]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.removeAttributeNode Mozilla Element.removeAttributeNode documentation> removeAttributeNode_ :: (MonadDOM m, IsElement self) => self -> Attr -> m () removeAttributeNode_ self attr = liftDOM (void ((toElement self) ^. jsf "removeAttributeNode" [toJSVal attr])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.attachShadow Mozilla Element.attachShadow documentation> attachShadow :: (MonadDOM m, IsElement self) => self -> ShadowRootInit -> m ShadowRoot attachShadow self init = liftDOM (((toElement self) ^. jsf "attachShadow" [toJSVal init]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.attachShadow Mozilla Element.attachShadow documentation> attachShadow_ :: (MonadDOM m, IsElement self) => self -> ShadowRootInit -> m () attachShadow_ self init = liftDOM (void ((toElement self) ^. jsf "attachShadow" [toJSVal init])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.closest Mozilla Element.closest documentation> closest :: (MonadDOM m, IsElement self, ToJSString selectors) => self -> selectors -> m (Maybe Element) closest self selectors = liftDOM (((toElement self) ^. jsf "closest" [toJSVal selectors]) >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.closest Mozilla Element.closest documentation> closest_ :: (MonadDOM m, IsElement self, ToJSString selectors) => self -> selectors -> m () closest_ self selectors = liftDOM (void ((toElement self) ^. jsf "closest" [toJSVal selectors])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.closest Mozilla Element.closest documentation> closestUnsafe :: (MonadDOM m, IsElement self, ToJSString selectors, HasCallStack) => self -> selectors -> m Element closestUnsafe self selectors = liftDOM ((((toElement self) ^. jsf "closest" [toJSVal selectors]) >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.closest Mozilla Element.closest documentation> closestUnchecked :: (MonadDOM m, IsElement self, ToJSString selectors) => self -> selectors -> m Element closestUnchecked self selectors = liftDOM (((toElement self) ^. jsf "closest" [toJSVal selectors]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.matches Mozilla Element.matches documentation> matches :: (MonadDOM m, IsElement self, ToJSString selectors) => self -> selectors -> m Bool matches self selectors = liftDOM (((toElement self) ^. jsf "matches" [toJSVal selectors]) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.matches Mozilla Element.matches documentation> matches_ :: (MonadDOM m, IsElement self, ToJSString selectors) => self -> selectors -> m () matches_ self selectors = liftDOM (void ((toElement self) ^. jsf "matches" [toJSVal selectors])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.webkitMatchesSelector Mozilla Element.webkitMatchesSelector documentation> webkitMatchesSelector :: (MonadDOM m, IsElement self, ToJSString selectors) => self -> selectors -> m Bool webkitMatchesSelector self selectors = liftDOM (((toElement self) ^. jsf "webkitMatchesSelector" [toJSVal selectors]) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.webkitMatchesSelector Mozilla Element.webkitMatchesSelector documentation> webkitMatchesSelector_ :: (MonadDOM m, IsElement self, ToJSString selectors) => self -> selectors -> m () webkitMatchesSelector_ self selectors = liftDOM (void ((toElement self) ^. jsf "webkitMatchesSelector" [toJSVal selectors])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName Mozilla Element.getElementsByTagName documentation> getElementsByTagName :: (MonadDOM m, IsElement self, ToJSString qualifiedName) => self -> qualifiedName -> m HTMLCollection getElementsByTagName self qualifiedName = liftDOM (((toElement self) ^. jsf "getElementsByTagName" [toJSVal qualifiedName]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName Mozilla Element.getElementsByTagName documentation> getElementsByTagName_ :: (MonadDOM m, IsElement self, ToJSString qualifiedName) => self -> qualifiedName -> m () getElementsByTagName_ self qualifiedName = liftDOM (void ((toElement self) ^. jsf "getElementsByTagName" [toJSVal qualifiedName])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagNameNS Mozilla Element.getElementsByTagNameNS documentation> getElementsByTagNameNS :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m HTMLCollection getElementsByTagNameNS self namespaceURI localName = liftDOM (((toElement self) ^. jsf "getElementsByTagNameNS" [toJSVal namespaceURI, toJSVal localName]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagNameNS Mozilla Element.getElementsByTagNameNS documentation> getElementsByTagNameNS_ :: (MonadDOM m, IsElement self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m () getElementsByTagNameNS_ self namespaceURI localName = liftDOM (void ((toElement self) ^. jsf "getElementsByTagNameNS" [toJSVal namespaceURI, toJSVal localName])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByClassName Mozilla Element.getElementsByClassName documentation> getElementsByClassName :: (MonadDOM m, IsElement self, ToJSString name) => self -> name -> m HTMLCollection getElementsByClassName self name = liftDOM (((toElement self) ^. jsf "getElementsByClassName" [toJSVal name]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByClassName Mozilla Element.getElementsByClassName documentation> getElementsByClassName_ :: (MonadDOM m, IsElement self, ToJSString name) => self -> name -> m () getElementsByClassName_ self name = liftDOM (void ((toElement self) ^. jsf "getElementsByClassName" [toJSVal name])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentElement Mozilla Element.insertAdjacentElement documentation> insertAdjacentElement :: (MonadDOM m, IsElement self, ToJSString where', IsElement element) => self -> where' -> element -> m (Maybe Element) insertAdjacentElement self where' element = liftDOM (((toElement self) ^. jsf "insertAdjacentElement" [toJSVal where', toJSVal element]) >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentElement Mozilla Element.insertAdjacentElement documentation> insertAdjacentElement_ :: (MonadDOM m, IsElement self, ToJSString where', IsElement element) => self -> where' -> element -> m () insertAdjacentElement_ self where' element = liftDOM (void ((toElement self) ^. jsf "insertAdjacentElement" [toJSVal where', toJSVal element])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentElement Mozilla Element.insertAdjacentElement documentation> insertAdjacentElementUnsafe :: (MonadDOM m, IsElement self, ToJSString where', IsElement element, HasCallStack) => self -> where' -> element -> m Element insertAdjacentElementUnsafe self where' element = liftDOM ((((toElement self) ^. jsf "insertAdjacentElement" [toJSVal where', toJSVal element]) >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentElement Mozilla Element.insertAdjacentElement documentation> insertAdjacentElementUnchecked :: (MonadDOM m, IsElement self, ToJSString where', IsElement element) => self -> where' -> element -> m Element insertAdjacentElementUnchecked self where' element = liftDOM (((toElement self) ^. jsf "insertAdjacentElement" [toJSVal where', toJSVal element]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentText Mozilla Element.insertAdjacentText documentation> insertAdjacentText :: (MonadDOM m, IsElement self, ToJSString where', ToJSString data') => self -> where' -> data' -> m () insertAdjacentText self where' data' = liftDOM (void ((toElement self) ^. jsf "insertAdjacentText" [toJSVal where', toJSVal data'])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getClientRects Mozilla Element.getClientRects documentation> getClientRects :: (MonadDOM m, IsElement self) => self -> m [DOMRect] getClientRects self = liftDOM (((toElement self) ^. jsf "getClientRects" ()) >>= fromJSArrayUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getClientRects Mozilla Element.getClientRects documentation> getClientRects_ :: (MonadDOM m, IsElement self) => self -> m () getClientRects_ self = liftDOM (void ((toElement self) ^. jsf "getClientRects" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect Mozilla Element.getBoundingClientRect documentation> getBoundingClientRect :: (MonadDOM m, IsElement self) => self -> m DOMRect getBoundingClientRect self = liftDOM (((toElement self) ^. jsf "getBoundingClientRect" ()) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect Mozilla Element.getBoundingClientRect documentation> getBoundingClientRect_ :: (MonadDOM m, IsElement self) => self -> m () getBoundingClientRect_ self = liftDOM (void ((toElement self) ^. jsf "getBoundingClientRect" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView Mozilla Element.scrollIntoView documentation> scrollIntoView :: (MonadDOM m, IsElement self) => self -> Bool -> m () scrollIntoView self alignWithTop = liftDOM (void ((toElement self) ^. jsf "scrollIntoView" [toJSVal alignWithTop])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scroll Mozilla Element.scroll documentation> scrollOpt :: (MonadDOM m, IsElement self) => self -> Maybe ScrollToOptions -> m () scrollOpt self options = liftDOM (void ((toElement self) ^. jsf "scroll" [toJSVal options])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scroll Mozilla Element.scroll documentation> scroll :: (MonadDOM m, IsElement self) => self -> Double -> Double -> m () scroll self x y = liftDOM (void ((toElement self) ^. jsf "scroll" [toJSVal x, toJSVal y])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTo Mozilla Element.scrollTo documentation> scrollToOpt :: (MonadDOM m, IsElement self) => self -> Maybe ScrollToOptions -> m () scrollToOpt self options = liftDOM (void ((toElement self) ^. jsf "scrollTo" [toJSVal options])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTo Mozilla Element.scrollTo documentation> scrollTo :: (MonadDOM m, IsElement self) => self -> Double -> Double -> m () scrollTo self x y = liftDOM (void ((toElement self) ^. jsf "scrollTo" [toJSVal x, toJSVal y])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollBy Mozilla Element.scrollBy documentation> scrollByOpt :: (MonadDOM m, IsElement self) => self -> Maybe ScrollToOptions -> m () scrollByOpt self option = liftDOM (void ((toElement self) ^. jsf "scrollBy" [toJSVal option])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollBy Mozilla Element.scrollBy documentation> scrollBy :: (MonadDOM m, IsElement self) => self -> Double -> Double -> m () scrollBy self x y = liftDOM (void ((toElement self) ^. jsf "scrollBy" [toJSVal x, toJSVal y])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML Mozilla Element.insertAdjacentHTML documentation> insertAdjacentHTML :: (MonadDOM m, IsElement self, ToJSString position, ToJSString text) => self -> position -> text -> m () insertAdjacentHTML self position text = liftDOM (void ((toElement self) ^. jsf "insertAdjacentHTML" [toJSVal position, toJSVal text])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.webkitRequestFullScreen Mozilla Element.webkitRequestFullScreen documentation> webkitRequestFullScreen :: (MonadDOM m, IsElement self) => self -> m () webkitRequestFullScreen self = liftDOM (void ((toElement self) ^. jsf "webkitRequestFullScreen" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.webkitRequestFullscreen Mozilla Element.webkitRequestFullscreen documentation> webkitRequestFullscreen :: (MonadDOM m, IsElement self) => self -> m () webkitRequestFullscreen self = liftDOM (void ((toElement self) ^. jsf "webkitRequestFullscreen" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.requestPointerLock Mozilla Element.requestPointerLock documentation> requestPointerLock :: (MonadDOM m, IsElement self) => self -> m () requestPointerLock self = liftDOM (void ((toElement self) ^. jsf "requestPointerLock" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.webkitGetRegionFlowRanges Mozilla Element.webkitGetRegionFlowRanges documentation> webkitGetRegionFlowRanges :: (MonadDOM m, IsElement self) => self -> m (Maybe [Range]) webkitGetRegionFlowRanges self = liftDOM (((toElement self) ^. jsf "webkitGetRegionFlowRanges" ()) >>= maybeNullOrUndefined' fromJSArrayUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.webkitGetRegionFlowRanges Mozilla Element.webkitGetRegionFlowRanges documentation> webkitGetRegionFlowRanges_ :: (MonadDOM m, IsElement self) => self -> m () webkitGetRegionFlowRanges_ self = liftDOM (void ((toElement self) ^. jsf "webkitGetRegionFlowRanges" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoViewIfNeeded Mozilla Element.scrollIntoViewIfNeeded documentation> scrollIntoViewIfNeeded :: (MonadDOM m, IsElement self) => self -> Bool -> m () scrollIntoViewIfNeeded self centerIfNeeded = liftDOM (void ((toElement self) ^. jsf "scrollIntoViewIfNeeded" [toJSVal centerIfNeeded])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.namespaceURI Mozilla Element.namespaceURI documentation> getNamespaceURI :: (MonadDOM m, IsElement self, FromJSString result) => self -> m (Maybe result) getNamespaceURI self = liftDOM (((toElement self) ^. js "namespaceURI") >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.namespaceURI Mozilla Element.namespaceURI documentation> getNamespaceURIUnsafe :: (MonadDOM m, IsElement self, HasCallStack, FromJSString result) => self -> m result getNamespaceURIUnsafe self = liftDOM ((((toElement self) ^. js "namespaceURI") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.namespaceURI Mozilla Element.namespaceURI documentation> getNamespaceURIUnchecked :: (MonadDOM m, IsElement self, FromJSString result) => self -> m result getNamespaceURIUnchecked self = liftDOM (((toElement self) ^. js "namespaceURI") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.prefix Mozilla Element.prefix documentation> getPrefix :: (MonadDOM m, IsElement self, FromJSString result) => self -> m (Maybe result) getPrefix self = liftDOM (((toElement self) ^. js "prefix") >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.prefix Mozilla Element.prefix documentation> getPrefixUnsafe :: (MonadDOM m, IsElement self, HasCallStack, FromJSString result) => self -> m result getPrefixUnsafe self = liftDOM ((((toElement self) ^. js "prefix") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.prefix Mozilla Element.prefix documentation> getPrefixUnchecked :: (MonadDOM m, IsElement self, FromJSString result) => self -> m result getPrefixUnchecked self = liftDOM (((toElement self) ^. js "prefix") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.localName Mozilla Element.localName documentation> getLocalName :: (MonadDOM m, IsElement self, FromJSString result) => self -> m result getLocalName self = liftDOM (((toElement self) ^. js "localName") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.tagName Mozilla Element.tagName documentation> getTagName :: (MonadDOM m, IsElement self, FromJSString result) => self -> m result getTagName self = liftDOM (((toElement self) ^. js "tagName") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.id Mozilla Element.id documentation> setId :: (MonadDOM m, IsElement self, ToJSString val) => self -> val -> m () setId self val = liftDOM ((toElement self) ^. jss "id" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.id Mozilla Element.id documentation> getId :: (MonadDOM m, IsElement self, FromJSString result) => self -> m result getId self = liftDOM (((toElement self) ^. js "id") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.className Mozilla Element.className documentation> setClassName :: (MonadDOM m, IsElement self, ToJSString val) => self -> val -> m () setClassName self val = liftDOM ((toElement self) ^. jss "className" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.className Mozilla Element.className documentation> getClassName :: (MonadDOM m, IsElement self, FromJSString result) => self -> m result getClassName self = liftDOM (((toElement self) ^. js "className") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.classList Mozilla Element.classList documentation> getClassList :: (MonadDOM m, IsElement self) => self -> m DOMTokenList getClassList self = liftDOM (((toElement self) ^. js "classList") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.slot Mozilla Element.slot documentation> setSlot :: (MonadDOM m, IsElement self, ToJSString val) => self -> val -> m () setSlot self val = liftDOM ((toElement self) ^. jss "slot" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.slot Mozilla Element.slot documentation> getSlot :: (MonadDOM m, IsElement self, FromJSString result) => self -> m result getSlot self = liftDOM (((toElement self) ^. js "slot") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.attributes Mozilla Element.attributes documentation> getAttributes :: (MonadDOM m, IsElement self) => self -> m NamedNodeMap getAttributes self = liftDOM (((toElement self) ^. js "attributes") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.shadowRoot Mozilla Element.shadowRoot documentation> getShadowRoot :: (MonadDOM m, IsElement self) => self -> m (Maybe ShadowRoot) getShadowRoot self = liftDOM (((toElement self) ^. js "shadowRoot") >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.shadowRoot Mozilla Element.shadowRoot documentation> getShadowRootUnsafe :: (MonadDOM m, IsElement self, HasCallStack) => self -> m ShadowRoot getShadowRootUnsafe self = liftDOM ((((toElement self) ^. js "shadowRoot") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.shadowRoot Mozilla Element.shadowRoot documentation> getShadowRootUnchecked :: (MonadDOM m, IsElement self) => self -> m ShadowRoot getShadowRootUnchecked self = liftDOM (((toElement self) ^. js "shadowRoot") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop Mozilla Element.scrollTop documentation> setScrollTop :: (MonadDOM m, IsElement self) => self -> Int -> m () setScrollTop self val = liftDOM ((toElement self) ^. jss "scrollTop" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop Mozilla Element.scrollTop documentation> getScrollTop :: (MonadDOM m, IsElement self) => self -> m Int getScrollTop self = liftDOM (round <$> (((toElement self) ^. js "scrollTop") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollLeft Mozilla Element.scrollLeft documentation> setScrollLeft :: (MonadDOM m, IsElement self) => self -> Int -> m () setScrollLeft self val = liftDOM ((toElement self) ^. jss "scrollLeft" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollLeft Mozilla Element.scrollLeft documentation> getScrollLeft :: (MonadDOM m, IsElement self) => self -> m Int getScrollLeft self = liftDOM (round <$> (((toElement self) ^. js "scrollLeft") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollWidth Mozilla Element.scrollWidth documentation> getScrollWidth :: (MonadDOM m, IsElement self) => self -> m Int getScrollWidth self = liftDOM (round <$> (((toElement self) ^. js "scrollWidth") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollHeight Mozilla Element.scrollHeight documentation> getScrollHeight :: (MonadDOM m, IsElement self) => self -> m Int getScrollHeight self = liftDOM (round <$> (((toElement self) ^. js "scrollHeight") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.clientTop Mozilla Element.clientTop documentation> getClientTop :: (MonadDOM m, IsElement self) => self -> m Double getClientTop self = liftDOM (((toElement self) ^. js "clientTop") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.clientLeft Mozilla Element.clientLeft documentation> getClientLeft :: (MonadDOM m, IsElement self) => self -> m Double getClientLeft self = liftDOM (((toElement self) ^. js "clientLeft") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.clientWidth Mozilla Element.clientWidth documentation> getClientWidth :: (MonadDOM m, IsElement self) => self -> m Double getClientWidth self = liftDOM (((toElement self) ^. js "clientWidth") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.clientHeight Mozilla Element.clientHeight documentation> getClientHeight :: (MonadDOM m, IsElement self) => self -> m Double getClientHeight self = liftDOM (((toElement self) ^. js "clientHeight") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML Mozilla Element.innerHTML documentation> setInnerHTML :: (MonadDOM m, IsElement self, ToJSString val) => self -> val -> m () setInnerHTML self val = liftDOM ((toElement self) ^. jss "innerHTML" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML Mozilla Element.innerHTML documentation> getInnerHTML :: (MonadDOM m, IsElement self, FromJSString result) => self -> m result getInnerHTML self = liftDOM (((toElement self) ^. js "innerHTML") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.outerHTML Mozilla Element.outerHTML documentation> setOuterHTML :: (MonadDOM m, IsElement self, ToJSString val) => self -> val -> m () setOuterHTML self val = liftDOM ((toElement self) ^. jss "outerHTML" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.outerHTML Mozilla Element.outerHTML documentation> getOuterHTML :: (MonadDOM m, IsElement self, FromJSString result) => self -> m result getOuterHTML self = liftDOM (((toElement self) ^. js "outerHTML") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.webkitRegionOverset Mozilla Element.webkitRegionOverset documentation> getWebkitRegionOverset :: (MonadDOM m, IsElement self, FromJSString result) => self -> m result getWebkitRegionOverset self = liftDOM (((toElement self) ^. js "webkitRegionOverset") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onselectstart Mozilla Element.onselectstart documentation> selectStart :: (IsElement self, IsEventTarget self) => EventName self Event selectStart = unsafeEventName (toJSString "selectstart") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.ongesturechange Mozilla Element.ongesturechange documentation> gestureChange :: (IsElement self, IsEventTarget self) => EventName self UIEvent gestureChange = unsafeEventName (toJSString "gesturechange") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.ongestureend Mozilla Element.ongestureend documentation> gestureEnd :: (IsElement self, IsEventTarget self) => EventName self UIEvent gestureEnd = unsafeEventName (toJSString "gestureend") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.ongesturestart Mozilla Element.ongesturestart documentation> gestureStart :: (IsElement self, IsEventTarget self) => EventName self UIEvent gestureStart = unsafeEventName (toJSString "gesturestart") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onwebkitanimationend Mozilla Element.onwebkitanimationend documentation> webKitAnimationEnd :: (IsElement self, IsEventTarget self) => EventName self AnimationEvent webKitAnimationEnd = unsafeEventName (toJSString "webkitanimationend") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onwebkitanimationiteration Mozilla Element.onwebkitanimationiteration documentation> webKitAnimationIteration :: (IsElement self, IsEventTarget self) => EventName self AnimationEvent webKitAnimationIteration = unsafeEventName (toJSString "webkitanimationiteration") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onwebkitanimationstart Mozilla Element.onwebkitanimationstart documentation> webKitAnimationStart :: (IsElement self, IsEventTarget self) => EventName self AnimationEvent webKitAnimationStart = unsafeEventName (toJSString "webkitanimationstart") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onwebkittransitionend Mozilla Element.onwebkittransitionend documentation> webKitTransitionEnd :: (IsElement self, IsEventTarget self) => EventName self TransitionEvent webKitTransitionEnd = unsafeEventName (toJSString "webkittransitionend") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onwebkitfullscreenchange Mozilla Element.onwebkitfullscreenchange documentation> webKitFullscreenChange :: (IsElement self, IsEventTarget self) => EventName self Event webKitFullscreenChange = unsafeEventName (toJSString "webkitfullscreenchange") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onwebkitfullscreenerror Mozilla Element.onwebkitfullscreenerror documentation> webKitFullscreenError :: (IsElement self, IsEventTarget self) => EventName self Event webKitFullscreenError = unsafeEventName (toJSString "webkitfullscreenerror") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onfocusin Mozilla Element.onfocusin documentation> focusin :: (IsElement self, IsEventTarget self) => EventName self onfocusin focusin = unsafeEventName (toJSString "focusin") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onfocusout Mozilla Element.onfocusout documentation> focusout :: (IsElement self, IsEventTarget self) => EventName self onfocusout focusout = unsafeEventName (toJSString "focusout") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onbeforeload Mozilla Element.onbeforeload documentation> beforeload :: (IsElement self, IsEventTarget self) => EventName self onbeforeload beforeload = unsafeEventName (toJSString "beforeload") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onwebkitneedkey Mozilla Element.onwebkitneedkey documentation> webKitNeedKey :: (IsElement self, IsEventTarget self) => EventName self Event webKitNeedKey = unsafeEventName (toJSString "webkitneedkey") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onwebkitpresentationmodechanged Mozilla Element.onwebkitpresentationmodechanged documentation> webKitPresentationModeChanged :: (IsElement self, IsEventTarget self) => EventName self Event webKitPresentationModeChanged = unsafeEventName (toJSString "webkitpresentationmodechanged") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onwebkitcurrentplaybacktargetiswirelesschanged Mozilla Element.onwebkitcurrentplaybacktargetiswirelesschanged documentation> webKitCurrentPlaybackTargetIsWirelessChanged :: (IsElement self, IsEventTarget self) => EventName self Event webKitCurrentPlaybackTargetIsWirelessChanged = unsafeEventName (toJSString "webkitcurrentplaybacktargetiswirelesschanged") -- | <https://developer.mozilla.org/en-US/docs/Web/API/Element.onwebkitplaybacktargetavailabilitychanged Mozilla Element.onwebkitplaybacktargetavailabilitychanged documentation> webKitPlaybackTargetAvailabilityChanged :: (IsElement self, IsEventTarget self) => EventName self Event webKitPlaybackTargetAvailabilityChanged = unsafeEventName (toJSString "webkitplaybacktargetavailabilitychanged")
ghcjs/jsaddle-dom
src/JSDOM/Generated/Element.hs
mit
52,968
0
14
10,857
10,573
5,501
5,072
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Y2017.M10.D09.Exercise where {-- So, 'yesterday' we saved our data out as JSON, read it back in, and then visualized it. The data was the NYT article archive, and, doing that, we saw we had a lot of data to visualize. Today, let's par that down a smidge. --} import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as BL import Data.Set (Set) -- below imports available via 1HaskellADay git repository import Data.Hierarchy -- hint: use this to visualize your results import Y2017.M10.D04.Exercise import Y2017.M10.D05.Exercise -- From the grouping that you formed before (so, you have to reformulate that -- grouping again, today), par it down to the top 5 topics, that is to say: -- the topics that have the most articles topicality :: Grouping -> [(Topic, Int)] topicality groups = undefined -- topicality gives us the number of articles of that topic -- Now that you have topicality, reform the group to contain only those -- top 5 topics (and no other topics) reformGrouping :: Set Topic -> Grouping -> Grouping reformGrouping hotTopics groups = undefined -- Great! Now let's visualize that subset. What do you get? Tweet your results {-- BONUS ----------------------------------------------------------------- * What are the topics of the NYT archive slice that have 10 or more articles? * How many topic make the cut of ten or more articles? * Chart those topics --} top10sTopics :: Grouping -> [(Topic, Int)] top10sTopics grps = undefined
geophf/1HaskellADay
exercises/HAD/Y2017/M10/D09/Exercise.hs
mit
1,521
0
7
264
142
91
51
14
1
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, CPP #-} module Melchior.Dom.Html ( Renderable , Html , Fragment #ifdef __UHC_TARGET_JS__ , Text , JDiv , JSpan #endif , render , addClassTo , addAttribute , (<+>) , (+>) , (<+) ) where import Melchior.Data.String (JSString, stringToJSString) import Melchior.Dom.Internal.Fragments class Renderable a where render :: a -> Html instance Renderable Fragment where render f = stringToJSString $ show f instance Renderable (Int, Int) where render x = stringToJSString $ "<span>"++(show $ fst x)++","++(show $ snd x)++"</span>" instance Renderable Int where render i = stringToJSString $ "<span>"++(show i)++"</span>" instance Renderable Integer where render i = stringToJSString $ "<span>"++(show i)++"</span>" instance Renderable JSString where render s = s instance Renderable String where render = stringToJSString instance (Renderable a, Show a) => Renderable [a] where render xs = stringToJSString $ join $ map show xs (<+>) :: Html -> Html -> Html a <+> b = primAppendHtml a b (+>) :: String -> Html -> Html a +> b = primAppendHtml (stringToJSString a) b (<+) :: Html -> String -> Html a <+ b = primAppendHtml a (stringToJSString b) join [] = "" join (x:[]) = x join (x:xs) = x++","++(join xs) #ifdef __UHC_TARGET_JS__ foreign import js "Html.append(%1, %2)" primAppendHtml :: Html -> Html -> Html #else primAppendHtml = undefined #endif
kjgorman/melchior
Melchior/Dom/Html.hs
mit
1,456
1
12
275
495
270
225
39
1