code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module DL3055 (tests) where import qualified Data.Map as Map import qualified Hadolint.Process import qualified Hadolint.Rule as Rule import Helpers import Test.Hspec tests :: SpecWith () tests = do let ?rulesConfig = Hadolint.Process.RulesConfig [] (Map.fromList [("githash", Rule.GitHash)]) False describe "DL3055 - Label `<label>` is not a valid git hash." $ do it "not ok with label not containing git hash" $ do ruleCatches "DL3055" "LABEL githash=\"not-git-hash\"" onBuildRuleCatches "DL3055" "LABEL githash=\"not-git-hash\"" it "ok with label containing short git hash" $ do ruleCatchesNot "DL3055" "LABEL githash=\"2dbfae9\"" onBuildRuleCatchesNot "DL3055" "LABEL githash=\"2dbfae9\"" it "ok with label containing long git hash" $ do ruleCatchesNot "DL3055" "LABEL githash=\"43c572f1272b6b3171dd1db9e41b7027128ce080\"" onBuildRuleCatchesNot "DL3055" "LABEL githash=\"43c572f1272b6b3171dd1db9e41b7027128ce080\"" it "ok with other label not containing git hash" $ do ruleCatchesNot "DL3055" "LABEL other=\"foo\"" onBuildRuleCatchesNot "DL3055" "LABEL other=\"bar\""
lukasmartinelli/hadolint
test/DL3055.hs
gpl-3.0
1,143
0
15
195
208
100
108
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Container.Projects.Locations.Clusters.SetLocations -- 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) -- -- Sets the locations for a specific cluster. Deprecated. Use -- [projects.locations.clusters.update](https:\/\/cloud.google.com\/kubernetes-engine\/docs\/reference\/rest\/v1\/projects.locations.clusters\/update) -- instead. -- -- /See:/ <https://cloud.google.com/container-engine/ Kubernetes Engine API Reference> for @container.projects.locations.clusters.setLocations@. module Network.Google.Resource.Container.Projects.Locations.Clusters.SetLocations ( -- * REST Resource ProjectsLocationsClustersSetLocationsResource -- * Creating a Request , projectsLocationsClustersSetLocations , ProjectsLocationsClustersSetLocations -- * Request Lenses , plcslsXgafv , plcslsUploadProtocol , plcslsAccessToken , plcslsUploadType , plcslsPayload , plcslsName , plcslsCallback ) where import Network.Google.Container.Types import Network.Google.Prelude -- | A resource alias for @container.projects.locations.clusters.setLocations@ method which the -- 'ProjectsLocationsClustersSetLocations' request conforms to. type ProjectsLocationsClustersSetLocationsResource = "v1" :> CaptureMode "name" "setLocations" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SetLocationsRequest :> Post '[JSON] Operation -- | Sets the locations for a specific cluster. Deprecated. Use -- [projects.locations.clusters.update](https:\/\/cloud.google.com\/kubernetes-engine\/docs\/reference\/rest\/v1\/projects.locations.clusters\/update) -- instead. -- -- /See:/ 'projectsLocationsClustersSetLocations' smart constructor. data ProjectsLocationsClustersSetLocations = ProjectsLocationsClustersSetLocations' { _plcslsXgafv :: !(Maybe Xgafv) , _plcslsUploadProtocol :: !(Maybe Text) , _plcslsAccessToken :: !(Maybe Text) , _plcslsUploadType :: !(Maybe Text) , _plcslsPayload :: !SetLocationsRequest , _plcslsName :: !Text , _plcslsCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsClustersSetLocations' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plcslsXgafv' -- -- * 'plcslsUploadProtocol' -- -- * 'plcslsAccessToken' -- -- * 'plcslsUploadType' -- -- * 'plcslsPayload' -- -- * 'plcslsName' -- -- * 'plcslsCallback' projectsLocationsClustersSetLocations :: SetLocationsRequest -- ^ 'plcslsPayload' -> Text -- ^ 'plcslsName' -> ProjectsLocationsClustersSetLocations projectsLocationsClustersSetLocations pPlcslsPayload_ pPlcslsName_ = ProjectsLocationsClustersSetLocations' { _plcslsXgafv = Nothing , _plcslsUploadProtocol = Nothing , _plcslsAccessToken = Nothing , _plcslsUploadType = Nothing , _plcslsPayload = pPlcslsPayload_ , _plcslsName = pPlcslsName_ , _plcslsCallback = Nothing } -- | V1 error format. plcslsXgafv :: Lens' ProjectsLocationsClustersSetLocations (Maybe Xgafv) plcslsXgafv = lens _plcslsXgafv (\ s a -> s{_plcslsXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plcslsUploadProtocol :: Lens' ProjectsLocationsClustersSetLocations (Maybe Text) plcslsUploadProtocol = lens _plcslsUploadProtocol (\ s a -> s{_plcslsUploadProtocol = a}) -- | OAuth access token. plcslsAccessToken :: Lens' ProjectsLocationsClustersSetLocations (Maybe Text) plcslsAccessToken = lens _plcslsAccessToken (\ s a -> s{_plcslsAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plcslsUploadType :: Lens' ProjectsLocationsClustersSetLocations (Maybe Text) plcslsUploadType = lens _plcslsUploadType (\ s a -> s{_plcslsUploadType = a}) -- | Multipart request metadata. plcslsPayload :: Lens' ProjectsLocationsClustersSetLocations SetLocationsRequest plcslsPayload = lens _plcslsPayload (\ s a -> s{_plcslsPayload = a}) -- | The name (project, location, cluster) of the cluster to set locations. -- Specified in the format \`projects\/*\/locations\/*\/clusters\/*\`. plcslsName :: Lens' ProjectsLocationsClustersSetLocations Text plcslsName = lens _plcslsName (\ s a -> s{_plcslsName = a}) -- | JSONP plcslsCallback :: Lens' ProjectsLocationsClustersSetLocations (Maybe Text) plcslsCallback = lens _plcslsCallback (\ s a -> s{_plcslsCallback = a}) instance GoogleRequest ProjectsLocationsClustersSetLocations where type Rs ProjectsLocationsClustersSetLocations = Operation type Scopes ProjectsLocationsClustersSetLocations = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsClustersSetLocations'{..} = go _plcslsName _plcslsXgafv _plcslsUploadProtocol _plcslsAccessToken _plcslsUploadType _plcslsCallback (Just AltJSON) _plcslsPayload containerService where go = buildClient (Proxy :: Proxy ProjectsLocationsClustersSetLocationsResource) mempty
brendanhay/gogol
gogol-container/gen/Network/Google/Resource/Container/Projects/Locations/Clusters/SetLocations.hs
mpl-2.0
6,230
0
16
1,257
783
459
324
120
1
-- This file is part of purebred -- Copyright (C) 2018-2021 Róman Joost and Fraser Tweedale -- -- purebred is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. {-# OPTIONS_HADDOCK hide #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Purebred.UI.Status.Main where import Brick.BChan (BChan, writeBChan) import Brick.Types (Widget, Padding(..)) import Brick.Focus (focusGetCurrent, focusRingLength) import Brick.Widgets.Core (hBox, txt, str, withAttr, (<+>), strWrap, emptyWidget, padRight, padLeft, padLeftRight) import Brick.Widgets.Center (hCenter) import qualified Brick.Widgets.List as L import qualified Brick.Widgets.Edit as E import qualified Brick.Widgets.FileBrowser as FB import Control.Monad.Except (runExceptT) import Control.Monad (void) import Control.Lens import Control.Concurrent (forkIO, threadDelay) import Data.Text (Text) import Data.Text.Zipper (cursorPosition) import Purebred.UI.Draw.Main (fillLine) import Purebred.UI.Utils (titleize) import Purebred.UI.Views (focusedViewWidget, focusedViewName) import Purebred.Types import Purebred.Config ( statusbarAttr, statusbarErrorAttr, statusbarInfoAttr, statusbarWarningAttr ) import qualified Purebred.Storage.Notmuch as Notmuch import Purebred.UI.Widgets (editEditorL) checkForNewMail :: BChan PurebredEvent -> FilePath -> Text -> Delay -> IO () checkForNewMail chan dbpath query delay = do r <- runExceptT (Notmuch.countThreads query dbpath) case r of Left _ -> pure () Right n -> notify n *> rescheduleMailcheck chan dbpath query delay where notify = writeBChan chan . NotifyNewMailArrived rescheduleMailcheck :: BChan PurebredEvent -> FilePath -> Text -> Delay -> IO () rescheduleMailcheck chan dbpath query delay = void $ forkIO (threadDelay (toMilisecond delay) *> checkForNewMail chan dbpath query delay) where toMilisecond (Seconds x) = x * 1000000 toMilisecond (Minutes x) = x * 60 * 1000000 data StatusbarContext a = ListContext a | EditorContext a | ErrorContext a deriving (Show) renderUserMessage :: UserMessage -> Widget Name renderUserMessage (UserMessage _ (Warning t)) = withAttr statusbarWarningAttr $ hCenter $ txt t renderUserMessage (UserMessage _ (Info t)) = withAttr statusbarInfoAttr $ hCenter $ txt t renderUserMessage (UserMessage _ (Error e)) = withAttr statusbarErrorAttr $ hCenter $ strWrap (show e) statusbar :: AppState -> Widget Name statusbar s = case view asUserMessage s of Just m -> renderUserMessage m Nothing -> case focusedViewWidget s of SearchThreadsEditor -> renderStatusbar (view (asThreadsView . miSearchThreadsEditor . editEditorL) s) s ManageMailTagsEditor -> renderStatusbar (view (asThreadsView . miMailTagsEditor) s) s ManageThreadTagsEditor -> renderStatusbar (view (asThreadsView . miThreadTagsEditor) s) s MailAttachmentOpenWithEditor -> renderStatusbar (view (asMailView . mvOpenCommand) s) s MailAttachmentPipeToEditor -> renderStatusbar (view (asMailView . mvPipeCommand) s) s ScrollingMailViewFindWordEditor -> renderStatusbar (view (asMailView . mvFindWordEditor) s) s SaveToDiskPathEditor -> renderStatusbar (view (asMailView . mvSaveToDiskPath) s) s ListOfThreads -> renderStatusbar (view (asThreadsView . miThreads) s) s ListOfMails -> renderStatusbar (view (asThreadsView . miMails) s) s ScrollingMailView -> renderStatusbar (view (asThreadsView . miMails) s) s ComposeListOfAttachments -> renderStatusbar (views (asCompose . cAttachments) lwl s) s MailListOfAttachments -> renderStatusbar (views (asMailView . mvAttachments) lwl s) s ListOfFiles -> renderStatusbar (view (asFileBrowser . fbEntries) s) s ComposeTo -> renderStatusbar (view (asCompose . cTo . editEditorL) s) s ComposeFrom -> renderStatusbar (view (asCompose . cFrom . editEditorL) s) s ComposeSubject -> renderStatusbar (view (asCompose . cSubject . editEditorL) s) s _ -> withAttr statusbarAttr $ str "Purebred: " <+> fillLine class WithContext a where renderContext :: AppState -> a -> Widget Name instance WithContext (ListWithLength t e) where renderContext _ = currentItemW instance WithContext (E.Editor Text Name) where renderContext _ = str . show . cursorPosition . view E.editContentsL instance WithContext (FB.FileBrowser Name) where renderContext _ _ = emptyWidget renderStatusbar :: WithContext w => w -> AppState -> Widget Name renderStatusbar w s = withAttr statusbarAttr $ hBox [ str "Purebred: " , renderContext s w , padLeftRight 1 (str "[") , renderNewMailIndicator s , renderMatches s , padLeft (Pad 1) (str "]") , fillLine , txt ( titleize (focusedViewName s) <> "-" <> titleize (focusedViewWidget s) <> " " ) ] renderMatches :: AppState -> Widget n renderMatches s = let showCount = view (non "0") $ preview (asMailView . mvScrollSteps . to (show . focusRingLength)) s currentItem = view (non "0") $ preview (asMailView . mvScrollSteps . to focusGetCurrent . _Just . stNumber . to show) s in if view (asMailView . mvBody . to matchCount) s > 0 then str (currentItem <> " of " <> showCount <> " matches") else emptyWidget renderNewMailIndicator :: AppState -> Widget n renderNewMailIndicator s = let newMailCount = view (asThreadsView . miNewMail) s indicator = str $ "New: " <> show newMailCount in padRight (Pad 1) indicator currentItemW :: ListWithLength t e -> Widget n currentItemW (ListWithLength l len) = str $ maybe "No items" (\i -> "Item " <> show (i + 1) <> " of " <> maybe "?" show len) (view L.listSelectedL l) -- | Convenience function for promoting a brick list to a 'ListWithLength', -- using 'length' on the underlying list. lwl :: (Foldable t) => L.GenericList Name t e -> ListWithLength t e lwl l = ListWithLength l (views L.listElementsL (Just . length) l)
purebred-mua/purebred
src/Purebred/UI/Status/Main.hs
agpl-3.0
6,755
0
16
1,380
1,853
965
888
115
18
module Libaddutil.Entity where import Libaddutil.Vector class Eq a => Entital a where getEntity :: a -> Entity data Entity = Entity { location :: Vector3 , velocity :: Vector3 , acceleration :: Vector3 } deriving (Eq, Show, Read) setEntityLocation :: Entity -> Vector3 -> Entity setEntityLocation e l = e{location = l} nullEntity :: Entity nullEntity = Entity nullVector3 nullVector3 nullVector3 stopEntity :: Entity -> Entity stopEntity e = e{velocity=(0,0,0),acceleration=(0,0,0)} updateEntity :: Float -> Entity -> Entity updateEntity i e = e{location=nl,velocity=nv} where nl = (location e) `addVector3` ((velocity e) `scaleVector3` i) nv = (velocity e) `addVector3` ((acceleration e) `scaleVector3` i) updateEntityMax :: Float -> Float -> Entity -> Entity updateEntityMax mx i e | mx <= 0 = updateEntity i e | otherwise = updateEntity i ne where ne = e{velocity = clampVector 0 mx (velocity e)} setEntityAcceleration :: Entity -> Vector3 -> Entity setEntityAcceleration e a = e{acceleration = a} setEntityVelocity :: Entity -> Vector3 -> Entity setEntityVelocity e v = e{velocity = v} vectorFromTo :: Entity -> Entity -> Vector3 vectorFromTo e1 e2 = (location e2) `diffVector3` (location e1)
anttisalonen/freekick
haskell/addutil/Libaddutil/Entity.hs
agpl-3.0
1,331
0
11
316
467
258
209
28
1
{-# OPTIONS_GHC -F -pgmF ./scripts/local-htfpp #-} module Repeat (repeatMain) where import Test.Framework import Data.IORef import System.IO.Unsafe globalBool :: IORef Bool globalBool = unsafePerformIO (newIORef True) {-# NOINLINE globalBool #-} readGlobalBool :: IO Bool readGlobalBool = do b <- readIORef globalBool writeIORef globalBool False return b test_globalMVarIsTrue = do b <- readGlobalBool assertEqual b True repeatMain args = htfMainWithArgs args htf_thisModulesTests
skogsbaer/HTF
tests/real-bbt/Repeat.hs
lgpl-2.1
516
0
8
95
119
60
59
17
1
module HEP.Jet.FastJet.Class.Selector where
wavewave/HFastJet
oldsrc/HEP/Jet/FastJet/Class/Selector.hs
lgpl-2.1
45
0
3
4
9
7
2
1
0
module Lupo.Site ( lupoInit ) where import qualified Database.HDBC as DB import qualified Database.HDBC.Sqlite3 as Sqlite3 import qualified Heist.Interpreted as H import Prelude hiding (filter) import Snap import qualified Snap.Snaplet.Heist as H import qualified Snap.Snaplet.Session.Backends.CookieSession as Cookie import Snap.Util.FileServe import qualified Lupo.AdminHandler as Admin import Lupo.Application import qualified Lupo.Backends.Auth as A import qualified Lupo.Backends.Entry as E import qualified Lupo.Backends.Notice as N import qualified Lupo.Backends.URLMapper as U import qualified Lupo.Backends.View as V import Lupo.Config import qualified Lupo.ConnectionPool as CP import Lupo.Import import qualified Lupo.Locale as L import qualified Lupo.PublicHandler as Public import qualified Lupo.URLMapper as U import Lupo.Util lupoInit :: LupoConfig -> SnapletInit Lupo Lupo lupoInit lc = makeSnaplet "lupo" "A personal web diary" Nothing $ do h <- nestSnaplet "heist" heist $ H.heistInit "templates" s <- nestSnaplet "session" session $ Cookie.initCookieSessionManager "site_key.txt" "sess" Nothing a <- nestSnaplet "auth" auth $ A.initAuthenticator session lc conn <- liftIO $ DB.ConnWrapper <$> Sqlite3.connectSqlite3 (lc ^. lcSqlitePath) edbs <- liftIO $ CP.makeConnectionPool (E.makeEntryDatabase conn $ lc ^. lcSpamFilter) 5 l <- liftIO $ L.loadYamlLocalizer $ lc ^. lcLocaleFile addRoutes [ ("", Public.handleTop) , ("admin", Admin.handleAdmin) , ("admin/new", Admin.handleNewEntry) , ("admin/:id/edit", Admin.handleEditEntry) , ("admin/:id/delete", Admin.handleDeleteEntry) , ("login", Admin.handleLogin) , ("js", serveDirectory "static/js") , ("css", serveDirectory "static/css") , ("images", serveDirectory "static/images") , ("search", Public.handleSearch) , ("entries/:id", Public.handleEntries) , (":query", Public.handleDay =<< textParam "query") , (":day/comment", Public.handleComment) , ("recent.atom", Public.handleFeed) ] onUnload $ DB.disconnect conn H.addSplices [ ("lupo:language", H.textSplice $ lc ^. lcLanguage) , ("lupo:top-page-path", U.urlSplice U.topPagePath) , ("lupo:search-path", U.urlSplice (U.fullPath "search")) ] pure Lupo { _heist = h , _session = s , _auth = a , _lupoConfig = lc , _localizer = l , _noticeDB = initNoticeDB conn , _urlMapper = U.makeURLMapper $ lc ^. lcBasePath , _entryDBPool = edbs , _viewFactory = V.makeViewFactory } where initNoticeDB conn = N.makeNoticeDB conn $ N.makeSessionBackend session
keitax/lupo
src/Lupo/Site.hs
lgpl-3.0
2,616
0
15
448
713
417
296
63
1
{-# LANGUAGE ConstraintKinds #-} -- TODO: Maybe use TVar instead of IORef to allow concurrency ? module Link ( Link , Linkable , Context , initContext , saveContext , defaultLink , invalidLink , createLink , destroyLink , restoreLink , readLink , writeLink , modifyLink ) where import Control.Monad import Data.Aeson import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString as B import qualified Data.Cache.LRU as L import Data.Dynamic import Data.Foldable import Data.IORef import Data.Maybe import qualified Data.Text as T import System.Mem import System.Mem.Weak import System.Directory import System.IO.Error import System.IO.Unsafe -- TODO: instead of IO a, please use MonadIO m => m a type Linkable a = (Typeable a, FromJSON a, ToJSON a) type LinkId = Integer type LinkRef a = IORef (Maybe (Weak (IORef a))) type LinkCache = L.LRU LinkId LinkCacheWrapper data LinkCacheWrapper = MkLinkCacheWrapper { lcwDynamic :: Dynamic , lcwSaveLink :: IO () } -- TODO: This should contain a linkRead, linkUpdate... to get rid of unsafePerformIO -- It should incidentally fix the GHCi reload problems where there's previous references bugging out not being collected data Link a = MkLink { linkId :: LinkId , linkRef :: LinkRef a } data Context = MkContext -- TODO: needs a better name than that { ctxCache :: IORef LinkCache , ctxJsonStore :: FilePath , ctxNextLinkId :: Link LinkId } instance Eq (Link a) where (==) (MkLink i _) (MkLink k _) = i == k instance Ord (Link a) where compare (MkLink i _) (MkLink k _) = i `compare` k instance Show (Link a) where show (MkLink i _) = "{Link #" ++ show i ++ "}" instance Linkable a => FromJSON (Link a) where parseJSON (String i) = return . restoreLink . read . T.unpack $ i parseJSON _ = error "Unable to parse Link json" instance ToJSON (Link a) where toJSON (MkLink i _) = String . T.pack . show $ i -- TODO: Functor, Applicative, Monad instances of `Relational` newtype, -- then give it a MonadRelational and allow it to be newtypederived for Game. -- This might prompt a huge refactor of the functions below. -- | Initializes a context for link isolation and preservation. initContext :: Maybe Integer -> FilePath -> IO Context initContext maybeLimit jsonStore = do cache <- newIORef (L.newLRU maybeLimit) return $ MkContext cache jsonStore (restoreLink 0) -- | Default link defaultLink :: Link a defaultLink = restoreLink 1 -- | Invalid link invalidLink :: Link a invalidLink = restoreLink (-1) -- | Linkify something createLink :: Linkable a => Context -> a -> IO (Link a) createLink ctx x = do refVal <- newIORef x weakRefVal <- mkWeakIORef refVal (return ()) ref <- newIORef $ Just weakRefVal maybeLid <- readLink ctx (ctxNextLinkId ctx) case maybeLid of Just _ -> modifyLink ctx (ctxNextLinkId ctx) (+1) Nothing -> do -- TODO review this case here, when there's no next id lidVal <- newIORef 2 weakLidVal <- mkWeakIORef lidVal (return ()) writeIORef (linkRef $ ctxNextLinkId ctx) (Just weakLidVal) saveLink ctx (ctxNextLinkId ctx) void $ fixLink ctx (ctxNextLinkId ctx) let link = MkLink (fromMaybe 1 maybeLid) ref -- TODO: instead of this, we could manually add it to the cache and fix the link, to not touch the disk saveLink ctx link _ <- fixLink ctx link return link -- | Destroy a link destroyLink :: Context -> Link a -> IO () destroyLink ctx link = do modifyIORef' (ctxCache ctx) $ \cache -> fst (L.delete (linkId link) cache) removeFile filename modifyIORef' (linkRef link) (const Nothing) where filename = ctxJsonStore ctx ++ show (linkId link) ++ ".json" -- | This creates an unresolved link, any LinkId is therefore valid and doesn't require IO. restoreLink :: LinkId -> Link a restoreLink lid = unsafePerformIO $ do -- Yes, I know what I'm doing. ref <- newIORef Nothing return $ MkLink lid ref -- | Writes a given value to a link writeLink :: Linkable a => Context -> Link a -> a -> IO () writeLink ctx link x = modifyLink ctx link (const x) -- | Transform the value of a link by a given function modifyLink :: Linkable a => Context -> Link a -> (a -> a) -> IO () modifyLink ctx link f = do maybeWeakRefVal <- readIORef (linkRef link) case maybeWeakRefVal of -- The link has already been resolved and we have a weak pointer in memory. Just weakRefVal -> do maybeRefVal <- deRefWeak weakRefVal case maybeRefVal of -- Our weak pointer is still valid, use that. Just refVal -> modifyIORef' refVal f -- Unfortunately, the weak pointer was garbage collected; so we need to reload the link again. Nothing -> do maybeVal <- fixLink ctx link case maybeVal of -- It failed to load the link, we cannot modify anything then. Nothing -> return () -- It recovered the link successfully; let's try again Just _ -> modifyLink ctx link f -- The link is not resolved yet Nothing -> do maybeVal <- fixLink ctx link case maybeVal of -- It failed to load the link, we cannot modify anything then. Nothing -> return () -- It resolved the link successfully; let's try again Just _ -> modifyLink ctx link f -- | Reads the value of a link readLink :: Linkable a => Context -> Link a -> IO (Maybe a) readLink ctx link = do maybeWeakRefVal <- readIORef (linkRef link) case maybeWeakRefVal of -- The link has already been resolved and we have a weak pointer in memory. Just weakRefVal -> do maybeRefVal <- deRefWeak weakRefVal case maybeRefVal of -- Our weak pointer is still valid, use that. Just refVal -> do val <- readIORef refVal return $ Just val -- Unfortunately, the weak pointer was garbage collected; so we need to reload the link again. Nothing -> fixLink ctx link -- The link is not resolved yet Nothing -> do cache <- readIORef (ctxCache ctx) -- Let's try to resolve it from the cache let (_, maybeCached) = L.lookup (linkId link) cache case maybeCached of -- Not found in cache; time to reload the link Nothing -> fixLink ctx link -- We have it cache, use that. Just cached -> do case fromDynamic (lcwDynamic cached) of Nothing -> return Nothing Just refVal -> do val <- readIORef refVal return $ Just val -- | This function loads a value in cache and create a healthy resolved link to the cache entry. fixLink :: Linkable a => Context -> Link a -> IO (Maybe a) fixLink ctx link = do cache <- readIORef (ctxCache ctx) -- Make sure the entry doesn't already exist in cache first let (newCache, maybeCached) = L.lookup (linkId link) cache case maybeCached of Just cached -> do modifyIORef (ctxCache ctx) (const newCache) case (fromDynamic $ lcwDynamic cached) of -- The value present in cache has been incorrectly cast; ignoring the user mistake to preserve stability Nothing -> return Nothing -- Recovered former cache entry, using that Just refVal -> do newWeakRefVal <- mkWeakIORef refVal (return ()) writeIORef (linkRef link) (Just newWeakRefVal) readLink ctx link Nothing -> do newMaybeVal <- loadVal ctx (linkId link) case newMaybeVal of -- Unable to load the value Nothing -> return Nothing Just newVal -> do -- Fixing the link newRefVal <- newIORef newVal newWeakRefVal <- mkWeakIORef newRefVal (return ()) writeIORef (linkRef link) (Just newWeakRefVal) -- Caching; here we exploit that saveLink is lazy let (newNewCache, maybeDropped) = L.insertInforming (linkId link) (MkLinkCacheWrapper (toDyn newRefVal) (saveLink ctx link)) newCache modifyIORef' (ctxCache ctx) (const newNewCache) fold $ lcwSaveLink . snd <$> maybeDropped return newMaybeVal -- | Helper function to load values from disk loadVal :: Linkable a => Context -> LinkId -> IO (Maybe a) loadVal ctx lid = do -- TODO: ignore io exceptions -- putStrLn ("Loading link #" ++ show lid) result <- eitherDecode' . LB.fromStrict <$> catchIOError (B.readFile filename) (const $ return B.empty) case result of Right x -> return $ Just x Left x -> do putStrLn ("Failed to decode #" ++ show lid ++ " with error: " ++ x) return Nothing where filename = ctxJsonStore ctx ++ show lid ++ ".json" -- | Helper function to save a link to disk. saveLink :: Linkable a => Context -> Link a -> IO () saveLink ctx link = do -- putStrLn ("Saving link #" ++ show (linkId link)) -- TODO: ignore io exceptions -- TODO: also create directory automatically if missing maybeVal <- readLink ctx link case maybeVal of Nothing -> return () Just val -> B.writeFile filename $ LB.toStrict $ encode val where filename = ctxJsonStore ctx ++ show (linkId link) ++ ".json" -- | Notably saves all links saveContext :: Context -> IO () saveContext ctx = do -- putStrLn "Saving context" cache <- readIORef (ctxCache ctx) mapM_ (lcwSaveLink . snd) (L.toList cache) -- TODO: Link is breaking referential transparency. TIL. It needs a good refactoring. performMajorGC
nitrix/lspace
legacy/Link.hs
unlicense
10,466
0
24
3,375
2,422
1,193
1,229
182
5
{-# LANGUAGE TemplateHaskell #-} module Main where import qualified Data.FormulaTest import Test.Tasty import Test.Tasty.TH main :: IO () main = $(defaultMainGenerator) test_all :: [TestTree] test_all = [ Data.FormulaTest.tests ]
jokusi/mso
test/mso-test.hs
apache-2.0
238
0
6
37
60
37
23
10
1
module ParserSpec(spec) where import Text.Parsec import ParserSupport import Parser import Syntax import Test.Hspec spec :: Spec spec = do describe "The common parser" $ do it "Should pick standard expressions" $ do let Right (Expression (Standard body) _ _) = parseExpression "{ evendistr 1 1 }" body `shouldBe` " evendistr 1 1 " it "Should pick do expressions" $ do let Right (Expression (Custom body) _ _) = parseExpression "do { def x(a, b) a * b; x(1, 1); }" body `shouldBe` " def x(a, b) a * b; x(1, 1); " it "Should parse repetitions" $ do let Right (Expression _ once _) = parseExpression "do { } once" once `shouldBe` (Times $ Exact 1) let Right (Expression _ twice _) = parseExpression "do { } 2 times" twice `shouldBe` (Times $ Exact 2) let Right (Expression _ oneToThree _) = parseExpression "do { } [1..3] times" oneToThree `shouldBe` (Times $ Between 1 3) let Right (Expression _ forever _) = parseExpression "do { } forever" forever `shouldBe` Forever it "Should parse delays" $ do let Right (Expression _ _ (Fixed exact)) = parseExpression "do { } every 1000ms" exact `shouldBe` (Exact 1000000) let Right (Expression _ _ (Fixed oneToThree)) = parseExpression "do { } every [1..3]ms" oneToThree `shouldBe` (Between 1000 3000) describe "Range parser" $ do it "Parses exact" $ do let Right one = parse range "<stdin>" "1" one `shouldBe` Exact 1 it "Parses ranges" $ do let Right oneToThree = parse range "<stdin>" "[1..3]" oneToThree `shouldBe` Between 1 3
eigengo/hwsexp
core/test/ParserSpec.hs
apache-2.0
1,629
0
23
412
535
248
287
36
1
module Syntax where import Control.Monad.Error import Text.ParserCombinators.Parsec hiding (spaces) data LispVal = Atom String | List [LispVal] | DottedList [LispVal] LispVal | Number Double | String String | Bool Bool data LispError = NumArgs Integer [LispVal] | TypeMismatch String LispVal | Parser ParseError | BadSpecialForm String LispVal | NotFunction String String | UnboundVar String String | Default String
sys1yagi/scheme-haskell-llvm
Syntax.hs
apache-2.0
570
0
7
212
116
70
46
16
0
import Lift main = do putStrLn "What lift?" -- lift <- getLine let lift = "squat" putStrLn "How many sets?" -- sets <- getLine let sets = "5" putStrLn "Input the weight" -- weight <- getLine let weight = "255" putStrLn "Input the reps" --reps <- getLine let reps = "5" let set = Set (fromInteger (read weight)) (read reps) sesh = Session lift $ take (read sets) $ repeat set putStr "Your session:\t" putStrLn (show sesh) let vol = sessionVolume sesh putStr "Volume:\t" putStrLn (show vol)
parsonsmatt/hlift
Main.hs
apache-2.0
571
0
14
169
181
80
101
17
1
-- 14316 import Data.Array((!), bounds, listArray) import Data.List(group) import Euler(intSqrt, primeFactorsP, primeSieve) nn = 1000000 primes = primeSieve (intSqrt nn) buildNext n = listArray (2,n) [divFunction x | x <- [2..n]] divFunction n = product [sum [p^ai | ai <- [0..a]] | (a,p) <- xs] - n where ds = primeFactorsP primes n xs = zip (map length $ group ds) (map head $ group ds) chainLength0 a s xs | x < (fst $ bounds a) = 0 -- outside bounds | x > (snd $ bounds a) = 0 -- outside bounds | s > n = 0 -- already found | s == n = length xs -- cycle found | n `elem` xs = 0 -- defer | otherwise = chainLength0 a s (n:xs) where x = head xs n = a ! x chainLength n x = chainLength0 (buildNext n) x [x] bestChainLength n = maximum [(chainLength n x, x) | x <- [1..nn]] main = putStrLn $ show $ snd $ bestChainLength nn
higgsd/euler
hs/95.hs
bsd-2-clause
917
0
12
262
434
226
208
21
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | A pedestrian implementation of a directed acyclic graph. Sharing is -- explicitely represented by using node-level and edge-level identifiers. The -- module may be convenient to use if your data structure doesn't change often. module Data.DAG ( -- * Types DAG , NodeID (..) , EdgeID (..) , Edge (..) -- * Primitive Operations , begsWith , endsWith , ingoingEdges , outgoingEdges , maybeNodeLabel , nodeLabel , maybeEdgeLabel , edgeLabel -- * Intermediate Operations , prevEdges , isInitialEdge -- , isInitialNode , nextEdges , isFinalEdge , minEdge , maxEdge , mapN , mapE , zipE , zipE' -- * Advanced Operations , dagNodes , dagEdges -- * Conversion , fromList , fromList' , fromEdgesUnsafe -- -- ** Provisional -- , toListProv -- * Splitting , splitTmp -- * Filtering , filterDAG -- * Check , isOK , isDAG -- * Topological sorting , topoSort ) where import Control.Applicative ((<|>)) import Control.Arrow (first) import Control.Monad (guard) import qualified Data.Foldable as F import qualified Data.List as L import Data.Maybe (isJust) import qualified Data.Traversable as T import qualified Data.Array as A -- import qualified Data.Vector as V import qualified Data.Set as S import qualified Data.Map.Strict as M import Data.Binary (Binary, get, put) --, putWord8, getWord8) -- import Data.Vector.Binary () -- import qualified Data.Binary as B ------------------------------------------------------------------ -- Types ------------------------------------------------------------------ -- | A directed acyclic graph (DAG) with nodes of type `a` and -- edges of type `b`. data DAG a b = DAG { nodeMap :: M.Map NodeID (Node a) , edgeMap :: M.Map EdgeID (Edge b) } deriving (Functor, F.Foldable, T.Traversable) -- The instance below is needed for Concraft. Something has to be done with -- it. instance (Binary a, Binary b) => Binary (DAG a b) where put = undefined get = undefined -- | Node ID. newtype NodeID = NodeID {unNodeID :: Int} deriving (Show, Eq, Ord) -- | Node of the DAG. data Node a = Node { ingoSet :: S.Set EdgeID , outgoSet :: S.Set EdgeID , ndLabel :: a } deriving (Show, Eq, Ord) -- | ID of an edge. The following properties must be satisfied by `EdgeID`: -- -- * The ordering of edge IDs (`Ord` instance) is consistent with the -- topological ordering of the edges. (TODO 26/02/2018: be more specific -- about what consistency means in this context) -- * The smallest `EdgeID` of a given DAG, `minEdge`, is equal -- to `0` (`EdgeID 0`). -- -- Additional important property, which guarantees that inference computations -- over the DAG, based on dynamic programming, are efficient: -- -- * Let `e` be the greatest `EdgeID` in the DAG. Then, the set of `EdgeID`s -- in the DAG is equal to {0 .. e}. -- -- However, this last property is not required for the correcntess of the -- inference computations, it only improves their memory complexity. -- -- TODO (13/11/2017): It seems that the following is not required: -- * The smallest `EdgeID` of a given DAG, `minEdge`, is equal -- to `0` (`EdgeID 0`). -- Verify that (see also `splitTmp`, whose second element does not satisfy the -- above description)! -- -- TODO (26/02/2018): Perhaps we should also assume that node IDs are sorted -- topologically? (see `splitTmp`). newtype EdgeID = EdgeID {unEdgeID :: Int} deriving (Show, Eq, Ord, Num, A.Ix) -- | Edge of the DAG. data Edge a = Edge { tailNode :: NodeID , headNode :: NodeID , edLabel :: a } deriving (Show, Eq, Ord, Functor, F.Foldable, T.Traversable) ------------------------------------------------------------------ -- Primitive Operations ------------------------------------------------------------------ -- | Return the edge for the given edge ID. edgeOn :: EdgeID -> DAG a b -> Edge b edgeOn i DAG{..} = case M.lookup i edgeMap of Nothing -> error "edgeWith: incorrent edge ID" Just edge -> edge -- | Return the tail node of the given edge. begsWith :: EdgeID -> DAG a b -> NodeID begsWith i DAG{..} = case M.lookup i edgeMap of Nothing -> error "begsWith: incorrent edge ID" Just Edge{..} -> tailNode -- | Return the head node of the given edge. endsWith :: EdgeID -> DAG a b -> NodeID endsWith i DAG{..} = case M.lookup i edgeMap of Nothing -> error "endsWith: incorrent edge ID" Just Edge{..} -> headNode -- | The list of outgoint edges from the given node, in ascending order. ingoingEdges :: NodeID -> DAG a b -> [EdgeID] ingoingEdges i DAG{..} = case M.lookup i nodeMap of Nothing -> error "ingoingEdges: incorrect ID" Just Node{..} -> S.toAscList ingoSet -- | The list of outgoint edges from the given node, in ascending order. outgoingEdges :: NodeID -> DAG a b -> [EdgeID] outgoingEdges i DAG{..} = case M.lookup i nodeMap of Nothing -> error "outgoingEdges: incorrect ID" Just Node{..} -> S.toAscList outgoSet -- | The label assigned to the given node. Return `Nothing` if the node ID is -- out of bounds. maybeNodeLabel :: NodeID -> DAG a b -> Maybe a maybeNodeLabel i DAG{..} = ndLabel <$> M.lookup i nodeMap -- | The label assigned to the given node. nodeLabel :: NodeID -> DAG a b -> a nodeLabel i DAG{..} = case M.lookup i nodeMap of Nothing -> error "nodeLabel: incorrect ID" Just Node{..} -> ndLabel -- | The label assigned to the given edge. Return `Nothing` if the edge ID is -- out of bounds. maybeEdgeLabel :: EdgeID -> DAG a b -> Maybe b maybeEdgeLabel i DAG{..} = edLabel <$> M.lookup i edgeMap -- | The label assigned to the given node. edgeLabel :: EdgeID -> DAG a b -> b edgeLabel i DAG{..} = case M.lookup i edgeMap of Nothing -> error "edgeLabel: incorrent ID" Just Edge{..} -> edLabel -- | The greatest `EdgeID` in the DAG. minEdge :: DAG a b -> EdgeID minEdge = fst . M.findMin . edgeMap -- | The greatest `EdgeID` in the DAG. maxEdge :: DAG a b -> EdgeID maxEdge = fst . M.findMax . edgeMap ------------------------------------------------------------------ -- Not-so-primitive ops, but still looking at the implementation ------------------------------------------------------------------ -- | The list of DAG nodes in ascending order. dagNodes :: DAG a b -> [NodeID] dagNodes = M.keys . nodeMap -- | Map function over node labels. mapN :: (a -> b) -> DAG a c -> DAG b c mapN f dag = dag {nodeMap = nodeMap'} where nodeMap' = M.fromList [ (nodeID, node {ndLabel = newLabel}) | (nodeID, node) <- M.toList (nodeMap dag) , let newLabel = f (ndLabel node) ] -- | The list of DAG edges in ascending order. dagEdges :: DAG a b -> [EdgeID] dagEdges = M.keys . edgeMap -- | Similar to `fmap` but the mapping function has access to IDs of the -- individual edges. mapE :: (EdgeID -> b -> c) -> DAG a b -> DAG a c mapE f dag = dag {edgeMap = edgeMap'} where edgeMap' = M.fromList [ (edgeID, edge {edLabel = newLabel}) | (edgeID, edge) <- M.toList (edgeMap dag) , let newLabel = f edgeID (edLabel edge) ] -- | Zip labels assigned to the same edges in the two input DAGs. Node labels -- from the first DAG are preserved. The function fails if the input DAGs -- contain different sets of edge IDs or node IDs. zipE :: DAG a b -> DAG x c -> DAG a (b, c) zipE dagL dagR | M.keysSet (nodeMap dagL) /= M.keysSet (nodeMap dagR) = error "zipE: different sets of node IDs" | M.keysSet (edgeMap dagL) /= M.keysSet (edgeMap dagR) = error "zipE: different sets of edge IDs" | otherwise = DAG { nodeMap = newNodeMap , edgeMap = newEdgeMap } where newNodeMap = nodeMap dagL newEdgeMap = M.fromList [ (edgeID, newEdge) | edgeID <- M.keys (edgeMap dagL) , let newEdge = mergeEdges (edgeMap dagL M.! edgeID) (edgeMap dagR M.! edgeID) ] mergeEdges e1 e2 | tailNode e1 /= tailNode e2 = error "zipE.mergEdges: different tail nodes" | headNode e1 /= headNode e2 = error "zipE.mergEdges: different head nodes" | otherwise = let newLabel = (edLabel e1, edLabel e2) in e1 {edLabel = newLabel} -- | A version of `zipE` which does not require that the sets of edges/nodes be -- the same. It does not preserve the node labels, though (it could be probably -- easily modified so as to account for them, though). zipE' :: DAG x a -> DAG y b -> DAG () (Maybe a, Maybe b) zipE' dagL dagR -- | M.keysSet (nodeMap dagL) /= M.keysSet (nodeMap dagR) = -- error "zipE': different sets of node IDs" -- | otherwise = fromEdgesUnsafe newEdgeList = fromEdgesUnsafe newEdgeList where edgesIn dag = map (flip edgeOn dag) (dagEdges dag) reconcile (x1, y1) (x2, y2) = (x1 <|> x2, y1 <|> y2) newEdgeMap = M.fromListWith reconcile $ [ ( (tailNode edge, headNode edge) , (Just (edLabel edge), Nothing) ) | edge <- edgesIn dagL ] ++ [ ( (tailNode edge, headNode edge) , (Nothing, Just (edLabel edge)) ) | edge <- edgesIn dagR ] newEdgeList = [ Edge {tailNode = from, headNode = to, edLabel = label} | ((from, to), label) <- M.toList newEdgeMap ] ------------------------------------------------------------------ -- Intermediate Operations ------------------------------------------------------------------ -- | The list of the preceding edges of the given edge. prevEdges :: EdgeID -> DAG a b -> [EdgeID] prevEdges edgeID dag = let tailNodeID = begsWith edgeID dag in ingoingEdges tailNodeID dag -- | Is the given edge initial? isInitialEdge :: EdgeID -> DAG a b -> Bool isInitialEdge edgeID = null . prevEdges edgeID -- -- | Is the given node initial? -- isInitialNode :: NodeID -> DAG a b -> Bool -- isInitialNode nodeID = null . ingoingEdges nodeID -- | The list of the succeding edges of the given edge. nextEdges :: EdgeID -> DAG a b -> [EdgeID] nextEdges edgeID dag = let headNodeID = endsWith edgeID dag in outgoingEdges headNodeID dag -- | Is the given edge initial? isFinalEdge :: EdgeID -> DAG a b -> Bool isFinalEdge edgeID = null . nextEdges edgeID ------------------------------------------------------------------ -- Conversion: List ------------------------------------------------------------------ -- | Convert a sequence of (node label, edge label) pairs to a trivial DAG. -- The first argument is the first node label. _fromList :: a -> [(a, b)] -> DAG a b _fromList nodeLabel0 xs = DAG { nodeMap = newNodeMap -- M.unions [begNodeMap, middleNodeMap, endNodeMap] , edgeMap = newEdgeMap } where newNodeMap = M.fromList $ do let nodeLabels = nodeLabel0 : map fst xs xsLength = length xs (i, y) <- zip [0 .. length xs] nodeLabels let node = Node { ingoSet = if i > 0 then S.singleton $ EdgeID (i-1) else S.empty , outgoSet = if i < xsLength then S.singleton $ EdgeID i else S.empty , ndLabel = y } return (NodeID i, node) newEdgeMap = M.fromList $ do (i, x) <- zip [0..] (map snd xs) let edge = Edge { tailNode = NodeID i , headNode = NodeID (i+1) , edLabel = x } return (EdgeID i, edge) -- | Convert a sequence of items to a trivial DAG. Afterwards, check if the -- resulting DAG is well-structured and throw error if not. fromList :: [a] -> DAG () a fromList xs = if isOK dag then dag else error "fromList: resulting DAG not `isOK`" where dag = _fromList () $ zip (repeat ()) xs -- | Convert a sequence of items to a trivial DAG. Afterwards, check if the -- resulting DAG is well-structured and throw error if not. fromList' :: a -> [(a, b)] -> DAG a b fromList' x xs = if isOK dag then dag else error "fromList': resulting DAG not `isOK`" where dag = _fromList x xs ------------------------------------------------------------------ -- Conversion: DAG ------------------------------------------------------------------ -- | Convert a sequence of labeled edges into a dag. -- The function assumes that edges are given in topological order. _fromEdgesUnsafe :: [Edge a] -> DAG () a _fromEdgesUnsafe edges = DAG { nodeMap = newNodeMap , edgeMap = newEdgeMap } where newEdgeMap = M.fromList $ do (i, edge) <- zip [0..] edges return (EdgeID i, edge) tailMap = M.fromListWith S.union $ do (i, edge) <- zip [0..] edges return (tailNode edge, S.singleton $ EdgeID i) headMap = M.fromListWith S.union $ do (i, edge) <- zip [0..] edges return (headNode edge, S.singleton $ EdgeID i) newNodeMap = M.fromList $ do nodeID <- S.toList $ S.union (M.keysSet headMap) (M.keysSet tailMap) let ingo = case M.lookup nodeID headMap of Nothing -> S.empty Just st -> st ougo = case M.lookup nodeID tailMap of Nothing -> S.empty Just st -> st node = Node { ingoSet = ingo , outgoSet = ougo , ndLabel = () } return (nodeID, node) -- | Convert a sequence of labeled edges into a dag. -- The function assumes that edges are given in topological order. fromEdgesUnsafe :: [Edge a] -> DAG () a fromEdgesUnsafe xs = if isOK dag then dag else error "fromEdgesUnsafe: resulting DAG not `isOK`" where dag = _fromEdgesUnsafe xs ------------------------------------------------------------------ -- Splitting ------------------------------------------------------------------ -- | Try to split the DAG on the given node, so that all the fst element of the -- result contains all nodes and edges from the given node is reachable, while -- the snd element contains all nodes/edges reachable from this node. -- -- NOTE: some edges can be discarded this way, it seems! -- -- TODO: A provisional function which does not necessarily work correctly. -- Now it assumes that node IDs are sorted topologically. splitTmp :: NodeID -> DAG a b -> Maybe (DAG a b, DAG a b) splitTmp splitNodeID dag | isOK dagLeft && isOK dagRight = Just (dagLeft, dagRight) | otherwise = Nothing where dagLeft = DAG nodesLeft edgesLeft dagRight = DAG nodesRight edgesRight edgesLeft = M.fromList [ (edgeID, edge) | (edgeID, edge) <- M.toList (edgeMap dag) , endsWith edgeID dag <= splitNodeID ] nodesLeft = M.fromList [ (nodeID, trim node) | (nodeID, node) <- M.toList (nodeMap dag) , nodeID <= splitNodeID ] where trim = trimNode (M.keysSet edgesLeft) edgesRight = M.fromList [ (edgeID, edge) | (edgeID, edge) <- M.toList (edgeMap dag) , begsWith edgeID dag >= splitNodeID ] nodesRight = M.fromList [ (nodeID, trim node) | (nodeID, node) <- M.toList (nodeMap dag) , nodeID >= splitNodeID ] where trim = trimNode (M.keysSet edgesRight) trimNode edgeSet = trimIngo edgeSet . trimOutgo edgeSet trimIngo edgeSet node = node {ingoSet = ingoSet node `S.intersection` edgeSet} trimOutgo edgeSet node = node {outgoSet = outgoSet node `S.intersection` edgeSet} ----------------------------------------------------------------- -- Filtering ------------------------------------------------------------------ -- -- | Remove the nodes (and the corresponding edges) which are not in the given set. -- filterDAG :: S.Set NodeID -> DAG a b -> DAG a b -- filterDAG nodeSet DAG{..} = -- DAG newNodeMap newEdgeMap -- where -- edgeSet = S.fromList -- [ edgeID -- | (edgeID, edge) <- M.toList edgeMap -- , tailNode edge `S.member` nodeSet -- , headNode edge `S.member` nodeSet ] -- updNode nd = nd -- { ingoSet = ingoSet nd `S.intersection` edgeSet -- , outgoSet = outgoSet nd `S.intersection` edgeSet } -- newNodeMap = M.fromList -- [ (nodeID, updNode node) -- | (nodeID, node) <- M.toList nodeMap -- , nodeID `S.member` nodeSet ] -- newEdgeMap = M.fromList -- [ (edgeID, edge) -- | (edgeID, edge) <- M.toList edgeMap -- , tailNode edge `S.member` nodeSet -- , headNode edge `S.member` nodeSet ] -- | Remove the edges (and the corresponding nodes) which are not in the given set. filterDAG :: S.Set EdgeID -> DAG a b -> DAG a b filterDAG edgeSet DAG{..} = DAG newNodeMap newEdgeMap where newEdgeMap = M.fromList $ do (edgeID, edge) <- M.toList edgeMap guard $ edgeID `S.member` edgeSet return (edgeID, edge) newNodeMap = M.fromList $ do (nodeID, node) <- M.toList nodeMap Just newNode <- return $ updNode node return (nodeID, newNode) updNode nd -- removing disconnected nodes | S.null newIngoSet && S.null newOutgoSet = Nothing | otherwise = Just $ nd { ingoSet = newIngoSet , outgoSet = newOutgoSet } where newIngoSet = ingoSet nd `S.intersection` edgeSet newOutgoSet = outgoSet nd `S.intersection` edgeSet -- ------------------------------------------------------------------ -- -- Provisional -- ------------------------------------------------------------------ -- -- -- -- | Convert the DAG to a list, provided that it was constructed from a list, -- -- which is not checked. -- toListProv :: DAG () a -> [a] -- toListProv DAG{..} = -- [ edLabel edge -- | (_edgeID, edge) <- M.toAscList edgeMap ] ------------------------------------------------------------------ -- Check ------------------------------------------------------------------ -- | Check if the DAG is well-structured (see also `isDAG`). isOK :: DAG a b -> Bool isOK DAG{..} = nodeMapOK && edgeMapOK where nodeMapOK = and [ M.member edgeID edgeMap | (_nodeID, Node{..}) <- M.toList nodeMap , edgeID <- S.toList (S.union ingoSet outgoSet) ] edgeMapOK = and [ M.member nodeID nodeMap | (_edgeID, Edge{..}) <- M.toList edgeMap , nodeID <- [tailNode, headNode] ] -- | Check if the DAG is actually acyclic. isDAG :: DAG a b -> Bool isDAG = isJust . topoSort ------------------------------------------------------------------ -- Topological sorting ------------------------------------------------------------------ -- | Retrieve the list of nodes sorted topologically. Returns `Nothing` if the -- graph has cycles. topoSort :: DAG a b -> Maybe [NodeID] topoSort dag0 = go dag0 $ S.fromList [ nodeID | nodeID <- dagNodes dag0 , null $ ingoingEdges nodeID dag0 ] where -- `noIncoming` is the set of nodes with no incoming edges. go dag noIncoming = case S.minView noIncoming of Just (nodeID, rest) -> let (dag', noIncoming') = removeNode nodeID dag in (nodeID:) <$> go dag' (S.union rest noIncoming') Nothing -> if null dag then Just [] else Nothing -- | Remove the node from the graph, together with all the outgoing edges, and -- return the set of nodes in the resulting DAG which have no incoming edges. removeNode :: NodeID -> DAG a b -> (DAG a b, S.Set NodeID) removeNode nodeID dag0 = first doRemoveNode $ L.foldl' f (dag0, S.empty) (outgoingEdges nodeID dag0) where doRemoveNode dag = dag { nodeMap = M.delete nodeID (nodeMap dag) } f (dag, nodeSet) edgeID = let nextID = endsWith edgeID dag dag' = dag { edgeMap = M.delete edgeID (edgeMap dag) , nodeMap = let adj node = node {ingoSet = S.delete edgeID (ingoSet node)} in M.adjust adj nextID (nodeMap dag) } in if null $ ingoingEdges nextID dag' then (dag', S.insert nextID nodeSet) else (dag', nodeSet)
kawu/pedestrian-dag
src/Data/DAG.hs
bsd-2-clause
19,908
0
21
4,703
4,588
2,462
2,126
337
3
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, FlexibleInstances, GADTs, ConstraintKinds, TypeOperators, DataKinds, UndecidableInstances #-} module Control.Coeffect.Coreader where import Control.Coeffect import Data.Type.Map import GHC.TypeLits {-| Provides 'reader monad'-like behaviour but as a comonad, using an indexed version of the product comonad -} data IxCoreader (s :: [Mapping Symbol *]) a = IxR { runCoreader :: (a, Map s) } instance Coeffect IxCoreader where type Inv IxCoreader s t = (Unionable s t, Split s t (Union s t)) type Unit IxCoreader = '[] type Plus IxCoreader s t = Union s t extract (IxR (x, Empty)) = x extend k (IxR (x, st)) = let (s, t) = split st in IxR (k (IxR (x, t)), s) instance CoeffectZip IxCoreader where type Meet IxCoreader s t = Union s t type CzipInv IxCoreader s t = (Unionable s t) czip (IxR (a, s)) (IxR (b, t)) = IxR ((a, b), union s t) {-| 'ask' for the value of variable 'v', e.g., 'ask (Var::(Var "x"))' -} ask :: Var v -> IxCoreader '[v :-> a] b -> a ask _ = \(IxR (_, Ext Var a Empty)) -> a
dorchard/effect-monad
src/Control/Coeffect/Coreader.hs
bsd-2-clause
1,135
0
13
276
394
214
180
20
1
import Data.Array kmp_table :: String -> Array Int Int kmp_table (_ : []) = array (0, 0) [(0, -1)] kmp_table (_ : _ : []) = array (0, 1) (zip [1 ..] [-1, 0]) kmp_table w = t where wl = length w warr = array (0, wl - 1) (zip [0 ..] w) tl = (zip [0 ..] (-1 : 0 : (kmp 2 0))) t = array (0, wl - 1) tl kmp pos cnd = if pos > wl - 1 then [] else if (warr ! (pos - 1)) == (warr ! cnd) then (succ cnd) : (kmp (succ pos) (succ cnd)) else if cnd > 0 then kmp pos (snd (tl !! cnd)) else 0 : (kmp (succ pos) cnd) kmp_search w s = s' 0 0 where sl = length s wl = length w sarr = array (0, sl - 1) (zip [0 ..] s) warr = array (0, wl - 1) (zip [0 ..] w) t = kmp_table s s' m i = if m + i < sl then if (warr ! i) == (sarr ! (m + i)) then if i == wl - 1 then m else s' m (succ i) else let m' = m + i - (t ! i) in if (t ! i) > -1 then s' m' (t ! i) else s' m' 0 else sl tst = do haystack <- getLine needle <- getLine putStrLn (if kmp_search needle haystack == length haystack then "NO" else "YES") main = do tstr <- getLine mapM_ (const tst) [1 .. (read tstr)]
pbl64k/HackerRank-Contests
2014-03-21-FP/SubstringSearching/ss.accepted.hs
bsd-2-clause
1,749
0
15
971
699
372
327
41
5
-- | UTF-8 encode a text -- -- Tested in this benchmark: -- -- * Replicating a string a number of times -- -- * UTF-8 encoding it -- module Benchmarks.EncodeUtf8 ( benchmark ) where import Test.Tasty.Bench (Benchmark, bgroup, bench, whnf) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL benchmark :: String -> String -> Benchmark benchmark name string = bgroup "EncodeUtf8" [ bench ("Text (" ++ name ++ ")") $ whnf (B.length . T.encodeUtf8) text , bench ("LazyText (" ++ name ++ ")") $ whnf (BL.length . TL.encodeUtf8) lazyText ] where -- The string in different formats text = T.replicate k $ T.pack string lazyText = TL.replicate (fromIntegral k) $ TL.pack string -- Amount k = 100000
bos/text
benchmarks/haskell/Benchmarks/EncodeUtf8.hs
bsd-2-clause
946
0
11
207
247
148
99
17
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} -- ^ is for the Bits a => Default a instance module HSGen.FFI where import Aux (apToLast) import Control.Monad (liftM2) import qualified Data.Text as T (Text, append, concat, cons, intercalate, pack, singleton, unwords) import Data.Bits (Bits(..)) import Data.Default (Default(..)) import Data.Fixable (Fix(..), isFixed) import Data.Text.Aux (addArrows, appendAfter, parens, showInt, textAp, unwords2, wrapText) -- | This is the standard language pragma for Haskell FFI pragma :: T.Text pragma = T.pack "{-# LANGUAGE ForeignFunctionInterface #-}\n" -- | This generates the import line for "Foreign.C.Types" typesImport :: [T.Text] -> T.Text typesImport typeList = T.concat [T.pack "import Foreign.C.Types (", T.unwords typeList, T.pack ")\n"] tlist :: [T.Text] tlist = map T.pack ["CInt","CInt", "CULLong", "CSChar", "CInt"] -- | Example: -- -- >>> ioifyUnit (T.pack "Bool") -- "IO (Bool)" ioifyUnit :: T.Text -> T.Text ioifyUnit = textAp "IO" -- | Example: -- -- >>> fixUnit (T.pack "String") -- "Fix (String)" -- fixUnit :: T.Text -> T.Text fixUnit = textAp "Fix" -- | Example: -- -- >>> ioifyTypeList . map T.pack ["Bool", "String", "Int"] -- ["Bool", "String", "IO (Int)"] -- ioifyTypeList :: [T.Text] -> [T.Text] ioifyTypeList = apToLast ioifyUnit -- | Example: -- -- >>> fixInit . map T.pack $ ["a", "b", "c"] -- "Fix (a) -> Fix (b)" -- fixInit :: [T.Text] -> T.Text fixInit = addArrows . map fixUnit . init -- | Example: -- -- >>> wrapperLast . map T.pack $ ["a", "b", "c"] -- "Wrapper (FunPtr (a -> b -> c) (c))" -- wrapperLast :: [T.Text] -> T.Text wrapperLast = textAp "Wrapper" . liftM2 unwords2 (textAp "FunPtr" . addArrows) (parens . last) -- fixTypeList = -- | Example: -- -- >>> fixTypeList (T.pack "a -> b -> c") -- "Fix (a) -> Fix (b) -> Wrapper (FunPtr (a -> b -> c)) c" -- fixTypeList :: [T.Text] -> T.Text fixTypeList = liftM2 (appendAfter (T.pack " -> ")) fixInit wrapperLast -- | Example: -- -- >>> functionImport (T.pack "math.h") (T.pack "sin") (T.pack "CDouble -> CDouble") -- "foreign import ccall \"math.h sin\" c_sin :: CDouble -> CDouble \n" -- functionImport :: T.Text -> T.Text -> T.Text -> T.Text functionImport header name ftype = T.unwords [T.pack "foreign import ccall", wrapText '\"' . T.concat $ [header, T.singleton ' ', name], T.append (T.pack "c_") name, T.pack "::", ftype, T.pack "\n"] -- c_func :: a -> b -> c -- c_compilable_func :: instance Bits a => Default a where def = zeroBits defUnfix :: Default a => Fix a -> a defUnfix (Fixed x) = x defUnfix Unfixed = def -- boolsToCUInt :: [Bool] -> CUInt -- func x y = if isFixed2 (x, y) -- then Wrap undefined (c_func x y) -- else Wrap (c_compilable_func fixity (f2C x) (f2C y)) undefined -- where -- f2C = fixedToC -- fixity = boolsToCUInt [isFixed x, isFixed y] -- func x y z = if isFixed3 (x,y,z) -- then Wrap undefined (c_func x y) -- else Wrap (c_compilable_func fixity (f2C x) (f2C y) (f2C z)) undefined -- where -- fixity = boolsToCUInt [isFixed x, isFixed y, isFixed z] importBits :: T.Text importBits = T.pack "import Data.Bits (bit, xor, zeroBits)\n" auxBoolToText :: Int -> T.Text auxBoolToText pos = parens . T.concat $ [T.pack "if x", showInt pos, T.pack " then bit ", showInt (pos - 1), T.pack " else zeroBits"] mkTup :: Int -> T.Text mkTup n = parens . T.intercalate (T.singleton ',') . map (T.cons 'x' . showInt) $ [1..n] -- NEED TO GENERATE TYPE: (Bool, Bool, .., Bool) -> CUInt {-# WARNING mkBoolToCUInt "This (generated) function needs a specific type declaration, don't forget to implement!" #-} mkBoolToCUInt :: Int -> T.Text mkBoolToCUInt n = T.concat [T.pack "boolToCUInt", showInt n, T.singleton ' ', mkTup n, T.pack " = ", T.intercalate (T.pack " `xor` ") . map auxBoolToText $ [1..n]] mkBoolToCUIntName :: Int -> T.Text mkBoolToCUIntName n = T.append (T.pack "boolToCUInt") (showInt n) andIsFixed :: Int -> T.Text andIsFixed = T.intercalate (T.pack " && ") . map (T.append (T.pack "isFixed x") . showInt) . enumFromTo 1 mkIsFixed :: Int -> T.Text mkIsFixed n = T.concat [T.pack "isFixed", T.intercalate (T.pack " x") (showInt n : map showInt [1..n]), T.pack " = ", andIsFixed n, T.singleton '\n'] mkIsFixedName :: Int -> T.Text mkIsFixedName n = T.append (T.pack "isFixed") (showInt n) -- isFixed2 x0 x1 = isFixed x0 && isFixed x1 -- isFixed3 x0 x1 x2 = isFixed x0 && isFixed x1 && isFixed x2 -- isFixed4 x0 x1 x2 x3 = isFixed x0 && isFixed x1 && isFixed x2 && isFixed x3
michaeljklein/CPlug
src/HSGen/FFI.hs
bsd-3-clause
4,801
0
13
1,085
1,151
637
514
57
1
module Data.NotZero( NotZero , getNotZero , notZero , notZeroElse , notZero1 , notZeroElse1 ) where import Control.Lens(Prism', prism') import Data.Monoid(Monoid(mappend, mempty)) import Data.Semigroup(Semigroup((<>))) import Data.Bool(bool) import Data.Eq(Eq((==))) import Data.Maybe(Maybe(Just, Nothing)) import Data.Ord(Ord) import Prelude(Num((*)), Show) newtype NotZero a = NotZero a deriving (Eq, Ord, Show) getNotZero :: NotZero a -> a getNotZero (NotZero a) = a notZero :: (Eq a, Num a) => Prism' a (NotZero a) notZero = prism' getNotZero (\a -> bool (Just (NotZero a)) Nothing (a == 0)) notZeroElse :: (Eq a, Num a) => NotZero a -> a -> NotZero a notZeroElse d a = bool (NotZero a) d (a == 0) notZero1 :: (Eq a, Num a) => NotZero a notZero1 = NotZero 1 notZeroElse1 :: (Eq a, Num a) => a -> NotZero a notZeroElse1 = notZeroElse notZero1 instance Num a => Semigroup (NotZero a) where NotZero a <> NotZero b = NotZero (a * b) instance Num a => Monoid (NotZero a) where mappend = (<>) mempty = NotZero 1
NICTA/notzero
src/Data/NotZero.hs
bsd-3-clause
1,091
0
12
248
479
266
213
56
1
{-# LANGUAGE DeriveDataTypeable , DataKinds , RankNTypes , GADTs , FlexibleContexts #-} {-# OPTIONS_GHC -Wall -fwarn-tabs #-} module Tests.TestTools where import Language.Hakaru.Types.Sing import Language.Hakaru.Parser.Parser import Language.Hakaru.Parser.SymbolResolve (resolveAST) import Language.Hakaru.Command (parseAndInfer, splitLines) import Language.Hakaru.Syntax.ABT import Language.Hakaru.Syntax.AST import Language.Hakaru.Syntax.TypeCheck import Language.Hakaru.Syntax.AST.Eq (alphaEq) import Language.Hakaru.Syntax.IClasses (TypeEq(..), jmEq1) import Language.Hakaru.Pretty.Concrete import Language.Hakaru.Simplify import Language.Hakaru.Syntax.AST.Eq() import Data.Maybe (isJust) import Data.List import qualified Data.Text as T import qualified Data.Text.IO as IO import Data.Typeable (Typeable) import Control.Exception import Control.Monad import Test.HUnit data TestException = TestSimplifyException String SomeException deriving Typeable instance Exception TestException instance Show TestException where show (TestSimplifyException prettyHakaru e) = show e ++ "\nwhile simplifying Hakaru:\n" ++ prettyHakaru -- assert that we get a result and that no error is thrown assertResult :: [a] -> Assertion assertResult s = assertBool "no result" $ not $ null s assertJust :: Maybe a -> Assertion assertJust = assertBool "expected Just but got Nothing" . isJust handleException :: String -> SomeException -> IO a handleException t e = throw (TestSimplifyException t e) testS :: (ABT Term abt) => String -> abt '[] a -> Assertion testS p x = do _ <- simplify x `catch` handleException (p ++ ": simplify failed") return () testStriv :: TrivialABT Term '[] a -> Assertion testStriv = testS "" -- Assert that all the given Hakaru programs simplify to the given one testSS :: (ABT Term abt) => String -> [(abt '[] a)] -> abt '[] a -> Assertion testSS nm ts t' = mapM_ (\t -> do p <- simplify t assertAlphaEq nm p t') (t':ts) testSStriv :: [(TrivialABT Term '[] a)] -> TrivialABT Term '[] a -> Assertion testSStriv = testSS "" assertAlphaEq :: (ABT Term abt) => String -> abt '[] a -> abt '[] a -> Assertion assertAlphaEq preface a b = unless (alphaEq a b) (assertFailure msg) where msg = concat [ p , "expected:\n" , show (pretty b) , "\nbut got:\n" , show (pretty a) ] p = if null preface then "" else preface ++ "\n" testWithConcrete :: (ABT Term abt) => T.Text -> TypeCheckMode -> (forall a. Sing a -> abt '[] a -> Assertion) -> Assertion testWithConcrete s mode k = case parseHakaru s of Left err -> assertFailure (show err) Right past -> let m = inferType (resolveAST past) in case runTCM m (splitLines s) mode of Left err -> assertFailure (show err) Right (TypedAST typ ast) -> k typ ast testWithConcrete' :: T.Text -> TypeCheckMode -> (forall a. Sing a -> TrivialABT Term '[] a -> Assertion) -> Assertion testWithConcrete' = testWithConcrete testConcreteFiles :: FilePath -> FilePath -> Assertion testConcreteFiles f1 f2 = do t1 <- IO.readFile f1 t2 <- IO.readFile f2 case (parseAndInfer t1, parseAndInfer t2) of (Left err, _) -> assertFailure (show err) (_, Left err) -> assertFailure (show err) (Right (TypedAST typ1 ast1), Right (TypedAST typ2 ast2)) -> do ast1' <- simplify ast1 case jmEq1 typ1 typ2 of Just Refl -> assertAlphaEq "" ast1' ast2 Nothing -> assertFailure "files don't have same type" ignore :: a -> Assertion ignore _ = assertFailure "ignored" -- ignoring a test reports as a failure -- Runs a single test from a list of tests given its index runTestI :: Test -> Int -> IO Counts runTestI (TestList ts) i = runTestTT $ ts !! i runTestI (TestCase _) _ = error "expecting a TestList, but got a TestCase" runTestI (TestLabel _ _) _ = error "expecting a TestList, but got a TestLabel" hasLab :: String -> Test -> Bool hasLab l (TestLabel lab _) = lab == l hasLab _ _ = False -- Runs a single test from a TestList given its label runTestN :: Test -> String -> IO Counts runTestN (TestList ts) l = case find (hasLab l) ts of Just t -> runTestTT t Nothing -> error $ "no test with label " ++ l runTestN (TestCase _) _ = error "expecting a TestList, but got a TestCase" runTestN (TestLabel _ _) _ = error "expecting a TestList, but got a TestLabel"
zaxtax/hakaru
haskell/Tests/TestTools.hs
bsd-3-clause
4,683
0
15
1,174
1,424
737
687
131
4
module Fal.Shape ( Shape (Rectangle, Ellipse, RtTriangle, Polygon), Radius, Side, Vertex, square, circle, distBetween, area ) where data Shape = Rectangle Side Side | Ellipse Radius Radius | RtTriangle Side Side | Polygon [Vertex] deriving Show type Radius = Float type Side = Float type Vertex = (Float,Float) square s = Rectangle s s circle r = Ellipse r r triArea :: Vertex -> Vertex -> Vertex -> Float triArea v1 v2 v3 = let a = distBetween v1 v2 b = distBetween v2 v3 c = distBetween v3 v1 s = 0.5*(a+b+c) in sqrt (s*(s-a)*(s-b)*(s-c)) distBetween :: Vertex -> Vertex -> Float distBetween (x1,y1) (x2,y2) = sqrt ((x1-x2)^2 + (y1-y2)^2) area :: Shape -> Float area (Rectangle s1 s2) = s1*s2 area (RtTriangle s1 s2) = s1*s2/2 area (Ellipse r1 r2) = pi*r1*r2 area (Polygon (v1:vs)) = polyArea vs where polyArea :: [Vertex] -> Float polyArea (v2:v3:vs') = triArea v1 v2 v3 + polyArea (v3:vs') polyArea _ = 0
Tarrasch/Hong
Fal/Shape.hs
bsd-3-clause
1,235
0
13
486
482
263
219
33
2
{-# LANGUAGE PatternGuards #-} module Idris.Elab.Data(elabData) where import Idris.AbsSyntax import Idris.ASTUtils import Idris.DSL import Idris.Error import Idris.Delaborate import Idris.Imports import Idris.Elab.Term import Idris.Coverage import Idris.DataOpts import Idris.Providers import Idris.Primitives import Idris.Inliner import Idris.PartialEval import Idris.DeepSeq import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting) import IRTS.Lang import Idris.Elab.Type import Idris.Elab.Utils import Idris.Elab.Value import Idris.Core.TT import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.Execute import Idris.Core.Typecheck import Idris.Core.CaseTree import Idris.Docstrings import Prelude hiding (id, (.)) import Control.Category import Control.Applicative hiding (Const) import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State import Data.List import Data.Maybe import Debug.Trace import qualified Data.Map as Map import qualified Data.Set as S import qualified Data.Text as T import Data.Char(isLetter, toLower) import Data.List.Split (splitOn) import Util.Pretty(pretty, text) elabData :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm)-> [(Name, Docstring (Either Err PTerm))] -> FC -> DataOpts -> PData -> Idris () elabData info syn doc argDocs fc opts (PLaterdecl n nfc t_in) = do let codata = Codata `elem` opts logLvl 1 (show (fc, doc)) checkUndefined fc n (cty, _, t, inacc) <- buildType info syn fc [] n t_in addIBC (IBCDef n) updateContext (addTyDecl n (TCon 0 0) cty) -- temporary, to check cons sendHighlighting [(nfc, AnnName n Nothing Nothing Nothing)] elabData info syn doc argDocs fc opts (PDatadecl n nfc t_in dcons) = do let codata = Codata `elem` opts logLvl 1 (show fc) undef <- isUndefined fc n (cty, ckind, t, inacc) <- buildType info syn fc [] n t_in -- if n is defined already, make sure it is just a type declaration -- with the same type we've just elaborated, and no constructors -- yet i <- getIState checkDefinedAs fc n cty i -- temporary, to check cons when undef $ updateContext (addTyDecl n (TCon 0 0) cty) let cnameinfo = cinfo info (map cname dcons) let unique = case getRetTy cty of UType UniqueType -> True _ -> False cons <- mapM (elabCon cnameinfo syn n codata (getRetTy cty) ckind) dcons ttag <- getName i <- getIState let as = map (const (Left (Msg ""))) (getArgTys cty) let params = findParams (map snd cons) logLvl 2 $ "Parameters : " ++ show params -- TI contains information about mutually declared types - this will -- be updated when the mutual block is complete putIState (i { idris_datatypes = addDef n (TI (map fst cons) codata opts params [n]) (idris_datatypes i) }) addIBC (IBCDef n) addIBC (IBCData n) checkDocs fc argDocs t doc' <- elabDocTerms info doc argDocs' <- mapM (\(n, d) -> do d' <- elabDocTerms info d return (n, d')) argDocs addDocStr n doc' argDocs' addIBC (IBCDoc n) let metainf = DataMI params addIBC (IBCMetaInformation n metainf) -- TMP HACK! Make this a data option updateContext (addDatatype (Data n ttag cty unique cons)) updateContext (setMetaInformation n metainf) mapM_ totcheck (zip (repeat fc) (map fst cons)) -- mapM_ (checkPositive n) cons -- if there's exactly one constructor, -- mark both the type and the constructor as detaggable case cons of [(cn,ct)] -> setDetaggable cn >> setDetaggable n >> addIBC (IBCOpt cn) >> addIBC (IBCOpt n) _ -> return () -- create an eliminator when (DefaultEliminator `elem` opts) $ evalStateT (elabCaseFun True params n t dcons info) Map.empty -- create a case function when (DefaultCaseFun `elem` opts) $ evalStateT (elabCaseFun False params n t dcons info) Map.empty -- Emit highlighting info sendHighlighting $ [(nfc, AnnName n Nothing Nothing Nothing)] ++ map (\(_, _, n, nfc, _, _, _) -> (nfc, AnnName n Nothing Nothing Nothing)) dcons where setDetaggable :: Name -> Idris () setDetaggable n = do ist <- getIState let opt = idris_optimisation ist case lookupCtxt n opt of [oi] -> putIState ist{ idris_optimisation = addDef n oi{ detaggable = True } opt } _ -> putIState ist{ idris_optimisation = addDef n (Optimise [] True) opt } checkDefinedAs fc n t i = let defined = tclift $ tfail (At fc (AlreadyDefined n)) ctxt = tt_ctxt i in case lookupDef n ctxt of [] -> return () [TyDecl _ ty] -> case converts ctxt [] t ty of OK () -> case lookupCtxtExact n (idris_datatypes i) of Nothing -> return () _ -> defined _ -> defined _ -> defined -- parameters are names which are unchanged across the structure, -- which appear exactly once in the return type of a constructor -- First, find all applications of the constructor, then check over -- them for repeated arguments findParams :: [Type] -> [Int] findParams ts = let allapps = map getDataApp ts -- do each constructor separately, then merge the results (names -- may change between constructors) conParams = map paramPos allapps in inAll conParams inAll :: [[Int]] -> [Int] inAll [] = [] inAll (x : xs) = filter (\p -> all (\ps -> p `elem` ps) xs) x paramPos [] = [] paramPos (args : rest) = dropNothing $ keepSame (zip [0..] args) rest dropNothing [] = [] dropNothing ((x, Nothing) : ts) = dropNothing ts dropNothing ((x, _) : ts) = x : dropNothing ts keepSame :: [(Int, Maybe Name)] -> [[Maybe Name]] -> [(Int, Maybe Name)] keepSame as [] = as keepSame as (args : rest) = keepSame (update as args) rest where update [] _ = [] update _ [] = [] update ((n, Just x) : as) (Just x' : args) | x == x' = (n, Just x) : update as args update ((n, _) : as) (_ : args) = (n, Nothing) : update as args getDataApp :: Type -> [[Maybe Name]] getDataApp f@(App _ _ _) | (P _ d _, args) <- unApply f = if (d == n) then [mParam args args] else [] getDataApp (Bind n (Pi _ t _) sc) = getDataApp t ++ getDataApp (instantiate (P Bound n t) sc) getDataApp _ = [] -- keep the arguments which are single names, which don't appear -- elsewhere mParam args [] = [] mParam args (P Bound n _ : rest) | count n args == 1 = Just n : mParam args rest where count n [] = 0 count n (t : ts) | n `elem` freeNames t = 1 + count n ts | otherwise = count n ts mParam args (_ : rest) = Nothing : mParam args rest cname (_, _, n, _, _, _, _) = n -- Abuse of ElabInfo. -- TODO Contemplate whether the ElabInfo type needs modification. cinfo :: ElabInfo -> [Name] -> ElabInfo cinfo info ds = let newps = params info dsParams = map (\n -> (n, [])) ds newb = addAlist dsParams (inblock info) l = liftname info in info { params = newps, inblock = newb, liftname = id -- Is this appropriate? } elabCon :: ElabInfo -> SyntaxInfo -> Name -> Bool -> Type -> -- for unique kind checking Type -> -- data type's kind (Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, PTerm, FC, [Name]) -> Idris (Name, Type) elabCon info syn tn codata expkind dkind (doc, argDocs, n, nfc, t_in, fc, forcenames) = do checkUndefined fc n logLvl 2 $ show fc ++ ":Constructor " ++ show n ++ " : " ++ show t_in (cty, ckind, t, inacc) <- buildType info syn fc [Constructor] n (if codata then mkLazy t_in else t_in) ctxt <- getContext let cty' = normalise ctxt [] cty checkUniqueKind ckind expkind addDataConstraint ckind dkind -- Check that the constructor type is, in fact, a part of the family being defined tyIs n cty' logLvl 5 $ show fc ++ ":Constructor " ++ show n ++ " elaborated : " ++ show t logLvl 5 $ "Inaccessible args: " ++ show inacc logLvl 2 $ "---> " ++ show n ++ " : " ++ show cty' -- Add to the context (this is temporary, so that later constructors -- can be indexed by it) updateContext (addTyDecl n (DCon 0 0 False) cty) addIBC (IBCDef n) checkDocs fc argDocs t doc' <- elabDocTerms info doc argDocs' <- mapM (\(n, d) -> do d' <- elabDocTerms info d return (n, d')) argDocs addDocStr n doc' argDocs' addIBC (IBCDoc n) fputState (opt_inaccessible . ist_optimisation n) inacc addIBC (IBCOpt n) return (n, cty') where tyIs con (Bind n b sc) = tyIs con sc tyIs con t | (P _ n' _, _) <- unApply t = if n' /= tn then tclift $ tfail (At fc (Elaborating "constructor " con (Msg (show n' ++ " is not " ++ show tn)))) else return () tyIs con t = tclift $ tfail (At fc (Elaborating "constructor " con (Msg (show t ++ " is not " ++ show tn)))) mkLazy (PPi pl n nfc ty sc) = let ty' = if getTyName ty then PApp fc (PRef fc (sUN "Lazy'")) [pexp (PRef fc (sUN "LazyCodata")), pexp ty] else ty in PPi pl n nfc ty' (mkLazy sc) mkLazy t = t getTyName (PApp _ (PRef _ n) _) = n == nsroot tn getTyName (PRef _ n) = n == nsroot tn getTyName _ = False getNamePos :: Int -> PTerm -> Name -> Maybe Int getNamePos i (PPi _ n _ _ sc) x | n == x = Just i | otherwise = getNamePos (i + 1) sc x getNamePos _ _ _ = Nothing -- if the constructor is a UniqueType, the datatype must be too -- (AnyType is fine, since that is checked for uniqueness too) -- if hte contructor is AnyType, the datatype must be at least AnyType checkUniqueKind (UType NullType) (UType NullType) = return () checkUniqueKind (UType NullType) _ = tclift $ tfail (At fc (UniqueKindError NullType n)) checkUniqueKind (UType UniqueType) (UType UniqueType) = return () checkUniqueKind (UType UniqueType) (UType AllTypes) = return () checkUniqueKind (UType UniqueType) _ = tclift $ tfail (At fc (UniqueKindError UniqueType n)) checkUniqueKind (UType AllTypes) (UType AllTypes) = return () checkUniqueKind (UType AllTypes) (UType UniqueType) = return () checkUniqueKind (UType AllTypes) _ = tclift $ tfail (At fc (UniqueKindError AllTypes n)) checkUniqueKind _ _ = return () -- Constructor's kind must be <= expected kind addDataConstraint (TType con) (TType exp) = do ctxt <- getContext let v = next_tvar ctxt addConstraints fc (v, [ULT con exp]) addDataConstraint _ _ = return () type EliminatorState = StateT (Map.Map String Int) Idris -- -- Issue #1616 in the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1616 -- -- TODO: Rewrite everything to use idris_implicits instead of manual splitting (or in TT) -- FIXME: Many things have name starting with elim internally since this was the only purpose in the first edition of the function -- rename to caseFun to match updated intend elabCaseFun :: Bool -> [Int] -> Name -> PTerm -> [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, PTerm, FC, [Name])] -> ElabInfo -> EliminatorState () elabCaseFun ind paramPos n ty cons info = do elimLog $ "Elaborating case function" put (Map.fromList $ zip (concatMap (\(_, p, _, _, ty, _, _) -> (map show $ boundNamesIn ty) ++ map (show . fst) p) cons ++ (map show $ boundNamesIn ty)) (repeat 0)) let (cnstrs, _) = splitPi ty let (splittedTy@(pms, idxs)) = splitPms cnstrs generalParams <- namePis False pms motiveIdxs <- namePis False idxs let motive = mkMotive n paramPos generalParams motiveIdxs consTerms <- mapM (\(c@(_, _, cnm, _, _, _, _)) -> do let casefunt = if ind then "elim_" else "case_" name <- freshName $ casefunt ++ simpleName cnm consTerm <- extractConsTerm c generalParams return (name, expl, consTerm)) cons scrutineeIdxs <- namePis False idxs let motiveConstr = [(motiveName, expl, motive)] let scrutinee = (scrutineeName, expl, applyCons n (interlievePos paramPos generalParams scrutineeIdxs 0)) let eliminatorTy = piConstr (generalParams ++ motiveConstr ++ consTerms ++ scrutineeIdxs ++ [scrutinee]) (applyMotive (map (\(n,_,_) -> PRef elimFC n) scrutineeIdxs) (PRef elimFC scrutineeName)) let eliminatorTyDecl = PTy (fmap (const (Left $ Msg "")) . parseDocstring . T.pack $ show n) [] defaultSyntax elimFC [TotalFn] elimDeclName NoFC eliminatorTy let clauseConsElimArgs = map getPiName consTerms let clauseGeneralArgs' = map getPiName generalParams ++ [motiveName] ++ clauseConsElimArgs let clauseGeneralArgs = map (\arg -> pexp (PRef elimFC arg)) clauseGeneralArgs' let elimSig = "-- case function signature: " ++ showTmImpls eliminatorTy elimLog elimSig eliminatorClauses <- mapM (\(cns, cnsElim) -> generateEliminatorClauses cns cnsElim clauseGeneralArgs generalParams) (zip cons clauseConsElimArgs) let eliminatorDef = PClauses emptyFC [TotalFn] elimDeclName eliminatorClauses elimLog $ "-- case function definition: " ++ (show . showDeclImp verbosePPOption) eliminatorDef State.lift $ idrisCatch (rec_elabDecl info EAll info eliminatorTyDecl) (ierror . Elaborating "type declaration of " elimDeclName) -- Do not elaborate clauses if there aren't any case eliminatorClauses of [] -> State.lift $ solveDeferred elimDeclName -- Remove meta-variable for type _ -> State.lift $ idrisCatch (rec_elabDecl info EAll info eliminatorDef) (ierror . Elaborating "clauses of " elimDeclName) where elimLog :: String -> EliminatorState () elimLog s = State.lift (logLvl 2 s) elimFC :: FC elimFC = fileFC "(casefun)" elimDeclName :: Name elimDeclName = if ind then SN . ElimN $ n else SN . CaseN $ n applyNS :: Name -> [String] -> Name applyNS n [] = n applyNS n ns = sNS n ns splitPi :: PTerm -> ([(Name, Plicity, PTerm)], PTerm) splitPi = splitPi' [] where splitPi' :: [(Name, Plicity, PTerm)] -> PTerm -> ([(Name, Plicity, PTerm)], PTerm) splitPi' acc (PPi pl n _ tyl tyr) = splitPi' ((n, pl, tyl):acc) tyr splitPi' acc t = (reverse acc, t) splitPms :: [(Name, Plicity, PTerm)] -> ([(Name, Plicity, PTerm)], [(Name, Plicity, PTerm)]) splitPms cnstrs = (map fst pms, map fst idxs) where (pms, idxs) = partition (\c -> snd c `elem` paramPos) (zip cnstrs [0..]) isMachineGenerated :: Name -> Bool isMachineGenerated (MN _ _) = True isMachineGenerated _ = False namePis :: Bool -> [(Name, Plicity, PTerm)] -> EliminatorState [(Name, Plicity, PTerm)] namePis keepOld pms = do names <- mapM (mkPiName keepOld) pms let oldNames = map fst names let params = map snd names return $ map (\(n, pl, ty) -> (n, pl, removeParamPis oldNames params ty)) params mkPiName :: Bool -> (Name, Plicity, PTerm) -> EliminatorState (Name, (Name, Plicity, PTerm)) mkPiName keepOld (n, pl, piarg) | not (isMachineGenerated n) && keepOld = do return (n, (n, pl, piarg)) mkPiName _ (oldName, pl, piarg) = do name <- freshName $ keyOf piarg return (oldName, (name, pl, piarg)) where keyOf :: PTerm -> String keyOf (PRef _ name) | isLetter (nameStart name) = (toLower $ nameStart name):"__" keyOf (PApp _ tyf _) = keyOf tyf keyOf (PType _) = "ty__" keyOf _ = "carg__" nameStart :: Name -> Char nameStart n = nameStart' (simpleName n) where nameStart' :: String -> Char nameStart' "" = ' ' nameStart' ns = head ns simpleName :: Name -> String simpleName (NS n _) = simpleName n simpleName (MN i n) = str n ++ show i simpleName n = show n nameSpaces :: Name -> [String] nameSpaces (NS _ ns) = map str ns nameSpaces _ = [] freshName :: String -> EliminatorState Name freshName key = do nameMap <- get let i = fromMaybe 0 (Map.lookup key nameMap) let name = uniqueName (sUN (key ++ show i)) (map (\(nm, nb) -> sUN (nm ++ show nb)) $ Map.toList nameMap) put $ Map.insert key (i+1) nameMap return name scrutineeName :: Name scrutineeName = sUN "scrutinee" scrutineeArgName :: Name scrutineeArgName = sUN "scrutineeArg" motiveName :: Name motiveName = sUN "prop" mkMotive :: Name -> [Int] -> [(Name, Plicity, PTerm)] -> [(Name, Plicity, PTerm)] -> PTerm mkMotive n paramPos params indicies = let scrutineeTy = (scrutineeArgName, expl, applyCons n (interlievePos paramPos params indicies 0)) in piConstr (indicies ++ [scrutineeTy]) (PType elimFC) piConstr :: [(Name, Plicity, PTerm)] -> PTerm -> PTerm piConstr [] ty = ty piConstr ((n, pl, tyb):tyr) ty = PPi pl n NoFC tyb (piConstr tyr ty) interlievePos :: [Int] -> [a] -> [a] -> Int -> [a] interlievePos idxs [] l2 i = l2 interlievePos idxs l1 [] i = l1 interlievePos idxs (x:xs) l2 i | i `elem` idxs = x:(interlievePos idxs xs l2 (i+1)) interlievePos idxs l1 (y:ys) i = y:(interlievePos idxs l1 ys (i+1)) replaceParams :: [Int] -> [(Name, Plicity, PTerm)] -> PTerm -> PTerm replaceParams paramPos params cns = let (_, cnsResTy) = splitPi cns in case cnsResTy of PApp _ _ args -> let oldParams = paramNamesOf 0 paramPos args in removeParamPis oldParams params cns _ -> cns removeParamPis :: [Name] -> [(Name, Plicity, PTerm)] -> PTerm -> PTerm removeParamPis oldParams params (PPi pl n fc tyb tyr) = case findIndex (== n) oldParams of Nothing -> (PPi pl n fc (removeParamPis oldParams params tyb) (removeParamPis oldParams params tyr)) Just i -> (removeParamPis oldParams params tyr) removeParamPis oldParams params (PRef _ n) = case findIndex (== n) oldParams of Nothing -> (PRef elimFC n) Just i -> let (newname,_,_) = params !! i in (PRef elimFC (newname)) removeParamPis oldParams params (PApp _ cns args) = PApp elimFC (removeParamPis oldParams params cns) $ replaceParamArgs args where replaceParamArgs :: [PArg] -> [PArg] replaceParamArgs [] = [] replaceParamArgs (arg:args) = case extractName (getTm arg) of [] -> arg:replaceParamArgs args [n] -> case findIndex (== n) oldParams of Nothing -> arg:replaceParamArgs args Just i -> let (newname,_,_) = params !! i in arg {getTm = PRef elimFC newname}:replaceParamArgs args removeParamPis oldParams params t = t paramNamesOf :: Int -> [Int] -> [PArg] -> [Name] paramNamesOf i paramPos [] = [] paramNamesOf i paramPos (arg:args) = (if i `elem` paramPos then extractName (getTm arg) else []) ++ paramNamesOf (i+1) paramPos args extractName :: PTerm -> [Name] extractName (PRef _ n) = [n] extractName _ = [] splitArgPms :: PTerm -> ([PTerm], [PTerm]) splitArgPms (PApp _ f args) = splitArgPms' args where splitArgPms' :: [PArg] -> ([PTerm], [PTerm]) splitArgPms' cnstrs = (map (getTm . fst) pms, map (getTm . fst) idxs) where (pms, idxs) = partition (\c -> snd c `elem` paramPos) (zip cnstrs [0..]) splitArgPms _ = ([],[]) implicitIndexes :: (Docstring (Either Err PTerm), Name, PTerm, FC, [Name]) -> EliminatorState [(Name, Plicity, PTerm)] implicitIndexes (cns@(doc, cnm, ty, fc, fs)) = do i <- State.lift getIState implargs' <- case lookupCtxt cnm (idris_implicits i) of [] -> do fail $ "Error while showing implicits for " ++ show cnm [args] -> do return args _ -> do fail $ "Ambigous name for " ++ show cnm let implargs = mapMaybe convertImplPi implargs' let (_, cnsResTy) = splitPi ty case cnsResTy of PApp _ _ args -> let oldParams = paramNamesOf 0 paramPos args in return $ filter (\(n,_,_) -> not (n `elem` oldParams))implargs _ -> return implargs extractConsTerm :: (Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, PTerm, FC, [Name]) -> [(Name, Plicity, PTerm)] -> EliminatorState PTerm extractConsTerm (doc, argDocs, cnm, _, ty, fc, fs) generalParameters = do let cons' = replaceParams paramPos generalParameters ty let (args, resTy) = splitPi cons' implidxs <- implicitIndexes (doc, cnm, ty, fc, fs) consArgs <- namePis False args let recArgs = findRecArgs consArgs let recMotives = if ind then map applyRecMotive recArgs else [] let (_, consIdxs) = splitArgPms resTy return $ piConstr (implidxs ++ consArgs ++ recMotives) (applyMotive consIdxs (applyCons cnm consArgs)) where applyRecMotive :: (Name, Plicity, PTerm) -> (Name, Plicity, PTerm) applyRecMotive (n,_,ty) = (sUN $ "ih" ++ simpleName n, expl, applyMotive idxs (PRef elimFC n)) where (_, idxs) = splitArgPms ty findRecArgs :: [(Name, Plicity, PTerm)] -> [(Name, Plicity, PTerm)] findRecArgs [] = [] findRecArgs (ty@(_,_,PRef _ tn):rs) | simpleName tn == simpleName n = ty:findRecArgs rs findRecArgs (ty@(_,_,PApp _ (PRef _ tn) _):rs) | simpleName tn == simpleName n = ty:findRecArgs rs findRecArgs (ty:rs) = findRecArgs rs applyCons :: Name -> [(Name, Plicity, PTerm)] -> PTerm applyCons tn targs = PApp elimFC (PRef elimFC tn) (map convertArg targs) convertArg :: (Name, Plicity, PTerm) -> PArg convertArg (n, _, _) = pexp (PRef elimFC n) applyMotive :: [PTerm] -> PTerm -> PTerm applyMotive idxs t = PApp elimFC (PRef elimFC motiveName) (map pexp idxs ++ [pexp t]) getPiName :: (Name, Plicity, PTerm) -> Name getPiName (name,_,_) = name convertImplPi :: PArg -> Maybe (Name, Plicity, PTerm) convertImplPi (PImp {getTm = t, pname = n}) = Just (n, expl, t) convertImplPi _ = Nothing generateEliminatorClauses :: (Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, PTerm, FC, [Name]) -> Name -> [PArg] -> [(Name, Plicity, PTerm)] -> EliminatorState PClause generateEliminatorClauses (doc, _, cnm, _, ty, fc, fs) cnsElim generalArgs generalParameters = do let cons' = replaceParams paramPos generalParameters ty let (args, resTy) = splitPi cons' i <- State.lift getIState implidxs <- implicitIndexes (doc, cnm, ty, fc, fs) let (_, generalIdxs') = splitArgPms resTy let generalIdxs = map pexp generalIdxs' consArgs <- namePis False args let lhsPattern = PApp elimFC (PRef elimFC elimDeclName) (generalArgs ++ generalIdxs ++ [pexp $ applyCons cnm consArgs]) let recArgs = findRecArgs consArgs let recElims = if ind then map applyRecElim recArgs else [] let rhsExpr = PApp elimFC (PRef elimFC cnsElim) (map convertArg implidxs ++ map convertArg consArgs ++ recElims) return $ PClause elimFC elimDeclName lhsPattern [] rhsExpr [] where applyRecElim :: (Name, Plicity, PTerm) -> PArg applyRecElim (constr@(recCnm,_,recTy)) = pexp $ PApp elimFC (PRef elimFC elimDeclName) (generalArgs ++ map pexp idxs ++ [pexp $ PRef elimFC recCnm]) where (_, idxs) = splitArgPms recTy
bkoropoff/Idris-dev
src/Idris/Elab/Data.hs
bsd-3-clause
26,097
0
22
8,515
8,941
4,615
4,326
438
41
-- | The Syntax is as follows : -- "nodeName[Class(optional)]{ID(optional)} > nodeName[Class(optional)]{ID(optional)}" -- eg : "div{id1} > h1[class]" {-# LANGUAGE OverloadedStrings, NoMonomorphismRestriction, FlexibleContexts #-} module HScraper.QueryParser ( parseQuery ) where import qualified Data.Text as T import Text.Parsec import HScraper.Types parseQuery :: String -> Either ParseError Query parseQuery s = case parse parseNodeQueries "" (unwords (words s)) of Left err -> Left err Right nodes -> Right nodes parseNodeQueries :: Stream s m Char => ParsecT s u m [NodeQuery] parseNodeQueries = sepBy node (spaces >> char '>' >> spaces) clas :: Stream s m Char => ParsecT s u m String clas = do _ <- char '[' clnm <- many (noneOf "]") _ <- char ']' return clnm idd :: Stream s m Char => ParsecT s u m String idd = do _ <- char '{' idnm <- many (noneOf "}") _ <- char '}' return idnm node :: Stream s m Char => ParsecT s u m NodeQuery node = do name <-many (noneOf " {[>") cls <- optionMaybe clas ids <- optionMaybe idd return (NodeQuery (T.pack name) (fmap T.pack cls) (fmap T.pack ids))
Nishant9/hScraper
HScraper/QueryParser.hs
bsd-3-clause
1,134
0
12
227
408
196
212
30
2
-------------------------------------------------------------------------------- {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} -- | write module implements most of the utilities of the bot module Write ( write, msg, msgPrivate, privateOrPublic ) where -------------------------------------------------------------------------------- -- | User defined modules import IMonad import Google import Http import FlipRandom import CowsAndBulls import WeatherForecast import Try -------------------------------------------------------------------------------- -- | Pre-Defined System Modules import System.IO import System.IO.Unsafe import Text.Printf import Control.Monad.Reader import Control.Monad.Trans (liftIO) import qualified Data.Text as T import Data.List import Data.Char import Data.Time import Data.String import Data.IORef import System.Exit -------------------------------------------------------------------------------- -- | simulation of global variables and functions to manipulate them guessNum = unsafePerformIO $ newIORef 0 count = unsafePerformIO $ newIORef 19 newNode1 num num1= do i <- readIORef num1 writeIORef num1 num writeDummy "Sahil" newNode3 num1= do i <- readIORef num1 modifyIORef num1 sub writeDummy "Sahil" newNode2 num = do i <- readIORef num writeIORef num i return i -- minus by 1 function sub :: Int -> Int sub h = h-1 -- writes down dummy strings writeDummy :: String -> IO() writeDummy dummy = printf dummy -------------------------------------------------------------------------------- -- | main write operation which inputs protocoled message in the socket write :: String -> String -> Net () write s t = do h <- asks socket io $ hPrintf h "%s %s\r\n" s t io $ printf "> %s %s\n" s t -- | function to get the sender of the recent message getSender :: String -> String getSender = takeWhile(/= '!').drop 1 -- | function to get the receiver of the message getReceiver :: String->String getReceiver = takeWhile(/= '\SP').drop 1.dropWhile(/= '\SP'). drop 1.dropWhile(/= '\SP') -- | decider function to check whether the next message is private or public privateOrPublic :: String -> Net () privateOrPublic message | getReceiver message == getNick = evalPri message | otherwise = evalPub message -- | separate evaluate for the private commands evalPri :: String -> Net() evalPri message = do if ping message then pong message else evalPrivate (clean message) (getSender message) (getReceiver message) where ping x = "PING :" `isPrefixOf` x pong x = write "PONG" (':' : drop 6 x) clean = drop 1.dropWhile (/= ':').drop 1 -- | separate evaluate for the public commands evalPub :: String -> Net() evalPub message = do if ping message then pong message else evalPublic (clean message) (getSender message) (getReceiver message) where ping x = "PING :" `isPrefixOf` x pong x = write "PONG" (':' : drop 6 x) clean = drop 1.dropWhile (/= ':').drop 1 -- | guarded function to decide which private command to execute evalPrivate ::String -> String -> String -> Net() evalPrivate "!quit" y z= write "QUIT" ":Exiting" >> io (exitWith ExitSuccess) evalPrivate x y z | "!echo " `isPrefixOf` x = msgPrivate (drop 6 x) y | "!dec2bin " `isPrefixOf` x = dec2bin (drop 9 x) y | "!bin2dec " `isPrefixOf` x = bin2dec (drop 9 x) y | "!google " `isPrefixOf` x = gQuery (drop 8 x) y | "!gmt_time" `isPrefixOf` x = getTime y | "!local_time" `isPrefixOf` x = getLocalTime y | x == "!cowsNbulls" = initCnB y | "!guess " `isPrefixOf` x = guessNumber (drop 7 x) y | x == "!commands" = dispHelp y | x == "!echo@help" = echHelp y | x == "!dec2bin@help" = d2bHelp y | x == "!bin2dec@help" = b2dHelp y | x == "!google@help" = gHelp y | x == "!gmt_time@help" = gtHelp y | x == "!local_time@help" = ltHelp y | x == "!cowsNBulls@help" = cnbHelp y | x == "!guess@help" = guHelp y | x == "!randomCoin@help" = rcHelp y | x == "!rDie@help" = rdHelp y | x == "!weather" = wHelp y evalPrivate _ _ _ = return() -- | guarded function to decide which private command to execute evalPublic ::String -> String -> String -> Net() evalPublic "!quit" y z= write "QUIT" ":Exiting" >> io (exitWith ExitSuccess) evalPublic x y z | "!echo " `isPrefixOf` x = msg (drop 6 x) y | x == "!randomCoin" = rCoin y | x == "!local_time" = getLocalTime' y | x == "!rDie" = rDie y | x == "!weather" = weather y | x == "!commands" = dispHelp' y | x == "!echo@help" = echHelp' y | x == "!dec2bin@help" = d2bHelp' y | x == "!bin2dec@help" = b2dHelp' y | x == "!google@help" = gHelp' y | x == "!gmt_time@help" = gtHelp' y | x == "!local_time@help" = ltHelp' y | x == "!cowsNBulls@help" = cnbHelp' y | x == "!guess@help" = guHelp' y | x == "!randomCoin@help" = rcHelp' y | x == "!rDie@help" = rdHelp' y | x == "!weather" = wHelp' y evalPublic _ _ _ = return() msg :: String->String ->Net () -- | Separate messaging command for public commands msg str sender= do write "PRIVMSG" (getChannel ++ " :" ++ sender ++": "++ str) -- | Separate messaging command for private commands msgPrivate :: String->String->Net () msgPrivate str sender = write "PRIVMSG" (sender ++ " :" ++ str) --function to get current time in GMT form getTime ::String -> Net() getTime sender = do let a = unsafePerformIO(getCurrentTime) msgPrivate (show a) sender -- | function to get current time according to their respective time zone getLocalTime ::String -> Net() getLocalTime sender = do let a = unsafePerformIO(getZonedTime) msgPrivate (show a) sender getLocalTime' ::String -> Net() getLocalTime' sender = do let a = unsafePerformIO(getZonedTime) msg (show a) sender -- | function to simulate tossing of a coin rCoin :: String -> Net() rCoin sender | randomInt == 0 = msg "Heads" sender | otherwise = msg "Tails" sender -- | function to simulate throwing of a die rDie :: String -> Net() rDie sender = msg ("The Number on The Die is "++(show rollDice)) sender -- | function to initiate the cows and bulls game initCnB ::String -> Net() initCnB sender = do io $ printf "Inside Init of CnB" io $ newNode1 randomNumber guessNum io $ newNode1 10 count msgPrivate "Guess the number, Your Time Starts Now" sender -- | function to evaluate user guess in the game guessNumber :: String -> String -> Net() guessNumber number sender = if unsafePerformIO(readIORef count) == 0 then msgPrivate "Sorry, Time's up!" sender else do io $ newNode3 count let b = getNumList (read number ::Int) let c = checkCows b (getNumList (unsafePerformIO(readIORef guessNum))) 3 let d = (checkBulls b (getNumList (unsafePerformIO(readIORef guessNum)))) - c msgPrivate ("Turn " ++ (intToDigit(11- unsafePerformIO(newNode2 count)):[]) ++ " : "++"Cows = "++ (show c)++" Bulls = "++ (show d)) sender -- | helper function to convert to binary toBin :: Int -> [Int] toBin 0 = [0] toBin n = reverse(helpBin n) -- | another helper function to help in converting to binary helpBin 0 = [] helpBin n | n `mod` 2 == 1 = 1:helpBin(n `div` 2) | n `mod` 2 == 0 = 0:helpBin(n `div` 2) -- | function to convert decimal to binary dec2bin :: String -> String ->Net() dec2bin num sender = do let number = read num :: Int msgPrivate (intToDigit `map` (toBin number)) sender -- |helper function to convert to decimal toDec :: String -> Int toDec = foldl' (\acc x -> acc * 2 + digitToInt x) 0 -- |function to convert decimal to binary bin2dec :: String -> String -> Net() bin2dec num sender = do let number = toDec num msgPrivate (show number) sender -- |function to search for a google query gQuery :: String -> String ->Net() gQuery search sender = msgPrivate (T.unpack (google1 (T.pack search))) sender -- |function to get current weather weather :: String -> Net() weather sender = msg (unsafePerformIO(getForeCast)) sender wHelp :: String -> Net() wHelp sender = msgPrivate weatherHelp sender echHelp :: String -> Net() echHelp sender = msgPrivate echoHelp sender dispHelp :: String -> Net() dispHelp sender = msgPrivate displayHelp sender d2bHelp :: String -> Net() d2bHelp sender = msgPrivate dec2binHelp sender b2dHelp :: String -> Net() b2dHelp sender = msgPrivate bin2decHelp sender gHelp :: String -> Net() gHelp sender = msgPrivate googleHelp sender gtHelp :: String -> Net() gtHelp sender = msgPrivate gmt_timeHelp sender ltHelp :: String -> Net() ltHelp sender = msgPrivate local_timeHelp sender cnbHelp :: String -> Net() cnbHelp sender = msgPrivate cowsNbullsHelp sender guHelp :: String -> Net() guHelp sender = msgPrivate guesssHelp sender rcHelp :: String -> Net() rcHelp sender = msgPrivate randomCoinHelp sender rdHelp :: String -> Net() rdHelp sender = msgPrivate rDieHelp sender dispHelp' :: String -> Net() dispHelp' sender = msg displayHelp sender d2bHelp' :: String -> Net() d2bHelp' sender = msg dec2binHelp sender b2dHelp' :: String -> Net() b2dHelp' sender = msg bin2decHelp sender gHelp' :: String -> Net() gHelp' sender = msg googleHelp sender gtHelp' :: String -> Net() gtHelp' sender = msg gmt_timeHelp sender ltHelp' :: String -> Net() ltHelp' sender = msg local_timeHelp sender cnbHelp' :: String -> Net() cnbHelp' sender = msg cowsNbullsHelp sender guHelp' :: String -> Net() guHelp' sender = msg guesssHelp sender rcHelp' :: String -> Net() rcHelp' sender = msg randomCoinHelp sender rdHelp' :: String -> Net() rdHelp' sender = msg rDieHelp sender echHelp' :: String -> Net() echHelp' sender = msg echoHelp sender wHelp' :: String -> Net() wHelp' sender = msg weatherHelp sender -- dispHelp :: String -> Net() -- dispHelp sender = msgPrivate displayHelp sender
Sahil-yerawar/IRChbot
src/Write.hs
bsd-3-clause
10,064
0
23
2,124
3,247
1,592
1,655
223
2
calcdigit :: (Int -> Int -> Int) -> [Int] -> [Int] -> [Int] calcdigit _ [] [] = [] calcdigit c (m:ms) [] = m : calcdigit c ms [] calcdigit c [] (n:ns) = n : calcdigit c [] ns calcdigit c (m:ms) (n:ns) = (c m n) : calcdigit c ms ns sumdigit :: [Int] -> [Int] -> [Int] sumdigit = calcdigit (+) toDecimal :: Char -> Int toDecimal c = fromEnum c - fromEnum '0' carry :: [Int] -> [Int] carry d = sumdigit d' (0 : m) where (d', m) = unzip . fmap (\n -> n `divMod` 10) $ d main = do s <- readFile "./150digits.txt" let d = foldl sumdigit [] . fmap (fmap toDecimal) $ lines s let e = carry . carry . carry . carry $ d mapM_ (putStr . show) . take 10 . dropWhile (==0) $ e
mskmysht/ProjectEuler
src/Problem13.hs
bsd-3-clause
682
0
14
167
413
212
201
17
1
main = print $ snd . head $ rest where fib' = 1 : 1 : zipWith (+) fib' (tail fib') fib = zip fib' [1 .. ] rest = dropWhile (\(f, index) -> (length . show $ f) < 1000) fib
foreverbell/project-euler-solutions
src/25.hs
bsd-3-clause
184
0
13
55
101
55
46
4
1
-- Solution to Stanford Compilers Course. -- (c) Copyright 2012 Michael Starzinger. All Rights Reserved. module Main (main) where import CoolLexer (scan) import System.Console.GetOpt import System.Environment (getArgs) -- This is a description of the command line options to this program. options :: [OptDescr ()] options = [ Option ['g'] ["garbage"] (NoArg ()) "gabage collection", Option ['o'] ["output"] (ReqArg (const ()) "FILE") "output file" ] -- This is the main program entry for the scanner used as a standalone -- program that reads input from a file and prints resulting tokens. main = do args <- getArgs filename <- do case getOpt RequireOrder options args of (_,[x],[]) -> return x (_,___,__) -> error $ usageInfo "Invalid usage." options input <- readFile filename mapM print $ either error id $ scan input
mstarzinger/coolc
lexer.hs
bsd-3-clause
841
6
14
150
234
125
109
16
2
{-# Language GADTs #-} {-# Language RecordWildCards #-} {-# Language FlexibleContexts #-} {-# Language LambdaCase #-} {-# Language BlockArguments #-} {-# Language RankNTypes #-} {-# Language TemplateHaskell #-} {-# Language QuasiQuotes #-} {-# Language TypeOperators #-} {-# Language DataKinds #-} {-# Language ViewPatterns #-} {-# Language ScopedTypeVariables #-} {-# Language KindSignatures #-} {-# Options_GHC -Wno-unused-foralls #-} module Verifier.SAW.Heapster.TypeChecker ( -- * Checker type Tc, startTc, -- * Checker errors TypeError(..), -- * Checker entry-points tcFunPerm, tcCtx, tcType, tcExpr, tcValPerm, inParsedCtxM, tcAtomicPerms, tcValPermInCtx, tcSortedMbValuePerms, ) where import Control.Monad import Data.Functor.Product import Data.Functor.Constant import GHC.TypeLits (Nat, KnownNat) import GHC.Natural import Data.Binding.Hobbits import Data.Binding.Hobbits.MonadBind import Prettyprinter hiding (comma, space) import qualified Data.Type.RList as RL import Data.Parameterized.Some (Some(Some), mapSome) import qualified Data.Parameterized.Context as Ctx import Data.Parameterized.BoolRepr (BoolRepr(TrueRepr)) import Lang.Crucible.Types import Lang.Crucible.LLVM.MemModel import Lang.Crucible.LLVM.Bytes import Verifier.SAW.Heapster.Permissions import Verifier.SAW.Heapster.CruUtil import Verifier.SAW.Heapster.Located import Verifier.SAW.Heapster.UntypedAST import Verifier.SAW.Heapster.ParsedCtx ---------------------------------------------------------------------- -- * Type-checking environment ---------------------------------------------------------------------- data TcEnv = TcEnv { tcEnvExprVars :: [(String, TypedName)], tcEnvPermEnv :: PermEnv } ---------------------------------------------------------------------- -- * Type errors ---------------------------------------------------------------------- data TypeError = TypeError Pos String deriving Show mkNuMatching [t| TypeError |] instance Closable TypeError where toClosed = unsafeClose instance Liftable TypeError where mbLift = unClosed . mbLift . fmap toClosed ---------------------------------------------------------------------- -- * Type-checking type ---------------------------------------------------------------------- -- | Type-checking computations carrying a 'TcEnv' and which -- can fail. Access the environment with 'tcLocal' and 'tcAsk' -- and fail with 'tcError'. newtype Tc a = Tc { runTc :: TcEnv -> Either TypeError a } -- | Run a type-checking computation given an initial permission -- environment. startTc :: Tc a {- ^ typechecking action -} -> PermEnv {- ^ permission environment -} -> Either TypeError a startTc tc env = runTc tc (TcEnv [] env) -- | 'fmap' derived from 'Monad' instance Functor Tc where fmap = liftM -- | ('<*>') derived from 'Monad' instance Applicative Tc where pure x = Tc \_ -> Right x (<*>) = ap instance Monad Tc where Tc f >>= g = Tc \env -> do x <- f env runTc (g x) env instance MonadBind Tc where mbM m = Tc \env -> case mbMatch $ fmap (`runTc` env) m of [nuMP| Left e |] -> Left (mbLift e) [nuMP| Right x |] -> Right x -- | Run type-checking computation with local changes to the -- type-checking environment. tcLocal :: (TcEnv -> TcEnv) {- ^ environment update -} -> Tc a -> Tc a tcLocal f (Tc k) = Tc (k . f) -- | Get current type-checking environment tcAsk :: Tc TcEnv tcAsk = Tc Right -- | Abort checking with an error message tcError :: Pos {- ^ error location -} -> String {- ^ error message -} -> Tc a tcError p err = Tc (\_ -> Left (TypeError p err)) ---------------------------------------------------------------------- -- * Casting ---------------------------------------------------------------------- -- | Cast a typed value to the requested type or -- raise an error in 'Tc' tcCastTyped :: Pos {- ^ position of expression -} -> TypeRepr a {- ^ target type -} -> Typed f b {- ^ expression -} -> Tc (f a) {- ^ casted expression -} tcCastTyped p tp (Typed tp' f) = case testEquality tp tp' of Just Refl -> pure f Nothing -> tcError p ("Expected type " ++ show tp ++ ", got type " ++ show tp') ---------------------------------------------------------------------- -- * Extending variable environment ---------------------------------------------------------------------- -- | Run a parsing computation in a context extended with an expression variable withExprVar :: String {- ^ identifier -} -> TypeRepr tp {- ^ type of identifer -} -> ExprVar tp {- ^ implementation -} -> Tc a -> Tc a withExprVar str tp x = tcLocal \env -> env { tcEnvExprVars = (str, Some (Typed tp x)) : tcEnvExprVars env } -- | Run a parsing computation in a context extended with 0 or more expression -- variables withExprVars :: RAssign (Constant String) ctx -> CruCtx ctx -> RAssign Name ctx -> Tc a -> Tc a withExprVars MNil CruCtxNil MNil m = m withExprVars (xs :>: Constant x) (CruCtxCons ctx tp) (ns :>: n) m = withExprVars xs ctx ns (withExprVar x tp n m) ---------------------------------------------------------------------- -- * Checking Types ---------------------------------------------------------------------- -- | Check an 'AstType' as a 'TypeRepr' tcType :: AstType -> Tc (Some TypeRepr) tcType t = mapSome unKnownReprObj <$> tcTypeKnown t -- | Check an 'AstType' and build a @'KnownRepr' 'TypeRepr'@ instance for it tcTypeKnown :: AstType -> Tc (Some (KnownReprObj TypeRepr)) tcTypeKnown t = case t of TyUnit {} -> pure (Some (mkKnownReprObj UnitRepr)) TyBool {} -> pure (Some (mkKnownReprObj BoolRepr)) TyNat {} -> pure (Some (mkKnownReprObj NatRepr)) TyLifetime {} -> pure (Some (mkKnownReprObj LifetimeRepr)) TyRwModality {} -> pure (Some (mkKnownReprObj RWModalityRepr)) TyPermList {} -> pure (Some (mkKnownReprObj PermListRepr)) TyBV p n -> withPositive p "Zero bitvector width not allowed" n \w -> pure (Some (mkKnownReprObj (BVRepr w))) TyLlvmPtr p n -> withPositive p "Zero LLVM Ptr width not allowed" n \w -> pure (Some (mkKnownReprObj (LLVMPointerRepr w))) TyLlvmFrame p n -> withPositive p "Zero LLVM Frame width not allowed" n \w -> pure (Some (mkKnownReprObj (LLVMFrameRepr w))) TyLlvmShape p n -> withPositive p "Zero LLVM Shape width not allowed" n \w -> pure (Some (mkKnownReprObj (LLVMShapeRepr w))) TyLlvmBlock p n -> withPositive p "Zero LLVM Block width not allowed" n \w -> pure (Some (mkKnownReprObj (LLVMBlockRepr w))) TyStruct _ fs -> do fs1 <- traverse tcTypeKnown fs let fs2 = foldl structAdd (Some (mkKnownReprObj Ctx.empty)) fs1 case fs2 of Some xs@KnownReprObj -> pure (Some (mkKnownReprObj (StructRepr (unKnownReprObj xs)))) TyPerm _ x -> do Some tp@KnownReprObj <- tcTypeKnown x pure (Some (mkKnownReprObj (ValuePermRepr (unKnownReprObj tp)))) -- | Helper function for building struct type lists structAdd :: Some (KnownReprObj (Ctx.Assignment TypeRepr)) -> Some (KnownReprObj TypeRepr) -> Some (KnownReprObj (Ctx.Assignment TypeRepr)) structAdd (Some acc@KnownReprObj) (Some x@KnownReprObj) = Some (mkKnownReprObj (Ctx.extend (unKnownReprObj acc) (unKnownReprObj x))) ---------------------------------------------------------------------- -- * Checking Expressions ---------------------------------------------------------------------- -- | Parse an identifier as an expression variable of a specific type tcVar :: TypeRepr a {- ^ expected type -} -> Pos {- ^ identifier position -} -> String {- ^ identifier -} -> Tc (ExprVar a) tcVar ty p name = do Some tn <- tcTypedName p name tcCastTyped p ty tn -- | Check a valid identifier string as an expression variable tcTypedName :: Pos {- ^ identifier position -} -> String {- ^ identifier -} -> Tc TypedName tcTypedName p name = do env <- tcAsk case lookup name (tcEnvExprVars env) of Nothing -> tcError p ("Unknown variable:" ++ name) Just stn -> pure stn -- | Check an 'AstExpr' as a 'PermExpr' with a known type. tcKExpr :: KnownRepr TypeRepr a => AstExpr -> Tc (PermExpr a) tcKExpr = tcExpr knownRepr -- | Check an 'AstExpr' as a 'PermExpr' with a given type. -- This is a top-level entry-point to the checker that will -- resolve variables. tcExpr :: TypeRepr a -> AstExpr -> Tc (PermExpr a) tcExpr ty (ExVar p name Nothing Nothing) = PExpr_Var <$> tcVar ty p name tcExpr tp@(LLVMShapeRepr w) (ExVar p name (Just args) Nothing) = do env <- tcAsk case lookupNamedShape (tcEnvPermEnv env) name of Just (SomeNamedShape nmsh) | Just Refl <- testEquality w (natRepr nmsh) -> do sub <- tcExprs p (namedShapeArgs nmsh) args pure (PExpr_NamedShape Nothing Nothing nmsh sub) Just (SomeNamedShape nmsh) -> tcError p $ renderDoc $ sep [ pretty "Named shape" <+> pretty name <+> pretty "is of incorrect type" , pretty "Expected:" <+> permPretty emptyPPInfo tp , pretty "Found:" <+> permPretty emptyPPInfo (LLVMShapeRepr (natRepr nmsh)) ] Nothing -> tcError p ("Unknown shape name: " ++ name) tcExpr tp@(ValuePermRepr sub_tp) (ExVar p name (Just args) Nothing) = do env <- tcAsk case lookupNamedPermName (tcEnvPermEnv env) name of Just (SomeNamedPermName npn) | Just Refl <- testEquality (namedPermNameType npn) sub_tp -> do arg_exprs <- tcExprs p (namedPermNameArgs npn) args pure (PExpr_ValPerm $ ValPerm_Named npn arg_exprs NoPermOffset) Just (SomeNamedPermName npn) -> tcError p $ renderDoc $ sep [ pretty "Named permission" <+> pretty (namedPermNameName npn) <+> pretty "is of incorrect type" , pretty "Expected:" <+> permPretty emptyPPInfo tp , pretty "Found:" <+> permPretty emptyPPInfo (namedPermNameType npn) ] Nothing -> tcError p ("Unknown shape name: " ++ name) tcExpr _ (ExVar p _ Just{} _) = tcError p "Unexpected variable instantiation" tcExpr _ (ExVar p _ _ Just{}) = tcError p "Unexpected variable offset" tcExpr UnitRepr e = tcUnit e tcExpr NatRepr e = tcNat e tcExpr (BVRepr w) e = withKnownNat w (normalizeBVExpr <$> tcBV e) tcExpr (StructRepr fs) e = tcStruct fs e tcExpr LifetimeRepr e = tcLifetimeLit e tcExpr (LLVMPointerRepr w) e = withKnownNat w (tcLLVMPointer w e) tcExpr FunctionHandleRepr{} e = tcError (pos e) "Expected functionhandle" -- no literals tcExpr PermListRepr e = tcError (pos e) "Expected permlist" -- no literals tcExpr RWModalityRepr e = tcRWModality e tcExpr (ValuePermRepr t) e = permToExpr <$> tcValPerm t e tcExpr (LLVMShapeRepr w) e = withKnownNat w (tcLLVMShape e) tcExpr (IntrinsicRepr s _) e = tcError (pos e) ("Expected intrinsic type: " ++ show s) -- reprs that we explicitly do not support tcExpr BoolRepr e = tcError (pos e) "Expected boolean" tcExpr IntegerRepr e = tcError (pos e) "Expected integerl" tcExpr AnyRepr e = tcError (pos e) "Expected any type" tcExpr RealValRepr e = tcError (pos e) "Expected realval" tcExpr ComplexRealRepr e = tcError (pos e) "Expected realval" tcExpr CharRepr e = tcError (pos e) "Expected char" tcExpr RecursiveRepr {} e = tcError (pos e) "Expected recursive-value" tcExpr FloatRepr {} e = tcError (pos e) "Expected float" tcExpr IEEEFloatRepr {} e = tcError (pos e) "Expected ieeefloat" tcExpr StringRepr {} e = tcError (pos e) "Expected string" tcExpr MaybeRepr {} e = tcError (pos e) "Expected maybe" tcExpr VectorRepr {} e = tcError (pos e) "Expected vector" tcExpr VariantRepr {} e = tcError (pos e) "Expected variant" tcExpr ReferenceRepr {} e = tcError (pos e) "Expected reference" tcExpr WordMapRepr {} e = tcError (pos e) "Expected wordmap" tcExpr StringMapRepr {} e = tcError (pos e) "Expected stringmap" tcExpr SymbolicArrayRepr {} e = tcError (pos e) "Expected symbolicarray" tcExpr SymbolicStructRepr{} e = tcError (pos e) "Expected symbolicstruct" tcExpr SequenceRepr {} e = tcError (pos e) "Expected sequencerepr" -- | Check for a unit literal tcUnit :: AstExpr -> Tc (PermExpr UnitType) tcUnit ExUnit{} = pure PExpr_Unit tcUnit e = tcError (pos e) "Expected unit" -- | Check for a nat literal tcNat :: AstExpr -> Tc (PermExpr NatType) tcNat (ExNat _ i) = pure (PExpr_Nat i) tcNat e = tcError (pos e) "Expected integer" -- | Check for a bitvector expression tcBV :: (KnownNat w, 1 <= w) => AstExpr -> Tc (PermExpr (BVType w)) tcBV (ExAdd _ x y) = bvAdd <$> tcBV x <*> tcBV y tcBV e = tcBVFactor e -- | Check for a bitvector factor. This is limited to -- variables, constants, and multiplication by a constant. tcBVFactor :: (KnownNat w, 1 <= w) => AstExpr -> Tc (PermExpr (BVType w)) tcBVFactor (ExNat _ i) = pure (bvInt (fromIntegral i)) tcBVFactor (ExMul _ (ExNat _ i) (ExVar p name Nothing Nothing)) = do Some tn <- tcTypedName p name bvMult i . PExpr_Var <$> tcCastTyped p knownRepr tn tcBVFactor (ExMul _ (ExVar p name Nothing Nothing) (ExNat _ i)) = do Some tn <- tcTypedName p name bvMult i . PExpr_Var <$> tcCastTyped p knownRepr tn tcBVFactor (ExVar p name Nothing Nothing) = do Some tn <- tcTypedName p name PExpr_Var <$> tcCastTyped p knownRepr tn tcBVFactor e = tcError (pos e) "Expected BV factor" -- | Check for a struct literal tcStruct :: CtxRepr fs -> AstExpr -> Tc (PermExpr (StructType fs)) tcStruct ts (ExStruct p es) = PExpr_Struct <$> tcExprs p (mkCruCtx ts) es tcStruct _ e = tcError (pos e) "Expected struct" -- | Check a list of expressions. In case of arity issues -- an arity error is reported at the given position. tcExprs :: Pos {- ^ position for arity error -} -> CruCtx fs {- ^ expected types -} -> [AstExpr] {- ^ expressions -} -> Tc (PermExprs fs) tcExprs p tys es = tcExprs' p tys (reverse es) -- | Helper for 'tcExprs' tcExprs' :: Pos -> CruCtx fs -> [AstExpr] -> Tc (PermExprs fs) tcExprs' _ CruCtxNil [] = pure PExprs_Nil tcExprs' p (CruCtxCons xs x) (y:ys) = do zs <- tcExprs' p xs ys z <- tcExpr x y pure (zs :>: z) tcExprs' p _ _ = tcError p "Bad arity" -- | Parse a sequence of permissions of some given types tcValuePerms :: Pos -> RAssign TypeRepr tys -> [AstExpr] -> Tc (RAssign ValuePerm tys) tcValuePerms p tys es = tcValuePerms' p tys (reverse es) -- | Helper for 'tcValuePerms' tcValuePerms' :: Pos -> RAssign TypeRepr tps -> [AstExpr] -> Tc (RAssign ValuePerm tps) tcValuePerms' _ MNil [] = pure MNil tcValuePerms' p (xs :>: x) (y:ys) = do zs <- tcValuePerms' p xs ys z <- tcValPerm x y pure (zs :>: z) tcValuePerms' p _ _ = tcError p "Bad arity" -- | Check an rwmodality literal tcRWModality :: AstExpr -> Tc (PermExpr RWModalityType) tcRWModality ExRead {} = pure PExpr_Read tcRWModality ExWrite{} = pure PExpr_Write tcRWModality e = tcError (pos e) "Expected rwmodality" -- | Check an optional lifetime expression. Default to @always@ if missing. tcOptLifetime :: Maybe AstExpr -> Tc (PermExpr LifetimeType) tcOptLifetime Nothing = pure PExpr_Always tcOptLifetime (Just e) = tcKExpr e -- | Check a lifetime literal tcLifetimeLit :: AstExpr -> Tc (PermExpr LifetimeType) tcLifetimeLit ExAlways{} = pure PExpr_Always tcLifetimeLit e = tcError (pos e) "Expected lifetime" -- | Check an LLVM shape expression tcLLVMShape :: (KnownNat w, 1 <= w) => AstExpr -> Tc (PermExpr (LLVMShapeType w)) tcLLVMShape (ExOrSh _ x y) = PExpr_OrShape <$> tcKExpr x <*> tcKExpr y tcLLVMShape (ExExSh _ var vartype sh) = do Some ktp'@KnownReprObj <- tcTypeKnown vartype fmap PExpr_ExShape $ mbM $ nu \z -> withExprVar var (unKnownReprObj ktp') z (tcKExpr sh) tcLLVMShape (ExSeqSh _ x y) = PExpr_SeqShape <$> tcKExpr x <*> tcKExpr y tcLLVMShape ExEmptySh{} = pure PExpr_EmptyShape tcLLVMShape (ExEqSh _ len v) = PExpr_EqShape <$> tcKExpr len <*> tcKExpr v tcLLVMShape (ExPtrSh _ maybe_l maybe_rw sh) = PExpr_PtrShape <$> traverse tcKExpr maybe_l <*> traverse tcKExpr maybe_rw <*> tcKExpr sh tcLLVMShape (ExFieldSh _ w fld) = PExpr_FieldShape <$> tcLLVMFieldShape_ w fld tcLLVMShape (ExArraySh _ len stride sh) = PExpr_ArrayShape <$> tcKExpr len <*> (Bytes . fromIntegral <$> tcNatural stride) <*> tcKExpr sh tcLLVMShape e = tcError (pos e) "Expected shape" -- | Field and array helper for 'tcLLVMShape' tcLLVMFieldShape_ :: forall w. (KnownNat w, 1 <= w) => Maybe AstExpr -> AstExpr -> Tc (LLVMFieldShape w) tcLLVMFieldShape_ Nothing e = tcLLVMFieldShape (knownNat :: NatRepr w) e tcLLVMFieldShape_ (Just w) e = do Some (Pair nr LeqProof) <- tcPositive w withKnownNat nr (tcLLVMFieldShape nr e) -- | Check a single field or array element shape tcLLVMFieldShape :: forall (w :: Nat) (v :: Nat). (KnownNat w, 1 <= w) => NatRepr w -> AstExpr -> Tc (LLVMFieldShape v) tcLLVMFieldShape nr e = LLVMFieldShape <$> tcValPerm (LLVMPointerRepr nr) e -- | Check a LLVM pointer expression tcLLVMPointer :: (KnownNat w, 1 <= w) => NatRepr w -> AstExpr -> Tc (PermExpr (LLVMPointerType w)) tcLLVMPointer _ (ExLlvmWord _ e) = PExpr_LLVMWord <$> tcKExpr e tcLLVMPointer w (ExAdd _ (ExVar p name Nothing Nothing) off) = PExpr_LLVMOffset <$> tcVar (LLVMPointerRepr w) p name <*> tcKExpr off tcLLVMPointer _ e = tcError (pos e) "Expected llvmpointer" -- | Check a value permission of a known type in a given context tcValPermInCtx :: ParsedCtx ctx -> TypeRepr a -> AstExpr -> Tc (Mb ctx (ValuePerm a)) tcValPermInCtx ctx tp = inParsedCtxM ctx . const . tcValPerm tp -- | Parse a value permission of a known type tcValPerm :: TypeRepr a -> AstExpr -> Tc (ValuePerm a) tcValPerm _ ExTrue{} = pure ValPerm_True tcValPerm ty (ExOr _ x y) = ValPerm_Or <$> tcValPerm ty x <*> tcValPerm ty y tcValPerm ty (ExEq _ e) = ValPerm_Eq <$> tcExpr ty e tcValPerm ty (ExExists _ var vartype e) = do Some ktp'@KnownReprObj <- tcTypeKnown vartype fmap ValPerm_Exists $ mbM $ nu \z -> withExprVar var (unKnownReprObj ktp') z (tcValPerm ty e) tcValPerm ty (ExVar p n (Just argEs) maybe_off) = do env <- tcEnvPermEnv <$> tcAsk case lookupNamedPermName env n of Just (SomeNamedPermName rpn) | Just Refl <- testEquality (namedPermNameType rpn) ty -> do args <- tcExprs p (namedPermNameArgs rpn) argEs off <- tcPermOffset ty p maybe_off pure (ValPerm_Named rpn args off) Just (SomeNamedPermName rpn) -> tcError p $ renderDoc $ sep [ pretty "Named permission" <+> pretty n <+> pretty "is of incorrect type" , pretty "Expected:" <+> permPretty emptyPPInfo ty , pretty "Found:" <+> permPretty emptyPPInfo (namedPermNameType rpn) ] Nothing -> tcError p ("Unknown named permission '" ++ n ++ "'") tcValPerm ty (ExVar p n Nothing off) = ValPerm_Var <$> tcVar (ValuePermRepr ty) p n <*> tcPermOffset ty p off tcValPerm ty e = ValPerm_Conj <$> tcAtomicPerms ty e -- | Parse a @*@-separated list of atomic permissions tcAtomicPerms :: TypeRepr a -> AstExpr -> Tc [AtomicPerm a] tcAtomicPerms ty (ExMul _ x y) = (++) <$> tcAtomicPerms ty x <*> tcAtomicPerms ty y tcAtomicPerms ty e = pure <$> tcAtomicPerm ty e -- | Parse an atomic permission of a specific type tcAtomicPerm :: TypeRepr a -> AstExpr -> Tc (AtomicPerm a) tcAtomicPerm ty (ExVar p n (Just argEs) maybe_off) = do env <- tcEnvPermEnv <$> tcAsk case lookupNamedPermName env n of Just (SomeNamedPermName npn) | Just Refl <- testEquality (namedPermNameType npn) ty , TrueRepr <- nameIsConjRepr npn -> do args <- tcExprs p (namedPermNameArgs npn) argEs off <- tcPermOffset ty p maybe_off return (Perm_NamedConj npn args off) Just (SomeNamedPermName npn) | Just Refl <- testEquality (namedPermNameType npn) ty -> tcError p ("Non-conjoinable permission name '" ++ n ++ "' used in conjunctive context") Just (SomeNamedPermName _) -> tcError p ("Permission name '" ++ n ++ "' has incorrect type") Nothing -> tcError p ("Unknown permission name '" ++ n ++ "'") tcAtomicPerm (LLVMPointerRepr w) e = withKnownNat w (tcPointerAtomic e) tcAtomicPerm (LLVMFrameRepr w) e = withKnownNat w (tcFrameAtomic e) tcAtomicPerm (LLVMBlockRepr w) e = withKnownNat w (tcBlockAtomic e) tcAtomicPerm (StructRepr tys) e = tcStructAtomic tys e tcAtomicPerm LifetimeRepr e = tcLifetimeAtomic e tcAtomicPerm _ e = tcError (pos e) "Expected perm" -- | Build a field permission using an 'LLVMFieldShape' fieldPermFromShape :: (KnownNat w, 1 <= w) => PermExpr RWModalityType -> PermExpr LifetimeType -> PermExpr (BVType w) -> LLVMFieldShape w -> AtomicPerm (LLVMPointerType w) fieldPermFromShape rw l off (LLVMFieldShape p) = Perm_LLVMField $ LLVMFieldPerm rw l off p -- | Check an LLVM pointer atomic permission expression tcPointerAtomic :: (KnownNat w, 1 <= w) => AstExpr -> Tc (AtomicPerm (LLVMPointerType w)) tcPointerAtomic (ExPtr _ l rw off sz c) = fieldPermFromShape <$> tcKExpr rw <*> tcOptLifetime l <*> tcKExpr off <*> tcLLVMFieldShape_ sz c tcPointerAtomic (ExArray _ l rw off len stride sh) = Perm_LLVMArray <$> tcArrayAtomic l rw off len stride sh tcPointerAtomic (ExMemblock _ l rw off len sh) = Perm_LLVMBlock <$> tcMemblock l rw off len sh tcPointerAtomic (ExFree _ x ) = Perm_LLVMFree <$> tcKExpr x tcPointerAtomic (ExLlvmFunPtr _ n w f) = tcFunPtrAtomic n w f tcPointerAtomic (ExEqual _ x y) = Perm_BVProp <$> (BVProp_Eq <$> tcKExpr x <*> tcKExpr y) tcPointerAtomic (ExNotEqual _ x y) = Perm_BVProp <$> (BVProp_Neq <$> tcKExpr x <*> tcKExpr y) tcPointerAtomic (ExLessThan _ x y) = Perm_BVProp <$> (BVProp_ULt <$> tcKExpr x <*> tcKExpr y) tcPointerAtomic (ExLessEqual _ x y) = Perm_BVProp <$> (BVProp_ULeq <$> tcKExpr x <*> tcKExpr y) tcPointerAtomic e = tcError (pos e) "Expected pointer perm" -- | Check a function pointer permission literal tcFunPtrAtomic :: (KnownNat w, 1 <= w) => AstExpr -> AstExpr -> AstFunPerm -> Tc (AtomicPerm (LLVMPointerType w)) tcFunPtrAtomic x y fun = do Some args_no <- mkNatRepr <$> tcNatural x Some (Pair w' LeqProof) <- tcPositive y Some args <- pure (cruCtxReplicate args_no (LLVMPointerRepr w')) SomeFunPerm fun_perm <- tcFunPerm args (LLVMPointerRepr w') fun pure (mkPermLLVMFunPtr knownNat fun_perm) -- | Check a memblock permission literal tcMemblock :: (KnownNat w, 1 <= w) => Maybe AstExpr -> AstExpr -> AstExpr -> AstExpr -> AstExpr -> Tc (LLVMBlockPerm w) tcMemblock l rw off len sh = do llvmBlockLifetime <- tcOptLifetime l llvmBlockRW <- tcKExpr rw llvmBlockOffset <- tcKExpr off llvmBlockLen <- tcKExpr len llvmBlockShape <- tcKExpr sh pure LLVMBlockPerm{..} -- | Check an atomic array permission literal tcArrayAtomic :: (KnownNat w, 1 <= w) => Maybe AstExpr -> AstExpr -> AstExpr -> AstExpr -> AstExpr -> AstExpr -> Tc (LLVMArrayPerm w) tcArrayAtomic l rw off len stride sh = LLVMArrayPerm <$> tcKExpr rw <*> tcOptLifetime l <*> tcKExpr off <*> tcKExpr len <*> (Bytes . fromIntegral <$> tcNatural stride) <*> tcKExpr sh <*> pure [] -- | Check a frame permission literal tcFrameAtomic :: (KnownNat w, 1 <= w) => AstExpr -> Tc (AtomicPerm (LLVMFrameType w)) tcFrameAtomic (ExLlvmFrame _ xs) = Perm_LLVMFrame <$> traverse (\(e,i) -> (,) <$> tcKExpr e <*> pure (fromIntegral i)) xs tcFrameAtomic e = tcError (pos e) "Expected llvmframe perm" -- | Check a struct permission literal tcStructAtomic :: CtxRepr tys -> AstExpr -> Tc (AtomicPerm (StructType tys)) tcStructAtomic tys (ExStruct p es) = Perm_Struct <$> tcValuePerms p (assignToRList tys) es tcStructAtomic _ e = tcError (pos e) "Expected struct perm" -- | Check a block shape permission literal tcBlockAtomic :: (KnownNat w, 1 <= w) => AstExpr -> Tc (AtomicPerm (LLVMBlockType w)) tcBlockAtomic (ExShape _ e) = Perm_LLVMBlockShape <$> tcKExpr e tcBlockAtomic e = tcError (pos e) "Expected llvmblock perm" -- | Check a lifetime permission literal tcLifetimeAtomic :: AstExpr -> Tc (AtomicPerm LifetimeType) tcLifetimeAtomic (ExLOwned _ ls x y) = do Some x' <- tcLOwnedPerms x Some y' <- tcLOwnedPerms y ls' <- mapM tcKExpr ls pure (Perm_LOwned ls' x' y') tcLifetimeAtomic (ExLCurrent _ l) = Perm_LCurrent <$> tcOptLifetime l tcLifetimeAtomic (ExLFinished _) = return Perm_LFinished tcLifetimeAtomic e = tcError (pos e) "Expected lifetime perm" -- | Helper for lowned permission checking tcLOwnedPerms :: [(Located String,AstExpr)] -> Tc (Some LOwnedPerms) tcLOwnedPerms [] = pure (Some MNil) tcLOwnedPerms ((Located p n,e):xs) = do Some (Typed tp x) <- tcTypedName p n perm <- tcValPerm tp e lop <- case varAndPermLOwnedPerm (VarAndPerm x perm) of Just lop -> return lop Nothing -> tcError (pos e) ("Not a valid lifetime ownership permission: " ++ permPrettyString emptyPPInfo perm) Some lops <- tcLOwnedPerms xs pure (Some (lops :>: lop)) -- | Helper for checking permission offsets tcPermOffset :: TypeRepr a -> Pos -> Maybe AstExpr -> Tc (PermOffset a) tcPermOffset _ _ Nothing = pure NoPermOffset tcPermOffset (LLVMPointerRepr w) _ (Just i) = withKnownNat w (LLVMPermOffset <$> tcKExpr i) tcPermOffset _ p _ = tcError p "Unexpected offset" -- | Check for a number literal tcNatural :: AstExpr -> Tc Natural tcNatural (ExNat _ i) = pure i tcNatural e = tcError (pos e) "Expected integer literal" -- | Ensure a natural nubmer is positive withPositive :: Pos {- ^ location of literal -} -> String {- ^ error message -} -> Natural {- ^ number -} -> (forall w. (1 <= w, KnownNat w) => NatRepr w -> Tc a) {- ^ continuation -} -> Tc a withPositive p err n k = case someNatGeq1 n of Nothing -> tcError p err Just (Some (Pair w LeqProof)) -> withKnownNat w (k w) -- | Check for a positive number literal tcPositive :: AstExpr -> Tc (Some (Product NatRepr (LeqProof 1))) tcPositive e = do i <- tcNatural e withPositive (pos e) "positive required" i \w -> pure (Some (Pair w LeqProof)) -- | Check a typing context @x1:tp1, x2:tp2, ...@ tcCtx :: [(Located String, AstType)] -> Tc (Some ParsedCtx) tcCtx [] = pure (Some emptyParsedCtx) tcCtx ((n,t):xs) = preconsSomeParsedCtx (locThing n) <$> tcType t <*> tcCtx xs -- | Check a sequence @x1:p1, x2:p2, ...@ of variables and their permissions, -- where each variable occurs at most once. The input list says which variables -- can occur and which have already been seen. Return a sequence of the -- permissions in the same order as the input list of variables. tcSortedValuePerms :: VarPermSpecs ctx -> [(Located String, AstExpr)] -> Tc (ValuePerms ctx) tcSortedValuePerms var_specs [] = pure (varSpecsToPerms var_specs) tcSortedValuePerms var_specs ((Located p var, x):xs) = do Some (Typed tp n) <- tcTypedName p var perm <- tcValPerm tp x var_specs' <- tcSetVarSpecs p var n perm var_specs tcSortedValuePerms var_specs' xs -- | Check a sequence @x1:p1, x2:p2, ...@ of variables and their permissions, -- and sort the result into a 'ValuePerms' in a multi-binding that is in the -- same order as the 'ParsedCtx' supplied on input tcSortedMbValuePerms :: ParsedCtx ctx -> [(Located String, AstExpr)] -> Tc (MbValuePerms ctx) tcSortedMbValuePerms ctx perms = inParsedCtxM ctx \ns -> tcSortedValuePerms (mkVarPermSpecs ns) perms -- | Check a function permission of the form -- -- > (x1:tp1, ...). arg1:p1, ... -o -- > (y1:tp1', ..., ym:tpm'). arg1:p1', ..., argn:pn', ret:p_ret -- -- for some arbitrary context @x1:tp1, ...@ of ghost variables tcFunPerm :: CruCtx args -> TypeRepr ret -> AstFunPerm -> Tc (SomeFunPerm args ret) tcFunPerm args ret (AstFunPerm _ untyCtx ins untyCtxOut outs) = do Some ghosts_ctx@(ParsedCtx _ ghosts) <- tcCtx untyCtx Some gouts_ctx@(ParsedCtx _ gouts) <- tcCtx untyCtxOut let args_ctx = mkArgsParsedCtx args perms_in_ctx = appendParsedCtx ghosts_ctx args_ctx perms_out_ctx = appendParsedCtx (appendParsedCtx ghosts_ctx args_ctx) (consParsedCtx "ret" ret gouts_ctx) perms_in <- tcSortedMbValuePerms perms_in_ctx ins perms_out <- tcSortedMbValuePerms perms_out_ctx outs pure (SomeFunPerm (FunPerm ghosts args gouts ret perms_in perms_out)) ---------------------------------------------------------------------- -- * Parsing Permission Sets and Function Permissions ---------------------------------------------------------------------- -- | Helper type for 'parseValuePerms' that represents whether a pair @x:p@ has -- been parsed yet for a specific variable @x@ and, if so, contains that @p@ data VarPermSpec a = VarPermSpec (Name a) (Maybe (ValuePerm a)) -- | A sequence of variables @x@ and what pairs @x:p@ have been parsed so far type VarPermSpecs = RAssign VarPermSpec -- | Build a 'VarPermSpecs' from a list of names mkVarPermSpecs :: RAssign Name ctx -> VarPermSpecs ctx mkVarPermSpecs = RL.map (\n -> VarPermSpec n Nothing) -- | Find a 'VarPermSpec' for a particular variable findVarPermSpec :: Name (a :: CrucibleType) -> VarPermSpecs ctx -> Maybe (Member ctx a) findVarPermSpec _ MNil = Nothing findVarPermSpec n (_ :>: VarPermSpec n' _) | Just Refl <- testEquality n n' = Just Member_Base findVarPermSpec n (specs :>: _) = Member_Step <$> findVarPermSpec n specs -- | Try to set the permission for a variable in a 'VarPermSpecs' list, raising -- a parse error if the variable already has a permission or is one of the -- expected variables tcSetVarSpecs :: Pos -> String -> Name tp -> ValuePerm tp -> VarPermSpecs ctx -> Tc (VarPermSpecs ctx) tcSetVarSpecs p var n perm var_specs = case findVarPermSpec n var_specs of Nothing -> tcError p ("Unknown variable: " ++ var) Just memb -> case RL.get memb var_specs of VarPermSpec _ Nothing -> pure (RL.modify memb (const (VarPermSpec n (Just perm))) var_specs) _ -> tcError p ("Variable " ++ var ++ " occurs more than once!") -- | Convert a 'VarPermSpecs' sequence to a sequence of permissions, using the -- @true@ permission for any variables without permissions varSpecsToPerms :: VarPermSpecs ctx -> ValuePerms ctx varSpecsToPerms MNil = ValPerms_Nil varSpecsToPerms (var_specs :>: VarPermSpec _ (Just p)) = ValPerms_Cons (varSpecsToPerms var_specs) p varSpecsToPerms (var_specs :>: VarPermSpec _ Nothing) = ValPerms_Cons (varSpecsToPerms var_specs) ValPerm_True -- | Run a parsing computation inside a name-binding for expressions variables -- given by a 'ParsedCtx'. Returning the results inside a name-binding. inParsedCtxM :: NuMatching a => ParsedCtx ctx -> (RAssign Name ctx -> Tc a) -> Tc (Mb ctx a) inParsedCtxM (ParsedCtx ids tps) f = mbM (nuMulti (cruCtxProxies tps) \ns -> withExprVars ids tps ns (f ns))
GaloisInc/saw-script
heapster-saw/src/Verifier/SAW/Heapster/TypeChecker.hs
bsd-3-clause
31,814
0
21
7,121
9,342
4,607
4,735
-1
-1
{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module IPoint (IPoint, point) where import Graphics.Gloss (Point) -- Integer version of Graphics.Gloss.Point, which is Float-based. type IPoint = (Int, Int) instance Num IPoint where (+) (x1, y1) (x2, y2) = (x1 + x2, y1 + y2) (-) (x1, y1) (x2, y2) = (x1 - x2, y1 - y2) (*) (x1, y1) (x2, y2) = (x1 * x2, y1 * y2) signum (x, y) = (signum x, signum y) abs (x, y) = (abs x, abs y) negate (x, y) = (negate x, negate y) fromInteger x = (fromInteger x, fromInteger x) point :: IPoint -> Point point (x, y) = (fromIntegral x, fromIntegral y)
kqr/pacmANN
src/IPoint.hs
bsd-3-clause
683
0
7
189
292
169
123
15
1
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE PackageImports #-} {-# OPTIONS_GHC -fno-warn-overlapping-patterns #-} module Repr.Stringy ( showsAST, parseAST, tryParseAST , showsType, showsScheme ) where import Core.Ast import Core.Transmogrify import Data.Function import Control.Category ( (<<<) ) import Data.Functor.Identity import Text.ParserCombinators.Parsec hiding ( State(..) ) import Text.ParserCombinators.Parsec.Error ( Message(..), errorMessages ) import Control.Applicative hiding ( Alternative(..), many ) import "monads-fd" Control.Monad.State import Data.Generics -- in {{{ cleanSpaces :: Parser a -> Parser a cleanSpaces p = spaces *> p <* spaces bracketed :: Parser a -> Parser b -> Parser c -> Parser c bracketed open close p = open *> cleanSpaces p <* close paren'd :: Parser a -> Parser a paren'd = bracketed (char '(') (char ')') pIdent :: Parser Ident pIdent = cleanSpaces ( ((ident.) . (:)) <$> letter <*> many alphaNum <?> "variable" ) lambda :: Parser () lambda = () <$ oneOf "\\|λ" pTerm, pAtom, pLambda, pVar, pLet, pTermEND :: Parser AST pVar = var bAst <$> pIdent pTerm = foldl1 (app bAst) <$> many1 ( pAtom <?> "term" ) pAtom = spaces *> ( paren'd pTerm <|> pLambda <|> pLet <|> pVar ) <* spaces -- closing space?? pLambda = do vars <- lambda *> many1 pIdent <* char '.' flip (foldr (lam bAst)) vars <$> pTerm pLet = flip (foldr (uncurry $ le7 bAst)) <$> (try (string "let") *> many1 (try binder)) <*> pTerm where binder = cleanSpaces ( paren'd ((,) <$> pIdent <* string "=" <*> pTerm) ) pTermEND = pTerm <* eof parseAST :: SourceName -> String -> Either ParseError AST parseAST n s = parse pTermEND n s tryParseAST :: SourceName -> String -> Either ParseError (Maybe AST) tryParseAST n s = case parseAST n s of Left e | unexpectedEOF e -> Right Nothing | otherwise -> Left e ast -> Just <$> ast unexpectedEOF :: ParseError -> Bool unexpectedEOF = any unexpected . errorMessages where unexpected (SysUnExpect "") = True unexpected _ = False instance Read AST where readsPrec _ = either (const []) (:[]) . parse p "<literal>" where p = (,) <$> pTermEND <*> getInput -- }}} -- out lam {{{ bracket :: String -> String -> ShowS -> ShowS bracket open close between = (open ++) <<< between <<< (close ++) parens :: ShowS -> ShowS parens = bracket "(" ")" showsASTParens, showsAST :: ASTAnn f => Term f -> ShowS showsASTParens t@(ast -> Var _) = showsAST t showsASTParens t = parens (showsAST t) showsAST (ast -> Var x) = shows x showsAST (ast -> App l r) = ( case ast l of App _ _ -> showsAST l _ -> showsASTParens l ) <<< (' ' :) <<< showsASTParens r showsAST (ast -> Lam x t) = ('λ' :) <<< shows x <<< fix ( \f t -> case ast t of Lam x t' -> shows x <<< f t' _ -> ('.' :) <<< showsAST t ) t showsAST t@(ast -> Let _ _ _) = ("let " ++) <<< fix ( \f t -> case ast t of Let x e t' -> binder x e <<< f t' _ -> showsAST t ) t where binder x e = parens ( shows x <<< (" = "++) <<< showsAST e ) <<< (' ' :) instance (Data (Term f), ASTAnn f) => Show (Term f) where showsPrec _ = showsAST . cleanIdents -- }}} -- {{{ out ty showsTypeParens, showsType :: Type -> ShowS showsTypeParens t@(TyVar _) = showsType t showsTypeParens t@(TyCon _ []) = showsType t showsTypeParens t = parens (showsType t) showsType (TyVar i) = shows i showsType (Arrow t1 t2) = showsTypeParens t1 <<< (" -> " ++) <<< case t2 of (Arrow _ _) -> showsType t2 _ -> showsTypeParens t2 showsType (TyCon c []) = (c ++) showsType (TyCon c ts) = (c ++) <<< foldr (\s k -> (' ':) . s . k) id (map showsTypeParens ts) showsScheme (Scheme [] t) = showsType t showsScheme (Scheme as t) = ("forall " ++) <<< foldr (\a -> ((shows a <<< (' ':)).)) id as <<< (". " ++) <<< showsType t instance Show Type where showsPrec _ = showsType . cleanIdents instance Show TypeScheme where showsPrec _ = showsScheme . cleanIdents -- }}} -- {{{ ident render data IdentRenderState = IRS { candidate, takenGen0, takenGen1 :: [Ident] , replaceMap :: [(Ident, Ident)] } type Shw a = State IdentRenderState a runShw :: State IdentRenderState c -> c runShw sh = (fst . fix) (\ ~(_, s) -> runState sh IRS { candidate = [ ident [x] | x <- ['a'..] ] , takenGen1 = takenGen0 s , takenGen0 = [] , replaceMap = [] } ) cleanIdentifier :: Ident -> Shw Ident cleanIdentifier t@(Id _) = modify (\s -> s { takenGen0 = t : takenGen0 s }) >> return t cleanIdentifier t@(Idn _ _) = do bundle <- get case t `lookup` replaceMap bundle of Just t' -> return t' Nothing -> do let (c0:cands) = dropWhile (`elem` takenGen1 bundle) (candidate bundle) put bundle { candidate = cands , replaceMap = (t, c0) : replaceMap bundle } return c0 cleanIdents :: (Data t) => t -> t cleanIdents = runShw . everywhereM (mkM cleanIdentifier) -- }}} -- vim:set fdm=marker:
pqwy/redex
src/Repr/Stringy.hs
bsd-3-clause
5,597
0
17
1,693
2,041
1,072
969
-1
-1
-- | This modules contains short names for common ops. -- To try and compete with numpy/matlab in shortness. -- Although those still win the battle -- due to their task specific syntax[sugar].. module Data.NumKell.Aliases ( (##), hn, sa, tf, tt ) where import Data.HList (HCons(..), HNil(..)) import Data.NumKell.Slice (SAll(..)) import Data.NumKell.SumAxes (TTrue(..), TFalse(..)) infixr 2 ## (##) :: a -> b -> HCons a b (##) = HCons hn :: HNil hn = HNil sa :: SAll sa = SAll tf :: TFalse tf = TFalse tt :: TTrue tt = TTrue
yairchu/numkell
src/Data/NumKell/Aliases.hs
bsd-3-clause
538
0
7
106
160
104
56
16
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module GitHub ( startApp ) where import Control.Monad.Logger import Control.Monad.Reader import Control.Monad.Trans.Either import Data.Aeson import Database.Persist import Database.Persist.Sqlite import Database.Persist.TH import GHC.Generics import Network.Wai import Network.Wai.Handler.Warp import Servant share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Organization name String deriving Generic Repository name String organizationId OrganizationId deriving Generic |] instance ToJSON Organization instance ToJSON Repository instance FromJSON Organization instance FromJSON Repository instance FromText (Key Organization) where fromText = Just . OrganizationKey . SqlBackendKey . Prelude.read . show instance FromText (Key Repository) where fromText = Just . RepositoryKey . SqlBackendKey . Prelude.read . show type Create a = ReqBody '[JSON] a :> Post '[JSON] a type Read a = Capture "id" (Key a) :> Get '[JSON] a type ReadAll a = Get '[JSON] [a] type Update a = Capture "id" (Key a) :> ReqBody '[JSON] a :> Put '[JSON] () type Delete a = Capture "id" (Key a) :> Servant.Delete '[JSON] () type Crud a = Create a :<|> GitHub.Read a :<|> ReadAll a :<|> GitHub.Update a :<|> GitHub.Delete a type GitHub = "organizations" :> Crud Organization :<|> "repositories" :> Crud Repository type GitHubT = ReaderT ConnectionPool (EitherT ServantErr IO) class (PersistEntity a, SqlBackend ~ PersistEntityBackend a) => HasCrud a where create :: a -> GitHubT a create organization = do entity <- runDB $ insertEntity organization return $ entityVal entity read :: Key a -> GitHubT a read entityId = do maybeEntity <- runDB $ get entityId case maybeEntity of Nothing -> lift $ left err404 Just entity -> return entity readAll :: GitHubT [a] readAll = do entities <- runDB $ selectList [] [] return $ map entityVal entities update :: Key a -> a -> GitHubT () update entityId = runDB . replace entityId delete :: Key a -> GitHubT () delete = runDB . Database.Persist.Sqlite.delete instance HasCrud Organization instance HasCrud Repository startApp :: IO () startApp = do pool <- createPool runSqlPool (runMigration migrateAll) pool run 8080 $ app pool createPool :: IO ConnectionPool createPool = runStdoutLoggingT $ createSqlitePool "db" 1 app :: ConnectionPool -> Application app = serve gitHub . readServer gitHub :: Proxy GitHub gitHub = Proxy readServer :: ConnectionPool -> Server GitHub readServer pool = enter (runReaderTNat pool) server server :: ServerT GitHub GitHubT server = crud :<|> crud crud :: HasCrud a => (a -> GitHubT a) :<|> (Key a -> GitHubT a) :<|> GitHubT [a] :<|> (Key a -> a -> GitHubT ()) :<|> (Key a -> GitHubT ()) crud = create :<|> GitHub.read :<|> readAll :<|> GitHub.update :<|> GitHub.delete runDB :: SqlPersistT IO a -> GitHubT a runDB query = ask >>= liftIO . runSqlPool query
sestrella/servant-persistent
src/GitHub.hs
bsd-3-clause
3,739
0
14
958
1,042
533
509
96
1
{-# LANGUAGE OverloadedStrings #-} module Arc where import Graphics.Blank import Wiki -- (578,200) main :: IO () main = blankCanvas 3000 $ \ context -> do send context $ do let centerX = width context / 2; let centerY = height context / 2; let radius = 75; let startingAngle = 1.1 * pi let endingAngle = 1.9 * pi lineWidth 15 strokeStyle "black" beginPath() arc(centerX - 50, centerY, radius, startingAngle, endingAngle, False) stroke() beginPath() strokeStyle "blue" arc(centerX + 50, centerY, radius, startingAngle, endingAngle, True) stroke() wiki $ snapShot context "images/Arc.png" wiki $ close context
ku-fpg/blank-canvas
wiki-suite/Arc.hs
bsd-3-clause
738
0
16
225
249
120
129
23
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Types.FormQuote where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative #endif import Control.Monad (mzero) import Data.Aeson import Data.Set (Set) import qualified Data.Text as T import Data.Typeable import Types.Slug data FormQuote = FormQuote { formQuoteSlug :: Slug , formQuoteTitle :: T.Text , formQuoteContents :: T.Text , formQuoteCategoryList :: Set Slug } deriving (Eq, Ord, Show, Typeable) instance ToJSON FormQuote where toJSON (FormQuote slug title contents categories) = object [ "slug" .= slug , "title" .= title , "contents" .= contents , "categories" .= categories ] instance FromJSON FormQuote where parseJSON (Object v) = FormQuote <$> v .: "slug" <*> v .: "title" <*> v .: "contents" <*> v .: "categories" parseJSON _ = mzero
meoblast001/quotum-snap
src/Types/FormQuote.hs
mit
1,065
0
13
309
240
136
104
32
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.CognitoIdentity.DescribeIdentity -- 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) -- -- Returns metadata related to the given identity, including when the -- identity was created and any associated linked logins. -- -- You must use AWS Developer credentials to call this API. -- -- /See:/ <http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_DescribeIdentity.html AWS API Reference> for DescribeIdentity. module Network.AWS.CognitoIdentity.DescribeIdentity ( -- * Creating a Request describeIdentity , DescribeIdentity -- * Request Lenses , diIdentityId -- * Destructuring the Response , identityDescription , IdentityDescription -- * Response Lenses , idLastModifiedDate , idCreationDate , idLogins , idIdentityId ) where import Network.AWS.CognitoIdentity.Types import Network.AWS.CognitoIdentity.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Input to the 'DescribeIdentity' action. -- -- /See:/ 'describeIdentity' smart constructor. newtype DescribeIdentity = DescribeIdentity' { _diIdentityId :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeIdentity' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'diIdentityId' describeIdentity :: Text -- ^ 'diIdentityId' -> DescribeIdentity describeIdentity pIdentityId_ = DescribeIdentity' { _diIdentityId = pIdentityId_ } -- | A unique identifier in the format REGION:GUID. diIdentityId :: Lens' DescribeIdentity Text diIdentityId = lens _diIdentityId (\ s a -> s{_diIdentityId = a}); instance AWSRequest DescribeIdentity where type Rs DescribeIdentity = IdentityDescription request = postJSON cognitoIdentity response = receiveJSON (\ s h x -> eitherParseJSON x) instance ToHeaders DescribeIdentity where toHeaders = const (mconcat ["X-Amz-Target" =# ("AWSCognitoIdentityService.DescribeIdentity" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON DescribeIdentity where toJSON DescribeIdentity'{..} = object (catMaybes [Just ("IdentityId" .= _diIdentityId)]) instance ToPath DescribeIdentity where toPath = const "/" instance ToQuery DescribeIdentity where toQuery = const mempty
fmapfmapfmap/amazonka
amazonka-cognito-identity/gen/Network/AWS/CognitoIdentity/DescribeIdentity.hs
mpl-2.0
3,218
0
12
727
383
234
149
56
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} module Test.Blackbox ( tests , haTests , ssltests , startTestServers ) where -------------------------------------------------------------------------------- import Control.Applicative ((<$>)) import Control.Arrow (first) import Control.Concurrent (MVar, ThreadId, forkIO, forkIOWithUnmask, killThread, newEmptyMVar, putMVar, takeMVar, threadDelay, tryPutMVar) import Control.Exception (bracket, bracketOnError, finally, mask_) import Control.Monad (forM_, forever, void, when) import qualified Data.ByteString.Base16 as B16 import Data.ByteString.Builder (byteString) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy.Char8 as L import Data.CaseInsensitive (CI) import qualified Data.CaseInsensitive as CI import Data.List (sort) import Data.Monoid (Monoid (mconcat, mempty)) import qualified Network.Http.Client as HTTP import qualified Network.Http.Types as HTTP import qualified Network.Socket as N import qualified Network.Socket.ByteString as NB import Prelude (Bool (..), Eq (..), IO, Int, Maybe (..), Show (..), String, concat, concatMap, const, dropWhile, elem, flip, fromIntegral, fst, head, id, map, mapM_, maybe, min, not, null, otherwise, putStrLn, replicate, return, reverse, uncurry, ($), ($!), (*), (++), (.), (^)) import qualified Prelude ------------------------------------------------------------------------------ #ifdef OPENSSL import qualified OpenSSL.Session as SSL #endif import qualified System.IO.Streams as Streams import System.Timeout (timeout) import Test.Framework (Test, TestOptions' (topt_maximum_generated_tests), plusTestOptions) import Test.Framework.Providers.HUnit (testCase) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.HUnit hiding (Test, path) import Test.QuickCheck (Arbitrary (arbitrary)) import Test.QuickCheck.Monadic (forAllM, monadicIO) import qualified Test.QuickCheck.Monadic as QC import qualified Test.QuickCheck.Property as QC ------------------------------------------------------------------------------ import Snap.Internal.Debug (debug) import Snap.Internal.Http.Server.Session (httpAcceptLoop, snapToServerHandler) import qualified Snap.Internal.Http.Server.Socket as Sock import qualified Snap.Internal.Http.Server.TLS as TLS import qualified Snap.Internal.Http.Server.Types as Types import Snap.Test.Common (ditchHeaders, eatException, expectExceptionBeforeTimeout, recvAll, timeoutIn, withSock) import Test.Common.Rot13 (rot13) import Test.Common.TestHandler (testHandler) ------------------------------------------------------------------------------ tests :: Int -> [Test] tests port = map (\f -> f False port "") testFunctions ssltests :: Maybe Int -> [Test] ssltests = maybe [] httpsTests where httpsTests port = map (\f -> f True port sslname) testFunctions sslname = "ssl/" haTests :: Int -> [Test] haTests port = [ testHaProxy port , testHaProxyLocal port , testHaProxyFileServe port ] testFunctions :: [Bool -> Int -> String -> Test] testFunctions = [ testPong -- FIXME: waiting on http-enumerator patch for HEAD behaviour -- , testHeadPong , testEcho , testRot13 , testSlowLoris , testBlockingRead , testBigResponse , testPartial , testFileUpload , testTimeoutTickle , testHasDateHeader , testServerHeader , testFileServe , testTimelyRedirect , testChunkedHead ] ------------------------------------------------------------------------------ startServer :: Types.ServerConfig hookState -> IO a -> (a -> N.Socket) -> (a -> Types.AcceptFunc) -> IO (ThreadId, Int, MVar ()) startServer config bind projSock afunc = bracketOnError bind (N.close . projSock) forkServer where forkServer a = do mv <- newEmptyMVar port <- fromIntegral <$> N.socketPort (projSock a) tid <- forkIO $ eatException $ (httpAcceptLoop (snapToServerHandler testHandler) config (afunc a) `finally` putMVar mv ()) return (tid, port, mv) ------------------------------------------------------------------------------ -- | Returns the thread the server is running in as well as the port it is -- listening on. data TestServerType = NormalTest | ProxyTest | SSLTest deriving (Show) startTestSocketServer :: TestServerType -> IO (ThreadId, Int, MVar ()) startTestSocketServer serverType = do putStrLn $ "Blackbox: starting " ++ show serverType ++ " server" case serverType of NormalTest -> startServer emptyServerConfig bindSock id Sock.httpAcceptFunc ProxyTest -> startServer emptyServerConfig bindSock id Sock.haProxyAcceptFunc SSLTest -> startServer emptyServerConfig bindSSL fst (uncurry TLS.httpsAcceptFunc) where #if MIN_VERSION_network(2,7,0) anyport = N.defaultPort #else anyport = N.aNY_PORT #endif bindSSL = do sockCtx <- TLS.bindHttps "127.0.0.1" (fromIntegral anyport) "test/cert.pem" False "test/key.pem" #ifdef OPENSSL -- Set client code not to verify HTTP.modifyContextSSL $ \ctx -> do SSL.contextSetVerificationMode ctx SSL.VerifyNone return ctx #endif return sockCtx bindSock = Sock.bindSocket "127.0.0.1" (fromIntegral anyport) logAccess !_ !_ !_ = return () logError !_ = return () onStart !_ = return () onParse !_ !_ = return () onUserHandlerFinished !_ !_ !_ = return () onDataFinished !_ !_ !_ = return () onExceptionHook !_ !_ = return () onEscape !_ = return () emptyServerConfig = Types.ServerConfig logAccess logError onStart onParse onUserHandlerFinished onDataFinished onExceptionHook onEscape "localhost" 6 False 1 ------------------------------------------------------------------------------ waitabit :: IO () waitabit = threadDelay $ 2*seconds ------------------------------------------------------------------------------ seconds :: Int seconds = (10::Int) ^ (6::Int) ------------------------------------------------------------------------------ fetch :: ByteString -> IO ByteString fetch url = HTTP.get url HTTP.concatHandler' ------------------------------------------------------------------------------ fetchWithHeaders :: ByteString -> IO (ByteString, [(CI ByteString, ByteString)]) fetchWithHeaders url = HTTP.get url h where h resp is = do let hdrs = map (first CI.mk) $ HTTP.retrieveHeaders $ HTTP.getHeaders resp body <- HTTP.concatHandler' resp is return (body, hdrs) ------------------------------------------------------------------------------ slowTestOptions :: Bool -> TestOptions' Maybe slowTestOptions ssl = if ssl then mempty { topt_maximum_generated_tests = Just 75 } else mempty { topt_maximum_generated_tests = Just 300 } ------------------------------------------------------------------------------ -- FIXME: waiting on http-enumerator patch for HEAD behaviour -- headPong :: Bool -> Int -> IO ByteString -- headPong ssl port = do -- let uri = (if ssl then "https" else "http") -- ++ "://127.0.0.1:" ++ show port ++ "/echo" -- req0 <- HTTP.parseUrl uri -- let req = req0 { HTTP.method = "HEAD" } -- rsp <- HTTP.httpLbs req -- return $ S.concat $ L.toChunks $ HTTP.responseBody rsp ------------------------------------------------------------------------------ -- FIXME: waiting on http-enumerator patch for HEAD behaviour -- testHeadPong :: Bool -> Int -> String -> Test -- testHeadPong ssl port name = testCase (name ++ "blackbox/pong/HEAD") $ do -- doc <- headPong ssl port -- assertEqual "pong HEAD response" "" doc ------------------------------------------------------------------------------ -- TODO: doesn't work w/ ssl testBlockingRead :: Bool -> Int -> String -> Test testBlockingRead ssl port name = testCase (name ++ "blackbox/testBlockingRead") $ if ssl then return () else runIt where runIt = withSock port $ \sock -> do m <- timeout (60*seconds) $ go sock maybe (assertFailure "timeout") (const $ return ()) m go sock = do NB.sendAll sock "GET /" waitabit NB.sendAll sock "pong HTTP/1.1\r\n" NB.sendAll sock "Host: 127.0.0.1\r\n" NB.sendAll sock "Content-Length: 0\r\n" NB.sendAll sock "Connection: close\r\n\r\n" resp <- recvAll sock let s = head $ ditchHeaders $ S.lines resp assertEqual "pong response" "PONG" s ------------------------------------------------------------------------------ -- TODO: this one doesn't work w/ SSL testSlowLoris :: Bool -> Int -> String -> Test testSlowLoris ssl port name = testCase (name ++ "blackbox/slowloris") $ if ssl then return () else withSock port go where go sock = do NB.sendAll sock "POST /echo HTTP/1.1\r\n" NB.sendAll sock "Host: 127.0.0.1\r\n" NB.sendAll sock "Content-Length: 2500000\r\n" NB.sendAll sock "Connection: close\r\n\r\n" b <- expectExceptionBeforeTimeout (loris sock) 30 assertBool "didn't catch slow loris attack" b loris sock = forever $ do NB.sendAll sock "." waitabit ------------------------------------------------------------------------------ testRot13 :: Bool -> Int -> String -> Test testRot13 ssl port name = plusTestOptions (slowTestOptions ssl) $ testProperty (name ++ "blackbox/rot13") $ monadicIO $ forAllM arbitrary prop where prop txt = do let uri = (if ssl then "https" else "http") ++ "://127.0.0.1:" ++ show port ++ "/rot13" doc <- QC.run $ HTTP.post (S.pack uri) "text/plain" (Streams.write (Just $ byteString txt)) HTTP.concatHandler' QC.assert $ txt == rot13 doc ------------------------------------------------------------------------------ doPong :: Bool -> Int -> IO ByteString doPong ssl port = do debug "getting URI" let !uri = (if ssl then "https" else "http") ++ "://127.0.0.1:" ++ show port ++ "/pong" debug $ "URI is: '" ++ uri ++ "', calling simpleHttp" rsp <- fetch $ S.pack uri debug $ "response was " ++ show rsp return rsp ------------------------------------------------------------------------------ testPong :: Bool -> Int -> String -> Test testPong ssl port name = testCase (name ++ "blackbox/pong") $ do doc <- doPong ssl port assertEqual "pong response" "PONG" doc ------------------------------------------------------------------------------ testHasDateHeader :: Bool -> Int -> String -> Test testHasDateHeader ssl port name = testCase (name ++ "blackbox/hasDateHdr") $ do let !url = (if ssl then "https" else "http") ++ "://127.0.0.1:" ++ show port ++ "/pong" (rsp, hdrs) <- fetchWithHeaders $ S.pack url let hasDate = "date" `elem` map fst hdrs when (not hasDate) $ do putStrLn "server not sending dates:" forM_ hdrs $ \(k,v) -> S.putStrLn $ S.concat [CI.original k, ": ", v] assertBool "has date" hasDate assertEqual "pong response" "PONG" rsp ------------------------------------------------------------------------------ testChunkedHead :: Bool -> Int -> String -> Test testChunkedHead ssl port name = testCase (name ++ "blackbox/chunkedHead") $ if ssl then return () else withSock port go where go sock = do NB.sendAll sock $ S.concat [ "HEAD /chunked HTTP/1.1\r\n" , "Host: localhost\r\n" , "\r\n" ] s <- NB.recv sock 4096 assertBool (concat [ "no body: received '" , S.unpack s , "'" ]) $ isOK s split x l | S.null x = reverse l | otherwise = let (a, b) = S.break (== '\r') x b' = S.drop 2 b in split b' (a : l) isOK s = let lns = split s [] lns' = Prelude.drop 1 $ dropWhile (not . S.null) lns in null lns' ------------------------------------------------------------------------------ -- TODO: no ssl here -- test server's ability to trap/recover from IO errors testPartial :: Bool -> Int -> String -> Test testPartial ssl port name = testCase (name ++ "blackbox/testPartial") $ if ssl then return () else runIt where runIt = do m <- timeout (60*seconds) go maybe (assertFailure "timeout") (const $ return ()) m go = do withSock port $ \sock -> NB.sendAll sock "GET /pong HTTP/1.1\r\n" doc <- doPong ssl port assertEqual "pong response" "PONG" doc ------------------------------------------------------------------------------ -- TODO: no ssl here -- test server's ability to trap/recover from IO errors testTimelyRedirect :: Bool -> Int -> String -> Test testTimelyRedirect ssl port name = testCase (name ++ "blackbox/testTimelyRedirect") $ if ssl then return () else runIt where runIt = do m <- timeout (5*seconds) go maybe (assertFailure "timeout") (const $ return ()) m go = do withSock port $ \sock -> do NB.sendAll sock $ S.concat [ "GET /redirect HTTP/1.1\r\n" , "Host: localhost\r\n\r\n" ] resp <- NB.recv sock 100000 assertBool "wasn't code 302" $ S.isInfixOf "302" resp assertBool "didn't have content length" $ S.isInfixOf "content-length: 0" resp ------------------------------------------------------------------------------ -- TODO: no ssl testBigResponse :: Bool -> Int -> String -> Test testBigResponse ssl port name = testCase (name ++ "blackbox/testBigResponse") $ if ssl then return () else runIt where runIt = withSock port $ \sock -> do m <- timeout (120*seconds) $ go sock maybe (assertFailure "timeout") (const $ return ()) m go sock = do NB.sendAll sock "GET /bigresponse HTTP/1.1\r\n" NB.sendAll sock "Host: 127.0.0.1\r\n" NB.sendAll sock "Content-Length: 0\r\n" NB.sendAll sock "Connection: close\r\n\r\n" let body = S.replicate 4000000 '.' resp <- recvAll sock let s = head $ ditchHeaders $ S.lines resp assertBool "big response" $ body == s ------------------------------------------------------------------------------ testHaProxy :: Int -> Test testHaProxy port = testCase "blackbox/haProxy" runIt where runIt = withSock port $ \sock -> do m <- timeout (120*seconds) $ go sock maybe (assertFailure "timeout") (const $ return ()) m go sock = do NB.sendAll sock $ S.concat [ "PROXY TCP4 1.2.3.4 5.6.7.8 1234 5678\r\n" , "GET /remoteAddrPort HTTP/1.1\r\n" , "Host: 127.0.0.1\r\n" , "Content-Length: 0\r\n" , "Connection: close\r\n\r\n" ] resp <- recvAll sock let s = head $ ditchHeaders $ S.lines resp when (s /= "1.2.3.4:1234") $ S.putStrLn s assertEqual "haproxy response" "1.2.3.4:1234" s ------------------------------------------------------------------------------ testHaProxyFileServe :: Int -> Test testHaProxyFileServe port = testCase "blackbox/haProxyFileServe" runIt where runIt = withSock port $ \sock -> do m <- timeout (120*seconds) $ go sock maybe (assertFailure "timeout") (const $ return ()) m go sock = do NB.sendAll sock $ S.concat [ "PROXY UNKNOWN\r\n" , "GET /fileserve/hello.txt HTTP/1.1\r\n" , "Host: 127.0.0.1\r\n" , "Content-Length: 0\r\n" , "Connection: close\r\n\r\n" ] resp <- recvAll sock let s = head $ ditchHeaders $ S.lines resp assertEqual "haproxy response" "hello world" s ------------------------------------------------------------------------------ testHaProxyLocal :: Int -> Test testHaProxyLocal port = testCase "blackbox/haProxyLocal" runIt where #if MIN_VERSION_network(2,7,0) anyport = N.defaultPort #else anyport = N.aNY_PORT #endif remoteAddrServer :: N.Socket -> MVar (Maybe String) -> (forall a . IO a -> IO a) -> IO () remoteAddrServer ssock mvar restore = timeoutIn 10 $ flip finally (tryPutMVar mvar Nothing) $ bracket (restore $ N.accept ssock) (eatException . N.close . fst) (\(_, peer) -> putMVar mvar $! Just $! show peer) slurp p input = timeoutIn 10 $ withSock p $ \sock -> do NB.sendAll sock input recvAll sock determineSourceInterfaceAddr = timeoutIn 10 $ bracket (Sock.bindSocket "127.0.0.1" (fromIntegral anyport)) (eatException . N.close) (\ssock -> do mv <- newEmptyMVar svrPort <- fromIntegral <$> N.socketPort ssock bracket (mask_ $ forkIOWithUnmask $ remoteAddrServer ssock mv) (eatException . killThread) (const $ do void $ slurp svrPort "" (Just s) <- takeMVar mv return $! fst $ S.breakEnd (==':') $ S.pack s)) runIt = do saddr <- determineSourceInterfaceAddr resp <- slurp port $ S.concat [ "PROXY UNKNOWN\r\n" , "GET /remoteAddrPort HTTP/1.1\r\n" , "Host: 127.0.0.1\r\n" , "Content-Length: 0\r\n" , "Connection: close\r\n\r\n" ] let s = head $ ditchHeaders $ S.lines resp when (not $ S.isPrefixOf saddr s) $ S.putStrLn s assertBool "haproxy response" $ S.isPrefixOf saddr s ------------------------------------------------------------------------------ -- This test checks two things: -- -- 1. that the timeout tickling logic works -- 2. that "flush" is passed along through a gzip operation. testTimeoutTickle :: Bool -> Int -> String -> Test testTimeoutTickle ssl port name = testCase (name ++ "blackbox/timeout/tickle") $ do let uri = (if ssl then "https" else "http") ++ "://127.0.0.1:" ++ show port ++ "/timeout/tickle" doc <- fetch $ S.pack uri let expected = S.concat $ replicate 10 ".\n" assertEqual "response equal" expected doc ------------------------------------------------------------------------------ testFileServe :: Bool -> Int -> String -> Test testFileServe ssl port name = testCase (name ++ "blackbox/fileserve") $ do let uri = (if ssl then "https" else "http") ++ "://127.0.0.1:" ++ show port ++ "/fileserve/hello.txt" doc <- fetch $ S.pack uri let expected = "hello world\n" assertEqual "response equal" expected doc ------------------------------------------------------------------------------ testFileUpload :: Bool -> Int -> String -> Test testFileUpload ssl port name = plusTestOptions (slowTestOptions ssl) $ testProperty (name ++ "blackbox/upload") $ QC.mapSize (if ssl then min 100 else min 300) $ monadicIO $ forAllM arbitrary prop where boundary = "boundary-jdsklfjdsalkfjadlskfjldskjfldskjfdsfjdsklfldksajfl" prefix = [ "--" , boundary , "\r\n" , "content-disposition: form-data; name=\"submit\"\r\n" , "\r\nSubmit\r\n" ] body kvps = L.concat $ prefix ++ concatMap part kvps ++ suffix where part (k,v) = [ "--" , boundary , "\r\ncontent-disposition: attachment; filename=\"" , k , "\"\r\nContent-Type: text/plain\r\n\r\n" , v , "\r\n" ] suffix = [ "--", boundary, "--\r\n" ] hdrs = [ ("Content-type", S.concat $ [ "multipart/form-data; boundary=" ] ++ L.toChunks boundary) ] b16 (k,v) = (ne $ e k, e v) where ne s = if L.null s then "file" else s e s = L.fromChunks [ B16.encode $ S.concat $ L.toChunks s ] response kvps = L.concat $ [ "Param:\n" , "submit\n" , "Value:\n" , "Submit\n\n" ] ++ concatMap responseKVP kvps responseKVP (k,v) = [ "File:\n" , k , "\nValue:\n" , v , "\n\n" ] prop kvps' = do let kvps = sort $ map b16 kvps' let uri = S.pack $ concat [ if ssl then "https" else "http" , "://127.0.0.1:" , show port , "/upload/handle" ] let txt = response kvps doc0 <- QC.run $ HTTP.withConnection (HTTP.establishConnection uri) $ \conn -> do req <- HTTP.buildRequest $ do HTTP.http HTTP.POST uri mapM_ (uncurry HTTP.setHeader) hdrs HTTP.sendRequest conn req (Streams.write $ Just $ mconcat $ map byteString $ L.toChunks $ body kvps) HTTP.receiveResponse conn HTTP.concatHandler' let doc = L.fromChunks [doc0] when (txt /= doc) $ QC.run $ do L.putStrLn "expected:" L.putStrLn "----------------------------------------" L.putStrLn txt L.putStrLn "----------------------------------------" L.putStrLn "\ngot:" L.putStrLn "----------------------------------------" L.putStrLn doc L.putStrLn "----------------------------------------" QC.assert $ txt == doc ------------------------------------------------------------------------------ testEcho :: Bool -> Int -> String -> Test testEcho ssl port name = plusTestOptions (slowTestOptions ssl) $ testProperty (name ++ "blackbox/echo") $ QC.mapSize (if ssl then min 100 else min 300) $ monadicIO $ forAllM arbitrary prop where prop txt = do let uri = (if ssl then "https" else "http") ++ "://127.0.0.1:" ++ show port ++ "/echo" doc <- QC.run $ HTTP.post (S.pack uri) "text/plain" (Streams.write (Just $ byteString txt)) HTTP.concatHandler' QC.assert $ txt == doc ------------------------------------------------------------------------------ testServerHeader :: Bool -> Int -> String -> Test testServerHeader ssl port name = testCase (name ++ "blackbox/server-header") $ do let uri = (if ssl then "https" else "http") ++ "://127.0.0.1:" ++ show port ++ "/server-header" HTTP.get (S.pack uri) $ \resp _ -> do let serverHeader = HTTP.getHeader resp "server" assertEqual "server header" (Just "foo") serverHeader ------------------------------------------------------------------------------ startTestServers :: IO ((ThreadId, Int, MVar ()), (ThreadId, Int, MVar ()), Maybe (ThreadId, Int, MVar ())) startTestServers = do x <- startTestSocketServer NormalTest y <- startTestSocketServer ProxyTest #ifdef OPENSSL z <- startTestSocketServer SSLTest return (x, y, Just z) #else return (x, y, Nothing) #endif
sopvop/snap-server
test/Test/Blackbox.hs
bsd-3-clause
26,260
2
21
8,766
5,883
3,033
2,850
467
4
-- | standalone solver -- command line arguments: -- depth, width, instance module Main where import PCProblem.Family import PCProblem.Param import System import IO main = runit $ Param { alpha = "0123" , paare = 4 , breite = 6 , nah = 0 , fern = 100 , viel = 10000 }
florianpilz/autotool
src/PCP.hs
gpl-2.0
320
2
7
105
72
47
25
12
1
{-# LANGUAGE BangPatterns , FlexibleContexts , FlexibleInstances , ScopedTypeVariables , UnboxedTuples , UndecidableInstances , UnicodeSyntax #-} strictHead ∷ G.Bitstream (Packet d) ⇒ Bitstream d → Bool {-# RULES "head → strictHead" [1] ∀(v ∷ G.Bitstream (Packet d) ⇒ Bitstream d). head v = strictHead v #-} {-# INLINE strictHead #-} strictHead (Bitstream _ v) = head (SV.head v)
mpickering/ghc-exactprint
tests/examples/ghc8/UnicodeRules.hs
bsd-3-clause
421
0
8
85
58
29
29
14
1
{-# LANGUAGE BangPatterns #-} module Throughput.BlazeBuilder ( serialize ) where import Data.Monoid import qualified Data.ByteString.Lazy as L import Blaze.ByteString.Builder import Throughput.Utils serialize :: Int -> Int -> Endian -> Int -> L.ByteString serialize wordSize chunkSize end = toLazyByteString . case (wordSize, chunkSize, end) of (1, 1,_) -> writeByteN1 (1, 2,_) -> writeByteN2 (1, 4,_) -> writeByteN4 (1, 8,_) -> writeByteN8 (1, 16, _) -> writeByteN16 (2, 1, Big) -> writeWord16N1Big (2, 2, Big) -> writeWord16N2Big (2, 4, Big) -> writeWord16N4Big (2, 8, Big) -> writeWord16N8Big (2, 16, Big) -> writeWord16N16Big (2, 1, Little) -> writeWord16N1Little (2, 2, Little) -> writeWord16N2Little (2, 4, Little) -> writeWord16N4Little (2, 8, Little) -> writeWord16N8Little (2, 16, Little) -> writeWord16N16Little (2, 1, Host) -> writeWord16N1Host (2, 2, Host) -> writeWord16N2Host (2, 4, Host) -> writeWord16N4Host (2, 8, Host) -> writeWord16N8Host (2, 16, Host) -> writeWord16N16Host (4, 1, Big) -> writeWord32N1Big (4, 2, Big) -> writeWord32N2Big (4, 4, Big) -> writeWord32N4Big (4, 8, Big) -> writeWord32N8Big (4, 16, Big) -> writeWord32N16Big (4, 1, Little) -> writeWord32N1Little (4, 2, Little) -> writeWord32N2Little (4, 4, Little) -> writeWord32N4Little (4, 8, Little) -> writeWord32N8Little (4, 16, Little) -> writeWord32N16Little (4, 1, Host) -> writeWord32N1Host (4, 2, Host) -> writeWord32N2Host (4, 4, Host) -> writeWord32N4Host (4, 8, Host) -> writeWord32N8Host (4, 16, Host) -> writeWord32N16Host (8, 1, Host) -> writeWord64N1Host (8, 2, Host) -> writeWord64N2Host (8, 4, Host) -> writeWord64N4Host (8, 8, Host) -> writeWord64N8Host (8, 16, Host) -> writeWord64N16Host (8, 1, Big) -> writeWord64N1Big (8, 2, Big) -> writeWord64N2Big (8, 4, Big) -> writeWord64N4Big (8, 8, Big) -> writeWord64N8Big (8, 16, Big) -> writeWord64N16Big (8, 1, Little) -> writeWord64N1Little (8, 2, Little) -> writeWord64N2Little (8, 4, Little) -> writeWord64N4Little (8, 8, Little) -> writeWord64N8Little (8, 16, Little) -> writeWord64N16Little ------------------------------------------------------------------------ ------------------------------------------------------------------------ writeByteN1 bytes = loop 0 0 where loop !s !n | n == bytes = mempty | otherwise = fromWord8 s `mappend` loop (s+1) (n+1) writeByteN2 = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord8 (s+0) `mappend` writeWord8 (s+1)) `mappend` loop (s+2) (n-2) writeByteN4 = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord8 (s+0) `mappend` writeWord8 (s+1) `mappend` writeWord8 (s+2) `mappend` writeWord8 (s+3)) `mappend` loop (s+4) (n-4) writeByteN8 = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord8 (s+0) `mappend` writeWord8 (s+1) `mappend` writeWord8 (s+2) `mappend` writeWord8 (s+3) `mappend` writeWord8 (s+4) `mappend` writeWord8 (s+5) `mappend` writeWord8 (s+6) `mappend` writeWord8 (s+7)) `mappend` loop (s+8) (n-8) writeByteN16 = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord8 (s+0) `mappend` writeWord8 (s+1) `mappend` writeWord8 (s+2) `mappend` writeWord8 (s+3) `mappend` writeWord8 (s+4) `mappend` writeWord8 (s+5) `mappend` writeWord8 (s+6) `mappend` writeWord8 (s+7) `mappend` writeWord8 (s+8) `mappend` writeWord8 (s+9) `mappend` writeWord8 (s+10) `mappend` writeWord8 (s+11) `mappend` writeWord8 (s+12) `mappend` writeWord8 (s+13) `mappend` writeWord8 (s+14) `mappend` writeWord8 (s+15)) `mappend` loop (s+16) (n-16) ------------------------------------------------------------------------ -- Big endian, word16 writes writeWord16N1Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16be (s+0)) `mappend` loop (s+1) (n-1) writeWord16N2Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16be (s+0) `mappend` writeWord16be (s+1)) `mappend` loop (s+2) (n-2) writeWord16N4Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16be (s+0) `mappend` writeWord16be (s+1) `mappend` writeWord16be (s+2) `mappend` writeWord16be (s+3)) `mappend` loop (s+4) (n-4) writeWord16N8Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16be (s+0) `mappend` writeWord16be (s+1) `mappend` writeWord16be (s+2) `mappend` writeWord16be (s+3) `mappend` writeWord16be (s+4) `mappend` writeWord16be (s+5) `mappend` writeWord16be (s+6) `mappend` writeWord16be (s+7)) `mappend` loop (s+8) (n-8) writeWord16N16Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16be (s+0) `mappend` writeWord16be (s+1) `mappend` writeWord16be (s+2) `mappend` writeWord16be (s+3) `mappend` writeWord16be (s+4) `mappend` writeWord16be (s+5) `mappend` writeWord16be (s+6) `mappend` writeWord16be (s+7) `mappend` writeWord16be (s+8) `mappend` writeWord16be (s+9) `mappend` writeWord16be (s+10) `mappend` writeWord16be (s+11) `mappend` writeWord16be (s+12) `mappend` writeWord16be (s+13) `mappend` writeWord16be (s+14) `mappend` writeWord16be (s+15)) `mappend` loop (s+16) (n-16) ------------------------------------------------------------------------ -- Little endian, word16 writes writeWord16N1Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite (writeWord16le (s+0)) `mappend` loop (s+1) (n-1) writeWord16N2Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16le (s+0) `mappend` writeWord16le (s+1)) `mappend` loop (s+2) (n-2) writeWord16N4Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16le (s+0) `mappend` writeWord16le (s+1) `mappend` writeWord16le (s+2) `mappend` writeWord16le (s+3)) `mappend` loop (s+4) (n-4) writeWord16N8Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16le (s+0) `mappend` writeWord16le (s+1) `mappend` writeWord16le (s+2) `mappend` writeWord16le (s+3) `mappend` writeWord16le (s+4) `mappend` writeWord16le (s+5) `mappend` writeWord16le (s+6) `mappend` writeWord16le (s+7)) `mappend` loop (s+8) (n-8) writeWord16N16Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16le (s+0) `mappend` writeWord16le (s+1) `mappend` writeWord16le (s+2) `mappend` writeWord16le (s+3) `mappend` writeWord16le (s+4) `mappend` writeWord16le (s+5) `mappend` writeWord16le (s+6) `mappend` writeWord16le (s+7) `mappend` writeWord16le (s+8) `mappend` writeWord16le (s+9) `mappend` writeWord16le (s+10) `mappend` writeWord16le (s+11) `mappend` writeWord16le (s+12) `mappend` writeWord16le (s+13) `mappend` writeWord16le (s+14) `mappend` writeWord16le (s+15)) `mappend` loop (s+16) (n-16) ------------------------------------------------------------------------ -- Host endian, unaligned, word16 writes writeWord16N1Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16host (s+0)) `mappend` loop (s+1) (n-1) writeWord16N2Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16host (s+0) `mappend` writeWord16host (s+1)) `mappend` loop (s+2) (n-2) writeWord16N4Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16host (s+0) `mappend` writeWord16host (s+1) `mappend` writeWord16host (s+2) `mappend` writeWord16host (s+3)) `mappend` loop (s+4) (n-4) writeWord16N8Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16host (s+0) `mappend` writeWord16host (s+1) `mappend` writeWord16host (s+2) `mappend` writeWord16host (s+3) `mappend` writeWord16host (s+4) `mappend` writeWord16host (s+5) `mappend` writeWord16host (s+6) `mappend` writeWord16host (s+7)) `mappend` loop (s+8) (n-8) writeWord16N16Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord16host (s+0) `mappend` writeWord16host (s+1) `mappend` writeWord16host (s+2) `mappend` writeWord16host (s+3) `mappend` writeWord16host (s+4) `mappend` writeWord16host (s+5) `mappend` writeWord16host (s+6) `mappend` writeWord16host (s+7) `mappend` writeWord16host (s+8) `mappend` writeWord16host (s+9) `mappend` writeWord16host (s+10) `mappend` writeWord16host (s+11) `mappend` writeWord16host (s+12) `mappend` writeWord16host (s+13) `mappend` writeWord16host (s+14) `mappend` writeWord16host (s+15)) `mappend` loop (s+16) (n-16) ------------------------------------------------------------------------ writeWord32N1Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32be (s+0)) `mappend` loop (s+1) (n-1) writeWord32N2Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32be (s+0) `mappend` writeWord32be (s+1)) `mappend` loop (s+2) (n-2) writeWord32N4Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32be (s+0) `mappend` writeWord32be (s+1) `mappend` writeWord32be (s+2) `mappend` writeWord32be (s+3)) `mappend` loop (s+4) (n-4) writeWord32N8Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32be (s+0) `mappend` writeWord32be (s+1) `mappend` writeWord32be (s+2) `mappend` writeWord32be (s+3) `mappend` writeWord32be (s+4) `mappend` writeWord32be (s+5) `mappend` writeWord32be (s+6) `mappend` writeWord32be (s+7)) `mappend` loop (s+8) (n-8) writeWord32N16Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32be (s+0) `mappend` writeWord32be (s+1) `mappend` writeWord32be (s+2) `mappend` writeWord32be (s+3) `mappend` writeWord32be (s+4) `mappend` writeWord32be (s+5) `mappend` writeWord32be (s+6) `mappend` writeWord32be (s+7) `mappend` writeWord32be (s+8) `mappend` writeWord32be (s+9) `mappend` writeWord32be (s+10) `mappend` writeWord32be (s+11) `mappend` writeWord32be (s+12) `mappend` writeWord32be (s+13) `mappend` writeWord32be (s+14) `mappend` writeWord32be (s+15)) `mappend` loop (s+16) (n-16) ------------------------------------------------------------------------ writeWord32N1Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32le (s+0)) `mappend` loop (s+1) (n-1) writeWord32N2Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32le (s+0) `mappend` writeWord32le (s+1)) `mappend` loop (s+2) (n-2) writeWord32N4Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32le (s+0) `mappend` writeWord32le (s+1) `mappend` writeWord32le (s+2) `mappend` writeWord32le (s+3)) `mappend` loop (s+4) (n-4) writeWord32N8Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32le (s+0) `mappend` writeWord32le (s+1) `mappend` writeWord32le (s+2) `mappend` writeWord32le (s+3) `mappend` writeWord32le (s+4) `mappend` writeWord32le (s+5) `mappend` writeWord32le (s+6) `mappend` writeWord32le (s+7)) `mappend` loop (s+8) (n-8) writeWord32N16Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32le (s+0) `mappend` writeWord32le (s+1) `mappend` writeWord32le (s+2) `mappend` writeWord32le (s+3) `mappend` writeWord32le (s+4) `mappend` writeWord32le (s+5) `mappend` writeWord32le (s+6) `mappend` writeWord32le (s+7) `mappend` writeWord32le (s+8) `mappend` writeWord32le (s+9) `mappend` writeWord32le (s+10) `mappend` writeWord32le (s+11) `mappend` writeWord32le (s+12) `mappend` writeWord32le (s+13) `mappend` writeWord32le (s+14) `mappend` writeWord32le (s+15)) `mappend` loop (s+16) (n-16) ------------------------------------------------------------------------ writeWord32N1Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32host (s+0)) `mappend` loop (s+1) (n-1) writeWord32N2Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32host (s+0) `mappend` writeWord32host (s+1)) `mappend` loop (s+2) (n-2) writeWord32N4Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32host (s+0) `mappend` writeWord32host (s+1) `mappend` writeWord32host (s+2) `mappend` writeWord32host (s+3)) `mappend` loop (s+4) (n-4) writeWord32N8Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32host (s+0) `mappend` writeWord32host (s+1) `mappend` writeWord32host (s+2) `mappend` writeWord32host (s+3) `mappend` writeWord32host (s+4) `mappend` writeWord32host (s+5) `mappend` writeWord32host (s+6) `mappend` writeWord32host (s+7)) `mappend` loop (s+8) (n-8) writeWord32N16Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord32host (s+0) `mappend` writeWord32host (s+1) `mappend` writeWord32host (s+2) `mappend` writeWord32host (s+3) `mappend` writeWord32host (s+4) `mappend` writeWord32host (s+5) `mappend` writeWord32host (s+6) `mappend` writeWord32host (s+7) `mappend` writeWord32host (s+8) `mappend` writeWord32host (s+9) `mappend` writeWord32host (s+10) `mappend` writeWord32host (s+11) `mappend` writeWord32host (s+12) `mappend` writeWord32host (s+13) `mappend` writeWord32host (s+14) `mappend` writeWord32host (s+15)) `mappend` loop (s+16) (n-16) ------------------------------------------------------------------------ writeWord64N1Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64be (s+0)) `mappend` loop (s+1) (n-1) writeWord64N2Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64be (s+0) `mappend` writeWord64be (s+1)) `mappend` loop (s+2) (n-2) writeWord64N4Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64be (s+0) `mappend` writeWord64be (s+1) `mappend` writeWord64be (s+2) `mappend` writeWord64be (s+3)) `mappend` loop (s+4) (n-4) writeWord64N8Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64be (s+0) `mappend` writeWord64be (s+1) `mappend` writeWord64be (s+2) `mappend` writeWord64be (s+3) `mappend` writeWord64be (s+4) `mappend` writeWord64be (s+5) `mappend` writeWord64be (s+6) `mappend` writeWord64be (s+7)) `mappend` loop (s+8) (n-8) writeWord64N16Big = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64be (s+0) `mappend` writeWord64be (s+1) `mappend` writeWord64be (s+2) `mappend` writeWord64be (s+3) `mappend` writeWord64be (s+4) `mappend` writeWord64be (s+5) `mappend` writeWord64be (s+6) `mappend` writeWord64be (s+7) `mappend` writeWord64be (s+8) `mappend` writeWord64be (s+9) `mappend` writeWord64be (s+10) `mappend` writeWord64be (s+11) `mappend` writeWord64be (s+12) `mappend` writeWord64be (s+13) `mappend` writeWord64be (s+14) `mappend` writeWord64be (s+15)) `mappend` loop (s+16) (n-16) ------------------------------------------------------------------------ writeWord64N1Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64le (s+0)) `mappend` loop (s+1) (n-1) writeWord64N2Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64le (s+0) `mappend` writeWord64le (s+1)) `mappend` loop (s+2) (n-2) writeWord64N4Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64le (s+0) `mappend` writeWord64le (s+1) `mappend` writeWord64le (s+2) `mappend` writeWord64le (s+3)) `mappend` loop (s+4) (n-4) writeWord64N8Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64le (s+0) `mappend` writeWord64le (s+1) `mappend` writeWord64le (s+2) `mappend` writeWord64le (s+3) `mappend` writeWord64le (s+4) `mappend` writeWord64le (s+5) `mappend` writeWord64le (s+6) `mappend` writeWord64le (s+7)) `mappend` loop (s+8) (n-8) writeWord64N16Little = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64le (s+0) `mappend` writeWord64le (s+1) `mappend` writeWord64le (s+2) `mappend` writeWord64le (s+3) `mappend` writeWord64le (s+4) `mappend` writeWord64le (s+5) `mappend` writeWord64le (s+6) `mappend` writeWord64le (s+7) `mappend` writeWord64le (s+8) `mappend` writeWord64le (s+9) `mappend` writeWord64le (s+10) `mappend` writeWord64le (s+11) `mappend` writeWord64le (s+12) `mappend` writeWord64le (s+13) `mappend` writeWord64le (s+14) `mappend` writeWord64le (s+15)) `mappend` loop (s+16) (n-16) ------------------------------------------------------------------------ writeWord64N1Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64host (s+0)) `mappend` loop (s+1) (n-1) writeWord64N2Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64host (s+0) `mappend` writeWord64host (s+1)) `mappend` loop (s+2) (n-2) writeWord64N4Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64host (s+0) `mappend` writeWord64host (s+1) `mappend` writeWord64host (s+2) `mappend` writeWord64host (s+3)) `mappend` loop (s+4) (n-4) writeWord64N8Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64host (s+0) `mappend` writeWord64host (s+1) `mappend` writeWord64host (s+2) `mappend` writeWord64host (s+3) `mappend` writeWord64host (s+4) `mappend` writeWord64host (s+5) `mappend` writeWord64host (s+6) `mappend` writeWord64host (s+7)) `mappend` loop (s+8) (n-8) writeWord64N16Host = loop 0 where loop s n | s `seq` n `seq` False = undefined loop _ 0 = mempty loop s n = fromWrite ( writeWord64host (s+0) `mappend` writeWord64host (s+1) `mappend` writeWord64host (s+2) `mappend` writeWord64host (s+3) `mappend` writeWord64host (s+4) `mappend` writeWord64host (s+5) `mappend` writeWord64host (s+6) `mappend` writeWord64host (s+7) `mappend` writeWord64host (s+8) `mappend` writeWord64host (s+9) `mappend` writeWord64host (s+10) `mappend` writeWord64host (s+11) `mappend` writeWord64host (s+12) `mappend` writeWord64host (s+13) `mappend` writeWord64host (s+14) `mappend` writeWord64host (s+15)) `mappend` loop (s+16) (n-16)
meiersi/blaze-builder
benchmarks/Throughput/BlazeBuilder.hs
bsd-3-clause
24,218
0
27
7,725
9,938
5,440
4,498
618
50
{- % (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 TcGenDeriv: Generating derived instance declarations This module is nominally ``subordinate'' to @TcDeriv@, which is the ``official'' interface to deriving-related things. This is where we do all the grimy bindings' generation. -} {-# LANGUAGE CPP, ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} module TcGenDeriv ( BagDerivStuff, DerivStuff(..), hasBuiltinDeriving, canDeriveAnyClass, FFoldType(..), functorLikeTraverse, deepSubtypesContaining, foldDataConArgs, mkCoerceClassMethEqn, gen_Newtype_binds, genAuxBinds, ordOpTbl, boxConTbl, litConTbl, mkRdrFunBind ) where #include "HsVersions.h" import HsSyn import RdrName import BasicTypes import DataCon import Name import Fingerprint import Encoding import DynFlags import PrelInfo import FamInstEnv( FamInst ) import MkCore ( eRROR_ID ) import PrelNames hiding (error_RDR) import THNames import Module ( moduleName, moduleNameString , moduleUnitId, unitIdString ) import MkId ( coerceId ) import PrimOp import SrcLoc import TyCon import TcType import TysPrim import TysWiredIn import Type import Class import TypeRep import VarSet import VarEnv import State import Util import Var #if __GLASGOW_HASKELL__ < 709 import MonadUtils #endif import Outputable import Lexeme import FastString import Pair import Bag import TcEnv (InstInfo) import StaticFlags( opt_PprStyle_Debug ) import ListSetOps ( assocMaybe ) import Data.List ( partition, intersperse ) type BagDerivStuff = Bag DerivStuff data AuxBindSpec = DerivCon2Tag TyCon -- The con2Tag for given TyCon | DerivTag2Con TyCon -- ...ditto tag2Con | DerivMaxTag TyCon -- ...and maxTag deriving( Eq ) -- All these generate ZERO-BASED tag operations -- I.e first constructor has tag 0 data DerivStuff -- Please add this auxiliary stuff = DerivAuxBind AuxBindSpec -- Generics | DerivTyCon TyCon -- New data types | DerivFamInst FamInst -- New type family instances -- New top-level auxiliary bindings | DerivHsBind (LHsBind RdrName, LSig RdrName) -- Also used for SYB | DerivInst (InstInfo RdrName) -- New, auxiliary instances {- ************************************************************************ * * Class deriving diagnostics * * ************************************************************************ Only certain blessed classes can be used in a deriving clause. These classes are listed below in the definition of hasBuiltinDeriving (with the exception of Generic and Generic1, which are handled separately in TcGenGenerics). A class might be able to be used in a deriving clause if it -XDeriveAnyClass is willing to support it. The canDeriveAnyClass function checks if this is the case. -} hasBuiltinDeriving :: DynFlags -> (Name -> Fixity) -> Class -> Maybe (SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff)) hasBuiltinDeriving dflags fix_env clas = assocMaybe gen_list (getUnique clas) where gen_list :: [(Unique, SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff))] gen_list = [ (eqClassKey, gen_Eq_binds) , (ordClassKey, gen_Ord_binds) , (enumClassKey, gen_Enum_binds) , (boundedClassKey, gen_Bounded_binds) , (ixClassKey, gen_Ix_binds) , (showClassKey, gen_Show_binds fix_env) , (readClassKey, gen_Read_binds fix_env) , (dataClassKey, gen_Data_binds dflags) , (functorClassKey, gen_Functor_binds) , (foldableClassKey, gen_Foldable_binds) , (traversableClassKey, gen_Traversable_binds) , (liftClassKey, gen_Lift_binds) ] -- Nothing: we can (try to) derive it via Generics -- Just s: we can't, reason s canDeriveAnyClass :: DynFlags -> TyCon -> Class -> Maybe SDoc canDeriveAnyClass dflags _tycon clas = let b `orElse` s = if b then Nothing else Just (ptext (sLit s)) Just m <> _ = Just m Nothing <> n = n -- We can derive a given class for a given tycon via Generics iff in -- 1) The class is not a "standard" class (like Show, Functor, etc.) (not (getUnique clas `elem` standardClassKeys) `orElse` "") -- 2) Opt_DeriveAnyClass is on <> (xopt Opt_DeriveAnyClass dflags `orElse` "Try enabling DeriveAnyClass") {- ************************************************************************ * * Eq instances * * ************************************************************************ Here are the heuristics for the code we generate for @Eq@. Let's assume we have a data type with some (possibly zero) nullary data constructors and some ordinary, non-nullary ones (the rest, also possibly zero of them). Here's an example, with both \tr{N}ullary and \tr{O}rdinary data cons. data Foo ... = N1 | N2 ... | Nn | O1 a b | O2 Int | O3 Double b b | ... * For the ordinary constructors (if any), we emit clauses to do The Usual Thing, e.g.,: (==) (O1 a1 b1) (O1 a2 b2) = a1 == a2 && b1 == b2 (==) (O2 a1) (O2 a2) = a1 == a2 (==) (O3 a1 b1 c1) (O3 a2 b2 c2) = a1 == a2 && b1 == b2 && c1 == c2 Note: if we're comparing unlifted things, e.g., if 'a1' and 'a2' are Float#s, then we have to generate case (a1 `eqFloat#` a2) of r -> r for that particular test. * If there are a lot of (more than en) nullary constructors, we emit a catch-all clause of the form: (==) a b = case (con2tag_Foo a) of { a# -> case (con2tag_Foo b) of { b# -> case (a# ==# b#) of { r -> r }}} If con2tag gets inlined this leads to join point stuff, so it's better to use regular pattern matching if there aren't too many nullary constructors. "Ten" is arbitrary, of course * If there aren't any nullary constructors, we emit a simpler catch-all: (==) a b = False * For the @(/=)@ method, we normally just use the default method. If the type is an enumeration type, we could/may/should? generate special code that calls @con2tag_Foo@, much like for @(==)@ shown above. We thought about doing this: If we're also deriving 'Ord' for this tycon, we generate: instance ... Eq (Foo ...) where (==) a b = case (compare a b) of { _LT -> False; _EQ -> True ; _GT -> False} (/=) a b = case (compare a b) of { _LT -> True ; _EQ -> False; _GT -> True } However, that requires that (Ord <whatever>) was put in the context for the instance decl, which it probably wasn't, so the decls produced don't get through the typechecker. -} gen_Eq_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Eq_binds loc tycon = (method_binds, aux_binds) where all_cons = tyConDataCons tycon (nullary_cons, non_nullary_cons) = partition isNullarySrcDataCon all_cons -- If there are ten or more (arbitrary number) nullary constructors, -- use the con2tag stuff. For small types it's better to use -- ordinary pattern matching. (tag_match_cons, pat_match_cons) | nullary_cons `lengthExceeds` 10 = (nullary_cons, non_nullary_cons) | otherwise = ([], all_cons) no_tag_match_cons = null tag_match_cons fall_through_eqn | no_tag_match_cons -- All constructors have arguments = case pat_match_cons of [] -> [] -- No constructors; no fall-though case [_] -> [] -- One constructor; no fall-though case _ -> -- Two or more constructors; add fall-through of -- (==) _ _ = False [([nlWildPat, nlWildPat], false_Expr)] | otherwise -- One or more tag_match cons; add fall-through of -- extract tags compare for equality = [([a_Pat, b_Pat], untag_Expr tycon [(a_RDR,ah_RDR), (b_RDR,bh_RDR)] (genPrimOpApp (nlHsVar ah_RDR) eqInt_RDR (nlHsVar bh_RDR)))] aux_binds | no_tag_match_cons = emptyBag | otherwise = unitBag $ DerivAuxBind $ DerivCon2Tag tycon method_binds = listToBag [eq_bind, ne_bind] eq_bind = mk_FunBind loc eq_RDR (map pats_etc pat_match_cons ++ fall_through_eqn) ne_bind = mk_easy_FunBind loc ne_RDR [a_Pat, b_Pat] ( nlHsApp (nlHsVar not_RDR) (nlHsPar (nlHsVarApps eq_RDR [a_RDR, b_RDR]))) ------------------------------------------------------------------ pats_etc data_con = let con1_pat = nlConVarPat data_con_RDR as_needed con2_pat = nlConVarPat data_con_RDR bs_needed data_con_RDR = getRdrName data_con con_arity = length tys_needed as_needed = take con_arity as_RDRs bs_needed = take con_arity bs_RDRs tys_needed = dataConOrigArgTys data_con in ([con1_pat, con2_pat], nested_eq_expr tys_needed as_needed bs_needed) where nested_eq_expr [] [] [] = true_Expr nested_eq_expr tys as bs = foldl1 and_Expr (zipWith3Equal "nested_eq" nested_eq tys as bs) where nested_eq ty a b = nlHsPar (eq_Expr tycon ty (nlHsVar a) (nlHsVar b)) {- ************************************************************************ * * Ord instances * * ************************************************************************ Note [Generating Ord instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose constructors are K1..Kn, and some are nullary. The general form we generate is: * Do case on first argument case a of K1 ... -> rhs_1 K2 ... -> rhs_2 ... Kn ... -> rhs_n _ -> nullary_rhs * To make rhs_i If i = 1, 2, n-1, n, generate a single case. rhs_2 case b of K1 {} -> LT K2 ... -> ...eq_rhs(K2)... _ -> GT Otherwise do a tag compare against the bigger range (because this is the one most likely to succeed) rhs_3 case tag b of tb -> if 3 <# tg then GT else case b of K3 ... -> ...eq_rhs(K3).... _ -> LT * To make eq_rhs(K), which knows that a = K a1 .. av b = K b1 .. bv we just want to compare (a1,b1) then (a2,b2) etc. Take care on the last field to tail-call into comparing av,bv * To make nullary_rhs generate this case con2tag a of a# -> case con2tag b of -> a# `compare` b# Several special cases: * Two or fewer nullary constructors: don't generate nullary_rhs * Be careful about unlifted comparisons. When comparing unboxed values we can't call the overloaded functions. See function unliftedOrdOp Note [Do not rely on compare] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's a bad idea to define only 'compare', and build the other binary comparisons on top of it; see Trac #2130, #4019. Reason: we don't want to laboriously make a three-way comparison, only to extract a binary result, something like this: (>) (I# x) (I# y) = case <# x y of True -> False False -> case ==# x y of True -> False False -> True So for sufficiently small types (few constructors, or all nullary) we generate all methods; for large ones we just use 'compare'. -} data OrdOp = OrdCompare | OrdLT | OrdLE | OrdGE | OrdGT ------------ ordMethRdr :: OrdOp -> RdrName ordMethRdr op = case op of OrdCompare -> compare_RDR OrdLT -> lt_RDR OrdLE -> le_RDR OrdGE -> ge_RDR OrdGT -> gt_RDR ------------ ltResult :: OrdOp -> LHsExpr RdrName -- Knowing a<b, what is the result for a `op` b? ltResult OrdCompare = ltTag_Expr ltResult OrdLT = true_Expr ltResult OrdLE = true_Expr ltResult OrdGE = false_Expr ltResult OrdGT = false_Expr ------------ eqResult :: OrdOp -> LHsExpr RdrName -- Knowing a=b, what is the result for a `op` b? eqResult OrdCompare = eqTag_Expr eqResult OrdLT = false_Expr eqResult OrdLE = true_Expr eqResult OrdGE = true_Expr eqResult OrdGT = false_Expr ------------ gtResult :: OrdOp -> LHsExpr RdrName -- Knowing a>b, what is the result for a `op` b? gtResult OrdCompare = gtTag_Expr gtResult OrdLT = false_Expr gtResult OrdLE = false_Expr gtResult OrdGE = true_Expr gtResult OrdGT = true_Expr ------------ gen_Ord_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Ord_binds loc tycon | null tycon_data_cons -- No data-cons => invoke bale-out case = (unitBag $ mk_FunBind loc compare_RDR [], emptyBag) | otherwise = (unitBag (mkOrdOp OrdCompare) `unionBags` other_ops, aux_binds) where aux_binds | single_con_type = emptyBag | otherwise = unitBag $ DerivAuxBind $ DerivCon2Tag tycon -- Note [Do not rely on compare] other_ops | (last_tag - first_tag) <= 2 -- 1-3 constructors || null non_nullary_cons -- Or it's an enumeration = listToBag (map mkOrdOp [OrdLT,OrdLE,OrdGE,OrdGT]) | otherwise = emptyBag get_tag con = dataConTag con - fIRST_TAG -- We want *zero-based* tags, because that's what -- con2Tag returns (generated by untag_Expr)! tycon_data_cons = tyConDataCons tycon single_con_type = isSingleton tycon_data_cons (first_con : _) = tycon_data_cons (last_con : _) = reverse tycon_data_cons first_tag = get_tag first_con last_tag = get_tag last_con (nullary_cons, non_nullary_cons) = partition isNullarySrcDataCon tycon_data_cons mkOrdOp :: OrdOp -> LHsBind RdrName -- Returns a binding op a b = ... compares a and b according to op .... mkOrdOp op = mk_easy_FunBind loc (ordMethRdr op) [a_Pat, b_Pat] (mkOrdOpRhs op) mkOrdOpRhs :: OrdOp -> LHsExpr RdrName mkOrdOpRhs op -- RHS for comparing 'a' and 'b' according to op | length nullary_cons <= 2 -- Two nullary or fewer, so use cases = nlHsCase (nlHsVar a_RDR) $ map (mkOrdOpAlt op) tycon_data_cons -- i.e. case a of { C1 x y -> case b of C1 x y -> ....compare x,y... -- C2 x -> case b of C2 x -> ....comopare x.... } | null non_nullary_cons -- All nullary, so go straight to comparing tags = mkTagCmp op | otherwise -- Mixed nullary and non-nullary = nlHsCase (nlHsVar a_RDR) $ (map (mkOrdOpAlt op) non_nullary_cons ++ [mkSimpleHsAlt nlWildPat (mkTagCmp op)]) mkOrdOpAlt :: OrdOp -> DataCon -> LMatch RdrName (LHsExpr RdrName) -- Make the alternative (Ki a1 a2 .. av -> mkOrdOpAlt op data_con = mkSimpleHsAlt (nlConVarPat data_con_RDR as_needed) (mkInnerRhs op data_con) where as_needed = take (dataConSourceArity data_con) as_RDRs data_con_RDR = getRdrName data_con mkInnerRhs op data_con | single_con_type = nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con ] | tag == first_tag = nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con , mkSimpleHsAlt nlWildPat (ltResult op) ] | tag == last_tag = nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con , mkSimpleHsAlt nlWildPat (gtResult op) ] | tag == first_tag + 1 = nlHsCase (nlHsVar b_RDR) [ mkSimpleHsAlt (nlConWildPat first_con) (gtResult op) , mkInnerEqAlt op data_con , mkSimpleHsAlt nlWildPat (ltResult op) ] | tag == last_tag - 1 = nlHsCase (nlHsVar b_RDR) [ mkSimpleHsAlt (nlConWildPat last_con) (ltResult op) , mkInnerEqAlt op data_con , mkSimpleHsAlt nlWildPat (gtResult op) ] | tag > last_tag `div` 2 -- lower range is larger = untag_Expr tycon [(b_RDR, bh_RDR)] $ nlHsIf (genPrimOpApp (nlHsVar bh_RDR) ltInt_RDR tag_lit) (gtResult op) $ -- Definitely GT nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con , mkSimpleHsAlt nlWildPat (ltResult op) ] | otherwise -- upper range is larger = untag_Expr tycon [(b_RDR, bh_RDR)] $ nlHsIf (genPrimOpApp (nlHsVar bh_RDR) gtInt_RDR tag_lit) (ltResult op) $ -- Definitely LT nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con , mkSimpleHsAlt nlWildPat (gtResult op) ] where tag = get_tag data_con tag_lit = noLoc (HsLit (HsIntPrim "" (toInteger tag))) mkInnerEqAlt :: OrdOp -> DataCon -> LMatch RdrName (LHsExpr RdrName) -- First argument 'a' known to be built with K -- Returns a case alternative Ki b1 b2 ... bv -> compare (a1,a2,...) with (b1,b2,...) mkInnerEqAlt op data_con = mkSimpleHsAlt (nlConVarPat data_con_RDR bs_needed) $ mkCompareFields tycon op (dataConOrigArgTys data_con) where data_con_RDR = getRdrName data_con bs_needed = take (dataConSourceArity data_con) bs_RDRs mkTagCmp :: OrdOp -> LHsExpr RdrName -- Both constructors known to be nullary -- genreates (case data2Tag a of a# -> case data2Tag b of b# -> a# `op` b# mkTagCmp op = untag_Expr tycon [(a_RDR, ah_RDR),(b_RDR, bh_RDR)] $ unliftedOrdOp tycon intPrimTy op ah_RDR bh_RDR mkCompareFields :: TyCon -> OrdOp -> [Type] -> LHsExpr RdrName -- Generates nested comparisons for (a1,a2...) against (b1,b2,...) -- where the ai,bi have the given types mkCompareFields tycon op tys = go tys as_RDRs bs_RDRs where go [] _ _ = eqResult op go [ty] (a:_) (b:_) | isUnLiftedType ty = unliftedOrdOp tycon ty op a b | otherwise = genOpApp (nlHsVar a) (ordMethRdr op) (nlHsVar b) go (ty:tys) (a:as) (b:bs) = mk_compare ty a b (ltResult op) (go tys as bs) (gtResult op) go _ _ _ = panic "mkCompareFields" -- (mk_compare ty a b) generates -- (case (compare a b) of { LT -> <lt>; EQ -> <eq>; GT -> <bt> }) -- but with suitable special cases for mk_compare ty a b lt eq gt | isUnLiftedType ty = unliftedCompare lt_op eq_op a_expr b_expr lt eq gt | otherwise = nlHsCase (nlHsPar (nlHsApp (nlHsApp (nlHsVar compare_RDR) a_expr) b_expr)) [mkSimpleHsAlt (nlNullaryConPat ltTag_RDR) lt, mkSimpleHsAlt (nlNullaryConPat eqTag_RDR) eq, mkSimpleHsAlt (nlNullaryConPat gtTag_RDR) gt] where a_expr = nlHsVar a b_expr = nlHsVar b (lt_op, _, eq_op, _, _) = primOrdOps "Ord" tycon ty unliftedOrdOp :: TyCon -> Type -> OrdOp -> RdrName -> RdrName -> LHsExpr RdrName unliftedOrdOp tycon ty op a b = case op of OrdCompare -> unliftedCompare lt_op eq_op a_expr b_expr ltTag_Expr eqTag_Expr gtTag_Expr OrdLT -> wrap lt_op OrdLE -> wrap le_op OrdGE -> wrap ge_op OrdGT -> wrap gt_op where (lt_op, le_op, eq_op, ge_op, gt_op) = primOrdOps "Ord" tycon ty wrap prim_op = genPrimOpApp a_expr prim_op b_expr a_expr = nlHsVar a b_expr = nlHsVar b unliftedCompare :: RdrName -> RdrName -> LHsExpr RdrName -> LHsExpr RdrName -- What to cmpare -> LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName -- Three results -> LHsExpr RdrName -- Return (if a < b then lt else if a == b then eq else gt) unliftedCompare lt_op eq_op a_expr b_expr lt eq gt = nlHsIf (genPrimOpApp a_expr lt_op b_expr) lt $ -- Test (<) first, not (==), because the latter -- is true less often, so putting it first would -- mean more tests (dynamically) nlHsIf (genPrimOpApp a_expr eq_op b_expr) eq gt nlConWildPat :: DataCon -> LPat RdrName -- The pattern (K {}) nlConWildPat con = noLoc (ConPatIn (noLoc (getRdrName con)) (RecCon (HsRecFields { rec_flds = [] , rec_dotdot = Nothing }))) {- ************************************************************************ * * Enum instances * * ************************************************************************ @Enum@ can only be derived for enumeration types. For a type \begin{verbatim} data Foo ... = N1 | N2 | ... | Nn \end{verbatim} we use both @con2tag_Foo@ and @tag2con_Foo@ functions, as well as a @maxtag_Foo@ variable (all generated by @gen_tag_n_con_binds@). \begin{verbatim} instance ... Enum (Foo ...) where succ x = toEnum (1 + fromEnum x) pred x = toEnum (fromEnum x - 1) toEnum i = tag2con_Foo i enumFrom a = map tag2con_Foo [con2tag_Foo a .. maxtag_Foo] -- or, really... enumFrom a = case con2tag_Foo a of a# -> map tag2con_Foo (enumFromTo (I# a#) maxtag_Foo) enumFromThen a b = map tag2con_Foo [con2tag_Foo a, con2tag_Foo b .. maxtag_Foo] -- or, really... enumFromThen a b = case con2tag_Foo a of { a# -> case con2tag_Foo b of { b# -> map tag2con_Foo (enumFromThenTo (I# a#) (I# b#) maxtag_Foo) }} \end{verbatim} For @enumFromTo@ and @enumFromThenTo@, we use the default methods. -} gen_Enum_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Enum_binds loc tycon = (method_binds, aux_binds) where method_binds = listToBag [ succ_enum, pred_enum, to_enum, enum_from, enum_from_then, from_enum ] aux_binds = listToBag $ map DerivAuxBind [DerivCon2Tag tycon, DerivTag2Con tycon, DerivMaxTag tycon] occ_nm = getOccString tycon succ_enum = mk_easy_FunBind loc succ_RDR [a_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ nlHsIf (nlHsApps eq_RDR [nlHsVar (maxtag_RDR tycon), nlHsVarApps intDataCon_RDR [ah_RDR]]) (illegal_Expr "succ" occ_nm "tried to take `succ' of last tag in enumeration") (nlHsApp (nlHsVar (tag2con_RDR tycon)) (nlHsApps plus_RDR [nlHsVarApps intDataCon_RDR [ah_RDR], nlHsIntLit 1])) pred_enum = mk_easy_FunBind loc pred_RDR [a_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ nlHsIf (nlHsApps eq_RDR [nlHsIntLit 0, nlHsVarApps intDataCon_RDR [ah_RDR]]) (illegal_Expr "pred" occ_nm "tried to take `pred' of first tag in enumeration") (nlHsApp (nlHsVar (tag2con_RDR tycon)) (nlHsApps plus_RDR [nlHsVarApps intDataCon_RDR [ah_RDR], nlHsLit (HsInt "-1" (-1))])) to_enum = mk_easy_FunBind loc toEnum_RDR [a_Pat] $ nlHsIf (nlHsApps and_RDR [nlHsApps ge_RDR [nlHsVar a_RDR, nlHsIntLit 0], nlHsApps le_RDR [nlHsVar a_RDR, nlHsVar (maxtag_RDR tycon)]]) (nlHsVarApps (tag2con_RDR tycon) [a_RDR]) (illegal_toEnum_tag occ_nm (maxtag_RDR tycon)) enum_from = mk_easy_FunBind loc enumFrom_RDR [a_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ nlHsApps map_RDR [nlHsVar (tag2con_RDR tycon), nlHsPar (enum_from_to_Expr (nlHsVarApps intDataCon_RDR [ah_RDR]) (nlHsVar (maxtag_RDR tycon)))] enum_from_then = mk_easy_FunBind loc enumFromThen_RDR [a_Pat, b_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR), (b_RDR, bh_RDR)] $ nlHsApp (nlHsVarApps map_RDR [tag2con_RDR tycon]) $ nlHsPar (enum_from_then_to_Expr (nlHsVarApps intDataCon_RDR [ah_RDR]) (nlHsVarApps intDataCon_RDR [bh_RDR]) (nlHsIf (nlHsApps gt_RDR [nlHsVarApps intDataCon_RDR [ah_RDR], nlHsVarApps intDataCon_RDR [bh_RDR]]) (nlHsIntLit 0) (nlHsVar (maxtag_RDR tycon)) )) from_enum = mk_easy_FunBind loc fromEnum_RDR [a_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ (nlHsVarApps intDataCon_RDR [ah_RDR]) {- ************************************************************************ * * Bounded instances * * ************************************************************************ -} gen_Bounded_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Bounded_binds loc tycon | isEnumerationTyCon tycon = (listToBag [ min_bound_enum, max_bound_enum ], emptyBag) | otherwise = ASSERT(isSingleton data_cons) (listToBag [ min_bound_1con, max_bound_1con ], emptyBag) where data_cons = tyConDataCons tycon ----- enum-flavored: --------------------------- min_bound_enum = mkHsVarBind loc minBound_RDR (nlHsVar data_con_1_RDR) max_bound_enum = mkHsVarBind loc maxBound_RDR (nlHsVar data_con_N_RDR) data_con_1 = head data_cons data_con_N = last data_cons data_con_1_RDR = getRdrName data_con_1 data_con_N_RDR = getRdrName data_con_N ----- single-constructor-flavored: ------------- arity = dataConSourceArity data_con_1 min_bound_1con = mkHsVarBind loc minBound_RDR $ nlHsVarApps data_con_1_RDR (nOfThem arity minBound_RDR) max_bound_1con = mkHsVarBind loc maxBound_RDR $ nlHsVarApps data_con_1_RDR (nOfThem arity maxBound_RDR) {- ************************************************************************ * * Ix instances * * ************************************************************************ Deriving @Ix@ is only possible for enumeration types and single-constructor types. We deal with them in turn. For an enumeration type, e.g., \begin{verbatim} data Foo ... = N1 | N2 | ... | Nn \end{verbatim} things go not too differently from @Enum@: \begin{verbatim} instance ... Ix (Foo ...) where range (a, b) = map tag2con_Foo [con2tag_Foo a .. con2tag_Foo b] -- or, really... range (a, b) = case (con2tag_Foo a) of { a# -> case (con2tag_Foo b) of { b# -> map tag2con_Foo (enumFromTo (I# a#) (I# b#)) }} -- Generate code for unsafeIndex, because using index leads -- to lots of redundant range tests unsafeIndex c@(a, b) d = case (con2tag_Foo d -# con2tag_Foo a) of r# -> I# r# inRange (a, b) c = let p_tag = con2tag_Foo c in p_tag >= con2tag_Foo a && p_tag <= con2tag_Foo b -- or, really... inRange (a, b) c = case (con2tag_Foo a) of { a_tag -> case (con2tag_Foo b) of { b_tag -> case (con2tag_Foo c) of { c_tag -> if (c_tag >=# a_tag) then c_tag <=# b_tag else False }}} \end{verbatim} (modulo suitable case-ification to handle the unlifted tags) For a single-constructor type (NB: this includes all tuples), e.g., \begin{verbatim} data Foo ... = MkFoo a b Int Double c c \end{verbatim} we follow the scheme given in Figure~19 of the Haskell~1.2 report (p.~147). -} gen_Ix_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Ix_binds loc tycon | isEnumerationTyCon tycon = ( enum_ixes , listToBag $ map DerivAuxBind [DerivCon2Tag tycon, DerivTag2Con tycon, DerivMaxTag tycon]) | otherwise = (single_con_ixes, unitBag (DerivAuxBind (DerivCon2Tag tycon))) where -------------------------------------------------------------- enum_ixes = listToBag [ enum_range, enum_index, enum_inRange ] enum_range = mk_easy_FunBind loc range_RDR [nlTuplePat [a_Pat, b_Pat] Boxed] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ untag_Expr tycon [(b_RDR, bh_RDR)] $ nlHsApp (nlHsVarApps map_RDR [tag2con_RDR tycon]) $ nlHsPar (enum_from_to_Expr (nlHsVarApps intDataCon_RDR [ah_RDR]) (nlHsVarApps intDataCon_RDR [bh_RDR])) enum_index = mk_easy_FunBind loc unsafeIndex_RDR [noLoc (AsPat (noLoc c_RDR) (nlTuplePat [a_Pat, nlWildPat] Boxed)), d_Pat] ( untag_Expr tycon [(a_RDR, ah_RDR)] ( untag_Expr tycon [(d_RDR, dh_RDR)] ( let rhs = nlHsVarApps intDataCon_RDR [c_RDR] in nlHsCase (genOpApp (nlHsVar dh_RDR) minusInt_RDR (nlHsVar ah_RDR)) [mkSimpleHsAlt (nlVarPat c_RDR) rhs] )) ) enum_inRange = mk_easy_FunBind loc inRange_RDR [nlTuplePat [a_Pat, b_Pat] Boxed, c_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] ( untag_Expr tycon [(b_RDR, bh_RDR)] ( untag_Expr tycon [(c_RDR, ch_RDR)] ( nlHsIf (genPrimOpApp (nlHsVar ch_RDR) geInt_RDR (nlHsVar ah_RDR)) ( (genPrimOpApp (nlHsVar ch_RDR) leInt_RDR (nlHsVar bh_RDR)) ) {-else-} ( false_Expr )))) -------------------------------------------------------------- single_con_ixes = listToBag [single_con_range, single_con_index, single_con_inRange] data_con = case tyConSingleDataCon_maybe tycon of -- just checking... Nothing -> panic "get_Ix_binds" Just dc -> dc con_arity = dataConSourceArity data_con data_con_RDR = getRdrName data_con as_needed = take con_arity as_RDRs bs_needed = take con_arity bs_RDRs cs_needed = take con_arity cs_RDRs con_pat xs = nlConVarPat data_con_RDR xs con_expr = nlHsVarApps data_con_RDR cs_needed -------------------------------------------------------------- single_con_range = mk_easy_FunBind loc range_RDR [nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed] $ noLoc (mkHsComp ListComp stmts con_expr) where stmts = zipWith3Equal "single_con_range" mk_qual as_needed bs_needed cs_needed mk_qual a b c = noLoc $ mkBindStmt (nlVarPat c) (nlHsApp (nlHsVar range_RDR) (mkLHsVarTuple [a,b])) ---------------- single_con_index = mk_easy_FunBind loc unsafeIndex_RDR [nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed, con_pat cs_needed] -- We need to reverse the order we consider the components in -- so that -- range (l,u) !! index (l,u) i == i -- when i is in range -- (from http://haskell.org/onlinereport/ix.html) holds. (mk_index (reverse $ zip3 as_needed bs_needed cs_needed)) where -- index (l1,u1) i1 + rangeSize (l1,u1) * (index (l2,u2) i2 + ...) mk_index [] = nlHsIntLit 0 mk_index [(l,u,i)] = mk_one l u i mk_index ((l,u,i) : rest) = genOpApp ( mk_one l u i ) plus_RDR ( genOpApp ( (nlHsApp (nlHsVar unsafeRangeSize_RDR) (mkLHsVarTuple [l,u])) ) times_RDR (mk_index rest) ) mk_one l u i = nlHsApps unsafeIndex_RDR [mkLHsVarTuple [l,u], nlHsVar i] ------------------ single_con_inRange = mk_easy_FunBind loc inRange_RDR [nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed, con_pat cs_needed] $ foldl1 and_Expr (zipWith3Equal "single_con_inRange" in_range as_needed bs_needed cs_needed) where in_range a b c = nlHsApps inRange_RDR [mkLHsVarTuple [a,b], nlHsVar c] {- ************************************************************************ * * Read instances * * ************************************************************************ Example infix 4 %% data T = Int %% Int | T1 { f1 :: Int } | T2 T instance Read T where readPrec = parens ( prec 4 ( do x <- ReadP.step Read.readPrec expectP (Symbol "%%") y <- ReadP.step Read.readPrec return (x %% y)) +++ prec (appPrec+1) ( -- Note the "+1" part; "T2 T1 {f1=3}" should parse ok -- Record construction binds even more tightly than application do expectP (Ident "T1") expectP (Punc '{') expectP (Ident "f1") expectP (Punc '=') x <- ReadP.reset Read.readPrec expectP (Punc '}') return (T1 { f1 = x })) +++ prec appPrec ( do expectP (Ident "T2") x <- ReadP.step Read.readPrec return (T2 x)) ) readListPrec = readListPrecDefault readList = readListDefault Note [Use expectP] ~~~~~~~~~~~~~~~~~~ Note that we use expectP (Ident "T1") rather than Ident "T1" <- lexP The latter desugares to inline code for matching the Ident and the string, and this can be very voluminous. The former is much more compact. Cf Trac #7258, although that also concerned non-linearity in the occurrence analyser, a separate issue. Note [Read for empty data types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ What should we get for this? (Trac #7931) data Emp deriving( Read ) -- No data constructors Here we want read "[]" :: [Emp] to succeed, returning [] So we do NOT want instance Read Emp where readPrec = error "urk" Rather we want instance Read Emp where readPred = pfail -- Same as choose [] Because 'pfail' allows the parser to backtrack, but 'error' doesn't. These instances are also useful for Read (Either Int Emp), where we want to be able to parse (Left 3) just fine. -} gen_Read_binds :: (Name -> Fixity) -> SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Read_binds get_fixity loc tycon = (listToBag [read_prec, default_readlist, default_readlistprec], emptyBag) where ----------------------------------------------------------------------- default_readlist = mkHsVarBind loc readList_RDR (nlHsVar readListDefault_RDR) default_readlistprec = mkHsVarBind loc readListPrec_RDR (nlHsVar readListPrecDefault_RDR) ----------------------------------------------------------------------- data_cons = tyConDataCons tycon (nullary_cons, non_nullary_cons) = partition isNullarySrcDataCon data_cons read_prec = mkHsVarBind loc readPrec_RDR (nlHsApp (nlHsVar parens_RDR) read_cons) read_cons | null data_cons = nlHsVar pfail_RDR -- See Note [Read for empty data types] | otherwise = foldr1 mk_alt (read_nullary_cons ++ read_non_nullary_cons) read_non_nullary_cons = map read_non_nullary_con non_nullary_cons read_nullary_cons = case nullary_cons of [] -> [] [con] -> [nlHsDo DoExpr (match_con con ++ [noLoc $ mkLastStmt (result_expr con [])])] _ -> [nlHsApp (nlHsVar choose_RDR) (nlList (map mk_pair nullary_cons))] -- NB For operators the parens around (:=:) are matched by the -- enclosing "parens" call, so here we must match the naked -- data_con_str con match_con con | isSym con_str = [symbol_pat con_str] | otherwise = ident_h_pat con_str where con_str = data_con_str con -- For nullary constructors we must match Ident s for normal constrs -- and Symbol s for operators mk_pair con = mkLHsTupleExpr [nlHsLit (mkHsString (data_con_str con)), result_expr con []] read_non_nullary_con data_con | is_infix = mk_parser infix_prec infix_stmts body | is_record = mk_parser record_prec record_stmts body -- Using these two lines instead allows the derived -- read for infix and record bindings to read the prefix form -- | is_infix = mk_alt prefix_parser (mk_parser infix_prec infix_stmts body) -- | is_record = mk_alt prefix_parser (mk_parser record_prec record_stmts body) | otherwise = prefix_parser where body = result_expr data_con as_needed con_str = data_con_str data_con prefix_parser = mk_parser prefix_prec prefix_stmts body read_prefix_con | isSym con_str = [read_punc "(", symbol_pat con_str, read_punc ")"] | otherwise = ident_h_pat con_str read_infix_con | isSym con_str = [symbol_pat con_str] | otherwise = [read_punc "`"] ++ ident_h_pat con_str ++ [read_punc "`"] prefix_stmts -- T a b c = read_prefix_con ++ read_args infix_stmts -- a %% b, or a `T` b = [read_a1] ++ read_infix_con ++ [read_a2] record_stmts -- T { f1 = a, f2 = b } = read_prefix_con ++ [read_punc "{"] ++ concat (intersperse [read_punc ","] field_stmts) ++ [read_punc "}"] field_stmts = zipWithEqual "lbl_stmts" read_field labels as_needed con_arity = dataConSourceArity data_con labels = map flLabel $ dataConFieldLabels data_con dc_nm = getName data_con is_infix = dataConIsInfix data_con is_record = length labels > 0 as_needed = take con_arity as_RDRs read_args = zipWithEqual "gen_Read_binds" read_arg as_needed (dataConOrigArgTys data_con) (read_a1:read_a2:_) = read_args prefix_prec = appPrecedence infix_prec = getPrecedence get_fixity dc_nm record_prec = appPrecedence + 1 -- Record construction binds even more tightly -- than application; e.g. T2 T1 {x=2} means T2 (T1 {x=2}) ------------------------------------------------------------------------ -- Helpers ------------------------------------------------------------------------ mk_alt e1 e2 = genOpApp e1 alt_RDR e2 -- e1 +++ e2 mk_parser p ss b = nlHsApps prec_RDR [nlHsIntLit p -- prec p (do { ss ; b }) , nlHsDo DoExpr (ss ++ [noLoc $ mkLastStmt b])] con_app con as = nlHsVarApps (getRdrName con) as -- con as result_expr con as = nlHsApp (nlHsVar returnM_RDR) (con_app con as) -- return (con as) -- For constructors and field labels ending in '#', we hackily -- let the lexer generate two tokens, and look for both in sequence -- Thus [Ident "I"; Symbol "#"]. See Trac #5041 ident_h_pat s | Just (ss, '#') <- snocView s = [ ident_pat ss, symbol_pat "#" ] | otherwise = [ ident_pat s ] bindLex pat = noLoc (mkBodyStmt (nlHsApp (nlHsVar expectP_RDR) pat)) -- expectP p -- See Note [Use expectP] ident_pat s = bindLex $ nlHsApps ident_RDR [nlHsLit (mkHsString s)] -- expectP (Ident "foo") symbol_pat s = bindLex $ nlHsApps symbol_RDR [nlHsLit (mkHsString s)] -- expectP (Symbol ">>") read_punc c = bindLex $ nlHsApps punc_RDR [nlHsLit (mkHsString c)] -- expectP (Punc "<") data_con_str con = occNameString (getOccName con) read_arg a ty = ASSERT( not (isUnLiftedType ty) ) noLoc (mkBindStmt (nlVarPat a) (nlHsVarApps step_RDR [readPrec_RDR])) read_field lbl a = read_lbl lbl ++ [read_punc "=", noLoc (mkBindStmt (nlVarPat a) (nlHsVarApps reset_RDR [readPrec_RDR]))] -- When reading field labels we might encounter -- a = 3 -- _a = 3 -- or (#) = 4 -- Note the parens! read_lbl lbl | isSym lbl_str = [read_punc "(", symbol_pat lbl_str, read_punc ")"] | otherwise = ident_h_pat lbl_str where lbl_str = unpackFS lbl {- ************************************************************************ * * Show instances * * ************************************************************************ Example infixr 5 :^: data Tree a = Leaf a | Tree a :^: Tree a instance (Show a) => Show (Tree a) where showsPrec d (Leaf m) = showParen (d > app_prec) showStr where showStr = showString "Leaf " . showsPrec (app_prec+1) m showsPrec d (u :^: v) = showParen (d > up_prec) showStr where showStr = showsPrec (up_prec+1) u . showString " :^: " . showsPrec (up_prec+1) v -- Note: right-associativity of :^: ignored up_prec = 5 -- Precedence of :^: app_prec = 10 -- Application has precedence one more than -- the most tightly-binding operator -} gen_Show_binds :: (Name -> Fixity) -> SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Show_binds get_fixity loc tycon = (listToBag [shows_prec, show_list], emptyBag) where ----------------------------------------------------------------------- show_list = mkHsVarBind loc showList_RDR (nlHsApp (nlHsVar showList___RDR) (nlHsPar (nlHsApp (nlHsVar showsPrec_RDR) (nlHsIntLit 0)))) ----------------------------------------------------------------------- data_cons = tyConDataCons tycon shows_prec = mk_FunBind loc showsPrec_RDR (map pats_etc data_cons) pats_etc data_con | nullary_con = -- skip the showParen junk... ASSERT(null bs_needed) ([nlWildPat, con_pat], mk_showString_app op_con_str) | record_syntax = -- skip showParen (#2530) ([a_Pat, con_pat], nlHsPar (nested_compose_Expr show_thingies)) | otherwise = ([a_Pat, con_pat], showParen_Expr (genOpApp a_Expr ge_RDR (nlHsLit (HsInt "" con_prec_plus_one))) (nlHsPar (nested_compose_Expr show_thingies))) where data_con_RDR = getRdrName data_con con_arity = dataConSourceArity data_con bs_needed = take con_arity bs_RDRs arg_tys = dataConOrigArgTys data_con -- Correspond 1-1 with bs_needed con_pat = nlConVarPat data_con_RDR bs_needed nullary_con = con_arity == 0 labels = map flLabel $ dataConFieldLabels data_con lab_fields = length labels record_syntax = lab_fields > 0 dc_nm = getName data_con dc_occ_nm = getOccName data_con con_str = occNameString dc_occ_nm op_con_str = wrapOpParens con_str backquote_str = wrapOpBackquotes con_str show_thingies | is_infix = [show_arg1, mk_showString_app (" " ++ backquote_str ++ " "), show_arg2] | record_syntax = mk_showString_app (op_con_str ++ " {") : show_record_args ++ [mk_showString_app "}"] | otherwise = mk_showString_app (op_con_str ++ " ") : show_prefix_args show_label l = mk_showString_app (nm ++ " = ") -- Note the spaces around the "=" sign. If we -- don't have them then we get Foo { x=-1 } and -- the "=-" parses as a single lexeme. Only the -- space after the '=' is necessary, but it -- seems tidier to have them both sides. where nm = wrapOpParens (unpackFS l) show_args = zipWith show_arg bs_needed arg_tys (show_arg1:show_arg2:_) = show_args show_prefix_args = intersperse (nlHsVar showSpace_RDR) show_args -- Assumption for record syntax: no of fields == no of -- labelled fields (and in same order) show_record_args = concat $ intersperse [mk_showString_app ", "] $ [ [show_label lbl, arg] | (lbl,arg) <- zipEqual "gen_Show_binds" labels show_args ] show_arg :: RdrName -> Type -> LHsExpr RdrName show_arg b arg_ty | isUnLiftedType arg_ty -- See Note [Deriving and unboxed types] in TcDeriv = nlHsApps compose_RDR [mk_shows_app boxed_arg, mk_showString_app postfixMod] | otherwise = mk_showsPrec_app arg_prec arg where arg = nlHsVar b boxed_arg = box "Show" tycon arg arg_ty postfixMod = assoc_ty_id "Show" tycon postfixModTbl arg_ty -- Fixity stuff is_infix = dataConIsInfix data_con con_prec_plus_one = 1 + getPrec is_infix get_fixity dc_nm arg_prec | record_syntax = 0 -- Record fields don't need parens | otherwise = con_prec_plus_one wrapOpParens :: String -> String wrapOpParens s | isSym s = '(' : s ++ ")" | otherwise = s wrapOpBackquotes :: String -> String wrapOpBackquotes s | isSym s = s | otherwise = '`' : s ++ "`" isSym :: String -> Bool isSym "" = False isSym (c : _) = startsVarSym c || startsConSym c -- | showString :: String -> ShowS mk_showString_app :: String -> LHsExpr RdrName mk_showString_app str = nlHsApp (nlHsVar showString_RDR) (nlHsLit (mkHsString str)) -- | showsPrec :: Show a => Int -> a -> ShowS mk_showsPrec_app :: Integer -> LHsExpr RdrName -> LHsExpr RdrName mk_showsPrec_app p x = nlHsApps showsPrec_RDR [nlHsLit (HsInt "" p), x] -- | shows :: Show a => a -> ShowS mk_shows_app :: LHsExpr RdrName -> LHsExpr RdrName mk_shows_app x = nlHsApp (nlHsVar shows_RDR) x getPrec :: Bool -> (Name -> Fixity) -> Name -> Integer getPrec is_infix get_fixity nm | not is_infix = appPrecedence | otherwise = getPrecedence get_fixity nm appPrecedence :: Integer appPrecedence = fromIntegral maxPrecedence + 1 -- One more than the precedence of the most -- tightly-binding operator getPrecedence :: (Name -> Fixity) -> Name -> Integer getPrecedence get_fixity nm = case get_fixity nm of Fixity x _assoc -> fromIntegral x -- NB: the Report says that associativity is not taken -- into account for either Read or Show; hence we -- ignore associativity here {- ************************************************************************ * * Data instances * * ************************************************************************ From the data type data T a b = T1 a b | T2 we generate $cT1 = mkDataCon $dT "T1" Prefix $cT2 = mkDataCon $dT "T2" Prefix $dT = mkDataType "Module.T" [] [$con_T1, $con_T2] -- the [] is for field labels. instance (Data a, Data b) => Data (T a b) where gfoldl k z (T1 a b) = z T `k` a `k` b gfoldl k z T2 = z T2 -- ToDo: add gmapT,Q,M, gfoldr gunfold k z c = case conIndex c of I# 1# -> k (k (z T1)) I# 2# -> z T2 toConstr (T1 _ _) = $cT1 toConstr T2 = $cT2 dataTypeOf _ = $dT dataCast1 = gcast1 -- If T :: * -> * dataCast2 = gcast2 -- if T :: * -> * -> * -} gen_Data_binds :: DynFlags -> SrcSpan -> TyCon -- For data families, this is the -- *representation* TyCon -> (LHsBinds RdrName, -- The method bindings BagDerivStuff) -- Auxiliary bindings gen_Data_binds dflags loc rep_tc = (listToBag [gfoldl_bind, gunfold_bind, toCon_bind, dataTypeOf_bind] `unionBags` gcast_binds, -- Auxiliary definitions: the data type and constructors listToBag ( DerivHsBind (genDataTyCon) : map (DerivHsBind . genDataDataCon) data_cons)) where data_cons = tyConDataCons rep_tc n_cons = length data_cons one_constr = n_cons == 1 genDataTyCon :: (LHsBind RdrName, LSig RdrName) genDataTyCon -- $dT = (mkHsVarBind loc rdr_name rhs, L loc (TypeSig [L loc rdr_name] sig_ty PlaceHolder)) where rdr_name = mk_data_type_name rep_tc sig_ty = nlHsTyVar dataType_RDR constrs = [nlHsVar (mk_constr_name con) | con <- tyConDataCons rep_tc] rhs = nlHsVar mkDataType_RDR `nlHsApp` nlHsLit (mkHsString (showSDocOneLine dflags (ppr rep_tc))) `nlHsApp` nlList constrs genDataDataCon :: DataCon -> (LHsBind RdrName, LSig RdrName) genDataDataCon dc -- $cT1 etc = (mkHsVarBind loc rdr_name rhs, L loc (TypeSig [L loc rdr_name] sig_ty PlaceHolder)) where rdr_name = mk_constr_name dc sig_ty = nlHsTyVar constr_RDR rhs = nlHsApps mkConstr_RDR constr_args constr_args = [ -- nlHsIntLit (toInteger (dataConTag dc)), -- Tag nlHsVar (mk_data_type_name (dataConTyCon dc)), -- DataType nlHsLit (mkHsString (occNameString dc_occ)), -- String name nlList labels, -- Field labels nlHsVar fixity] -- Fixity labels = map (nlHsLit . mkHsString . unpackFS . flLabel) (dataConFieldLabels dc) dc_occ = getOccName dc is_infix = isDataSymOcc dc_occ fixity | is_infix = infix_RDR | otherwise = prefix_RDR ------------ gfoldl gfoldl_bind = mk_FunBind loc gfoldl_RDR (map gfoldl_eqn data_cons) gfoldl_eqn con = ([nlVarPat k_RDR, nlVarPat z_RDR, nlConVarPat con_name as_needed], foldl mk_k_app (nlHsVar z_RDR `nlHsApp` nlHsVar con_name) as_needed) where con_name :: RdrName con_name = getRdrName con as_needed = take (dataConSourceArity con) as_RDRs mk_k_app e v = nlHsPar (nlHsOpApp e k_RDR (nlHsVar v)) ------------ gunfold gunfold_bind = mk_FunBind loc gunfold_RDR [([k_Pat, z_Pat, if one_constr then nlWildPat else c_Pat], gunfold_rhs)] gunfold_rhs | one_constr = mk_unfold_rhs (head data_cons) -- No need for case | otherwise = nlHsCase (nlHsVar conIndex_RDR `nlHsApp` c_Expr) (map gunfold_alt data_cons) gunfold_alt dc = mkSimpleHsAlt (mk_unfold_pat dc) (mk_unfold_rhs dc) mk_unfold_rhs dc = foldr nlHsApp (nlHsVar z_RDR `nlHsApp` nlHsVar (getRdrName dc)) (replicate (dataConSourceArity dc) (nlHsVar k_RDR)) mk_unfold_pat dc -- Last one is a wild-pat, to avoid -- redundant test, and annoying warning | tag-fIRST_TAG == n_cons-1 = nlWildPat -- Last constructor | otherwise = nlConPat intDataCon_RDR [nlLitPat (HsIntPrim "" (toInteger tag))] where tag = dataConTag dc ------------ toConstr toCon_bind = mk_FunBind loc toConstr_RDR (map to_con_eqn data_cons) to_con_eqn dc = ([nlWildConPat dc], nlHsVar (mk_constr_name dc)) ------------ dataTypeOf dataTypeOf_bind = mk_easy_FunBind loc dataTypeOf_RDR [nlWildPat] (nlHsVar (mk_data_type_name rep_tc)) ------------ gcast1/2 -- Make the binding dataCast1 x = gcast1 x -- if T :: * -> * -- or dataCast2 x = gcast2 s -- if T :: * -> * -> * -- (or nothing if T has neither of these two types) -- But care is needed for data families: -- If we have data family D a -- data instance D (a,b,c) = A | B deriving( Data ) -- and we want instance ... => Data (D [(a,b,c)]) where ... -- then we need dataCast1 x = gcast1 x -- because D :: * -> * -- even though rep_tc has kind * -> * -> * -> * -- Hence looking for the kind of fam_tc not rep_tc -- See Trac #4896 tycon_kind = case tyConFamInst_maybe rep_tc of Just (fam_tc, _) -> tyConKind fam_tc Nothing -> tyConKind rep_tc gcast_binds | tycon_kind `tcEqKind` kind1 = mk_gcast dataCast1_RDR gcast1_RDR | tycon_kind `tcEqKind` kind2 = mk_gcast dataCast2_RDR gcast2_RDR | otherwise = emptyBag mk_gcast dataCast_RDR gcast_RDR = unitBag (mk_easy_FunBind loc dataCast_RDR [nlVarPat f_RDR] (nlHsVar gcast_RDR `nlHsApp` nlHsVar f_RDR)) kind1, kind2 :: Kind kind1 = liftedTypeKind `mkArrowKind` liftedTypeKind kind2 = liftedTypeKind `mkArrowKind` kind1 gfoldl_RDR, gunfold_RDR, toConstr_RDR, dataTypeOf_RDR, mkConstr_RDR, mkDataType_RDR, conIndex_RDR, prefix_RDR, infix_RDR, dataCast1_RDR, dataCast2_RDR, gcast1_RDR, gcast2_RDR, constr_RDR, dataType_RDR, eqChar_RDR , ltChar_RDR , geChar_RDR , gtChar_RDR , leChar_RDR , eqInt_RDR , ltInt_RDR , geInt_RDR , gtInt_RDR , leInt_RDR , eqWord_RDR , ltWord_RDR , geWord_RDR , gtWord_RDR , leWord_RDR , eqAddr_RDR , ltAddr_RDR , geAddr_RDR , gtAddr_RDR , leAddr_RDR , eqFloat_RDR , ltFloat_RDR , geFloat_RDR , gtFloat_RDR , leFloat_RDR , eqDouble_RDR, ltDouble_RDR, geDouble_RDR, gtDouble_RDR, leDouble_RDR :: RdrName gfoldl_RDR = varQual_RDR gENERICS (fsLit "gfoldl") gunfold_RDR = varQual_RDR gENERICS (fsLit "gunfold") toConstr_RDR = varQual_RDR gENERICS (fsLit "toConstr") dataTypeOf_RDR = varQual_RDR gENERICS (fsLit "dataTypeOf") dataCast1_RDR = varQual_RDR gENERICS (fsLit "dataCast1") dataCast2_RDR = varQual_RDR gENERICS (fsLit "dataCast2") gcast1_RDR = varQual_RDR tYPEABLE (fsLit "gcast1") gcast2_RDR = varQual_RDR tYPEABLE (fsLit "gcast2") mkConstr_RDR = varQual_RDR gENERICS (fsLit "mkConstr") constr_RDR = tcQual_RDR gENERICS (fsLit "Constr") mkDataType_RDR = varQual_RDR gENERICS (fsLit "mkDataType") dataType_RDR = tcQual_RDR gENERICS (fsLit "DataType") conIndex_RDR = varQual_RDR gENERICS (fsLit "constrIndex") prefix_RDR = dataQual_RDR gENERICS (fsLit "Prefix") infix_RDR = dataQual_RDR gENERICS (fsLit "Infix") eqChar_RDR = varQual_RDR gHC_PRIM (fsLit "eqChar#") ltChar_RDR = varQual_RDR gHC_PRIM (fsLit "ltChar#") leChar_RDR = varQual_RDR gHC_PRIM (fsLit "leChar#") gtChar_RDR = varQual_RDR gHC_PRIM (fsLit "gtChar#") geChar_RDR = varQual_RDR gHC_PRIM (fsLit "geChar#") eqInt_RDR = varQual_RDR gHC_PRIM (fsLit "==#") ltInt_RDR = varQual_RDR gHC_PRIM (fsLit "<#" ) leInt_RDR = varQual_RDR gHC_PRIM (fsLit "<=#") gtInt_RDR = varQual_RDR gHC_PRIM (fsLit ">#" ) geInt_RDR = varQual_RDR gHC_PRIM (fsLit ">=#") eqWord_RDR = varQual_RDR gHC_PRIM (fsLit "eqWord#") ltWord_RDR = varQual_RDR gHC_PRIM (fsLit "ltWord#") leWord_RDR = varQual_RDR gHC_PRIM (fsLit "leWord#") gtWord_RDR = varQual_RDR gHC_PRIM (fsLit "gtWord#") geWord_RDR = varQual_RDR gHC_PRIM (fsLit "geWord#") eqAddr_RDR = varQual_RDR gHC_PRIM (fsLit "eqAddr#") ltAddr_RDR = varQual_RDR gHC_PRIM (fsLit "ltAddr#") leAddr_RDR = varQual_RDR gHC_PRIM (fsLit "leAddr#") gtAddr_RDR = varQual_RDR gHC_PRIM (fsLit "gtAddr#") geAddr_RDR = varQual_RDR gHC_PRIM (fsLit "geAddr#") eqFloat_RDR = varQual_RDR gHC_PRIM (fsLit "eqFloat#") ltFloat_RDR = varQual_RDR gHC_PRIM (fsLit "ltFloat#") leFloat_RDR = varQual_RDR gHC_PRIM (fsLit "leFloat#") gtFloat_RDR = varQual_RDR gHC_PRIM (fsLit "gtFloat#") geFloat_RDR = varQual_RDR gHC_PRIM (fsLit "geFloat#") eqDouble_RDR = varQual_RDR gHC_PRIM (fsLit "==##") ltDouble_RDR = varQual_RDR gHC_PRIM (fsLit "<##" ) leDouble_RDR = varQual_RDR gHC_PRIM (fsLit "<=##") gtDouble_RDR = varQual_RDR gHC_PRIM (fsLit ">##" ) geDouble_RDR = varQual_RDR gHC_PRIM (fsLit ">=##") {- ************************************************************************ * * Functor instances see http://www.mail-archive.com/haskell-prime@haskell.org/msg02116.html * * ************************************************************************ For the data type: data T a = T1 Int a | T2 (T a) We generate the instance: instance Functor T where fmap f (T1 b1 a) = T1 b1 (f a) fmap f (T2 ta) = T2 (fmap f ta) Notice that we don't simply apply 'fmap' to the constructor arguments. Rather - Do nothing to an argument whose type doesn't mention 'a' - Apply 'f' to an argument of type 'a' - Apply 'fmap f' to other arguments That's why we have to recurse deeply into the constructor argument types, rather than just one level, as we typically do. What about types with more than one type parameter? In general, we only derive Functor for the last position: data S a b = S1 [b] | S2 (a, T a b) instance Functor (S a) where fmap f (S1 bs) = S1 (fmap f bs) fmap f (S2 (p,q)) = S2 (a, fmap f q) However, we have special cases for - tuples - functions More formally, we write the derivation of fmap code over type variable 'a for type 'b as ($fmap 'a 'b). In this general notation the derived instance for T is: instance Functor T where fmap f (T1 x1 x2) = T1 ($(fmap 'a 'b1) x1) ($(fmap 'a 'a) x2) fmap f (T2 x1) = T2 ($(fmap 'a '(T a)) x1) $(fmap 'a 'b) = \x -> x -- when b does not contain a $(fmap 'a 'a) = f $(fmap 'a '(b1,b2)) = \x -> case x of (x1,x2) -> ($(fmap 'a 'b1) x1, $(fmap 'a 'b2) x2) $(fmap 'a '(T b1 b2)) = fmap $(fmap 'a 'b2) -- when a only occurs in the last parameter, b2 $(fmap 'a '(b -> c)) = \x b -> $(fmap 'a' 'c) (x ($(cofmap 'a 'b) b)) For functions, the type parameter 'a can occur in a contravariant position, which means we need to derive a function like: cofmap :: (a -> b) -> (f b -> f a) This is pretty much the same as $fmap, only without the $(cofmap 'a 'a) case: $(cofmap 'a 'b) = \x -> x -- when b does not contain a $(cofmap 'a 'a) = error "type variable in contravariant position" $(cofmap 'a '(b1,b2)) = \x -> case x of (x1,x2) -> ($(cofmap 'a 'b1) x1, $(cofmap 'a 'b2) x2) $(cofmap 'a '[b]) = map $(cofmap 'a 'b) $(cofmap 'a '(T b1 b2)) = fmap $(cofmap 'a 'b2) -- when a only occurs in the last parameter, b2 $(cofmap 'a '(b -> c)) = \x b -> $(cofmap 'a' 'c) (x ($(fmap 'a 'c) b)) Note that the code produced by $(fmap _ _) is always a higher order function, with type `(a -> b) -> (g a -> g b)` for some g. When we need to do pattern matching on the type, this means create a lambda function (see the (,) case above). The resulting code for fmap can look a bit weird, for example: data X a = X (a,Int) -- generated instance instance Functor X where fmap f (X x) = (\y -> case y of (x1,x2) -> X (f x1, (\z -> z) x2)) x The optimizer should be able to simplify this code by simple inlining. An older version of the deriving code tried to avoid these applied lambda functions by producing a meta level function. But the function to be mapped, `f`, is a function on the code level, not on the meta level, so it was eta expanded to `\x -> [| f $x |]`. This resulted in too much eta expansion. It is better to produce too many lambdas than to eta expand, see ticket #7436. -} gen_Functor_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Functor_binds loc tycon = (unitBag fmap_bind, emptyBag) where data_cons = tyConDataCons tycon fmap_bind = mkRdrFunBind (L loc fmap_RDR) eqns fmap_eqn con = evalState (match_for_con [f_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_fmap con eqns | null data_cons = [mkSimpleMatch [nlWildPat, nlWildPat] (error_Expr "Void fmap")] | otherwise = map fmap_eqn data_cons ft_fmap :: FFoldType (State [RdrName] (LHsExpr RdrName)) ft_fmap = FT { ft_triv = mkSimpleLam $ \x -> return x -- fmap f = \x -> x , ft_var = return f_Expr -- fmap f = f , ft_fun = \g h -> do -- fmap f = \x b -> h (x (g b)) gg <- g hh <- h mkSimpleLam2 $ \x b -> return $ nlHsApp hh (nlHsApp x (nlHsApp gg b)) , ft_tup = \t gs -> do -- fmap f = \x -> case x of (a1,a2,..) -> (g1 a1,g2 a2,..) gg <- sequence gs mkSimpleLam $ mkSimpleTupleCase match_for_con t gg , ft_ty_app = \_ g -> nlHsApp fmap_Expr <$> g -- fmap f = fmap g , ft_forall = \_ g -> g , ft_bad_app = panic "in other argument" , ft_co_var = panic "contravariant" } -- Con a1 a2 ... -> Con (f1 a1) (f2 a2) ... match_for_con :: [LPat RdrName] -> DataCon -> [LHsExpr RdrName] -> State [RdrName] (LMatch RdrName (LHsExpr RdrName)) match_for_con = mkSimpleConMatch $ \con_name xs -> return $ nlHsApps con_name xs -- Con x1 x2 .. {- Utility functions related to Functor deriving. Since several things use the same pattern of traversal, this is abstracted into functorLikeTraverse. This function works like a fold: it makes a value of type 'a' in a bottom up way. -} -- Generic traversal for Functor deriving data FFoldType a -- Describes how to fold over a Type in a functor like way = FT { ft_triv :: a -- Does not contain variable , ft_var :: a -- The variable itself , ft_co_var :: a -- The variable itself, contravariantly , ft_fun :: a -> a -> a -- Function type , ft_tup :: TyCon -> [a] -> a -- Tuple type , ft_ty_app :: Type -> a -> a -- Type app, variable only in last argument , ft_bad_app :: a -- Type app, variable other than in last argument , ft_forall :: TcTyVar -> a -> a -- Forall type } functorLikeTraverse :: forall a. TyVar -- ^ Variable to look for -> FFoldType a -- ^ How to fold -> Type -- ^ Type to process -> a functorLikeTraverse var (FT { ft_triv = caseTrivial, ft_var = caseVar , ft_co_var = caseCoVar, ft_fun = caseFun , ft_tup = caseTuple, ft_ty_app = caseTyApp , ft_bad_app = caseWrongArg, ft_forall = caseForAll }) ty = fst (go False ty) where go :: Bool -- Covariant or contravariant context -> Type -> (a, Bool) -- (result of type a, does type contain var) go co ty | Just ty' <- coreView ty = go co ty' go co (TyVarTy v) | v == var = (if co then caseCoVar else caseVar,True) go co (FunTy x y) | isPredTy x = go co y | xc || yc = (caseFun xr yr,True) where (xr,xc) = go (not co) x (yr,yc) = go co y go co (AppTy x y) | xc = (caseWrongArg, True) | yc = (caseTyApp x yr, True) where (_, xc) = go co x (yr,yc) = go co y go co ty@(TyConApp con args) | not (or xcs) = (caseTrivial, False) -- Variable does not occur -- At this point we know that xrs, xcs is not empty, -- and at least one xr is True | isTupleTyCon con = (caseTuple con xrs, True) | or (init xcs) = (caseWrongArg, True) -- T (..var..) ty | Just (fun_ty, _) <- splitAppTy_maybe ty -- T (..no var..) ty = (caseTyApp fun_ty (last xrs), True) | otherwise = (caseWrongArg, True) -- Non-decomposable (eg type function) where (xrs,xcs) = unzip (map (go co) args) go co (ForAllTy v x) | v /= var && xc = (caseForAll v xr,True) where (xr,xc) = go co x go _ _ = (caseTrivial,False) -- Return all syntactic subterms of ty that contain var somewhere -- These are the things that should appear in instance constraints deepSubtypesContaining :: TyVar -> Type -> [TcType] deepSubtypesContaining tv = functorLikeTraverse tv (FT { ft_triv = [] , ft_var = [] , ft_fun = (++) , ft_tup = \_ xs -> concat xs , ft_ty_app = (:) , ft_bad_app = panic "in other argument" , ft_co_var = panic "contravariant" , ft_forall = \v xs -> filterOut ((v `elemVarSet`) . tyVarsOfType) xs }) foldDataConArgs :: FFoldType a -> DataCon -> [a] -- Fold over the arguments of the datacon foldDataConArgs ft con = map foldArg (dataConOrigArgTys con) where foldArg = case getTyVar_maybe (last (tyConAppArgs (dataConOrigResTy con))) of Just tv -> functorLikeTraverse tv ft Nothing -> const (ft_triv ft) -- If we are deriving Foldable for a GADT, there is a chance that the last -- type variable in the data type isn't actually a type variable at all. -- (for example, this can happen if the last type variable is refined to -- be a concrete type such as Int). If the last type variable is refined -- to be a specific type, then getTyVar_maybe will return Nothing. -- See Note [DeriveFoldable with ExistentialQuantification] -- -- The kind checks have ensured the last type parameter is of kind *. -- Make a HsLam using a fresh variable from a State monad mkSimpleLam :: (LHsExpr RdrName -> State [RdrName] (LHsExpr RdrName)) -> State [RdrName] (LHsExpr RdrName) -- (mkSimpleLam fn) returns (\x. fn(x)) mkSimpleLam lam = do (n:names) <- get put names body <- lam (nlHsVar n) return (mkHsLam [nlVarPat n] body) mkSimpleLam2 :: (LHsExpr RdrName -> LHsExpr RdrName -> State [RdrName] (LHsExpr RdrName)) -> State [RdrName] (LHsExpr RdrName) mkSimpleLam2 lam = do (n1:n2:names) <- get put names body <- lam (nlHsVar n1) (nlHsVar n2) return (mkHsLam [nlVarPat n1,nlVarPat n2] body) -- "Con a1 a2 a3 -> fold [x1 a1, x2 a2, x3 a3]" mkSimpleConMatch :: Monad m => (RdrName -> [LHsExpr RdrName] -> m (LHsExpr RdrName)) -> [LPat RdrName] -> DataCon -> [LHsExpr RdrName] -> m (LMatch RdrName (LHsExpr RdrName)) mkSimpleConMatch fold extra_pats con insides = do let con_name = getRdrName con let vars_needed = takeList insides as_RDRs let pat = nlConVarPat con_name vars_needed rhs <- fold con_name (zipWith nlHsApp insides (map nlHsVar vars_needed)) return $ mkMatch (extra_pats ++ [pat]) rhs emptyLocalBinds -- "case x of (a1,a2,a3) -> fold [x1 a1, x2 a2, x3 a3]" mkSimpleTupleCase :: Monad m => ([LPat RdrName] -> DataCon -> [a] -> m (LMatch RdrName (LHsExpr RdrName))) -> TyCon -> [a] -> LHsExpr RdrName -> m (LHsExpr RdrName) mkSimpleTupleCase match_for_con tc insides x = do { let data_con = tyConSingleDataCon tc ; match <- match_for_con [] data_con insides ; return $ nlHsCase x [match] } {- ************************************************************************ * * Foldable instances see http://www.mail-archive.com/haskell-prime@haskell.org/msg02116.html * * ************************************************************************ Deriving Foldable instances works the same way as Functor instances, only Foldable instances are not possible for function types at all. Here the derived instance for the type T above is: instance Foldable T where foldr f z (T1 x1 x2 x3) = $(foldr 'a 'b1) x1 ( $(foldr 'a 'a) x2 ( $(foldr 'a 'b2) x3 z ) ) The cases are: $(foldr 'a 'b) = \x z -> z -- when b does not contain a $(foldr 'a 'a) = f $(foldr 'a '(b1,b2)) = \x z -> case x of (x1,x2) -> $(foldr 'a 'b1) x1 ( $(foldr 'a 'b2) x2 z ) $(foldr 'a '(T b1 b2)) = \x z -> foldr $(foldr 'a 'b2) z x -- when a only occurs in the last parameter, b2 Note that the arguments to the real foldr function are the wrong way around, since (f :: a -> b -> b), while (foldr f :: b -> t a -> b). Foldable instances differ from Functor and Traversable instances in that Foldable instances can be derived for data types in which the last type variable is existentially quantified. In particular, if the last type variable is refined to a more specific type in a GADT: data GADT a where G :: a ~ Int => a -> G Int then the deriving machinery does not attempt to check that the type a contains Int, since it is not syntactically equal to a type variable. That is, the derived Foldable instance for GADT is: instance Foldable GADT where foldr _ z (GADT _) = z See Note [DeriveFoldable with ExistentialQuantification]. -} gen_Foldable_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Foldable_binds loc tycon = (listToBag [foldr_bind, foldMap_bind], emptyBag) where data_cons = tyConDataCons tycon foldr_bind = mkRdrFunBind (L loc foldable_foldr_RDR) eqns eqns = map foldr_eqn data_cons foldr_eqn con = evalState (match_foldr z_Expr [f_Pat,z_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_foldr con foldMap_bind = mkRdrFunBind (L loc foldMap_RDR) (map foldMap_eqn data_cons) foldMap_eqn con = evalState (match_foldMap [f_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_foldMap con ft_foldr :: FFoldType (State [RdrName] (LHsExpr RdrName)) ft_foldr = FT { ft_triv = mkSimpleLam2 $ \_ z -> return z -- foldr f = \x z -> z , ft_var = return f_Expr -- foldr f = f , ft_tup = \t g -> do gg <- sequence g -- foldr f = (\x z -> case x of ...) mkSimpleLam2 $ \x z -> mkSimpleTupleCase (match_foldr z) t gg x , ft_ty_app = \_ g -> do gg <- g -- foldr f = (\x z -> foldr g z x) mkSimpleLam2 $ \x z -> return $ nlHsApps foldable_foldr_RDR [gg,z,x] , ft_forall = \_ g -> g , ft_co_var = panic "contravariant" , ft_fun = panic "function" , ft_bad_app = panic "in other argument" } match_foldr z = mkSimpleConMatch $ \_con_name xs -> return $ foldr nlHsApp z xs -- g1 v1 (g2 v2 (.. z)) ft_foldMap :: FFoldType (State [RdrName] (LHsExpr RdrName)) ft_foldMap = FT { ft_triv = mkSimpleLam $ \_ -> return mempty_Expr -- foldMap f = \x -> mempty , ft_var = return f_Expr -- foldMap f = f , ft_tup = \t g -> do gg <- sequence g -- foldMap f = \x -> case x of (..,) mkSimpleLam $ mkSimpleTupleCase match_foldMap t gg , ft_ty_app = \_ g -> nlHsApp foldMap_Expr <$> g -- foldMap f = foldMap g , ft_forall = \_ g -> g , ft_co_var = panic "contravariant" , ft_fun = panic "function" , ft_bad_app = panic "in other argument" } match_foldMap = mkSimpleConMatch $ \_con_name xs -> return $ case xs of [] -> mempty_Expr xs -> foldr1 (\x y -> nlHsApps mappend_RDR [x,y]) xs {- ************************************************************************ * * Traversable instances see http://www.mail-archive.com/haskell-prime@haskell.org/msg02116.html * * ************************************************************************ Again, Traversable is much like Functor and Foldable. The cases are: $(traverse 'a 'b) = pure -- when b does not contain a $(traverse 'a 'a) = f $(traverse 'a '(b1,b2)) = \x -> case x of (x1,x2) -> (,) <$> $(traverse 'a 'b1) x1 <*> $(traverse 'a 'b2) x2 $(traverse 'a '(T b1 b2)) = traverse $(traverse 'a 'b2) -- when a only occurs in the last parameter, b2 Note that the generated code is not as efficient as it could be. For instance: data T a = T Int a deriving Traversable gives the function: traverse f (T x y) = T <$> pure x <*> f y instead of: traverse f (T x y) = T x <$> f y -} gen_Traversable_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Traversable_binds loc tycon = (unitBag traverse_bind, emptyBag) where data_cons = tyConDataCons tycon traverse_bind = mkRdrFunBind (L loc traverse_RDR) eqns eqns = map traverse_eqn data_cons traverse_eqn con = evalState (match_for_con [f_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_trav con ft_trav :: FFoldType (State [RdrName] (LHsExpr RdrName)) ft_trav = FT { ft_triv = return pure_Expr -- traverse f = pure x , ft_var = return f_Expr -- traverse f = f x , ft_tup = \t gs -> do -- traverse f = \x -> case x of (a1,a2,..) -> gg <- sequence gs -- (,,) <$> g1 a1 <*> g2 a2 <*> .. mkSimpleLam $ mkSimpleTupleCase match_for_con t gg , ft_ty_app = \_ g -> nlHsApp traverse_Expr <$> g -- traverse f = travese g , ft_forall = \_ g -> g , ft_co_var = panic "contravariant" , ft_fun = panic "function" , ft_bad_app = panic "in other argument" } -- Con a1 a2 ... -> Con <$> g1 a1 <*> g2 a2 <*> ... match_for_con = mkSimpleConMatch $ \con_name xs -> return $ mkApCon (nlHsVar con_name) xs -- ((Con <$> x1) <*> x2) <*> .. mkApCon con [] = nlHsApps pure_RDR [con] mkApCon con (x:xs) = foldl appAp (nlHsApps fmap_RDR [con,x]) xs where appAp x y = nlHsApps ap_RDR [x,y] {- ************************************************************************ * * Lift instances * * ************************************************************************ Example: data Foo a = Foo a | a :^: a deriving Lift ==> instance (Lift a) => Lift (Foo a) where lift (Foo a) = appE (conE (mkNameG_d "package-name" "ModuleName" "Foo")) (lift a) lift (u :^: v) = infixApp (lift u) (conE (mkNameG_d "package-name" "ModuleName" ":^:")) (lift v) Note that (mkNameG_d "package-name" "ModuleName" "Foo") is equivalent to what 'Foo would be when using the -XTemplateHaskell extension. To make sure that -XDeriveLift can be used on stage-1 compilers, however, we expliticly invoke makeG_d. -} gen_Lift_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Lift_binds loc tycon | null data_cons = (unitBag (L loc $ mkFunBind (L loc lift_RDR) [mkMatch [nlWildPat] errorMsg_Expr emptyLocalBinds]) , emptyBag) | otherwise = (unitBag lift_bind, emptyBag) where errorMsg_Expr = nlHsVar error_RDR `nlHsApp` nlHsLit (mkHsString $ "Can't lift value of empty datatype " ++ tycon_str) lift_bind = mk_FunBind loc lift_RDR (map pats_etc data_cons) data_cons = tyConDataCons tycon tycon_str = occNameString . nameOccName . tyConName $ tycon pats_etc data_con = ([con_pat], lift_Expr) where con_pat = nlConVarPat data_con_RDR as_needed data_con_RDR = getRdrName data_con con_arity = dataConSourceArity data_con as_needed = take con_arity as_RDRs lifted_as = zipWithEqual "mk_lift_app" mk_lift_app tys_needed as_needed tycon_name = tyConName tycon is_infix = dataConIsInfix data_con tys_needed = dataConOrigArgTys data_con mk_lift_app ty a | not (isUnLiftedType ty) = nlHsApp (nlHsVar lift_RDR) (nlHsVar a) | otherwise = nlHsApp (nlHsVar litE_RDR) (primLitOp (mkBoxExp (nlHsVar a))) where (primLitOp, mkBoxExp) = primLitOps "Lift" tycon ty pkg_name = unitIdString . moduleUnitId . nameModule $ tycon_name mod_name = moduleNameString . moduleName . nameModule $ tycon_name con_name = occNameString . nameOccName . dataConName $ data_con conE_Expr = nlHsApp (nlHsVar conE_RDR) (nlHsApps mkNameG_dRDR (map (nlHsLit . mkHsString) [pkg_name, mod_name, con_name])) lift_Expr | is_infix = nlHsApps infixApp_RDR [a1, conE_Expr, a2] | otherwise = foldl mk_appE_app conE_Expr lifted_as (a1:a2:_) = lifted_as mk_appE_app :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName mk_appE_app a b = nlHsApps appE_RDR [a, b] {- ************************************************************************ * * Newtype-deriving instances * * ************************************************************************ We take every method in the original instance and `coerce` it to fit into the derived instance. We need a type annotation on the argument to `coerce` to make it obvious what instantiation of the method we're coercing from. See #8503 for more discussion. -} mkCoerceClassMethEqn :: Class -- the class being derived -> [TyVar] -- the tvs in the instance head -> [Type] -- instance head parameters (incl. newtype) -> Type -- the representation type (already eta-reduced) -> Id -- the method to look at -> Pair Type mkCoerceClassMethEqn cls inst_tvs cls_tys rhs_ty id = Pair (substTy rhs_subst user_meth_ty) (substTy lhs_subst user_meth_ty) where cls_tvs = classTyVars cls in_scope = mkInScopeSet $ mkVarSet inst_tvs lhs_subst = mkTvSubst in_scope (zipTyEnv cls_tvs cls_tys) rhs_subst = mkTvSubst in_scope (zipTyEnv cls_tvs (changeLast cls_tys rhs_ty)) (_class_tvs, _class_constraint, user_meth_ty) = tcSplitSigmaTy (varType id) changeLast :: [a] -> a -> [a] changeLast [] _ = panic "changeLast" changeLast [_] x = [x] changeLast (x:xs) x' = x : changeLast xs x' gen_Newtype_binds :: SrcSpan -> Class -- the class being derived -> [TyVar] -- the tvs in the instance head -> [Type] -- instance head parameters (incl. newtype) -> Type -- the representation type (already eta-reduced) -> LHsBinds RdrName gen_Newtype_binds loc cls inst_tvs cls_tys rhs_ty = listToBag $ zipWith mk_bind (classMethods cls) (map (mkCoerceClassMethEqn cls inst_tvs cls_tys rhs_ty) (classMethods cls)) where coerce_RDR = getRdrName coerceId mk_bind :: Id -> Pair Type -> LHsBind RdrName mk_bind id (Pair tau_ty user_ty) = mkRdrFunBind (L loc meth_RDR) [mkSimpleMatch [] rhs_expr] where meth_RDR = getRdrName id rhs_expr = ( nlHsVar coerce_RDR `nlHsApp` (nlHsVar meth_RDR `nlExprWithTySig` toHsType tau_ty')) `nlExprWithTySig` toHsType user_ty -- Open the representation type here, so that it's forall'ed type -- variables refer to the ones bound in the user_ty (_, _, tau_ty') = tcSplitSigmaTy tau_ty nlExprWithTySig :: LHsExpr RdrName -> LHsType RdrName -> LHsExpr RdrName nlExprWithTySig e s = noLoc (ExprWithTySig e s PlaceHolder) {- ************************************************************************ * * \subsection{Generating extra binds (@con2tag@ and @tag2con@)} * * ************************************************************************ \begin{verbatim} data Foo ... = ... con2tag_Foo :: Foo ... -> Int# tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int# maxtag_Foo :: Int -- ditto (NB: not unlifted) \end{verbatim} The `tags' here start at zero, hence the @fIRST_TAG@ (currently one) fiddling around. -} genAuxBindSpec :: SrcSpan -> AuxBindSpec -> (LHsBind RdrName, LSig RdrName) genAuxBindSpec loc (DerivCon2Tag tycon) = (mk_FunBind loc rdr_name eqns, L loc (TypeSig [L loc rdr_name] (L loc sig_ty) PlaceHolder)) where rdr_name = con2tag_RDR tycon sig_ty = HsCoreTy $ mkSigmaTy (tyConTyVars tycon) (tyConStupidTheta tycon) $ mkParentType tycon `mkFunTy` intPrimTy lots_of_constructors = tyConFamilySize tycon > 8 -- was: mAX_FAMILY_SIZE_FOR_VEC_RETURNS -- but we don't do vectored returns any more. eqns | lots_of_constructors = [get_tag_eqn] | otherwise = map mk_eqn (tyConDataCons tycon) get_tag_eqn = ([nlVarPat a_RDR], nlHsApp (nlHsVar getTag_RDR) a_Expr) mk_eqn :: DataCon -> ([LPat RdrName], LHsExpr RdrName) mk_eqn con = ([nlWildConPat con], nlHsLit (HsIntPrim "" (toInteger ((dataConTag con) - fIRST_TAG)))) genAuxBindSpec loc (DerivTag2Con tycon) = (mk_FunBind loc rdr_name [([nlConVarPat intDataCon_RDR [a_RDR]], nlHsApp (nlHsVar tagToEnum_RDR) a_Expr)], L loc (TypeSig [L loc rdr_name] (L loc sig_ty) PlaceHolder)) where sig_ty = HsCoreTy $ mkForAllTys (tyConTyVars tycon) $ intTy `mkFunTy` mkParentType tycon rdr_name = tag2con_RDR tycon genAuxBindSpec loc (DerivMaxTag tycon) = (mkHsVarBind loc rdr_name rhs, L loc (TypeSig [L loc rdr_name] (L loc sig_ty) PlaceHolder)) where rdr_name = maxtag_RDR tycon sig_ty = HsCoreTy intTy rhs = nlHsApp (nlHsVar intDataCon_RDR) (nlHsLit (HsIntPrim "" max_tag)) max_tag = case (tyConDataCons tycon) of data_cons -> toInteger ((length data_cons) - fIRST_TAG) type SeparateBagsDerivStuff = -- AuxBinds and SYB bindings ( Bag (LHsBind RdrName, LSig RdrName) -- Extra bindings (used by Generic only) , Bag TyCon -- Extra top-level datatypes , Bag (FamInst) -- Extra family instances , Bag (InstInfo RdrName)) -- Extra instances genAuxBinds :: SrcSpan -> BagDerivStuff -> SeparateBagsDerivStuff genAuxBinds loc b = genAuxBinds' b2 where (b1,b2) = partitionBagWith splitDerivAuxBind b splitDerivAuxBind (DerivAuxBind x) = Left x splitDerivAuxBind x = Right x rm_dups = foldrBag dup_check emptyBag dup_check a b = if anyBag (== a) b then b else consBag a b genAuxBinds' :: BagDerivStuff -> SeparateBagsDerivStuff genAuxBinds' = foldrBag f ( mapBag (genAuxBindSpec loc) (rm_dups b1) , emptyBag, emptyBag, emptyBag) f :: DerivStuff -> SeparateBagsDerivStuff -> SeparateBagsDerivStuff f (DerivAuxBind _) = panic "genAuxBinds'" -- We have removed these before f (DerivHsBind b) = add1 b f (DerivTyCon t) = add2 t f (DerivFamInst t) = add3 t f (DerivInst i) = add4 i add1 x (a,b,c,d) = (x `consBag` a,b,c,d) add2 x (a,b,c,d) = (a,x `consBag` b,c,d) add3 x (a,b,c,d) = (a,b,x `consBag` c,d) add4 x (a,b,c,d) = (a,b,c,x `consBag` d) mk_data_type_name :: TyCon -> RdrName -- "$tT" mk_data_type_name tycon = mkAuxBinderName (tyConName tycon) mkDataTOcc mk_constr_name :: DataCon -> RdrName -- "$cC" mk_constr_name con = mkAuxBinderName (dataConName con) mkDataCOcc mkParentType :: TyCon -> Type -- Turn the representation tycon of a family into -- a use of its family constructor mkParentType tc = case tyConFamInst_maybe tc of Nothing -> mkTyConApp tc (mkTyVarTys (tyConTyVars tc)) Just (fam_tc,tys) -> mkTyConApp fam_tc tys {- ************************************************************************ * * \subsection{Utility bits for generating bindings} * * ************************************************************************ -} mk_FunBind :: SrcSpan -> RdrName -> [([LPat RdrName], LHsExpr RdrName)] -> LHsBind RdrName mk_FunBind loc fun pats_and_exprs = mkRdrFunBind (L loc fun) matches where matches = [mkMatch p e emptyLocalBinds | (p,e) <-pats_and_exprs] mkRdrFunBind :: Located RdrName -> [LMatch RdrName (LHsExpr RdrName)] -> LHsBind RdrName mkRdrFunBind fun@(L loc fun_rdr) matches = L loc (mkFunBind fun matches') where -- Catch-all eqn looks like -- fmap = error "Void fmap" -- It's needed if there no data cons at all, -- which can happen with -XEmptyDataDecls -- See Trac #4302 matches' = if null matches then [mkMatch [] (error_Expr str) emptyLocalBinds] else matches str = "Void " ++ occNameString (rdrNameOcc fun_rdr) box :: String -- The class involved -> TyCon -- The tycon involved -> LHsExpr RdrName -- The argument -> Type -- The argument type -> LHsExpr RdrName -- Boxed version of the arg -- See Note [Deriving and unboxed types] in TcDeriv box cls_str tycon arg arg_ty = nlHsApp (nlHsVar box_con) arg where box_con = assoc_ty_id cls_str tycon boxConTbl arg_ty --------------------- primOrdOps :: String -- The class involved -> TyCon -- The tycon involved -> Type -- The type -> (RdrName, RdrName, RdrName, RdrName, RdrName) -- (lt,le,eq,ge,gt) -- See Note [Deriving and unboxed types] in TcDeriv primOrdOps str tycon ty = assoc_ty_id str tycon ordOpTbl ty primLitOps :: String -- The class involved -> TyCon -- The tycon involved -> Type -- The type -> ( LHsExpr RdrName -> LHsExpr RdrName -- Constructs a Q Exp value , LHsExpr RdrName -> LHsExpr RdrName -- Constructs a boxed value ) primLitOps str tycon ty = ( assoc_ty_id str tycon litConTbl ty , \v -> nlHsVar boxRDR `nlHsApp` v ) where boxRDR | ty == addrPrimTy = unpackCString_RDR | otherwise = assoc_ty_id str tycon boxConTbl ty ordOpTbl :: [(Type, (RdrName, RdrName, RdrName, RdrName, RdrName))] ordOpTbl = [(charPrimTy , (ltChar_RDR , leChar_RDR , eqChar_RDR , geChar_RDR , gtChar_RDR )) ,(intPrimTy , (ltInt_RDR , leInt_RDR , eqInt_RDR , geInt_RDR , gtInt_RDR )) ,(wordPrimTy , (ltWord_RDR , leWord_RDR , eqWord_RDR , geWord_RDR , gtWord_RDR )) ,(addrPrimTy , (ltAddr_RDR , leAddr_RDR , eqAddr_RDR , geAddr_RDR , gtAddr_RDR )) ,(floatPrimTy , (ltFloat_RDR , leFloat_RDR , eqFloat_RDR , geFloat_RDR , gtFloat_RDR )) ,(doublePrimTy, (ltDouble_RDR, leDouble_RDR, eqDouble_RDR, geDouble_RDR, gtDouble_RDR)) ] boxConTbl :: [(Type, RdrName)] boxConTbl = [(charPrimTy , getRdrName charDataCon ) ,(intPrimTy , getRdrName intDataCon ) ,(wordPrimTy , getRdrName wordDataCon ) ,(floatPrimTy , getRdrName floatDataCon ) ,(doublePrimTy, getRdrName doubleDataCon) ] -- | A table of postfix modifiers for unboxed values. postfixModTbl :: [(Type, String)] postfixModTbl = [(charPrimTy , "#" ) ,(intPrimTy , "#" ) ,(wordPrimTy , "##") ,(floatPrimTy , "#" ) ,(doublePrimTy, "##") ] litConTbl :: [(Type, LHsExpr RdrName -> LHsExpr RdrName)] litConTbl = [(charPrimTy , nlHsApp (nlHsVar charPrimL_RDR)) ,(intPrimTy , nlHsApp (nlHsVar intPrimL_RDR) . nlHsApp (nlHsVar toInteger_RDR)) ,(wordPrimTy , nlHsApp (nlHsVar wordPrimL_RDR) . nlHsApp (nlHsVar toInteger_RDR)) ,(addrPrimTy , nlHsApp (nlHsVar stringPrimL_RDR) . nlHsApp (nlHsApp (nlHsVar map_RDR) (compose_RDR `nlHsApps` [ nlHsVar fromIntegral_RDR , nlHsVar fromEnum_RDR ]))) ,(floatPrimTy , nlHsApp (nlHsVar floatPrimL_RDR) . nlHsApp (nlHsVar toRational_RDR)) ,(doublePrimTy, nlHsApp (nlHsVar doublePrimL_RDR) . nlHsApp (nlHsVar toRational_RDR)) ] -- | Lookup `Type` in an association list. assoc_ty_id :: String -- The class involved -> TyCon -- The tycon involved -> [(Type,a)] -- The table -> Type -- The type -> a -- The result of the lookup assoc_ty_id cls_str _ tbl ty | null res = pprPanic "Error in deriving:" (text "Can't derive" <+> text cls_str <+> text "for primitive type" <+> ppr ty) | otherwise = head res where res = [id | (ty',id) <- tbl, ty `eqType` ty'] ----------------------------------------------------------------------- and_Expr :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName and_Expr a b = genOpApp a and_RDR b ----------------------------------------------------------------------- eq_Expr :: TyCon -> Type -> LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName eq_Expr tycon ty a b | not (isUnLiftedType ty) = genOpApp a eq_RDR b | otherwise = genPrimOpApp a prim_eq b where (_, _, prim_eq, _, _) = primOrdOps "Eq" tycon ty untag_Expr :: TyCon -> [( RdrName, RdrName)] -> LHsExpr RdrName -> LHsExpr RdrName untag_Expr _ [] expr = expr untag_Expr tycon ((untag_this, put_tag_here) : more) expr = nlHsCase (nlHsPar (nlHsVarApps (con2tag_RDR tycon) [untag_this])) {-of-} [mkSimpleHsAlt (nlVarPat put_tag_here) (untag_Expr tycon more expr)] enum_from_to_Expr :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName enum_from_then_to_Expr :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName enum_from_to_Expr f t2 = nlHsApp (nlHsApp (nlHsVar enumFromTo_RDR) f) t2 enum_from_then_to_Expr f t t2 = nlHsApp (nlHsApp (nlHsApp (nlHsVar enumFromThenTo_RDR) f) t) t2 showParen_Expr :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName showParen_Expr e1 e2 = nlHsApp (nlHsApp (nlHsVar showParen_RDR) e1) e2 nested_compose_Expr :: [LHsExpr RdrName] -> LHsExpr RdrName nested_compose_Expr [] = panic "nested_compose_expr" -- Arg is always non-empty nested_compose_Expr [e] = parenify e nested_compose_Expr (e:es) = nlHsApp (nlHsApp (nlHsVar compose_RDR) (parenify e)) (nested_compose_Expr es) -- impossible_Expr is used in case RHSs that should never happen. -- We generate these to keep the desugarer from complaining that they *might* happen! error_Expr :: String -> LHsExpr RdrName error_Expr string = nlHsApp (nlHsVar error_RDR) (nlHsLit (mkHsString string)) -- illegal_Expr is used when signalling error conditions in the RHS of a derived -- method. It is currently only used by Enum.{succ,pred} illegal_Expr :: String -> String -> String -> LHsExpr RdrName illegal_Expr meth tp msg = nlHsApp (nlHsVar error_RDR) (nlHsLit (mkHsString (meth ++ '{':tp ++ "}: " ++ msg))) -- illegal_toEnum_tag is an extended version of illegal_Expr, which also allows you -- to include the value of a_RDR in the error string. illegal_toEnum_tag :: String -> RdrName -> LHsExpr RdrName illegal_toEnum_tag tp maxtag = nlHsApp (nlHsVar error_RDR) (nlHsApp (nlHsApp (nlHsVar append_RDR) (nlHsLit (mkHsString ("toEnum{" ++ tp ++ "}: tag (")))) (nlHsApp (nlHsApp (nlHsApp (nlHsVar showsPrec_RDR) (nlHsIntLit 0)) (nlHsVar a_RDR)) (nlHsApp (nlHsApp (nlHsVar append_RDR) (nlHsLit (mkHsString ") is outside of enumeration's range (0,"))) (nlHsApp (nlHsApp (nlHsApp (nlHsVar showsPrec_RDR) (nlHsIntLit 0)) (nlHsVar maxtag)) (nlHsLit (mkHsString ")")))))) parenify :: LHsExpr RdrName -> LHsExpr RdrName parenify e@(L _ (HsVar _)) = e parenify e = mkHsPar e -- genOpApp wraps brackets round the operator application, so that the -- renamer won't subsequently try to re-associate it. genOpApp :: LHsExpr RdrName -> RdrName -> LHsExpr RdrName -> LHsExpr RdrName genOpApp e1 op e2 = nlHsPar (nlHsOpApp e1 op e2) genPrimOpApp :: LHsExpr RdrName -> RdrName -> LHsExpr RdrName -> LHsExpr RdrName genPrimOpApp e1 op e2 = nlHsPar (nlHsApp (nlHsVar tagToEnum_RDR) (nlHsOpApp e1 op e2)) a_RDR, b_RDR, c_RDR, d_RDR, f_RDR, k_RDR, z_RDR, ah_RDR, bh_RDR, ch_RDR, dh_RDR :: RdrName a_RDR = mkVarUnqual (fsLit "a") b_RDR = mkVarUnqual (fsLit "b") c_RDR = mkVarUnqual (fsLit "c") d_RDR = mkVarUnqual (fsLit "d") f_RDR = mkVarUnqual (fsLit "f") k_RDR = mkVarUnqual (fsLit "k") z_RDR = mkVarUnqual (fsLit "z") ah_RDR = mkVarUnqual (fsLit "a#") bh_RDR = mkVarUnqual (fsLit "b#") ch_RDR = mkVarUnqual (fsLit "c#") dh_RDR = mkVarUnqual (fsLit "d#") as_RDRs, bs_RDRs, cs_RDRs :: [RdrName] as_RDRs = [ mkVarUnqual (mkFastString ("a"++show i)) | i <- [(1::Int) .. ] ] bs_RDRs = [ mkVarUnqual (mkFastString ("b"++show i)) | i <- [(1::Int) .. ] ] cs_RDRs = [ mkVarUnqual (mkFastString ("c"++show i)) | i <- [(1::Int) .. ] ] a_Expr, c_Expr, f_Expr, z_Expr, ltTag_Expr, eqTag_Expr, gtTag_Expr, false_Expr, true_Expr, fmap_Expr, pure_Expr, mempty_Expr, foldMap_Expr, traverse_Expr :: LHsExpr RdrName a_Expr = nlHsVar a_RDR -- b_Expr = nlHsVar b_RDR c_Expr = nlHsVar c_RDR f_Expr = nlHsVar f_RDR z_Expr = nlHsVar z_RDR ltTag_Expr = nlHsVar ltTag_RDR eqTag_Expr = nlHsVar eqTag_RDR gtTag_Expr = nlHsVar gtTag_RDR false_Expr = nlHsVar false_RDR true_Expr = nlHsVar true_RDR fmap_Expr = nlHsVar fmap_RDR pure_Expr = nlHsVar pure_RDR mempty_Expr = nlHsVar mempty_RDR foldMap_Expr = nlHsVar foldMap_RDR traverse_Expr = nlHsVar traverse_RDR a_Pat, b_Pat, c_Pat, d_Pat, f_Pat, k_Pat, z_Pat :: LPat RdrName a_Pat = nlVarPat a_RDR b_Pat = nlVarPat b_RDR c_Pat = nlVarPat c_RDR d_Pat = nlVarPat d_RDR f_Pat = nlVarPat f_RDR k_Pat = nlVarPat k_RDR z_Pat = nlVarPat z_RDR minusInt_RDR, tagToEnum_RDR, error_RDR :: RdrName minusInt_RDR = getRdrName (primOpId IntSubOp ) tagToEnum_RDR = getRdrName (primOpId TagToEnumOp) error_RDR = getRdrName eRROR_ID con2tag_RDR, tag2con_RDR, maxtag_RDR :: TyCon -> RdrName -- Generates Orig s RdrName, for the binding positions con2tag_RDR tycon = mk_tc_deriv_name tycon mkCon2TagOcc tag2con_RDR tycon = mk_tc_deriv_name tycon mkTag2ConOcc maxtag_RDR tycon = mk_tc_deriv_name tycon mkMaxTagOcc mk_tc_deriv_name :: TyCon -> (OccName -> OccName) -> RdrName mk_tc_deriv_name tycon occ_fun = mkAuxBinderName (tyConName tycon) occ_fun mkAuxBinderName :: Name -> (OccName -> OccName) -> RdrName -- ^ Make a top-level binder name for an auxiliary binding for a parent name -- See Note [Auxiliary binders] mkAuxBinderName parent occ_fun = mkRdrUnqual (occ_fun stable_parent_occ) where stable_parent_occ = mkOccName (occNameSpace parent_occ) stable_string stable_string | opt_PprStyle_Debug = parent_stable | otherwise = parent_stable_hash parent_stable = nameStableString parent parent_stable_hash = let Fingerprint high low = fingerprintString parent_stable in toBase62 high ++ toBase62Padded low -- See Note [Base 62 encoding 128-bit integers] parent_occ = nameOccName parent {- Note [Auxiliary binders] ~~~~~~~~~~~~~~~~~~~~~~~~ We often want to make a top-level auxiliary binding. E.g. for comparison we haev instance Ord T where compare a b = $con2tag a `compare` $con2tag b $con2tag :: T -> Int $con2tag = ...code.... Of course these top-level bindings should all have distinct name, and we are generating RdrNames here. We can't just use the TyCon or DataCon to distinguish because with standalone deriving two imported TyCons might both be called T! (See Trac #7947.) So we use package name, module name and the name of the parent (T in this example) as part of the OccName we generate for the new binding. To make the symbol names short we take a base62 hash of the full name. In the past we used the *unique* from the parent, but that's not stable across recompilations as uniques are nondeterministic. Note [DeriveFoldable with ExistentialQuantification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Functor and Traversable instances can only be derived for data types whose last type parameter is truly universally polymorphic. For example: data T a b where T1 :: b -> T a b -- YES, b is unconstrained T2 :: Ord b => b -> T a b -- NO, b is constrained by (Ord b) T3 :: b ~ Int => b -> T a b -- NO, b is constrained by (b ~ Int) T4 :: Int -> T a Int -- NO, this is just like T3 T5 :: Ord a => a -> b -> T a b -- YES, b is unconstrained, even -- though a is existential T6 :: Int -> T Int b -- YES, b is unconstrained For Foldable instances, however, we can completely lift the constraint that the last type parameter be truly universally polymorphic. This means that T (as defined above) can have a derived Foldable instance: instance Foldable (T a) where foldr f z (T1 b) = f b z foldr f z (T2 b) = f b z foldr f z (T3 b) = f b z foldr f z (T4 b) = z foldr f z (T5 a b) = f b z foldr f z (T6 a) = z foldMap f (T1 b) = f b foldMap f (T2 b) = f b foldMap f (T3 b) = f b foldMap f (T4 b) = mempty foldMap f (T5 a b) = f b foldMap f (T6 a) = mempty In a Foldable instance, it is safe to fold over an occurrence of the last type parameter that is not truly universally polymorphic. However, there is a bit of subtlety in determining what is actually an occurrence of a type parameter. T3 and T4, as defined above, provide one example: data T a b where ... T3 :: b ~ Int => b -> T a b T4 :: Int -> T a Int ... instance Foldable (T a) where ... foldr f z (T3 b) = f b z foldr f z (T4 b) = z ... foldMap f (T3 b) = f b foldMap f (T4 b) = mempty ... Notice that the argument of T3 is folded over, whereas the argument of T4 is not. This is because we only fold over constructor arguments that syntactically mention the universally quantified type parameter of that particular data constructor. See foldDataConArgs for how this is implemented. As another example, consider the following data type. The argument of each constructor has the same type as the last type parameter: data E a where E1 :: (a ~ Int) => a -> E a E2 :: Int -> E Int E3 :: (a ~ Int) => a -> E Int E4 :: (a ~ Int) => Int -> E a Only E1's argument is an occurrence of a universally quantified type variable that is syntactically equivalent to the last type parameter, so only E1's argument will be be folded over in a derived Foldable instance. See Trac #10447 for the original discussion on this feature. Also see https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/DeriveFunctor for a more in-depth explanation. -}
siddhanathan/ghc
compiler/typecheck/TcGenDeriv.hs
bsd-3-clause
103,666
0
19
32,855
18,402
9,689
8,713
1,292
8
{-# LANGUAGE RecordWildCards, ScopedTypeVariables, MultiParamTypeClasses , DeriveDataTypeable, OverloadedStrings , GeneralizedNewtypeDeriving, FlexibleContexts #-} -- this module isn't finished, and there's heaps of warnings. {-# OPTIONS_GHC -w #-} -- | -- Module : Yi.Frontend.Pango.Control -- License : GPL module Yi.Frontend.Pango.Control ( Control(..) , ControlM(..) , Buffer(..) , View(..) , Iter(..) , startControl , runControl , controlIO , liftYi , getControl , newBuffer , newView , getBuffer , setBufferMode , withCurrentBuffer , setText , getText , keyTable ) where import Data.Text (unpack, pack, Text) import qualified Data.Text as T import Prelude hiding (concatMap, concat, foldl, elem, mapM_) import Control.Exception (catch) import Control.Monad hiding (mapM_, forM_) import Control.Monad.Reader hiding (mapM_, forM_) import Control.Applicative import Lens.Micro.Platform hiding (views, Action) import Data.Foldable import Data.Maybe (maybe, fromJust, fromMaybe) import Data.Monoid import Data.IORef import Data.List (nub, filter, drop, zip, take, length) import Data.Prototype import Yi.Rope (toText, splitAtLine, YiString) import qualified Yi.Rope as R import qualified Data.Map as Map import Yi.Core (startEditor, focusAllSyntax) import Yi.Buffer import Yi.Config import Yi.Tab import Yi.Window as Yi import Yi.Editor import Yi.Event import Yi.Keymap import Yi.Monad import Yi.Style import Yi.UI.Utils import Yi.Utils import Yi.Debug import Graphics.UI.Gtk as Gtk (Color(..), PangoRectangle(..), Rectangle(..), selectionDataSetText, targetString, clipboardSetWithData, clipboardRequestText, selectionPrimary, clipboardGetForDisplay, widgetGetDisplay, onMotionNotify, drawRectangle, drawLine, layoutIndexToPos, layoutGetCursorPos, drawLayout, widgetGetDrawWindow, layoutSetAttributes, widgetGrabFocus, scrolledWindowSetPolicy, scrolledWindowAddWithViewport, scrolledWindowNew, contextGetMetrics, contextGetLanguage, layoutSetFontDescription, layoutEmpty, widgetCreatePangoContext, widgetModifyBg, drawingAreaNew, FontDescription, ScrolledWindow, FontMetrics, Language, DrawingArea, layoutXYToIndex, layoutSetText, layoutGetText, widgetSetSizeRequest, layoutGetPixelExtents, layoutSetWidth, layoutGetWidth, layoutGetFontDescription, PangoLayout, descent, ascent, widgetGetSize, widgetQueueDraw, mainQuit, signalDisconnect, ConnectId(..), PolicyType(..), StateType(..), EventMask(..), AttrOp(..), Weight(..), PangoAttribute(..), Underline(..), FontStyle(..)) import Graphics.UI.Gtk.Gdk.GC as Gtk (newGCValues, gcSetValues, gcNew, foreground) import qualified Graphics.UI.Gtk as Gtk import qualified Graphics.UI.Gtk.Gdk.Events as Gdk.Events import System.Glib.GError import Control.Monad.Reader (ask, asks, MonadReader(..)) import Control.Monad.State (ap, get, put, modify) import Control.Monad.Base import Control.Concurrent (newMVar, modifyMVar, MVar, newEmptyMVar, putMVar, readMVar, isEmptyMVar) import Data.Typeable import qualified Data.List.PointedList as PL (insertRight, withFocus, PointedList(..), singleton) import Yi.Regex ((=~), AllTextSubmatches(..)) import Yi.String (showT) import System.FilePath import qualified Yi.UI.Common as Common data Control = Control { controlYi :: Yi , tabCache :: IORef [TabInfo] , views :: IORef (Map.Map WindowRef View) } -- { config :: Config -- , editor :: Editor -- , input :: Event -> IO () -- , output :: Action -> IO () -- } data TabInfo = TabInfo { coreTab :: Tab -- , page :: VBox } instance Show TabInfo where show t = show (coreTab t) --type ControlM = YiM newtype ControlM a = ControlM { runControl'' :: ReaderT Control IO a } deriving (Monad, MonadBase IO, MonadReader Control, Typeable, Functor, Applicative) -- Helper functions to avoid issues with mismatching monad libraries controlIO :: IO a -> ControlM a controlIO = liftBase getControl :: ControlM Control getControl = ask liftYi :: YiM a -> ControlM a liftYi m = do yi <- asks controlYi liftBase $ runReaderT (runYiM m) yi --instance MonadState Editor ControlM where -- get = readRef =<< editor <$> ask -- put v = flip modifyRef (const v) =<< editor <$> ask --instance MonadEditor ControlM where -- askCfg = config <$> ask -- withEditor f = do -- r <- asks editor -- cfg <- asks config -- liftBase $ controlUnsafeWithEditor cfg r f startControl :: Config -> ControlM () -> IO () startControl config main = startEditor (config { startFrontEnd = start main } ) Nothing runControl' :: ControlM a -> MVar Control -> IO (Maybe a) runControl' m yiMVar = do empty <- isEmptyMVar yiMVar if empty then return Nothing else do yi <- readMVar yiMVar result <- runControl m yi return $ Just result -- runControl :: ControlM a -> Yi -> IO a -- runControl m yi = runReaderT (runYiM m) yi runControl :: ControlM a -> Control -> IO a runControl f = runReaderT (runControl'' f) -- runControlEditor f yiMVar = yiMVar runAction :: Action -> ControlM () runAction action = do out <- liftYi $ asks yiOutput liftBase $ out MustRefresh [action] -- | Test 2 mkUI :: IO () -> MVar Control -> Common.UI Editor mkUI main yiMVar = Common.dummyUI { Common.main = main , Common.end = \_ -> void $ runControl' end yiMVar , Common.suspend = void $ runControl' suspend yiMVar , Common.refresh = \e -> void $ runControl' (refresh e) yiMVar , Common.layout = \e -> fmap (fromMaybe e) $ runControl' (doLayout e) yiMVar , Common.reloadProject = \f -> void $ runControl' (reloadProject f) yiMVar } start :: ControlM () -> UIBoot start main cfg ch outCh ed = catch (startNoMsg main cfg ch outCh ed) (\(GError _dom _code msg) -> fail $ unpack msg) makeControl :: MVar Control -> YiM () makeControl controlMVar = do controlYi <- ask tabCache <- liftBase $ newIORef [] views <- liftBase $ newIORef Map.empty liftBase $ putMVar controlMVar Control{..} startNoMsg :: ControlM () -> UIBoot startNoMsg main config input output ed = do control <- newEmptyMVar let wrappedMain = do output [makeAction $ makeControl control] void (runControl' main control) return (mkUI wrappedMain control) end :: ControlM () end = do liftBase $ putStrLn "Yi Control End" liftBase mainQuit suspend :: ControlM () suspend = do liftBase $ putStrLn "Yi Control Suspend" return () {-# ANN refresh ("HLint: ignore Redundant do" :: String) #-} refresh :: Editor -> ControlM () refresh e = do --contextId <- statusbarGetContextId (uiStatusbar ui) "global" --statusbarPop (uiStatusbar ui) contextId --statusbarPush (uiStatusbar ui) contextId $ intercalate " " $ statusLine e updateCache e -- The cursor may have changed since doLayout viewsRef <- asks views vs <- liftBase $ readIORef viewsRef forM_ (Map.elems vs) $ \v -> do let b = findBufferWith (viewFBufRef v) e -- when (not $ null $ b ^. pendingUpdatesA) $ do -- sig <- readIORef (renderer w) -- signalDisconnect sig -- writeRef (renderer w) -- =<< (textview w `onExpose` render e ui b (wkey (coreWin w))) liftBase $ widgetQueueDraw (drawArea v) doLayout :: Editor -> ControlM Editor doLayout e = do liftBase $ putStrLn "Yi Control Do Layout" updateCache e cacheRef <- asks tabCache tabs <- liftBase $ readIORef cacheRef dims <- concat <$> mapM (getDimensionsInTab e) tabs let e' = (tabsA %~ fmap (mapWindows updateWin)) e updateWin w = case find (\(ref,_,_,_) -> (wkey w == ref)) dims of Nothing -> w Just (_, wi, h,rgn) -> w { width = wi , height = h , winRegion = rgn } -- Don't leak references to old Windows let forceWin x w = height w `seq` winRegion w `seq` x return $ (foldl . tabFoldl) forceWin e' (e' ^. tabsA) -- | Width, Height getDimensionsInTab :: Editor -> TabInfo -> ControlM [(WindowRef,Int,Int,Region)] getDimensionsInTab e tab = do viewsRef <- asks views vs <- liftBase $ readIORef viewsRef foldlM (\a w -> case Map.lookup (wkey w) vs of Just v -> do (wi, h) <- liftBase $ widgetGetSize $ drawArea v let lineHeight = ascent (metrics v) + descent (metrics v) charWidth = Gtk.approximateCharWidth $ metrics v b0 = findBufferWith (viewFBufRef v) e rgn <- shownRegion e v b0 let ret= (windowRef v, round $ fromIntegral wi / charWidth, round $ fromIntegral h / lineHeight, rgn) return $ a <> [ret] Nothing -> return a) [] (coreTab tab ^. tabWindowsA) shownRegion :: Editor -> View -> FBuffer -> ControlM Region shownRegion e v b = do (tos, _, bos) <- updatePango e v b (layout v) return $ mkRegion tos bos updatePango :: Editor -> View -> FBuffer -> PangoLayout -> ControlM (Point, Point, Point) updatePango e v b layout = do (width', height') <- liftBase $ widgetGetSize $ drawArea v font <- liftBase $ layoutGetFontDescription layout --oldFont <- layoutGetFontDescription layout --oldFontStr <- maybe (return Nothing) -- (fmap Just . fontDescriptionToString) oldFont --newFontStr <- Just <$> fontDescriptionToString font --when (oldFontStr /= newFontStr) -- (layoutSetFontDescription layout (Just font)) let win = findWindowWith (windowRef v) e [width'', height''] = map fromIntegral [width', height'] lineHeight = ascent (metrics v) + descent (metrics v) winh = max 1 $ floor (height'' / lineHeight) (tos, point, text) = askBuffer win b $ do from <- (use . markPointA) =<< fromMark <$> askMarks rope <- streamB Forward from p <- pointB let content = fst $ splitAtLine winh rope -- allow BOS offset to be just after the last line let addNL = if R.countNewLines content == winh then id else (`R.snoc` '\n') return (from, p, R.toText $ addNL content) config <- liftYi askCfg if configLineWrap $ configUI config then do oldWidth <- liftBase $ layoutGetWidth layout when (oldWidth /= Just width'') $ liftBase $ layoutSetWidth layout $ Just width'' else do (Rectangle px _py pwidth _pheight, _) <- liftBase $ layoutGetPixelExtents layout liftBase $ widgetSetSizeRequest (drawArea v) (px+pwidth) (-1) -- optimize for cursor movement oldText <- liftBase $ layoutGetText layout when (oldText /= text) $ liftBase $ layoutSetText layout text (_, bosOffset, _) <- liftBase $ layoutXYToIndex layout width'' (fromIntegral winh * lineHeight - 1) return (tos, point, tos + fromIntegral bosOffset + 1) updateCache :: Editor -> ControlM () updateCache e = do let tabs = e ^. tabsA cacheRef <- asks tabCache cache <- liftBase $ readIORef cacheRef cache' <- syncTabs e (toList $ PL.withFocus tabs) cache liftBase $ writeIORef cacheRef cache' syncTabs :: Editor -> [(Tab, Bool)] -> [TabInfo] -> ControlM [TabInfo] syncTabs e (tfocused@(t,focused):ts) (c:cs) | t == coreTab c = do when focused $ setTabFocus c -- let vCache = views c (:) <$> syncTab e c t <*> syncTabs e ts cs | t `elem` map coreTab cs = do removeTab c syncTabs e (tfocused:ts) cs | otherwise = do c' <- insertTabBefore e t c when focused $ setTabFocus c' return (c':) `ap` syncTabs e ts (c:cs) syncTabs e ts [] = mapM (\(t,focused) -> do c' <- insertTab e t when focused $ setTabFocus c' return c') ts syncTabs _ [] cs = mapM_ removeTab cs >> return [] syncTab :: Editor -> TabInfo -> Tab -> ControlM TabInfo syncTab e tab ws = -- TODO Maybe do something here return tab setTabFocus :: TabInfo -> ControlM () setTabFocus t = -- TODO this needs to set the tab focus with callback -- but only if the tab focus has changed return () askBuffer :: Yi.Window -> FBuffer -> BufferM a -> a askBuffer w b f = fst $ runBuffer w b f setWindowFocus :: Editor -> TabInfo -> View -> ControlM () setWindowFocus e t v = do let bufferName = shortIdentString (length $ commonNamePrefix e) $ findBufferWith (viewFBufRef v) e window = findWindowWith (windowRef v) e ml = askBuffer window (findBufferWith (viewFBufRef v) e) $ getModeLine (T.pack <$> commonNamePrefix e) -- TODO -- update (textview w) widgetIsFocus True -- update (modeline w) labelText ml -- update (uiWindow ui) windowTitle $ bufferName <> " - Yi" -- update (uiNotebook ui) (notebookChildTabLabel (page t)) -- (tabAbbrevTitle bufferName) return () removeTab :: TabInfo -> ControlM () removeTab t = -- TODO this needs to close the views in the tab with callback return () removeView :: TabInfo -> View -> ControlM () removeView tab view = -- TODO this needs to close the view with callback return () -- | Make a new tab. newTab :: Editor -> Tab -> ControlM TabInfo newTab e ws = do let t' = TabInfo { coreTab = ws } -- cache <- syncWindows e t' (toList $ PL.withFocus ws) [] return t' -- { views = cache } {-# ANN insertTabBefore ("HLint: ignore Redundant do" :: String) #-} insertTabBefore :: Editor -> Tab -> TabInfo -> ControlM TabInfo insertTabBefore e ws c = do -- Just p <- notebookPageNum (uiNotebook ui) (page c) -- vb <- vBoxNew False 1 -- notebookInsertPage (uiNotebook ui) vb "" p -- widgetShowAll $ vb newTab e ws {-# ANN insertTab ("HLint: ignore Redundant do" :: String) #-} insertTab :: Editor -> Tab -> ControlM TabInfo insertTab e ws = do -- vb <- vBoxNew False 1 -- notebookAppendPage (uiNotebook ui) vb "" -- widgetShowAll $ vb newTab e ws {- insertWindowBefore :: Editor -> TabInfo -> Yi.Window -> WinInfo -> IO WinInfo insertWindowBefore e ui tab w _c = insertWindow e ui tab w insertWindowAtEnd :: Editor -> UI -> TabInfo -> Window -> IO WinInfo insertWindowAtEnd e ui tab w = insertWindow e ui tab w insertWindow :: Editor -> UI -> TabInfo -> Window -> IO WinInfo insertWindow e ui tab win = do let buf = findBufferWith (bufkey win) e liftBase $ do w <- newWindow e ui win buf set (page tab) $ [ containerChild := widget w , boxChildPacking (widget w) := if isMini (coreWin w) then PackNatural else PackGrow ] let ref = (wkey . coreWin) w textview w `onButtonRelease` handleClick ui ref textview w `onButtonPress` handleClick ui ref textview w `onScroll` handleScroll ui ref textview w `onConfigure` handleConfigure ui ref widgetShowAll (widget w) return w -} reloadProject :: FilePath -> ControlM () reloadProject _ = return () controlUnsafeWithEditor :: Config -> MVar Editor -> EditorM a -> IO a controlUnsafeWithEditor cfg r f = modifyMVar r $ \e -> do let (e',a) = runEditor cfg f e -- Make sure that the result of runEditor is evaluated before -- replacing the editor state. Otherwise, we might replace e -- with an exception-producing thunk, which makes it impossible -- to look at or update the editor state. -- Maybe this could also be fixed by -fno-state-hack flag? -- TODO: can we simplify this? e' `seq` a `seq` return (e', a) data Buffer = Buffer { fBufRef :: BufferRef } data View = View { viewFBufRef :: BufferRef , windowRef :: WindowRef , drawArea :: DrawingArea , layout :: PangoLayout , language :: Language , metrics :: FontMetrics , scrollWin :: ScrolledWindow , shownTos :: IORef Point , winMotionSignal :: IORef (Maybe (ConnectId DrawingArea)) } data Iter = Iter { iterFBufRef :: BufferRef , point :: Point } newBuffer :: BufferId -> R.YiString -> ControlM Buffer newBuffer id text = do fBufRef <- liftYi . withEditor . newBufferE id $ text return Buffer{..} newView :: Buffer -> FontDescription -> ControlM View newView buffer font = do control <- ask config <- liftYi askCfg let viewFBufRef = fBufRef buffer newWindow <- fmap (\w -> w { height=50 , winRegion = mkRegion (Point 0) (Point 2000) }) $ liftYi $ withEditor $ newWindowE False viewFBufRef let windowRef = wkey newWindow liftYi $ withEditor $ do windowsA %= PL.insertRight newWindow e <- get put $ focusAllSyntax e drawArea <- liftBase drawingAreaNew liftBase . widgetModifyBg drawArea StateNormal . mkCol False . Yi.Style.background . baseAttributes . configStyle $ configUI config context <- liftBase $ widgetCreatePangoContext drawArea layout <- liftBase $ layoutEmpty context liftBase $ layoutSetFontDescription layout (Just font) language <- liftBase $ contextGetLanguage context metrics <- liftBase $ contextGetMetrics context font language liftBase $ layoutSetText layout ("" :: Text) scrollWin <- liftBase $ scrolledWindowNew Nothing Nothing liftBase $ do scrolledWindowAddWithViewport scrollWin drawArea scrolledWindowSetPolicy scrollWin PolicyAutomatic PolicyNever initialTos <- liftYi . withEditor . withGivenBufferAndWindow newWindow viewFBufRef $ (use . markPointA) =<< fromMark <$> askMarks shownTos <- liftBase $ newIORef initialTos winMotionSignal <- liftBase $ newIORef Nothing let view = View {..} liftBase $ Gtk.widgetAddEvents drawArea [KeyPressMask] liftBase $ Gtk.set drawArea [Gtk.widgetCanFocus := True] liftBase $ drawArea `Gtk.onKeyPress` \event -> do putStrLn $ "Yi Control Key Press = " <> show event runControl (runAction $ makeAction $ do focusWindowE windowRef switchToBufferE viewFBufRef) control result <- processEvent (yiInput $ controlYi control) event widgetQueueDraw drawArea return result liftBase $ drawArea `Gtk.onButtonPress` \event -> do widgetGrabFocus drawArea runControl (handleClick view event) control liftBase $ drawArea `Gtk.onButtonRelease` \event -> runControl (handleClick view event) control liftBase $ drawArea `Gtk.onScroll` \event -> runControl (handleScroll view event) control liftBase $ drawArea `Gtk.onExpose` \event -> do (text, allAttrs, debug, tos, rel, point, inserting) <- runControl (liftYi $ withEditor $ do window <- findWindowWith windowRef <$> get (%=) buffersA (fmap (clearSyntax . clearHighlight)) let winh = height window let tos = max 0 (regionStart (winRegion window)) let bos = regionEnd (winRegion window) let rel p = fromIntegral (p - tos) withGivenBufferAndWindow window viewFBufRef $ do -- tos <- getMarkPointB =<< fromMark <$> askMarks rope <- streamB Forward tos point <- pointB inserting <- use insertingA modeNm <- gets (withMode0 modeName) -- let (tos, point, text, picture) = do runBu -- from <- getMarkPointB =<< fromMark <$> askMarks -- rope <- streamB Forward from -- p <- pointB let content = fst $ splitAtLine winh rope -- allow BOS offset to be just after the last line let addNL = if R.countNewLines content == winh then id else (`R.snoc` '\n') sty = configStyle $ configUI config -- attributesPictureAndSelB sty (currentRegex e) -- (mkRegion tos bos) -- return (from, p, addNL $ Rope.toString content, -- picture) let text = R.toText $ addNL content picture <- attributesPictureAndSelB sty Nothing (mkRegion tos bos) -- add color attributes. let picZip = zip picture $ drop 1 (fst <$> picture) <> [bos] strokes = [ (start',s,end') | ((start', s), end') <- picZip , s /= emptyAttributes ] rel p = fromIntegral (p - tos) allAttrs = concat $ do (p1, Attributes fg bg _rv bd itlc udrl, p2) <- strokes let atr x = x (rel p1) (rel p2) if' p x y = if p then x else y return [ atr AttrForeground $ mkCol True fg , atr AttrBackground $ mkCol False bg , atr AttrStyle $ if' itlc StyleItalic StyleNormal , atr AttrUnderline $ if' udrl UnderlineSingle UnderlineNone , atr AttrWeight $ if' bd WeightBold WeightNormal ] return (text, allAttrs, (picture, strokes, modeNm, window, tos, bos, winh), tos, rel, point, inserting)) control -- putStrLn $ "Setting Layout Attributes " <> show debug layoutSetAttributes layout allAttrs -- putStrLn "Done Stting Layout Attributes" dw <- widgetGetDrawWindow drawArea gc <- gcNew dw oldText <- layoutGetText layout when (text /= oldText) $ layoutSetText layout text drawLayout dw gc 0 0 layout liftBase $ writeIORef shownTos tos -- paint the cursor (PangoRectangle curx cury curw curh, _) <- layoutGetCursorPos layout (rel point) PangoRectangle chx chy chw chh <- layoutIndexToPos layout (rel point) gcSetValues gc (newGCValues { Gtk.foreground = mkCol True . Yi.Style.foreground . baseAttributes . configStyle $ configUI config }) if inserting then drawLine dw gc (round curx, round cury) (round $ curx + curw, round $ cury + curh) else drawRectangle dw gc False (round chx) (round chy) (if chw > 0 then round chw else 8) (round chh) return True liftBase $ widgetGrabFocus drawArea tabsRef <- asks tabCache ts <- liftBase $ readIORef tabsRef -- TODO: the Tab idkey should be assigned using -- Yi.Editor.newRef. But we can't modify that here, since our -- access to 'Yi' is readonly. liftBase $ writeIORef tabsRef (TabInfo (makeTab1 0 newWindow):ts) viewsRef <- asks views vs <- liftBase $ readIORef viewsRef liftBase $ writeIORef viewsRef $ Map.insert windowRef view vs return view where clearHighlight fb = -- if there were updates, then hide the selection. let h = view highlightSelectionA fb us = view pendingUpdatesA fb in highlightSelectionA .~ (h && null us) $ fb {-# ANN setBufferMode ("HLint: ignore Redundant do" :: String) #-} setBufferMode :: FilePath -> Buffer -> ControlM () setBufferMode f buffer = do let bufRef = fBufRef buffer -- adjust the mode tbl <- liftYi $ asks (modeTable . yiConfig) contents <- liftYi $ withGivenBuffer bufRef elemsB let header = R.toString $ R.take 1024 contents hmode = case header =~ ("\\-\\*\\- *([^ ]*) *\\-\\*\\-" :: String) of AllTextSubmatches [_,m] -> T.pack m _ -> "" Just mode = find (\(AnyMode m)-> modeName m == hmode) tbl <|> find (\(AnyMode m)-> modeApplies m f contents) tbl <|> Just (AnyMode emptyMode) case mode of AnyMode newMode -> do -- liftBase $ putStrLn $ show (f, modeName newMode) liftYi $ withEditor $ do withGivenBuffer bufRef $ do setMode newMode modify clearSyntax switchToBufferE bufRef -- withEditor focusAllSyntax withBuffer :: Buffer -> BufferM a -> ControlM a withBuffer Buffer{fBufRef = b} f = liftYi $ withGivenBuffer b f getBuffer :: View -> Buffer getBuffer view = Buffer {fBufRef = viewFBufRef view} setText :: Buffer -> YiString -> ControlM () setText b text = withBuffer b $ do r <- regionOfB Document replaceRegionB r text getText :: Buffer -> Iter -> Iter -> ControlM Text getText b Iter{point = p1} Iter{point = p2} = fmap toText . withBuffer b . readRegionB $ mkRegion p1 p2 mkCol :: Bool -- ^ is foreground? -> Yi.Style.Color -> Gtk.Color mkCol True Default = Color 0 0 0 mkCol False Default = Color maxBound maxBound maxBound mkCol _ (RGB x y z) = Color (fromIntegral x * 256) (fromIntegral y * 256) (fromIntegral z * 256) handleClick :: View -> Gdk.Events.Event -> ControlM Bool handleClick view event = do control <- ask -- (_tabIdx,winIdx,w) <- getWinInfo ref <$> readIORef (tabCache ui) logPutStrLn $ "Click: " <> showT (Gdk.Events.eventX event, Gdk.Events.eventY event, Gdk.Events.eventClick event) -- retrieve the clicked offset. (_,layoutIndex,_) <- io $ layoutXYToIndex (layout view) (Gdk.Events.eventX event) (Gdk.Events.eventY event) tos <- liftBase $ readIORef (shownTos view) let p1 = tos + fromIntegral layoutIndex let winRef = windowRef view -- maybe focus the window -- logPutStrLn $ "Clicked inside window: " <> show view -- let focusWindow = do -- TODO: check that tabIdx is the focus? -- (%=) windowsA (fromJust . PL.move winIdx) liftBase $ case (Gdk.Events.eventClick event, Gdk.Events.eventButton event) of (Gdk.Events.SingleClick, Gdk.Events.LeftButton) -> do cid <- onMotionNotify (drawArea view) False $ \event -> runControl (handleMove view p1 event) control writeIORef (winMotionSignal view) $ Just cid _ -> do maybe (return ()) signalDisconnect =<< readIORef (winMotionSignal view) writeIORef (winMotionSignal view) Nothing case (Gdk.Events.eventClick event, Gdk.Events.eventButton event) of (Gdk.Events.SingleClick, Gdk.Events.LeftButton) -> runAction . EditorA $ do -- b <- gets $ (bkey . findBufferWith (viewFBufRef view)) -- focusWindow window <- findWindowWith winRef <$> get withGivenBufferAndWindow window (viewFBufRef view) $ do moveTo p1 setVisibleSelection False -- (Gdk.Events.SingleClick, _) -> runAction focusWindow (Gdk.Events.ReleaseClick, Gdk.Events.MiddleButton) -> do disp <- liftBase $ widgetGetDisplay (drawArea view) cb <- liftBase $ clipboardGetForDisplay disp selectionPrimary let cbHandler :: Maybe R.YiString -> IO () cbHandler Nothing = return () cbHandler (Just txt) = runControl (runAction . EditorA $ do window <- findWindowWith winRef <$> get withGivenBufferAndWindow window (viewFBufRef view) $ do pointB >>= setSelectionMarkPointB moveTo p1 insertN txt) control liftBase $ clipboardRequestText cb (cbHandler . fmap R.fromText) _ -> return () liftBase $ widgetQueueDraw (drawArea view) return True handleScroll :: View -> Gdk.Events.Event -> ControlM Bool handleScroll view event = do let editorAction = withCurrentBuffer $ vimScrollB $ case Gdk.Events.eventDirection event of Gdk.Events.ScrollUp -> -1 Gdk.Events.ScrollDown -> 1 _ -> 0 -- Left/right scrolling not supported runAction $ EditorA editorAction liftBase $ widgetQueueDraw (drawArea view) return True handleMove :: View -> Point -> Gdk.Events.Event -> ControlM Bool handleMove view p0 event = do logPutStrLn $ "Motion: " <> showT (Gdk.Events.eventX event, Gdk.Events.eventY event) -- retrieve the clicked offset. (_,layoutIndex,_) <- liftBase $ layoutXYToIndex (layout view) (Gdk.Events.eventX event) (Gdk.Events.eventY event) tos <- liftBase $ readIORef (shownTos view) let p1 = tos + fromIntegral layoutIndex let editorAction = do txt <- withCurrentBuffer $ if p0 /= p1 then Just <$> do m <- selMark <$> askMarks markPointA m .= p0 moveTo p1 setVisibleSelection True readRegionB =<< getSelectRegionB else return Nothing maybe (return ()) setRegE txt runAction $ makeAction editorAction -- drawWindowGetPointer (textview w) -- be ready for next message. -- Relies on uiActionCh being synchronous selection <- liftBase $ newIORef "" let yiAction = do txt <- withCurrentBuffer (readRegionB =<< getSelectRegionB) :: YiM R.YiString liftBase $ writeIORef selection txt runAction $ makeAction yiAction txt <- liftBase $ readIORef selection disp <- liftBase $ widgetGetDisplay (drawArea view) cb <- liftBase $ clipboardGetForDisplay disp selectionPrimary liftBase $ clipboardSetWithData cb [(targetString,0)] (\0 -> void (selectionDataSetText $ R.toText txt)) (return ()) liftBase $ widgetQueueDraw (drawArea view) return True processEvent :: ([Event] -> IO ()) -> Gdk.Events.Event -> IO Bool processEvent ch ev = do -- logPutStrLn $ "Gtk.Event: " <> show ev -- logPutStrLn $ "Event: " <> show (gtkToYiEvent ev) case gtkToYiEvent ev of Nothing -> logPutStrLn $ "Event not translatable: " <> showT ev Just e -> ch [e] return True gtkToYiEvent :: Gdk.Events.Event -> Maybe Event gtkToYiEvent (Gdk.Events.Key {Gdk.Events.eventKeyName = key , Gdk.Events.eventModifier = evModifier , Gdk.Events.eventKeyChar = char}) = (\k -> Event k $ nub $ notMShift $ concatMap modif evModifier) <$> key' where (key',isShift) = case char of Just c -> (Just $ KASCII c, True) Nothing -> (Map.lookup key keyTable, False) modif Gdk.Events.Control = [MCtrl] modif Gdk.Events.Alt = [MMeta] modif Gdk.Events.Shift = [MShift] modif _ = [] notMShift | isShift = filter (/= MShift) | otherwise = id gtkToYiEvent _ = Nothing -- | Map GTK long names to Keys keyTable :: Map.Map Text Key keyTable = Map.fromList [("Down", KDown) ,("Up", KUp) ,("Left", KLeft) ,("Right", KRight) ,("Home", KHome) ,("End", KEnd) ,("BackSpace", KBS) ,("Delete", KDel) ,("Page_Up", KPageUp) ,("Page_Down", KPageDown) ,("Insert", KIns) ,("Escape", KEsc) ,("Return", KEnter) ,("Tab", KTab) ,("ISO_Left_Tab", KTab) ]
noughtmare/yi
yi-frontend-pango/src/Yi/Frontend/Pango/Control.hs
gpl-2.0
32,220
195
22
9,711
8,243
4,333
3,910
601
5
----------------------------------------------------------------------------- {- | Module : Data.Packed Copyright : (c) Alberto Ruiz 2006-2010 License : GPL-style Maintainer : Alberto Ruiz (aruiz at um dot es) Stability : provisional Portability : uses ffi Types for dense 'Vector' and 'Matrix' of 'Storable' elements. -} ----------------------------------------------------------------------------- module Data.Packed ( module Data.Packed.Vector, module Data.Packed.Matrix, -- module Numeric.Conversion, -- module Data.Packed.Random, -- module Data.Complex ) where import Data.Packed.Vector import Data.Packed.Matrix --import Data.Packed.Random --import Data.Complex --import Numeric.Conversion
abakst/liquidhaskell
benchmarks/hmatrix-0.15.0.1/lib/Data/Packed.hs
bsd-3-clause
737
0
5
111
44
33
11
5
0
-- !! TEST OF DEFACTORISATION FOR FUNCTIONS THAT DROP -- !! POLYMORPHIC VARIABLES module Test where data Boolean = FF | TT data Pair a b = MkPair a b data LList alpha = Nill | Conss alpha (LList alpha) data Nat = Zero | Succ Nat data Tree x = Leaf x | Node (Tree x) (Tree x) data A a = MkA a (A a) append :: LList a -> LList a -> LList a append xs ys = case xs of Nill -> ys Conss z zs -> Conss z (append zs ys) -- The following function drops @b@. flat :: Tree (Pair a b) -> LList a flat t = case t of Leaf (MkPair a b) -> Conss a Nill Node l r -> append (flat l) (flat r) fl :: Boolean -> LList Boolean fl x = flat (Leaf (MkPair TT Zero))
urbanslug/ghc
testsuite/tests/stranal/should_compile/ins.hs
bsd-3-clause
736
0
10
243
298
154
144
17
2
module Main where -- See Trac #5549 -- The issue here is allocating integer constants inside a loop lcs3 :: Eq a => [a] -> [a] -> [a] lcs3 a b = fst $ aux (a, length a) (b, length b) where aux (_,0) _ = ([],0) aux _ (_,0) = ([],0) aux (a@(ha:as),la) (b@(hb:bs), lb) | ha == hb = let (s,n) = aux (as,la-1) (bs,lb-1) in (ha : s, n+1) | otherwise = let (sa,na) = aux (as,la-1) (b,lb) (sb,nb) = aux (a,la) (bs,lb-1) in if na > nb then (sa,na) else (sb,nb) f :: Integer -> Integer -> Integer f acc 0 = acc f acc n = g (acc + 1) (n-1) g :: Integer -> Integer -> Integer g acc 0 = acc g acc n = f (acc -1) (n-1) main = do putStrLn . show $ f 0 100000000 putStrLn . show $ lcs3 [1..20] [10..20]
urbanslug/ghc
testsuite/tests/perf/should_run/T5549.hs
bsd-3-clause
757
0
14
223
487
265
222
19
4
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, UndecidableInstances, GADTs, FunctionalDependencies, RankNTypes #-} data Empty data New e t class Env e where instance Env Empty where instance Env e => Env (New e t) where data X0 t = V0 data Succ v t = VS v t class Env e => Var e v t where instance Env e => Var (New e t) (X0 t) t where instance (Env e, Var e v t_) => Var (New e t) (Succ v t) t where data VT v data Sum a b data Lfp a data Prod a b data Gfp a -- | Unit type data U = U class Env e => Type e t instance (Env e, Var e v U) => Type e (VT v) instance (Env e, Type e a, Type e b) => Type e (Sum a b) instance (Env e, Type (New e U) a) => Type e (Lfp a) instance (Env e, Type e a, Type e b) => Type e (Prod a b) instance (Env e, Type (New e U) a) => Type e (Gfp a) data Triv data CSubst s x t class (Env e, Env f) => CtxMor e f s instance Env e => CtxMor e Empty Triv instance (Env e, Env f, CtxMor e f s, Var (New f U) x U, Type e t) => CtxMor e (New f U) (CSubst s x t) class (Env e, class (Env e, Env f, CtxMor e f s, Type f a, Type e b) => Subst e f s a b | a s -> b instance (Env e, Type Empty a, Weaken e a') => Subst e Empty Triv a a' instance (Env e, Env f, Var (New f U) x U, Type e t, CtxMor e f s) => Subst e (New f U) (CSubst s x t) (VT x) t {-instance (Env e, Env f, CtxMor e f s, Var (New f U) x U, Var f y U, Type e t, Subst e f s (VT y) t) => Subst e (New f U) (CSubst s x t) (VT y) t -} {- instance (Env e, Type (New e U) a1, Type (New e U) a2, Type e b, Var (New e U) x U, Type e c1, Type e c2, Subst e a1 b x c1, Subst e a2 b x c2) => Subst e (Sum a1 a2) b x (Sum c1 c2) instance (Env e, Type (New e U) a1, Type (New e U) a2, Type e b, Var (New e U) x U, Type e c1, Type e c2, Subst e a1 b x c1, Subst e a2 b x c2) => Subst e (Prod a1 a2) b x (Prod c1 c2) instance (Env e, Type (New (New e U) U) a, Type e b, Var (New e U) x U, Type (New e U) c, Subst e a b x c) => Subst e (Lfp a) b x (Lfp c) instance (Env e, Type (New (New e U) U) a, Type e b, Var (New e U) x U, Type (New e U) c, Subst e a b x c) => Subst e (Gfp a) b x (Gfp c) -} -- | Used environments: e for term variables, s for signature variables data Term s e t where V :: (Env e, Type Empty t, Var e v t) => v -> Term s e t Sym :: (Env s, Type Empty t, Var s v t) => v -> Term s e t Inj1 :: (Env e, Type Empty a, Type Empty b) => Term s e a -> Term s e (Sum a b) Inj2 :: (Env e, Type Empty a, Type Empty b) => Term s e b -> Term s e (Sum a b) In :: (Env e, Type (New Empty U) a, Subst (New Empty U) a (Lfp a) (X0 U) c) => Term s e c -> Term s e (Lfp a) Prj1 :: (Env e, Type Empty a, Type Empty b) => Term s e (Prod a b) -> Term s e a Prj2 :: (Env e, Type Empty a, Type Empty b) => Term s e (Prod a b) -> Term s e b Out :: (Env e, Type (New Empty U) a, Subst Empty a (Gfp a) (X0 U) c) => Term s e (Gfp a) -> Term s e c data Body s t where Hole :: (Env s, Type Empty a) => Term s Empty a -> Body s a Prod :: (Env s, Type Empty a, Type Empty b) => Term s Empty a -> Term s Empty b -> Body s (Prod a b) Tr :: (Env s, Type (New Empty U) a, Subst Empty a (Gfp a) (X0 U) c) => Term s Empty c -> Body s (Gfp a) data Defs s where Empty :: Defs Empty Cons :: (Env s, Type Empty a, Var (New s a) v a) => Defs s -> v -> Body (New s a) a -> Defs (New s a) data Prog where Prog :: (Env s, Type Empty a) => Defs s -> Term s Empty a -> Prog -- Examples -- -- Types type OneTVar = New Empty U type TX0 = X0 U type TX1 = Succ TX0 U type TX2 = Succ TX1 U type One = Gfp (VT TX0) type Nat = Lfp (Sum One TX0) type List a = Lfp (Sum One (Prod a TX0)) type OneVar a = New Empty a -- Programs type UnitSig = OneVar One unitDefs :: Defs UnitSig unitDefs = Cons Empty f unitBody where f = V0 :: X0 One unitBody :: Body UnitSig One unitBody = Tr (Sym f) unit :: Term UnitSig Empty One unit = Sym f where f = V0 :: X0 One unitP :: Prog unitP = Prog unitDefs unit z :: Term UnitSig Empty Nat z = In t -- (Inj1 unit :: Term UnitSig Empty (Sum One Nat)) where t :: Term UnitSig Empty (Sum One Nat) t = undefined
hbasold/Sandbox
OTTTests/DecideEquiv_.hs
mit
4,599
61
10
1,618
1,869
949
920
-1
-1
module Log where type Rep = Integer type Weight = Double type Name = String data LogEntry = Exercise Name [(Weight, Rep)] | RepExercise Name [Rep] deriving (Show) type ExerciseLog = [LogEntry] data Workout = MondayWorkout Name ExerciseLog | TuesdayWorkout Name ExerciseLog | WednesdayWorkout Name ExerciseLog | ThursdayWorkout Name ExerciseLog | FridayWorkout Name ExerciseLog | SaturdayWorkout Name ExerciseLog | SundayWorkout Name ExerciseLog deriving (Show)
ladinu/cs457
src/Log.hs
mit
615
0
8
218
128
77
51
16
0
module MacroExpander(expand) where import System.IO import Data.String.Utils import Control.Monad import Text.Regex.Posix expand :: String -> IO String expand program = do let capturedMacros = program =~ "(.*) = @(.*)\\((.*)\\)" :: [[String]] fst $ foldl (\(acc, id:ids) (pattern:macroReturn:macroFile:macroParameters:_) -> ((liftM3 replace (return pattern) (buildMacro macroFile macroReturn (split ", " macroParameters) id) acc), ids)) (return program, [0..]) (capturedMacros) buildMacro :: String -> String -> [String] -> Int -> IO String buildMacro macroFile macroReturn macroParameters macroID = do sourceMacro <- readFile $ macroFile ++ ".d" let prefix = "_" ++ macroFile ++ "_" ++ show macroID ++ "_" bindings = ("__return", macroReturn) : zip (map (("__param" ++) . show) [0..]) macroParameters withBoundParameters = foldl (\acc binding -> uncurry replace binding acc) sourceMacro bindings withUniquePrefixes = replace "__" prefix withBoundParameters return withUniquePrefixes
aleksanb/hdc
src/MacroExpander.hs
mit
1,140
0
17
284
358
190
168
33
1
{-| Module : Graphics.Shine.Input Description : Short description Copyright : (c) Francesco Gazzetta, 2016 License : MIT Maintainer : francygazz@gmail.com Stability : experimental Datatypes representing inputs. -} module Graphics.Shine.Input where import Web.KeyCode -- | The state of a button on the keyboard data KeyState = Down | Up deriving (Show, Eq) -- | The four key modifiers data Modifiers = Modifiers { ctrl :: KeyState , alt :: KeyState , shift :: KeyState , meta :: KeyState } deriving (Show, Eq) -- | The three mouse buttons data MouseBtn = BtnLeft | BtnRight | BtnMiddle deriving (Show, Eq) -- | Datatype representing all possible inputs data Input = Keyboard Key KeyState Modifiers | MouseBtn MouseBtn KeyState Modifiers | MouseWheel (Double, Double) | MouseMove (Int, Int) deriving (Show, Eq) -- | Convert a js mouse button identifier to the corresponding datatype toMouseBtn :: Word -> Maybe MouseBtn toMouseBtn 0 = Just BtnLeft toMouseBtn 1 = Just BtnMiddle toMouseBtn 2 = Just BtnRight toMouseBtn _ = Nothing -- | Convert a bool (from js) to a keystate toKeyState :: Bool -> KeyState toKeyState True = Down toKeyState False = Up
fgaz/shine
src/Graphics/Shine/Input.hs
mit
1,312
0
8
352
241
138
103
22
1
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveGeneric #-} module RWPAS.Control.Types ( SentinelAI() , sentinelAI , AI(..) , AITransition , IsAI(..) -- * Stepping AI , stepAI , stepDeadAI ) where import Control.Lens import Control.Monad.Primitive import qualified Data.ByteString as B import Data.Data import Data.SafeCopy import GHC.Generics import RWPAS.Level.Type import RWPAS.World.Type import RWPAS.Actor import System.Random.MWC import Unsafe.Coerce class (SafeCopy a, Eq a, Ord a, Show a, Read a, Typeable a) => IsAI a where {-# MINIMAL initialState, transitionFunction, aiName #-} initialState :: PrimMonad m => Gen (PrimState m) -> m a transitionFunction :: PrimMonad m => AITransition m a deadTransition :: PrimMonad m => AITransition m a deadTransition _ _ world actor_id level_id = return $ world & levelById level_id %~ fmap (removeActor actor_id) aiName :: Proxy a -> B.ByteString -- | Function that decides the next action of an AI. type AITransition m a = a -- state of the AI (parametric) -> Gen (PrimState m) -- random number generator -> World -- world state -> ActorID -- actor ID of the actor controlled by this AI -> LevelID -- level ID of the level the actor is in -> m World data AI = forall a. (IsAI a) => AI a deriving ( Typeable ) instance Eq AI where AI a1 == AI a2 = let r = typeOf a1 == typeOf a2 in r `seq` (r && unsafeCoerce a1 == a2) instance Ord AI where AI a1 `compare` AI a2 = let tc = typeOf a1 `compare` typeOf a2 in if tc == EQ then unsafeCoerce a1 `compare` a2 else tc instance Show AI where show (AI a) = "AI<" ++ show a ++ ">" -- | Sessile AI, used as a placeholder. data SentinelAI = SentinelAI deriving ( Eq, Ord, Show, Read, Typeable, Data, Generic, Enum ) deriveSafeCopy 0 'base ''SentinelAI instance IsAI SentinelAI where initialState _ = return SentinelAI transitionFunction _ _ w _ _ = return w aiName _ = "sessile AI" stepAI :: PrimMonad m => AI -> Gen (PrimState m) -> World -> ActorID -> LevelID -> m World stepAI (AI state) = transitionFunction state {-# INLINE stepAI #-} stepDeadAI :: PrimMonad m => AI -> Gen (PrimState m) -> World -> ActorID -> LevelID -> m World stepDeadAI (AI state) = deadTransition state {-# INLINE stepDeadAI #-} sentinelAI :: AI sentinelAI = AI SentinelAI
Noeda/rwpas
src/RWPAS/Control/Types.hs
mit
2,489
3
13
537
729
388
341
71
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE LambdaCase #-} module Main where import Prelude hiding (FilePath) import Control.Concurrent import Control.Concurrent.MVar import Control.Concurrent.Async import Control.Monad import Data.Graph.Inductive.Graph import Data.Graph.Inductive.PatriciaTree import Data.Graph.Inductive.NodeMap hiding (run, run_) import Data.List import Data.Maybe import Data.Tree import qualified Data.Map as M import qualified Data.Text as T import Shelly default (T.Text) -- Definitions for parallel job execution: type Job = MVar (Either (Sh (Async ())) (Async ())) type JobTag = String type JobMap = M.Map String (Sh ()) type JobDepends = (JobTag, JobTag, ()) type JobTagGraph = Gr String () type JobGraph = Gr Job () getNumCapabilitiesSh :: Sh T.Text getNumCapabilitiesSh = liftIO getNumCapabilities >>= (\n -> return $ T.pack $ show n) newMVarSh :: a -> Sh (MVar a) newMVarSh = liftIO . newMVar takeMVarSh :: MVar a -> Sh a takeMVarSh = liftIO . takeMVar putMVarSh :: MVar a -> a -> Sh () putMVarSh = (liftIO . ) . putMVar readMVarSh :: MVar a -> Sh a readMVarSh = liftIO . readMVar waitSh :: Async a -> Sh a waitSh = liftIO . wait mkJob :: Sh () -> Sh Job mkJob = newMVarSh . Left . asyncSh require :: a -> b -> (a, b, ()) require = flip flip () . (,,) sequenceNodes :: (DynGraph gr, Monad m) => gr (m a) b -> m (gr a b) sequenceNodes = ufold sequenceContext (return empty) where sequenceContext (ine, n, nl, oute) g = do nl' <- nl g' <- g return $ (ine, n, nl', oute) & g' mkJobTagGraph :: [JobDepends] -> JobTagGraph mkJobTagGraph js = fst $ mkMapGraph ujs js where ujs = nub $ foldr (\(a,b,()) ls -> a:b:ls) [] js mkJobGraph :: JobMap -> JobTagGraph -> Sh JobGraph mkJobGraph m = sequenceNodes . nmap (mkJob . (m M.!)) blockOn :: Job -> Sh () blockOn j = readMVarSh j >>= \case Left _ -> error "Cannot block on job that has not started." Right a -> waitSh a runJob :: JobGraph -> Node -> Sh () runJob g n = do let j = fromJust $ lab g n readMVarSh j >>= \case Right _ -> return () Left _ -> do let deps = suc g n mapM_ (runJob g) deps mapM_ blockOn $ map (fromJust . lab g) deps s <- takeMVarSh j case s of Right _ -> putMVarSh j s Left sh -> sh >>= putMVarSh j . Right runJobGraph :: JobMap -> JobTagGraph -> Sh () runJobGraph m g = do g' <- mkJobGraph m g let js = nodes g' mapM_ (runJob g') js mapM_ blockOn $ map (fromJust . lab g') js runlocal_ :: FilePath -> [T.Text] -> Sh () runlocal_ c as = pwd >>= (\cp -> run_ (cp </> c) as) -- Static relative paths to executables: whoami_path :: FilePath whoami_path = "whoami" wget_path :: FilePath wget_path = "wget" wget :: T.Text -> Sh () wget = run_ wget_path . ("-t" :) . ("0" :) . (:[]) rpm_path :: FilePath rpm_path = "rpm" yum_path :: FilePath yum_path = "yum" yum_update :: Sh () yum_update = run_ yum_path ["-y", "update"] yum_upgrade :: Sh () yum_upgrade = run_ yum_path ["-y", "upgrade"] yum_install :: [T.Text] -> Sh () yum_install = run_ yum_path . ("-y" :) . ("install" :) ldconfig_path :: FilePath ldconfig_path = "/sbin/ldconfig" tar_path :: FilePath tar_path = "tar" make_path :: FilePath make_path = "make" perl_path :: FilePath perl_path = "perl" -- Static config paths ld_local_path :: FilePath ld_local_path = "/etc/ld.so.conf.d/local.conf" pkg_config_var :: T.Text pkg_config_var = "PKG_CONFIG_PATH" pkg_config_val :: T.Text pkg_config_val = "/usr/lib64/pkgconfig:/usr/share/pkgconfig:/usr/local/lib/pkgconfig:/usr/local/share/pkgconfig" -- Static external paths: epel_name = "epel-release-6-8.noarch.rpm" epel_path = "http://download.fedoraproject.org/pub/epel/6/x86_64/" `T.append` epel_name raptor_dir = "raptor2-2.0.14" raptor_tar = raptor_dir `T.append` ".tar.gz" raptor_path = "http://download.librdf.org/source/" `T.append` raptor_tar rasqal_dir = "rasqal-0.9.32" rasqal_tar = rasqal_dir `T.append` ".tar.gz" rasqal_path = "http://download.librdf.org/source/" `T.append` rasqal_tar fstore_dir = "4store-v1.1.5" fstore_tar = fstore_dir `T.append` ".tar.gz" fstore_path = "http://4store.org/download/" `T.append` fstore_tar hdf5_dir = "hdf5-1.8.14" hdf5_tar = hdf5_dir `T.append` ".tar.gz" hdf5_path = "http://www.hdfgroup.org/ftp/HDF5/current/src/" `T.append` hdf5_tar zmq_dir = "zeromq-4.0.5" zmq_tar = zmq_dir `T.append` ".tar.gz" zmq_path = "http://download.zeromq.org/" `T.append` zmq_tar ghc_link1_dir = "ghc-7.4.1" ghc_link1_tar = ghc_link1_dir `T.append` "-src.tar.bz2" ghc_link1_path = "http://www.haskell.org/ghc/dist/7.4.1/" `T.append` ghc_link1_tar ghc_link2_dir = "ghc-7.8.4" ghc_link2_tar = ghc_link2_dir `T.append` "-src.tar.bz2" ghc_link2_path = "http://www.haskell.org/ghc/dist/7.8.4/" `T.append` ghc_link2_tar -- List of all RPMs we're going to need: allRPMs :: [T.Text] allRPMs = [ "tmux" ,"htop" ,"clang" ,"gcc" ,"autoconf" ,"libtool" ,"make" ,"valgrind" ,"gmp" ,"gmp-devel" ,"gmp-static" ,"mpfr" ,"mpfr-devel" ,"git" ,"nasm" ,"python33" ,"texlive-latex" ,"gnuplot" ,"R" ,"nodejs" ,"npm" ,"php" ,"nmap" ,"ocaml" ,"glib2" ,"glib2-devel" ,"libxml2" ,"libxml2-devel" ,"pcre" ,"pcre-devel" ,"avahi" ,"avahi-glib-devel" ,"avahi-libs" ,"avahi-devel" ,"avahi-tools" ,"readline" ,"readline-devel" ,"ncurses" ,"ncurses-libs" ,"ncurses-devel" ,"expat" ,"expat-devel" ,"zlib" ,"zlib-devel" ,"libcurl" ,"libcurl-devel" ,"libxslt" ,"libxslt-devel" ,"uuid" ,"libuuid" ,"libuuid-devel" ,"happy" ,"alex" ,"ghc" ] -- Job definition: initPKUtree :: Sh () initPKUtree = mkdirTree tree where (#) = Node tree = "/app" # [ "Analytics" # [] ,"Datablocks" # [] ,"sandboxes" # [] ,"schema_files" # [] ,"source_systems" # [ "edw" # [] ,"ODS" # [] ,"OLTP" # [] ,"Symyx_dev" # [] ,"Symyx_prod" # [] ] ,"src" # [ "lang" # [ "C" # [] ,"Haskell" # [] ] ,"pkg" # [ "4store" # [] ,"czmq" # [] ,"zmq" # [] ,"ghc_bootstrap" # [] ,"hdf5" # [] ,"libsodium" # [] ,"php-zmq" # [] ,"R" # [] ,"raptor" # [] ,"rasqal" # [] ] ] ,"sync_scripts" # [] ] pullEpel :: Sh () pullEpel = do cd "/app" rm_rf $ fromText epel_name wget epel_path pullRaptor :: Sh () pullRaptor = do cd "/app/src/pkg/raptor" rm_rf $ fromText raptor_dir rm_rf $ fromText raptor_tar wget raptor_path pullRasqal :: Sh () pullRasqal = do cd "/app/src/pkg/rasqal" rm_rf $ fromText rasqal_dir rm_rf $ fromText rasqal_tar wget rasqal_path pullFstore :: Sh () pullFstore = do cd "/app/src/pkg/4store" rm_rf $ fromText fstore_dir rm_rf $ fromText fstore_tar wget fstore_path pullHDF5 :: Sh () pullHDF5 = do cd "/app/src/pkg/hdf5" rm_rf $ fromText hdf5_dir rm_rf $ fromText hdf5_tar wget hdf5_path pullZmq :: Sh () pullZmq = do cd "/app/src/pkg/zmq" rm_rf $ fromText zmq_dir rm_rf $ fromText zmq_tar wget zmq_path pullGHC1 :: Sh () pullGHC1 = do cd "/app/src/pkg/ghc_bootstrap" rm_rf $ fromText ghc_link1_dir rm_rf $ fromText ghc_link1_tar wget ghc_link1_path pullGHC2 :: Sh () pullGHC2 = do cd "/app/src/pkg/ghc_bootstrap" rm_rf $ fromText ghc_link2_dir rm_rf $ fromText ghc_link2_tar wget ghc_link2_path initYum :: Sh () initYum = do cd "/app" yum_update yum_upgrade yum_install ["curl", "nss"] run_ rpm_path ["--force", "-ivh", epel_name] yum_update yum_upgrade yum_install allRPMs -- These installations must share an Sh environment raptorRasqalFstoreInstall :: Sh () raptorRasqalFstoreInstall = do cores <- getNumCapabilitiesSh let mj = "-j" `T.append` cores appendfile ld_local_path "/usr/local/lib\n/usr/local/lib64\n" run_ ldconfig_path [] setenv pkg_config_var pkg_config_val cd "/app/src/pkg/raptor" run_ tar_path ["xvzf", raptor_tar] cd $ fromText raptor_dir runlocal_ "configure" [] run_ make_path [mj] run_ make_path ["install"] run_ ldconfig_path [] cd "/app/src/pkg/rasqal" run_ tar_path ["xvzf", rasqal_tar] cd $ fromText rasqal_dir runlocal_ "configure" [] run_ make_path [mj] run_ make_path ["install"] run_ ldconfig_path [] cd "/app/src/pkg/4store" run_ tar_path ["xvzf", fstore_tar] cd $ fromText fstore_dir runlocal_ "configure" ["--with-storage-path=/app/4s-data"] run_ make_path [mj] run_ make_path ["install"] run_ ldconfig_path [] hdf5Install :: Sh () hdf5Install = do cores <- getNumCapabilitiesSh let mj = "-j" `T.append` cores cd "/app/src/pkg/hdf5" run_ tar_path ["xvzf", hdf5_tar] cd $ fromText hdf5_dir runlocal_ "configure" ["--prefix=/usr/local"] run_ make_path [mj] run_ make_path ["install"] run_ ldconfig_path [] zmqInstall :: Sh () zmqInstall = do cores <- getNumCapabilitiesSh let mj = "-j" `T.append` cores cd "/app/src/pkg/zmq" run_ tar_path ["xvzf", zmq_tar] cd $ fromText zmq_dir runlocal_ "configure" [] run_ make_path [mj] run_ make_path ["install"] run_ ldconfig_path [] ghcLink1 :: Sh () ghcLink1 = do cores <- getNumCapabilitiesSh let mj = "-j" `T.append` cores cd "/app/src/pkg/ghc_bootstrap" run_ tar_path ["xvjf", ghc_link1_tar] cd $ fromText ghc_link1_dir run_ perl_path ["boot"] runlocal_ "configure" [] run_ make_path [mj] run_ make_path ["install"] ghcLink2 :: Sh () ghcLink2 = do cores <- getNumCapabilitiesSh let mj = "-j" `T.append` cores cd "/app/src/pkg/ghc_bootstrap" run_ tar_path ["xvjf", ghc_link2_tar] cd $ fromText ghc_link2_dir run_ perl_path ["boot"] runlocal_ "configure" [] run_ make_path [mj] run_ make_path ["install"] depmap = M.fromList [ ("initPKUtree", initPKUtree) ,("pullEpel", pullEpel) ,("pullRaptor", pullRaptor) ,("pullRasqal", pullRasqal) ,("pullFstore", pullFstore) ,("pullHDF5", pullHDF5) ,("pullZmq", pullZmq) ,("pullGHC1", pullGHC1) ,("pullGHC2", pullGHC2) ,("initYum", initYum) ,("raptorRasqalFstoreInstall", raptorRasqalFstoreInstall) ,("hdf5Install", hdf5Install) ,("zmqInstall", zmqInstall) ,("ghcLink1", ghcLink1) ,("ghcLink2", ghcLink2) ] depgraph= mkJobTagGraph [ ("pullEpel" `require` "initPKUtree") ,("pullRaptor" `require` "initPKUtree") ,("pullRasqal" `require` "initPKUtree") ,("pullFstore" `require` "initPKUtree") ,("pullHDF5" `require` "initPKUtree") ,("pullZmq" `require` "initPKUtree") ,("pullGHC1" `require` "initPKUtree") ,("pullGHC2" `require` "initPKUtree") ,("initYum" `require` "pullEpel") ,("raptorRasqalFstoreInstall" `require` "initYum") ,("raptorRasqalFstoreInstall" `require` "pullRaptor") ,("raptorRasqalFstoreInstall" `require` "pullRasqal") ,("raptorRasqalFstoreInstall" `require` "pullFstore") ,("hdf5Install" `require` "pullHDF5") ,("zmqInstall" `require` "pullZmq") ,("ghcLink1" `require` "pullGHC1") ,("ghcLink2" `require` "pullGHC2") ,("ghcLink2" `require` "ghcLink1") ] preflight :: Sh [T.Text] preflight = liftM catMaybes checks where checks = sequence [ test_px whoami_path >>= (\e -> return $ if e then Nothing else Just $ "whoami program not found in $PATH.") ,run whoami_path [] >>= (\u -> return $ if (u == "root\n") then Nothing else Just $ "This program must be executed as root.") ,test_px wget_path >>= (\e -> return $ if e then Nothing else Just $ "wget program not found in $PATH.") ,test_px rpm_path >>= (\e -> return $ if e then Nothing else Just $ "rpm program not found in $PATH.") ,test_px yum_path >>= (\e -> return $ if e then Nothing else Just $ "yum program not found in $PATH.") ,test_px ldconfig_path >>= (\e -> return $ if e then Nothing else Just $ "/sbin/ldconfig program not found.") ,test_px tar_path >>= (\e -> return $ if e then Nothing else Just $ "tar program not found in $PATH.") ,test_px make_path >>= (\e -> return $ if e then Nothing else Just $ "make program not found in $PATH.") ,test_px perl_path >>= (\e -> return $ if e then Nothing else Just $ "perl program not found in $PATH.") -- ,test_f ld_local_path >>= (\e -> return $ if e then Nothing else Just $ "/etc/ld.so.conf.d/local.conf not found.") ] main = (shelly . silently) $ do echo_n "Performing pre-flight check... " preflight >>= \case [] -> echo "Success." es -> echo "Failure." >> echo (T.intercalate "\n" es) >> quietExit 1 runJobGraph depmap depgraph
MadSciGuys/NodeInit
Main.hs
mit
13,422
0
18
3,388
4,008
2,128
1,880
394
10
{-# LANGUAGE BangPatterns, FlexibleContexts #-} module Cmm.Register.Allocation( allocateRegisters , generateAllocatedx86 ) where import Data.Set (Set) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map.Strict as Map import Control.Monad.IO.Class import Control.Monad.Loops (maximumOnM) import Control.Lens hiding ((#), none) import Control.Monad.Trans.State hiding (State) import Control.Monad.Trans (lift) import Control.Concurrent.ParallelIO.Global (parallel) import Data.IORef import Text.Printf (printf) import Data.List (foldl', find, maximumBy) import Data.Maybe (fromJust) import Data.Ord (comparing) import Data.Char (isAlphaNum) import AST (MiniJava()) import Cmm.X86.Backend (generatex86Gen) import Cmm.X86.InstrCore import Cmm.DirectedGraph import Cmm.Backend (MachineInstr(..) , MachineFunction(..) , MachinePrg(..) , CodeGen(..)) import Cmm.LabelGenerator import Cmm.ControlFlowGraph (createControlFlowGraph) import Cmm.ActivityAnalysis (activityAnalysis, ActivityStorage(..)) import Cmm.InterferenceGraph (createInterferenceGraph) import Cmm.Register.Core -- | parallel register allocation -- generateAllocatedx86 :: MiniJava -> Bool -> IO X86Prog generateAllocatedx86 ast inParallel = do (x86prog, iorefstate) <- evalNameGenT (generatex86Gen ast) -- yes, it's that easy let runComputation | inParallel = parallel | otherwise = sequence functions <- runComputation $ map (go c iorefstate) (machinePrgFunctions x86prog) return $ replaceFunctions x86prog functions where c = X86CodeGen go :: X86CodeGen -> IORef ([Temp], [Label]) -> X86Func -> IO X86Func go c state f = runWithNameStateT state (allocateRegisters c f) -- | approximates the graph coloring problem, spills the temps and returns a colored function function -- allocateRegisters :: (CodeGen c p f i, Ord i, Show i, MonadIO m, Show f) => c -> f -> NameGenT m f allocateRegisters c function = evalStateT (modifyFunction function) regState where ig :: DirectedGraph Temp ig = createInterferenceGraph function regState = RegisterState { _interferenceGraph = ig , _tempStates = createDefaultTempStates ig , _colors = generalPurposeRegisters c , _tempStack = [] } modifyFunction :: (MonadNameGen m, MonadIO m, MachineFunction f i, Ord i, Show i, Show f) => f -> Reg m f modifyFunction f = do usefulFunction <- deleteUnusedTemps f coloringPass spilled <- getAllSpilled case (not . none $ spilled) of True -> do newFunction <- lift $ machineFunctionSpill usefulFunction spilled -- modifying the function with asm updateInterferenceGraph newFunction -- create new interferencegraph deleteSpilledTemps spilled -- delete spilled from our local (temp -> state mapping) resetAllSpilledTemps -- if you didn't spill every possible temp, this would reset them accordignly addNewTempStates -- new temps are generated by spilling, we need to add them modifyFunction newFunction False -> insertRegisterColors f -- | last step to inserting the new registers, we rename every instruction, -- filter unused instructions, and allocate enough space for the frame insertRegisterColors :: (MonadNameGen m, MonadIO m, MachineFunction f i, Ord i, Show i) => f -> Reg m f insertRegisterColors f = do (machineFunctionStackAlloc . machineFunctionFilterInstructions . machineFunctionRenameByMap f) <$> createTempMapping deleteUnusedTemps :: (MonadNameGen m, MonadIO m, MachineFunction f i, Ord i, Show i) => f -> Reg m f deleteUnusedTemps f = do usedNodes <- nodes <$> (view interferenceGraph <$> get) return $ machineFunctionFilterUnusedMoves f usedNodes coloringPass :: (MonadNameGen m, MonadIO m) => Reg m () coloringPass = do simplify mt <- findCurrentMaxChildrenNode case mt of Nothing -> reverseStack >> select (Just t) -> moveToStack t >> coloringPass simplify :: (MonadNameGen m, MonadIO m) => Reg m () simplify = do ns <- allNodes k <- Set.size <$> (view colors <$> get) lessThanKNodes <- filterSM (((< k) <$>) . getOutDegree) ns mapSM_ moveToStack lessThanKNodes -- | pick temps from the stack and give them a possible color, -- if none are possible, mark as spilled -- terminate when the stack is empty select :: (MonadNameGen m, MonadIO m) => Reg m () select = do mtemp <- getFromStack case mtemp of Nothing -> do return () (Just t@(NamedTemp color)) -> do tempStates %= Map.insert t (Colored t) -- named temps are already colored (this happens because 'ret' uses '%eax' and not a temp) select (Just temp) -> do children <- getColoredChildren temp mColor <- getFreeColor children case mColor of Nothing -> setSpilled temp >> select (Just color) -> do tempStates %= Map.insert temp color select -- | get node which is not on the stack, pick the one with the maximum children, otherwise there are not 'Clear' nodes findCurrentMaxChildrenNode :: (MonadNameGen m, MonadIO m) => Reg m (Maybe Temp) findCurrentMaxChildrenNode = do allNodes <- nodes <$> (view interferenceGraph <$> get) allAccessableNodes <- filterSM (\n -> not <$> (onStack n)) allNodes case (not . none $ allAccessableNodes) of True -> maximumOnM getOutDegree (Set.toList allAccessableNodes) False -> return Nothing -- | check which colors are used, pick one if possible getFreeColor :: (MonadNameGen m, MonadIO m) => Set Temp -> Reg m (Maybe State) getFreeColor children = do validChildren <- filterSM isColored children usedColors <- mapSM getColor validChildren allColors <- view colors <$> get let possibleColors = Set.difference allColors usedColors case none possibleColors of True -> return Nothing False -> return . Just . Colored $ 0 `Set.elemAt` possibleColors
cirquit/hjc
src/Cmm/Register/Allocation.hs
mit
6,897
0
19
2,158
1,596
833
763
126
4
{-# htermination lookupWithDefaultFM :: (Ord a, Ord k) => FiniteMap (Either a k) b -> b -> (Either a k) -> b #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_lookupWithDefaultFM_10.hs
mit
130
0
3
25
5
3
2
1
0
module RenderSpec (spec) where import Test.Hspec spec :: Spec spec = do describe "dummy" $ do it "dummy" $ do True `shouldBe` True
rcook/hqdsl
src/spec/RenderSpec.hs
mit
146
0
13
38
53
28
25
7
1
{-# LANGUAGE FlexibleInstances #-} module Database.Design.Ampersand.Classes.ConceptStructure (ConceptStructure(..)) where import Database.Design.Ampersand.Core.AbstractSyntaxTree import Database.Design.Ampersand.Basics import Data.List import Data.Maybe import Database.Design.Ampersand.ADL1.Expression(primitives,isMp1,foldrMapExpression) import Database.Design.Ampersand.Classes.ViewPoint import Prelude hiding (Ordering(..)) {- TODO: Interface parameters (of type Declaration) are returned as Expressions by expressionsIn, to preserve the meaning of relsMentionedIn (implemented using primsMentionedIn, which calls expressionsIn). A more correct way to do this would be to not use expressionsIn, but define relsMentionedIn directly. Another improvement would be to factorize the prim constructors from the Expression data type, so expressionsIn won't need to be partial anymore. -} class ConceptStructure a where concs :: a -> [A_Concept] -- ^ the set of all concepts used in data structure a relsUsedIn :: a -> [Declaration] -- ^ the set of all declaratons used within data structure a. `used within` means that there is a relation that refers to that declaration. relsUsedIn a = [ d | d@Sgn{}<-relsMentionedIn a]++[Isn c | c<-concs a] relsMentionedIn :: a -> [Declaration] -- ^ the set of all declaratons used within data structure a. `used within` means that there is a relation that refers to that declaration. relsMentionedIn = nub . map prim2rel . primsMentionedIn primsMentionedIn :: a -> [Expression] primsMentionedIn = nub . concatMap primitives . expressionsIn expressionsIn :: a -> [Expression] -- ^ The set of all expressions within data structure a -- | mp1Pops draws the population from singleton expressions. mp1Pops :: ContextInfo -> a -> [Population] mp1Pops ci struc = [ ACptPopu{ popcpt = cpt (head cl) , popas = map atm cl } | cl<-eqCl cpt ((filter isMp1.primsMentionedIn) struc)] where cpt (EMp1 _ c) = c cpt _ = fatal 31 "cpt error" atm (EMp1 val c) = safePSingleton2AAtomVal ci c val atm _ = fatal 31 "atm error" prim2rel :: Expression -> Declaration prim2rel e = case e of EDcD d@Sgn{} -> d EDcD{} -> fatal 23 "invalid declaration in EDcD{}" EDcI c -> Isn c EDcV sgn -> Vs sgn EMp1 _ c -> Isn c _ -> fatal 40 $ "only primitive expressions should be found here.\nHere we see: " ++ show e instance (ConceptStructure a,ConceptStructure b) => ConceptStructure (a, b) where concs (a,b) = concs a `uni` concs b expressionsIn (a,b) = expressionsIn a `uni` expressionsIn b instance ConceptStructure a => ConceptStructure (Maybe a) where concs ma = maybe [] concs ma expressionsIn ma = maybe [] expressionsIn ma instance ConceptStructure a => ConceptStructure [a] where concs = nub . concatMap concs expressionsIn = foldr ((uni) . expressionsIn) [] instance ConceptStructure A_Context where concs ctx = foldr uni [ONE, PlainConcept "SESSION"] -- ONE and [SESSION] are allways in any context. (see https://github.com/AmpersandTarski/ampersand/issues/70) [ (concs.ctxpats) ctx , (concs.ctxrs) ctx , (concs.ctxds) ctx , (concs.ctxpopus) ctx , (concs.ctxcds) ctx , (concs.ctxks) ctx , (concs.ctxvs) ctx , (concs.ctxgs) ctx , (concs.ctxifcs) ctx , (concs.ctxps) ctx , (concs.ctxsql) ctx , (concs.ctxphp) ctx ] expressionsIn ctx = foldr uni [] [ (expressionsIn.ctxpats) ctx , (expressionsIn.ctxifcs) ctx , (expressionsIn.ctxrs) ctx , (expressionsIn.ctxks) ctx , (expressionsIn.ctxvs) ctx , (expressionsIn.ctxsql) ctx , (expressionsIn.ctxphp) ctx , (expressionsIn.multrules) ctx , (expressionsIn.identityRules) ctx ] instance ConceptStructure IdentityDef where concs identity = [idCpt identity] `uni` concs [objDef | IdentityExp objDef <- identityAts identity] expressionsIn identity = expressionsIn [objDef | IdentityExp objDef <- identityAts identity] instance ConceptStructure ViewDef where concs vd = [vdcpt vd] `uni` concs [objDef | ViewExp _ objDef <- vdats vd] expressionsIn vd = expressionsIn [objDef | ViewExp _ objDef <- vdats vd] instance ConceptStructure Expression where concs (EDcI c ) = [c] concs (EEps i sgn) = nub (i:concs sgn) concs (EDcV sgn) = concs sgn concs (EMp1 _ c ) = [c] concs e = foldrMapExpression uni concs [] e expressionsIn e = [e] instance ConceptStructure A_Concept where concs c = [c] expressionsIn _ = [] instance ConceptStructure ConceptDef where concs cd = [PlainConcept { cptnm = name cd } ] expressionsIn _ = [] instance ConceptStructure Signature where concs (Sign s t) = nub [s,t] expressionsIn _ = [] instance ConceptStructure ObjectDef where concs obj = [target (objctx obj)] `uni` concs (objmsub obj) expressionsIn obj = foldr (uni) [] [ (expressionsIn.objctx) obj , (expressionsIn.objmsub) obj ] -- Note that these functions are not recursive in the case of InterfaceRefs (which is of course obvious from their types) instance ConceptStructure SubInterface where concs (Box _ _ objs) = concs objs concs InterfaceRef{} = [] expressionsIn (Box _ _ objs) = expressionsIn objs expressionsIn InterfaceRef{} = [] instance ConceptStructure Pattern where concs pat = foldr uni [] [ (concs.ptrls) pat , (concs.ptgns) pat , (concs.ptdcs) pat , (concs.ptups) pat , (concs.ptids) pat , (concs.ptxps) pat ] expressionsIn p = foldr (uni) [] [ (expressionsIn.ptrls) p , (expressionsIn.ptids) p , (expressionsIn.ptvds) p ] instance ConceptStructure Interface where concs ifc = concs (ifcObj ifc) expressionsIn ifc = foldr (uni) [] [ (expressionsIn.ifcObj) ifc , map EDcD $ ifcParams ifc -- Return param declarations as expressions ] instance ConceptStructure Declaration where concs d = concs (sign d) expressionsIn _ = fatal 148 "expressionsIn not allowed on Declaration" instance ConceptStructure Rule where concs r = concs (rrexp r) `uni` concs (rrviol r) expressionsIn r = foldr (uni) [] [ (expressionsIn.rrexp ) r , (expressionsIn.rrviol) r ] instance ConceptStructure (PairView Expression) where concs (PairView ps) = concs ps expressionsIn (PairView ps) = expressionsIn ps instance ConceptStructure Population where concs pop@ARelPopu{} = concs (popdcl pop) concs pop@ACptPopu{} = concs (popcpt pop) expressionsIn _ = [] instance ConceptStructure Purpose where concs pop@Expl{} = concs (explObj pop) expressionsIn _ = [] instance ConceptStructure ExplObj where concs (ExplConceptDef cd) = concs cd concs (ExplDeclaration d) = concs d concs (ExplRule _) = [{-beware of loops...-}] concs (ExplIdentityDef _) = [{-beware of loops...-}] concs (ExplViewDef _) = [{-beware of loops...-}] concs (ExplPattern _) = [{-beware of loops...-}] concs (ExplInterface _) = [{-beware of loops...-}] concs (ExplContext _) = [{-beware of loops...-}] expressionsIn _ = [] instance ConceptStructure (PairViewSegment Expression) where concs pvs = case pvs of PairViewText{} -> [] PairViewExp{} -> concs (pvsExp pvs) expressionsIn pvs = case pvs of PairViewText{} -> [] PairViewExp{} -> expressionsIn (pvsExp pvs) instance ConceptStructure A_Gen where concs g@Isa{} = nub [gengen g,genspc g] concs g@IsE{} = nub (genspc g: genrhs g) expressionsIn _ = fatal 160 "expressionsIn not allowed on A_Gen"
4ZP6Capstone2015/ampersand
src/Database/Design/Ampersand/Classes/ConceptStructure.hs
gpl-3.0
8,413
0
15
2,422
2,349
1,213
1,136
157
6
module Fizz.Store ( record , budget , spend , save , earn , realize , redo , queryBack , queryRange , queryUntil , findEntry , loadJournal ) where import Fizz.Core import Fizz.Utils import Fizz.Log import Data.Either import Data.List import Data.Time ensureTimestamp :: MaybeTimestamped Entry -> IO (Timestamped Entry) ensureTimestamp (Nothing, e) = getCurrentTime >>= (\t -> return (utctDay t, e)) ensureTimestamp (Just t, e) = return (t, e) budget :: MaybeTimestamped BudgetEntry -> IO () budget = record . withSecond Budget spend :: MaybeTimestamped ExpenseEntry -> IO () spend = record . withSecond Spend save :: MaybeTimestamped ExpenseEntry -> IO () save = record . withSecond Save earn :: MaybeTimestamped ExpenseEntry -> IO () earn = record . withSecond Earn realize :: MaybeTimestamped ExpenseEntry -> IO () realize = record . withSecond Realize redo :: MaybeTimestamped Entry -> IO () redo = record . withSecond Redo withSecond :: (b -> c) -> (a, b) -> (a, c) withSecond f (a, b) = (a, f b) record :: MaybeTimestamped Entry -> IO () record e = ensureTimestamp e >>= strictAppend journal . (++"\n") . show queryBack :: Integer -> IO Journal queryBack lookback = do now <- getTime queryRange (addDays (negate lookback) (localDay now)) (localDay now) queryRange :: Day -> Day -> IO Journal queryRange start end = filter (between start end . getTimestamp) <$> loadJournal queryUntil :: (Entry -> Bool) -> IO Journal queryUntil test = takeWhile (not . test . snd) . reverse <$> loadJournal findEntry :: (Entry -> Bool) -> IO (Maybe (Timestamped Entry)) findEntry test = find (test . snd) . reverse <$> loadJournal loadJournal :: IO Journal loadJournal = do (badEntries, goodEntries) <- partitionEithers . fmap tryRead . lines <$> strictRead journal mapM_ fizzLog badEntries return goodEntries tryRead :: Read a => String -> Either String a tryRead s = maybe (Left $ "Couldn't parse: " ++ s) Right (maybeRead s) journal :: FilePath journal = "data/journal" strictAppend :: FilePath -> String -> IO () strictAppend fn s = s `seq` appendFile fn s strictRead :: FilePath -> IO String strictRead fn = readFile fn >>= \t -> seq t (return t)
josuf107/Fizzckle
src/Fizz/Store.hs
gpl-3.0
2,276
0
11
492
852
437
415
69
1
{-# LANGUAGE GADTs #-} -- | The core module of Hive. -- -- In this module we define the constructors and combinators for the Hive process algebra and also the interpreter. -- -- For example usage check out the "Hive.Problem.Arithmetic" module. module Hive.Process ( Process (..) , BasicProcess , Predicate , runProcess ) where ------------------------------------------------------------------------------- import Prelude hiding ((>>), (||)) import Hive.Types (Master) import Hive.Imports.MkBinary import Hive.Master.Messaging (getNode, returnNode, getFakeMaster, terminateMaster) import Data.Monoid import Control.Arrow ((&&&)) import Control.Monad (forM) import Control.Concurrent.MVar (MVar, newEmptyMVar, takeMVar, putMVar) import Control.Distributed.Process (liftIO, getSelfPid, call, spawnLocal, say) import Control.Distributed.Process.Serializable (Serializable, SerializableDict) import qualified Control.Distributed.Process as CH (Process, Closure, Static) ------------------------------------------------------------------------------- type Predicate a = Process a Bool -- | A BasicProcess is carried out in the Cloud Haskell Process monad type BasicProcess b = CH.Process b -- | The process algebra data Process a b where Id :: Process a a -- A constant process that returns a constant value Const :: (Serializable b) => CH.Static (SerializableDict b) -> CH.Closure (BasicProcess b) -> Process a b -- A simple process that wraps a pure function Simple :: (Serializable b) => CH.Static (SerializableDict b) -> (a -> CH.Closure (BasicProcess b)) -> Process a b -- A wrapper for a process that will be run locally Local :: Process a b -> Process a b -- A choice between two processes, based on the input value and another value that are combined into one value. -- This combinator inspects the input value and therefore cannot be an arrow. Choice :: Predicate a -> Process a b -> Process a b -> Process a b -- Execute two processes sequentially Sequence :: Process a c -> Process c b -> Process a b -- Executes one process multiple times and folds the results together --Multiple :: (Serializable b) => Process a c -> Int -> b -> Process (b, [c]) b -> Process a b -- Execute two processes in parallel and combine the results Parallel :: Process a c -> Process a d -> Process (c, d) b -> Process a b -- Execute a list of processes in parallel and fold the results together Multilel :: [Process a c] -> Process a b -> Process (b, [c]) b -> Process a b -- Repeat the execution of a process, like in a loop, as long as a given predicate holds. -- Unlike in imperative programming, we need a value that will be returned in case the predicate doesn't hold. In imperative programming this is represented implicitly by a (global) state. -- This combinator inspects the input value and therefore cannot be an arrow. Repetition :: Predicate a -> Process a a -> Process a a ------------------------------------------------------------------------------- -- interpretation of Process structure ------------------------------------------------------------------------------- -- | This is the interpreter for processes created using the Hive process algebra. -- To run a process, we need a master node that can give us worker nodes to run the basic processes on. -- Then we need a process that should be run as well as an input value to run the process on. runProcess :: Master -> Process a b -> a -> BasicProcess b runProcess _ Id x = return x runProcess master (Const sDict closure) x = runProcess master (Simple sDict (const closure)) x runProcess master (Simple sDict closureGen) x = do node <- getNode master =<< getSelfPid res <- call sDict node (closureGen x) returnNode master node return res runProcess _ (Local p) x = do fakeMaster <- getFakeMaster =<< getSelfPid res <- runProcess fakeMaster p x terminateMaster fakeMaster return res runProcess master (Choice pr p1 p2) x = do b <- runProcess master pr x runProcess master (if b then p1 else p2) x runProcess master (Sequence p1 p2) x = runProcess master p1 x >>= runProcess master p2 runProcess master (Parallel p1 p2 combinator) x = do mvar <- liftIO newEmptyMVar _ <- spawnLocal $ runProcessHelper master p1 x mvar r2 <- runProcess master p2 x r1 <- liftIO $ takeMVar mvar runProcess master combinator (r1, r2) runProcess master (Multilel ps foldinit fold) x = do mvars <- forM ps $ \_ -> liftIO newEmptyMVar mapM_ (\(proc, mvar) -> spawnLocal $ runProcessHelper master proc x mvar) (ps `zip` mvars) ib <- runProcess master foldinit x ress <- forM mvars $ \mvar -> liftIO . takeMVar $ mvar runProcess master fold (ib, ress) runProcess master rep@(Repetition pr p) x = runProcess master (Choice pr (Sequence p rep) Id) x ------------------------------------------------------------------------------- -- | A helper function to run processes in background. -- The process helper will be spawned in a new local process and put its result into an MVar. runProcessHelper :: Master -> Process a b -> a -> MVar b -> CH.Process () runProcessHelper master p x mvar = do r <- runProcess master p x liftIO $ putMVar mvar r
chrisbloecker/Hive
src/Hive/Process.hs
gpl-3.0
5,280
0
12
1,016
1,220
637
583
67
2
{-# LANGUAGE TemplateHaskell #-} module View.State where import Debug.Trace import Control.Lens import Middleware.Gloss.Facade (Picture) import GameLogic import View.Convert import Paths_gamenumber_gloss data ViewData = ViewData { _game :: GameData , _windowSize :: (Int, Int) -- current window size } deriving (Show) makeLenses ''ViewData type ViewAction = ViewData -> ViewData type ViewActionIO = ViewData -> IO ViewData type WindowAction a = (Coord, Coord) -> ViewAction type WindowGameAction a = (Coord, Coord) -> GameState a type PanelAction a = Coord -> WindowGameAction a newState :: IO ViewData newState = do --runStartupTest game <- newGame return $ ViewData game (100, 100) runStartupTest = do traceIO "Testing" traceIO . show $ getNearestPoses (2,3) runGameStep :: Float -> ViewActionIO runGameStep _ = return . over game (execState doGameStep) startPlacement :: WindowAction () startPlacement pos = set placementModeOfGame True . doWithWindowPos doSelectCellAction pos stopPlacement :: ViewAction stopPlacement = set placementModeOfGame False inPlacementMode :: ViewData -> Bool inPlacementMode = view placementModeOfGame placementModeOfGame :: Lens' ViewData Bool placementModeOfGame = game . placementMode centering :: WindowAction () centering = doWithWindowPos2 setCenterPosLimited setCenterPosByMiniMap setCenterPosByMiniMap :: PanelAction () setCenterPosByMiniMap height (x, y) = setCenterPosOnMiniMap (x - dx, y - dy) where (dx, dy) = shiftMiniMap height setCenterPosOnMiniMap :: WindowGameAction () setCenterPosOnMiniMap (x, y) = setCenterPos (floor x, floor y) drawing :: WindowAction () drawing = doWithWindowPos doSelectCellAction updateWindowSize :: (Int, Int) -> ViewAction updateWindowSize = set windowSize saveFileName :: IO FilePath saveFileName = getDataFileName "gamenumber.gn" doSave :: ViewActionIO doSave state = do fileName <- saveFileName doSaveGame fileName $ state ^. game return state doLoad :: ViewActionIO doLoad state = do let g = state ^. game fileName <- saveFileName g' <- doLoadGame fileName g return $ set game g' state doHelpPlayer :: ViewAction doHelpPlayer state = state & game %~ execState (helpPlayer activePlayerIndex) doChangePaused :: ViewAction doChangePaused = game . paused %~ not doShieldAction :: ViewAction doShieldAction state = state & game %~ execState (shieldAction activePlayerIndex) increaseSpeed :: ViewAction increaseSpeed = game . gameSpeed %~ succ' where succ' gs = if gs == maxBound then gs else succ gs decreaseSpeed :: ViewAction decreaseSpeed = game . gameSpeed %~ pred' where pred' gs = if gs == minBound then gs else pred gs doWithWindowPosOnGame :: WorldAction -> WindowGameAction () doWithWindowPosOnGame action pos = gets (worldPosOfWindowPos pos) >>= action doWithWindowPosInField :: WorldAction -> WindowAction () doWithWindowPosInField action pos = game %~ execState (doWithWindowPosOnGame action pos) doWithWindowPos :: WorldAction -> WindowAction () doWithWindowPos action pos@(x, y) state | inPanel pos state = state | otherwise = doWithWindowPosInField action pos' state where pos' = (x - worldShiftX, y) doWithWindowPos2 :: WorldAction -> PanelAction () -> WindowAction () doWithWindowPos2 action panelAction pos@(x, y) state | inPanel pos state = doWithWindowPosInPanel panelAction pos state | otherwise = doWithWindowPosInField action pos' state where (w, h) = view windowSize state pos' = (x - worldShiftX, y) doWithWindowPosInPanel :: PanelAction () -> WindowAction () doWithWindowPosInPanel panelAction (x, y) state = state & game %~ f where x' = x - panelLeftX state (_, h) = state ^. windowSize f = execState $ panelAction (fromIntegral h) (x', y) inPanel :: (Coord, Coord) -> ViewData -> Bool inPanel (x, y) state = x >= panelLeftX state panelLeftX :: ViewData -> Coord panelLeftX state = width/2 - panelWidth where size = state ^. windowSize width = fromIntegral $ fst size worldShiftX = - panelWidth / 2 :: Coord
EPashkin/gamenumber-gloss
src/View/State.hs
gpl-3.0
4,193
0
10
837
1,254
653
601
-1
-1
{-# LANGUAGE FlexibleInstances #-} module Ampersand.Graphic.Graphics (makePicture, writePicture, Picture(..), PictureReq(..),imagePath )where import Ampersand.ADL1 import Ampersand.Basics import Ampersand.Classes import Ampersand.Graphic.ClassDiagram(ClassDiag) import Ampersand.FSpec.FSpec import Ampersand.Graphic.ClassDiag2Dot import Ampersand.Graphic.Fspec2ClassDiagrams import Ampersand.Misc import Control.Exception (catch, IOException) import Data.Char import Data.GraphViz import Data.GraphViz.Attributes.Complete import Data.List import qualified Data.Set as Set import Data.String(fromString) import System.Directory import System.FilePath hiding (addExtension) import System.Process (callCommand) data PictureReq = PTClassDiagram | PTCDPattern Pattern | PTDeclaredInPat Pattern | PTCDConcept A_Concept | PTCDRule Rule | PTLogicalDM | PTTechnicalDM data DotContent = ClassDiagram ClassDiag | ConceptualDg ConceptualStructure data Picture = Pict { pType :: PictureReq -- ^ the type of the picture , scale :: String -- ^ a scale factor, intended to pass on to LaTeX, because Pandoc seems to have a problem with scaling. , dotContent :: DotContent , dotProgName :: GraphvizCommand -- ^ the name of the program to use ("dot" or "neato" or "fdp" or "Sfdp") , caption :: String -- ^ a human readable name of this picture } makePicture :: FSpec -> PictureReq -> Picture makePicture fSpec pr = case pr of PTClassDiagram -> Pict { pType = pr , scale = scale' , dotContent = ClassDiagram $ clAnalysis fSpec , dotProgName = Dot , caption = case fsLang fSpec of English -> "Classification of " ++ name fSpec Dutch -> "Classificatie van " ++ name fSpec } PTLogicalDM -> Pict { pType = pr , scale = scale' , dotContent = ClassDiagram $ cdAnalysis fSpec , dotProgName = Dot , caption = case fsLang fSpec of English -> "Logical data model of " ++ name fSpec Dutch -> "Logisch gegevensmodel van " ++ name fSpec } PTTechnicalDM -> Pict { pType = pr , scale = scale' , dotContent = ClassDiagram $ tdAnalysis fSpec , dotProgName = Dot , caption = case fsLang fSpec of English -> "Technical data model of " ++ name fSpec Dutch -> "Technisch gegevensmodel van " ++ name fSpec } PTCDConcept cpt -> Pict { pType = pr , scale = scale' , dotContent = ConceptualDg $ conceptualStructure fSpec pr , dotProgName = graphVizCmdForConceptualGraph , caption = case fsLang fSpec of English -> "Concept diagram of the rules about " ++ name cpt Dutch -> "Conceptueel diagram van de regels rond " ++ name cpt } PTDeclaredInPat pat -> Pict { pType = pr , scale = scale' , dotContent = ConceptualDg $ conceptualStructure fSpec pr , dotProgName = graphVizCmdForConceptualGraph , caption = case fsLang fSpec of English -> "Concept diagram of relations in " ++ name pat Dutch -> "Conceptueel diagram van relaties in " ++ name pat } PTCDPattern pat -> Pict { pType = pr , scale = scale' , dotContent = ConceptualDg $ conceptualStructure fSpec pr , dotProgName = graphVizCmdForConceptualGraph , caption = case fsLang fSpec of English -> "Concept diagram of the rules in " ++ name pat Dutch -> "Conceptueel diagram van de regels in " ++ name pat } PTCDRule rul -> Pict { pType = pr , scale = scale' , dotContent = ConceptualDg $ conceptualStructure fSpec pr , dotProgName = graphVizCmdForConceptualGraph , caption = case fsLang fSpec of English -> "Concept diagram of rule " ++ name rul Dutch -> "Conceptueel diagram van regel " ++ name rul } where scale' = case pr of PTClassDiagram -> "1.0" PTCDPattern{}-> "0.7" PTDeclaredInPat{}-> "0.6" PTCDRule{} -> "0.7" PTCDConcept{} -> "0.7" PTLogicalDM -> "1.2" PTTechnicalDM -> "1.2" graphVizCmdForConceptualGraph = -- Dot gives bad results, but there seems no way to fiddle with the length of edges. Neato -- Sfdp is a bad choice, because it causes a bug in linux. see http://www.graphviz.org/content/sfdp-graphviz-not-built-triangulation-library) pictureID :: PictureReq -> String pictureID pr = case pr of PTClassDiagram -> "Classification" PTLogicalDM -> "LogicalDataModel" PTTechnicalDM -> "TechnicalDataModel" PTCDConcept cpt -> "CDConcept"++name cpt PTDeclaredInPat pat -> "RelationsInPattern"++name pat PTCDPattern pat -> "CDPattern"++name pat PTCDRule r -> "CDRule"++name r conceptualStructure :: FSpec -> PictureReq -> ConceptualStructure conceptualStructure fSpec pr = case pr of PTCDConcept c -> let gs = fsisa fSpec cpts' = concs rs rs = [r | r<-Set.elems $ vrules fSpec, c `elem` concs r] in CStruct { csCpts = nub$ Set.elems cpts' ++ [g |(s,g)<-gs, elem g cpts' || elem s cpts'] ++ [s |(s,g)<-gs, elem g cpts' || elem s cpts'] , csRels = filter (not . isProp . EDcD) . Set.elems . bindedRelationsIn $ rs -- the use of "bindedRelationsIn" restricts relations to those actually used in rs , csIdgs = [(s,g) |(s,g)<-gs, elem g cpts' || elem s cpts'] -- all isa edges } -- PTCDPattern makes a picture of at least the relations within pat; -- extended with a limited number of more general concepts; -- and rels to prevent disconnected concepts, which can be connected given the entire context. PTCDPattern pat -> let orphans = [c | c<-Set.elems cpts, not(c `elem` concs idgs || c `elem` concs rels)] xrels = Set.fromList [r | c<-orphans, r<-Set.elems $ vrels fSpec , (c == source r && target r `elem` cpts) || (c == target r && source r `elem` cpts) , source r /= target r, decusr r ] idgs = [(s,g) |(s,g)<-gs, g `elem` cpts, s `elem` cpts] -- all isa edges within the concepts gs = fsisa fSpec cpts = cpts' `Set.union` Set.fromList [g |cl<-eqCl id [g |(s,g)<-gs, s `elem` cpts'], length cl<3, g<-cl] -- up to two more general concepts cpts' = concs pat `Set.union` concs rels rels = Set.fromList . filter (not . isProp . EDcD) . Set.elems . bindedRelationsIn $ pat in CStruct { csCpts = Set.elems $ cpts' `Set.union` Set.fromList [g |cl<-eqCl id [g |(s,g)<-gs, s `elem` cpts'], length cl<3, g<-cl] -- up to two more general concepts , csRels = Set.elems $ rels `Set.union` xrels -- extra rels to connect concepts without rels in this picture, but with rels in the fSpec , csIdgs = idgs } -- PTDeclaredInPat makes a picture of relations and gens within pat only PTDeclaredInPat pat -> let gs = fsisa fSpec cpts = concs decs `Set.union` concs (gens pat) decs = relsDefdIn pat `Set.union` bindedRelationsIn (udefrules pat) in CStruct { csCpts = Set.elems cpts , csRels = Set.elems . Set.filter (not . isProp . EDcD) . Set.filter decusr $ decs , csIdgs = [(s,g) |(s,g)<-gs, g `elem` cpts, s `elem` cpts] -- all isa edges within the concepts } PTCDRule r -> let idgs = [(s,g) | (s,g)<-fsisa fSpec , g `elem` concs r || s `elem` concs r] -- all isa edges in CStruct { csCpts = Set.elems $ concs r `Set.union` Set.fromList [c |(s,g)<-idgs, c<-[g,s]] , csRels = Set.elems . Set.filter (not . isProp . EDcD) . Set.filter decusr $ bindedRelationsIn r , csIdgs = idgs -- involve all isa links from concepts touched by one of the affected rules } _ -> fatal "No conceptual graph defined for this type." writePicture :: Options -> Picture -> IO() writePicture opts pict = sequence_ ( [createDirectoryIfMissing True (takeDirectory (imagePath opts pict)) ]++ -- [dumpShow ]++ [writeDot Canon | genFSpec opts ]++ --Pretty-printed Dot output with no layout performed. [writeDot DotOutput | genFSpec opts] ++ --Reproduces the input along with layout information. [writeDot Png | genFSpec opts ] ++ --handy format to include in github comments/issues [writeDot Svg | genFSpec opts ] ++ -- format that is used when docx docs are being generated. [writePdf Eps | genFSpec opts ] -- .eps file that is postprocessed to a .pdf file ) where writeDot :: GraphvizOutput -> IO () writeDot = writeDotPostProcess Nothing writeDotPostProcess :: Maybe (FilePath -> IO ()) --Optional postprocessor -> GraphvizOutput -> IO () writeDotPostProcess postProcess gvOutput = do verboseLn opts ("Generating "++show gvOutput++" using "++show gvCommand++".") dotSource <- mkDotGraphIO opts pict path <- (addExtension (runGraphvizCommand gvCommand dotSource) gvOutput) $ (dropExtension . imagePath opts) pict verboseLn opts (path++" written.") case postProcess of Nothing -> return () Just x -> x path where gvCommand = dotProgName pict -- The GraphVizOutput Pdf generates pixelised graphics on Linux -- the GraphVizOutput Eps generates extended postscript that can be postprocessed to PDF. makePdf :: FilePath -> IO () makePdf path = do callCommand (ps2pdfCmd path) verboseLn opts (replaceExtension path ".pdf" ++ " written.") `catch` \ e -> verboseLn opts ("Could not invoke PostScript->PDF conversion."++ "\n Did you install MikTex? Can the command epstopdf be found?"++ "\n Your error message is:\n " ++ show (e :: IOException)) writePdf :: GraphvizOutput -> IO () writePdf x = (writeDotPostProcess (Just makePdf) x) `catch` (\ e -> verboseLn opts ("Something went wrong while creating your Pdf."++ --see issue at https://github.com/AmpersandTarski/RAP/issues/21 "\n Your error message is:\n " ++ show (e :: IOException))) ps2pdfCmd path = "epstopdf " ++ path -- epstopdf is installed in miktex. (package epspdfconversion ?) mkDotGraphIO :: Options -> Picture -> IO (DotGraph String) mkDotGraphIO opts pict = case dotContent pict of ClassDiagram x -> pure $ classdiagram2dot opts x ConceptualDg x -> pure $ conceptual2DotIO opts x class ReferableFromPandoc a where imagePath :: Options -> a -> FilePath -- ^ the full file path to the image file instance ReferableFromPandoc Picture where imagePath opts p = dirOutput opts </> (escapeNonAlphaNum . pictureID . pType ) p <.> case fspecFormat opts of Fpdf -> "png" -- If Pandoc makes a PDF file, the pictures must be delivered in .png format. .pdf-pictures don't seem to work. Fdocx -> "svg" -- If Pandoc makes a .docx file, the pictures are delivered in .svg format for scalable rendering in MS-word. _ -> "pdf" data ConceptualStructure = CStruct { csCpts :: [A_Concept] -- ^ The concepts to draw in the graph , csRels :: [Relation] -- ^ The relations, (the edges in the graph) , csIdgs :: [(A_Concept, A_Concept)] -- ^ list of Isa relations } conceptual2DotIO :: Options -> ConceptualStructure -> DotGraph String conceptual2DotIO opts cs@(CStruct _ rels idgs) = DotGraph { strictGraph = False , directedGraph = True , graphID = Nothing , graphStatements = DotStmts { attrStmts = [GraphAttrs [ BgColor [WC (X11Color White ) Nothing] , Landscape False , Mode IpSep , OutputOrder EdgesFirst , Overlap VoronoiOverlap , Sep (DVal 0.8) , NodeSep 1.0 , Rank SameRank , RankDir FromTop , RankSep [2.5] , ReMinCross True {- Commented out because of an issue: See https://gitlab.com/graphviz/graphviz/issues/1485 , Splines Curved -} ] , NodeAttrs [ Shape BoxShape , BgColor [WC (X11Color LightGray ) Nothing] , Style [SItem Rounded [] ,SItem Filled [] ,SItem Bold [] ] ] , EdgeAttrs [ Color [WC (X11Color Black ) Nothing] , edgeLenFactor 1 ] ] , subGraphs = [] , nodeStmts = concatMap nodes (allCpts cs) ++concatMap nodes rels ++concatMap nodes idgs , edgeStmts = concatMap edges (allCpts cs) ++concatMap edges rels ++concatMap edges idgs } } where nodes :: HasDotParts a => a -> [DotNode String] nodes = dotNodes opts cs edges :: HasDotParts a => a -> [DotEdge String] edges = dotEdges opts cs class HasDotParts a where dotNodes :: Options -> ConceptualStructure -> a -> [DotNode String] dotEdges :: Options -> ConceptualStructure -> a -> [DotEdge String] baseNodeId :: ConceptualStructure -> A_Concept -> String baseNodeId x c = case lookup c (zip (allCpts x) [(1::Int)..]) of Just i -> "cpt_"++show i _ -> fatal ("element "++name c++" not found by nodeLabel.") allCpts :: ConceptualStructure -> [A_Concept] allCpts (CStruct cpts' rels idgs) = Set.elems $ Set.fromList cpts' `Set.union` concs rels `Set.union` concs idgs edgeLenFactor :: Double -> Attribute edgeLenFactor x = Len (4 * x) instance HasDotParts A_Concept where dotNodes _ x cpt = [DotNode { nodeID = baseNodeId x cpt , nodeAttributes = [ Label . StrLabel . fromString . name $ cpt ] } ] dotEdges _ _ _ = [] instance HasDotParts Relation where dotNodes _ x rel | isEndo rel = [DotNode { nodeID = baseNodeId x (source rel) ++ name rel , nodeAttributes = [ Color [WC (X11Color Transparent ) Nothing] , Shape PlainText , Label . StrLabel . fromString . intercalate "\n" $ name rel : case Set.toList . properties $ rel of [] -> [] ps -> ["["++(intercalate ", " . map (map toLower . show) $ ps)++"]"] ] } ] | otherwise = [] dotEdges _ x rel | isEndo rel = [ DotEdge { fromNode = baseNodeId x . source $ rel , toNode = baseNodeId x (source rel) ++ name rel , edgeAttributes = [ Dir NoDir , edgeLenFactor 0.4 , Label . StrLabel . fromString $ "" ] } ] | otherwise = [ DotEdge { fromNode = baseNodeId x . source $ rel , toNode = baseNodeId x . target $ rel , edgeAttributes = [ Label . StrLabel . fromString . intercalate "\n" $ name rel : case Set.toList . properties $ rel of [] -> [] ps -> ["["++(intercalate ", " . map (map toLower . show) $ ps)++"]"] ] } ] instance HasDotParts (A_Concept,A_Concept) where dotNodes _ _ _ = [] dotEdges _ x (gen,spc) = [ DotEdge { fromNode = baseNodeId x gen , toNode = baseNodeId x spc , edgeAttributes = [ edgeLenFactor 0.5 , Label . StrLabel . fromString $ "" , Color [WC (X11Color Red ) Nothing] , ArrowHead (AType [( ArrMod { arrowFill = OpenArrow , arrowSide = BothSides } , Normal ) ] ) ] } ] {- crowfootArrowType :: Bool -> Relation -> ArrowType crowfootArrowType isHead r = AType (if isHead then getCrowfootShape (isUni bindedExpr) (isTot bindedExpr) else getCrowfootShape (isInj bindedExpr) (isSur bindedExpr) ) where bindedExpr = EDcD r getCrowfootShape :: Bool -> Bool -> [( ArrowModifier , ArrowShape )] getCrowfootShape a b = case (a,b) of (True ,True ) -> [my_tee ] (False,True ) -> [my_crow, my_tee ] (True ,False) -> [my_odot, my_tee ] (False,False) -> [my_crow, my_odot] my_tee :: ( ArrowModifier , ArrowShape ) my_tee = ( noMod , Tee ) my_odot :: ( ArrowModifier , ArrowShape ) my_odot= ( open, DotArrow ) my_crow :: ( ArrowModifier , ArrowShape ) my_crow= ( open, Crow ) noMod :: ArrowModifier noMod = ArrMod { arrowFill = FilledArrow , arrowSide = BothSides } open :: ArrowModifier open = noMod {arrowFill = OpenArrow} -}
AmpersandTarski/ampersand
src/Ampersand/Graphic/Graphics.hs
gpl-3.0
21,346
0
24
9,611
4,251
2,244
2,007
310
20
{-# LANGUAGE OverloadedStrings #-} module Pretty where import Prelude hiding ((<$>)) import Syntax import Text.PrettyPrint.ANSI.Leijen import System.IO (Handle) import Data.Text (Text, unpack) import qualified Data.Map.Strict as Map import qualified Data.Vector as V prettyVariable :: Variable -> Doc prettyVariable (NamedVar n) = pretty (unpack n) prettyVariable (GeneratedVar n) = "v_" <> pretty n label :: Text -> Doc label t = blue (pretty (unpack t)) tag :: Text -> Doc tag t = green (pretty (unpack t)) prettyType BoolT = "Bool" prettyType IntT = "Int" prettyType TextT = "Text" prettyType (VectorT t) = brackets (prettyType t) prettyType (RecordT r) = braces (align (vt (Map.toAscList r))) where vt [] = empty vt [(k, t)] = label k <> ":" <+> group (prettyType t) vt ((k, t):tes) = label k <> ":" <+> group (prettyType t) <> "," <$> vt tes prettyType (VariantT r) = "[|" <+> align (vt (Map.toAscList r)) <+> "|]" where vt [] = empty vt [(k, t)] = tag k <> ":" <+> group (prettyType t) vt ((k, t):tes) = tag k <> ":" <+> group (prettyType t) <> "|" <$> vt tes prettyType (FunT a b) = parens $ prettyType a <+> "->" <+> prettyType b prettyType otherwise = pretty (show otherwise) prettyCode :: Expr -> Doc prettyCode (VBool b) = pretty b prettyCode (VInt i) = pretty i prettyCode (VText t) = "\"" <> pretty (unpack t) <> "\"" prettyCode (Var Nothing v) = prettyVariable v prettyCode (Var (Just t) v) = prettyVariable v -- <> ":" <+> prettyType t prettyCode (Record es) = braces (align (ke (Map.toAscList es))) where ke [] = empty ke [(k, e)] = label k <> " = " <> group (prettyCode e) ke ((k, e):kes) = label k <> " = " <> group (prettyCode e) <> "," <$> ke kes prettyCode (List _ es) = brackets (align (ke (V.toList es))) where ke [] = empty ke [e] = group $ prettyCode e ke (e:es) = group (prettyCode e) <> "," <$> ke es prettyCode (Tag t e) = parens $ align $ tag t </> prettyCode e prettyCode (Switch _ e cs) = hang 2 $ magenta "switch" <+> prettyCode e <$> cases (Map.toAscList cs) where cases [] = empty cases [c] = case' c cases (c:cs) = case' c <$> cases cs case' (t, (v, e)) = hang 2 $ magenta "case" <+> green (pretty (unpack t)) <+> prettyVariable v <+> "=>" </> prettyCode e prettyCode (App a b) = -- red "(" <> prettyCode a <+> red "$" <+> prettyCode b <> red ")" prettyCode a </> prettyCode b prettyCode (Proj _ l e) = prettyCode e <> magenta "." <> label l prettyCode (DynProj _ a b) = parens (prettyCode b) <> magenta "!" <> parens (prettyCode a) prettyCode (Union l r) = parens $ prettyCode l <+> "++" <+> prettyCode r prettyCode (Eq l r) = parens $ prettyCode l <+> "==" <+> prettyCode r prettyCode (And l r) = parens $ prettyCode l <+> "&&" <+> prettyCode r prettyCode (PrependPrefix l r) = parens $ prettyCode l <+> magenta "⋅" <+> prettyCode r prettyCode (Indexed e) = parens $ magenta "indexed" <+> prettyCode e prettyCode (Table tn tt) = magenta "table" <+> prettyCode (VText tn) <+> prettyType tt prettyCode (For x l e) = hang 2 $ magenta "for" <+> parens (prettyVariable x <+> "<-" <+> group (prettyCode l)) <$> prettyCode e prettyCode (Lam _ x e) = parens $ hang 2 $ magenta "λ" <> prettyVariable x <> "." <$> prettyCode e prettyCode (Closure x env e) = hang 2 $ parens $ red "λ" <> prettyVariable x <> "." </> prettyCode e prettyCode (If c t e) = align $ magenta "if" <+> group (prettyCode c) <$> hang 2 (magenta "then" </> prettyCode t) <$> hang 2 (magenta "else" </> prettyCode e) prettyCode (RecordMap _ a x y b) = magenta "rmap" <+> prettyCode a <+> magenta "with" <+> parens (prettyVariable x <+> "=" <+> prettyVariable y) <+> "=>" </> prettyCode b prettyCode (Lookup _ b) = magenta "lookup" <+> prettyCode b prettyCode (Undefined t) = magenta "undefined" <+> prettyCode (VText t) prettyCode (Self b e) = magenta "self" <+> prettyCode b <+> prettyCode e prettyCode other = string (show other) printCode :: Handle -> Expr -> IO () printCode h c = displayIO h (renderSmart 0.8 120 (prettyCode c)) printType :: Handle -> Type -> IO () printType h t = displayIO h (renderPretty 0.8 120 (prettyType t))
fehrenbach/rechts
app/Pretty.hs
gpl-3.0
4,170
0
15
877
1,962
957
1,005
91
7
{-# 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.Compute.TargetPools.GetHealth -- 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) -- -- Gets the most recent health check results for each IP for the instance -- that is referenced by the given target pool. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetPools.getHealth@. module Network.Google.Resource.Compute.TargetPools.GetHealth ( -- * REST Resource TargetPoolsGetHealthResource -- * Creating a Request , targetPoolsGetHealth , TargetPoolsGetHealth -- * Request Lenses , tpghProject , tpghTargetPool , tpghPayload , tpghRegion ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.targetPools.getHealth@ method which the -- 'TargetPoolsGetHealth' request conforms to. type TargetPoolsGetHealthResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "targetPools" :> Capture "targetPool" Text :> "getHealth" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] InstanceReference :> Post '[JSON] TargetPoolInstanceHealth -- | Gets the most recent health check results for each IP for the instance -- that is referenced by the given target pool. -- -- /See:/ 'targetPoolsGetHealth' smart constructor. data TargetPoolsGetHealth = TargetPoolsGetHealth' { _tpghProject :: !Text , _tpghTargetPool :: !Text , _tpghPayload :: !InstanceReference , _tpghRegion :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TargetPoolsGetHealth' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tpghProject' -- -- * 'tpghTargetPool' -- -- * 'tpghPayload' -- -- * 'tpghRegion' targetPoolsGetHealth :: Text -- ^ 'tpghProject' -> Text -- ^ 'tpghTargetPool' -> InstanceReference -- ^ 'tpghPayload' -> Text -- ^ 'tpghRegion' -> TargetPoolsGetHealth targetPoolsGetHealth pTpghProject_ pTpghTargetPool_ pTpghPayload_ pTpghRegion_ = TargetPoolsGetHealth' { _tpghProject = pTpghProject_ , _tpghTargetPool = pTpghTargetPool_ , _tpghPayload = pTpghPayload_ , _tpghRegion = pTpghRegion_ } -- | Project ID for this request. tpghProject :: Lens' TargetPoolsGetHealth Text tpghProject = lens _tpghProject (\ s a -> s{_tpghProject = a}) -- | Name of the TargetPool resource to which the queried instance belongs. tpghTargetPool :: Lens' TargetPoolsGetHealth Text tpghTargetPool = lens _tpghTargetPool (\ s a -> s{_tpghTargetPool = a}) -- | Multipart request metadata. tpghPayload :: Lens' TargetPoolsGetHealth InstanceReference tpghPayload = lens _tpghPayload (\ s a -> s{_tpghPayload = a}) -- | Name of the region scoping this request. tpghRegion :: Lens' TargetPoolsGetHealth Text tpghRegion = lens _tpghRegion (\ s a -> s{_tpghRegion = a}) instance GoogleRequest TargetPoolsGetHealth where type Rs TargetPoolsGetHealth = TargetPoolInstanceHealth type Scopes TargetPoolsGetHealth = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient TargetPoolsGetHealth'{..} = go _tpghProject _tpghRegion _tpghTargetPool (Just AltJSON) _tpghPayload computeService where go = buildClient (Proxy :: Proxy TargetPoolsGetHealthResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/TargetPools/GetHealth.hs
mpl-2.0
4,547
0
18
1,107
552
328
224
91
1
{-# LANGUAGE OverloadedStrings #-} module HeistUtil where import qualified Text.XmlHtml as X import qualified Heist.Compiled as C import qualified Data.Text as DT import qualified Blaze.ByteString.Builder as BB import Heist import Data.Scientific -- import Data.ByteString.Builder import Control.Monad ------------------------------------------------------------------------------ -- | Splice wrapped around a HTML node transform; the first child node in the -- block is passed as the param to the RuntimeSplice function, allowing for -- runtime injection of an updated node. -- -- > <splice_key> -- > <node template="passed" to="runtime" function /> -- > </splice_key> -- templatedNodeSplice :: Monad n => (X.Node -> RuntimeSplice n X.Node) -> C.Splice n templatedNodeSplice f = do paramNode <- getParamNode let n = Prelude.head $ X.childElements paramNode return $ C.yieldRuntime $ liftM render (f n) where render x = X.renderHtmlFragment X.UTF8 [x] formatPrice :: Scientific -> String formatPrice num = "£" ++ (formatScientific Fixed (Just 2) num) escapingTextSplice :: (a -> DT.Text) -> a -> BB.Builder escapingTextSplice f a = C.nodeSplice (\b -> [X.TextNode b]) (f a)
rjohnsondev/haskellshop
src/HeistUtil.hs
bsd-2-clause
1,226
0
12
215
279
155
124
19
1
-- solve.hs -- a solver for Hashiwokakero puzzles -- Copyright (C) 2013 by Harald Bögeholz -- See LICENSE file for license information import Hashi import System.Environment import Control.Monad (when) main :: IO () main = do args <- getArgs case args of [filename] -> do s <- readFile filename work s (filename ++ ".solution.eps") [] -> error "Usage: solve filename\nWill write solution to filename.solution.eps" _ -> error "Too many arguments." where work s outfile = case readProblem s of Left e -> putStrLn e Right p -> do putStrLn $ "Will write first solution to '" ++ outfile ++ "'." let solutions = solve p when (not (null solutions)) $ writeFile outfile $ showStateEPS $ head solutions putStrLn $ "Total number of solutions: " ++ show (length solutions)
ctbo/hashi
solve.hs
bsd-2-clause
953
0
19
318
229
109
120
19
4
module Handler.View where import Import import Data.Time.Clock import Model.Epub import Handler.Utils import Model.PaperP import Handler.Render import Model.PaperMongo (getRawHtmlById) import Text.Blaze.Html (preEscapedToHtml) -- -- Handlers for sending / showing the paper. -- getPaperRa :: PaperId -> Handler TypedContent getPaperRa paperId = renderPaper paperId FormatA getPaperRb :: PaperId -> Handler TypedContent getPaperRb paperId = renderPaper paperId FormatB getPaperRc :: PaperId -> Handler TypedContent getPaperRc paperId = renderPaper paperId FormatC getPaperTabletRa :: PaperId -> Handler TypedContent getPaperTabletRa paperId = renderPaper paperId FormatATablet getPaperTabletRb :: PaperId -> Handler TypedContent getPaperTabletRb paperId = renderPaper paperId FormatBTablet getMobilePaperRa :: PaperId -> Handler TypedContent getMobilePaperRa paperId = renderPaper paperId FormatAMobile getMobilePaperRb :: PaperId -> Handler TypedContent getMobilePaperRb paperId = renderPaper paperId FormatBMobile getDoiPaperR :: Handler TypedContent getDoiPaperR = notFound {- getDoiPaperR :: String -> String -> Handler TypedContent getDoiPaperR pub doc = do email <- requireAuthId' let doi = T.pack (pub ++ "/" ++ doc) -- ToDo: support different versions for the same DOI. p <- getPaperByFilter email ["doi" =: doi] let pp = case res of ((Entity id p):_) -> Just (p,id) _ -> Nothing let (orig,paperId) = fromJust pp getPaperRb paperId -} getRawHtmlR :: PaperId -> Handler TypedContent getRawHtmlR paperId = do email <- requireAuthId' mhtml <- getRawHtmlById email paperId case mhtml of Just html -> return $ toTypedContent $ preEscapedToHtml html Nothing -> notFound getEpubPaperR :: PaperId -> Handler () getEpubPaperR pid = do email <- requireAuthId' paper <- runDB $ get404 pid if Just email == paperUserEmail paper then do let pp = paperToPaperP paper path <- epubFromPaper pid pp sendFile "application/epub+zip" path else notFound -- history data is a separate table from paper. doUpdateVisitHistory :: PaperId -> Paper -> Handler () doUpdateVisitHistory pid p = do time <- liftIO $ getCurrentTime case paperUserEmail p of Just email -> do let history = History (Just pid) HAView time (User email Nothing Nothing) Nothing _ <- runDB $ insert history return () Nothing -> return ()
hirokai/PaperServer
Handler/View.hs
bsd-2-clause
2,420
0
17
452
544
265
279
50
2
{-| A module that is the implementation of the CheckerState class for the InternalState class -} {-# LANGUAGE FlexibleInstances #-} module DuckTest.Internal.State.Instance where import DuckTest.Checker import DuckTest.Internal.Common hiding (union) import DuckTest.Internal.State import DuckTest.Internal.Format import DuckTest.Monad import DuckTest.Infer.Functions import DuckTest.Infer.Expression import DuckTest.Infer.Classes import DuckTest.Types import DuckTest.AST.Util import DuckTest.Parse import DuckTest.Internal.State.Init handleImport :: InternalState SrcSpan -> (String, [String]) -> Maybe String -> SrcSpan -> DuckTest SrcSpan (InternalState SrcSpan) {-| Handle the observation of an import statement. This relies - on the DuckTest monad to pull in the correct module into its - state. We then check the module and lift it into its own object-} handleImport state (h, t) as pos = do modType <- makeImport pos (h:t) parsePython $ \stmts -> stateToType =<< runChecker initState stmts maybe' modType (Warn %%! duckf "Error with import " h >> return state) $ \a -> do Debug %%! duckf "Module " h " :: " a case as of Nothing -> return $ addVariableType h (liftFromDotList t a) state Just name -> return $ addVariableType name a state handleReturn :: InternalState e -> Maybe (Expr e) -> e -> DuckTest e (InternalState e) {-| Handle the observation of a return statement. THis will - tell the current state that a return was hit and the return - type was given. -} handleReturn state expr' pos | returnHit state = return state | otherwise = let expr = fromMaybe (None pos) expr' in flip setReturnType state <$> (runDeferred state =<< inferTypeForExpression state expr) handleFunction :: InternalState SrcSpan -> Statement SrcSpan -> DuckTest SrcSpan (InternalState SrcSpan) {-| Handles a function observation `def <function>(...): ...'. When - this happens, there are two phases; we attempt to infer the type of the - parameters via type-observation, then we infer via type matching the - return type of the function -} handleFunction st fun@Fun {fun_name = (Ident name _), fun_body=body} = addVariableTypeDeferred name (Deferred fn) st where fn state' = do let state = biasedUnion state' st Debug %%! duckf Yellow "Running deferred type of function" Reset functionType <- inferTypeForFunction state fun let newstate = addVariableType name functionType state case functionType of (Functional args _) -> do ret <- getReturnType <$> runChecker (addAll args newstate) body let newfntype = Functional args ret Info %%! duckf "\n(Inferred) " name " :: " newfntype "\n" return newfntype _ -> do Warn %% "This should not happen, infer type of function returned a type that isn't a function." return Void handleFunction state _ = return state handleForLoop :: InternalState SrcSpan -> [Expr SrcSpan] -> Expr SrcSpan -> [Statement SrcSpan] -> [Statement SrcSpan] -> SrcSpan -> DuckTest SrcSpan (InternalState SrcSpan) handleForLoop state targets generator body elsebody pos = do generatorVariableType <- inferTypeForExpression state -- <generator>.__iter__().__next__() (Call (Dot (Call (Dot generator (Ident "__iter__" pos) pos) [] pos) (Ident "__next__" pos) pos) [] pos) let newVariables = flip mapMaybe targets $ \target -> case target of (Var (Ident name _) _) -> Just (name, generatorVariableType) _ -> Nothing forLoopInitState <- addAllDeferred newVariables state afterForLoopState <- runChecker forLoopInitState body afterElseState <- runChecker state elsebody return $ intersectStates afterForLoopState afterElseState handleClass :: InternalState SrcSpan -> String -> [Statement SrcSpan] -> SrcSpan -> DuckTest SrcSpan (InternalState SrcSpan) {-| Handle observing a class.-} handleClass state name body pos = do {- This is done in several parts thanks to Python's annoying - semantics when it comes to dealing with classes. First stage, - we infer the *static* varibales of the class. Then we can - go through and check all the methods as if they are static methods. - - This will give us the static type of the class. That means - the structural type representing the class object itself. This - is contrasted with the instance type. - - We then build the instance type by observing all self assingments - in the __init__ function and the functions of the static - type less the self parameter. Finally, we ad a __call__ method - to the class with the same parameters as __init__ but returns - an instance type.... classes are a bitch to deal with.-} staticVarsState <- foldM' mempty body $ \curstate stmt -> case stmt of (Assign [Var (Ident vname _) _] ex _) -> do inferredType <- inferTypeForExpression curstate ex addVariableTypeDeferred vname inferredType curstate _ -> return curstate staticVarType <- union <$> stateToType staticVarsState <*> pure (Functional [] (mkAlpha Void)) Trace %%! duckf "StaticVarType for Class " name " = " staticVarType let newstate = addVariableType name staticVarType state Trace %%! duckf "New state = " (intercalate ", " (stateDir newstate)) staticClassState <- runChecker newstate $ mapMaybe (\stmt -> case stmt of Fun {} -> Just stmt _ -> Nothing) body staticClassType@Scalar {} <- (union <$> pure staticVarType <*> stateToType (differenceStates staticClassState newstate)) Trace %%! duckf "StatiClassType for Class " name " = " staticClassType let nextstate = addVariableType name staticClassType state Debug %%! duckf Blue name " Static Type Before Rewire = " Green staticClassType boundType <- rewireAlphas <$> toBoundType name staticClassType <$> findSelfAssignments staticClassType nextstate body let classFunctionalType = initType boundType let staticClassType' = rewireAlphas' boundType (staticClassType `union` classFunctionalType) let laststate = addVariableType name staticClassType' state Debug %%! duckf Blue name " Instance Type = " Green boundType Debug %%! duckf Blue name " Static Type = " Green staticClassType' matchBoundWithStatic pos boundType staticClassType' return laststate handleAssign :: InternalState a -> String -> Expr a -> a -> DuckTest a (InternalState a) {-| Handle an assignment. a = <expr>. This will extend the state - to include the variable a with the type inferred from expr. If - the type happens to be inferred to be a void type, then a warning - is emitted warning of the void type usage. -} handleAssign state vname ex pos = do inferredType <- runDeferred state =<< inferTypeForExpression state ex Debug %%! duckf vname " = " (prettyText ex) " :: " inferredType when (isVoid2 inferredType) $ warn pos $ duckf "Void type not ignored as it ought to be!" return $ addVariableType vname inferredType state handleConditional :: (InternalState SrcSpan) -> [(Expr SrcSpan, [Statement SrcSpan])] -> [Statement SrcSpan] -> DuckTest SrcSpan (InternalState SrcSpan) {-| Handle a conditional. This will run a checker on all the different branches and at the end, intersect all the states before continuing. This includes intersecting the types as well. -} handleConditional state guards elsebody = do endStates <- forM guards $ \(expr, stmts) -> do modifiedState <- case expr of (Call (Var (Ident "hasattr" _) _) [ArgExpr (Var (Ident x _) _) _, ArgExpr (Call (Var (Ident "str" _) _) [ArgExpr (Strings s _) _] _) _] _) -> let s' = takeWhile (/='"') (tail $ concat s) in return $ modifyVariableType x (`union` singleton s' Any) state (Call (Dot (Dot (Var (Ident var _) _) (Ident "__class__" _) _) (Ident "__eq__" _) _) [ArgExpr (Var (Ident clazz _) _) _] _) -> do vartyp <- evalVariableType state clazz let instanceType = instanceTypeFromStatic =<< vartyp maybe (return state) (\t -> return (modifyVariableType var (const t) state)) instanceType _ -> return state _ <- inferTypeForExpression state expr runChecker modifiedState stmts elseState <- runChecker state elsebody return $ foldl intersectStates elseState endStates handleAttributeAssign :: InternalState a -> Expr a -> String -> Expr a -> DuckTest a (InternalState a) handleAttributeAssign state lhs att rhs = do rhsType <- inferTypeForExpression state rhs _ <- inferTypeForExpression state lhs typeToAssign <- singleton att <$> (runDeferred state rhsType) return $ assignType lhs typeToAssign where assignType (Var (Ident var _) _) typ = modifyVariableType var (`union` typ) state assignType (Dot expr (Ident attr _) _) typ = assignType expr $ singleton attr typ assignType _ _ = state instance CheckerState (InternalState SrcSpan) where foldFunction currentState statement = do Trace %%! duckf Blue statement Green " - " (intercalate ", " (stateDir currentState)) Reset when (returnHit currentState) $ warn (annot statement) $ duckf "Dead code" case statement of (Import [ImportItem dotted@(_:_) as pos] _) -> let (h:t) = map (\(Ident name _) -> name) dotted in handleImport currentState (h, t) (getIdentifier =<< as) pos (Return expr pos) -> handleReturn currentState expr pos Fun {} -> handleFunction currentState statement (Class (Ident name _) [] body pos) -> handleClass currentState name body pos Assign [Var (Ident vname _) _] ex pos -> handleAssign currentState vname ex pos Assign [(Dot lhs (Ident att _) _)] rhs _ -> handleAttributeAssign currentState lhs att rhs Conditional {cond_guards=guards, cond_else=elsebody} -> handleConditional currentState guards elsebody (For targets generators body elsebody pos) -> handleForLoop currentState targets generators body elsebody pos _ -> do mapM_ (inferTypeForExpression currentState) (subExpressions statement) return currentState
jrahm/DuckTest
src/DuckTest/Internal/State/Instance.hs
bsd-2-clause
11,460
0
25
3,461
2,715
1,310
1,405
157
3
module Type where newtype TypeVariable = TV String deriving (Eq, Ord, Show) data Type = TypeVariable TypeVariable | TypeSymbol String | TypeArrow Type Type | TypeProduct Type Type | TypeSum Type Type deriving (Eq, Ord, Show) data Scheme = Forall [TypeVariable] Type deriving (Eq, Ord, Show) nil :: Type nil = TypeSymbol "nil" t :: Type t = TypeSymbol "t" i1 :: Type i1 = TypeSymbol "i1" i64 :: Type i64 = TypeSymbol "i64" lambda :: Type lambda = TypeSymbol "lambda" typeSymbols :: [Type] typeSymbols = [nil, t, i1, i64, lambda] nth :: Type -> Int -> Type nth ty idx = nth' ty 0 where nth' :: Type -> Int -> Type nth' (TypeArrow a b) pos = if pos == idx then a else nth' b (pos + 1) nth' (TypeProduct a b) pos = if pos == idx then a else nth' b (pos + 1) nth' (TypeSum a b) pos = if pos == idx then a else nth' b (pos + 1) nth' _ _ = ty
jjingram/satori
src/Type.hs
bsd-3-clause
1,005
0
10
341
378
206
172
46
7
module Handler.Admin where import Import import Control.Monad.Random import Settings.StaticFiles import Yesod.Form.Bootstrap3 (BootstrapFormLayout (..), renderBootstrap3, withSmallInput) import Yesod.Auth.HashDB (setPassword) postRemoveUserR :: Handler Html postRemoveUserR = do ((musr, remWid), remEnc) <- runFormPost . removeAccountForm =<< otherUsers case musr of FormSuccess usr -> do runDB $ deleteBy (UniqueUser $ userIdent usr) setInfo [shamlet|削除完了:#{userIdent usr} (#{userScreenName usr})|] redirect AdminR FormFailure err -> do setDanger [shamlet|削除できませんでした:#{concat err}|] redirect AdminR FormMissing -> do setDanger [shamlet|削除できませんでした|] redirect AdminR getAdminR :: Handler Html getAdminR = do (addWid, addEnc) <- generateFormPost newAccountForm (remWid, remEnc) <- generateRemoveForm defaultLayout $ do setTitle "Administration" $(widgetFile "admin") postAdminR :: Handler Html postAdminR = redirect AdminR otherUsers :: Handler [User] otherUsers = do Entity _ usr <- requireAuth runDB (map entityVal <$> selectList [UserIdent !=. userIdent usr] []) generateRemoveForm :: Handler (Widget, Enctype) generateRemoveForm = generateFormPost . removeAccountForm =<< otherUsers postUserR :: Handler Html postUserR = do ((musr, addWid), addEnc) <- runFormPost newAccountForm (remWid, remEnc) <- generateRemoveForm case musr of FormMissing -> setDanger "Some data missing" >> redirect AdminR FormFailure err -> setDanger [shamlet|入力が不正です: #{unlines err}|] >> redirect AdminR FormSuccess usr0 -> do let pwLetters = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] tmpPass <- pack <$> replicateM 10 (uniform pwLetters) usr <- setPassword tmpPass usr0 r <- runDB $ insertUnique usr case r of Nothing -> do setDanger "既に同名のユーザが存在しています" defaultLayout $ do setTitle "Administration" $(widgetFile "admin") Just _ -> do setInfo $ [shamlet|登録完了:#{userScreenName usr} (PASS: #{tmpPass})|] redirect AdminR removeAccountForm :: [User] -> Form User removeAccountForm usrs = renderBootstrap3 BootstrapBasicForm $ areq (selectFieldList [(userIdent usr <> " (" <> userScreenName usr <> ")", usr) | usr <- usrs]) "User to be removed" Nothing newAccountForm :: Form User newAccountForm = renderBootstrap3 BootstrapBasicForm $ User <$> areq textField "User ID" Nothing <*> areq textField "Screen Name" Nothing <*> pure Nothing <*> areq (selectFieldList [("Normal" :: Text, Normal), ("Admin", Admin)]) "Access" (Just Normal)
konn/leport
leport-web/Handler/Admin.hs
bsd-3-clause
2,787
0
22
581
782
393
389
-1
-1
{- - Types.hs - By Steven Smith -} module SpirV.Builder.Types where import Control.Applicative hiding (empty) import Control.Monad.Fix import Data.Sequence (Seq) import Data.Word import SpirV.Builder.Types.Internal import SpirV.Instructions (Id(..), Instruction) newtype Builder a = Builder { runBuilder :: Id -> Module -> (a, Id, Module) } instance Functor Builder where fmap f (Builder b) = Builder go where go i m = let (a, i', m') = b i m in (f a, i', m') instance Applicative Builder where pure a = Builder go where go i m = (a, i, m) Builder b1 <*> Builder b2 = Builder go where go i m = let (f, i', m') = b1 i m (a, i'', m'') = b2 i' m' in (f a, i'', m'') instance Monad Builder where return = pure Builder b1 >>= f = Builder go where go i m = let (a, i', m') = b1 i m (Builder b2) = f a in b2 i' m' instance MonadFix Builder where mfix f = Builder go where go i m = let tup@(a, _, _) = runBuilder (f a) i m in tup data SpirVModule = SpirVModule { spirVMagicNumber :: Word32, spirVVersionNumber :: Word32, genMagicNumber :: Word32, idBound :: Word32, instructionStream :: Seq Instruction } newtype TypeId = TypeId { runTypeId :: Id } newtype FileId = FileId { runFileId :: Id } newtype ExtSet = ExtSet { runExtSet :: Id } newtype DecorationGroup = DecorationGroup { runDecGroup :: Id } newtype LabelId = LabelId { runLabelId :: Id } newtype NDRangeId = NDRangeId { runNDRangeId :: Id } newtype ReserveId = ReserveId { runReserveId :: Id } class IsId a where toId :: a -> Id instance IsId Id where toId = id instance IsId TypeId where toId (TypeId i) = i instance IsId FileId where toId (FileId i) = i instance IsId DecorationGroup where toId (DecorationGroup i) = i instance IsId LabelId where toId (LabelId i) = i instance IsId NDRangeId where toId (NDRangeId i) = i instance IsId ReserveId where toId (ReserveId i) = i
stevely/hspirv
src/SpirV/Builder/Types.hs
bsd-3-clause
2,109
0
14
621
754
414
340
58
0
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Instrument.Types ( createInstrumentPool, Samplers, Counters, Instrument (..), InstrumentConfig (..), SubmissionPacket (..), MetricName (..), DimensionName (..), DimensionValue (..), Dimensions, Payload (..), Aggregated (..), AggPayload (..), Stats (..), hostDimension, HostDimensionPolicy (..), Quantile (..), ) where ------------------------------------------------------------------------------- import Control.Applicative as A import qualified Data.ByteString.Char8 as B import Data.Default import Data.IORef import qualified Data.Map as M import Data.Monoid as Monoid import qualified Data.SafeCopy as SC import Data.Serialize as Ser import Data.Serialize.Text () import Data.String import Data.Text (Text) import qualified Data.Text as T #if MIN_VERSION_hedis(0,12,0) import Database.Redis as R #else import Database.Redis as R hiding (HostName, time) #endif import GHC.Generics ------------------------------------------------------------------------------- import qualified Instrument.Counter as C import qualified Instrument.Sampler as S import Network.HostName ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- createInstrumentPool :: ConnectInfo -> IO Connection createInstrumentPool ci = do c <- connect ci { connectMaxIdleTime = 15, connectMaxConnections = 1 } return c -- Map of user-defined samplers. type Samplers = M.Map (MetricName, Dimensions) S.Sampler -- Map of user-defined counters. type Counters = M.Map (MetricName, Dimensions) C.Counter type Dimensions = M.Map DimensionName DimensionValue newtype MetricName = MetricName { metricName :: String } deriving (Eq, Show, Generic, Ord, IsString, Serialize) data Instrument = I { hostName :: HostName, samplers :: !(IORef Samplers), counters :: !(IORef Counters), redis :: Connection } data InstrumentConfig = ICfg { redisQueueBound :: Maybe Integer } instance Default InstrumentConfig where def = ICfg Nothing -- | Submitted package of collected samples data SubmissionPacket_v0 = SP_v0 { -- | Timing of this submission spTimeStamp_v0 :: !Double, -- | Who sent it spHostName_v0 :: !HostName, -- | Metric name spName_v0 :: String, -- | Collected values spPayload_v0 :: Payload } deriving (Eq, Show, Generic) instance Serialize SubmissionPacket_v0 data SubmissionPacket = SP { -- | Timing of this submission spTimeStamp :: !Double, -- | Metric name spName :: !MetricName, -- | Collected values spPayload :: !Payload, -- | Defines slices that this packet belongs to. This allows -- drill-down on the backends. For instance, you could do -- "server_name" "app1" or "queue_name" "my_queue" spDimensions :: !Dimensions } deriving (Eq, Show, Generic) instance Serialize SubmissionPacket where get = (to <$> gGet) <|> (upgradeSP0 <$> Ser.get) instance SC.Migrate SubmissionPacket where type MigrateFrom SubmissionPacket = SubmissionPacket_v0 migrate = upgradeSP0 upgradeSP0 :: SubmissionPacket_v0 -> SubmissionPacket upgradeSP0 SP_v0 {..} = SP { spTimeStamp = spTimeStamp_v0, spName = MetricName spName_v0, spPayload = spPayload_v0, spDimensions = M.singleton hostDimension (DimensionValue (T.pack spHostName_v0)) } ------------------------------------------------------------------------------- -- | Convention for the dimension of the hostname. Used in the client -- to inject hostname into the parameters map hostDimension :: DimensionName hostDimension = "host" ------------------------------------------------------------------------------- -- | Should we automatically pull the host and add it as a -- dimension. Used at the call site of the various metrics ('timeI', -- 'sampleI', etc). Hosts are basically grandfathered in as a -- dimension and the functionality of automatically injecting them is -- useful, but it is not relevant to some metrics and actually makes -- some metrics difficult to use depending on the backend, so we made -- them opt-in. data HostDimensionPolicy = AddHostDimension | DoNotAddHostDimension deriving (Show, Eq) ------------------------------------------------------------------------------- newtype DimensionName = DimensionName { dimensionName :: Text } deriving (Eq, Ord, Show, Generic, Serialize, IsString) ------------------------------------------------------------------------------- newtype DimensionValue = DimensionValue { dimensionValue :: Text } deriving (Eq, Ord, Show, Generic, Serialize, IsString) ------------------------------------------------------------------------------- data Payload = Samples {unSamples :: [Double]} | Counter {unCounter :: Int} deriving (Eq, Show, Generic) instance Serialize Payload ------------------------------------------------------------------------------- data Aggregated_v0 = Aggregated_v0 { -- | Timestamp for this aggregation aggTS_v0 :: Double, -- | Name of the metric aggName_v0 :: String, -- | The aggregation level/group for this stat aggGroup_v0 :: B.ByteString, -- | Calculated stats for the metric aggPayload_v0 :: AggPayload } deriving (Eq, Show, Generic) instance Serialize Aggregated_v0 data Aggregated_v1 = Aggregated_v1 { -- | Timestamp for this aggregation aggTS_v1 :: Double, -- | Name of the metric aggName_v1 :: MetricName, -- | The aggregation level/group for this stat aggGroup_v1 :: B.ByteString, -- | Calculated stats for the metric aggPayload_v1 :: AggPayload } deriving (Eq, Show, Generic) instance SC.Migrate Aggregated_v1 where type MigrateFrom Aggregated_v1 = Aggregated_v0 migrate = upgradeAggregated_v0 upgradeAggregated_v0 :: Aggregated_v0 -> Aggregated_v1 upgradeAggregated_v0 a = Aggregated_v1 { aggTS_v1 = aggTS_v0 a, aggName_v1 = MetricName (aggName_v0 a), aggGroup_v1 = (aggGroup_v0 a), aggPayload_v1 = (aggPayload_v0 a) } instance Serialize Aggregated_v1 where get = (to <$> gGet) <|> (upgradeAggregated_v0 <$> Ser.get) data Aggregated = Aggregated { -- | Timestamp for this aggregation aggTS :: Double, -- | Name of the metric aggName :: MetricName, -- | Calculated stats for the metric aggPayload :: AggPayload, aggDimensions :: Dimensions } deriving (Eq, Show, Generic) upgradeAggregated_v1 :: Aggregated_v1 -> Aggregated upgradeAggregated_v1 a = Aggregated { aggTS = aggTS_v1 a, aggName = aggName_v1 a, aggPayload = aggPayload_v1 a, aggDimensions = Monoid.mempty } instance SC.Migrate Aggregated where type MigrateFrom Aggregated = Aggregated_v1 migrate = upgradeAggregated_v1 instance Serialize Aggregated where get = (to <$> gGet) <|> (upgradeAggregated_v1 <$> Ser.get) -- | Resulting payload for metrics aggregation data AggPayload = AggStats Stats | AggCount Int deriving (Eq, Show, Generic) instance Serialize AggPayload instance Default AggPayload where def = AggStats def instance Default Aggregated where def = Aggregated 0 "" def mempty ------------------------------------------------------------------------------- data Stats = Stats { smean :: Double, ssum :: Double, scount :: Int, smax :: Double, smin :: Double, srange :: Double, sstdev :: Double, sskewness :: Double, skurtosis :: Double, squantiles :: M.Map Int Double } deriving (Eq, Show, Generic) instance Default Stats where def = Stats 0 0 0 0 0 0 0 0 0 mempty instance Serialize Stats ------------------------------------------------------------------------------- -- | Integer quantile, valid values range from 1-99, inclusive. newtype Quantile = Q {quantile :: Int} deriving (Show, Eq, Ord) instance Bounded Quantile where minBound = Q 1 maxBound = Q 99 ------------------------------------------------------------------------------- $(SC.deriveSafeCopy 0 'SC.base ''Payload) $(SC.deriveSafeCopy 0 'SC.base ''SubmissionPacket_v0) $(SC.deriveSafeCopy 1 'SC.extension ''SubmissionPacket) $(SC.deriveSafeCopy 0 'SC.base ''AggPayload) $(SC.deriveSafeCopy 0 'SC.base ''Aggregated_v0) $(SC.deriveSafeCopy 1 'SC.extension ''Aggregated_v1) $(SC.deriveSafeCopy 2 'SC.extension ''Aggregated) $(SC.deriveSafeCopy 0 'SC.base ''Stats) $(SC.deriveSafeCopy 0 'SC.base ''DimensionName) $(SC.deriveSafeCopy 0 'SC.base ''DimensionValue) $(SC.deriveSafeCopy 0 'SC.base ''MetricName)
Soostone/instrument
instrument/src/Instrument/Types.hs
bsd-3-clause
8,846
0
12
1,585
1,793
1,041
752
205
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Pattern-matching bindings (HsBinds and MonoBinds) Handles @HsBinds@; those at the top level require different handling, in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at lower levels it is preserved with @let@/@letrec@s). -} {-# LANGUAGE CPP #-} module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, dsSpec, dsHsWrapper, dsTcEvBinds, dsTcEvBinds_s, dsEvBinds ) where #include "HsVersions.h" import {-# SOURCE #-} DsExpr( dsLExpr ) import {-# SOURCE #-} Match( matchWrapper ) import DsMonad import DsGRHSs import DsUtils import HsSyn -- lots of things import CoreSyn -- lots of things import Literal ( Literal(MachStr) ) import CoreSubst import OccurAnal ( occurAnalyseExpr ) import MkCore import CoreUtils import CoreArity ( etaExpand ) import CoreUnfold import CoreFVs import UniqSupply import Digraph import PrelNames import TysPrim ( mkProxyPrimTy ) import TyCon import TcEvidence import TcType import Type import Kind (returnsConstraintKind) import Coercion hiding (substCo) import TysWiredIn ( eqBoxDataCon, coercibleDataCon, mkListTy , mkBoxedTupleTy, stringTy, typeNatKind, typeSymbolKind ) import Id import MkId(proxyHashId) import Class import DataCon ( dataConTyCon ) import Name import IdInfo ( IdDetails(..) ) import Var import VarSet import Rules import VarEnv import Outputable import Module import SrcLoc import Maybes import OrdList import Bag import BasicTypes hiding ( TopLevel ) import DynFlags import FastString import ErrUtils( MsgDoc ) import Util import Control.Monad( when ) import MonadUtils import Control.Monad(liftM) import Fingerprint(Fingerprint(..), fingerprintString) {- ************************************************************************ * * \subsection[dsMonoBinds]{Desugaring a @MonoBinds@} * * ************************************************************************ -} dsTopLHsBinds :: LHsBinds Id -> DsM (OrdList (Id,CoreExpr)) dsTopLHsBinds binds = ds_lhs_binds binds dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)] dsLHsBinds binds = do { binds' <- ds_lhs_binds binds ; return (fromOL binds') } ------------------------ ds_lhs_binds :: LHsBinds Id -> DsM (OrdList (Id,CoreExpr)) ds_lhs_binds binds = do { ds_bs <- mapBagM dsLHsBind binds ; return (foldBag appOL id nilOL ds_bs) } dsLHsBind :: LHsBind Id -> DsM (OrdList (Id,CoreExpr)) dsLHsBind (L loc bind) = putSrcSpanDs loc $ dsHsBind bind dsHsBind :: HsBind Id -> DsM (OrdList (Id,CoreExpr)) dsHsBind (VarBind { var_id = var, var_rhs = expr, var_inline = inline_regardless }) = do { dflags <- getDynFlags ; core_expr <- dsLExpr expr -- Dictionary bindings are always VarBinds, -- so we only need do this here ; let var' | inline_regardless = var `setIdUnfolding` mkCompulsoryUnfolding core_expr | otherwise = var ; return (unitOL (makeCorePair dflags var' False 0 core_expr)) } dsHsBind (FunBind { fun_id = L _ fun, fun_matches = matches , fun_co_fn = co_fn, fun_tick = tick , fun_infix = inf }) = do { dflags <- getDynFlags ; (args, body) <- matchWrapper (FunRhs (idName fun) inf) matches ; let body' = mkOptTickBox tick body ; rhs <- dsHsWrapper co_fn (mkLams args body') ; {- pprTrace "dsHsBind" (ppr fun <+> ppr (idInlinePragma fun)) $ -} return (unitOL (makeCorePair dflags fun False 0 rhs)) } dsHsBind (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty , pat_ticks = (rhs_tick, var_ticks) }) = do { body_expr <- dsGuarded grhss ty ; let body' = mkOptTickBox rhs_tick body_expr ; sel_binds <- mkSelectorBinds var_ticks pat body' -- We silently ignore inline pragmas; no makeCorePair -- Not so cool, but really doesn't matter ; return (toOL sel_binds) } -- A common case: one exported variable -- Non-recursive bindings come through this way -- So do self-recursive bindings, and recursive bindings -- that have been chopped up with type signatures dsHsBind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts , abs_exports = [export] , abs_ev_binds = ev_binds, abs_binds = binds }) | ABE { abe_wrap = wrap, abe_poly = global , abe_mono = local, abe_prags = prags } <- export = do { dflags <- getDynFlags ; bind_prs <- ds_lhs_binds binds ; let core_bind = Rec (fromOL bind_prs) ; ds_binds <- dsTcEvBinds_s ev_binds ; rhs <- dsHsWrapper wrap $ -- Usually the identity mkLams tyvars $ mkLams dicts $ mkCoreLets ds_binds $ Let core_bind $ Var local ; (spec_binds, rules) <- dsSpecs rhs prags ; let global' = addIdSpecialisations global rules main_bind = makeCorePair dflags global' (isDefaultMethod prags) (dictArity dicts) rhs ; return (main_bind `consOL` spec_binds) } dsHsBind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts , abs_exports = exports, abs_ev_binds = ev_binds , abs_binds = binds }) -- See Note [Desugaring AbsBinds] = do { dflags <- getDynFlags ; bind_prs <- ds_lhs_binds binds ; let core_bind = Rec [ makeCorePair dflags (add_inline lcl_id) False 0 rhs | (lcl_id, rhs) <- fromOL bind_prs ] -- Monomorphic recursion possible, hence Rec locals = map abe_mono exports tup_expr = mkBigCoreVarTup locals tup_ty = exprType tup_expr ; ds_binds <- dsTcEvBinds_s ev_binds ; let poly_tup_rhs = mkLams tyvars $ mkLams dicts $ mkCoreLets ds_binds $ Let core_bind $ tup_expr ; poly_tup_id <- newSysLocalDs (exprType poly_tup_rhs) ; let mk_bind (ABE { abe_wrap = wrap, abe_poly = global , abe_mono = local, abe_prags = spec_prags }) = do { tup_id <- newSysLocalDs tup_ty ; rhs <- dsHsWrapper wrap $ mkLams tyvars $ mkLams dicts $ mkTupleSelector locals local tup_id $ mkVarApps (Var poly_tup_id) (tyvars ++ dicts) ; let rhs_for_spec = Let (NonRec poly_tup_id poly_tup_rhs) rhs ; (spec_binds, rules) <- dsSpecs rhs_for_spec spec_prags ; let global' = (global `setInlinePragma` defaultInlinePragma) `addIdSpecialisations` rules -- Kill the INLINE pragma because it applies to -- the user written (local) function. The global -- Id is just the selector. Hmm. ; return ((global', rhs) `consOL` spec_binds) } ; export_binds_s <- mapM mk_bind exports ; return ((poly_tup_id, poly_tup_rhs) `consOL` concatOL export_binds_s) } where inline_env :: IdEnv Id -- Maps a monomorphic local Id to one with -- the inline pragma from the source -- The type checker put the inline pragma -- on the *global* Id, so we need to transfer it inline_env = mkVarEnv [ (lcl_id, setInlinePragma lcl_id prag) | ABE { abe_mono = lcl_id, abe_poly = gbl_id } <- exports , let prag = idInlinePragma gbl_id ] add_inline :: Id -> Id -- tran add_inline lcl_id = lookupVarEnv inline_env lcl_id `orElse` lcl_id dsHsBind (PatSynBind{}) = panic "dsHsBind: PatSynBind" ------------------------ makeCorePair :: DynFlags -> Id -> Bool -> Arity -> CoreExpr -> (Id, CoreExpr) makeCorePair dflags gbl_id is_default_method dict_arity rhs | is_default_method -- Default methods are *always* inlined = (gbl_id `setIdUnfolding` mkCompulsoryUnfolding rhs, rhs) | DFunId is_newtype <- idDetails gbl_id = (mk_dfun_w_stuff is_newtype, rhs) | otherwise = case inlinePragmaSpec inline_prag of EmptyInlineSpec -> (gbl_id, rhs) NoInline -> (gbl_id, rhs) Inlinable -> (gbl_id `setIdUnfolding` inlinable_unf, rhs) Inline -> inline_pair where inline_prag = idInlinePragma gbl_id inlinable_unf = mkInlinableUnfolding dflags rhs inline_pair | Just arity <- inlinePragmaSat inline_prag -- Add an Unfolding for an INLINE (but not for NOINLINE) -- And eta-expand the RHS; see Note [Eta-expanding INLINE things] , let real_arity = dict_arity + arity -- NB: The arity in the InlineRule takes account of the dictionaries = ( gbl_id `setIdUnfolding` mkInlineUnfolding (Just real_arity) rhs , etaExpand real_arity rhs) | otherwise = pprTrace "makeCorePair: arity missing" (ppr gbl_id) $ (gbl_id `setIdUnfolding` mkInlineUnfolding Nothing rhs, rhs) -- See Note [ClassOp/DFun selection] in TcInstDcls -- See Note [Single-method classes] in TcInstDcls mk_dfun_w_stuff is_newtype | is_newtype = gbl_id `setIdUnfolding` mkInlineUnfolding (Just 0) rhs `setInlinePragma` alwaysInlinePragma { inl_sat = Just 0 } | otherwise = gbl_id `setIdUnfolding` mkDFunUnfolding dfun_bndrs dfun_constr dfun_args `setInlinePragma` dfunInlinePragma (dfun_bndrs, dfun_body) = collectBinders (simpleOptExpr rhs) (dfun_con, dfun_args) = collectArgs dfun_body dfun_constr | Var id <- dfun_con , DataConWorkId con <- idDetails id = con | otherwise = pprPanic "makeCorePair: dfun" (ppr rhs) dictArity :: [Var] -> Arity -- Don't count coercion variables in arity dictArity dicts = count isId dicts {- [Desugaring AbsBinds] ~~~~~~~~~~~~~~~~~~~~~ In the general AbsBinds case we desugar the binding to this: tup a (d:Num a) = let fm = ...gm... gm = ...fm... in (fm,gm) f a d = case tup a d of { (fm,gm) -> fm } g a d = case tup a d of { (fm,gm) -> fm } Note [Rules and inlining] ~~~~~~~~~~~~~~~~~~~~~~~~~ Common special case: no type or dictionary abstraction This is a bit less trivial than you might suppose The naive way woudl be to desguar to something like f_lcl = ...f_lcl... -- The "binds" from AbsBinds M.f = f_lcl -- Generated from "exports" But we don't want that, because if M.f isn't exported, it'll be inlined unconditionally at every call site (its rhs is trivial). That would be ok unless it has RULES, which would thereby be completely lost. Bad, bad, bad. Instead we want to generate M.f = ...f_lcl... f_lcl = M.f Now all is cool. The RULES are attached to M.f (by SimplCore), and f_lcl is rapidly inlined away. This does not happen in the same way to polymorphic binds, because they desugar to M.f = /\a. let f_lcl = ...f_lcl... in f_lcl Although I'm a bit worried about whether full laziness might float the f_lcl binding out and then inline M.f at its call site Note [Specialising in no-dict case] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Even if there are no tyvars or dicts, we may have specialisation pragmas. Class methods can generate AbsBinds [] [] [( ... spec-prag] { AbsBinds [tvs] [dicts] ...blah } So the overloading is in the nested AbsBinds. A good example is in GHC.Float: class (Real a, Fractional a) => RealFrac a where round :: (Integral b) => a -> b instance RealFrac Float where {-# SPECIALIZE round :: Float -> Int #-} The top-level AbsBinds for $cround has no tyvars or dicts (because the instance does not). But the method is locally overloaded! Note [Abstracting over tyvars only] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When abstracting over type variable only (not dictionaries), we don't really need to built a tuple and select from it, as we do in the general case. Instead we can take AbsBinds [a,b] [ ([a,b], fg, fl, _), ([b], gg, gl, _) ] { fl = e1 gl = e2 h = e3 } and desugar it to fg = /\ab. let B in e1 gg = /\b. let a = () in let B in S(e2) h = /\ab. let B in e3 where B is the *non-recursive* binding fl = fg a b gl = gg b h = h a b -- See (b); note shadowing! Notice (a) g has a different number of type variables to f, so we must use the mkArbitraryType thing to fill in the gaps. We use a type-let to do that. (b) The local variable h isn't in the exports, and rather than clone a fresh copy we simply replace h by (h a b), where the two h's have different types! Shadowing happens here, which looks confusing but works fine. (c) The result is *still* quadratic-sized if there are a lot of small bindings. So if there are more than some small number (10), we filter the binding set B by the free variables of the particular RHS. Tiresome. Why got to this trouble? It's a common case, and it removes the quadratic-sized tuple desugaring. Less clutter, hopefully faster compilation, especially in a case where there are a *lot* of bindings. Note [Eta-expanding INLINE things] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider foo :: Eq a => a -> a {-# INLINE foo #-} foo x = ... If (foo d) ever gets floated out as a common sub-expression (which can happen as a result of method sharing), there's a danger that we never get to do the inlining, which is a Terribly Bad thing given that the user said "inline"! To avoid this we pre-emptively eta-expand the definition, so that foo has the arity with which it is declared in the source code. In this example it has arity 2 (one for the Eq and one for x). Doing this should mean that (foo d) is a PAP and we don't share it. Note [Nested arities] ~~~~~~~~~~~~~~~~~~~~~ For reasons that are not entirely clear, method bindings come out looking like this: AbsBinds [] [] [$cfromT <= [] fromT] $cfromT [InlPrag=INLINE] :: T Bool -> Bool { AbsBinds [] [] [fromT <= [] fromT_1] fromT :: T Bool -> Bool { fromT_1 ((TBool b)) = not b } } } Note the nested AbsBind. The arity for the InlineRule on $cfromT should be gotten from the binding for fromT_1. It might be better to have just one level of AbsBinds, but that requires more thought! -} ------------------------ dsSpecs :: CoreExpr -- Its rhs -> TcSpecPrags -> DsM ( OrdList (Id,CoreExpr) -- Binding for specialised Ids , [CoreRule] ) -- Rules for the Global Ids -- See Note [Handling SPECIALISE pragmas] in TcBinds dsSpecs _ IsDefaultMethod = return (nilOL, []) dsSpecs poly_rhs (SpecPrags sps) = do { pairs <- mapMaybeM (dsSpec (Just poly_rhs)) sps ; let (spec_binds_s, rules) = unzip pairs ; return (concatOL spec_binds_s, rules) } dsSpec :: Maybe CoreExpr -- Just rhs => RULE is for a local binding -- Nothing => RULE is for an imported Id -- rhs is in the Id's unfolding -> Located TcSpecPrag -> DsM (Maybe (OrdList (Id,CoreExpr), CoreRule)) dsSpec mb_poly_rhs (L loc (SpecPrag poly_id spec_co spec_inl)) | isJust (isClassOpId_maybe poly_id) = putSrcSpanDs loc $ do { warnDs (ptext (sLit "Ignoring useless SPECIALISE pragma for class method selector") <+> quotes (ppr poly_id)) ; return Nothing } -- There is no point in trying to specialise a class op -- Moreover, classops don't (currently) have an inl_sat arity set -- (it would be Just 0) and that in turn makes makeCorePair bleat | no_act_spec && isNeverActive rule_act = putSrcSpanDs loc $ do { warnDs (ptext (sLit "Ignoring useless SPECIALISE pragma for NOINLINE function:") <+> quotes (ppr poly_id)) ; return Nothing } -- Function is NOINLINE, and the specialiation inherits that -- See Note [Activation pragmas for SPECIALISE] | otherwise = putSrcSpanDs loc $ do { uniq <- newUnique ; let poly_name = idName poly_id spec_occ = mkSpecOcc (getOccName poly_name) spec_name = mkInternalName uniq spec_occ (getSrcSpan poly_name) ; (bndrs, ds_lhs) <- liftM collectBinders (dsHsWrapper spec_co (Var poly_id)) ; let spec_ty = mkPiTypes bndrs (exprType ds_lhs) ; -- pprTrace "dsRule" (vcat [ ptext (sLit "Id:") <+> ppr poly_id -- , ptext (sLit "spec_co:") <+> ppr spec_co -- , ptext (sLit "ds_rhs:") <+> ppr ds_lhs ]) $ case decomposeRuleLhs bndrs ds_lhs of { Left msg -> do { warnDs msg; return Nothing } ; Right (rule_bndrs, _fn, args) -> do { dflags <- getDynFlags ; this_mod <- getModule ; let fn_unf = realIdUnfolding poly_id unf_fvs = stableUnfoldingVars fn_unf `orElse` emptyVarSet in_scope = mkInScopeSet (unf_fvs `unionVarSet` exprsFreeVars args) spec_unf = specUnfolding dflags (mkEmptySubst in_scope) bndrs args fn_unf spec_id = mkLocalId spec_name spec_ty `setInlinePragma` inl_prag `setIdUnfolding` spec_unf rule = mkRule this_mod False {- Not auto -} is_local_id (mkFastString ("SPEC " ++ showPpr dflags poly_name)) rule_act poly_name rule_bndrs args (mkVarApps (Var spec_id) bndrs) ; spec_rhs <- dsHsWrapper spec_co poly_rhs ; when (isInlinePragma id_inl && wopt Opt_WarnPointlessPragmas dflags) (warnDs (specOnInline poly_name)) ; return (Just (unitOL (spec_id, spec_rhs), rule)) -- NB: do *not* use makeCorePair on (spec_id,spec_rhs), because -- makeCorePair overwrites the unfolding, which we have -- just created using specUnfolding } } } where is_local_id = isJust mb_poly_rhs poly_rhs | Just rhs <- mb_poly_rhs = rhs -- Local Id; this is its rhs | Just unfolding <- maybeUnfoldingTemplate (realIdUnfolding poly_id) = unfolding -- Imported Id; this is its unfolding -- Use realIdUnfolding so we get the unfolding -- even when it is a loop breaker. -- We want to specialise recursive functions! | otherwise = pprPanic "dsImpSpecs" (ppr poly_id) -- The type checker has checked that it *has* an unfolding id_inl = idInlinePragma poly_id -- See Note [Activation pragmas for SPECIALISE] inl_prag | not (isDefaultInlinePragma spec_inl) = spec_inl | not is_local_id -- See Note [Specialising imported functions] -- in OccurAnal , isStrongLoopBreaker (idOccInfo poly_id) = neverInlinePragma | otherwise = id_inl -- Get the INLINE pragma from SPECIALISE declaration, or, -- failing that, from the original Id spec_prag_act = inlinePragmaActivation spec_inl -- See Note [Activation pragmas for SPECIALISE] -- no_act_spec is True if the user didn't write an explicit -- phase specification in the SPECIALISE pragma no_act_spec = case inlinePragmaSpec spec_inl of NoInline -> isNeverActive spec_prag_act _ -> isAlwaysActive spec_prag_act rule_act | no_act_spec = inlinePragmaActivation id_inl -- Inherit | otherwise = spec_prag_act -- Specified by user specOnInline :: Name -> MsgDoc specOnInline f = ptext (sLit "SPECIALISE pragma on INLINE function probably won't fire:") <+> quotes (ppr f) {- Note [Activation pragmas for SPECIALISE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From a user SPECIALISE pragma for f, we generate a) A top-level binding spec_fn = rhs b) A RULE f dOrd = spec_fn We need two pragma-like things: * spec_fn's inline pragma: inherited from f's inline pragma (ignoring activation on SPEC), unless overriden by SPEC INLINE * Activation of RULE: from SPECIALISE pragma (if activation given) otherwise from f's inline pragma This is not obvious (see Trac #5237)! Examples Rule activation Inline prag on spec'd fn --------------------------------------------------------------------- SPEC [n] f :: ty [n] Always, or NOINLINE [n] copy f's prag NOINLINE f SPEC [n] f :: ty [n] NOINLINE copy f's prag NOINLINE [k] f SPEC [n] f :: ty [n] NOINLINE [k] copy f's prag INLINE [k] f SPEC [n] f :: ty [n] INLINE [k] copy f's prag SPEC INLINE [n] f :: ty [n] INLINE [n] (ignore INLINE prag on f, same activation for rule and spec'd fn) NOINLINE [k] f SPEC f :: ty [n] INLINE [k] ************************************************************************ * * \subsection{Adding inline pragmas} * * ************************************************************************ -} decomposeRuleLhs :: [Var] -> CoreExpr -> Either SDoc ([Var], Id, [CoreExpr]) -- (decomposeRuleLhs bndrs lhs) takes apart the LHS of a RULE, -- The 'bndrs' are the quantified binders of the rules, but decomposeRuleLhs -- may add some extra dictionary binders (see Note [Free dictionaries]) -- -- Returns Nothing if the LHS isn't of the expected shape -- Note [Decomposing the left-hand side of a RULE] decomposeRuleLhs orig_bndrs orig_lhs | not (null unbound) -- Check for things unbound on LHS -- See Note [Unused spec binders] = Left (vcat (map dead_msg unbound)) | Just (fn_id, args) <- decompose fun2 args2 , let extra_dict_bndrs = mk_extra_dict_bndrs fn_id args = -- pprTrace "decmposeRuleLhs" (vcat [ ptext (sLit "orig_bndrs:") <+> ppr orig_bndrs -- , ptext (sLit "orig_lhs:") <+> ppr orig_lhs -- , ptext (sLit "lhs1:") <+> ppr lhs1 -- , ptext (sLit "extra_dict_bndrs:") <+> ppr extra_dict_bndrs -- , ptext (sLit "fn_id:") <+> ppr fn_id -- , ptext (sLit "args:") <+> ppr args]) $ Right (orig_bndrs ++ extra_dict_bndrs, fn_id, args) | otherwise = Left bad_shape_msg where lhs1 = drop_dicts orig_lhs lhs2 = simpleOptExpr lhs1 -- See Note [Simplify rule LHS] (fun2,args2) = collectArgs lhs2 lhs_fvs = exprFreeVars lhs2 unbound = filterOut (`elemVarSet` lhs_fvs) orig_bndrs orig_bndr_set = mkVarSet orig_bndrs -- Add extra dict binders: Note [Free dictionaries] mk_extra_dict_bndrs fn_id args = [ mkLocalId (localiseName (idName d)) (idType d) | d <- varSetElems (exprsFreeVars args `delVarSetList` (fn_id : orig_bndrs)) -- fn_id: do not quantify over the function itself, which may -- itself be a dictionary (in pathological cases, Trac #10251) , isDictId d ] decompose (Var fn_id) args | not (fn_id `elemVarSet` orig_bndr_set) = Just (fn_id, args) decompose _ _ = Nothing bad_shape_msg = hang (ptext (sLit "RULE left-hand side too complicated to desugar")) 2 (vcat [ text "Optimised lhs:" <+> ppr lhs2 , text "Orig lhs:" <+> ppr orig_lhs]) dead_msg bndr = hang (sep [ ptext (sLit "Forall'd") <+> pp_bndr bndr , ptext (sLit "is not bound in RULE lhs")]) 2 (vcat [ text "Orig bndrs:" <+> ppr orig_bndrs , text "Orig lhs:" <+> ppr orig_lhs , text "optimised lhs:" <+> ppr lhs2 ]) pp_bndr bndr | isTyVar bndr = ptext (sLit "type variable") <+> quotes (ppr bndr) | Just pred <- evVarPred_maybe bndr = ptext (sLit "constraint") <+> quotes (ppr pred) | otherwise = ptext (sLit "variable") <+> quotes (ppr bndr) drop_dicts :: CoreExpr -> CoreExpr drop_dicts e = wrap_lets needed bnds body where needed = orig_bndr_set `minusVarSet` exprFreeVars body (bnds, body) = split_lets (occurAnalyseExpr e) -- The occurAnalyseExpr drops dead bindings which is -- crucial to ensure that every binding is used later; -- which in turn makes wrap_lets work right split_lets :: CoreExpr -> ([(DictId,CoreExpr)], CoreExpr) split_lets e | Let (NonRec d r) body <- e , isDictId d , (bs, body') <- split_lets body = ((d,r):bs, body') | otherwise = ([], e) wrap_lets :: VarSet -> [(DictId,CoreExpr)] -> CoreExpr -> CoreExpr wrap_lets _ [] body = body wrap_lets needed ((d, r) : bs) body | rhs_fvs `intersectsVarSet` needed = Let (NonRec d r) (wrap_lets needed' bs body) | otherwise = wrap_lets needed bs body where rhs_fvs = exprFreeVars r needed' = (needed `minusVarSet` rhs_fvs) `extendVarSet` d {- Note [Decomposing the left-hand side of a RULE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are several things going on here. * drop_dicts: see Note [Drop dictionary bindings on rule LHS] * simpleOptExpr: see Note [Simplify rule LHS] * extra_dict_bndrs: see Note [Free dictionaries] Note [Drop dictionary bindings on rule LHS] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ drop_dicts drops dictionary bindings on the LHS where possible. E.g. let d:Eq [Int] = $fEqList $fEqInt in f d --> f d Reasoning here is that there is only one d:Eq [Int], and so we can quantify over it. That makes 'd' free in the LHS, but that is later picked up by extra_dict_bndrs (Note [Dead spec binders]). NB 1: We can only drop the binding if the RHS doesn't bind one of the orig_bndrs, which we assume occur on RHS. Example f :: (Eq a) => b -> a -> a {-# SPECIALISE f :: Eq a => b -> [a] -> [a] #-} Here we want to end up with RULE forall d:Eq a. f ($dfEqList d) = f_spec d Of course, the ($dfEqlist d) in the pattern makes it less likely to match, but there is no other way to get d:Eq a NB 2: We do drop_dicts *before* simplOptEpxr, so that we expect all the evidence bindings to be wrapped around the outside of the LHS. (After simplOptExpr they'll usually have been inlined.) dsHsWrapper does dependency analysis, so that civilised ones will be simple NonRec bindings. We don't handle recursive dictionaries! NB3: In the common case of a non-overloaded, but perhaps-polymorphic specialisation, we don't need to bind *any* dictionaries for use in the RHS. For example (Trac #8331) {-# SPECIALIZE INLINE useAbstractMonad :: ReaderST s Int #-} useAbstractMonad :: MonadAbstractIOST m => m Int Here, deriving (MonadAbstractIOST (ReaderST s)) is a lot of code but the RHS uses no dictionaries, so we want to end up with RULE forall s (d :: MonadAbstractIOST (ReaderT s)). useAbstractMonad (ReaderT s) d = $suseAbstractMonad s Trac #8848 is a good example of where there are some intersting dictionary bindings to discard. The drop_dicts algorithm is based on these observations: * Given (let d = rhs in e) where d is a DictId, matching 'e' will bind e's free variables. * So we want to keep the binding if one of the needed variables (for which we need a binding) is in fv(rhs) but not already in fv(e). * The "needed variables" are simply the orig_bndrs. Consider f :: (Eq a, Show b) => a -> b -> String ... SPECIALISE f :: (Show b) => Int -> b -> String ... Then orig_bndrs includes the *quantified* dictionaries of the type namely (dsb::Show b), but not the one for Eq Int So we work inside out, applying the above criterion at each step. Note [Simplify rule LHS] ~~~~~~~~~~~~~~~~~~~~~~~~ simplOptExpr occurrence-analyses and simplifies the LHS: (a) Inline any remaining dictionary bindings (which hopefully occur just once) (b) Substitute trivial lets so that they don't get in the way Note that we substitute the function too; we might have this as a LHS: let f71 = M.f Int in f71 (c) Do eta reduction. To see why, consider the fold/build rule, which without simplification looked like: fold k z (build (/\a. g a)) ==> ... This doesn't match unless you do eta reduction on the build argument. Similarly for a LHS like augment g (build h) we do not want to get augment (\a. g a) (build h) otherwise we don't match when given an argument like augment (\a. h a a) (build h) Note [Matching seqId] ~~~~~~~~~~~~~~~~~~~ The desugarer turns (seq e r) into (case e of _ -> r), via a special-case hack and this code turns it back into an application of seq! See Note [Rules for seq] in MkId for the details. Note [Unused spec binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: a -> a ... SPECIALISE f :: Eq a => a -> a ... It's true that this *is* a more specialised type, but the rule we get is something like this: f_spec d = f RULE: f = f_spec d Note that the rule is bogus, because it mentions a 'd' that is not bound on the LHS! But it's a silly specialisation anyway, because the constraint is unused. We could bind 'd' to (error "unused") but it seems better to reject the program because it's almost certainly a mistake. That's what the isDeadBinder call detects. Note [Free dictionaries] ~~~~~~~~~~~~~~~~~~~~~~~~ When the LHS of a specialisation rule, (/\as\ds. f es) has a free dict, which is presumably in scope at the function definition site, we can quantify over it too. *Any* dict with that type will do. So for example when you have f :: Eq a => a -> a f = <rhs> ... SPECIALISE f :: Int -> Int ... Then we get the SpecPrag SpecPrag (f Int dInt) And from that we want the rule RULE forall dInt. f Int dInt = f_spec f_spec = let f = <rhs> in f Int dInt But be careful! That dInt might be GHC.Base.$fOrdInt, which is an External Name, and you can't bind them in a lambda or forall without getting things confused. Likewise it might have an InlineRule or something, which would be utterly bogus. So we really make a fresh Id, with the same unique and type as the old one, but with an Internal name and no IdInfo. ************************************************************************ * * Desugaring evidence * * ************************************************************************ -} dsHsWrapper :: HsWrapper -> CoreExpr -> DsM CoreExpr dsHsWrapper WpHole e = return e dsHsWrapper (WpTyApp ty) e = return $ App e (Type ty) dsHsWrapper (WpLet ev_binds) e = do bs <- dsTcEvBinds ev_binds return (mkCoreLets bs e) dsHsWrapper (WpCompose c1 c2) e = do { e1 <- dsHsWrapper c2 e ; dsHsWrapper c1 e1 } dsHsWrapper (WpFun c1 c2 t1 _) e = do { x <- newSysLocalDs t1 ; e1 <- dsHsWrapper c1 (Var x) ; e2 <- dsHsWrapper c2 (e `mkCoreAppDs` e1) ; return (Lam x e2) } dsHsWrapper (WpCast co) e = ASSERT(tcCoercionRole co == Representational) dsTcCoercion co (mkCast e) dsHsWrapper (WpEvLam ev) e = return $ Lam ev e dsHsWrapper (WpTyLam tv) e = return $ Lam tv e dsHsWrapper (WpEvApp tm) e = liftM (App e) (dsEvTerm tm) -------------------------------------- dsTcEvBinds_s :: [TcEvBinds] -> DsM [CoreBind] dsTcEvBinds_s [] = return [] dsTcEvBinds_s (b:rest) = ASSERT( null rest ) -- Zonker ensures null dsTcEvBinds b dsTcEvBinds :: TcEvBinds -> DsM [CoreBind] dsTcEvBinds (TcEvBinds {}) = panic "dsEvBinds" -- Zonker has got rid of this dsTcEvBinds (EvBinds bs) = dsEvBinds bs dsEvBinds :: Bag EvBind -> DsM [CoreBind] dsEvBinds bs = mapM ds_scc (sccEvBinds bs) where ds_scc (AcyclicSCC (EvBind { eb_lhs = v, eb_rhs = r })) = liftM (NonRec v) (dsEvTerm r) ds_scc (CyclicSCC bs) = liftM Rec (mapM ds_pair bs) ds_pair (EvBind { eb_lhs = v, eb_rhs = r }) = liftM ((,) v) (dsEvTerm r) sccEvBinds :: Bag EvBind -> [SCC EvBind] sccEvBinds bs = stronglyConnCompFromEdgedVertices edges where edges :: [(EvBind, EvVar, [EvVar])] edges = foldrBag ((:) . mk_node) [] bs mk_node :: EvBind -> (EvBind, EvVar, [EvVar]) mk_node b@(EvBind { eb_lhs = var, eb_rhs = term }) = (b, var, varSetElems (evVarsOfTerm term)) --------------------------------------- dsEvTerm :: EvTerm -> DsM CoreExpr dsEvTerm (EvId v) = return (Var v) dsEvTerm (EvCast tm co) = do { tm' <- dsEvTerm tm ; dsTcCoercion co $ mkCast tm' } -- 'v' is always a lifted evidence variable so it is -- unnecessary to call varToCoreExpr v here. dsEvTerm (EvDFunApp df tys tms) = return (Var df `mkTyApps` tys `mkApps` (map Var tms)) dsEvTerm (EvCoercion (TcCoVarCo v)) = return (Var v) -- See Note [Simple coercions] dsEvTerm (EvCoercion co) = dsTcCoercion co mkEqBox dsEvTerm (EvSuperClass d n) = do { d' <- dsEvTerm d ; let (cls, tys) = getClassPredTys (exprType d') sc_sel_id = classSCSelId cls n -- Zero-indexed ; return $ Var sc_sel_id `mkTyApps` tys `App` d' } dsEvTerm (EvDelayedError ty msg) = return $ Var errorId `mkTyApps` [ty] `mkApps` [litMsg] where errorId = tYPE_ERROR_ID litMsg = Lit (MachStr (fastStringToByteString msg)) dsEvTerm (EvLit l) = case l of EvNum n -> mkIntegerExpr n EvStr s -> mkStringExprFS s dsEvTerm (EvCallStack cs) = dsEvCallStack cs dsEvTerm (EvTypeable ev) = dsEvTypeable ev dsEvTypeable :: EvTypeable -> DsM CoreExpr dsEvTypeable ev = do tyCl <- dsLookupTyCon typeableClassName typeRepTc <- dsLookupTyCon typeRepTyConName let tyRepType = mkTyConApp typeRepTc [] (ty, rep) <- case ev of EvTypeableTyCon tc ks -> do ctr <- dsLookupGlobalId mkPolyTyConAppName mkTyCon <- dsLookupGlobalId mkTyConName dflags <- getDynFlags let mkRep cRep kReps tReps = mkApps (Var ctr) [ cRep, mkListExpr tyRepType kReps , mkListExpr tyRepType tReps ] let kindRep k = case splitTyConApp_maybe k of Nothing -> panic "dsEvTypeable: not a kind constructor" Just (kc,ks) -> do kcRep <- tyConRep dflags mkTyCon kc reps <- mapM kindRep ks return (mkRep kcRep [] reps) tcRep <- tyConRep dflags mkTyCon tc kReps <- mapM kindRep ks return ( mkTyConApp tc ks , mkRep tcRep kReps [] ) EvTypeableTyApp t1 t2 -> do e1 <- getRep tyCl t1 e2 <- getRep tyCl t2 ctr <- dsLookupGlobalId mkAppTyName return ( mkAppTy (snd t1) (snd t2) , mkApps (Var ctr) [ e1, e2 ] ) EvTypeableTyLit t -> do e <- tyLitRep t return (snd t, e) -- TyRep -> Typeable t -- see also: Note [Memoising typeOf] repName <- newSysLocalDs tyRepType let proxyT = mkProxyPrimTy (typeKind ty) ty method = bindNonRec repName rep $ mkLams [mkWildValBinder proxyT] (Var repName) -- package up the method as `Typeable` dictionary return $ mkCast method $ mkSymCo $ getTypeableCo tyCl ty where -- co: method -> Typeable k t getTypeableCo tc t = case instNewTyCon_maybe tc [typeKind t, t] of Just (_,co) -> co _ -> panic "Class `Typeable` is not a `newtype`." -- Typeable t -> TyRep getRep tc (ev,t) = do typeableExpr <- dsEvTerm ev let co = getTypeableCo tc t method = mkCast typeableExpr co proxy = mkTyApps (Var proxyHashId) [typeKind t, t] return (mkApps method [proxy]) -- KnownNat t -> TyRep (also used for KnownSymbol) tyLitRep (ev,t) = do dict <- dsEvTerm ev fun <- dsLookupGlobalId $ case typeKind t of k | eqType k typeNatKind -> typeNatTypeRepName | eqType k typeSymbolKind -> typeSymbolTypeRepName | otherwise -> panic "dsEvTypeable: unknown type lit kind" let finst = mkTyApps (Var fun) [t] proxy = mkTyApps (Var proxyHashId) [typeKind t, t] return (mkApps finst [ dict, proxy ]) -- This part could be cached tyConRep dflags mkTyCon tc = do pkgStr <- mkStringExprFS pkg_fs modStr <- mkStringExprFS modl_fs nameStr <- mkStringExprFS name_fs return (mkApps (Var mkTyCon) [ int64 high, int64 low , pkgStr, modStr, nameStr ]) where tycon_name = tyConName tc modl = nameModule tycon_name pkg = modulePackageKey modl modl_fs = moduleNameFS (moduleName modl) pkg_fs = packageKeyFS pkg name_fs = occNameFS (nameOccName tycon_name) hash_name_fs | isPromotedTyCon tc = appendFS (mkFastString "$k") name_fs | isPromotedDataCon tc = appendFS (mkFastString "$c") name_fs | isTupleTyCon tc && returnsConstraintKind (tyConKind tc) = appendFS (mkFastString "$p") name_fs | otherwise = name_fs hashThis = unwords $ map unpackFS [pkg_fs, modl_fs, hash_name_fs] Fingerprint high low = fingerprintString hashThis int64 | wORD_SIZE dflags == 4 = mkWord64LitWord64 | otherwise = mkWordLit dflags . fromIntegral {- Note [Memoising typeOf] ~~~~~~~~~~~~~~~~~~~~~~~~~~ See #3245, #9203 IMPORTANT: we don't want to recalculate the TypeRep once per call with the proxy argument. This is what went wrong in #3245 and #9203. So we help GHC by manually keeping the 'rep' *outside* the lambda. -} dsEvCallStack :: EvCallStack -> DsM CoreExpr -- See Note [Overview of implicit CallStacks] in TcEvidence.hs dsEvCallStack cs = do df <- getDynFlags m <- getModule srcLocDataCon <- dsLookupDataCon srcLocDataConName let srcLocTyCon = dataConTyCon srcLocDataCon let srcLocTy = mkTyConTy srcLocTyCon let mkSrcLoc l = liftM (mkCoreConApps srcLocDataCon) (sequence [ mkStringExprFS (packageKeyFS $ modulePackageKey m) , mkStringExprFS (moduleNameFS $ moduleName m) , mkStringExprFS (srcSpanFile l) , return $ mkIntExprInt df (srcSpanStartLine l) , return $ mkIntExprInt df (srcSpanStartCol l) , return $ mkIntExprInt df (srcSpanEndLine l) , return $ mkIntExprInt df (srcSpanEndCol l) ]) let callSiteTy = mkBoxedTupleTy [stringTy, srcLocTy] matchId <- newSysLocalDs $ mkListTy callSiteTy callStackDataCon <- dsLookupDataCon callStackDataConName let callStackTyCon = dataConTyCon callStackDataCon let callStackTy = mkTyConTy callStackTyCon let emptyCS = mkCoreConApps callStackDataCon [mkNilExpr callSiteTy] let pushCS name loc rest = mkWildCase rest callStackTy callStackTy [( DataAlt callStackDataCon , [matchId] , mkCoreConApps callStackDataCon [mkConsExpr callSiteTy (mkCoreTup [name, loc]) (Var matchId)] )] let mkPush name loc tm = do nameExpr <- mkStringExprFS name locExpr <- mkSrcLoc loc case tm of EvCallStack EvCsEmpty -> return (pushCS nameExpr locExpr emptyCS) _ -> do tmExpr <- dsEvTerm tm -- at this point tmExpr :: IP sym CallStack -- but we need the actual CallStack to pass to pushCS, -- so we use unwrapIP to strip the dictionary wrapper -- See Note [Overview of implicit CallStacks] let ip_co = unwrapIP (exprType tmExpr) return (pushCS nameExpr locExpr (mkCast tmExpr ip_co)) case cs of EvCsTop name loc tm -> mkPush name loc tm EvCsPushCall name loc tm -> mkPush (occNameFS $ getOccName name) loc tm EvCsEmpty -> panic "Cannot have an empty CallStack" --------------------------------------- dsTcCoercion :: TcCoercion -> (Coercion -> CoreExpr) -> DsM CoreExpr -- This is the crucial function that moves -- from TcCoercions to Coercions; see Note [TcCoercions] in Coercion -- e.g. dsTcCoercion (trans g1 g2) k -- = case g1 of EqBox g1# -> -- case g2 of EqBox g2# -> -- k (trans g1# g2#) -- thing_inside will get a coercion at the role requested dsTcCoercion co thing_inside = do { us <- newUniqueSupply ; let eqvs_covs :: [(EqVar,CoVar)] eqvs_covs = zipWith mk_co_var (varSetElems (coVarsOfTcCo co)) (uniqsFromSupply us) subst = mkCvSubst emptyInScopeSet [(eqv, mkCoVarCo cov) | (eqv, cov) <- eqvs_covs] result_expr = thing_inside (ds_tc_coercion subst co) result_ty = exprType result_expr ; return (foldr (wrap_in_case result_ty) result_expr eqvs_covs) } where mk_co_var :: Id -> Unique -> (Id, Id) mk_co_var eqv uniq = (eqv, mkUserLocal occ uniq ty loc) where eq_nm = idName eqv occ = nameOccName eq_nm loc = nameSrcSpan eq_nm ty = mkCoercionType (getEqPredRole (evVarPred eqv)) ty1 ty2 (ty1, ty2) = getEqPredTys (evVarPred eqv) wrap_in_case result_ty (eqv, cov) body = case getEqPredRole (evVarPred eqv) of Nominal -> Case (Var eqv) eqv result_ty [(DataAlt eqBoxDataCon, [cov], body)] Representational -> Case (Var eqv) eqv result_ty [(DataAlt coercibleDataCon, [cov], body)] Phantom -> panic "wrap_in_case/phantom" ds_tc_coercion :: CvSubst -> TcCoercion -> Coercion -- If the incoming TcCoercion if of type (a ~ b) (resp. Coercible a b) -- the result is of type (a ~# b) (reps. a ~# b) -- The VarEnv maps EqVars of type (a ~ b) to Coercions of type (a ~# b) (resp. and so on) -- No need for InScope set etc because the ds_tc_coercion subst tc_co = go tc_co where go (TcRefl r ty) = Refl r (Coercion.substTy subst ty) go (TcTyConAppCo r tc cos) = mkTyConAppCo r tc (map go cos) go (TcAppCo co1 co2) = mkAppCo (go co1) (go co2) go (TcForAllCo tv co) = mkForAllCo tv' (ds_tc_coercion subst' co) where (subst', tv') = Coercion.substTyVarBndr subst tv go (TcAxiomInstCo ax ind cos) = AxiomInstCo ax ind (map go cos) go (TcPhantomCo ty1 ty2) = UnivCo (fsLit "ds_tc_coercion") Phantom ty1 ty2 go (TcSymCo co) = mkSymCo (go co) go (TcTransCo co1 co2) = mkTransCo (go co1) (go co2) go (TcNthCo n co) = mkNthCo n (go co) go (TcLRCo lr co) = mkLRCo lr (go co) go (TcSubCo co) = mkSubCo (go co) go (TcLetCo bs co) = ds_tc_coercion (ds_co_binds bs) co go (TcCastCo co1 co2) = mkCoCast (go co1) (go co2) go (TcCoVarCo v) = ds_ev_id subst v go (TcAxiomRuleCo co ts cs) = AxiomRuleCo co (map (Coercion.substTy subst) ts) (map go cs) go (TcCoercion co) = co ds_co_binds :: TcEvBinds -> CvSubst ds_co_binds (EvBinds bs) = foldl ds_scc subst (sccEvBinds bs) ds_co_binds eb@(TcEvBinds {}) = pprPanic "ds_co_binds" (ppr eb) ds_scc :: CvSubst -> SCC EvBind -> CvSubst ds_scc subst (AcyclicSCC (EvBind { eb_lhs = v, eb_rhs = ev_term })) = extendCvSubstAndInScope subst v (ds_co_term subst ev_term) ds_scc _ (CyclicSCC other) = pprPanic "ds_scc:cyclic" (ppr other $$ ppr tc_co) ds_co_term :: CvSubst -> EvTerm -> Coercion ds_co_term subst (EvCoercion tc_co) = ds_tc_coercion subst tc_co ds_co_term subst (EvId v) = ds_ev_id subst v ds_co_term subst (EvCast tm co) = mkCoCast (ds_co_term subst tm) (ds_tc_coercion subst co) ds_co_term _ other = pprPanic "ds_co_term" (ppr other $$ ppr tc_co) ds_ev_id :: CvSubst -> EqVar -> Coercion ds_ev_id subst v | Just co <- Coercion.lookupCoVar subst v = co | otherwise = pprPanic "ds_tc_coercion" (ppr v $$ ppr tc_co) {- Note [Simple coercions] ~~~~~~~~~~~~~~~~~~~~~~~ We have a special case for coercions that are simple variables. Suppose cv :: a ~ b is in scope Lacking the special case, if we see f a b cv we'd desguar to f a b (case cv of EqBox (cv# :: a ~# b) -> EqBox cv#) which is a bit stupid. The special case does the obvious thing. This turns out to be important when desugaring the LHS of a RULE (see Trac #7837). Suppose we have normalise :: (a ~ Scalar a) => a -> a normalise_Double :: Double -> Double {-# RULES "normalise" normalise = normalise_Double #-} Then the RULE we want looks like forall a, (cv:a~Scalar a). normalise a cv = normalise_Double But without the special case we generate the redundant box/unbox, which simpleOpt (currently) doesn't remove. So the rule never matches. Maybe simpleOpt should be smarter. But it seems like a good plan to simply never generate the redundant box/unbox in the first place. -}
urbanslug/ghc
compiler/deSugar/DsBinds.hs
bsd-3-clause
47,873
0
24
15,130
8,377
4,275
4,102
550
21
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. module Duckling.Time.GA.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Testing.Asserts import Duckling.Time.GA.Corpus tests :: TestTree tests = testGroup "GA Tests" [ makeCorpusTest [This Time] corpus ]
rfranek/duckling
tests/Duckling/Time/GA/Tests.hs
bsd-3-clause
591
0
9
96
80
51
29
11
1
module Main where import Control.Concurrent import Control.Concurrent.STM import Control.Concurrent.STM.TSem import Control.Monad import System.IO import Debug.Trace main = do hSetBuffering stdout NoBuffering noMansLand <- replicateM 998 $ newTVarIO 0 t0 <- newTVarIO (1::Int) t999 <- newTVarIO (-1) let ts = t0:noMansLand++[t999] done <- atomically $ newTSem 0 forkIO $ atomically $ nestedOrElseMap done ts -- need enough time here for nestedOrElseMap thread above to move past t0 -- in this version, the modifications to t0 force nestedOrElseMap to be restarted forkIO (trace "starting vexing!" $ forever $ atomically $ (modifyTVar' t0 (+1) >> trace "vex" (return ()))) -- in this version nestedOrElseMap causes this transaction to be restarted and never makes progress: --forkIO (atomically (trace "starting vexing!" $ forever $ (modifyTVar' t0 (+1) >> trace "vex" (return ())))) atomically $ waitTSem done putStrLn "No livelock! Did the t0 counter get incremented?: " atomically (readTVar t0) >>= print nestedOrElseMap :: TSem -> [TVar Int] -> STM () nestedOrElseMap done ts = trace "nestedOrElseMap starting" $ foldl1 orElse $ map transaction $ zip [(1::Int)..] ts where transaction (cnt,v) = do n <- traceShow cnt $ readTVar v if n < 0 then trace "@" (modifyTVar' v (subtract 1)) >> signalTSem done else retry -- NOTE: this shows at least that we get livelock as we wait on the first transaction (it may also be executed; add Debug.Trace) -- that's not really working... -- -- CONSIDER: -- The behavior we see ensures that all branches of orElse see the same view of -- the same variables, but is overzealous! It should do validation for each -- subtransaction by only checking oldest parent read of each variable *used* -- in the transaction, and if any changed, then go up only to the last -- inconsistency) -- ""If both t1 and t2 execute retry then even though the effects of t1 are -- thrown away, it could be that a change to a TVar that is only in the -- access set of t1 will allow the whole transaction to succeed when it is -- woken. To solve this problem, when a branch on a nested transaction is -- aborted the access set of the nested transaction is merged as a read set -- into the parent TRec. Specifically if the TVar is in any TRec up the -- chain of nested transactions it must be ignored, otherwise it is entered -- as a new entry (retaining just the read) in the parent TRec."" -- -- "aborted"? "read set"? -- -- is this the culprit? No. Clearly we move on from that branch in test. -- "A validation failure in the first branch aborts the entire transaction, not just the nested part" -- "validation"? -- "Before a transaction can make its effects visible to other threads -- it must check that it has seen a consistent view of memory while it -- was executing. Most of the work is done in -- validate_and_acquire_ownership by checking that TVars hold their -- expected values. " -- -- when commiting, do we force that the read set is unchanged? -- -- Soooo -- The writes to variables from other branches are causing a validation failure -- and causing whole transaction to reset
jberryman/chan-benchmarks
RetryExperiment.hs
bsd-3-clause
3,351
0
15
779
413
221
192
26
2
{-# LANGUAGE OverlappingInstances, TypeSynonymInstances, FlexibleContexts, UndecidableInstances #-} {- Flatten.hs Joel Svensson -} module Obsidian.ArrowObsidian.Flatten (Flatten, FData, List(Nil,Unit,Tuple,For), toFData, fromFData, size, sizeArr ) where import Obsidian.ArrowObsidian.Arr import Obsidian.ArrowObsidian.Exp import Obsidian.ArrowObsidian.PureAPI import Obsidian.ArrowObsidian.Printing import Data.Word import qualified Data.Foldable as Fold import System.IO.Unsafe -------------------------------------------------------------------------------- data List a = Nil | Unit a | Tuple [List a] | For (Arr (List a)) deriving Show instance (Eq (Arr (List a)),Eq a) => Eq (List a) where (==) (Unit a) (Unit b) = a == b (==) (Tuple xs) (Tuple ys) = and $ (length xs == length ys) : zipWith (==) xs ys (==) (For a) (For b) = a == b (==) _ _ = False instance Functor List where fmap f (Unit a) = Unit (f a) fmap f (Tuple xs) = Tuple (map (fmap f) xs) fmap f (For arr) = For (fmap (fmap f) arr) instance Fold.Foldable List where foldr f id (Unit a) = f a id foldr f id (Tuple xs) = foldr (flip $ Fold.foldr f) id xs foldr f id (For arr) = Fold.foldr (flip $ Fold.foldr f) id arr size :: List a -> Int size (Tuple xs) = sum (map size xs) size (Unit _) = 1 size (For arr) = len arr * size (arr ! 0) sizeArr :: Arr (List a) -> Int sizeArr arr = len arr * size (arr ! 0 ) -------------------------------------------------------------------------------- type FData = List (DExp, Type) -------------------------------------------------------------------------------- class Flatten a where toFData :: a -> FData fromFData :: FData -> a instance Flatten FData where toFData = id fromFData = id instance Flatten IntE where toFData a = Unit (unE a, Int) fromFData (Unit (a,Int)) = E a instance Flatten FloatE where toFData a = Unit (unE a, Float) fromFData (Unit (a,Float)) = E a instance Flatten WordE where toFData a = Unit (unE a, Unsigned Int) fromFData (Unit (a,Unsigned Int)) = E a instance (Flatten a, Flatten b) => Flatten (a,b) where toFData (x,y) = Tuple [toFData x,toFData y] fromFData (Tuple [a,b]) = (fromFData a,fromFData b) instance (Flatten a, Flatten b, Flatten c) => Flatten (a,b,c) where toFData (x,y,z) = Tuple [toFData x,toFData y,toFData z] fromFData (Tuple [x,y,z]) = (fromFData x,fromFData y, fromFData z) instance Flatten a => Flatten (Arr a) where toFData a = For (fmap toFData a) fromFData (For a) = fmap fromFData a --------------------------------------------------------------------------------
svenssonjoel/ArrowObsidian
Obsidian/ArrowObsidian/Flatten.hs
bsd-3-clause
2,827
0
10
699
1,114
589
525
73
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module GitHub (getVersionTags) where import Control.Monad.Error import Data.Aeson as Json import qualified Data.Maybe as Maybe import Data.Monoid ((<>)) import qualified Data.Vector as Vector import Network.HTTP.Client import qualified Elm.Package.Name as Name import qualified Elm.Package.Version as Version import qualified Utils.Http as Http -- TAGS from GITHUB newtype Tags = Tags [String] getVersionTags :: (MonadIO m, MonadError String m) => Name.Name -> m [Version.Version] getVersionTags (Name.Name user project) = do response <- Http.send url $ \request manager -> httpLbs (request {requestHeaders = headers}) manager case Json.eitherDecode (responseBody response) of Left err -> throwError err Right (Tags tags) -> return (Maybe.mapMaybe Version.fromString tags) where url = "https://api.github.com/repos/" ++ user ++ "/" ++ project ++ "/tags" headers = [("User-Agent", "elm-package")] <> [("Accept", "application/json")] instance FromJSON Tags where parseJSON (Array arr) = Tags `fmap` mapM toTag (Vector.toList arr) where toTag (Object obj) = obj .: "name" toTag _ = fail "expecting an object" parseJSON _ = fail "expecting an array"
rtfeldman/elm-package
src/GitHub.hs
bsd-3-clause
1,350
0
13
297
382
214
168
33
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-orphans #-} import Prelude import Control.Applicative import Control.Lens import Control.Monad import Control.Monad.IO.Class import Criterion import Criterion.Analysis import Criterion.Config import Criterion.Environment import Criterion.Monad import qualified Data.Attoparsec.ByteString.Char8 as P import Data.Basis import qualified Data.ByteString.Builder as S import qualified Data.ByteString.Lazy as SL import Data.Monoid import Data.Thyme import qualified Data.Time as T import Data.VectorSpace import System.Exit import System.Locale import System.Random import Test.QuickCheck import qualified Test.QuickCheck.Gen as Gen import Text.Printf instance Arbitrary Day where arbitrary = fmap (review gregorian) $ YearMonthDay -- FIXME: We disagree with time on how many digits to use for year. <$> choose (1000, 9999) <*> choose (1, 12) <*> choose (1, 31) instance Arbitrary DiffTime where arbitrary = (^*) (basisValue ()) . toRational <$> (choose (0, 86400.999999) :: Gen Double) instance Arbitrary UTCTime where arbitrary = fmap (review utcTime) $ UTCTime <$> arbitrary <*> arbitrary toTime :: UTCTime -> T.UTCTime toTime (view utcTime -> UTCTime (ModifiedJulianDay d) t) = T.UTCTime (T.ModifiedJulianDay $ fromIntegral d) (fromRational $ t ^/^ basisValue ()) (^/^) :: (HasBasis v, Basis v ~ (), Scalar v ~ s, Fractional s) => v -> v -> s x ^/^ y = decompose' x () / decompose' y () ------------------------------------------------------------------------ newtype Spec = Spec String deriving (Show) instance Arbitrary Spec where arbitrary = do -- Pick a non-overlapping day spec generator. day <- Gen.elements [ spec {-YearMonthDay-}"DFYyCBbhmde" , spec {-OrdinalDate-}"YyCj" -- TODO: time only consider the presence of %V as -- indication that it should parse as WeekDate , (++) "%V " <$> spec {-WeekDate-}"GgfuwAa" , spec {-SundayWeek-}"YyCUuwAa" , spec {-MondayWeek-}"YyCWuwAa" ] :: Gen (Gen String) -- Pick a non-overlapping day & tod spec generator. time <- Gen.frequency [ (16, pure $ Gen.frequency [ (8, day) , (4, rod) , (2, h12) , (1, sec) , (1, spec {-TimeZone-}"zZ") ] ) -- TODO: these are broken due to issues above and below -- , (2, pure $ spec {-aggregate-}"crXx") , (1, pure $ spec {-UTCTime-}"s") ] :: Gen (Gen String) fmap (Spec . unwords) . listOf1 $ frequency [(16, time), (4, string), (1, pure "%%")] where spec = Gen.elements . fmap (\ c -> ['%', c]) string = filter ('%' /=) <$> arbitrary -- TODO: time discards %q %Q or %p %P after setting %S or hours -- respectively. Fudge it by always including %q and %p at end. -- tod = spec {-TimeOfDay-}"RTPpHIklMSqQ" rod = spec {-RestOfDay-}"RHkMqQ" sec = (++ " %q") <$> spec {-seconds-}"ST" h12 = (++ " %p") <$> spec {-12-hour-}"Il" ------------------------------------------------------------------------ prop_formatTime :: Spec -> UTCTime -> Property prop_formatTime (Spec spec) t@(toTime -> t') = printTestCase desc (s == s') where s = formatTime defaultTimeLocale spec t s' = T.formatTime defaultTimeLocale spec t' desc = "thyme: " ++ s ++ "\ntime: " ++ s' prop_parseTime :: Spec -> UTCTime -> Property prop_parseTime (Spec spec) (T.formatTime defaultTimeLocale spec . toTime -> s) = printTestCase desc (fmap toTime t == t') where t = parseTime defaultTimeLocale spec s t' = T.parseTime defaultTimeLocale spec s tp = P.parseOnly (timeParser defaultTimeLocale spec) . SL.toStrict . S.toLazyByteString . S.stringUtf8 desc = "input: " ++ show s ++ "\nthyme: " ++ show t ++ "\ntime: " ++ show t' ++ "\nstate: " ++ show (tp s) ------------------------------------------------------------------------ main :: IO () main = do correct <- fmap (all isSuccess) . mapM quickCheckResult $ prop_formatTime : prop_parseTime : [] ts <- Gen.unGen (vectorOf 10 arbitrary) <$> newStdGen <*> pure 0 let ts' = toTime <$> ts let ss = T.formatTime defaultTimeLocale spec <$> ts' fast <- fmap and . withConfig config $ do env <- measureEnvironment ns <- getConfigItem $ fromLJ cfgResamples mapM (benchMean env ns) $ ( "formatTime", 9 , nf (formatTime defaultTimeLocale spec <$>) ts , nf (T.formatTime defaultTimeLocale spec <$>) ts' ) : ( "parseTime", 4.5, nf (parse <$>) ss, nf (parse' <$>) ss ) : [] exitWith $ if correct && fast then ExitSuccess else ExitFailure 1 where isSuccess r = case r of Success {} -> True; _ -> False config = defaultConfig {cfgVerbosity = Last (Just Quiet)} spec = "%F %G %V %u %j %T %s" parse = parseTime defaultTimeLocale spec :: String -> Maybe UTCTime parse' = T.parseTime defaultTimeLocale spec :: String -> Maybe T.UTCTime benchMean env n (name, expected, us, them) = do ours <- flip analyseMean n =<< runBenchmark env us theirs <- flip analyseMean n =<< runBenchmark env them let ratio = theirs / ours liftIO . void $ printf "%s: %.1f× faster; expected %.1f×.\n" name ratio expected return (ratio >= expected)
ekmett/thyme
tests/sanity.hs
bsd-3-clause
5,637
0
18
1,464
1,581
843
738
112
3
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} module Aws.ElasticTranscoder.Commands.CreateJob ( CreateJob(..) , CreateJobResponse(..) , createJob , defaultJSInput , defaultJSOutput ) where import Aws.Core import Aws.ElasticTranscoder.Core import Control.Applicative import Data.Aeson -- | A brief example createJob program -- -- myCreateJob :: IO () -- myCreateJob = -- do cfg <- Aws.baseConfiguration -- rsp <- withManager $ \mgr -> Aws.pureAws cfg my_ets_cfg mgr $ -- createJob "Wildlife.wmv" "Wildlife-t.f4v" my_preset my_pipeline -- print rsp -- my_ets_cfg :: EtsConfiguration NormalQuery -- my_ets_cfg = etsConfiguration HTTPS etsEndpointEu -- my_preset :: PresetId -- my_preset = "1351620000000-000001" -- my_pipeline :: PipelineId -- my_pipeline = "1359460188157-258e48" data CreateJob = CreateJob { cjInput :: JSInput , cjOutput :: JSOutput , cjPipelineId :: PipelineId } deriving (Show,Eq) data CreateJobResponse = CreateJobResponse { cjrId :: JobId , cjrInput :: JSInput , cjrOutput :: JSOutputStatus , cjrPipelineId :: PipelineId } deriving (Show,Eq) createJob :: S3Object -> S3Object -> PresetId -> PipelineId -> CreateJob createJob inb oub pri pli = CreateJob cji cjo pli where cji = defaultJSInput inb cjo = defaultJSOutput oub pri defaultJSInput :: S3Object -> JSInput defaultJSInput inb = JSInput inb FRauto Rauto ARauto ABauto Cauto defaultJSOutput :: S3Object -> PresetId -> JSOutput defaultJSOutput oub pri = JSOutput oub "" ROTauto pri instance SignQuery CreateJob where type ServiceConfiguration CreateJob = EtsConfiguration signQuery CreateJob {..} = etsSignQuery EtsQuery { etsqMethod = Post , etsqRequest = "jobs" , etsqQuery = [] , etsqBody = Just $ toJSON $ JobSpec cjInput cjOutput cjPipelineId } instance ResponseConsumer CreateJob CreateJobResponse where type ResponseMetadata CreateJobResponse = EtsMetadata responseConsumer _ mref = etsResponseConsumer mref $ \rsp -> cnv <$> jsonConsumer rsp where cnv (JobSingle(JobSpecId a b c d)) = CreateJobResponse a b c d instance Transaction CreateJob CreateJobResponse instance AsMemoryResponse CreateJobResponse where type MemoryResponse CreateJobResponse = CreateJobResponse loadToMemory = return
cdornan/aws-elastic-transcoder
Aws/ElasticTranscoder/Commands/CreateJob.hs
bsd-3-clause
2,696
0
12
735
471
266
205
51
1
{-# language CPP #-} -- | = Name -- -- VK_KHR_shader_subgroup_uniform_control_flow - device extension -- -- == VK_KHR_shader_subgroup_uniform_control_flow -- -- [__Name String__] -- @VK_KHR_shader_subgroup_uniform_control_flow@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 324 -- -- [__Revision__] -- 1 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.1 -- -- [__Contact__] -- -- - Alan Baker -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_shader_subgroup_uniform_control_flow] @alan-baker%0A<<Here describe the issue or question you have about the VK_KHR_shader_subgroup_uniform_control_flow extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2020-08-27 -- -- [__IP Status__] -- No known IP claims. -- -- [__Interactions and External Dependencies__] -- -- - Requires SPIR-V 1.3. -- -- - This extension requires -- <https://htmlpreview.github.io/?https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/KHR/SPV_KHR_subgroup_uniform_control_flow.html SPV_KHR_subgroup_uniform_control_flow> -- -- - This extension provides API support for -- <https://github.com/KhronosGroup/GLSL/blob/master/extensions/ext/GL_EXT_subgroupuniform_qualifier.txt GL_EXT_subgroupuniform_qualifier> -- -- [__Contributors__] -- -- - Alan Baker, Google -- -- - Jeff Bolz, NVIDIA -- -- == Description -- -- This extension allows the use of the -- @SPV_KHR_subgroup_uniform_control_flow@ SPIR-V extension in shader -- modules. @SPV_KHR_subgroup_uniform_control_flow@ provides stronger -- guarantees that diverged subgroups will reconverge. -- -- Developers should utilize this extension if they use subgroup operations -- to reduce the work performed by a uniform subgroup. This extension will -- guarantee that uniform subgroup will reconverge in the same manner as -- invocation groups (see “Uniform Control Flow” in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#spirv-spec Khronos SPIR-V Specification>). -- -- == New Structures -- -- - Extending -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2', -- 'Vulkan.Core10.Device.DeviceCreateInfo': -- -- - 'PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR' -- -- == New Enum Constants -- -- - 'KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_EXTENSION_NAME' -- -- - 'KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_SPEC_VERSION' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_FEATURES_KHR' -- -- == Version History -- -- - Revision 1, 2020-08-27 (Alan Baker) -- -- - Internal draft version -- -- == See Also -- -- 'PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_KHR_shader_subgroup_uniform_control_flow Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_KHR_shader_subgroup_uniform_control_flow ( PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR(..) , KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_SPEC_VERSION , pattern KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_SPEC_VERSION , KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_EXTENSION_NAME , pattern KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_EXTENSION_NAME ) where import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import Foreign.Ptr (Ptr) import Data.Kind (Type) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_FEATURES_KHR)) -- | VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR - Structure -- describing support for shader subgroup uniform control flow by an -- implementation -- -- = Members -- -- This structure describes the following feature: -- -- = Description -- -- If the -- 'Vulkan.Extensions.VK_EXT_private_data.PhysicalDevicePrivateDataFeaturesEXT' -- structure is included in the @pNext@ chain of the -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2' -- structure passed to -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2', -- it is filled in to indicate whether each corresponding feature is -- supported. -- 'Vulkan.Extensions.VK_EXT_private_data.PhysicalDevicePrivateDataFeaturesEXT' -- /can/ also be used in the @pNext@ chain of -- 'Vulkan.Core10.Device.DeviceCreateInfo' to selectively enable these -- features. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_shader_subgroup_uniform_control_flow VK_KHR_shader_subgroup_uniform_control_flow>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR = PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR { -- | #features-shaderSubgroupUniformControlFlow# -- @shaderSubgroupUniformControlFlow@ specifies whether the implementation -- supports the shader execution mode @SubgroupUniformControlFlowKHR@ shaderSubgroupUniformControlFlow :: Bool } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR) #endif deriving instance Show PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR instance ToCStruct PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_FEATURES_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (shaderSubgroupUniformControlFlow)) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_FEATURES_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR where peekCStruct p = do shaderSubgroupUniformControlFlow <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) pure $ PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR (bool32ToBool shaderSubgroupUniformControlFlow) instance Storable PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR where zero = PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR zero type KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_SPEC_VERSION = 1 -- No documentation found for TopLevel "VK_KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_SPEC_VERSION" pattern KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_SPEC_VERSION :: forall a . Integral a => a pattern KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_SPEC_VERSION = 1 type KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_EXTENSION_NAME = "VK_KHR_shader_subgroup_uniform_control_flow" -- No documentation found for TopLevel "VK_KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_EXTENSION_NAME" pattern KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern KHR_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_EXTENSION_NAME = "VK_KHR_shader_subgroup_uniform_control_flow"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_KHR_shader_subgroup_uniform_control_flow.hs
bsd-3-clause
9,078
0
14
1,354
970
606
364
-1
-1
module HughesTest where import Hughes import Test.Hspec import Test.Hspec.QuickCheck import Data.Monoid -- This operation is especially slow for regular lists... but -- actually quite fast for Hughes lists if you implement them -- right. slowReverse :: [a] -> Hughes a slowReverse = foldr (flip snoc) mempty main :: IO () main = hspec $ do describe "runHughes and mkHughes are mutual inverses" $ do prop "runHughes . mkHughes = id" $ \l -> runHughes (mkHughes l) == (l :: [Int]) describe "cons works" $ do prop "should work the same as consDumb" $ \l a -> let norm :: [Int] -> [Int] norm = runHughes . consDumb a . mkHughes new :: [Int] -> [Int] new = runHughes . cons a . mkHughes in new l == norm l describe "append works" $ do prop "should work the same as consDumb" $ \l l' -> let norm :: [Int] -> [Int] norm = runHughes . appendDumb (mkHughes l') . mkHughes new :: [Int] -> [Int] new = runHughes . mappend (mkHughes l') . mkHughes in new l == norm l describe "snoc works" $ do prop "should work the same as snocDumb" $ \l a -> let norm :: [Int] -> [Int] norm = runHughes . flip snocDumb a . mkHughes new :: [Int] -> [Int] new = runHughes . flip snoc a . mkHughes in new l == norm l describe "efficiency" $ do it "should reverse efficiently" $ let a = [1..100000] b = slowReverse a in runHughes b `shouldBe` reverse a
bitemyapp/kata
HughesTest.hs
bsd-3-clause
1,564
0
21
496
510
257
253
42
1
{-# LANGUAGE OverloadedStrings #-} module Bazaari.Types where import Data.ByteString import Data.CountryCodes import Data.Fixed import qualified Data.Text as T import Data.Time import Text.Email.Validate -- getCurrentDay :: IO Day -- getCurrentDay = getCurrentTime >>= return . utctDay type AccessKeyId = ByteString type MarketplaceId = ByteString type SellerId = ByteString type SecretKey = ByteString type Version = ByteString data Endpoint = NorthAmerica | Europe | India | China | Japan newtype AmazonOrderId = AmazonOrderId { unAmazonOrderId :: T.Text } deriving (Eq, Show) newtype SellerOrderId = SellerOrderId { unSellerOrderId :: T.Text } deriving (Eq, Show) data ShipmentRequestDetails = ShipmentRequestDetails { amazonOrderId :: AmazonOrderId , sellerOrderId :: Maybe SellerOrderId , itemList :: [Item] , shipFromAddress :: Address , packageDimensions :: PackageDimensions , weight :: Weight , mustArriveByUTCTime :: Maybe UTCTime , requestShipUTCTime :: Maybe UTCTime , requestShippingServiceOptions :: ShippingServiceOptions } newtype ShippingServiceName = ShippingServiceName { unShippingServiceName :: T.Text } deriving (Eq, Show) newtype CarrierName = CarrierName { unCarrierName :: T.Text } deriving (Eq, Show) newtype ShippingServiceId = ShippingServiceId { unShippingServiceId :: T.Text } deriving (Eq, Show) newtype ShippingServiceOfferId = ShippingServiceOfferId { unShippingServiceOfferId :: T.Text } deriving (Eq, Show) data ShippingService = ShippingService { shippingServiceName :: ShippingServiceName , carrierName :: CarrierName , shippingServiceId :: ShippingServiceId , shippingServiceOfferId :: ShippingServiceOfferId , serviceShipUTCTime :: UTCTime , earliestEstimatedDeliveryUTCTime :: Maybe UTCTime , latestEstimatedDeliveryUTCTime :: Maybe UTCTime , rate :: CurrencyAmount , shippingServiceOptions :: ShippingServiceOptions } newtype TemporarilyUnavailableCarrier = TemporarilyUnavailableCarrier CarrierName newtype TermsAndConditionsNotAcceptedCarrier = TermsAndConditionsNotAcceptedCarrier CarrierName newtype OrderItemId = OrderItemId { unOrderItemId :: T.Text } deriving (Eq, Show) data Item = Item { orderItemId :: OrderItemId , quantity :: Int } newtype AddressName = AddressName { unAddressName :: T.Text } deriving (Eq, Show) newtype AddressLine = AddressLine { unAddressLine :: T.Text } deriving (Eq, Show) newtype City = City { unCity :: T.Text } deriving (Eq, Show) newtype County = County { unCounty :: T.Text } deriving (Eq, Show) -- or "province" newtype State = State { unState :: T.Text } deriving (Eq, Show) newtype PostalCode = PostalCode { unPostalCode :: T.Text } deriving (Eq, Show) newtype PhoneNumber = PhoneNumber { unPhoneNumber :: T.Text } deriving (Eq, Show) data Address = Address { name :: AddressName , addressLine1 :: AddressLine , addressLine2 :: Maybe SecondaryAddressLine , addressLine3 :: Maybe SecondaryAddressLine , districtOrCounty :: Maybe County , email :: EmailAddress , city :: City , stateOrProvinceCode :: Maybe State , postalCode :: PostalCode -- note that Currency uses a different CountryCode library , countryCode :: CountryCode , phone :: PhoneNumber } newtype Name = Name T.Text makeName :: T.Text -> Either T.Text Name makeName name | T.length name == 0 = Left "Empty name" | T.length name > 30 = Left "Name is too long" | T.length name <= 30 = Right $ Name name makeAddressLine :: T.Text -> Either T.Text AddressLine makeAddressLine line | T.length line == 0 = Left "Empty line" | T.length line > 180 = Left "line is too long" | T.length line <= 180 = Right $ AddressLine line newtype SecondaryAddressLine = SecondaryAddressLine { unSecondaryAddressLine :: T.Text } deriving (Eq, Show) makeSecondaryAddressLine :: T.Text -> Either T.Text SecondaryAddressLine makeSecondaryAddressLine line | T.length line == 0 = Left "Empty line" | T.length line > 60 = Left "line is too long" | T.length line <= 60 = Right $ SecondaryAddressLine line makeCounty :: T.Text -> Either T.Text County makeCounty county | T.length county == 0 = Left "Empty county" | T.length county > 30 = Left "County is too long" | T.length county <= 30 = Right $ County county newtype Email = Email T.Text makeEmail :: T.Text -> Either T.Text Email makeEmail email | T.length email == 0 = Left "Empty email" | T.length email > 256 = Left "Email is too long" | T.length email <= 256 = Right $ Email email makeCity :: T.Text -> Either T.Text City makeCity city | T.length city == 0 = Left "Empty city name" | T.length city > 30 = Left "City name is too long" | T.length city <= 30 = Right $ City city newtype StateOrProvinceCode = StateOrProvinceCode T.Text makeStateOrProvinceCode :: T.Text -> Either T.Text StateOrProvinceCode makeStateOrProvinceCode state | T.length state == 0 = Left "Empty state or province code" | T.length state > 30 = Left "State or province code is too long" | T.length state <= 30 = Right $ StateOrProvinceCode state makePostalCode :: T.Text -> Either T.Text PostalCode makePostalCode code | T.length code == 0 = Left "Empty postal code" | T.length code > 30 = Left "Postal code is too long" | T.length code <= 30 = Right $ PostalCode code makePhoneNumber :: T.Text -> Either T.Text PhoneNumber makePhoneNumber number | T.length number == 0 = Left "Empty phone number" | T.length number > 30 = Left "Phone number is too long" | T.length number <= 30 = Right $ PhoneNumber number data PackageDimensions = CustomDimensions { len :: Length , width :: Width , height :: Height , unit :: LengthUnit } | PredefinedDimensions { predefinedPackageDimensions :: PredefinedPackageDimensions } newtype Length = Length { unLength :: Float } deriving (Eq, Show) makeLength :: Float -> Either T.Text Length makeLength len | len <= 0 = Left "Length must be greater than zero" | len > 0 = Right $ Length len newtype Width = Width { unWidth :: Float } deriving (Eq, Show) makeWidth :: Float -> Either T.Text Width makeWidth width | width <= 0 = Left "Width must be greater than zero" | width > 0 = Right $ Width width newtype Height = Height { unHeight :: Float } deriving (Eq, Show) makeHeight :: Float -> Either T.Text Height makeHeight height | height <= 0 = Left "Height must be greater than zero" | height > 0 = Right $ Height height data LengthUnit = Inches | Centimeters data Weight = Weight { value :: WeightValue , units :: WeightUnit } newtype WeightValue = WeightValue { unWeightValue :: Float } makeWeightValue :: Float -> Either T.Text WeightValue makeWeightValue weight | weight <= 0 = Left "Weigth must be greater than zero" | weight > 0 = Right $ WeightValue weight data WeightUnit = Ounces | Grams data ShippingServiceOptions = ShippingServiceOptions { deliveryExperience :: DeliveryExperience , declaredValue :: Maybe CurrencyAmount , carrierWillPickUp :: Bool } data DeliveryExperience = DeliveryConfirmationWithAdultSignature | DeliveryConfirmationWithSignature | DeliveryConfirmationWithoutSignature | NoTracking data CurrencyAmount = CurrencyAmount { currencyCode :: CurrencyCode , amount :: Float } data PredefinedPackageDimensions = FedEx_Box_10kg | FedEx_Box_25kg | FedEx_Box_Extra_Large_1 | FedEx_Box_Extra_Large_2 | FedEx_Box_Large_1 | FedEx_Box_Large_2 | FedEx_Box_Medium_1 | FedEx_Box_Medium_2 | FedEx_Box_Small_1 | FedEx_Box_Small_2 | FedEx_Envelope | FedEx_Padded_Pak | FedEx_Pak_1 | FedEx_Pak_2 | FedEx_Tube | FedEx_XL_Pak | UPS_Box_10kg | UPS_Box_25kg | UPS_Express_Box | UPS_Express_Box_Large | UPS_Express_Box_Medium | UPS_Express_Box_Small | UPS_Express_Envelope | UPS_Express_Hard_Pak | UPS_Express_Legal_Envelope | UPS_Express_Pak | UPS_Express_Tube | UPS_Laboratory_Pak | UPS_Pad_Pak | UPS_Pallet | USPS_Card | USPS_Flat | USPS_FlatRateCardboardEnvelope | USPS_FlatRateEnvelope | USPS_FlatRateGiftCardEnvelope | USPS_FlatRateLegalEnvelope | USPS_FlatRatePaddedEnvelope | USPS_FlatRateWindowEnvelope | USPS_LargeFlatRateBoardGameBox | USPS_LargeFlatRateBox | USPS_Letter | USPS_MediumFlatRateBox1 | USPS_MediumFlatRateBox2 | USPS_RegionalRateBoxA1 | USPS_RegionalRateBoxA2 | USPS_RegionalRateBoxB1 | USPS_RegionalRateBoxB2 | USPS_RegionalRateBoxC | USPS_SmallFlatRateBox | USPS_SmallFlatRateEnvelope data CurrencyCode = AED | AFN | ALL | AMD | ANG | AOA | ARS | AUD | AWG | AZN | BAM | BBD | BDT | BGN | BHD | BIF | BMD | BND | BOB | BOV | BRL | BSD | BTN | BWP | BYR | BZD | CAD | CDF | CHE | CHF | CHW | CLF | CLP | CNY | COP | COU | CRC | CUC | CUP | CVE | CZK | DJF | DKK | DOP | DZD | EGP | ERN | ETB | EUR | FJD | FKP | GBP | GEL | GHS | GIP | GMD | GNF | GTQ | GYD | HKD | HNL | HRK | HTG | HUF | IDR | ILS | INR | IQD | IRR | ISK | JMD | JOD | JPY | KES | KGS | KHR | KMF | KPW | KRW | KWD | KYD | KZT | LAK | LBP | LKR | LRD | LSL | LYD | MAD | MDL | MGA | MKD | MMK | MNT | MOP | MRO | MUR | MVR | MWK | MXN | MXV | MYR | MZN | NAD | NGN | NIO | NOK | NPR | NZD | OMR | PAB | PEN | PGK | PHP | PKR | PLN | PYG | QAR | RON | RSD | RUB | RWF | SAR | SBD | SCR | SDG | SEK | SGD | SHP | SLL | SOS | SRD | SSP | STD | SYP | SZL | THB | TJS | TMT | TND | TOP | TRY | TTD | TWD | TZS | UAH | UGX | USD | USN | USS | UYI | UYU | UZS | VEF | VND | VUV | WST | XAF | XAG | XAU | XBA | XBB | XBC | XBD | XCD | XDR | XFU | XOF | XPD | XPF | XPT | XSU | XTS | XUA | XXX | YER | ZAR | ZMW
nlander/bazaari
src/Bazaari/Types.hs
bsd-3-clause
11,537
0
10
3,875
2,749
1,558
1,191
445
1
import Test.HUnit import Core.Partition import Data.Word (Word8) import Core.UTF8 import Data.List (sort) main :: IO () main = do runTestTT suite return () t_splitRange = "splitRange" ~: test [ -- 1 splitRange (Range '\0' '\10') ~=? ([Range '\0' '\10'], [], [], []) , splitRange (Range '\40' '\127') ~=? ([Range '\40' '\127'], [], [], []) -- 1, 2 , splitRange (Range '\20' '\128') ~=? ([Range '\20' '\127'], [Range '\128' '\128'], [], []) , splitRange (Range '\0' '\2047') ~=? ([Range '\0' '\127'], [Range '\128' '\2047'], [], []) -- 1, 2, 3 , splitRange (Range '\127' '\2048') ~=? ([Range '\127' '\127'], [Range '\128' '\2047'] ,[Range '\2048' '\2048'], []) , splitRange (Range '\63' '\55055') ~=? ([Range '\63' '\127'], [Range '\128' '\2047'] ,[Range '\2048' '\55055'], []) , splitRange (Range '\1' '\65535') ~=? ([Range '\1' '\127'], [Range '\128' '\2047'] ,[Range '\2048' '\65535'], []) -- 1, 2, 3, 4 , splitRange (Range '\15' '\65536') ~=? ([Range '\15' '\127'], [Range '\128' '\2047'] ,[Range '\2048' '\65535'], [Range '\65536' '\65536']) , splitRange (Range '\6' '\822522') ~=? ([Range '\6' '\127'], [Range '\128' '\2047'] ,[Range '\2048' '\65535'], [Range '\65536' '\822522']) , splitRange (Range '\127' '\1100000') ~=? ([Range '\127' '\127'], [Range '\128' '\2047'] ,[Range '\2048' '\65535'], [Range '\65536' '\1100000']) , splitRange (Range '\0' maxBound) ~=? ([Range '\0' '\127'], [Range '\128' '\2047'] ,[Range '\2048' '\65535'], [Range '\65536' '\1114111']) -- 2 , splitRange (Range '\128' '\128') ~=? ([], [Range '\128' '\128'], [], []) , splitRange (Range '\128' '\1222') ~=? ([], [Range '\128' '\1222'], [], []) , splitRange (Range '\147' '\2000') ~=? ([], [Range '\147' '\2000'], [], []) , splitRange (Range '\128' '\2047') ~=? ([], [Range '\128' '\2047'], [], []) , splitRange (Range '\1578' '\2047') ~=? ([], [Range '\1578' '\2047'], [], []) -- 2, 3 ] t_charToBytes = "charToBytes 1-4" ~: test [ -- 1 charToBytes1 '\0' ~=? [0] , charToBytes1 '\64' ~=? [64] , charToBytes1 '\127' ~=? [127] -- 2 , charToBytes2 '\128' ~=? [0xC2, 0x80] , charToBytes2 '\175' ~=? [0xC2, 0xAF] , charToBytes2 '\997' ~=? [0xCF, 0xA5] , charToBytes2 '\999' ~=? [0xCF, 0xA7] , charToBytes2 '\1253' ~=? [0xD3, 0xA5] , charToBytes2 '\1987' ~=? [0xDF, 0x83] , charToBytes2 '\2040' ~=? [0xDF, 0xB8] , charToBytes2 '\2047' ~=? [0xDF, 0xBF] -- 3 , charToBytes3 '\2048' ~=? [0xE0, 0xA0, 0x80] , charToBytes3 '\2049' ~=? [0xE0, 0xA0, 0x81] , charToBytes3 '\7052' ~=? [0xE1, 0xAE, 0x8C] , charToBytes3 '\16384' ~=? [0xE4, 0x80, 0x80] , charToBytes3 '\25467' ~=? [0xE6, 0x8D, 0xBB] , charToBytes3 '\32767' ~=? [0xE7, 0xBF, 0xBF] , charToBytes3 '\32768' ~=? [0xE8, 0x80, 0x80] , charToBytes3 '\59001' ~=? [0xEE, 0x99, 0xB9] , charToBytes3 '\65535' ~=? [0xEF, 0xBF, 0xBF] -- 4 , charToBytes4 '\65536' ~=? [0xF0, 0x90, 0x80, 0x80] , charToBytes4 '\175211' ~=? [0xF0, 0xAA, 0xB1, 0xAB] , charToBytes4 '\512301' ~=? [0xF1, 0xBD, 0x84, 0xAD] , charToBytes4 '\1014667' ~=? [0xF3, 0xB7, 0xAE, 0x8B] , charToBytes4 maxBound ~=? [0xF4, 0x8F, 0xBF, 0xBF] ] t_bytesToChar = "bytesToChar" ~: test [ -- bytesToChar is inverse of charToBytes 1-4. let chars = ['\0'..'\127'] in map (bytesToChar . charToBytes1) chars ~=? chars , let chars = ['\128'..'\2047'] in map (bytesToChar . charToBytes2) chars ~=? chars , let chars = ['\2048', '\2049', '\20543', '\31484', '\32768', '\45876' ,'\55456', '\65535'] in map (bytesToChar . charToBytes3) chars ~=? chars , let chars = ['\65536', '\65799', '\94234', '\175841', '\546448' ,'\745576', '\957416', '\1046036', maxBound] in map (bytesToChar . charToBytes4) chars ~=? chars ] t_convertRange = "t_convertRange" ~: test [ testRange '\0' '\0' , testRange '\0' '\33' , testRange '\65' '\65' , testRange '\65' '\66' , testRange '\0' '\128' , testRange '\65535' '\65536' , testRange '\547' '\1248' , testRange '\0' '\2048' , testRange '\1999' '\2508' , testRange '\32475' '\33000' , testRange '\48253' '\48255' , testRange '\65500' '\65800' , testRange '\1114011' '\1114111' , testRange '\1114111' maxBound ] where testRange lo hi = rangeToChars lo hi ~=? [lo..hi] rangeToChars lo hi = sort $ map bytesToChar $ concatMap sequenceToBytes $ convertRange (Range lo hi) where sequenceToBytes :: Sequence -> [[Word8]] sequenceToBytes [] = [[]] sequenceToBytes (Range a b:ranges) = concat [map (w:) (sequenceToBytes ranges) | w <- [a..b]] suite = test [ t_splitRange, t_charToBytes, t_bytesToChar, t_convertRange ]
radekm/crep
tests/UTF8.hs
bsd-3-clause
4,836
0
13
1,082
1,856
1,013
843
112
2
module Distribution.RefactorSpec (main, spec) where import Distribution.Refactor import Test.Hspec import Test.QuickCheck import Test.QuickCheck.Instances main :: IO () main = hspec spec spec :: Spec spec = do describe "someFunction" $ do it "should work fine" $ do property someFunction someFunction :: Bool -> Bool -> Property someFunction x y = x === y
athanclark/cabal-utils
test/Distribution/RefactorSpec.hs
bsd-3-clause
373
0
13
70
116
61
55
14
1
module Jerimum.PostgreSQL.Types.Boolean -- * CBOR codec ( boolEncoderV0 , boolDecoderV0 , encodeBool -- * Value constructors , fromBool ) where import qualified Codec.CBOR.Decoding as D import qualified Codec.CBOR.Encoding as E import Jerimum.PostgreSQL.Types import Jerimum.PostgreSQL.Types.Encoding v0 :: Version v0 = 0 encodeBool :: Maybe Bool -> E.Encoding encodeBool = encodeWithVersion v0 boolEncoderV0 boolEncoderV0 :: Bool -> E.Encoding boolEncoderV0 = E.encodeBool boolDecoderV0 :: D.Decoder s Bool boolDecoderV0 = D.decodeBool fromBool :: Maybe Bool -> Value fromBool = mkValue (ScalarType TBoolean) encodeBool
dgvncsz0f/nws
src/Jerimum/PostgreSQL/Types/Boolean.hs
bsd-3-clause
693
0
7
151
154
92
62
19
1
{-# LANGUAGE OverloadedStrings #-} module Subversion.Dump.Raw ( FieldMap , Entry(..) , readInt , readSvnDumpRaw ) where import Control.Applicative hiding (many) import Control.Monad import qualified Data.Attoparsec.Char8 as AC import Data.Attoparsec.Combinator import Data.Attoparsec.Lazy as AL import Data.ByteString as B hiding (map) import qualified Data.ByteString.Lazy as BL hiding (map) import qualified Data.List as L import Data.Maybe import Data.Word (Word8) import Prelude hiding (getContents) default (ByteString) type FieldMap = [(ByteString, ByteString)] data Entry = Entry { entryTags :: FieldMap , entryProps :: FieldMap , entryBody :: BL.ByteString } deriving Show readSvnDumpRaw :: BL.ByteString -> [Entry] readSvnDumpRaw dump = case parse parseHeader dump of Fail {} -> error "Stream is not a Subversion dump file" Done contents _ -> parseDumpFile contents parseHeader :: Parser ByteString parseHeader = string "SVN-fs-dump-format-version: 2\n\n" *> string "UUID: " *> takeWhile1 uuidMember <* newline <* newline -- Accept any hexadecimal character or '-' where uuidMember w = w == 45 || (w >= 48 && w <= 57) || (w >= 97 && w <= 102) parseDumpFile :: BL.ByteString -> [Entry] parseDumpFile contents = case parse parseEntry contents of --Fail _ _ y -> error y Fail {} -> [] Done contents' (entry, bodyLen) -> entry { entryBody = BL.take (fromIntegral bodyLen) contents' } : parseDumpFile (BL.drop (fromIntegral bodyLen) contents') -- Don't read the entry body here in the parser, rather let the caller extract -- it from the ByteString (which might be lazy, saving us from needlessly -- strictifying it here). parseEntry :: Parser (Entry, Int) parseEntry = do fields <- skipWhile (== 10) *> many1 parseTag <* newline props <- case L.lookup "Prop-content-length" fields of Nothing -> return [] Just _ -> manyTill parseProperty (try (string "PROPS-END\n")) return ( Entry { entryTags = fields , entryProps = props , entryBody = BL.empty } , fromMaybe 0 (readInt <$> L.lookup "Text-content-length" fields) ) parseTag :: Parser (ByteString, ByteString) parseTag = (,) <$> takeWhile1 fieldChar <* string ": " <*> takeWhile1 (/= 10) <* newline where fieldChar w = (w >= 97 && w <= 121) -- a-z || (w >= 65 && w <= 90) -- A-Z || w == 45 -- - || (w >= 48 && w <= 57) -- 0-9 parseProperty :: Parser (ByteString, ByteString) parseProperty = (,) <$> (string "K " *> getField <* newline) <*> (string "V " *> getField <* newline) -- Read a decimal integer followed by \n and 'take' that many bytes where getField = AC.decimal <* newline >>= AL.take newline :: Parser Word8 newline = word8 10 -- | Efficiently convert a ByteString of integers into an Int. -- -- >>> readInt (Data.ByteString.Char8.pack "12345") -- 12345 readInt :: ByteString -> Int readInt = B.foldl' addup 0 where addup acc x = acc * 10 + (fromIntegral x - 48) -- '0' -- SvnDump.hs ends here
jwiegley/svndump
src/Subversion/Dump/Raw.hs
bsd-3-clause
3,385
4
15
988
868
480
388
68
2
module LocalPrelude ( Bool(..) , Int , Integer , Rational , Float , Double , Char , String , Maybe(..) , Either(..) , undefined , error , fromInteger , fromRational , toRational , Show (..) , IO , map , concat , (++) , ($) -- , (.) , Num --(..) , Proxy (..) , Symbol , Nat , Constraint -- , module GHC.Exts -- , module Data.Kind -- , module GHC.TypeLits ) where import Prelude -- import Data.Kind import Data.Proxy import GHC.Exts import GHC.TypeLits
mikeizbicki/homoiconic
src/Homoiconic/Heterogeneous/LocalPrelude.hs
bsd-3-clause
586
0
5
220
132
92
40
31
0
{-# LANGUAGE NoImplicitPrelude #-} module Structure.Monadiclasses.Conquer ( Conquer(..), Unquer(..), Contity(..) ) where import Structure.Function import Structure.Unit class Conquer f where conquer :: f a conquer = undefined conquer' :: (Unit t) => (a -> t) -> f a conquer' = const $ conquer class Unquer f where -- 本来はここに書かれるべきだがGHCの警告に従い型クラスの構成要素から外す -- unquer :: (Unit t) => t -- unquer = undefined unquer' :: (Unit t) => f a -> (a -> t) unquer' = const $ const $ unit unquer :: (Unit unit) => unit unquer = unit class Contity f where --
Hexirp/monadiclasses
src/Structure/Monadiclasses/Conquer.hs
bsd-3-clause
734
0
10
218
182
104
78
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} #if MTL {-# OPTIONS_GHC -fno-warn-orphans #-} #endif module Control.Effect.Writer ( EffectWriter, Writer, runWriter, tell, listen, listens, pass, censor, stateWriter ) where import Control.Monad.Effect import Control.Arrow (second) #if !MIN_VERSION_base(4, 8, 0) import Data.Monoid (Monoid (..)) #endif import Control.Effect.State #ifdef MTL import Data.Type.Row import qualified Control.Monad.Writer.Class as W instance (Monoid w, Member (Writer w) l, Writer w ~ InstanceOf Writer l) => W.MonadWriter w (Effect l) where tell = tell listen = listen pass = pass #endif -- | An effect that allows accumulating output. data Writer w a where Tell :: w -> Writer w () type instance Is Writer f = IsWriter f type family IsWriter f where IsWriter (Writer w) = 'True IsWriter f = 'False class (Monoid w, MemberEffect Writer (Writer w) l) => EffectWriter w l instance (Monoid w, MemberEffect Writer (Writer w) l) => EffectWriter w l -- | Writes a value to the output. tell :: EffectWriter w l => w -> Effect l () tell = send . Tell -- | Executes a computation, and obtains the writer output. -- The writer output of the inner computation is still -- written to the writer output of the outer computation. listen :: EffectWriter w l => Effect l a -> Effect l (a, w) listen effect = do value@(_, output) <- intercept point bind effect tell output return value -- | Like `listen`, but the writer output is run through a function. listens :: EffectWriter w l => (w -> b) -> Effect l a -> Effect l (a, b) listens f = fmap (second f) . listen -- | Runs a computation that returns a value and a function, -- applies the function to the writer output, and then returns the value. pass :: EffectWriter w l => Effect l (a, w -> w) -> Effect l a pass effect = do ((x, f), l) <- listen effect tell (f l) return x -- | Applies a function to the writer output of a computation. censor :: EffectWriter w l => (w -> w) -> Effect l a -> Effect l a censor f effect = pass $ do a <- effect return (a, f) -- | Executes a writer computation which sends its output to a state effect. stateWriter :: (Monoid s, EffectState s l) => Effect (Writer s ':+ l) a -> Effect l a stateWriter = eliminate return (\(Tell l) k -> modify (mappend l) >> k ()) -- | Completely handles a writer effect. The writer value must be a `Monoid`. -- `mempty` is used as an initial value, and `mappend` is used to combine values. -- Returns the result of the computation and the final output value. runWriter :: Monoid w => Effect (Writer w ':+ l) a -> Effect l (a, w) runWriter = eliminate point bind point :: Monoid w => a -> Effect l (a, w) point x = return (x, mempty) bind :: Monoid w => Writer w a -> (a -> Effect l (b, w)) -> Effect l (b, w) bind (Tell l) k = second (mappend l) `fmap` k ()
YellPika/effin
src/Control/Effect/Writer.hs
bsd-3-clause
3,202
0
11
735
942
504
438
-1
-1
{-- snippet tuples --} a = ("Porpoise", "Grey") b = ("Table", "Oak") {-- /snippet tuples --} {-- snippet data --} data Cetacean = Cetacean String String data Furniture = Furniture String String c = Cetacean "Porpoise" "Grey" d = Furniture "Table" "Oak" {-- /snippet data --}
binesiyu/ifl
examples/ch03/Distinction.hs
mit
277
3
6
48
78
40
38
6
1
{- | Module : $Header$ Description : abstract syntax of VSE programs and dynamic logic Copyright : (c) C. Maeder, DFKI 2008 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable CASL extention to VSE programs and dynamic logic as described on page 4-7 (Sec 2.3.1, 2.5.2, 2.5.4, 2.6) of Bruno Langenstein's API description -} module VSE.As where import Data.Char import qualified Data.Map as Map import Control.Monad (foldM) import Common.AS_Annotation import Common.Id import Common.Doc import Common.DocUtils import Common.Result import Common.LibName import Common.Utils (number) import CASL.AS_Basic_CASL import CASL.ToDoc -- | input or output procedure parameter kind data Paramkind = In | Out deriving (Show, Eq, Ord) -- | a procedure parameter data Procparam = Procparam Paramkind SORT deriving (Show, Eq, Ord) -- | procedure or function declaration data Profile = Profile [Procparam] (Maybe SORT) deriving (Show, Eq, Ord) -- | further VSE signature entries data Sigentry = Procedure Id Profile Range deriving (Show, Eq) data Procdecls = Procdecls [Annoted Sigentry] Range deriving (Show, Eq) instance GetRange Procdecls where getRange (Procdecls _ r) = r -- | wrapper for positions data Ranged a = Ranged { unRanged :: a, range :: Range } deriving (Show, Eq, Ord) -- | attach a nullRange mkRanged :: a -> Ranged a mkRanged a = Ranged a nullRange -- | programs with ranges type Program = Ranged PlainProgram -- | programs based on restricted terms and formulas data PlainProgram = Abort | Skip | Assign VAR (TERM ()) | Call (FORMULA ()) -- ^ a procedure call as predication | Return (TERM ()) | Block [VAR_DECL] Program | Seq Program Program | If (FORMULA ()) Program Program | While (FORMULA ()) Program deriving (Show, Eq, Ord) -- | alternative variable declaration data VarDecl = VarDecl VAR SORT (Maybe (TERM ())) Range deriving Show toVarDecl :: [VAR_DECL] -> [VarDecl] toVarDecl = concatMap (\ (Var_decl vs s r) -> map (\ v -> VarDecl v s Nothing r) vs) addInits :: [VarDecl] -> Program -> ([VarDecl], Program) addInits vs p = case vs of vd@(VarDecl v s Nothing z) : r -> case unRanged p of Seq (Ranged (Assign av t) _) p2 | v == av -> let (rs, q) = addInits r p2 in (VarDecl v s (Just t) z : rs, q) _ -> let (rs, q) = addInits r p in (vd : rs, q) _ -> (vs, p) -- | extend CASL formulas by box or diamond formulas and defprocs data VSEforms = Dlformula BoxOrDiamond Program Sentence | Defprocs [Defproc] | RestrictedConstraint [Constraint] (Map.Map SORT Id) Bool deriving (Show, Eq, Ord) type Dlformula = Ranged VSEforms type Sentence = FORMULA Dlformula -- | box or diamond indicator data BoxOrDiamond = Box | Diamond deriving (Show, Eq, Ord) data ProcKind = Proc | Func deriving (Show, Eq, Ord) -- | procedure definitions as basic items becoming sentences data Defproc = Defproc ProcKind Id [VAR] Program Range deriving (Show, Eq, Ord) data Procs = Procs { procsMap :: Map.Map Id Profile } deriving (Show, Eq, Ord) emptyProcs :: Procs emptyProcs = Procs Map.empty unionProcs :: Procs -> Procs -> Result Procs unionProcs (Procs m1) (Procs m2) = fmap Procs $ foldM (\ m (k, v) -> case Map.lookup k m1 of Nothing -> return $ Map.insert k v m Just w -> if w == v then return m else mkError "different union profiles for" k) m1 $ Map.toList m2 interProcs :: Procs -> Procs -> Result Procs interProcs (Procs m1) (Procs m2) = fmap Procs $ foldM (\ m (k, v) -> case Map.lookup k m1 of Nothing -> return m Just w -> if w == v then return $ Map.insert k v m else mkError "different intersection profiles for" k) Map.empty $ Map.toList m2 diffProcs :: Procs -> Procs -> Procs diffProcs (Procs m1) (Procs m2) = Procs $ Map.difference m1 m2 isSubProcsMap :: Procs -> Procs -> Bool isSubProcsMap (Procs m1) (Procs m2) = Map.isSubmapOfBy (==) m1 m2 -- * Pretty instances instance Pretty Profile where pretty (Profile ps ores) = fsep [ ppWithCommas ps , case ores of Nothing -> empty Just s -> funArrow <+> idDoc s] instance Pretty Sigentry where pretty (Procedure i p _) = fsep [idDoc i, colon <+> pretty p] instance Pretty Procdecls where pretty (Procdecls l _) = if null l then empty else fsep [ text $ "PROCEDURE" ++ case l of [_] -> "" _ -> "S" , semiAnnos pretty l ] instance Pretty Procparam where pretty (Procparam m s) = text (map toUpper $ show m) <+> idDoc s block :: Doc -> Doc block d = sep [text "BEGIN", d, text "END"] prettyProcKind :: ProcKind -> Doc prettyProcKind k = text $ case k of Proc -> "PROCEDURE" Func -> "FUNCTION" assign :: Doc assign = text ":=" instance Pretty Defproc where pretty (Defproc pk p ps pr _) = vcat [ prettyProcKind pk <+> idDoc p <> parens (ppWithCommas ps) , pretty pr ] instance Pretty a => Pretty (Ranged a) where pretty (Ranged a _) = pretty a instance GetRange (Ranged a) where getRange (Ranged _ r) = r instance FormExtension a => FormExtension (Ranged a) where isQuantifierLike (Ranged a _) = isQuantifierLike a instance Pretty VarDecl where pretty (VarDecl v s mt _) = sidDoc v <+> colon <+> idDoc s <+> case mt of Nothing -> empty Just t -> assign <+> pretty t instance Pretty PlainProgram where pretty prg = case prg of Abort -> text "ABORT" Skip -> text "SKIP" Assign v t -> pretty v <+> assign <+> pretty t Call f -> pretty f Return t -> text "RETURN" <+> pretty t Block vs p -> if null vs then block $ pretty p else let (vds, q) = addInits (toVarDecl vs) p in sep [ text "DECLARE" , ppWithCommas vds <> semi , pretty q ] Seq p1 p2 -> vcat [pretty p1 <> semi, pretty p2] If f t e -> sep [ text "IF" <+> pretty f , text "THEN" <+> pretty t , case e of Ranged Skip _ -> empty _ -> text "ELSE" <+> pretty e , text "FI" ] While f p -> sep [ text "WHILE" <+> pretty f , text "DO" <+> pretty p , text "OD" ] instance FormExtension VSEforms instance GetRange VSEforms instance Pretty VSEforms where pretty v = case v of Dlformula b p f -> let d = pretty p in sep [ case b of Box -> text "[:" <> d <> text ":]" Diamond -> text "<:" <> d <> text ":>" , pretty f ] Defprocs ps -> prettyProcdefs ps RestrictedConstraint constrs restr _b -> let l = recoverType constrs in fsep [ text "true %[generated type" , semiAnnos (printRestrTypedecl restr) l , text "]%"] genSortName :: String -> SORT -> Id genSortName str s@(Id ts cs ps) = case cs of [] -> genName $ str ++ show s i : r | isQualName s -> Id ts (genSortName str i : r) ps _ -> Id [genToken $ str ++ show (Id ts [] ps)] cs ps {- since such names are generated out of sentences, the qualification of the sort may be misleading -} gnUniformName :: SORT -> Id gnUniformName = genSortName "uniform_" . unQualName gnRestrName :: SORT -> Id gnRestrName = genSortName "restr_" gnEqName :: SORT -> Id gnEqName = genSortName "eq_" genVars :: [SORT] -> [(Token, SORT)] genVars = map (\ (t, n) -> (genNumVar "x" n, t)) . number xVar :: Token xVar = genToken "x" yVar :: Token yVar = genToken "y" printRestrTypedecl :: Map.Map SORT Id -> DATATYPE_DECL -> Doc printRestrTypedecl restr (Datatype_decl s a r) = let pa = printAnnoted printALTERNATIVE in case a of [] -> printRestrTypedecl restr (Datatype_decl s [emptyAnno $ Subsorts [s] r] r) h : t -> sep [idLabelDoc s, colon <> colon <> sep ((equals <+> pa h) : map ((bar <+>) . pa) t), text "restricted by", pretty $ Map.findWithDefault (gnRestrName s) s restr] prettyProcdefs :: [Defproc] -> Doc prettyProcdefs ps = vcat [ text "DEFPROCS" , vsep . punctuate semi $ map pretty ps , text "DEFPROCSEND" ] instance Pretty Procs where pretty (Procs m) = pretty $ Procdecls (map (\ (i, p) -> emptyAnno $ Procedure i p nullRange) $ Map.toList m) nullRange
nevrenato/HetsAlloy
VSE/As.hs
gpl-2.0
8,212
2
20
2,041
2,989
1,524
1,465
194
3
{- | Module : $Header$ Copyright : Francisc-Nicolae Bungiu, Jacobs University Bremen License : GPLv2 or higher, see LICENSE.txt RDF signature and sentences -} module RDF.Sign where import RDF.AS import Common.Result import qualified Data.Set as Set data Sign = Sign { subjects :: Set.Set Term , predicates :: Set.Set Term , objects :: Set.Set Term } deriving (Show, Eq, Ord) emptySign :: Sign emptySign = Sign { subjects = Set.empty , predicates = Set.empty , objects = Set.empty } diffSig :: Sign -> Sign -> Sign diffSig a b = a { subjects = subjects a `Set.difference` subjects b , predicates = predicates a `Set.difference` predicates b , objects = objects a `Set.difference` objects b } addSign :: Sign -> Sign -> Sign addSign toIns totalSign = totalSign { subjects = Set.union (subjects totalSign) (subjects toIns) , predicates = Set.union (predicates totalSign) (predicates toIns) , objects = Set.union (objects totalSign) (objects toIns) } isSubSign :: Sign -> Sign -> Bool isSubSign a b = Set.isSubsetOf (subjects a) (subjects b) && Set.isSubsetOf (predicates a) (predicates b) && Set.isSubsetOf (objects a) (objects b) uniteSign :: Sign -> Sign -> Result Sign uniteSign s1 s2 = return $ addSign s1 s2 symOf :: Sign -> Set.Set RDFEntity symOf s = Set.unions [ Set.map (RDFEntity SubjectEntity) $ subjects s , Set.map (RDFEntity PredicateEntity) $ predicates s , Set.map (RDFEntity ObjectEntity) $ objects s ]
nevrenato/HetsAlloy
RDF/Sign.hs
gpl-2.0
1,527
0
10
340
516
271
245
36
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.IAM.UpdateSigningCertificate -- Copyright : (c) 2013-2014 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) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Changes the status of the specified signing certificate from active to -- disabled, or vice versa. This action can be used to disable a user's signing -- certificate as part of a certificate rotation work flow. -- -- If the 'UserName' field is not specified, the UserName is determined -- implicitly based on the AWS access key ID used to sign the request. Because -- this action works for access keys under the AWS account, you can use this -- action to manage root credentials even if the AWS account has no associated -- users. -- -- For information about rotating certificates, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/ManagingCredentials.html Managing Keys andCertificates> in the /Using IAM/ guide. -- -- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateSigningCertificate.html> module Network.AWS.IAM.UpdateSigningCertificate ( -- * Request UpdateSigningCertificate -- ** Request constructor , updateSigningCertificate -- ** Request lenses , uscCertificateId , uscStatus , uscUserName -- * Response , UpdateSigningCertificateResponse -- ** Response constructor , updateSigningCertificateResponse ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.IAM.Types import qualified GHC.Exts data UpdateSigningCertificate = UpdateSigningCertificate { _uscCertificateId :: Text , _uscStatus :: StatusType , _uscUserName :: Maybe Text } deriving (Eq, Read, Show) -- | 'UpdateSigningCertificate' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'uscCertificateId' @::@ 'Text' -- -- * 'uscStatus' @::@ 'StatusType' -- -- * 'uscUserName' @::@ 'Maybe' 'Text' -- updateSigningCertificate :: Text -- ^ 'uscCertificateId' -> StatusType -- ^ 'uscStatus' -> UpdateSigningCertificate updateSigningCertificate p1 p2 = UpdateSigningCertificate { _uscCertificateId = p1 , _uscStatus = p2 , _uscUserName = Nothing } -- | The ID of the signing certificate you want to update. uscCertificateId :: Lens' UpdateSigningCertificate Text uscCertificateId = lens _uscCertificateId (\s a -> s { _uscCertificateId = a }) -- | The status you want to assign to the certificate. 'Active' means the -- certificate can be used for API calls to AWS, while 'Inactive' means the -- certificate cannot be used. uscStatus :: Lens' UpdateSigningCertificate StatusType uscStatus = lens _uscStatus (\s a -> s { _uscStatus = a }) -- | The name of the user the signing certificate belongs to. uscUserName :: Lens' UpdateSigningCertificate (Maybe Text) uscUserName = lens _uscUserName (\s a -> s { _uscUserName = a }) data UpdateSigningCertificateResponse = UpdateSigningCertificateResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'UpdateSigningCertificateResponse' constructor. updateSigningCertificateResponse :: UpdateSigningCertificateResponse updateSigningCertificateResponse = UpdateSigningCertificateResponse instance ToPath UpdateSigningCertificate where toPath = const "/" instance ToQuery UpdateSigningCertificate where toQuery UpdateSigningCertificate{..} = mconcat [ "CertificateId" =? _uscCertificateId , "Status" =? _uscStatus , "UserName" =? _uscUserName ] instance ToHeaders UpdateSigningCertificate instance AWSRequest UpdateSigningCertificate where type Sv UpdateSigningCertificate = IAM type Rs UpdateSigningCertificate = UpdateSigningCertificateResponse request = post "UpdateSigningCertificate" response = nullResponse UpdateSigningCertificateResponse
kim/amazonka
amazonka-iam/gen/Network/AWS/IAM/UpdateSigningCertificate.hs
mpl-2.0
4,726
0
9
971
473
292
181
58
1
{-# LANGUAGE BangPatterns #-} {-| Monitoring daemon backend This module holds implements the querying of the monitoring daemons for dynamic utilisation data. -} {- Copyright (C) 2015 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.HTools.Backend.MonD ( queryAllMonDDCs , pMonDData , Report(..) , DataCollector , dName , fromCurl , mkReport , totalCPUCollector , xenCPUCollector , kvmRSSCollector , scaleMemoryWeight , useInstanceRSSData ) where import Control.Monad import Control.Monad.Writer import qualified Data.List as L import qualified Data.IntMap as IntMap import qualified Data.Map as Map import Data.Maybe (catMaybes, mapMaybe) import qualified Data.Set as Set import Network.Curl import qualified Text.JSON as J import Ganeti.BasicTypes import qualified Ganeti.Constants as C import Ganeti.Cpu.Types import qualified Ganeti.DataCollectors.CPUload as CPUload import qualified Ganeti.DataCollectors.KvmRSS as KvmRSS import qualified Ganeti.DataCollectors.XenCpuLoad as XenCpuLoad import Ganeti.DataCollectors.Types ( DCReport, DCCategory , dcReportData, dcReportName , getCategoryName ) import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Instance as Instance import Ganeti.HTools.Loader (ClusterData(..)) import Ganeti.HTools.Types import Ganeti.HTools.CLI import Ganeti.JSON (fromJVal, tryFromObj, JSRecord, loadJSArray, maybeParseMap) import Ganeti.Logging.Lifted (logWarning) import Ganeti.Utils (exitIfBad) -- * General definitions -- | The actual data types for MonD's Data Collectors. data Report = CPUavgloadReport CPUavgload | InstanceCpuReport (Map.Map String Double) | InstanceRSSReport (Map.Map String Double) -- | Type describing a data collector basic information. data DataCollector = DataCollector { dName :: String -- ^ Name of the data collector , dCategory :: Maybe DCCategory -- ^ The name of the category , dMkReport :: DCReport -> Maybe Report -- ^ How to parse a monitor report , dUse :: [(Node.Node, Report)] -> (Node.List, Instance.List) -> Result (Node.List, Instance.List) -- ^ How the collector reports are to be used to bring dynamic -- data into a cluster } -- * Node-total CPU load average data collector -- | Parse a DCReport for the node-total CPU collector. mkCpuReport :: DCReport -> Maybe Report mkCpuReport dcr = case fromJVal (dcReportData dcr) :: Result CPUavgload of Ok cav -> Just $ CPUavgloadReport cav Bad _ -> Nothing -- | Take reports of node CPU values and update a node accordingly. updateNodeCpuFromReport :: (Node.Node, Report) -> Node.Node updateNodeCpuFromReport (node, CPUavgloadReport cav) = let ct = cavCpuTotal cav du = Node.utilLoad node du' = du {cpuWeight = ct} in node { Node.utilLoad = du' } updateNodeCpuFromReport (node, _) = node -- | Update the instance CPU-utilization data, asuming that each virtual -- CPU contributes equally to the node CPU load. updateCpuUtilDataFromNode :: Instance.List -> Node.Node -> Instance.List updateCpuUtilDataFromNode il node = let ct = cpuWeight (Node.utilLoad node) n_uCpu = Node.uCpu node upd inst = if Node.idx node == Instance.pNode inst then let i_vcpus = Instance.vcpus inst i_util = ct / fromIntegral n_uCpu * fromIntegral i_vcpus i_du = Instance.util inst i_du' = i_du {cpuWeight = i_util} in inst {Instance.util = i_du'} else inst in Container.map upd il -- | Update cluster data from node CPU load reports. useNodeTotalCPU :: [(Node.Node, Report)] -> (Node.List, Instance.List) -> Result (Node.List, Instance.List) useNodeTotalCPU reports (nl, il) = let newnodes = map updateNodeCpuFromReport reports il' = foldl updateCpuUtilDataFromNode il newnodes nl' = zip (Container.keys nl) newnodes in return (Container.fromList nl', il') -- | The node-total CPU collector. totalCPUCollector :: DataCollector totalCPUCollector = DataCollector { dName = CPUload.dcName , dCategory = CPUload.dcCategory , dMkReport = mkCpuReport , dUse = useNodeTotalCPU } -- * Xen instance CPU-usage collector -- | Parse results of the Xen-Cpu-load data collector. mkXenCpuReport :: DCReport -> Maybe Report mkXenCpuReport = liftM InstanceCpuReport . maybeParseMap . dcReportData -- | Update cluster data based on the per-instance CPU usage -- reports useInstanceCpuData :: [(Node.Node, Report)] -> (Node.List, Instance.List) -> Result (Node.List, Instance.List) useInstanceCpuData reports (nl, il) = do let toMap (InstanceCpuReport m) = Just m toMap _ = Nothing let usage = Map.unions $ mapMaybe (toMap . snd) reports missingData = (Set.fromList . map Instance.name $ IntMap.elems il) Set.\\ Map.keysSet usage unless (Set.null missingData) . Bad . (++) "No CPU information available for " . show $ Set.elems missingData let updateInstance inst = let cpu = Map.lookup (Instance.name inst) usage dynU = Instance.util inst dynU' = maybe dynU (\c -> dynU { cpuWeight = c }) cpu in inst { Instance.util = dynU' } let il' = IntMap.map updateInstance il let updateNode node = let cpu = sum . map (\ idx -> maybe 0 (cpuWeight . Instance.util) $ IntMap.lookup idx il') $ Node.pList node dynU = Node.utilLoad node dynU' = dynU { cpuWeight = cpu } in node { Node.utilLoad = dynU' } let nl' = IntMap.map updateNode nl return (nl', il') -- | Collector for per-instance CPU data as observed by Xen xenCPUCollector :: DataCollector xenCPUCollector = DataCollector { dName = XenCpuLoad.dcName , dCategory = XenCpuLoad.dcCategory , dMkReport = mkXenCpuReport , dUse = useInstanceCpuData } -- * kvm instance RSS collector -- | Parse results of the kvm instance RSS data Collector mkKvmRSSReport :: DCReport -> Maybe Report mkKvmRSSReport = liftM InstanceRSSReport . maybeParseMap . dcReportData -- | Conversion constant from htools' internal memory unit, -- which is MiB to RSS unit, which reported in pages (of 4kiB -- each). pagesPerMiB :: Double pagesPerMiB = 256.0 -- | Update cluster data based on per-instance RSS data. -- Also set the node's memoy util pool correctly. Our unit -- of memory usage is pages; there are 256 pages per MiB -- of node memory not used by the node itself. useInstanceRSSData :: [(Node.Node, Report)] -> (Node.List, Instance.List) -> Result (Node.List, Instance.List) useInstanceRSSData reports (nl, il) = do let toMap (InstanceRSSReport m) = Just m toMap _ = Nothing let usage = Map.unions $ mapMaybe (toMap . snd) reports missingData = (Set.fromList . map Instance.name $ IntMap.elems il) Set.\\ Map.keysSet usage unless (Set.null missingData) . Bad . (++) "No RSS information available for " . show $ Set.elems missingData let updateInstance inst = let mem = Map.lookup (Instance.name inst) usage dynU = Instance.util inst dynU' = maybe dynU (\m -> dynU { memWeight = m }) mem in inst { Instance.util = dynU' } let il' = IntMap.map updateInstance il let updateNode node = let mem = sum . map (\ idx -> maybe 0 (memWeight . Instance.util) $ IntMap.lookup idx il') $ Node.pList node dynU = Node.utilLoad node dynU' = dynU { memWeight = mem } pool = Node.utilPool node nodePages = (Node.tMem node - fromIntegral (Node.nMem node)) * pagesPerMiB pool' = pool { memWeight = nodePages } in node { Node.utilLoad = dynU', Node.utilPool = pool' } let nl' = IntMap.map updateNode nl return (nl', il') -- | Update cluster data based on the per-instance CPU usage kvmRSSCollector :: DataCollector kvmRSSCollector = DataCollector { dName = KvmRSS.dcName , dCategory = KvmRSS.dcCategory , dMkReport = mkKvmRSSReport , dUse = useInstanceRSSData } -- | Scale the importance of the memory weight in dynamic utilisation, -- by multiplying the usage with the given factor. Note that the underlying -- model for dynamic utilisation is that they are reported in arbitrary units. scaleMemoryWeight :: Double -> (Node.List, Instance.List) -> (Node.List, Instance.List) scaleMemoryWeight f (nl, il) = let updateInst inst = let dynU = Instance.util inst dynU' = dynU { memWeight = f * memWeight dynU} in inst { Instance.util = dynU' } updateNode node = let dynU = Node.utilLoad node dynU' = dynU { memWeight = f * memWeight dynU} in node { Node.utilLoad = dynU' } in (IntMap.map updateNode nl, IntMap.map updateInst il) -- * Collector choice -- | The list of Data Collectors used by hail and hbal. collectors :: Options -> [DataCollector] collectors opts | optIgnoreDynu opts = [] | otherwise = (if optMonDXen opts then [ xenCPUCollector ] else [ totalCPUCollector ] ) ++ [ kvmRSSCollector | optMonDKvmRSS opts ] -- * Querying infrastructure -- | Return the data from correct combination of a Data Collector -- and a DCReport. mkReport :: DataCollector -> Maybe DCReport -> Maybe Report mkReport dc = (>>= dMkReport dc) -- | MonDs Data parsed by a mock file. Representing (node name, list of reports -- produced by MonDs Data Collectors). type MonDData = (String, [DCReport]) -- | A map storing MonDs data. type MapMonDData = Map.Map String [DCReport] -- | Get data report for the specified Data Collector and Node from the map. fromFile :: DataCollector -> Node.Node -> MapMonDData -> Maybe DCReport fromFile dc node m = let matchDCName dcr = dName dc == dcReportName dcr in maybe Nothing (L.find matchDCName) $ Map.lookup (Node.name node) m -- | Get Category Name. getDCCName :: Maybe DCCategory -> String getDCCName dcc = case dcc of Nothing -> "default" Just c -> getCategoryName c -- | Prepare url to query a single collector. prepareUrl :: DataCollector -> Node.Node -> URLString prepareUrl dc node = Node.name node ++ ":" ++ show C.defaultMondPort ++ "/" ++ show C.mondLatestApiVersion ++ "/report/" ++ getDCCName (dCategory dc) ++ "/" ++ dName dc -- | Query a specified MonD for a Data Collector. fromCurl :: DataCollector -> Node.Node -> IO (Maybe DCReport) fromCurl dc node = do (code, !body) <- curlGetString (prepareUrl dc node) [] case code of CurlOK -> case J.decodeStrict body :: J.Result DCReport of J.Ok r -> return $ Just r J.Error _ -> return Nothing _ -> do logWarning $ "Failed to contact node's " ++ Node.name node ++ " MonD for DC " ++ dName dc return Nothing -- | Parse a node's JSON record. pMonDN :: JSRecord -> Result MonDData pMonDN a = do node <- tryFromObj "Parsing node's name" a "node" reports <- tryFromObj "Parsing node's reports" a "reports" return (node, reports) -- | Parse MonD data file contents. pMonDData :: String -> Result [MonDData] pMonDData input = loadJSArray "Parsing MonD's answer" input >>= mapM (pMonDN . J.fromJSObject) -- | Query a single MonD for a single Data Collector. queryAMonD :: Maybe MapMonDData -> DataCollector -> Node.Node -> IO (Maybe Report) queryAMonD m dc node = liftM (mkReport dc) $ case m of Nothing -> fromCurl dc node Just m' -> return $ fromFile dc node m' -- | Query all MonDs for a single Data Collector. Return the updated -- cluster, as well as a bit inidicating wether the collector succeeded. queryAllMonDs :: Maybe MapMonDData -> (Node.List, Instance.List) -> DataCollector -> WriterT All IO (Node.List, Instance.List) queryAllMonDs m (nl, il) dc = do elems <- liftIO $ mapM (queryAMonD m dc) (Container.elems nl) let elems' = catMaybes elems if length elems == length elems' then let results = zip (Container.elems nl) elems' in case dUse dc results (nl, il) of Ok (nl', il') -> return (nl', il') Bad s -> do logWarning s tell $ All False return (nl, il) else do logWarning $ "Didn't receive an answer by all MonDs, " ++ dName dc ++ "'s data will be ignored." tell $ All False return (nl,il) -- | Query all MonDs for all Data Collector. Return the cluster enriched -- by dynamic data, as well as a bit indicating wether all collectors -- could be queried successfully. queryAllMonDDCs :: ClusterData -> Options -> WriterT All IO ClusterData queryAllMonDDCs cdata opts = do map_mDD <- case optMonDFile opts of Nothing -> return Nothing Just fp -> do monDData_contents <- liftIO $ readFile fp monDData <- liftIO . exitIfBad "can't parse MonD data" . pMonDData $ monDData_contents return . Just $ Map.fromList monDData let (ClusterData _ nl il _ _) = cdata (nl', il') <- foldM (queryAllMonDs map_mDD) (nl, il) (collectors opts) return $ cdata {cdNodes = nl', cdInstances = il'}
andir/ganeti
src/Ganeti/HTools/Backend/MonD.hs
bsd-2-clause
15,106
0
23
3,927
3,396
1,799
1,597
262
3
{-# OPTIONS_GHC -fno-cse #-} {-# OPTIONS_HADDOCK hide #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GLU.ErrorsInternal -- Copyright : (c) Sven Panne 2002-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- This is a purely internal module corresponding to some parts of section 2.5 -- (GL Errors) of the OpenGL 2.1 specs and chapter 8 (Errors) of the GLU specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GLU.ErrorsInternal ( Error(..), ErrorCategory(..), getErrors, recordErrorCode, recordInvalidEnum, recordInvalidValue, recordOutOfMemory ) where import Data.IORef ( IORef, newIORef, readIORef, writeIORef ) import Foreign.C.String ( peekCString ) import Foreign.Ptr ( castPtr ) import Graphics.Rendering.GLU.Raw import Graphics.Rendering.OpenGL.Raw import System.IO.Unsafe ( unsafePerformIO ) -------------------------------------------------------------------------------- -- | GL\/GLU errors consist of a general error category and a description of -- what went wrong. data Error = Error ErrorCategory String deriving ( Eq, Ord, Show ) -------------------------------------------------------------------------------- -- | General GL\/GLU error categories data ErrorCategory = InvalidEnum | InvalidValue | InvalidOperation | InvalidFramebufferOperation | OutOfMemory | StackOverflow | StackUnderflow | TableTooLarge | TesselatorError | NURBSError deriving ( Eq, Ord, Show ) unmarshalErrorCategory :: GLenum -> ErrorCategory unmarshalErrorCategory c | isInvalidEnum c = InvalidEnum | isInvalidValue c = InvalidValue | isInvalidOperation c = InvalidOperation | isInvalidFramebufferOperation c = InvalidFramebufferOperation | isOutOfMemory c = OutOfMemory | isStackOverflow c = StackOverflow | isStackUnderflow c = StackUnderflow | isTableTooLarge c = TableTooLarge | isTesselatorError c = TesselatorError | isNURBSError c = NURBSError | otherwise = error "unmarshalErrorCategory" isInvalidEnum :: GLenum -> Bool isInvalidEnum c = c == gl_INVALID_ENUM || c == glu_INVALID_ENUM isInvalidValue :: GLenum -> Bool isInvalidValue c = c == gl_INVALID_VALUE || c == glu_INVALID_VALUE isInvalidOperation :: GLenum -> Bool isInvalidOperation c = c == gl_INVALID_OPERATION || c == glu_INVALID_OPERATION isInvalidFramebufferOperation :: GLenum -> Bool isInvalidFramebufferOperation c = c == gl_INVALID_FRAMEBUFFER_OPERATION isOutOfMemory :: GLenum -> Bool isOutOfMemory c = c == gl_OUT_OF_MEMORY || c == glu_OUT_OF_MEMORY isStackOverflow :: GLenum -> Bool isStackOverflow c = c == gl_STACK_OVERFLOW isStackUnderflow :: GLenum -> Bool isStackUnderflow c = c == gl_STACK_UNDERFLOW isTableTooLarge :: GLenum -> Bool isTableTooLarge c = c == gl_TABLE_TOO_LARGE isTesselatorError :: GLenum -> Bool isTesselatorError c = glu_TESS_ERROR1 <= c && c <= glu_TESS_ERROR8 isNURBSError :: GLenum -> Bool isNURBSError c = glu_NURBS_ERROR1 <= c && c <= glu_NURBS_ERROR37 -------------------------------------------------------------------------------- -- The returned error string is statically allocated, so peekCString -- does the right thing here. No malloc/free necessary here. makeError :: GLenum -> IO Error makeError e = do let category = unmarshalErrorCategory e ptr <- gluErrorString e description <- peekCString (castPtr ptr) return $ Error category description -------------------------------------------------------------------------------- -- This seems to be a common Haskell hack nowadays: A plain old global variable -- with an associated getter and mutator. Perhaps some language/library support -- is needed? {-# NOINLINE theRecordedErrors #-} theRecordedErrors :: IORef ([GLenum],Bool) theRecordedErrors = unsafePerformIO (newIORef ([], True)) getRecordedErrors :: IO ([GLenum],Bool) getRecordedErrors = readIORef theRecordedErrors setRecordedErrors :: ([GLenum],Bool) -> IO () setRecordedErrors = writeIORef theRecordedErrors -------------------------------------------------------------------------------- getGLErrors :: IO [GLenum] getGLErrors = getGLErrorsAux [] where getGLErrorsAux acc = do errorCode <- glGetError if isError errorCode then getGLErrorsAux (errorCode : acc) else return $ reverse acc isError :: GLenum -> Bool isError = (/= gl_NO_ERROR) -------------------------------------------------------------------------------- getErrors :: IO [Error] getErrors = do es <- getErrorCodesAux (const ([], True)) mapM makeError es recordErrorCode :: GLenum -> IO () recordErrorCode e = do -- We don't need the return value because this calls setRecordedErrors _ <- getErrorCodesAux (\es -> (if null es then [e] else [], False)) return () recordInvalidEnum :: IO () recordInvalidEnum = recordErrorCode gl_INVALID_ENUM recordInvalidValue :: IO () recordInvalidValue = recordErrorCode gl_INVALID_VALUE recordOutOfMemory :: IO () recordOutOfMemory = recordErrorCode gl_OUT_OF_MEMORY -- ToDo: Make this thread-safe getErrorCodesAux :: ([GLenum] -> ([GLenum],Bool)) -> IO [GLenum] getErrorCodesAux f = do (recordedErrors, useGLErrors) <- getRecordedErrors glErrors <- getGLErrors let es = if useGLErrors then recordedErrors ++ glErrors else recordedErrors setRecordedErrors (f es) return es
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GLU/ErrorsInternal.hs
bsd-3-clause
5,582
0
13
905
1,142
611
531
101
2
{-| Cluster information printer. -} {- Copyright (C) 2012 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.HTools.Program.Hinfo ( main , options , arguments ) where import Control.Monad import Data.List import System.IO import Text.Printf (printf) import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Cluster as Cluster import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Group as Group import qualified Ganeti.HTools.Instance as Instance import Ganeti.Common import Ganeti.HTools.CLI import Ganeti.HTools.ExtLoader import Ganeti.HTools.Loader import Ganeti.Utils -- | Options list and functions. options :: IO [OptType] options = do luxi <- oLuxiSocket return [ oPrintNodes , oPrintInsts , oDataFile , oRapiMaster , luxi , oIAllocSrc , oVerbose , oQuiet , oOfflineNode ] -- | The list of arguments supported by the program. arguments :: [ArgCompletion] arguments = [] -- | Group information data-type. data GroupInfo = GroupInfo { giName :: String , giNodeCount :: Int , giInstCount :: Int , giBadNodes :: Int , giBadInsts :: Int , giN1Status :: Bool , giScore :: Double } -- | Node group statistics. calcGroupInfo :: Group.Group -> Node.List -> Instance.List -> GroupInfo calcGroupInfo g nl il = let nl_size = Container.size nl il_size = Container.size il (bad_nodes, bad_instances) = Cluster.computeBadItems nl il bn_size = length bad_nodes bi_size = length bad_instances n1h = bn_size == 0 score = Cluster.compCV nl in GroupInfo (Group.name g) nl_size il_size bn_size bi_size n1h score -- | Helper to format one group row result. groupRowFormatHelper :: GroupInfo -> [String] groupRowFormatHelper gi = [ giName gi , printf "%d" $ giNodeCount gi , printf "%d" $ giInstCount gi , printf "%d" $ giBadNodes gi , printf "%d" $ giBadInsts gi , show $ giN1Status gi , printf "%.8f" $ giScore gi ] -- | Print node group information. showGroupInfo :: Int -> Group.List -> Node.List -> Instance.List -> IO () showGroupInfo verbose gl nl il = do let cgrs = map (\(gdx, (gnl, gil)) -> calcGroupInfo (Container.find gdx gl) gnl gil) $ Cluster.splitCluster nl il cn1h = all giN1Status cgrs grs = map groupRowFormatHelper cgrs header = ["Group", "Nodes", "Instances", "Bad_Nodes", "Bad_Instances", "N+1", "Score"] when (verbose > 1) $ printf "Node group information:\n%s" (printTable " " header grs [False, True, True, True, True, False, True]) printf "Cluster is N+1 %s\n" $ if cn1h then "happy" else "unhappy" -- | Gather and print split instances. splitInstancesInfo :: Int -> Node.List -> Instance.List -> IO () splitInstancesInfo verbose nl il = do let split_insts = Cluster.findSplitInstances nl il if null split_insts then when (verbose > 1) $ putStrLn "No split instances found"::IO () else do putStrLn "Found instances belonging to multiple node groups:" mapM_ (\i -> hPutStrLn stderr $ " " ++ Instance.name i) split_insts -- | Print common (interesting) information. commonInfo :: Int -> Group.List -> Node.List -> Instance.List -> IO () commonInfo verbose gl nl il = do when (Container.null il && verbose > 1) $ printf "Cluster is empty.\n"::IO () let nl_size = Container.size nl il_size = Container.size il gl_size = Container.size gl printf "Loaded %d %s, %d %s, %d %s\n" nl_size (plural nl_size "node" "nodes") il_size (plural il_size "instance" "instances") gl_size (plural gl_size "node group" "node groups")::IO () let csf = commonSuffix nl il when (not (null csf) && verbose > 2) $ printf "Note: Stripping common suffix of '%s' from names\n" csf -- | Main function. main :: Options -> [String] -> IO () main opts args = do unless (null args) $ exitErr "This program doesn't take any arguments." let verbose = optVerbose opts shownodes = optShowNodes opts showinsts = optShowInsts opts (ClusterData gl fixed_nl ilf ctags ipol) <- loadExternalData opts putStrLn $ "Loaded cluster tags: " ++ intercalate "," ctags when (verbose > 2) . putStrLn $ "Loaded cluster ipolicy: " ++ show ipol nlf <- setNodeStatus opts fixed_nl commonInfo verbose gl nlf ilf splitInstancesInfo verbose nlf ilf showGroupInfo verbose gl nlf ilf maybePrintInsts showinsts "Instances" (Cluster.printInsts nlf ilf) maybePrintNodes shownodes "Cluster" (Cluster.printNodes nlf) printf "Cluster coefficients:\n%s" (Cluster.printStats " " nlf)::IO () printf "Cluster score: %.8f\n" (Cluster.compCV nlf)
narurien/ganeti-ceph
src/Ganeti/HTools/Program/Hinfo.hs
gpl-2.0
5,789
0
17
1,569
1,339
694
645
117
2
-- | The definitions related to jhc core module E.Type where import Data.Foldable hiding(concat) import Data.Traversable import C.Prims import Cmm.Number import Doc.DocLike hiding((<$>)) import Info.Types import Name.Id import Name.Names import StringTable.Atom import Util.Gen import qualified Info.Info as Info {- @Internals # Jhc core normalized forms Jhc core has a number of 'normalized forms' in which certain invarients are met. many routines expect code to be in a certain form, and guarentee theier output is also in a given form. The type system also can change with each form by adding/removing terms from the PTS axioms and rules. normalized form alpha : There are basically no restrictions other than the code is typesafe, but certain constructs that are checked by the type checker are okay when they wouldn't otherwise be. In particular, 'newtype' casts still exist at the data level. 'enum' scrutinizations are creations may be in terms of the virtual constructors rather than the internal representations. let may bind unboxed values, which is normaly not allowed. normalized form beta : This is like alpha except all data type constructors and case scrutinizations are in their final form. As in, newtype coercions are removed, Enums are desugared etc. also, 'let' bindings of unboxed values are translated to the appropriate 'case' statements. The output of E.FromHs is in this form. normalized form blue : This is the form that most routines work on. normalized form larry : post lambda-lifting normalized form mangled : All polymorphism has been replaced with subtyping -} -- the type of a supercombinator data Comb = Comb { combHead :: TVr, combBody :: E, combRules :: [Rule] } instance HasProperties Comb where modifyProperties f comb = combHead_u (modifyProperties f) comb getProperties comb = getProperties $ combHead comb putProperties p comb = combHead_u (putProperties p) comb instance HasProperties TVr where modifyProperties f = tvrInfo_u (modifyProperties f) getProperties = getProperties . tvrInfo putProperties prop = tvrInfo_u (putProperties prop) combBody_u f r@Comb{combBody = x} = r{combBody = f x} combHead_u f r@Comb{combHead = x} = r{combHead = f x} combRules_u f r@Comb{combRules = x} = cp r{combRules = fx} where cp = if null fx then unsetProperty PROP_HASRULE else setProperty PROP_HASRULE fx = f x combBody_s v = combBody_u (const v) combHead_s v = combHead_u (const v) combRules_s v = combRules_u (const v) emptyComb = Comb { combHead = tvr, combBody = Unknown, combRules = [] } combIdent = tvrIdent . combHead combArgs = snd . fromLam . combBody combABody = fst . fromLam . combBody combBind b = (combHead b,combBody b) bindComb (t,e) = combHead_s t . combBody_s e $ emptyComb combTriple comb = (combHead comb,combArgs comb,combABody comb) combTriple_s (t,as,e) comb = comb { combHead = t, combBody = Prelude.foldr ELam e as } data RuleType = RuleSpecialization | RuleUser | RuleCatalyst deriving(Eq) -- a rule in its user visible form data Rule = Rule { ruleHead :: TVr, ruleBinds :: [TVr], ruleArgs :: [E], ruleNArgs :: {-# UNPACK #-} !Int, ruleBody :: E, ruleType :: RuleType, ruleUniq :: (Module,Int), ruleName :: Atom } data ARules = ARules { aruleFreeVars :: IdSet, aruleRules :: [Rule] } data Lit e t = LitInt { litNumber :: Number, litType :: t } | LitCons { litName :: Name, litArgs :: [e], litType :: t, litAliasFor :: Maybe E } deriving(Eq,Ord,Functor,Foldable,Traversable) {-!derive: is !-} -------------------------------------- -- Lambda Cube (it's just fun to say.) -- We are now based on a PTS, which is -- a generalization of the lambda cube -- see E.TypeCheck for a description -- of the type system. -------------------------------------- data ESort = EStar -- ^ the sort of boxed lazy types | EBang -- ^ the sort of boxed strict types | EHash -- ^ the sort of unboxed types | ETuple -- ^ the sort of unboxed tuples | EHashHash -- ^ the supersort of unboxed types | EStarStar -- ^ the supersort of boxed types | ESortNamed Name -- ^ user defined sorts deriving(Eq, Ord) {-! derive: is !-} data E = EAp E E | ELam TVr E | EPi TVr E | EVar TVr | Unknown | ESort ESort | ELit !(Lit E E) | ELetRec { eDefs :: [(TVr, E)], eBody :: E } | EPrim Prim [E] E | EError String E | ECase { eCaseScrutinee :: E, eCaseType :: E, -- due to GADTs and typecases, the final type of the expression might not be so obvious, so we include it here. eCaseBind :: TVr, eCaseAlts :: [Alt E], eCaseDefault :: (Maybe E), eCaseAllFV :: IdSet } deriving(Eq, Ord) {-! derive: is, from !-} --instance Functor (Lit e) where -- fmap f x = runIdentity $ fmapM (return . f) x --instance FunctorM (Lit e) where -- fmapM f x = case x of -- LitCons { litName = a, litArgs = es, litType = e, litAliasFor = af } -> do e <- f e; return LitCons { litName = a, litArgs = es, litType = e, litAliasFor = af } -- LitInt i t -> do t <- f t; return $ LitInt i t instance Show ESort where showsPrec _ EStar = showString "*" showsPrec _ EHash = showString "#" showsPrec _ EStarStar = showString "**" showsPrec _ EHashHash = showString "##" showsPrec _ ETuple = showString "(#)" showsPrec _ EBang = showString "!" showsPrec _ (ESortNamed n) = shows n instance (Show e,Show t) => Show (Lit e t) where showsPrec p (LitInt x t) = showParen (p > 10) $ shows x <> showString "::" <> shows t showsPrec p LitCons { litName = n, litArgs = es, litType = t } = showParen (p > 10) $ hsep (shows n:map (showsPrec 11) es) <> showString "::" <> shows t instance Show a => Show (TVr' a) where showsPrec n TVr { tvrIdent = eid, tvrType = e} | eid == emptyId = showParen (n > 10) $ showString "_::" . shows e showsPrec n TVr { tvrIdent = x, tvrType = e} = showParen (n > 10) $ case fromId x of Just n -> shows n . showString "::" . shows e Nothing -> shows x . showString "::" . shows e type TVr = TVr' E data TVr' e = TVr { tvrIdent :: !Id, tvrType :: e, tvrInfo :: !Info.Info } deriving(Functor,Foldable,Traversable) {-!derive: update !-} data Alt e = Alt (Lit TVr e) e deriving(Eq,Ord) instance Eq TVr where (==) (TVr { tvrIdent = i }) (TVr { tvrIdent = i' }) = i == i' (/=) (TVr { tvrIdent = i }) (TVr { tvrIdent = i' }) = i /= i' instance Ord TVr where compare (TVr { tvrIdent = x }) (TVr { tvrIdent = y }) = compare x y x < y = tvrIdent x < tvrIdent y x > y = tvrIdent x > tvrIdent y x >= y = tvrIdent x >= tvrIdent y x <= y = tvrIdent x <= tvrIdent y -- simple querying routines altHead :: Alt E -> Lit () () altHead (Alt l _) = litHead l litHead :: Lit a b -> Lit () () litHead (LitInt x _) = LitInt x () litHead LitCons { litName = s, litAliasFor = af } = litCons { litName = s, litType = (), litAliasFor = af } litBinds (LitCons { litArgs = xs } ) = xs litBinds _ = [] patToLitEE LitCons { litName = n, litArgs = [a,b], litType = t } | t == eStar, n == tc_Arrow = EPi (tVr emptyId (EVar a)) (EVar b) patToLitEE LitCons { litName = n, litArgs = xs, litType = t, litAliasFor = af } = ELit $ LitCons { litName = n, litArgs = (map EVar xs), litType = t, litAliasFor = af } patToLitEE (LitInt x t) = ELit $ LitInt x t caseBodies :: E -> [E] caseBodies ec = [ b | Alt _ b <- eCaseAlts ec] ++ maybeToMonad (eCaseDefault ec) casePats ec = [ p | Alt p _ <- eCaseAlts ec] caseBinds ec = eCaseBind ec : concat [ xs | LitCons { litArgs = xs } <- casePats ec] -- | extract out EAp nodes a value and the arguments it is applied to. fromAp :: E -> (E,[E]) fromAp e = f [] e where f as (EAp e a) = f (a:as) e f as e = (e,as) -- | deconstruct EPi terms, getting function argument types. fromPi :: E -> (E,[TVr]) fromPi e = f [] e where f as (EPi v e) = f (v:as) e f as e = (e,reverse as) -- | deconstruct ELam term. fromLam :: E -> (E,[TVr]) fromLam e = f [] e where f as (ELam v e) = f (v:as) e f as e = (e,reverse as) litCons = LitCons { litName = error "litName: name not set", litArgs = [], litType = error "litCons: type not set", litAliasFor = Nothing } ----------------- -- E constructors ----------------- eStar :: E eStar = ESort EStar eHash :: E eHash = ESort EHash tVr x y = tvr { tvrIdent = x, tvrType = y } tvr = TVr { tvrIdent = emptyId, tvrType = Unknown, tvrInfo = Info.empty }
hvr/jhc
src/E/Type.hs
mit
8,669
2
14
2,121
2,588
1,407
1,181
153
2
module Test11 where f = \ x y -> x + y
SAdams601/HaRe
old/testing/refacSlicing/Test11_TokOut.hs
bsd-3-clause
40
0
6
13
20
12
8
2
1
module Case where {- imports will be added for the PointlessP librasies -} import PointlessP.Combinators import PointlessP.RecursionPatterns import PointlessP.Isomorphisms import PointlessP.Functors -- the hole expression will be selected for translation. coswap = app . (((curry (app . ((curry (((Right . snd) \/ (Left . snd)) . distr)) /\ snd))) . bang) /\ id)
mpickering/HaRe
old/testing/pointwiseToPointfree/Case_TokOut.hs
bsd-3-clause
506
0
23
196
103
60
43
12
1
module C2 (module D2, module C2) where import D2 hiding (sq) anotherFun (x:xs) = x^4 + anotherFun xs anotherFun [] = 0
kmate/HaRe
old/testing/liftToToplevel/C2_TokOut.hs
bsd-3-clause
129
0
7
32
59
34
25
4
1
{-# LANGUAGE CPP, MagicHash, BangPatterns #-} -- | -- Module : Data.Text.Encoding.Utf8 -- Copyright : (c) 2008, 2009 Tom Harper, -- (c) 2009, 2010 Bryan O'Sullivan, -- (c) 2009 Duncan Coutts -- -- License : BSD-style -- Maintainer : bos@serpentine.com, rtomharper@googlemail.com, -- duncan@haskell.org -- Stability : experimental -- Portability : GHC -- -- Basic UTF-8 validation and character manipulation. module Data.Text.Encoding.Utf8 ( -- Decomposition ord2 , ord3 , ord4 -- Construction , chr2 , chr3 , chr4 -- * Validation , validate1 , validate2 , validate3 , validate4 ) where #if defined(ASSERTS) import Control.Exception (assert) #endif import Data.Bits ((.&.)) import Data.Text.UnsafeChar (ord) import Data.Text.UnsafeShift (shiftR) import GHC.Exts import GHC.Word (Word8(..)) default(Int) between :: Word8 -- ^ byte to check -> Word8 -- ^ lower bound -> Word8 -- ^ upper bound -> Bool between x y z = x >= y && x <= z {-# INLINE between #-} ord2 :: Char -> (Word8,Word8) ord2 c = #if defined(ASSERTS) assert (n >= 0x80 && n <= 0x07ff) #endif (x1,x2) where n = ord c x1 = fromIntegral $ (n `shiftR` 6) + 0xC0 x2 = fromIntegral $ (n .&. 0x3F) + 0x80 ord3 :: Char -> (Word8,Word8,Word8) ord3 c = #if defined(ASSERTS) assert (n >= 0x0800 && n <= 0xffff) #endif (x1,x2,x3) where n = ord c x1 = fromIntegral $ (n `shiftR` 12) + 0xE0 x2 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80 x3 = fromIntegral $ (n .&. 0x3F) + 0x80 ord4 :: Char -> (Word8,Word8,Word8,Word8) ord4 c = #if defined(ASSERTS) assert (n >= 0x10000) #endif (x1,x2,x3,x4) where n = ord c x1 = fromIntegral $ (n `shiftR` 18) + 0xF0 x2 = fromIntegral $ ((n `shiftR` 12) .&. 0x3F) + 0x80 x3 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80 x4 = fromIntegral $ (n .&. 0x3F) + 0x80 chr2 :: Word8 -> Word8 -> Char chr2 (W8# x1#) (W8# x2#) = C# (chr# (z1# +# z2#)) where !y1# = word2Int# x1# !y2# = word2Int# x2# !z1# = uncheckedIShiftL# (y1# -# 0xC0#) 6# !z2# = y2# -# 0x80# {-# INLINE chr2 #-} chr3 :: Word8 -> Word8 -> Word8 -> Char chr3 (W8# x1#) (W8# x2#) (W8# x3#) = C# (chr# (z1# +# z2# +# z3#)) where !y1# = word2Int# x1# !y2# = word2Int# x2# !y3# = word2Int# x3# !z1# = uncheckedIShiftL# (y1# -# 0xE0#) 12# !z2# = uncheckedIShiftL# (y2# -# 0x80#) 6# !z3# = y3# -# 0x80# {-# INLINE chr3 #-} chr4 :: Word8 -> Word8 -> Word8 -> Word8 -> Char chr4 (W8# x1#) (W8# x2#) (W8# x3#) (W8# x4#) = C# (chr# (z1# +# z2# +# z3# +# z4#)) where !y1# = word2Int# x1# !y2# = word2Int# x2# !y3# = word2Int# x3# !y4# = word2Int# x4# !z1# = uncheckedIShiftL# (y1# -# 0xF0#) 18# !z2# = uncheckedIShiftL# (y2# -# 0x80#) 12# !z3# = uncheckedIShiftL# (y3# -# 0x80#) 6# !z4# = y4# -# 0x80# {-# INLINE chr4 #-} validate1 :: Word8 -> Bool validate1 x1 = x1 <= 0x7F {-# INLINE validate1 #-} validate2 :: Word8 -> Word8 -> Bool validate2 x1 x2 = between x1 0xC2 0xDF && between x2 0x80 0xBF {-# INLINE validate2 #-} validate3 :: Word8 -> Word8 -> Word8 -> Bool {-# INLINE validate3 #-} validate3 x1 x2 x3 = validate3_1 || validate3_2 || validate3_3 || validate3_4 where validate3_1 = (x1 == 0xE0) && between x2 0xA0 0xBF && between x3 0x80 0xBF validate3_2 = between x1 0xE1 0xEC && between x2 0x80 0xBF && between x3 0x80 0xBF validate3_3 = x1 == 0xED && between x2 0x80 0x9F && between x3 0x80 0xBF validate3_4 = between x1 0xEE 0xEF && between x2 0x80 0xBF && between x3 0x80 0xBF validate4 :: Word8 -> Word8 -> Word8 -> Word8 -> Bool {-# INLINE validate4 #-} validate4 x1 x2 x3 x4 = validate4_1 || validate4_2 || validate4_3 where validate4_1 = x1 == 0xF0 && between x2 0x90 0xBF && between x3 0x80 0xBF && between x4 0x80 0xBF validate4_2 = between x1 0xF1 0xF3 && between x2 0x80 0xBF && between x3 0x80 0xBF && between x4 0x80 0xBF validate4_3 = x1 == 0xF4 && between x2 0x80 0x8F && between x3 0x80 0xBF && between x4 0x80 0xBF
ssaavedra/liquidhaskell
benchmarks/text-0.11.2.3/Data/Text/Encoding/Utf8.hs
bsd-3-clause
4,573
0
12
1,490
1,442
766
676
110
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude #-} {-# LANGUAGE ForeignFunctionInterface #-} ----------------------------------------------------------------------------- -- | -- Module : System.IO -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : stable -- Portability : portable -- -- The standard IO library. -- ----------------------------------------------------------------------------- module System.IO ( -- * The IO monad IO, -- instance MonadFix fixIO, -- :: (a -> IO a) -> IO a -- * Files and handles FilePath, -- :: String Handle, -- abstract, instance of: Eq, Show. -- | GHC note: a 'Handle' will be automatically closed when the garbage -- collector detects that it has become unreferenced by the program. -- However, relying on this behaviour is not generally recommended: -- the garbage collector is unpredictable. If possible, use -- an explicit 'hClose' to close 'Handle's when they are no longer -- required. GHC does not currently attempt to free up file -- descriptors when they have run out, it is your responsibility to -- ensure that this doesn't happen. -- ** Standard handles -- | Three handles are allocated during program initialisation, -- and are initially open. stdin, stdout, stderr, -- :: Handle -- * Opening and closing files -- ** Opening files withFile, openFile, -- :: FilePath -> IOMode -> IO Handle IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode), -- ** Closing files hClose, -- :: Handle -> IO () -- ** Special cases -- | These functions are also exported by the "Prelude". readFile, -- :: FilePath -> IO String writeFile, -- :: FilePath -> String -> IO () appendFile, -- :: FilePath -> String -> IO () -- ** File locking -- $locking -- * Operations on handles -- ** Determining and changing the size of a file hFileSize, -- :: Handle -> IO Integer #ifdef __GLASGOW_HASKELL__ hSetFileSize, -- :: Handle -> Integer -> IO () #endif -- ** Detecting the end of input hIsEOF, -- :: Handle -> IO Bool isEOF, -- :: IO Bool -- ** Buffering operations BufferMode(NoBuffering,LineBuffering,BlockBuffering), hSetBuffering, -- :: Handle -> BufferMode -> IO () hGetBuffering, -- :: Handle -> IO BufferMode hFlush, -- :: Handle -> IO () -- ** Repositioning handles hGetPosn, -- :: Handle -> IO HandlePosn hSetPosn, -- :: HandlePosn -> IO () HandlePosn, -- abstract, instance of: Eq, Show. hSeek, -- :: Handle -> SeekMode -> Integer -> IO () SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd), #if !defined(__NHC__) hTell, -- :: Handle -> IO Integer #endif -- ** Handle properties hIsOpen, hIsClosed, -- :: Handle -> IO Bool hIsReadable, hIsWritable, -- :: Handle -> IO Bool hIsSeekable, -- :: Handle -> IO Bool -- ** Terminal operations (not portable: GHC\/Hugs only) #if !defined(__NHC__) hIsTerminalDevice, -- :: Handle -> IO Bool hSetEcho, -- :: Handle -> Bool -> IO () hGetEcho, -- :: Handle -> IO Bool #endif -- ** Showing handle state (not portable: GHC only) #ifdef __GLASGOW_HASKELL__ hShow, -- :: Handle -> IO String #endif -- * Text input and output -- ** Text input hWaitForInput, -- :: Handle -> Int -> IO Bool hReady, -- :: Handle -> IO Bool hGetChar, -- :: Handle -> IO Char hGetLine, -- :: Handle -> IO [Char] hLookAhead, -- :: Handle -> IO Char hGetContents, -- :: Handle -> IO [Char] -- ** Text output hPutChar, -- :: Handle -> Char -> IO () hPutStr, -- :: Handle -> [Char] -> IO () hPutStrLn, -- :: Handle -> [Char] -> IO () hPrint, -- :: Show a => Handle -> a -> IO () -- ** Special cases for standard input and output -- | These functions are also exported by the "Prelude". interact, -- :: (String -> String) -> IO () putChar, -- :: Char -> IO () putStr, -- :: String -> IO () putStrLn, -- :: String -> IO () print, -- :: Show a => a -> IO () getChar, -- :: IO Char getLine, -- :: IO String getContents, -- :: IO String readIO, -- :: Read a => String -> IO a readLn, -- :: Read a => IO a -- * Binary input and output withBinaryFile, openBinaryFile, -- :: FilePath -> IOMode -> IO Handle hSetBinaryMode, -- :: Handle -> Bool -> IO () hPutBuf, -- :: Handle -> Ptr a -> Int -> IO () hGetBuf, -- :: Handle -> Ptr a -> Int -> IO Int #if !defined(__NHC__) && !defined(__HUGS__) hGetBufSome, -- :: Handle -> Ptr a -> Int -> IO Int hPutBufNonBlocking, -- :: Handle -> Ptr a -> Int -> IO Int hGetBufNonBlocking, -- :: Handle -> Ptr a -> Int -> IO Int #endif -- * Temporary files openTempFile, openBinaryTempFile, openTempFileWithDefaultPermissions, openBinaryTempFileWithDefaultPermissions, #if !defined(__NHC__) && !defined(__HUGS__) -- * Unicode encoding\/decoding -- | A text-mode 'Handle' has an associated 'TextEncoding', which -- is used to decode bytes into Unicode characters when reading, -- and encode Unicode characters into bytes when writing. -- -- The default 'TextEncoding' is the same as the default encoding -- on your system, which is also available as 'localeEncoding'. -- (GHC note: on Windows, we currently do not support double-byte -- encodings; if the console\'s code page is unsupported, then -- 'localeEncoding' will be 'latin1'.) -- -- Encoding and decoding errors are always detected and reported, -- except during lazy I/O ('hGetContents', 'getContents', and -- 'readFile'), where a decoding error merely results in -- termination of the character stream, as with other I/O errors. hSetEncoding, hGetEncoding, -- ** Unicode encodings TextEncoding, latin1, utf8, utf8_bom, utf16, utf16le, utf16be, utf32, utf32le, utf32be, localeEncoding, char8, mkTextEncoding, #endif #if !defined(__NHC__) && !defined(__HUGS__) -- * Newline conversion -- | In Haskell, a newline is always represented by the character -- '\n'. However, in files and external character streams, a -- newline may be represented by another character sequence, such -- as '\r\n'. -- -- A text-mode 'Handle' has an associated 'NewlineMode' that -- specifies how to transate newline characters. The -- 'NewlineMode' specifies the input and output translation -- separately, so that for instance you can translate '\r\n' -- to '\n' on input, but leave newlines as '\n' on output. -- -- The default 'NewlineMode' for a 'Handle' is -- 'nativeNewlineMode', which does no translation on Unix systems, -- but translates '\r\n' to '\n' and back on Windows. -- -- Binary-mode 'Handle's do no newline translation at all. -- hSetNewlineMode, Newline(..), nativeNewline, NewlineMode(..), noNewlineTranslation, universalNewlineMode, nativeNewlineMode, #endif ) where import Control.Exception.Base #ifndef __NHC__ import Data.Bits import Data.List import Data.Maybe import Foreign.C.Error #ifdef mingw32_HOST_OS import Foreign.C.String #endif import Foreign.C.Types import System.Posix.Internals import System.Posix.Types #endif #ifdef __GLASGOW_HASKELL__ import GHC.Base import GHC.IO hiding ( bracket, onException ) import GHC.IO.IOMode import GHC.IO.Handle.FD import qualified GHC.IO.FD as FD import GHC.IO.Handle import GHC.IO.Handle.Text ( hGetBufSome, hPutStrLn ) import GHC.IO.Exception ( userError ) import GHC.IO.Encoding import GHC.Num import Text.Read import GHC.Show import GHC.MVar #endif #ifdef __HUGS__ import Hugs.IO import Hugs.IOExts import Hugs.IORef import System.IO.Unsafe ( unsafeInterleaveIO ) #endif #ifdef __NHC__ import IO ( Handle () , HandlePosn () , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode) , BufferMode (NoBuffering,LineBuffering,BlockBuffering) , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd) , stdin, stdout, stderr , openFile -- :: FilePath -> IOMode -> IO Handle , hClose -- :: Handle -> IO () , hFileSize -- :: Handle -> IO Integer , hIsEOF -- :: Handle -> IO Bool , isEOF -- :: IO Bool , hSetBuffering -- :: Handle -> BufferMode -> IO () , hGetBuffering -- :: Handle -> IO BufferMode , hFlush -- :: Handle -> IO () , hGetPosn -- :: Handle -> IO HandlePosn , hSetPosn -- :: HandlePosn -> IO () , hSeek -- :: Handle -> SeekMode -> Integer -> IO () , hWaitForInput -- :: Handle -> Int -> IO Bool , hGetChar -- :: Handle -> IO Char , hGetLine -- :: Handle -> IO [Char] , hLookAhead -- :: Handle -> IO Char , hGetContents -- :: Handle -> IO [Char] , hPutChar -- :: Handle -> Char -> IO () , hPutStr -- :: Handle -> [Char] -> IO () , hPutStrLn -- :: Handle -> [Char] -> IO () , hPrint -- :: Handle -> [Char] -> IO () , hReady -- :: Handle -> [Char] -> IO () , hIsOpen, hIsClosed -- :: Handle -> IO Bool , hIsReadable, hIsWritable -- :: Handle -> IO Bool , hIsSeekable -- :: Handle -> IO Bool , bracket , IO () , FilePath -- :: String ) import NHC.IOExtras (fixIO, hPutBuf, hGetBuf) import NHC.FFI (Ptr) #endif -- ----------------------------------------------------------------------------- -- Standard IO #ifdef __GLASGOW_HASKELL__ -- | Write a character to the standard output device -- (same as 'hPutChar' 'stdout'). putChar :: Char -> IO () putChar c = hPutChar stdout c -- | Write a string to the standard output device -- (same as 'hPutStr' 'stdout'). putStr :: String -> IO () putStr s = hPutStr stdout s -- | The same as 'putStr', but adds a newline character. putStrLn :: String -> IO () putStrLn s = hPutStrLn stdout s -- | The 'print' function outputs a value of any printable type to the -- standard output device. -- Printable types are those that are instances of class 'Show'; 'print' -- converts values to strings for output using the 'show' operation and -- adds a newline. -- -- For example, a program to print the first 20 integers and their -- powers of 2 could be written as: -- -- > main = print ([(n, 2^n) | n <- [0..19]]) print :: Show a => a -> IO () print x = putStrLn (show x) -- | Read a character from the standard input device -- (same as 'hGetChar' 'stdin'). getChar :: IO Char getChar = hGetChar stdin -- | Read a line from the standard input device -- (same as 'hGetLine' 'stdin'). getLine :: IO String getLine = hGetLine stdin -- | The 'getContents' operation returns all user input as a single string, -- which is read lazily as it is needed -- (same as 'hGetContents' 'stdin'). getContents :: IO String getContents = hGetContents stdin -- | The 'interact' function takes a function of type @String->String@ -- as its argument. The entire input from the standard input device is -- passed to this function as its argument, and the resulting string is -- output on the standard output device. interact :: (String -> String) -> IO () interact f = do s <- getContents putStr (f s) -- | The 'readFile' function reads a file and -- returns the contents of the file as a string. -- The file is read lazily, on demand, as with 'getContents'. readFile :: FilePath -> IO String readFile name = openFile name ReadMode >>= hGetContents -- | The computation 'writeFile' @file str@ function writes the string @str@, -- to the file @file@. writeFile :: FilePath -> String -> IO () writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt) -- | The computation 'appendFile' @file str@ function appends the string @str@, -- to the file @file@. -- -- Note that 'writeFile' and 'appendFile' write a literal string -- to a file. To write a value of any printable type, as with 'print', -- use the 'show' function to convert the value to a string first. -- -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]]) appendFile :: FilePath -> String -> IO () appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt) -- | The 'readLn' function combines 'getLine' and 'readIO'. readLn :: Read a => IO a readLn = do l <- getLine r <- readIO l return r -- | The 'readIO' function is similar to 'read' except that it signals -- parse failure to the 'IO' monad instead of terminating the program. readIO :: Read a => String -> IO a readIO s = case (do { (x,t) <- reads s ; ("","") <- lex t ; return x }) of [x] -> return x [] -> ioError (userError "Prelude.readIO: no parse") _ -> ioError (userError "Prelude.readIO: ambiguous parse") -- | The Unicode encoding of the current locale -- -- This is the initial locale encoding: if it has been subsequently changed by -- 'GHC.IO.Encoding.setLocaleEncoding' this value will not reflect that change. localeEncoding :: TextEncoding localeEncoding = initLocaleEncoding #endif /* __GLASGOW_HASKELL__ */ #ifndef __NHC__ -- | Computation 'hReady' @hdl@ indicates whether at least one item is -- available for input from handle @hdl@. -- -- This operation may fail with: -- -- * 'System.IO.Error.isEOFError' if the end of file has been reached. hReady :: Handle -> IO Bool hReady h = hWaitForInput h 0 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@ -- given by the 'shows' function to the file or channel managed by @hdl@ -- and appends a newline. -- -- This operation may fail with: -- -- * 'System.IO.Error.isFullError' if the device is full; or -- -- * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded. hPrint :: Show a => Handle -> a -> IO () hPrint hdl = hPutStrLn hdl . show #endif /* !__NHC__ */ -- | @'withFile' name mode act@ opens a file using 'openFile' and passes -- the resulting handle to the computation @act@. The handle will be -- closed on exit from 'withFile', whether by normal termination or by -- raising an exception. If closing the handle raises an exception, then -- this exception will be raised by 'withFile' rather than any exception -- raised by 'act'. withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r withFile name mode = bracket (openFile name mode) hClose -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile' -- and passes the resulting handle to the computation @act@. The handle -- will be closed on exit from 'withBinaryFile', whether by normal -- termination or by raising an exception. withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r withBinaryFile name mode = bracket (openBinaryFile name mode) hClose -- --------------------------------------------------------------------------- -- fixIO #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__) fixIO :: (a -> IO a) -> IO a fixIO k = do m <- newEmptyMVar ans <- unsafeInterleaveIO (takeMVar m) result <- k ans putMVar m result return result -- NOTE: we do our own explicit black holing here, because GHC's lazy -- blackholing isn't enough. In an infinite loop, GHC may run the IO -- computation a few times before it notices the loop, which is wrong. -- -- NOTE2: the explicit black-holing with an IORef ran into trouble -- with multiple threads (see #5421), so now we use an MVar. I'm -- actually wondering whether we should use readMVar rather than -- takeMVar, just in case it ends up being executed multiple times, -- but even then it would have to be masked to protect against async -- exceptions. Ugh. What we really need here is an IVar, or an -- atomic readMVar, or even STM. All these seem like overkill. -- -- See also System.IO.Unsafe.unsafeFixIO. -- #endif #if defined(__NHC__) -- Assume a unix platform, where text and binary I/O are identical. openBinaryFile = openFile hSetBinaryMode _ _ = return () type CMode = Int #endif -- | The function creates a temporary file in ReadWrite mode. -- The created file isn\'t deleted automatically, so you need to delete it manually. -- -- The file is creates with permissions such that only the current -- user can read\/write it. -- -- With some exceptions (see below), the file will be created securely -- in the sense that an attacker should not be able to cause -- openTempFile to overwrite another file on the filesystem using your -- credentials, by putting symbolic links (on Unix) in the place where -- the temporary file is to be created. On Unix the @O_CREAT@ and -- @O_EXCL@ flags are used to prevent this attack, but note that -- @O_EXCL@ is sometimes not supported on NFS filesystems, so if you -- rely on this behaviour it is best to use local filesystems only. -- openTempFile :: FilePath -- ^ Directory in which to create the file -> String -- ^ File name template. If the template is \"foo.ext\" then -- the created file will be \"fooXXX.ext\" where XXX is some -- random number. -> IO (FilePath, Handle) openTempFile tmp_dir template = openTempFile' "openTempFile" tmp_dir template False 0o600 -- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments. openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle) openBinaryTempFile tmp_dir template = openTempFile' "openBinaryTempFile" tmp_dir template True 0o600 -- | Like 'openTempFile', but uses the default file permissions openTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle) openTempFileWithDefaultPermissions tmp_dir template = openTempFile' "openBinaryTempFile" tmp_dir template False 0o666 -- | Like 'openBinaryTempFile', but uses the default file permissions openBinaryTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle) openBinaryTempFileWithDefaultPermissions tmp_dir template = openTempFile' "openBinaryTempFile" tmp_dir template True 0o666 openTempFile' :: String -> FilePath -> String -> Bool -> CMode -> IO (FilePath, Handle) openTempFile' loc tmp_dir template binary mode = do pid <- c_getpid findTempName pid where -- We split off the last extension, so we can use .foo.ext files -- for temporary files (hidden on Unix OSes). Unfortunately we're -- below filepath in the hierarchy here. (prefix,suffix) = case break (== '.') $ reverse template of -- First case: template contains no '.'s. Just re-reverse it. (rev_suffix, "") -> (reverse rev_suffix, "") -- Second case: template contains at least one '.'. Strip the -- dot from the prefix and prepend it to the suffix (if we don't -- do this, the unique number will get added after the '.' and -- thus be part of the extension, which is wrong.) (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix) -- Otherwise, something is wrong, because (break (== '.')) should -- always return a pair with either the empty string or a string -- beginning with '.' as the second component. _ -> error "bug in System.IO.openTempFile" #ifndef __NHC__ #endif #if defined(__NHC__) findTempName x = do h <- openFile filepath ReadWriteMode return (filepath, h) #elif defined(__GLASGOW_HASKELL__) findTempName x = do r <- openNewFile filepath binary mode case r of FileExists -> findTempName (x + 1) OpenNewError errno -> ioError (errnoToIOError loc errno Nothing (Just tmp_dir)) NewFileCreated fd -> do (fD,fd_type) <- FD.mkFD fd ReadWriteMode Nothing{-no stat-} False{-is_socket-} True{-is_nonblock-} enc <- getLocaleEncoding h <- mkHandleFromFD fD fd_type filepath ReadWriteMode False{-set non-block-} (Just enc) return (filepath, h) #else h <- fdToHandle fd `onException` c_close fd return (filepath, h) #endif where filename = prefix ++ show x ++ suffix filepath = tmp_dir `combine` filename -- XXX bits copied from System.FilePath, since that's not available here combine a b | null b = a | null a = b | last a == pathSeparator = a ++ b | otherwise = a ++ [pathSeparator] ++ b #if __HUGS__ fdToHandle fd = openFd (fromIntegral fd) False ReadWriteMode binary #endif #if defined(__GLASGOW_HASKELL__) data OpenNewFileResult = NewFileCreated CInt | FileExists | OpenNewError Errno openNewFile :: FilePath -> Bool -> CMode -> IO OpenNewFileResult openNewFile filepath binary mode = do let oflags1 = rw_flags .|. o_EXCL binary_flags | binary = o_BINARY | otherwise = 0 oflags = oflags1 .|. binary_flags fd <- withFilePath filepath $ \ f -> c_open f oflags mode if fd < 0 then do errno <- getErrno case errno of _ | errno == eEXIST -> return FileExists # ifdef mingw32_HOST_OS -- If c_open throws EACCES on windows, it could mean that filepath is a -- directory. In this case, we want to return FileExists so that the -- enclosing openTempFile can try again instead of failing outright. -- See bug #4968. _ | errno == eACCES -> do withCString filepath $ \path -> do -- There is a race here: the directory might have been moved or -- deleted between the c_open call and the next line, but there -- doesn't seem to be any direct way to detect that the c_open call -- failed because of an existing directory. exists <- c_fileExists path return $ if exists then FileExists else OpenNewError errno # endif _ -> return (OpenNewError errno) else return (NewFileCreated fd) # ifdef mingw32_HOST_OS foreign import ccall "file_exists" c_fileExists :: CString -> IO Bool # endif #endif -- XXX Should use filepath library pathSeparator :: Char #ifdef mingw32_HOST_OS pathSeparator = '\\' #else pathSeparator = '/' #endif #ifndef __NHC__ -- XXX Copied from GHC.Handle std_flags, output_flags, rw_flags :: CInt std_flags = o_NONBLOCK .|. o_NOCTTY output_flags = std_flags .|. o_CREAT rw_flags = output_flags .|. o_RDWR #endif #ifdef __NHC__ foreign import ccall "getpid" c_getpid :: IO Int #endif -- $locking -- Implementations should enforce as far as possible, at least locally to the -- Haskell process, multiple-reader single-writer locking on files. -- That is, /there may either be many handles on the same file which manage input, or just one handle on the file which manages output/. If any -- open or semi-closed handle is managing a file for output, no new -- handle can be allocated for that file. If any open or semi-closed -- handle is managing a file for input, new handles can only be allocated -- if they do not manage output. Whether two files are the same is -- implementation-dependent, but they should normally be the same if they -- have the same absolute path name and neither has been renamed, for -- example. -- -- /Warning/: the 'readFile' operation holds a semi-closed handle on -- the file until the entire contents of the file have been consumed. -- It follows that an attempt to write to a file (using 'writeFile', for -- example) that was earlier opened by 'readFile' will usually result in -- failure with 'System.IO.Error.isAlreadyInUseError'.
abakst/liquidhaskell
benchmarks/base-4.5.1.0/System/IO.hs
bsd-3-clause
25,258
0
22
7,049
2,637
1,611
1,026
-1
-1
module A2 where import D2 import C2 import B2 main :: Tree Int ->Bool main t = isSame (sumSquares (fringe t)) (sumSquares (B2.myFringe t)+sumSquares (C2.myFringe t))
RefactoringTools/HaRe
old/testing/moveDefBtwMods/A2_TokOut.hs
bsd-3-clause
185
0
11
45
79
41
38
7
1
module T11245 where foo x = do let a | Just i <- x , odd i = True | Nothing <- x = False print x print a
ezyang/ghc
testsuite/tests/pmcheck/should_compile/T11245.hs
bsd-3-clause
147
0
14
71
66
29
37
9
1