code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
add (x,y) = x + y add' x y = x + y second xs = head (tail xs) swap (x, y) = (y, x) pair x y = (x, y) -- a -> b -> (a, b) double x = x * 2 -- Num a => a -> a palindrome xs = reverse xs == xs -- How is the type of this function determined? twice f x = f (f x) -- (a -> a) -> a -> a f xs = take 3 (reverse xs)
jugalps/edX
FP101x/week2/week2.hs
Haskell
mit
314
{-# OPTIONS_GHC -fno-warn-orphans #-} module Application ( getApplicationDev , appMain , develMain , makeFoundation -- * for DevelMain , getApplicationRepl , shutdownApp -- * for GHCI , handler , db ) where import Control.Monad.Logger (liftLoc, runLoggingT) import Database.Persist.Sqlite (createSqlitePool, runSqlPool, sqlDatabase, sqlPoolSize) import Import import Language.Haskell.TH.Syntax (qLocation) import Network.Wai.Handler.Warp (Settings, defaultSettings, defaultShouldDisplayException, runSettings, setHost, setOnException, setPort, getPort) import Network.Wai.Middleware.RequestLogger (Destination (Logger), IPAddrSource (..), OutputFormat (..), destination, mkRequestLogger, outputFormat) import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet, toLogStr) -- Import all relevant handler modules here. -- Don't forget to add new modules to your cabal file! import Handler.Common import Handler.Home import Handler.Game import Handler.GameHome -- This line actually creates our YesodDispatch instance. It is the second half -- of the call to mkYesodData which occurs in Foundation.hs. Please see the -- comments there for more details. mkYesodDispatch "App" resourcesApp -- | This function allocates resources (such as a database connection pool), -- performs initialization and return a foundation datatype value. This is also -- the place to put your migrate statements to have automatic database -- migrations handled by Yesod. makeFoundation :: AppSettings -> IO App makeFoundation appSettings = do -- Some basic initializations: HTTP connection manager, logger, and static -- subsite. appHttpManager <- newManager appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger appStatic <- (if appMutableStatic appSettings then staticDevel else static) (appStaticDir appSettings) -- We need a log function to create a connection pool. We need a connection -- pool to create our foundation. And we need our foundation to get a -- logging function. To get out of this loop, we initially create a -- temporary foundation without a real connection pool, get a log function -- from there, and then create the real foundation. let mkFoundation appConnPool = App {..} tempFoundation = mkFoundation $ error "connPool forced in tempFoundation" logFunc = messageLoggerSource tempFoundation appLogger -- Create the database connection pool pool <- flip runLoggingT logFunc $ createSqlitePool (sqlDatabase $ appDatabaseConf appSettings) (sqlPoolSize $ appDatabaseConf appSettings) -- Perform database migration using our application's logging settings. runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc -- Return the foundation return $ mkFoundation pool -- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and -- applyng some additional middlewares. makeApplication :: App -> IO Application makeApplication foundation = do logWare <- mkRequestLogger def { outputFormat = if appDetailedRequestLogging $ appSettings foundation then Detailed True else Apache (if appIpFromHeader $ appSettings foundation then FromFallback else FromSocket) , destination = Logger $ loggerSet $ appLogger foundation } -- Create the WAI application and apply middlewares appPlain <- toWaiAppPlain foundation return $ logWare $ defaultMiddlewaresNoLogging appPlain -- | Warp settings for the given foundation value. warpSettings :: App -> Settings warpSettings foundation = setPort (appPort $ appSettings foundation) $ setHost (appHost $ appSettings foundation) $ setOnException (\_req e -> when (defaultShouldDisplayException e) $ messageLoggerSource foundation (appLogger foundation) $(qLocation >>= liftLoc) "yesod" LevelError (toLogStr $ "Exception from Warp: " ++ show e)) defaultSettings -- | For yesod devel, return the Warp settings and WAI Application. getApplicationDev :: IO (Settings, Application) getApplicationDev = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app <- makeApplication foundation return (wsettings, app) getAppSettings :: IO AppSettings getAppSettings = loadAppSettings [configSettingsYml] [] useEnv -- | main function for use by yesod devel develMain :: IO () develMain = develMainHelper getApplicationDev -- | The @main@ function for an executable running this site. appMain :: IO () appMain = do -- Get the settings from all relevant sources settings <- loadAppSettingsArgs -- fall back to compile-time values, set to [] to require values at runtime [configSettingsYmlValue] -- allow environment variables to override useEnv -- Generate the foundation from the settings foundation <- makeFoundation settings -- Generate a WAI Application from the foundation app <- makeApplication foundation -- Run the application with Warp runSettings (warpSettings foundation) app -------------------------------------------------------------- -- Functions for DevelMain.hs (a way to run the app from GHCi) -------------------------------------------------------------- getApplicationRepl :: IO (Int, App, Application) getApplicationRepl = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app1 <- makeApplication foundation return (getPort wsettings, foundation, app1) shutdownApp :: App -> IO () shutdownApp _ = return () --------------------------------------------- -- Functions for use in development with GHCi --------------------------------------------- -- | Run a handler handler :: Handler a -> IO a handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h -- | Run DB queries db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a db = handler . runDB
total-git/missingno
yesodMissingNo/Application.hs
Haskell
mit
6,654
{- Copyright (c) Facebook, Inc. and its affiliates. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- module Thrift.Transport.Handle ( module Thrift.Transport , Port , HandleSource(..) ) where import Control.Exception ( catch, throw ) import Data.ByteString.Internal (c2w) #if __GLASGOW_HASKELL__ < 710 import Data.Functor #endif #if MIN_VERSION_network(2,7,0) import Data.Maybe import Network.Socket #else import Network #endif import System.IO import System.IO.Error ( isEOFError ) import Thrift.Transport import qualified Data.ByteString.Lazy as LBS #if __GLASGOW_HASKELL__ < 710 import Data.Monoid #endif instance Transport Handle where tIsOpen = hIsOpen tClose = hClose tRead h n = LBS.hGet h n `catch` handleEOF mempty tPeek h = (Just . c2w <$> hLookAhead h) `catch` handleEOF Nothing tWrite = LBS.hPut tFlush = hFlush -- | Type class for all types that can open a Handle. This class is used to -- replace tOpen in the Transport type class. class HandleSource s where hOpen :: s -> IO Handle instance HandleSource FilePath where hOpen s = openFile s ReadWriteMode type Port = String instance HandleSource (HostName, Port) where #if MIN_VERSION_network(2,7,0) hOpen (h,p) = do let hints = defaultHints{addrFamily = AF_INET} addr <- fromMaybe (error "getAddrInfo") . listToMaybe <$> getAddrInfo (Just hints) (Just h) (Just p) s <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr) connect s $ addrAddress addr socketToHandle s ReadWriteMode #else hOpen (h,p) = connectTo h (PortNumber $ read p) #endif handleEOF :: a -> IOError -> IO a handleEOF a e = if isEOFError e then return a else throw $ TransportExn "TChannelTransport: Could not read" TE_UNKNOWN
facebook/fbthrift
thrift/lib/hs/Thrift/Transport/Handle.hs
Haskell
apache-2.0
3,315
module CourseStitch.Models ( module CourseStitch.Models.Tables, module CourseStitch.Models.Types, module CourseStitch.Models.RunDB, module CourseStitch.Models.Queries, module CourseStitch.Models.Models ) where import CourseStitch.Models.Tables import CourseStitch.Models.Types import CourseStitch.Models.RunDB import CourseStitch.Models.Queries import CourseStitch.Models.Models
coursestitch/coursestitch-api
lib/CourseStitch/Models.hs
Haskell
apache-2.0
400
{-# LANGUAGE TupleSections #-} module Handler.DownloadFeeds where import qualified Data.Text as T import Data.Maybe import Data.Time (getCurrentTimeZone) import Data.Default (def) import Blaze.ByteString.Builder import qualified Model import Import typeTorrent :: T.Text typeTorrent = "application/x-bittorrent" nsAtom :: T.Text nsAtom = "http://www.w3.org/2005/Atom" torrentLink :: Download -> Route UIApp torrentLink d = TorrentFileR (downloadUser d) (downloadSlug d) (TorrentName $ downloadName d) data FeedParameters = Parameters { pTitle :: T.Text, pImage :: T.Text, pLink :: Route UIApp } class RepFeed c where renderFeed :: FeedParameters -> [Item] -> Handler c renderFeed' :: FeedParameters -> [Download] -> Handler c renderFeed' params downloads = renderFeed params $ groupDownloads downloads withXmlDecl :: Content -> Content withXmlDecl (ContentBuilder b _) = flip ContentBuilder Nothing $ fromByteString "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" `mappend` b withXmlDecl c = c newtype RepRss = RepRss Content instance HasReps RepRss where chooseRep (RepRss content) _cts = return (typeRss, withXmlDecl content) instance RepFeed RepRss where renderFeed params items = do url <- getFullUrlRender let image = pImage params RepRss `fmap` hamletToContent [xhamlet| <rss version="2.0" xmlns:atom=#{nsAtom}> <channel> <title>#{pTitle params} <link>#{url $ pLink params} $if not (T.null image) <image> <url>#{image} $forall item <- items <item> <title>#{itemTitle item} <link>#{itemLink url item} $if not (T.null $ fromMaybe "" $ itemLang item) <language>#{fromMaybe "" $ itemLang item} $maybe summary <- itemSummary item <description>#{summary} <guid isPermaLink="true">#{itemLink url item} <pubDate>#{rfc822 (itemPublished item)} $if not (T.null $ itemImage item) <image> <url>#{itemImage item} $if not (T.null $ itemPayment item) <atom:link rel="payment" href=#{itemPayment item} > $forall d <- itemDownloads item <enclosure type="#{typeTorrent}" length="#{downloadSize d}" url="#{url $ torrentLink d}"> |] newtype RepAtom = RepAtom Content instance HasReps RepAtom where chooseRep (RepAtom content) _cts = return (typeAtom, withXmlDecl content) instance RepFeed RepAtom where renderFeed params items = do let image = pImage params url <- getFullUrlRender tz <- liftIO getCurrentTimeZone RepAtom `fmap` hamletToContent [xhamlet| <feed version="1.0" xmlns=#{nsAtom}> <title>#{pTitle params} <link rel="alternate" type="text/html" href=#{url $ pLink params} > <id>#{url $ pLink params} $if not (T.null image) <link rel="icon" href=#{image} > $forall item <- items <entry xml:lang="#{fromMaybe "" $ itemLang item}"> <title>#{itemTitle item} <link rel="alternate" type="text/html" href=#{itemLink url item} > <id>#{itemLink url item} <published>#{iso8601 $ localTimeToZonedTime tz $ itemPublished item} $maybe summary <- itemSummary item <summary>#{summary} $if not (T.null $ itemImage item) <link rel="icon" href=#{itemImage item} > $if not (T.null $ itemPayment item) <link rel="payment" href=#{itemPayment item} > $forall d <- itemDownloads item <link rel="enclosure" type=#{typeTorrent} size=#{downloadSize d} href=#{url $ torrentLink d} > |] itemLink urlRender item = urlRender (UserFeedR (itemUser item) (itemSlug item)) `T.append` "#" `T.append` itemId item getNew :: RepFeed a => Handler a getNew = withDB (Model.recentDownloads def) >>= renderFeed' Parameters { pTitle = "Bitlove: New", pLink = NewR, pImage = "" } getNewRssR :: Handler RepRss getNewRssR = getNew getNewAtomR :: Handler RepAtom getNewAtomR = getNew getTop :: RepFeed a => Handler a getTop = withDB (Model.popularDownloads def) >>= renderFeed' Parameters { pTitle = "Bitlove: Top", pLink = TopR, pImage = "" } getTopRssR :: Handler RepRss getTopRssR = getTop getTopAtomR :: Handler RepAtom getTopAtomR = getTop getTopDownloaded :: RepFeed a => Period -> Handler a getTopDownloaded period = let (period_days, period_title) = case period of PeriodDays 1 -> (1, "1 day") PeriodDays days -> (days, T.pack $ show days ++ " days") PeriodAll -> (10000, "all time") in withDB (Model.mostDownloaded period_days def) >>= renderFeed' Parameters { pTitle = "Bitlove: Top Downloaded in " `T.append` period_title, pLink = TopDownloadedR period, pImage = "" } getTopDownloadedRssR :: Period -> Handler RepRss getTopDownloadedRssR = getTopDownloaded getTopDownloadedAtomR :: Period -> Handler RepAtom getTopDownloadedAtomR = getTopDownloaded getUserDownloads :: RepFeed a => UserName -> Handler a getUserDownloads user = do (details, downloads) <- withDB $ \db -> do details <- Model.userDetailsByName user db downloads <- Model.userDownloads user def db return (details, downloads) case details of [] -> notFound (details':_) -> renderFeed' Parameters { pTitle = userName user `T.append` " on Bitlove", pLink = UserR user, pImage = userImage details' } downloads getUserDownloadsRssR :: UserName -> Handler RepRss getUserDownloadsRssR = getUserDownloads getUserDownloadsAtomR :: UserName -> Handler RepAtom getUserDownloadsAtomR = getUserDownloads getUserFeed :: RepFeed a => UserName -> Text -> Handler a getUserFeed user slug = do mFeedDownloads <- withDB $ \db -> do feeds <- Model.userFeedInfo user slug db case feeds of [] -> return Nothing (feed:_) -> (Just . (feed, )) `fmap` Model.feedDownloads (feedUrl feed) def db case mFeedDownloads of Nothing -> notFound Just (feed, downloads) -> renderFeed' Parameters { pTitle = feedTitle feed `T.append` " on Bitlove" , pLink = UserFeedR user slug , pImage = feedImage feed } downloads getUserFeedRssR :: UserName -> Text -> Handler RepRss getUserFeedRssR = getUserFeed getUserFeedAtomR :: UserName -> Text -> Handler RepAtom getUserFeedAtomR = getUserFeed
jannschu/bitlove-ui
Handler/DownloadFeeds.hs
Haskell
bsd-2-clause
7,345
{-# LANGUAGE GADTs #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} -- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * 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. -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- 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 Feldspar.Core.Constructs.Tuple ( module Language.Syntactic.Constructs.Tuple ) where import Data.Tuple.Select import Language.Syntactic import Language.Syntactic.Constructs.Binding import Language.Syntactic.Constructs.Binding.HigherOrder (CLambda) import Language.Syntactic.Constructs.Tuple import Feldspar.Core.Types import Feldspar.Core.Interpretation import Feldspar.Core.Constructs.Binding instance Sharable Tuple instance SizeProp (Tuple :|| Type) where sizeProp (C' Tup2) (a :* b :* Nil) | WrapFull ia <- a , WrapFull ib <- b = (infoSize ia, infoSize ib) sizeProp (C' Tup3) (a :* b :* c :* Nil) | WrapFull ia <- a , WrapFull ib <- b , WrapFull ic <- c = ( infoSize ia , infoSize ib , infoSize ic ) sizeProp (C' Tup4) (a :* b :* c :* d :* Nil) | WrapFull ia <- a , WrapFull ib <- b , WrapFull ic <- c , WrapFull id <- d = ( infoSize ia , infoSize ib , infoSize ic , infoSize id ) sizeProp (C' Tup5) (a :* b :* c :* d :* e :* Nil) | WrapFull ia <- a , WrapFull ib <- b , WrapFull ic <- c , WrapFull id <- d , WrapFull ie <- e = ( infoSize ia , infoSize ib , infoSize ic , infoSize id , infoSize ie ) sizeProp (C' Tup6) (a :* b :* c :* d :* e :* g :* Nil) | WrapFull ia <- a , WrapFull ib <- b , WrapFull ic <- c , WrapFull id <- d , WrapFull ie <- e , WrapFull ig <- g = ( infoSize ia , infoSize ib , infoSize ic , infoSize id , infoSize ie , infoSize ig ) sizeProp (C' Tup7) (a :* b :* c :* d :* e :* g :* h :* Nil) | WrapFull ia <- a , WrapFull ib <- b , WrapFull ic <- c , WrapFull id <- d , WrapFull ie <- e , WrapFull ig <- g , WrapFull ih <- h = ( infoSize ia , infoSize ib , infoSize ic , infoSize id , infoSize ie , infoSize ig , infoSize ih ) instance Sharable Select where sharable _ = False sel1Size :: (Sel1' a ~ b) => TypeRep a -> Size a -> Size b sel1Size Tup2Type{} = sel1 sel1Size Tup3Type{} = sel1 sel1Size Tup4Type{} = sel1 sel1Size Tup5Type{} = sel1 sel1Size Tup6Type{} = sel1 sel1Size Tup7Type{} = sel1 sel2Size :: (Sel2' a ~ b) => TypeRep a -> (Size a -> Size b) sel2Size Tup2Type{} = sel2 sel2Size Tup3Type{} = sel2 sel2Size Tup4Type{} = sel2 sel2Size Tup5Type{} = sel2 sel2Size Tup6Type{} = sel2 sel2Size Tup7Type{} = sel2 sel3Size :: (Sel3' a ~ b) => TypeRep a -> (Size a -> Size b) sel3Size Tup3Type{} = sel3 sel3Size Tup4Type{} = sel3 sel3Size Tup5Type{} = sel3 sel3Size Tup6Type{} = sel3 sel3Size Tup7Type{} = sel3 sel4Size :: (Sel4' a ~ b) => TypeRep a -> (Size a -> Size b) sel4Size Tup4Type{} = sel4 sel4Size Tup5Type{} = sel4 sel4Size Tup6Type{} = sel4 sel4Size Tup7Type{} = sel4 sel5Size :: (Sel5' a ~ b) => TypeRep a -> (Size a -> Size b) sel5Size Tup5Type{} = sel5 sel5Size Tup6Type{} = sel5 sel5Size Tup7Type{} = sel5 sel6Size :: (Sel6' a ~ b) => TypeRep a -> (Size a -> Size b) sel6Size Tup6Type{} = sel6 sel6Size Tup7Type{} = sel6 sel7Size :: (Sel7' a ~ b) => TypeRep a -> (Size a -> Size b) sel7Size Tup7Type{} = sel7 instance SizeProp (Select :|| Type) where sizeProp (C' Sel1) (WrapFull ia :* Nil) = sel1Size (infoType ia) (infoSize ia) sizeProp (C' Sel2) (WrapFull ia :* Nil) = sel2Size (infoType ia) (infoSize ia) sizeProp (C' Sel3) (WrapFull ia :* Nil) = sel3Size (infoType ia) (infoSize ia) sizeProp (C' Sel4) (WrapFull ia :* Nil) = sel4Size (infoType ia) (infoSize ia) sizeProp (C' Sel5) (WrapFull ia :* Nil) = sel5Size (infoType ia) (infoSize ia) sizeProp (C' Sel6) (WrapFull ia :* Nil) = sel6Size (infoType ia) (infoSize ia) sizeProp (C' Sel7) (WrapFull ia :* Nil) = sel7Size (infoType ia) (infoSize ia) -- | Compute a witness that a symbol and an expression have the same result type tupEq :: Type (DenResult a) => sym a -> ASTF (Decor Info dom) b -> Maybe (TypeEq (DenResult a) b) tupEq _ b = typeEq typeRep (infoType $ getInfo b) instance ( (Tuple :|| Type) :<: dom , (Select :|| Type) :<: dom , OptimizeSuper dom ) => Optimize (Tuple :|| Type) dom where constructFeatOpt _ (C' tup@Tup2) (s1 :* s2 :* Nil) | (prjF -> Just (C' Sel1)) :$ a <- s1 , (prjF -> Just (C' Sel2)) :$ b <- s2 , alphaEq a b , Just TypeEq <- tupEq tup a = return a constructFeatOpt _ (C' tup@Tup3) (s1 :* s2 :* s3 :* Nil) | (prjF -> Just (C' Sel1)) :$ a <- s1 , (prjF -> Just (C' Sel2)) :$ b <- s2 , (prjF -> Just (C' Sel3)) :$ c <- s3 , alphaEq a b , alphaEq a c , Just TypeEq <- tupEq tup a = return a constructFeatOpt _ (C' tup@Tup4) (s1 :* s2 :* s3 :* s4 :* Nil) | (prjF -> Just (C' Sel1)) :$ a <- s1 , (prjF -> Just (C' Sel2)) :$ b <- s2 , (prjF -> Just (C' Sel3)) :$ c <- s3 , (prjF -> Just (C' Sel4)) :$ d <- s4 , alphaEq a b , alphaEq a c , alphaEq a d , Just TypeEq <- tupEq tup a = return a constructFeatOpt _ (C' tup@Tup5) (s1 :* s2 :* s3 :* s4 :* s5 :* Nil) | (prjF -> Just (C' Sel1)) :$ a <- s1 , (prjF -> Just (C' Sel2)) :$ b <- s2 , (prjF -> Just (C' Sel3)) :$ c <- s3 , (prjF -> Just (C' Sel4)) :$ d <- s4 , (prjF -> Just (C' Sel5)) :$ e <- s5 , alphaEq a b , alphaEq a c , alphaEq a d , alphaEq a e , Just TypeEq <- tupEq tup a = return a constructFeatOpt _ (C' tup@Tup6) (s1 :* s2 :* s3 :* s4 :* s5 :* s6 :* Nil) | (prjF -> Just (C' Sel1)) :$ a <- s1 , (prjF -> Just (C' Sel2)) :$ b <- s2 , (prjF -> Just (C' Sel3)) :$ c <- s3 , (prjF -> Just (C' Sel4)) :$ d <- s4 , (prjF -> Just (C' Sel5)) :$ e <- s5 , (prjF -> Just (C' Sel6)) :$ f <- s6 , alphaEq a b , alphaEq a c , alphaEq a d , alphaEq a e , alphaEq a f , Just TypeEq <- tupEq tup a = return a constructFeatOpt _ (C' tup@Tup7) (s1 :* s2 :* s3 :* s4 :* s5 :* s6 :* s7 :* Nil) | (prjF -> Just (C' Sel1)) :$ a <- s1 , (prjF -> Just (C' Sel2)) :$ b <- s2 , (prjF -> Just (C' Sel3)) :$ c <- s3 , (prjF -> Just (C' Sel4)) :$ d <- s4 , (prjF -> Just (C' Sel5)) :$ e <- s5 , (prjF -> Just (C' Sel6)) :$ f <- s6 , (prjF -> Just (C' Sel7)) :$ g <- s7 , alphaEq a b , alphaEq a c , alphaEq a d , alphaEq a e , alphaEq a f , alphaEq a g , Just TypeEq <- tupEq tup a = return a constructFeatOpt opts feat args = constructFeatUnOpt opts feat args constructFeatUnOpt opts x@(C' _) = constructFeatUnOptDefault opts x instance ( (Select :|| Type) :<: dom , CLambda Type :<: dom , (Tuple :|| Type) :<: dom , Let :<: dom , (Variable :|| Type) :<: dom , OptimizeSuper dom ) => Optimize (Select :|| Type) dom where constructFeatOpt opts s@(C' Sel1) (t :* Nil) | ((prjF -> Just (C' Tup2)) :$ a :$ _) <- t = return a | ((prjF -> Just (C' Tup3)) :$ a :$ _ :$ _) <- t = return a | ((prjF -> Just (C' Tup4)) :$ a :$ _ :$ _ :$ _) <- t = return a | ((prjF -> Just (C' Tup5)) :$ a :$ _ :$ _ :$ _ :$ _) <- t = return a | ((prjF -> Just (C' Tup6)) :$ a :$ _ :$ _ :$ _ :$ _ :$ _) <- t = return a | ((prjF -> Just (C' Tup7)) :$ a :$ _ :$ _ :$ _ :$ _ :$ _ :$ _) <- t = return a | ((prj -> Just Let) :$ a :$ (lam :$ b)) <- t , (Just v@(SubConstr2 (Lambda {}))) <- prjLambda lam = do s' <- constructFeatOpt opts s (b :* Nil) b' <- constructFeatOpt opts (reuseCLambda v) (s' :* Nil) constructFeatOpt opts Let (a :* b' :* Nil) constructFeatOpt opts s@(C' Sel2) (t :* Nil) | ((prjF -> Just (C' Tup2)) :$ _ :$ a) <- t = return a | ((prjF -> Just (C' Tup3)) :$ _ :$ a :$ _) <- t = return a | ((prjF -> Just (C' Tup4)) :$ _ :$ a :$ _ :$ _) <- t = return a | ((prjF -> Just (C' Tup5)) :$ _ :$ a :$ _ :$ _ :$ _) <- t = return a | ((prjF -> Just (C' Tup6)) :$ _ :$ a :$ _ :$ _ :$ _ :$ _) <- t = return a | ((prjF -> Just (C' Tup7)) :$ _ :$ a :$ _ :$ _ :$ _ :$ _ :$ _) <- t = return a | ((prj -> Just Let) :$ a :$ (lam :$ b)) <- t , (Just v@(SubConstr2 (Lambda {}))) <- prjLambda lam = do s' <- constructFeatOpt opts s (b :* Nil) b' <- constructFeatOpt opts (reuseCLambda v) (s' :* Nil) constructFeatOpt opts Let (a :* b' :* Nil) constructFeatOpt opts s@(C' Sel3) (t :* Nil) | ((prjF -> Just (C' Tup3)) :$ _ :$ _ :$ a) <- t = return a | ((prjF -> Just (C' Tup4)) :$ _ :$ _ :$ a :$ _) <- t = return a | ((prjF -> Just (C' Tup5)) :$ _ :$ _ :$ a :$ _ :$ _) <- t = return a | ((prjF -> Just (C' Tup6)) :$ _ :$ _ :$ a :$ _ :$ _ :$ _) <- t = return a | ((prjF -> Just (C' Tup7)) :$ _ :$ _ :$ a :$ _ :$ _ :$ _ :$ _) <- t = return a | ((prj -> Just Let) :$ a :$ (lam :$ b)) <- t , (Just v@(SubConstr2 (Lambda {}))) <- prjLambda lam = do s' <- constructFeatOpt opts s (b :* Nil) b' <- constructFeatOpt opts (reuseCLambda v) (s' :* Nil) constructFeatOpt opts Let (a :* b' :* Nil) constructFeatOpt opts s@(C' Sel4) (t :* Nil) | ((prjF -> Just (C' Tup4)) :$ _ :$ _ :$ _ :$ a) <- t = return a | ((prjF -> Just (C' Tup5)) :$ _ :$ _ :$ _ :$ a :$ _) <- t = return a | ((prjF -> Just (C' Tup6)) :$ _ :$ _ :$ _ :$ a :$ _ :$ _) <- t = return a | ((prjF -> Just (C' Tup7)) :$ _ :$ _ :$ _ :$ a :$ _ :$ _ :$ _) <- t = return a | ((prj -> Just Let) :$ a :$ (lam :$ b)) <- t , (Just v@(SubConstr2 (Lambda {}))) <- prjLambda lam = do s' <- constructFeatOpt opts s (b :* Nil) b' <- constructFeatOpt opts (reuseCLambda v) (s' :* Nil) constructFeatOpt opts Let (a :* b' :* Nil) constructFeatOpt opts s@(C' Sel5) (t :* Nil) | ((prjF -> Just (C' Tup5)) :$ _ :$ _ :$ _ :$ _ :$ a) <- t = return a | ((prjF -> Just (C' Tup6)) :$ _ :$ _ :$ _ :$ _ :$ a :$ _) <- t = return a | ((prjF -> Just (C' Tup7)) :$ _ :$ _ :$ _ :$ _ :$ a :$ _ :$ _) <- t = return a | ((prj -> Just Let) :$ a :$ (lam :$ b)) <- t , (Just v@(SubConstr2 (Lambda {}))) <- prjLambda lam = do s' <- constructFeatOpt opts s (b :* Nil) b' <- constructFeatOpt opts (reuseCLambda v) (s' :* Nil) constructFeatOpt opts Let (a :* b' :* Nil) constructFeatOpt opts s@(C' Sel6) (t :* Nil) | ((prjF -> Just (C' Tup6)) :$ _ :$ _ :$ _ :$ _ :$ _ :$ a) <- t = return a | ((prjF -> Just (C' Tup7)) :$ _ :$ _ :$ _ :$ _ :$ _ :$ a :$ _) <- t = return a | ((prj -> Just Let) :$ a :$ (lam :$ b)) <- t , (Just v@(SubConstr2 (Lambda {}))) <- prjLambda lam = do s' <- constructFeatOpt opts s (b :* Nil) b' <- constructFeatOpt opts (reuseCLambda v) (s' :* Nil) constructFeatOpt opts Let (a :* b' :* Nil) constructFeatOpt opts s@(C' Sel7) (t :* Nil) | ((prjF -> Just (C' Tup7)) :$ _ :$ _ :$ _ :$ _ :$ _ :$ _ :$ a) <- t = return a | ((prj -> Just Let) :$ a :$ (lam :$ b)) <- t , (Just v@(SubConstr2 (Lambda {}))) <- prjLambda lam = do s' <- constructFeatOpt opts s (b :* Nil) b' <- constructFeatOpt opts (reuseCLambda v) (s' :* Nil) constructFeatOpt opts Let (a :* b' :* Nil) constructFeatOpt opts feat args = constructFeatUnOpt opts feat args constructFeatUnOpt opts x@(C' _) = constructFeatUnOptDefault opts x
rCEx/feldspar-lang-small
src/Feldspar/Core/Constructs/Tuple.hs
Haskell
bsd-3-clause
14,139
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.KHR.ParallelShaderCompile -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.KHR.ParallelShaderCompile ( -- * Extension Support glGetKHRParallelShaderCompile, gl_KHR_parallel_shader_compile, -- * Enums pattern GL_COMPLETION_STATUS_KHR, pattern GL_MAX_SHADER_COMPILER_THREADS_KHR, -- * Functions glMaxShaderCompilerThreadsKHR ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/KHR/ParallelShaderCompile.hs
Haskell
bsd-3-clause
813
{-# LANGUAGE OverloadedStrings #-} import Language.Swift.Quote.Syntax import Language.Swift.Quote.Pretty import Control.Arrow (left, right) import Language.Swift.Quote.Parser import qualified Data.ByteString.Lazy.Char8 as C import Data.Either import qualified Data.Text.Lazy as L import qualified Data.Text as T import qualified Data.Text.IO as DTI import Debug.Trace import System.IO import System.FilePath import Test.Tasty import Test.Tasty.Golden import Test.Tasty.HUnit import qualified Text.Parsec.Text as P import qualified Text.ParserCombinators.Parsec as PC import Text.PrettyPrint.Mainland (Pretty, ppr, prettyLazyText) main :: IO () main = do hSetBuffering stdout NoBuffering hSetBuffering stderr NoBuffering swifts <- findByExtension [".swift"] "tests/golden" defaultMain $ testGroup "Unit" [ operatorTests , src2ast , src2ast2src , swifts2Goldens swifts ] swifts2Goldens :: [FilePath] -> TestTree swifts2Goldens paths = testGroup "Golden" $ map swift2Golden paths where swift2Golden s = mkTest s (s <.> "golden") mkTest s g = goldenVsStringDiff (dropExtension s) diffCmd g (file2ast2bytestring s) diffCmd ref new = ["diff", "--unified=5", ref, new] text2ast2string :: T.Text -> String text2ast2string input = case parse input of (Left err) -> err (Right m) -> L.unpack $ prettyPrint (trace ("\n\n" ++ show m ++ "\n\n") m) file2ast2bytestring :: String -> IO C.ByteString file2ast2bytestring fileName = do contents <- DTI.readFile fileName return (C.pack (text2ast2string contents)) litIntExp :: Integer -> Expression litIntExp i = litExp (NumericLiteral (show i)) litStrExp :: String -> Expression litStrExp s = litExp (StringLiteral (StaticStringLiteral s)) parserToEither :: P.Parser a -> T.Text -> Either String a parserToEither p input = left show (PC.parse p "<stdin>" input) goodOperator :: String -> T.Text -> TestTree goodOperator o input = testCase ("good operator: " ++ wrap o ++ " input " ++ wrap (T.unpack input)) $ parserToEither (op o) input @?= Right () badOperator :: String -> T.Text -> TestTree badOperator o input = testCase ("bad operator: " ++ wrap o ++ " input " ++ wrap (T.unpack input)) $ assertBool ("Expected left, got " ++ show e) (isLeft e) where e = parserToEither (op o) input operatorTests :: TestTree operatorTests = testGroup "Operator" [ goodOperator "&" "&" , goodOperator "&" "& " , goodOperator "&" " &" , goodOperator "&" " & " , goodOperator "<" "<" , goodOperator ">" ">" , goodOperator ">" ">" , goodOperator "+" "+" , goodOperator "-" "-" , goodOperator "*" "*" , goodOperator "/" "/" , goodOperator "!" "!" , goodOperator "?" "?" , goodOperator "++" "++" , goodOperator "->" "->" , goodOperator "=" "=" , badOperator ":" ":" , badOperator "." "." , badOperator ".." ".." , badOperator "..." "..." , badOperator "_" "_" , badOperator "," "," , badOperator "(" "(" , badOperator ")" ")" , badOperator "a" "a" , badOperator "foo" "foo" ] src2ast :: TestTree src2ast = testGroup "src2ast" [ expressionTest "1" $ litIntExp 1 , expressionTest "-1" $ Expression Nothing (PrefixExpression (Just "-") (PostfixPrimary (PrimaryLiteral (RegularLiteral (NumericLiteral "1"))))) [] , expressionTest " 2" $ litIntExp 2 , expressionTest "3 " $ litIntExp 3 , expressionTest " 10 " $ litIntExp 10 , expressionTest "1234567890" $ litIntExp 1234567890 , expressionTest "1.0" $ litExp (NumericLiteral "1.0") , expressionTest "1.1234567890" $ litExp (NumericLiteral "1.1234567890") , expressionTest "0xb10101111" $ litExp (NumericLiteral "0xb10101111") , expressionTest "0xCAFEBABE" $ litExp (NumericLiteral "0xCAFEBABE") , expressionTest "0o12345670" $ litExp (NumericLiteral "0o12345670") , expressionTest "\"Hello\"" $ litStrExp "Hello" , expressionTest " \"Hello\"" $ litStrExp "Hello" , expressionTest "\"Hello\" " $ litStrExp "Hello" , expressionTest " \"Hello\" " $ litStrExp "Hello" , expressionTest "true" $ litExp (BooleanLiteral True) , expressionTest "false" $ litExp (BooleanLiteral False) , expressionTest " true" $ litExp (BooleanLiteral True) , expressionTest "true " $ litExp (BooleanLiteral True) , expressionTest " true " $ litExp (BooleanLiteral True) , expressionTest " false" $ litExp (BooleanLiteral False) , expressionTest "false " $ litExp (BooleanLiteral False) , expressionTest " false " $ litExp (BooleanLiteral False) , expressionTest "&a" $ Expression Nothing (InOutExpression "a") [] , expressionTest "& b" $ Expression Nothing (InOutExpression "b") [] , expressionTest "self" $ self Self , expressionTest "self.a" $ self (SelfMethod "a") , expressionTest "self. a" $ self (SelfMethod "a") , expressionTest "self . a" $ self (SelfMethod "a") , expressionTest " self . a" $ self (SelfMethod "a") , expressionTest " self . a " $ self (SelfMethod "a") , expressionTest "self[1]" $ self (SelfSubscript [litIntExp 1]) , expressionTest "self[1,2]" $ self (SelfSubscript [litIntExp 1, litIntExp 2]) , expressionTest "self[1, 2]" $ self (SelfSubscript [litIntExp 1, litIntExp 2]) , expressionTest "self [1, 2]" $ self (SelfSubscript [litIntExp 1, litIntExp 2]) , expressionTest "self [ 1, 2 ]" $ self (SelfSubscript [litIntExp 1, litIntExp 2]) , expressionTest "self.init" $ self SelfInit , expressionTest "a.123" $ Expression Nothing (PrefixExpression Nothing (ExplicitMemberExpressionDigits (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "a", idgGenericArgs = []}))) "123")) [] , expressionTest "a.b" $ Expression Nothing (PrefixExpression Nothing (ExplicitMemberExpressionIdentifier (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "a", idgGenericArgs = []}))) (IdG {idgIdentifier = "b", idgGenericArgs = []}))) [] , expressionTest ".b" $ Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryImplicitMember "b"))) [] , expressionTest "foo" $ primary1 "foo" , expressionTest "a" $ primary1 "a" , expressionTest "a1" $ primary1 "a1" , expressionTest "xs" $ primary1 "xs" , expressionTest "1 is Int" $ typeCastExp (NumericLiteral "1") "is" (TypeIdentifierType (TypeIdentifier [("Int",[])])) , expressionTest "200 as Double" $ typeCastExp (NumericLiteral "200") "as" (TypeIdentifierType (TypeIdentifier [("Double",[])])) , expressionTest "\"s\" as? String" $ typeCastExp (StringLiteral (StaticStringLiteral "s")) "as?" (TypeIdentifierType (TypeIdentifier [("String",[])])) , expressionTest "\"s\" as! String" $ typeCastExp (StringLiteral (StaticStringLiteral "s")) "as!" (TypeIdentifierType (TypeIdentifier [("String",[])])) , expressionTest "a++" $ Expression Nothing (PrefixExpression Nothing (PostfixOperator (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "a", idgGenericArgs = []}))) "++")) [] , expressionTest "foo()" $ (Expression Nothing (PrefixExpression Nothing (FunctionCallE (FunctionCall (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "foo", idgGenericArgs = []}))) [] Nothing))) []) , expressionTest "foo(1)" $ Expression Nothing (PrefixExpression Nothing (FunctionCallE (FunctionCall (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "foo", idgGenericArgs = []}))) [ExpressionElement Nothing (Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryLiteral (RegularLiteral (NumericLiteral "1"))))) [])] Nothing))) [] , expressionTest "foo(1, 2)" $ Expression Nothing (PrefixExpression Nothing (FunctionCallE (FunctionCall (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "foo", idgGenericArgs = []}))) [ExpressionElement Nothing (Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryLiteral (RegularLiteral (NumericLiteral "1"))))) []),ExpressionElement Nothing (Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryLiteral (RegularLiteral (NumericLiteral "2"))))) [])] Nothing))) [] , expressionTest "foo(1, 2, isBlue: false)" $ Expression Nothing (PrefixExpression Nothing (FunctionCallE (FunctionCall (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "foo", idgGenericArgs = []}))) [ExpressionElement Nothing (Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryLiteral (RegularLiteral (NumericLiteral "1"))))) []),ExpressionElement Nothing (Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryLiteral (RegularLiteral (NumericLiteral "2"))))) []),ExpressionElement (Just "isBlue") (Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryLiteral (RegularLiteral (BooleanLiteral False))))) [])] Nothing))) [] , expressionTest "1.init" $ Expression Nothing (PrefixExpression Nothing (PostfixExpression4Initalizer (PostfixPrimary (PrimaryLiteral (RegularLiteral (NumericLiteral "1")))))) [] , expressionTest "a.init" $ Expression Nothing (PrefixExpression Nothing (PostfixExpression4Initalizer (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "a", idgGenericArgs = []}))))) [] , expressionTest "foo.init" $ Expression Nothing (PrefixExpression Nothing (PostfixExpression4Initalizer (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "foo", idgGenericArgs = []}))))) [] , expressionTest "a.self" $ Expression Nothing (PrefixExpression Nothing (PostfixSelf (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "a", idgGenericArgs = []}))))) [] , expressionTest "a.dynamicType" $ Expression Nothing (PrefixExpression Nothing (PostfixDynamicType (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "a", idgGenericArgs = []}))))) [] , expressionTest "a!" $ Expression Nothing (PrefixExpression Nothing (PostfixForcedValue (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "a", idgGenericArgs = []}))))) [] , expressionTest "a?" $ Expression Nothing (PrefixExpression Nothing (PostfixOptionChaining (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "a", idgGenericArgs = []}))))) [] , expressionTest "a[1]" $ Expression Nothing (PrefixExpression Nothing (Subscript (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "a", idgGenericArgs = []}))) [Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryLiteral (RegularLiteral (NumericLiteral "1"))))) []])) [] , expressionTest "try someThrowingFunction() + anotherThrowingFunction()" $ Expression (Just "try") (PrefixExpression Nothing (FunctionCallE (FunctionCall (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "someThrowingFunction", idgGenericArgs = []}))) [] Nothing))) [BinaryExpression1 {beOperator = "+", bePrefixExpression = PrefixExpression Nothing (FunctionCallE (FunctionCall (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "anotherThrowingFunction", idgGenericArgs = []}))) [] Nothing))}] , expressionTest "(try someThrowingFunction()) + anotherThrowingFunction()" $ Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryParenthesized [ExpressionElement Nothing (Expression (Just "try") (PrefixExpression Nothing (FunctionCallE (FunctionCall (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "someThrowingFunction", idgGenericArgs = []}))) [] Nothing))) []) ]))) [BinaryExpression1 {beOperator = "+", bePrefixExpression = PrefixExpression Nothing (FunctionCallE (FunctionCall (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "anotherThrowingFunction", idgGenericArgs = []}))) [] Nothing))}] , moduleTest "import foo" $ singleImport Nothing ["foo"] , moduleTest "import foo.math.BitVector" $ singleImport Nothing ["foo", "math", "BitVector"] , moduleTest "import typealias foo.a.b" $ singleImport (Just "typealias") ["foo", "a", "b"] , moduleTest "print(\"Hello world\\n\")" $ Module [ExpressionStatement (Expression Nothing (PrefixExpression Nothing (FunctionCallE (FunctionCall (PostfixPrimary (PrimaryExpression1 (IdG {idgIdentifier = "print", idgGenericArgs = []}))) [ExpressionElement Nothing (Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryLiteral (RegularLiteral (StringLiteral (StaticStringLiteral"Hello world\n")))))) [])] Nothing))) [])] , moduleTest "let n = 1" $ Module [DeclarationStatement (ConstantDeclaration [] [] [PatternInitializer (IdentifierPattern "n" Nothing) (Just (Initializer (Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryLiteral (RegularLiteral (NumericLiteral "1"))))) [])))])] , moduleTest "var d = 1.0" $ Module [DeclarationStatement (DeclVariableDeclaration (VarDeclPattern [] [] [PatternInitializer (IdentifierPattern "d" Nothing) (Just (Initializer (Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryLiteral (RegularLiteral (NumericLiteral "1.0"))))) [])))]))] , moduleTest "typealias TypeAliasName = String" $ Module [DeclarationStatement (TypeAlias [] Nothing "TypeAliasName" (TypeIdentifierType (TypeIdentifier [("String",[])])))] ] singleImport :: Maybe ImportKind -> [String] -> Module singleImport optImportKind imports = Module [DeclarationStatement (import_ optImportKind (map ImportIdentifier imports))] import_ :: Maybe ImportKind -> ImportPath -> Declaration import_ = ImportDeclaration [] src2ast2src :: TestTree src2ast2src = testGroup "src2ast2src" [ ppExpTest "1" "1" , ppExpTest "2 " "2" , ppExpTest " 3" "3" , ppExpTest " 4 " "4" , ppExpTest "\"Hello\"" "\"Hello\"" , ppExpTest "\"foo\"" "\"foo\"" , ppExpTest " \"x\"" "\"x\"" , ppExpTest " \"y\" " "\"y\"" , ppExpTest " true " "true" , ppExpTest "true" "true" , ppExpTest " \t false " "false" , ppExpTest "self" "self" , ppExpTest "self . id" "self.id" , ppExpTest "self . init" "self.init" , ppExpTest "self [1,2, 3] " "self[1, 2, 3]" , ppExpTest "foo()" "foo()" , ppExpTest "foo( ) " "foo()" , ppExpTest "foo ( ) " "foo()" , ppExpTest "foo (false ) " "foo(false)" , ppExpTest "foo (a ) " "foo(a)" , ppExpTest "foo ( 1, 2 , isFred : true)" "foo(1, 2, isFred: true)" ] primary1 :: String -> Expression primary1 ident = Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryExpression1 (IdG ident [])))) [] typeCastExp :: Literal -> String -> Type -> Expression typeCastExp lit typeCastKind t = Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryLiteral (RegularLiteral lit)))) [BinaryExpression4 typeCastKind t] litExp :: Literal -> Expression litExp lit = Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimaryLiteral (RegularLiteral lit)))) [] self :: SelfExpression -> Expression self se = Expression Nothing (PrefixExpression Nothing (PostfixPrimary (PrimarySelf se))) [] wrap :: String -> String wrap s = "[[" ++ s ++ "]]" moduleTest :: T.Text -> Module -> TestTree moduleTest input m = testCase ("module: " ++ wrap (T.unpack input)) $ parse input @?= Right m expressionTest :: T.Text -> Expression -> TestTree expressionTest input e = testCase ("expression: " ++ wrap (T.unpack input)) $ parseExpression input @?= Right e pp :: Pretty pretty => Either d pretty -> Either d L.Text pp = right (prettyLazyText 100 . ppr) ppExpTest :: T.Text -> String -> TestTree ppExpTest input s = testCase ("expression " ++ wrap (T.unpack input) ++ " => " ++ wrap s) $ sosrc @?= Right s where ast = parseExpression input osrc = pp ast sosrc = fmap L.unpack osrc
steshaw/language-swift-quote
tests/unit/Main.hs
Haskell
bsd-3-clause
15,523
{-# LANGUAGE OverloadedStrings #-} module Main where import Network.Socks5 import Network.Socks5.Types import Network.Socks5.Lowlevel import Network.Socket hiding (recv, recvFrom, sendTo) import Network.Socket.ByteString import Control.Concurrent import Data.List (find) import Data.Foldable (for_) import Data.Serialize (encode,decode) import Control.Monad import Control.Exception import System.IO import System.IO.Error import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString as B import Data.ByteString (ByteString) import BinaryHandle ------------------------------------------------------------------------ -- Configuration ------------------------------------------------------------------------ data Configuration = Configuration { listenHost :: HostName , listenService :: ServiceName , debugLevel :: Verbosity , logLock :: MVar () , configUser :: ByteString , configPass :: ByteString , authPreference :: [SocksMethod] , bindAddress :: SockAddr , forceLearningMode :: Bool } data Verbosity = VInfo | VDebug deriving (Read, Show, Eq, Ord) getConfiguration = do logMutex <- newMVar () return (Configuration "" "2080" VDebug logMutex "emertens" "paswerd" [SocksMethodUsernamePassword,SocksMethodNone] (SockAddrInet aNY_PORT iNADDR_ANY) True) ------------------------------------------------------------------------ -- Logging ------------------------------------------------------------------------ logMsg :: Verbosity -> Configuration -> String -> IO () logMsg level config msg = when (level <= debugLevel config) $ do threadId <- myThreadId let msg' = drop 9 (show threadId) ++ ": " ++ msg withMVar (logLock config) (const (hPutStrLn stderr msg')) info :: Configuration -> String -> IO () info = logMsg VInfo debug :: Configuration -> String -> IO () debug = logMsg VDebug ------------------------------------------------------------------------ -- Main ------------------------------------------------------------------------ main :: IO () main = withSocketsDo $ do config <- getConfiguration let hints = tcpHints { addrFlags = [AI_PASSIVE, AI_ADDRCONFIG] } ais <- getAddrInfo (Just hints) (Just (listenHost config)) (Just (listenService config)) when (null ais) (fail "Failed to resolve listening address") done <- newEmptyMVar for_ ais $ \ai -> forkIO (listenerLoop config ai `finally` putMVar done ()) takeMVar done ------------------------------------------------------------------------ -- Top-level listener ------------------------------------------------------------------------ listenerLoop :: Configuration -> AddrInfo -> IO () listenerLoop config ai = withTcpSocket (addrFamily ai) $ \s -> do setSocketOption s ReuseAddr 1 -- We support binding on multiple addresses. Keeping them separate -- will help later when we're making additional connections for UDP. when (addrFamily ai == AF_INET6) (setSocketOption s IPv6Only 1) bind s (addrAddress ai) info config ("Listening on " ++ show (addrAddress ai)) listen s maxListenQueue forever $ do (c,who) <- accept s cxt <- newGetContext info config ("Connection accepted from " ++ show who) forkIO (handleClientHello config c cxt who `finally` sClose c) ------------------------------------------------------------------------ -- Client startup ------------------------------------------------------------------------ handleClientHello :: Configuration -> Socket -> GetContext -> SockAddr -> IO () handleClientHello config s cxt who = do debug config ("Client thread started for " ++ show who) SocksHello authTypes <- recvGet s cxt debug config ("Client proposed " ++ show authTypes) debug config ("Server supports " ++ show (authPreference config)) case find (`elem` authTypes) (authPreference config) of Just SocksMethodNone -> do debug config "No authentication selected" sendSerialized s (SocksHelloResponse SocksMethodNone) readyForClientRequest config s cxt who Just SocksMethodUsernamePassword -> do debug config "Username/password authentication selected" sendSerialized s (SocksHelloResponse SocksMethodUsernamePassword) login <- recvGet s cxt if configUser config == plainUsername login && configPass config == plainPassword login then do debug config "Authentication succeeded" sendSerialized s SocksPlainLoginSuccess readyForClientRequest config s cxt who else do debug config "Authentication failed" sendSerialized s SocksPlainLoginFailure _ -> do debug config "Authentication failed" sendSerialized s (SocksHelloResponse SocksMethodNotAcceptable) ------------------------------------------------------------------------ -- Post authentication ------------------------------------------------------------------------ readyForClientRequest :: Configuration -> Socket -> GetContext -> SockAddr -> IO () readyForClientRequest config s cxt who = do req <- recvGet s cxt mbDst <- resolveSocksAddress config (requestDst req) case mbDst of Nothing -> do info config "Connection failed" sendSerialized s (errorResponse SocksErrorHostUnreachable) Just dst -> do handleClientRequest (requestCommand req) config s who dst ------------------------------------------------------------------------ -- Request modes ------------------------------------------------------------------------ handleClientRequest :: SocksCommand -> Configuration -> Socket -> SockAddr -> SockAddr -> IO () handleClientRequest SocksCommandConnect config s who dst = flip finally (debug config "Thread complete") $ withTcpSocket (sockAddrFamily dst) $ \c -> do debug config ("Connecting to " ++ show dst) connectResult <- tryIOError (connect c dst) case connectResult of Left err -> do info config ("Connect failed with " ++ show err) sendSerialized s (errorResponse SocksErrorConnectionRefused) Right () -> do info config ("Connected to " ++ show dst) localAddr <- sockAddrToSocksAddress `fmap` getSocketName c sendSerialized s (SocksResponse SocksReplySuccess localAddr) tcpRelay config s c handleClientRequest SocksCommandBind config s who dst = flip finally (info config "Thread Complete") $ withTcpSocket (sockAddrFamily dst) $ \c -> do debug config "Binding TCP socket" bind c (bindAddress config) listen c 0 boundAddr <- getSocketName c info config ("Socket bound to " ++ show boundAddr) sendSerialized s (SocksResponse SocksReplySuccess (sockAddrToSocksAddress boundAddr)) bracket (accept c) (sClose.fst) $ \(c1,who) -> do debug config ("Connection received from " ++ show who) sendSerialized s (SocksResponse SocksReplySuccess (sockAddrToSocksAddress who)) tcpRelay config s c1 handleClientRequest SocksCommandUdpAssociate config s who dst = flip finally (info config "Thread Complete") $ getSocketName s >>= \localAddr -> withUdpSocket (sockAddrFamily localAddr) $ \c1 -> withUdpSocket (sockAddrFamily localAddr) $ \c2 -> do debug config "Associating UDP socket" debug config ("Client UDP address: " ++ show dst) bind c1 (setPort 0 localAddr) localDataAddr <- getSocketName c1 debug config ("Server UDP address: " ++ show localDataAddr) bind c2 (wildAddress (sockAddrFamily localAddr)) remoteDataAddr <- getSocketName c2 info config ("UDP outgoing socket bound to " ++ show remoteDataAddr) sendSerialized s (SocksResponse SocksReplySuccess (sockAddrToSocksAddress localDataAddr)) let relay = if forceLearningMode config || isWild dst then learningUdpRelay else udpRelay relay config c1 c2 dst -- UDP connections are preserved until the control connection goes down setSocketOption s KeepAlive 1 recv s 1 return () handleClientRequest cmd config s who _ = do info config ("Unsupported command " ++ show cmd) sendSerialized s (errorResponse SocksErrorCommandNotSupported) isWild (SockAddrInet p h ) = p == aNY_PORT || h == iNADDR_ANY isWild (SockAddrInet6 p _ h _) = p == aNY_PORT || h == iN6ADDR_ANY isWild (SockAddrUnix _ ) = error "isWild: SockAddrUnix not supported" discardIOErrors m = catchIOError m (const (return ())) learningUdpRelay :: Configuration -> Socket -> Socket -> SockAddr -> IO () learningUdpRelay config c1 c2 dst = do debug config "UDP address learning mode" forkIO (discardIOErrors handleFirst) return () where handleFirst = do (bs,src) <- recvFrom c1 4096 debug config ("-> client " ++ show src ++ " (" ++ show (B.length bs) ++ ")") case decode bs of Right udp | udpFragment udp == 0 -> do mbAddr <- resolveSocksAddress config (udpRemoteAddr udp) case mbAddr of Nothing -> do debug config ("Dropping unresolvable packet: " ++ show (udpRemoteAddr udp)) Just addr -> do let cnts = udpContents udp debug config ("<- remote " ++ show addr ++ " (" ++ show (B.length cnts) ++ ")") sendTo c2 cnts addr return () udpRelay config c1 c2 src Left err -> do debug config ("Ignoring malformed UDP packet: " ++ err) handleFirst udpRelay :: Configuration -> Socket -> Socket -> SockAddr -> IO () udpRelay config c1 c2 dst = do _forwardThread <- forkIO $ discardIOErrors $ forever $ do (bs,src) <- recvFrom c1 4096 debug config ("-> client " ++ show src ++ " (" ++ show (B.length bs) ++ ")") case (src == dst, decode bs) of (False,_) -> debug config "Dropping UDP packet due to source mismatch" (_,Left err) -> debug config ("Dropping malformed UDP packet: " ++ err) (_,Right udp) | udpFragment udp /= 0 -> debug config ("Dropping fragmented UDP packet: " ++ show (udpFragment udp)) (True, Right udp) -> do mbAddr <- resolveSocksAddress config (udpRemoteAddr udp) case mbAddr of Nothing -> do debug config "Dropping unresolvable packet" Just addr -> do let cnts = udpContents udp debug config ("<- remote " ++ show addr ++ " (" ++ show (B.length cnts) ++ ")") sendTo c2 cnts addr return () _backwardThread <- forkIO $ discardIOErrors $ forever $ do (msg, remote) <- recvFrom c2 4096 debug config ("-> remote " ++ show remote ++ " (" ++ show (B.length msg) ++ ")") let cnts = encode (SocksUdpEnvelope 0 (sockAddrToSocksAddress remote) msg) debug config ("<- client " ++ show dst ++ " (" ++ show (B.length cnts) ++ ")") sendTo c1 cnts dst return () ------------------------------------------------------------------------ -- TCP Proxy ------------------------------------------------------------------------ tcpRelay :: Configuration -> Socket -> Socket -> IO () tcpRelay config s c = do done <- newEmptyMVar t1 <- forkIO (shuttle config s c `finally` putMVar done ()) t2 <- forkIO (shuttle config c s `finally` putMVar done ()) takeMVar done takeMVar done shuttle :: Configuration -> Socket -> Socket -> IO () shuttle config source sink = loop `finally` cleanup where cleanup = do _ <- tryIOError (shutdown source ShutdownReceive) _ <- tryIOError (shutdown sink ShutdownSend) return () loop = do sourcePeer <- getPeerName source sourceName <- getSocketName source sinkName <- getSocketName sink sinkPeer <- getPeerName sink bs <- recv source (8*4096) unless (B.null bs) $ do sendAll sink bs debug config (show sourcePeer ++ " -> " ++ show sourceName ++ " : " ++ show sinkName ++ " -> " ++ show sinkPeer ++ " (" ++ show (B.length bs) ++ ")") loop ------------------------------------------------------------------------ -- Address utilities ------------------------------------------------------------------------ sockAddrToSocksAddress :: SockAddr -> SocksAddress sockAddrToSocksAddress (SockAddrInet p h ) = SocksAddress (SocksAddrIPV4 h) p sockAddrToSocksAddress (SockAddrInet6 p _ h _) = SocksAddress (SocksAddrIPV6 h) p sockAddrToSocksAddress (SockAddrUnix _ ) = error "sockAddrToSocksAddress: Unix sockets not supported" sockAddrFamily :: SockAddr -> Family sockAddrFamily SockAddrInet {} = AF_INET sockAddrFamily SockAddrInet6 {} = AF_INET6 sockAddrFamily SockAddrUnix {} = AF_UNIX errorResponse :: SocksError -> SocksResponse errorResponse err = (SocksResponse (SocksReplyError err) (SocksAddress (SocksAddrIPV4 iNADDR_ANY) aNY_PORT)) resolveSocksAddress :: Configuration -> SocksAddress -> IO (Maybe SockAddr) resolveSocksAddress config (SocksAddress host port) = case host of SocksAddrIPV4 a -> return (Just (SockAddrInet port a )) SocksAddrIPV6 a -> return (Just (SockAddrInet6 port 0 a 0)) SocksAddrDomainName str -> do let hostname = B8.unpack str ais <- getAddrInfo (Just tcpHints) (Just hostname) (Just (show port)) case ais of ai : _ -> do let addr = addrAddress ai debug config ("Resolved " ++ hostname ++ " to " ++ show addr) return (Just addr) [] -> do debug config ("Unable to resolve " ++ B8.unpack str) return Nothing tcpHints :: AddrInfo tcpHints = defaultHints { addrSocketType = Stream , addrFlags = [AI_ADDRCONFIG] } setPort :: PortNumber -> SockAddr -> SockAddr setPort port (SockAddrInet _ host ) = SockAddrInet port host setPort port (SockAddrInet6 _ flow host scope) = SockAddrInet6 port flow host scope setPort _ SockAddrUnix {} = error "unix sockets don't have ports" getPort :: SockAddr -> PortNumber getPort (SockAddrInet port _ ) = port getPort (SockAddrInet6 port _ _ _) = port getPort SockAddrUnix {} = error "seriously, stop using unix sockets" wildAddress :: Family -> SockAddr wildAddress AF_INET = SockAddrInet aNY_PORT iNADDR_ANY wildAddress AF_INET6 = SockAddrInet6 aNY_PORT 0 iN6ADDR_ANY 0 withTcpSocket :: Family -> (Socket -> IO a) -> IO a withTcpSocket family = bracket (socket family Stream defaultProtocol) sClose withUdpSocket :: Family -> (Socket -> IO a) -> IO a withUdpSocket family = bracket (socket family Datagram defaultProtocol) sClose
glguy/s5s
Main.hs
Haskell
bsd-3-clause
14,540
{-# LANGUAGE ScopedTypeVariables, DeriveDataTypeable #-} import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import Data.Typeable import Control.Concurrent (forkIO, myThreadId, threadDelay) import qualified Control.Exception as E import Control.Exception (Exception, IOException, throwTo) import Control.Monad import Control.Monad.Trans.Class import Control.Pipe import Control.Pipe.Combinators import Control.Pipe.Exception import qualified Control.Pipe.Binary as PB import System.IO import Prelude hiding (catch) -- line-by-line reader with verbose initializer and finalizer reader :: FilePath -> Producer B.ByteString IO () reader fp = fReader >+> PB.lines where fReader = bracket open close PB.handleReader open = do putStrLn $ "opening file " ++ show fp ++ " for reading" openFile fp ReadMode close h = do hClose h putStrLn $ "closed file " ++ show fp -- line-by-line writer with verbose initializer and finalizer writer :: FilePath -> Consumer B.ByteString IO () writer fp = pipe (`BC.snoc` '\n') >+> fWriter where fWriter = await >>= \x -> feed x (bracket open close PB.handleWriter) open = do putStrLn $ "opening file " ++ show fp ++ " for writing" openFile fp WriteMode close h = do hClose h putStrLn $ "closed file " ++ show fp -- interactive pipe prompt :: Pipe String String IO () prompt = forever $ await >>= \q -> do lift $ putStr $ q ++ ": " r <- lift getLine yield r -- copy "/etc/motd" to "/tmp/x" ex1 :: Pipeline IO () ex1 = reader "/etc/motd" >+> writer "/tmp/x" {- opening file "/etc/motd" for reading opening file "/tmp/x" for writing closed file "/etc/motd" closed file "/tmp/x" -} -- note that the files are not closed in LIFO order -- output error ex2 :: Pipeline IO () ex2 = reader "/etc/motd" >+> writer "/unopenable" {- opening file "/etc/motd" for reading opening file "/unopenable" for writing closed file "/etc/motd" *** Exception: /unopenable: openFile: permission denied (Permission denied) -} -- note that the input file was automatically closed before the exception -- terminated the pipeline -- joining two files ex3 :: Pipeline IO () ex3 = (reader "/etc/motd" >> reader "/usr/share/dict/words") >+> writer "/tmp/x" {- opening file "/etc/motd" for reading opening file "/tmp/x" for writing closed file "/etc/motd" opening file "/usr/share/dict/words" for reading closed file "/usr/share/dict/words" closed file "/tmp/x" -} -- recovering from exceptions ex4 :: Pipeline IO () ex4 = (safeReader "/etc/motd" >> safeReader "/nonexistent") >+> writer "/tmp/x" where safeReader fp = catch (reader fp) $ \(e :: IOException) -> lift $ putStrLn $ "exception " ++ show e {- opening file "/etc/motd" for reading opening file "/tmp/x" for writing closed file "/etc/motd" opening file "/nonexistent" for reading exception /nonexistent: openFile: does not exist (No such file or directory) closed file "/tmp/x" -} data Timeout = Timeout deriving (Show, Typeable) instance Exception Timeout -- recovering from asynchronous exceptions ex5 :: Pipeline IO () ex5 = questions >+> safePrompt >+> pipe BC.pack >+> writer "/tmp/x" where questions = do yield "Project name" yield "Version" yield "Description" lift $ E.throwIO Timeout timeout t = lift $ do tid <- myThreadId forkIO $ do threadDelay (t * 1000000) throwTo tid Timeout safePrompt = catch (timeout 5 >> prompt) $ \(_ :: Timeout) -> lift $ putStrLn "timeout" {- Project name: test opening file "/tmp/x" for writing Version: timeout closed file "/tmp/x" -}
pcapriotti/pipes-extra
examples/finalizers/simple.hs
Haskell
bsd-3-clause
3,698
module Main where import Zice main = do ziceMain
zachk/zice
src/Main.hs
Haskell
bsd-3-clause
57
import Data.List data EncodeType a = Single a | Multiple Int a deriving (Show) encode lst = map (\ x -> (length x, head x)) (Data.List.group lst) encodeModified :: Eq a => [a] -> [EncodeType a] encodeModified = map help . encode where help (1, x) = Single x help (n, x) = Multiple n x decodeModified :: [EncodeType b] -> [b] decodeModified = concatMap help where help (Single x) = [x] help (Multiple n x) = take n (repeat x)
m00nlight/99-problems
haskell/p-12.hs
Haskell
bsd-3-clause
462
module Main where import Finance.Quote.Yahoo import Data.Time.Calendar import Data.Map quoteSymbolList = ["YHOO"] :: [QuoteSymbol] quoteFieldsList = ["s","l1","c"] :: [QuoteField] main = do q <- getQuote quoteSymbolList quoteFieldsList case q of Nothing -> error "no map" Just m -> case (Data.Map.lookup ("YHOO","l1") m) of Nothing -> print "no match" Just a -> print a let startDate = Data.Time.Calendar.fromGregorian 2013 07 01 let endDate = Data.Time.Calendar.fromGregorian 2013 08 01 h <- getHistoricalQuote (head quoteSymbolList) startDate endDate Monthly case h of Nothing -> error "no historical" Just l -> sequence $ Prelude.map print l return ()
bradclawsie/haskell-Finance.Quote.Yahoo
quotes.hs
Haskell
bsd-3-clause
727
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS -fno-warn-name-shadowing #-} -- | Track clocking in and out of work. module Clockin where import Control.Monad import Control.Monad.Trans.Resource import Data.Aeson import qualified Data.ByteString.Lazy as L import Data.Conduit import qualified Data.Conduit.Binary as C import qualified Data.Conduit.List as CL import Data.List import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Time import Data.Time.Lens import GHC.Generics import System.Directory import System.FilePath import Data.Time.Locale.Compat import Text.Printf -- | Configuration for the clocking in setup. data Config = Config { configFilePath :: !FilePath , configHoursPerDay :: Int } deriving (Show) -- | An entry in the clocking log. data Entry = In !ClockIn | Out !ClockOut deriving (Show,Generic) instance ToJSON Entry instance FromJSON Entry -- | Clocking in. data ClockIn = ClockIn { inProject :: !Text , inTask :: !(Maybe Text) , inTime :: !Time } deriving (Show,Generic) instance ToJSON ClockIn instance FromJSON ClockIn -- | Clocking out. data ClockOut = ClockOut { outProject :: !Text , outTask :: !(Maybe Text) , outReason :: !(Maybe Text) , outTime :: !Time } deriving (Show,Generic) instance ToJSON ClockOut instance FromJSON ClockOut -- | A status report for the current log. data Status = Status { statusIn :: !Bool -- ^ Am I clocked in? , statusCurTimePeriod :: !NominalDiffTime -- ^ How long have I been clocked in/clocked out for? , statusInToday :: !NominalDiffTime -- ^ How long have I been in today? , statusRemainingToday :: !Remaining -- ^ How long left today? } deriving (Show) -- | How much time remaining. data Remaining = Credit NominalDiffTime | Due NominalDiffTime deriving (Eq,Show) -- | Get a default config. getClockinConfig :: IO Config getClockinConfig = do dir <- getHomeDirectory return (Config (dir </> ".clockin.log") 8) -- | Clock into something. clockIn :: Config -- ^ Config. -> Text -- ^ Project. -> Maybe Text -- ^ Task. -> IO () clockIn config project task = do now <- getLocalTime clock config (In (ClockIn project task (Time now))) -- | Clock out of something. clockOut :: Config -- ^ Config. -> Text -- ^ Project. -> Maybe Text -- ^ Task. -> Maybe Text -- ^ Reason. -> IO () clockOut config project task reason = do now <- getLocalTime clock config (Out (ClockOut project task reason (Time now))) -- | Clock in or out. clock :: Config -> Entry -> IO () clock config entry = L.appendFile (configFilePath config) (encode entry <> "\n") -- | Print out a status string. printClockinStatus :: Config -> IO () printClockinStatus config = do entries <- readClockinEntries config now <- getLocalTime T.putStrLn (describeStatus now (clockinStatus config now entries) entries) -- | Print hours worked per day in a format spark can consume. printSparkDays :: Config -> IO () printSparkDays config = do entries <- readClockinEntries config now <- getLocalTime forM_ (days now entries) (\day -> let diff = -1 * (statusInToday (clockinStatus config day (filter ((<=day).entryTime) entries))) in putStrLn (formatTime defaultTimeLocale "%F" day ++ " " ++ T.unpack (hoursIn day diff))) where days now = nub . map (min now . modL seconds (subtract 1) . modL day (+1) . startOfDay . entryTime) -- | Print minutes. printMinutes :: Config -> IO () printMinutes config = do entries <- readClockinEntries config now <- getLocalTime forM_ (days now entries) (\day -> let diff = -1 * (statusInToday (clockinStatus config day (filter ((<=day).entryTime) entries))) in putStrLn (formatTime defaultTimeLocale "%F" day ++ "\t" ++ show (minutesIn day diff))) where days now = nub . map (min now . modL seconds (subtract 1) . modL day (+1) . startOfDay . entryTime) -- | Print hours. printHours :: Config -> IO () printHours config = do entries <- readClockinEntries config now <- getLocalTime forM_ (days now entries) (\day -> let diff = -1 * (statusInToday (clockinStatus config day (filter ((<=day).entryTime) entries))) in putStrLn (formatTime defaultTimeLocale "%F" day ++ "\t" ++ show (hoursCountIn day diff))) where days now = nub . map (min now . modL seconds (subtract 1) . modL day (+1) . startOfDay . entryTime) -- | Read in the log entries from file. readClockinEntries :: Config -> IO [Entry] readClockinEntries config = runResourceT (C.sourceFile (configFilePath config) $= C.lines $= CL.mapMaybe (decode . L.fromStrict) $$ CL.consume) -- | Make a human-readable representation of the status. describeStatus :: LocalTime -> Status -> [Entry] -> Text describeStatus now status entries = T.intercalate "\n" ["Current time is: " <> T.pack (formatTime defaultTimeLocale "%F %R" now) ,"Currently clocked " <> (if statusIn status then "IN " else "OUT ") <> (if statusCurTimePeriod status == 0 && not (statusIn status) then "" else "(" <> diffTime (-1 * (statusCurTimePeriod status)) True <> ")") ,"Time spent today: " <> hoursIn now (-1 * (statusInToday status)) ,"Remaining: " <> hoursRemaining now (statusRemainingToday status) ,"Log today:\n" <> T.intercalate "\n" (map describeEntry (filter ((>startOfDay now).entryTime) entries)) ,if statusIn status then T.pack (formatTime defaultTimeLocale "%R (now)" now) else "" ] -- | Describe an entry. describeEntry :: Entry -> Text describeEntry (In (ClockIn _ _ t)) = T.pack (formatTime defaultTimeLocale "%R" t) <> " in" describeEntry (Out (ClockOut _ _ _ t)) = T.pack (formatTime defaultTimeLocale "%R" t) <> " out" -- | Hours remaining. hoursRemaining now (Due h) = hoursIn now h hoursRemaining now (Credit h) = "-" <> hoursIn now h -- | Show the number of hours in (or out, really). hoursIn :: LocalTime -> NominalDiffTime -> Text hoursIn now = T.pack . formatTime defaultTimeLocale "%R" . (`addLocalTime` startOfDay now) -- | Show the number of minutes in (or out, really). minutesIn :: LocalTime -> NominalDiffTime -> Int minutesIn now = getL minutes . (`addLocalTime` startOfDay now) -- | Show the number of hours in (or out, really). hoursCountIn :: LocalTime -> NominalDiffTime -> Int hoursCountIn now = getL hours . (`addLocalTime` startOfDay now) -- | Make a short human-readable representation of the status, on one line. onelinerStatus :: LocalTime -> Status -> Text onelinerStatus now status = hoursIn now (-1 * (statusInToday status)) <> "/" <> hoursRemaining now (statusRemainingToday status) <> " (" <> (if statusIn status then "in" else "out") <> ")" -- | Generate a status report of the current log. clockinStatus :: Config -> LocalTime -> [Entry] -> Status clockinStatus config now entries = Status clockedIn curPeriod todayDiff remaining where remaining | -1 * todayDiff < goalDiff = Due (diffLocalTime (addLocalTime goalDiff midnight) (addLocalTime (-1 * todayDiff) midnight)) | otherwise = Credit (diffLocalTime (addLocalTime (-1 * todayDiff) midnight) (addLocalTime goalDiff midnight)) goalDiff = (60 * 60 * fromIntegral (configHoursPerDay config)) todayDiff = inToday now descending clockedIn = fromMaybe False (fmap (\i -> case i of In{} -> True _ -> False) current) curPeriod = maybe 0 (diffLocalTime now . entryTime) current current = listToMaybe descending descending = reverse entries midnight = startOfDay now -- | Get the time, if any, of an entry's clocking in. entryTime :: Entry -> LocalTime entryTime (In i) = timeLocalTime (inTime i) entryTime (Out o) = timeLocalTime (outTime o) -- | Get the project of the entry. entryProject :: Entry -> Text entryProject (In i) = inProject i entryProject (Out o) = outProject o -- | Get the starting time of the day of the given time. startOfDay :: LocalTime -> LocalTime startOfDay (LocalTime day _) = LocalTime day midnight -- | How much time clocked in today? Expects a DESCENDING entry list. -- -- If the clocking in time was yesterday, then don't include the work -- from yesterday, only include the work for today starting from -- midnight. -- -- Stops traversing the list if it reaches an entry from yesterday. inToday :: LocalTime -> [Entry] -> NominalDiffTime inToday now = go now 0 . zip [0::Int ..] where go last total (((i,x):xs)) = case x of In{} | today -> go this (total + diffLocalTime this last) xs | otherwise -> go this (total + diffLocalTime (startOfDay now) last) [] Out{} | today -> go this total xs | i == 0 -> go this total [] | otherwise -> go this total [] where this = entryTime x today = localDay this == localDay now go _ total _ = total -- | Display a time span as one time relative to another. diffTime :: NominalDiffTime -> Bool -- ^ Display 'in/ago'? -> Text -- ^ Example: '3 seconds ago', 'in three days'. diffTime span' fix = T.pack $ maybe "unknown" format $ find (\(s,_,_) -> abs span'>=s) $ reverse ranges where minute = 60; hour = minute * 60; day = hour * 24; week = day * 7; month = day * 30; year = month * 12 format range = (if fix && span'>0 then "in " else "") ++ case range of (_,str,0) -> str (_,str,base) -> printf str (abs $ round (span' / base) :: Integer) ++ (if fix && span'<0 then " ago" else "") ranges = [(0,"%d seconds",1) ,(minute,"a minute",0) ,(minute*2,"%d minutes",minute) ,(minute*30,"half an hour",0) ,(minute*31,"%d minutes",minute) ,(hour,"an hour",0) ,(hour*2,"%d hours",hour) ,(hour*3,"a few hours",0) ,(hour*4,"%d hours",hour) ,(day,"a day",0) ,(day*2,"%d days",day) ,(week,"a week",0) ,(week*2,"%d weeks",week) ,(month,"a month",0) ,(month*2,"%d months",month) ,(year,"a year",0) ,(year*2,"%d years",year) ] -- Local time operations getLocalTime :: IO LocalTime getLocalTime = fmap zonedTimeToLocalTime getZonedTime diffLocalTime :: LocalTime -> LocalTime -> NominalDiffTime diffLocalTime t1 t2 = diffUTCTime (localTimeToUTC utc t1) (localTimeToUTC utc t2) addLocalTime :: NominalDiffTime -> LocalTime -> LocalTime addLocalTime d = tmap (addUTCTime d) tmap :: (UTCTime -> UTCTime) -> LocalTime -> LocalTime tmap f = utcToLocalTime utc . f . localTimeToUTC utc -- | A local time. The only reason for this is to avoid the orphan instance. newtype Time = Time { timeLocalTime :: LocalTime } deriving (Show,ParseTime,FormatTime,Generic) instance ToJSON Time where toJSON = toJSON . formatTime defaultTimeLocale "%F %T" instance FromJSON Time where parseJSON s = do s <- parseJSON s case parseTime defaultTimeLocale "%F %T" s of Nothing -> fail "Couldn't parse local time." Just t -> return t
chrisdone/clockin
src/Clockin.hs
Haskell
bsd-3-clause
12,791
module Data.Text.Aux where import Control.Monad (liftM2) import qualified Data.Text as T (Text, append, cons, intercalate, lines, pack, snoc, unlines, unwords, words) import Language.C.Pretty (Pretty, pretty) import Data.Text.Lazy (toStrict) import Data.Text.Lazy.Builder (toLazyText) import Data.Text.Lazy.Builder.Int (decimal) import Text.PrettyPrint.HughesPJ.Ext import TextShow (showt) -- | `showInt` should be equivalent to `pack . show` for the `Int` type, except -- a bit faster since it uses `Text` library functions showInt :: Int -> T.Text showInt = toStrict . toLazyText . decimal -- | Example: -- -- >>> textAp "Hello" "World" -- "Hello (World)" -- textAp :: String -> T.Text -> T.Text textAp ap = T.append (flip T.snoc ' ' . T.pack $ ap) . parens -- | Example: -- -- >>> wrapText '|' "text" -- "|text|" -- wrapText :: Char -> T.Text -> T.Text wrapText = liftM2 (.) T.cons (flip T.snoc) -- | Example: -- -- >>> addArrows . map T.pack ["Bool", "String", "Int"] -- "Bool -> String -> Int" -- addArrows :: [T.Text] -> T.Text addArrows = T.intercalate (T.pack " -> ") -- | Example: -- -- >>> unwords2 (T.pack "Hello") (T.pack "World") -- "Hello World" -- unwords2 :: T.Text -> T.Text -> T.Text unwords2 = appendAfter (T.pack " ") -- | Example: -- -- >>> appendAfter ", " "Hello" "World" -- "Hello, World" -- appendAfter :: T.Text -> T.Text -> T.Text -> T.Text appendAfter = (T.append .) . T.append -- | Add parentheses around a `Text` object parens :: T.Text -> T.Text parens = (T.cons '(') . (flip T.snoc ')') -- | `wordLines` converts a Text input to a list of lists, where -- `wordLines text !! i !! j` is the jth word of the ith line of `text`. wordLines :: T.Text -> [[T.Text]] wordLines = map T.words . T.lines -- | See `wordLines` unWordLines :: [[T.Text]] -> T.Text unWordLines = T.unlines . map T.unwords -- | Shortcut for -- -- > unlines . map pack -- packUnlines :: [String] -> T.Text packUnlines = T.unlines . map T.pack -- | Shortcut for -- -- > unwords . map pack -- packUnwords :: [String] -> T.Text packUnwords = T.unwords . map T.pack -- | Convert a pretty-printable object to `Text` prettyShowt :: Pretty p => p -> T.Text prettyShowt = showt . pretty
michaeljklein/CPlug
src/Data/Text/Aux.hs
Haskell
bsd-3-clause
2,199
-- -- Types.hs -- Copyright (C) 2017 jragonfyre <jragonfyre@jragonfyre> -- -- Distributed under terms of the MIT license. -- module Game.Types where --( --) where import qualified Data.HashMap.Lazy as M import qualified Data.Yaml as Y import Data.Yaml (FromJSON (..), (.:), (.!=), (.:?), (.=), ToJSON (..)) import Control.Applicative ((<$>),(<*>),(<|>)) import qualified Data.Maybe as May import qualified Data.List as L import qualified Data.Text as T import Data.Text (Text) import Data.Aeson.Types (typeMismatch) import Data.Vector (toList) import Game.BaseTypes import Game.MaterialTypes import Game.RelationTypes import Game.ObjectTypes import Game.SpaceTypes import ParseUtilities data World = World { registeredRelations :: M.HashMap Identifier Relation , registeredMaterials :: M.HashMap Identifier Material , registeredSpaceClasses :: M.HashMap Identifier SpaceClass , registeredObjectClasses :: M.HashMap Identifier ObjectClass } type Space = SpaceData -- dynamic data associated to a space data SpaceData = SpData { spaceId :: Identifier , spaceDescription :: Description , spaceClass :: Identifier , contents :: [Object] , subspaces :: [Space] , spaceInstanceProperties :: [SpaceProperty] } deriving (Show, Read, Eq) instance FromJSON SpaceData where parseJSON (Y.Object v) = SpData <$> v .: "space" <*> v .: "description" <*> v .: "space-class" <*> v .:? "contents" .!= [] <*> v .:? "subspaces" .!= [] <*> v .:? "properties" .!= [] instance ToJSON SpaceData where toJSON spdata = Y.object [ "space" .= spaceId spdata , "description" .= spaceDescription spdata , "space-class" .= spaceClass spdata , "contents" .= toJSONList (contents spdata) , "subspaces" .= toJSONList (subspaces spdata) , "properties" .= toJSONList (spaceInstanceProperties spdata) ] {- -- describes a space data Space where -- Space with an identifier and certain relations to subspaces NamedSpace :: Identifier -> SpaceClass -> SpaceData -> Space -- subspace of some parent space with the relation Subspace :: Relation -> SpaceClass -> SpaceData -> Space deriving (Show, Read, Eq) -} type Object = ObjectData data ObjectData = ObData { objectId :: Identifier , objectDescription :: Description , objectClass :: Identifier , objectSpaces :: [Space] , objectInstanceProperties :: [ObjectProperty] } deriving (Show, Read, Eq) instance FromJSON ObjectData where parseJSON (Y.Object v) = ObData <$> v .: "object" <*> v .: "description" <*> v .: "object-class" <*> v .:? "spaces" .!= [] <*> v .:? "properties" .!= [] instance ToJSON ObjectData where toJSON obdata = Y.object [ "object" .= objectId obdata , "description" .= objectDescription obdata , "object-class" .= objectClass obdata , "spaces" .= toJSONList (objectSpaces obdata) , "properties" .= toJSONList (objectInstanceProperties obdata) ] {- data Object where Object :: ObjectClass -> ObjectData -> Object deriving (Show, Read, Eq) -}
jragonfyre/TRPG
src/Game/Types.hs
Haskell
bsd-3-clause
3,090
module Main where import qualified Data.ByteString.Lazy as LazyBS import Data.Time.Clock import Data.Time.Format import Data.Time.LocalTime import System.IO --import System.Locale import CSVPlayer import Types import NameCluster import NameGender import OptApplicative import Utils -- |Clusterifies the specifed names and converts it into a String. stringifyClusters :: [String] -> String stringifyClusters ns = (show . clusterify) ns {-| Clusterifies the specified names and encodes the result into a CSV formatted String. -} stringifyCSV :: [String] -> String stringifyCSV ns = (show . convertClustersToCSVString . clusterify) ns -- TEST hardcodedValues :: [String] hardcodedValues = words "Armand Theo Alex Adrien Tristan Alexandra \ \ Arnaud Julien Juliette Ilhem Alyx Tristan Alexis Alexandre Theo Thibault Thomas \ \ Armande Armando Alexia" -- TEST displayHardCodedValues :: IO () displayHardCodedValues = (putStrLn . show . stringifyClusters) hardcodedValues -- |Uses input as a list of names for clusterification. displayInputValues :: IO () displayInputValues = do putStrLn "List your names separated by spaces: " interact (show . stringifyClusters . words) -- |Clusterifies input values and writes the result to a new CSV file. writeCSVFileInputValues :: IO () writeCSVFileInputValues = do putStrLn "List your names separated by spaces: " names <- getLine writeCSVFile "clusters" (toClusterRecordsAll . clusterify . words $ names) -- TEST writeCSVFileHardCodedValues :: IO () writeCSVFileHardCodedValues = do filename <- generateFilenameFromTime writeCSVFile filename (toClusterRecordsAll . clusterify $ hardcodedValues) -- |Generates a file name from the current time. generateFilenameFromTime :: IO String generateFilenameFromTime = do timezone <- getCurrentTimeZone utcTime <- getCurrentTime -- Getting current time for filename let localTime = utcToLocalTime timezone utcTime -- Formatting time for filename let filename = formatTime defaultTimeLocale "%Y-%m-%d_%H-%M-%S" localTime return filename findGender :: IO () findGender = do let basePath = "data/db_all_names.csv" let errorMsg = "Could not load gendered name base at path " ++ show basePath let ns = ["Alexandre", "Diamant", "ChouDeBruxelles41", "Jackie"] mbBase <- loadGenderedBase basePath True case mbBase of Nothing -> putStrLn errorMsg Just base -> (putStrLn . show) (findGenderBase base ns) callVlfFunc :: VLFOptions -> IO () callVlfFunc vlfOpts = {-| Distributes calls so that the right function is called based on the typed command. -} callMainFuncs :: GlobalOptions -> IO () callMainFuncs opts = let cmd = optCommand opts format = optCsvFlag opts results = case cmd of VoiciLesFemmes vlfOpts -> callVlfFunc vlfOpts GroupeLesNoms glnOpts -> callGlnFunc glnOpts strResults = case format of Csv -> expression Normal -> expression in expression -- |Parses all the options and call the entry function. optMain :: IO () optMain = execParser opts >>= callMainFuncs where opts = info (helper <*> globalOptions) ( fullDesc <> progDesc "Multiple tools for name classification purposes" <> header "ou-sont-les-femmes-? - name classification tools") main :: IO () main = optMain
Tydax/ou-sont-les-femmes
app/OuSontLesFemmes.hs
Haskell
bsd-3-clause
3,360
{-# LANGUAGE QuasiQuotes #-} module AltParsing where import Control.Applicative import Text.Trifecta import Text.RawString.QQ type NumberOrString = Either Integer String a = "blah" b = "123" c = "123blah789" eitherOr :: String eitherOr = [r| 123 abc 456 def |] parseNos :: Parser NumberOrString parseNos = do skipMany (oneOf "\n") v <- (Left <$> integer) <|> (Right <$> some letter) skipMany (oneOf "\n") return v main = do print $ parseString (some letter) mempty a print $ parseString integer mempty b print $ parseString parseNos mempty a print $ parseString parseNos mempty b print $ parseString (many parseNos) mempty c print $ parseString (some parseNos) mempty c print $ parseString (some parseNos) mempty eitherOr
chengzh2008/hpffp
src/ch24-Parser/altParsing.hs
Haskell
bsd-3-clause
751
{-# LANGUAGE PatternGuards, RecordWildCards #-} module Website where import Data.Char (toLower) import Data.Function (on) import Data.List (find, groupBy, nub, sort) import Data.Version (showVersion, versionBranch) import Development.Shake import Text.Hastache import Text.Hastache.Context import Dirs import Paths import PlatformDB import Releases import ReleaseFiles import Templates import Types websiteRules :: FilePath -> Rules () websiteRules templateSite = do websiteDir %/> \dst -> do bcCtx <- buildConfigContext let rlsCtx = releasesCtx ctx = ctxConcat [rlsCtx, historyCtx, bcCtx, currentPlatformCtx, errorCtx] copyExpandedDir ctx templateSite dst currentPlatformCtx :: Monad m => MuContext m currentPlatformCtx = mkStrContext ctx where ctx "freezeConfig" = mapListStrContext go freezeIncludes ctx _ = MuNothing go x "name" = MuVariable $ pkgName x go x "version" = MuVariable . showVersion $ pkgVersion x go _ _ = MuNothing freezeIncludes = map snd . filter filt . allRelIncludes $ head (reverse releases) filt x = not (fst x `elem` [IncGHC, IncGHCLib, IncGHCTool, IncTool]) fileCtx :: (Monad m) => FileInfo -> MuContext m fileCtx (dist, url, mHash, isFull) = mkStrContext ctx where ctx "osNameAndArch" = MuVariable $ distName dist ctx "url" = MuVariable url ctx "mHash" = maybe (MuBool False) MuVariable mHash ctx "archBits" | DistBinary _ arch <- dist = MuVariable $ archBits arch | otherwise = MuNothing ctx "isOSX" = MuBool $ distIsFor OsOSX dist ctx "isWindows" = MuBool $ distIsFor OsWindows dist ctx "isLinux" = MuBool $ distIsFor OsLinux dist ctx "isSource" = MuBool $ dist == DistSource ctx "isFull" = MuBool $ isFull ctx _ = MuNothing releaseCtx :: (Monad m) => ReleaseFiles -> MuContext m releaseCtx (ver, (month, year), files) = mkStrContext ctx where ctx "version" = MuVariable ver ctx "year" = MuVariable $ show year ctx "month" = MuVariable $ monthName month ctx "files" = mapListContext fileCtx files ctx _ = MuNothing releasesCtx :: (Monad m) => MuContext m releasesCtx = mkStrContext ctx where ctx "years" = mapListStrContext yearCtx years ctx "current" = MuList [releaseCtx currentFiles] ctx _ = MuNothing yearCtx [] _ = MuBool False yearCtx (r0:_) "year" = MuVariable $ show $ releaseYear r0 yearCtx rs "releases" = mapListContext releaseCtx rs yearCtx _ _ = MuNothing years = groupBy ((==) `on` releaseYear) priorFiles releaseYear :: ReleaseFiles -> Int releaseYear (_ver, (_month, year), _files) = year monthName :: Int -> String monthName i = maybe (show i) id $ lookup i monthNames where monthNames = zip [1..] $ words "January Feburary March April May June \ \July August September October November December" historyCtx :: (Monad m) => MuContext m historyCtx = mkStrContext outerCtx where outerCtx "history" = MuList [mkStrContext ctx] outerCtx _ = MuNothing ctx "hpReleases" = mapListStrContext rlsCtx releasesNewToOld ctx "ncols" = MuVariable $ length releasesNewToOld + 1 ctx "sections" = MuList [ sectionCtx "Compiler" [isGhc, not . isLib] , sectionCtx "Core Libraries, provided with GHC" [isGhc, isLib] , sectionCtx "Additional Minimal Platform Libraries" [not . isGhc, isLib] , sectionCtx "Programs and Tools" [isTool] , extendedCtx "Libraries with Full Platform" ] ctx _ = MuNothing rlsCtx rls "hpVersion" = MuVariable . showVersion . hpVersion . relVersion $ rls rlsCtx _ _ = MuNothing sectionCtx :: (Monad m) => String -> [IncludeType -> Bool] -> MuContext m sectionCtx name tests = mkStrContext ctx where ctx "name" = MuVariable name ctx "components" = mapListStrContext pCtx packages ctx _ = MuNothing packages = sortOnLower . nub . map pkgName . concat $ map (packagesByIncludeFilter (\i -> all ($i) tests) False) releasesNewToOld sortOnLower = map snd . sort . map (\s -> (map toLower s, s)) pCtx pName "package" = MuVariable pName pCtx pName "hackageUrl" = MuVariable $ "http://hackage.haskell.org/package/" ++ pName pCtx pName "releases" = mapListStrContext pvCtx $ packageVersionInfo False pName pCtx _ _ = MuNothing pvCtx (c, _) "class" = MuVariable c pvCtx (_, v) "version" = MuVariable v pvCtx _ _ = MuNothing extendedCtx :: (Monad m) => String -> MuContext m extendedCtx name = mkStrContext ctx where ctx "name" = MuVariable name ctx "components" = mapListStrContext pCtx packages ctx _ = MuNothing packages = sortOnLower . nub . map pkgName . concat $ map (map snd . relIncludes) releasesNewToOld sortOnLower = map snd . sort . map (\s -> (map toLower s, s)) pCtx pName "package" = MuVariable pName pCtx pName "hackageUrl" = MuVariable $ "http://hackage.haskell.org/package/" ++ pName pCtx pName "releases" = mapListStrContext pvCtx $ packageVersionInfo True pName pCtx _ _ = MuNothing pvCtx (c, _) "class" = MuVariable c pvCtx (_, v) "version" = MuVariable v pvCtx _ _ = MuNothing packageVersionInfo :: Bool -> String -> [(String, String)] packageVersionInfo searchFull pName = curr $ zipWith comp vers (drop 1 vers ++ [Nothing]) where comp Nothing _ = ("missing", "-") comp (Just v) Nothing = ("update", showVersion v) comp (Just v) (Just w) | maj v == maj w = ("same", showVersion v) | otherwise = ("update", showVersion v) maj = take 3 . versionBranch curr ((c, v) : cvs) = (c ++ " current", v) : cvs curr [] = [] vers = map (fmap pkgVersion . find ((==pName) . pkgName) . map snd . (if searchFull then allRelIncludes else relMinimalIncludes)) releasesNewToOld releasesNewToOld :: [Release] releasesNewToOld = reverse releases
gbaz/haskell-platform
hptool/src/Website.hs
Haskell
bsd-3-clause
6,097
module Karamaan.Plankton.Date where import Data.Time.Calendar (Day, addDays, fromGregorian, toGregorian) import Data.Time.LocalTime (ZonedTime, zonedTimeToLocalTime, getZonedTime, localDay) import Data.Time.Format (formatTime) import System.Locale (defaultTimeLocale) import qualified Data.Time.Parse import qualified Data.Time.LocalTime import Karamaan.Plankton ((.:)) usDateFormatString :: String usDateFormatString = "%m-%d-%Y" isoDateFormatString :: String isoDateFormatString = "%Y-%m-%d" monthNameFormatString :: String monthNameFormatString = "%B %e, %Y" ymdNoSpaceFormatString :: String ymdNoSpaceFormatString = "%Y%m%d" usDateFormat :: Day -> String usDateFormat = formatTimeDefault usDateFormatString isoDateFormat :: Day -> String isoDateFormat = formatTimeDefault isoDateFormatString dayToSQL :: Day -> String dayToSQL = formatTimeDefault isoDateFormatString monthNameFormat :: Day -> String monthNameFormat = formatTimeDefault monthNameFormatString formatTimeDefault :: String -> Day -> String formatTimeDefault = formatTime defaultTimeLocale zonedTimeToDay :: ZonedTime -> Day zonedTimeToDay = localDay . zonedTimeToLocalTime todayLocal :: IO Day todayLocal = (return . zonedTimeToDay) =<< getZonedTime yesterdayLocal :: IO Day yesterdayLocal = (return . dayBefore . zonedTimeToDay) =<< getZonedTime dayBefore :: Day -> Day dayBefore = addDays (-1) dayOrTodayLocal :: Maybe Day -> IO Day dayOrTodayLocal = maybe todayLocal return dayOrYesterdayLocal :: Maybe Day -> IO Day dayOrYesterdayLocal = maybe yesterdayLocal return -- TODO: this accepts "2013-07-123" and returns 'Just 2013-07-12'. -- Seems like a bug parseDate :: String -> Maybe Day parseDate = fmap (Data.Time.LocalTime.localDay . fst) . Data.Time.Parse.strptime isoDateFormatString -- ^^ Here we use Data.Time.Parse.strptime rather than parseTime because -- Massy wants '2013-5-28' to be valid -- (Message-Id: <10CFB694-68C0-4FFF-8019-61035E3F8C3E@karamaan.com>) -- parseTime doesn't support that because parseValue's definition for the -- 'm' character is 'digits 2', rather than 'spdigits 2' parseDateG :: String -> String -> Maybe Day parseDateG = fmap (Data.Time.LocalTime.localDay . fst) .: Data.Time.Parse.strptime firstDayOfYear :: Day -> Day firstDayOfYear day = fromGregorian year 1 1 where (year, _, _) = toGregorian day firstDayOfQuarter :: Day -> Day firstDayOfQuarter day = fromGregorian year quarterMonth 1 where (year, month, _) = toGregorian day quarterMonth = ((+1) . (*3) . (`div` 3) . (subtract 1)) month firstDayOfMonth :: Day -> Day firstDayOfMonth day = fromGregorian year month 1 where (year, month, _) = toGregorian day
karamaan/karamaan-plankton
Karamaan/Plankton/Date.hs
Haskell
bsd-3-clause
2,680
module Graphics.UI.Threepenny.Elements.ID where import Graphics.UI.Threepenny.Attributes.Extra import Graphics.UI.Threepenny.Extra import Data.UUID import Data.UUID.V4 newtype UID = UID { unUID :: String } deriving (Eq,Ord,Show) newID :: UI UID newID = liftIO $ shortenUUID <$> nextRandom shortenUUID :: UUID -> UID shortenUUID = UID . takeWhile (/= '-') . toString uid :: MAttr Element UID uid = strMAttr "id" & bimapAttr unUID (fmap UID) identify :: Widget w => w -> UI UID identify w = do i <- newID element w # set uid i return i type Selector = String selUID :: UID -> Selector selUID = ('#':) . unUID toVar :: UID -> String toVar = unUID byUID :: Identified a => a -> Selector byUID = selUID . getUID jsVar :: Identified a => a -> String jsVar = (\p i -> p ++ "_" ++ i) <$> jsVarPrefix <*> toVar . getUID class Identified a where getUID :: a -> UID jsVarPrefix :: a -> String
kylcarte/threepenny-extra
src/Graphics/UI/Threepenny/Elements/ID.hs
Haskell
bsd-3-clause
921
{-# LANGUAGE OverloadedStrings #-} module Main (main) where import Control.Applicative ((<**>), (<|>), optional) import Data.Char (toLower) import Data.Semigroup ((<>)) import System.IO (IOMode (WriteMode), stdout, openFile) import Genotype.Comparison (PhaseKnowledge (..)) import Genotype.Processor (Processor, preprocess) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Genotype.Parser.FastPhase as FastPhase import qualified Genotype.Printer.Arlequin as Arlequin import qualified Genotype.Printer.Geno as Geno import qualified Genotype.Processor.KeepColumnNumbers as KeepColumns import qualified Options.Applicative as O data InputFormat = FastPhase deriving (Eq, Show) parseInputFormat :: O.Parser InputFormat parseInputFormat = O.option (O.maybeReader formats) ( O.long "input-format" <> O.metavar "NAME" <> O.help "Select from: fastphase" ) where formats str = case map toLower str of "fastphase" -> Just FastPhase _ -> Nothing data InputSource = STDIN | InputFile T.Text deriving (Eq, Show) parseInputSourceFile :: O.Parser InputSource parseInputSourceFile = InputFile . T.pack <$> O.strOption ( O.long "input-file" <> O.metavar "FILENAME" <> O.help "Input file" ) parseInputSource :: O.Parser InputSource parseInputSource = parseInputSourceFile <|> pure STDIN data OutputFormat = Arlequin | Geno deriving (Eq, Show) parseOutputFormat :: O.Parser OutputFormat parseOutputFormat = O.option (O.maybeReader formats) ( O.long "output-format" <> O.metavar "NAME" <> O.help "Select from: arlequin, geno" ) where formats str = case map toLower str of "arlequin" -> Just Arlequin "geno" -> Just Geno _ -> Nothing data OutputSink = STDOUT | OutputFile T.Text deriving (Eq, Show) parseOutputSinkFile :: O.Parser OutputSink parseOutputSinkFile = OutputFile . T.pack <$> O.strOption ( O.long "output-file" <> O.metavar "FILENAME" <> O.help "Output file" ) parseOutputSink :: O.Parser OutputSink parseOutputSink = parseOutputSinkFile <|> pure STDOUT parseFilterColumns :: O.Parser (Maybe T.Text) parseFilterColumns = optional $ T.pack <$> O.strOption ( O.long "keep-columns" <> O.metavar "FILENAME" <> O.help "File containing list of column numbers to keep" ) parsePhaseKnown :: O.Parser PhaseKnowledge parsePhaseKnown = O.flag Unknown Known ( O.long "phase-known" <> O.help "Differeniate between phases in comparison output" ) data Options = Options { opt_inputFormat :: InputFormat , opt_inputSource :: InputSource , opt_outputFormat :: OutputFormat , opt_outputSink :: OutputSink , opt_filterColumns :: Maybe T.Text , opt_phaseKnown :: PhaseKnowledge } deriving (Eq, Show) parseOptions :: O.Parser Options parseOptions = Options <$> parseInputFormat <*> parseInputSource <*> parseOutputFormat <*> parseOutputSink <*> parseFilterColumns <*> parsePhaseKnown parseOptionsWithInfo :: O.ParserInfo Options parseOptionsWithInfo = O.info (parseOptions <**> O.helper) (O.header "genotype-parser - parser and printer of genotype data formats") -- TODO: ensure output file handle closes after use main :: IO () main = do opts <- O.execParser parseOptionsWithInfo input <- case opt_inputSource opts of InputFile file -> T.readFile $ T.unpack file STDIN -> T.getContents parsed <- either fail return $ case opt_inputFormat opts of FastPhase -> FastPhase.runParser input processed <- preprocess parsed $ preprocessors opts sink <- case opt_outputSink opts of OutputFile file -> openFile (T.unpack file) WriteMode STDOUT -> return stdout case opt_outputFormat opts of Arlequin -> Arlequin.print (opt_phaseKnown opts) sink processed Geno -> Geno.print (opt_phaseKnown opts) sink processed preprocessors :: Options -> [Processor] preprocessors = maybe [] (\f -> [KeepColumns.process f]) . opt_filterColumns
Jonplussed/genotype-parser
app/Main.hs
Haskell
bsd-3-clause
4,008
{- It can be verified that there are 23 positive integers less than 1000 that are divisible by at least four distinct primes less than 100. Find how many positive integers less than 10^16 are divisible by at least four distinct primes less than 100. -} {-# LANGUAGE ScopedTypeVariables #-} import qualified Zora.List as ZList import qualified Zora.Math as ZMath import qualified Data.Ord as Ord import qualified Data.Set as Set import qualified Data.Map as Map import qualified Data.Char as Char import qualified Data.List as List import qualified Data.Numbers.Primes as Primes import qualified Data.MemoCombinators as Memo import Data.Maybe import Data.Ratio import Data.Function import Debug.Trace import Data.Monoid import Control.Monad import Control.Applicative ub :: Integer ub = 1000 primes :: [Integer] primes = takeWhile (< 100) ZMath.primes prime_sets :: [[Integer]] prime_sets = takeWhile (any (< ub)) . map (map product . ZList.subsets_of_size primes) $ [4..] main :: IO () main = do putStrLn . show $ prime_sets
bgwines/project-euler
src/in progress/problem269.hs
Haskell
bsd-3-clause
1,042
module Yesod.Goodies.PNotify.Modules.Nonblock ( Nonblock(..) , defaultNonblock )where import Data.Aeson import Data.Text (Text) import Yesod.Goodies.PNotify.Types import Yesod.Goodies.PNotify.Types.Instances data Nonblock = Nonblock { _nonblock :: Maybe Bool , _nonblock_opacity :: Maybe Double } deriving (Read, Show, Eq, Ord) instance FromJSON Nonblock where parseJSON (Object v) = Nonblock <$> v .:? "nonblock" <*> v .:? "nonblock_opacity" instance ToJSON Nonblock where toJSON (Nonblock { _nonblock , _nonblock_opacity }) = object $ maybe [] (\x -> ["nonblock" .= x]) _nonblock ++ maybe [] (\x -> ["nonblock_opacity" .= x]) _nonblock_opacity ++ [] defaultNonblock :: Nonblock defaultNonblock = Nonblock { _nonblock = Nothing , _nonblock_opacity = Nothing }
cutsea110/yesod-pnotify
Yesod/Goodies/PNotify/Modules/Nonblock.hs
Haskell
bsd-3-clause
1,058
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE CPP #-} {-| This module defines a generic web application interface. It is a common protocol between web servers and web applications. The overriding design principles here are performance and generality. To address performance, this library is built on top of the conduit and blaze-builder packages. The advantages of conduits over lazy IO have been debated elsewhere and so will not be addressed here. However, helper functions like 'responseLBS' allow you to continue using lazy IO if you so desire. Generality is achieved by removing many variables commonly found in similar projects that are not universal to all servers. The goal is that the 'Request' object contains only data which is meaningful in all circumstances. Please remember when using this package that, while your application may compile without a hitch against many different servers, there are other considerations to be taken when moving to a new backend. For example, if you transfer from a CGI application to a FastCGI one, you might suddenly find you have a memory leak. Conversely, a FastCGI application would be well served to preload all templates from disk when first starting; this would kill the performance of a CGI application. This package purposely provides very little functionality. You can find various middlewares, backends and utilities on Hackage. Some of the most commonly used include: [warp] <http://hackage.haskell.org/package/warp> [wai-extra] <http://hackage.haskell.org/package/wai-extra> [wai-test] <http://hackage.haskell.org/package/wai-test> -} module Network.Wai ( -- * Types Application , Middleware , ResponseReceived -- * Request , Request , defaultRequest , RequestBodyLength (..) -- ** Request accessors , requestMethod , httpVersion , rawPathInfo , rawQueryString , requestHeaders , isSecure , remoteHost , pathInfo , queryString , requestBody , vault , requestBodyLength , requestHeaderHost , requestHeaderRange , lazyRequestBody -- * Response , Response , StreamingBody , FilePart (..) -- ** Response composers , responseFile , responseBuilder , responseLBS , responseStream , responseRaw -- * Response accessors , responseStatus , responseHeaders , responseToStream ) where import Blaze.ByteString.Builder (Builder, fromLazyByteString) import Blaze.ByteString.Builder (fromByteString) import Control.Monad (unless) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Internal as LI import Data.ByteString.Lazy.Internal (defaultChunkSize) import Data.ByteString.Lazy.Char8 () import Data.Function (fix) import Data.Monoid (mempty) import qualified Network.HTTP.Types as H import Network.Socket (SockAddr (SockAddrInet)) import Network.Wai.Internal import qualified System.IO as IO import System.IO.Unsafe (unsafeInterleaveIO) ---------------------------------------------------------------- -- | Creating 'Response' from a file. responseFile :: H.Status -> H.ResponseHeaders -> FilePath -> Maybe FilePart -> Response responseFile = ResponseFile -- | Creating 'Response' from 'Builder'. -- -- Some questions and answers about the usage of 'Builder' here: -- -- Q1. Shouldn't it be at the user's discretion to use Builders internally and -- then create a stream of ByteStrings? -- -- A1. That would be less efficient, as we wouldn't get cheap concatenation -- with the response headers. -- -- Q2. Isn't it really inefficient to convert from ByteString to Builder, and -- then right back to ByteString? -- -- A2. No. If the ByteStrings are small, then they will be copied into a larger -- buffer, which should be a performance gain overall (less system calls). If -- they are already large, then blaze-builder uses an InsertByteString -- instruction to avoid copying. -- -- Q3. Doesn't this prevent us from creating comet-style servers, since data -- will be cached? -- -- A3. You can force blaze-builder to output a ByteString before it is an -- optimal size by sending a flush command. responseBuilder :: H.Status -> H.ResponseHeaders -> Builder -> Response responseBuilder = ResponseBuilder -- | Creating 'Response' from 'L.ByteString'. This is a wrapper for -- 'responseBuilder'. responseLBS :: H.Status -> H.ResponseHeaders -> L.ByteString -> Response responseLBS s h = ResponseBuilder s h . fromLazyByteString -- | Creating 'Response' from 'C.Source'. responseStream :: H.Status -> H.ResponseHeaders -> StreamingBody -> Response responseStream = ResponseStream -- | Create a response for a raw application. This is useful for \"upgrade\" -- situations such as WebSockets, where an application requests for the server -- to grant it raw network access. -- -- This function requires a backup response to be provided, for the case where -- the handler in question does not support such upgrading (e.g., CGI apps). -- -- In the event that you read from the request body before returning a -- @responseRaw@, behavior is undefined. -- -- Since 2.1.0 responseRaw :: (IO B.ByteString -> (B.ByteString -> IO ()) -> IO ()) -> Response -> Response responseRaw = ResponseRaw ---------------------------------------------------------------- -- | Accessing 'H.Status' in 'Response'. responseStatus :: Response -> H.Status responseStatus (ResponseFile s _ _ _) = s responseStatus (ResponseBuilder s _ _ ) = s responseStatus (ResponseStream s _ _ ) = s responseStatus (ResponseRaw _ res ) = responseStatus res -- | Accessing 'H.ResponseHeaders' in 'Response'. responseHeaders :: Response -> H.ResponseHeaders responseHeaders (ResponseFile _ hs _ _) = hs responseHeaders (ResponseBuilder _ hs _ ) = hs responseHeaders (ResponseStream _ hs _ ) = hs responseHeaders (ResponseRaw _ res) = responseHeaders res -- | Converting the body information in 'Response' to 'Source'. responseToStream :: Response -> ( H.Status , H.ResponseHeaders , (StreamingBody -> IO a) -> IO a ) responseToStream (ResponseStream s h b) = (s, h, ($ b)) responseToStream (ResponseFile s h fp (Just part)) = ( s , h , \withBody -> IO.withBinaryFile fp IO.ReadMode $ \handle -> withBody $ \sendChunk _flush -> do IO.hSeek handle IO.AbsoluteSeek $ filePartOffset part let loop remaining | remaining <= 0 = return () loop remaining = do bs <- B.hGetSome handle defaultChunkSize unless (B.null bs) $ do let x = B.take remaining bs sendChunk $ fromByteString x loop $ remaining - B.length x loop $ fromIntegral $ filePartByteCount part ) responseToStream (ResponseFile s h fp Nothing) = ( s , h , \withBody -> IO.withBinaryFile fp IO.ReadMode $ \handle -> withBody $ \sendChunk _flush -> fix $ \loop -> do bs <- B.hGetSome handle defaultChunkSize unless (B.null bs) $ do sendChunk $ fromByteString bs loop ) responseToStream (ResponseBuilder s h b) = (s, h, \withBody -> withBody $ \sendChunk _flush -> sendChunk b) responseToStream (ResponseRaw _ res) = responseToStream res ---------------------------------------------------------------- -- | The WAI application. type Application = Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived -- | Middleware is a component that sits between the server and application. It -- can do such tasks as GZIP encoding or response caching. What follows is the -- general definition of middleware, though a middleware author should feel -- free to modify this. -- -- As an example of an alternate type for middleware, suppose you write a -- function to load up session information. The session information is simply a -- string map \[(String, String)\]. A logical type signature for this middleware -- might be: -- -- @ loadSession :: ([(String, String)] -> Application) -> Application @ -- -- Here, instead of taking a standard 'Application' as its first argument, the -- middleware takes a function which consumes the session information as well. type Middleware = Application -> Application -- | A default, blank request. -- -- Since 2.0.0 defaultRequest :: Request defaultRequest = Request { requestMethod = H.methodGet , httpVersion = H.http10 , rawPathInfo = B.empty , rawQueryString = B.empty , requestHeaders = [] , isSecure = False , remoteHost = SockAddrInet 0 0 , pathInfo = [] , queryString = [] , requestBody = return B.empty , vault = mempty , requestBodyLength = KnownLength 0 , requestHeaderHost = Nothing , requestHeaderRange = Nothing } -- | Get the request body as a lazy ByteString. This uses lazy I\/O under the -- surface, and therefore all typical warnings regarding lazy I/O apply. -- -- Since 1.4.1 lazyRequestBody :: Request -> IO L.ByteString lazyRequestBody req = loop where loop = unsafeInterleaveIO $ do bs <- requestBody req if B.null bs then return LI.Empty else do bss <- loop return $ LI.Chunk bs bss
sol/wai
wai/Network/Wai.hs
Haskell
mit
9,632
{-| Low-Level Inferface for LMDB Event Log. -} module Urbit.Vere.LMDB where import Urbit.Prelude hiding (init) import Data.RAcquire import Database.LMDB.Raw import Foreign.Marshal.Alloc import Foreign.Ptr import Urbit.Vere.Pier.Types import Foreign.Storable (peek, poke, sizeOf) import qualified Data.ByteString.Unsafe as BU -- Types ----------------------------------------------------------------------- type Env = MDB_env type Val = MDB_val type Txn = MDB_txn type Dbi = MDB_dbi type Cur = MDB_cursor data VereLMDBExn = NoLogIdentity | MissingEvent EventId | BadNounInLogIdentity ByteString DecodeErr ByteString | BadKeyInEventLog | BadWriteLogIdentity LogIdentity | BadWriteEvent EventId | BadWriteEffect EventId deriving Show instance Exception VereLMDBExn where -- Transactions ---------------------------------------------------------------- {-| A read-only transaction that commits at the end. Use this when opening database handles. -} openTxn :: Env -> RAcquire e Txn openTxn env = mkRAcquire begin commit where begin = io $ mdb_txn_begin env Nothing True commit = io . mdb_txn_commit {-| A read-only transaction that aborts at the end. Use this when reading data from already-opened databases. -} readTxn :: Env -> RAcquire e Txn readTxn env = mkRAcquire begin abort where begin = io $ mdb_txn_begin env Nothing True abort = io . mdb_txn_abort {-| A read-write transaction that commits upon sucessful completion and aborts on exception. Use this when reading data from already-opened databases. -} writeTxn :: Env -> RAcquire e Txn writeTxn env = mkRAcquireType begin finalize where begin = io $ mdb_txn_begin env Nothing False finalize txn = io . \case ReleaseNormal -> mdb_txn_commit txn ReleaseEarly -> mdb_txn_commit txn ReleaseException -> mdb_txn_abort txn -- Cursors --------------------------------------------------------------------- cursor :: Txn -> Dbi -> RAcquire e Cur cursor txn dbi = mkRAcquire open close where open = io $ mdb_cursor_open txn dbi close = io . mdb_cursor_close -- Last Key In Dbi ------------------------------------------------------------- lastKeyWord64 :: Env -> Dbi -> Txn -> RIO e Word64 lastKeyWord64 env dbi txn = rwith (cursor txn dbi) $ \cur -> withKVPtrs' nullVal nullVal $ \pKey pVal -> io $ mdb_cursor_get MDB_LAST cur pKey pVal >>= \case False -> pure 0 True -> peek pKey >>= mdbValToWord64 -- Delete Rows ----------------------------------------------------------------- deleteAllRows :: Env -> Dbi -> RIO e () deleteAllRows env dbi = rwith (writeTxn env) $ \txn -> rwith (cursor txn dbi) $ \cur -> withKVPtrs' nullVal nullVal $ \pKey pVal -> do let loop = io (mdb_cursor_get MDB_LAST cur pKey pVal) >>= \case False -> pure () True -> do io $ mdb_cursor_del (compileWriteFlags []) cur loop loop deleteRowsFrom :: HasLogFunc e => Env -> Dbi -> Word64 -> RIO e () deleteRowsFrom env dbi start = do rwith (writeTxn env) $ \txn -> do last <- lastKeyWord64 env dbi txn for_ [start..last] $ \eId -> do withWordPtr eId $ \pKey -> do let key = MDB_val 8 (castPtr pKey) found <- io $ mdb_del txn dbi key Nothing unless found $ throwIO (MissingEvent eId) -- Append Rows to Sequence ----------------------------------------------------- {- appendToSequence :: Env -> Dbi -> Vector ByteString -> RIO e () appendToSequence env dbi events = do numEvs <- readIORef (numEvents log) next <- pure (numEvs + 1) doAppend $ zip [next..] $ toList events writeIORef (numEvents log) (numEvs + word (length events)) where flags = compileWriteFlags [MDB_NOOVERWRITE] doAppend = \kvs -> rwith (writeTxn env) $ \txn -> for_ kvs $ \(k,v) -> do putBytes flags txn dbi k v >>= \case True -> pure () False -> throwIO (BadWriteEvent k) -} -- Insert ---------------------------------------------------------------------- insertWord64 :: Env -> Dbi -> Word64 -> ByteString -> RIO e () insertWord64 env dbi k v = do rwith (writeTxn env) $ \txn -> putBytes flags txn dbi k v >>= \case True -> pure () False -> throwIO (BadWriteEffect k) where flags = compileWriteFlags [] {- -------------------------------------------------------------------------------- -- Read Events ----------------------------------------------------------------- streamEvents :: HasLogFunc e => EventLog -> Word64 -> ConduitT () ByteString (RIO e) () streamEvents log first = do last <- lift $ lastEv log batch <- lift $ readBatch log first unless (null batch) $ do for_ batch yield streamEvents log (first + word (length batch)) streamEffectsRows :: ∀e. HasLogFunc e => EventLog -> EventId -> ConduitT () (Word64, ByteString) (RIO e) () streamEffectsRows log = go where go :: EventId -> ConduitT () (Word64, ByteString) (RIO e) () go next = do batch <- lift $ readRowsBatch (env log) (effectsTbl log) next unless (null batch) $ do for_ batch yield go (next + fromIntegral (length batch)) {- Read 1000 rows from the events table, starting from event `first`. Throws `MissingEvent` if an event was missing from the log. -} readBatch :: EventLog -> Word64 -> RIO e (V.Vector ByteString) readBatch log first = start where start = do last <- lastEv log if (first > last) then pure mempty else readRows $ fromIntegral $ min 1000 $ ((last+1) - first) assertFound :: EventId -> Bool -> RIO e () assertFound id found = do unless found $ throwIO $ MissingEvent id readRows count = withWordPtr first $ \pIdx -> withKVPtrs' (MDB_val 8 (castPtr pIdx)) nullVal $ \pKey pVal -> rwith (readTxn $ env log) $ \txn -> rwith (cursor txn $ eventsTbl log) $ \cur -> do assertFound first =<< io (mdb_cursor_get MDB_SET_KEY cur pKey pVal) fetchRows count cur pKey pVal fetchRows count cur pKey pVal = do env <- ask V.generateM count $ \i -> runRIO env $ do key <- io $ peek pKey >>= mdbValToWord64 val <- io $ peek pVal >>= mdbValToBytes idx <- pure (first + word i) unless (key == idx) $ throwIO $ MissingEvent idx when (count /= succ i) $ do assertFound idx =<< io (mdb_cursor_get MDB_NEXT cur pKey pVal) pure val {- Read 1000 rows from the database, starting from key `first`. -} readRowsBatch :: ∀e. HasLogFunc e => Env -> Dbi -> Word64 -> RIO e (V.Vector (Word64, ByteString)) readRowsBatch env dbi first = readRows where readRows = do logDebug $ display ("(readRowsBatch) From: " <> tshow first) withWordPtr first $ \pIdx -> withKVPtrs' (MDB_val 8 (castPtr pIdx)) nullVal $ \pKey pVal -> rwith (readTxn env) $ \txn -> rwith (cursor txn dbi) $ \cur -> io (mdb_cursor_get MDB_SET_RANGE cur pKey pVal) >>= \case False -> pure mempty True -> V.unfoldrM (fetchBatch cur pKey pVal) 1000 fetchBatch :: Cur -> Ptr Val -> Ptr Val -> Word -> RIO e (Maybe ((Word64, ByteString), Word)) fetchBatch cur pKey pVal 0 = pure Nothing fetchBatch cur pKey pVal n = do key <- io $ peek pKey >>= mdbValToWord64 val <- io $ peek pVal >>= mdbValToBytes io $ mdb_cursor_get MDB_NEXT cur pKey pVal >>= \case False -> pure $ Just ((key, val), 0) True -> pure $ Just ((key, val), pred n) -} -- Utils ----------------------------------------------------------------------- withKVPtrs' :: (MonadIO m, MonadUnliftIO m) => Val -> Val -> (Ptr Val -> Ptr Val -> m a) -> m a withKVPtrs' k v cb = withRunInIO $ \run -> withKVPtrs k v $ \x y -> run (cb x y) nullVal :: MDB_val nullVal = MDB_val 0 nullPtr word :: Int -> Word64 word = fromIntegral assertExn :: Exception e => Bool -> e -> IO () assertExn True _ = pure () assertExn False e = throwIO e eitherExn :: Exception e => Either a b -> (a -> e) -> IO b eitherExn eat exn = either (throwIO . exn) pure eat byteStringAsMdbVal :: ByteString -> (MDB_val -> IO a) -> IO a byteStringAsMdbVal bs k = BU.unsafeUseAsCStringLen bs $ \(ptr,sz) -> k (MDB_val (fromIntegral sz) (castPtr ptr)) mdbValToWord64 :: MDB_val -> IO Word64 mdbValToWord64 (MDB_val sz ptr) = do assertExn (sz == 8) BadKeyInEventLog peek (castPtr ptr) withWord64AsMDBval :: (MonadIO m, MonadUnliftIO m) => Word64 -> (MDB_val -> m a) -> m a withWord64AsMDBval w cb = do withWordPtr w $ \p -> cb (MDB_val (fromIntegral (sizeOf w)) (castPtr p)) withWordPtr :: (MonadIO m, MonadUnliftIO m) => Word64 -> (Ptr Word64 -> m a) -> m a withWordPtr w cb = withRunInIO $ \run -> allocaBytes (sizeOf w) (\p -> poke p w >> run (cb p)) -- Lower-Level Operations ------------------------------------------------------ getMb :: MonadIO m => Txn -> Dbi -> ByteString -> m (Maybe Noun) getMb txn db key = io $ byteStringAsMdbVal key $ \mKey -> mdb_get txn db mKey >>= traverse (mdbValToNoun key) mdbValToBytes :: MDB_val -> IO ByteString mdbValToBytes (MDB_val sz ptr) = do BU.unsafePackCStringLen (castPtr ptr, fromIntegral sz) mdbValToNoun :: ByteString -> MDB_val -> IO Noun mdbValToNoun key (MDB_val sz ptr) = do bs <- BU.unsafePackCStringLen (castPtr ptr, fromIntegral sz) let res = cueBS bs eitherExn res (\err -> BadNounInLogIdentity key err bs) putNoun :: MonadIO m => MDB_WriteFlags -> Txn -> Dbi -> ByteString -> Noun -> m Bool putNoun flags txn db key val = io $ byteStringAsMdbVal key $ \mKey -> byteStringAsMdbVal (jamBS val) $ \mVal -> mdb_put flags txn db mKey mVal putBytes :: MonadIO m => MDB_WriteFlags -> Txn -> Dbi -> Word64 -> ByteString -> m Bool putBytes flags txn db id bs = io $ withWord64AsMDBval id $ \idVal -> byteStringAsMdbVal bs $ \mVal -> mdb_put flags txn db idVal mVal
jfranklin9000/urbit
pkg/hs/urbit-king/lib/Urbit/Vere/LMDB.hs
Haskell
mit
10,406
module Haskmon.Types.MetaData( module Haskmon.Types.MetaData, I.MetaData ) where import Data.Time.Clock import Haskmon.Types.Internals(MetaData) import qualified Haskmon.Types.Internals as I resourceUri :: MetaData -> String resourceUri = I.resourceUri created :: MetaData -> UTCTime created = I.created modified :: MetaData -> UTCTime modified = I.modified
bitemyapp/Haskmon
src/Haskmon/Types/MetaData.hs
Haskell
mit
368
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="hu-HU"> <title>TLS Debug | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_hu_HU/helpset_hu_HU.hs
Haskell
apache-2.0
971
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="da-DK"> <title>HTTPS Info | ZAP Add-on</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/httpsInfo/src/main/javahelp/org/zaproxy/zap/extension/httpsinfo/resources/help_da_DK/helpset_da_DK.hs
Haskell
apache-2.0
969
-------------------------------------------------------------------- -- | -- Module : Flickr.Photos.Geo -- Description : flickr.photos.geo - setting/getting photo geo location. -- Copyright : (c) Sigbjorn Finne, 2008 -- License : BSD3 -- -- Maintainer : Sigbjorn Finne <sof@forkIO.com> -- Stability : provisional -- Portability : portable -- -- flickr.photos.geo API, setting/getting photo geo location. -------------------------------------------------------------------- module Flickr.Photos.Geo ( getLocation -- :: PhotoID -> FM GeoLocation , removeLocation -- :: PhotoID -> FM () , setLocation -- :: PhotoID -> GeoLocation -> FM () , batchCorrectLocation -- :: GeoLocation -> Either PlaceID WhereOnEarthID -> FM () , correctLocation -- :: PhotoID -> Either PlaceID WhereOnEarthID -> FM () , photosForLocation -- :: GeoLocation -> [PhotoInfo] -> FM [Photo] , setContext -- :: PhotoID -> ContextID -> FM () , getPerms -- :: PhotoID -> FM Permissions , setPerms -- :: PhotoID -> Permissions -> FM () ) where import Flickr.Monad import Flickr.Utils import Flickr.Types import Flickr.Types.Import -- | Correct the places hierarchy for all the photos for a user at -- a given latitude, longitude and accuracy. -- -- Batch corrections are processed in a delayed queue so it may take -- a few minutes before the changes are reflected in a user's photos. batchCorrectLocation :: GeoLocation -> Either PlaceID WhereOnEarthID -> FM () batchCorrectLocation (lat,lon,acc) ei = withWritePerm $ postMethod $ flickCall_ "flickr.photos.geo.batchCorrectLocation" (eiArg "place_id" "woe_id" ei $ mbArg "accuracy" (fmap show acc) $ [ ("latitude", lat) , ("longitude", lon) ]) -- | update/correct the location of attached to a photo. correctLocation :: PhotoID -> Either PlaceID WhereOnEarthID -> FM () correctLocation pid ei = withWritePerm $ postMethod $ flickCall_ "flickr.photos.geo.correctLocation" (eiArg "place_id" "woe_id" ei $ [ ("photo_id", pid) ]) -- | Get the geo data (latitude and longitude and the accuracy level) for a photo. getLocation :: PhotoID -> FM GeoLocation getLocation pid = flickTranslate toGeoLocation $ flickrCall "flickr.photos.geo.getLocation" [ ("photo_id", pid) ] -- | Get permissions for who may view geo data for a photo. getPerms :: PhotoID -> FM Permissions getPerms pid = flickTranslate toPermissions $ flickrCall "flickr.photos.geo.getPerms" [ ("photo_id", pid) ] -- | Return a list of photos for a user at a specific latitude, longitude and accuracy photosForLocation :: GeoLocation -> [PhotoInfo] -> FM (PhotoContext, [Photo]) photosForLocation (lat,lon,acc) extras = withReadPerm $ flickTranslate toPhotoList $ flickrCall "flickr.photo.geo.photosForLocation" (mbArg "accuracy" (fmap show acc) $ lsArg "extras" (map show extras) $ [ ("latitude", lat) , ("longitude", lon) ]) -- | Removes the geo data associated with a photo. removeLocation :: PhotoID -> FM () removeLocation pid = withWritePerm $ postMethod $ flickCall_ "flickr.photos.geo.removeLocation" [ ("photo_id", pid) ] -- | Indicate the state of a photo's geotagginess beyond -- latitude and longitude. Photos passed to this method must -- already be geotagged (using the 'setLocation' method). setContext :: PhotoID -> ContextID -> FM () setContext pid ctxtId = withWritePerm $ postMethod $ flickCall_ "flickr.photos.geo.setContext" [ ("photo_id", pid) , ("context", show ctxtId) ] -- | Sets the geo data (latitude and longitude and, optionally, -- the accuracy level) for a photo. Before users may assign -- location data to a photo they must define who, by default, -- may view that information. Users can edit this preference -- at http://www.flickr.com/account/geo/privacy/. If a user -- has not set this preference, the API method will return -- an error. setLocation :: PhotoID -> GeoLocation -> FM () setLocation pid (la,lo,ac) = withWritePerm $ postMethod $ flickCall_ "flickr.photos.geo.setLocation" (mbArg "accuracy" (fmap show ac) $ [ ("photo_id", pid) , ("lat", la) , ("lon", lo) ]) -- | Set the permission for who may view the geo data associated with a photo. setPerms :: PhotoID -> Permissions -> FM () setPerms pid p = withWritePerm $ postMethod $ flickCall_ "flickr.photos.geo.setPerms" [ ("photo_id", pid) , ("is_public", showBool $ permIsPublic p) , ("is_friend", showBool $ permIsFriend p) , ("is_family", showBool $ permIsFamily p) , ("is_contact", showBool (permIsFamily p || permIsFriend p)) ]
sof/flickr
Flickr/Photos/Geo.hs
Haskell
bsd-3-clause
4,894
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} -- | Pretty printing. module HIndent.Pretty ( -- * Printing Pretty , pretty , prettyNoExt -- * User state ,getState ,putState ,modifyState -- * Insertion , write , newline , space , comma , int , string -- * Common node types , withCtx , printComment , printComments , withCaseContext , rhsSeparator -- * Interspersing , inter , spaced , lined , prefixedLined , commas -- * Wrapping , parens , brackets , braces -- * Indentation , indented , indentedBlock , column , getColumn , getLineNum , depend , dependBind , swing , swingBy , getIndentSpaces , getColumnLimit -- * Predicates , nullBinds -- * Sandboxing , sandbox -- * Fallback , pretty' ) where import Control.Monad.Trans.Maybe import Data.Functor.Identity import HIndent.Types import Language.Haskell.Exts.Comments import Control.Monad.State.Strict hiding (state) import Data.Int import Data.List import Data.Maybe import Data.Foldable (traverse_) import Data.Monoid hiding (Alt) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Lazy as LT import Data.Text.Lazy.Builder (Builder) import qualified Data.Text.Lazy.Builder as T import Data.Text.Lazy.Builder.Int import Data.Typeable import qualified Language.Haskell.Exts as P import Language.Haskell.Exts.Syntax import Language.Haskell.Exts.SrcLoc import Prelude hiding (exp) -------------------------------------------------------------------------------- -- * Pretty printing class -- | Pretty printing class. class (Annotated ast,Typeable ast) => Pretty ast where prettyInternal :: MonadState (PrintState s) m => ast NodeInfo -> m () -- | Pretty print using extenders. pretty :: (Pretty ast,MonadState (PrintState s) m) => ast NodeInfo -> m () pretty a = do st <- get case st of PrintState{psExtenders = es,psUserState = s} -> do printComments Before a depend (case listToMaybe (mapMaybe (makePrinter s) es) of Just (Printer m) -> modify (\s' -> fromMaybe s' (runIdentity (runMaybeT (execStateT m s')))) Nothing -> prettyNoExt a) (printComments After a) where makePrinter _ (Extender f) = case cast a of Just v -> Just (f v) Nothing -> Nothing makePrinter s (CatchAll f) = f s a -- | Run the basic printer for the given node without calling an -- extension hook for this node, but do allow extender hooks in child -- nodes. Also auto-inserts comments. prettyNoExt :: (Pretty ast,MonadState (PrintState s) m) => ast NodeInfo -> m () prettyNoExt = prettyInternal -- | Print comments of a node. printComments :: (Pretty ast,MonadState (PrintState s) m) => ComInfoLocation -> ast NodeInfo -> m () printComments loc' ast = do preprocessor <- gets psCommentPreprocessor let correctLocation comment = comInfoLocation comment == Just loc' commentsWithLocation = filter correctLocation (nodeInfoComments info) comments <- preprocessor $ map comInfoComment commentsWithLocation forM_ comments $ \comment -> do -- Preceeding comments must have a newline before them. hasNewline <- gets psNewline when (not hasNewline && loc' == Before) newline printComment (Just $ srcInfoSpan $ nodeInfoSpan info) comment where info = ann ast -- | Pretty print a comment. printComment :: MonadState (PrintState s) m => Maybe SrcSpan -> Comment -> m () printComment mayNodespan (Comment inline cspan str) = do -- Insert proper amount of space before comment. -- This maintains alignment. This cannot force comments -- to go before the left-most possible indent (specified by depends). case mayNodespan of Just nodespan -> do let neededSpaces = srcSpanStartColumn cspan - max 1 (srcSpanEndColumn nodespan) replicateM_ neededSpaces space Nothing -> return () if inline then do write "{-" string str write "-}" when (1 == srcSpanStartColumn cspan) $ modify (\s -> s {psEolComment = True}) else do write "--" string str modify (\s -> s {psEolComment = True}) -- | Pretty print using HSE's own printer. The 'P.Pretty' class here -- is HSE's. pretty' :: (Pretty ast,P.Pretty (ast SrcSpanInfo),Functor ast,MonadState (PrintState s) m) => ast NodeInfo -> m () pretty' = write . T.fromText . T.pack . P.prettyPrint . fmap nodeInfoSpan -------------------------------------------------------------------------------- -- * Combinators -- | Get the user state. getState :: Printer s s getState = gets psUserState -- | Put the user state. putState :: s -> Printer s () putState s' = modifyState (const s') -- | Modify the user state. modifyState :: (s -> s) -> Printer s () modifyState f = modify (\s -> s {psUserState = f (psUserState s)}) -- | Increase indentation level by n spaces for the given printer. indented :: MonadState (PrintState s) m => Int64 -> m a -> m a indented i p = do level <- gets psIndentLevel modify (\s -> s {psIndentLevel = level + i}) m <- p modify (\s -> s {psIndentLevel = level}) return m indentedBlock :: MonadState (PrintState s) m => m a -> m a indentedBlock p = do indentSpaces <- getIndentSpaces indented indentSpaces p -- | Print all the printers separated by spaces. spaced :: MonadState (PrintState s) m => [m ()] -> m () spaced = inter space -- | Print all the printers separated by commas. commas :: MonadState (PrintState s) m => [m ()] -> m () commas = inter comma -- | Print all the printers separated by sep. inter :: MonadState (PrintState s) m => m () -> [m ()] -> m () inter sep ps = foldr (\(i,p) next -> depend (do p if i < length ps then sep else return ()) next) (return ()) (zip [1 ..] ps) -- | Print all the printers separated by newlines. lined :: MonadState (PrintState s) m => [m ()] -> m () lined ps = sequence_ (intersperse newline ps) -- | Print all the printers separated newlines and optionally a line -- prefix. prefixedLined :: MonadState (PrintState s) m => Text -> [m ()] -> m () prefixedLined pref ps' = case ps' of [] -> return () (p:ps) -> do p indented (fromIntegral (T.length pref * (-1))) (mapM_ (\p' -> do newline depend (write (T.fromText pref)) p') ps) -- | Set the (newline-) indent level to the given column for the given -- printer. column :: MonadState (PrintState s) m => Int64 -> m a -> m a column i p = do level <- gets psIndentLevel modify (\s -> s {psIndentLevel = i}) m <- p modify (\s -> s {psIndentLevel = level}) return m -- | Get the current indent level. getColumn :: MonadState (PrintState s) m => m Int64 getColumn = gets psColumn -- | Get the current line number. getLineNum :: MonadState (PrintState s) m => m Int64 getLineNum = gets psLine -- | Output a newline. newline :: MonadState (PrintState s) m => m () newline = do write "\n" modify (\s -> s {psNewline = True}) -- | Set the context to a case context, where RHS is printed with -> . withCaseContext :: MonadState (PrintState s) m => Bool -> m a -> m a withCaseContext bool pr = do original <- gets psInsideCase modify (\s -> s {psInsideCase = bool}) result <- pr modify (\s -> s {psInsideCase = original}) return result -- | Get the current RHS separator, either = or -> . rhsSeparator :: MonadState (PrintState s) m => m () rhsSeparator = do inCase <- gets psInsideCase if inCase then write "->" else write "=" -- | Make the latter's indentation depend upon the end column of the -- former. depend :: MonadState (PrintState s) m => m () -> m b -> m b depend maker dependent = do state' <- get maker st <- get col <- gets psColumn if psLine state' /= psLine st || psColumn state' /= psColumn st then column col dependent else dependent -- | Make the latter's indentation depend upon the end column of the -- former. dependBind :: MonadState (PrintState s) m => m a -> (a -> m b) -> m b dependBind maker dependent = do state' <- get v <- maker st <- get col <- gets psColumn if psLine state' /= psLine st || psColumn state' /= psColumn st then column col (dependent v) else (dependent v) -- | Wrap in parens. parens :: MonadState (PrintState s) m => m a -> m a parens p = depend (write "(") (do v <- p write ")" return v) -- | Wrap in braces. braces :: MonadState (PrintState s) m => m a -> m a braces p = depend (write "{") (do v <- p write "}" return v) -- | Wrap in brackets. brackets :: MonadState (PrintState s) m => m a -> m a brackets p = depend (write "[") (do v <- p write "]" return v) -- | Write a space. space :: MonadState (PrintState s) m => m () space = write " " -- | Write a comma. comma :: MonadState (PrintState s) m => m () comma = write "," -- | Write an integral. int :: (Integral n, MonadState (PrintState s) m) => n -> m () int = write . decimal -- | Write out a string, updating the current position information. write :: MonadState (PrintState s) m => Builder -> m () write x = do eol <- gets psEolComment when (eol && x /= "\n") newline state <- get let clearEmpty = configClearEmptyLines (psConfig state) writingNewline = x == "\n" out = if psNewline state && not (clearEmpty && writingNewline) then T.fromText (T.replicate (fromIntegral (psIndentLevel state)) " ") <> x else x out' = T.toLazyText out modify (\s -> s {psOutput = psOutput state <> out ,psNewline = False ,psEolComment = False ,psLine = psLine state + additionalLines ,psColumn = if additionalLines > 0 then LT.length (LT.concat (take 1 (reverse srclines))) else psColumn state + LT.length out'}) where x' = T.toLazyText x srclines = LT.lines x' additionalLines = LT.length (LT.filter (== '\n') x') -- | Write a string. string :: MonadState (PrintState s) m =>String -> m () string = write . T.fromText . T.pack -- | Indent spaces, e.g. 2. getIndentSpaces :: MonadState (PrintState s) m => m Int64 getIndentSpaces = gets (configIndentSpaces . psConfig) -- | Column limit, e.g. 80 getColumnLimit :: MonadState (PrintState s) m => m Int64 getColumnLimit = gets (configMaxColumns . psConfig) -- | Play with a printer and then restore the state to what it was -- before. sandbox :: MonadState s m => m a -> m (a,s) sandbox p = do orig <- get a <- p new <- get put orig return (a,new) -- | No binds? nullBinds :: Binds NodeInfo -> Bool nullBinds (BDecls _ x) = null x nullBinds (IPBinds _ x) = null x -- | Render a type with a context, or not. withCtx :: (MonadState (PrintState s) m ,Pretty ast) => Maybe (ast NodeInfo) -> m b -> m b withCtx Nothing m = m withCtx (Just ctx) m = do pretty ctx write " =>" newline m -- | Maybe render an overlap definition. maybeOverlap :: MonadState (PrintState s) m => Maybe (Overlap NodeInfo) -> m () maybeOverlap = maybe (return ()) (\p -> pretty p >> space) -- | Swing the second printer below and indented with respect to the first. swing :: MonadState (PrintState s) m => m () -> m b -> m b swing a b = do orig <- gets psIndentLevel a newline indentSpaces <- getIndentSpaces column (orig + indentSpaces) b -- | Swing the second printer below and indented with respect to the first by -- the specified amount. swingBy :: MonadState (PrintState s) m => Int64 -> m () -> m b -> m b swingBy i a b = do orig <- gets psIndentLevel a newline column (orig + i) b -------------------------------------------------------------------------------- -- * Instances instance Pretty Context where prettyInternal ctx = case ctx of CxSingle _ a -> pretty a CxTuple _ as -> parens (prefixedLined "," (map pretty as)) CxEmpty _ -> parens (return ()) instance Pretty Pat where prettyInternal x = case x of PLit _ sign l -> pretty sign >> pretty l PNPlusK _ n k -> depend (do pretty n write "+") (int k) PInfixApp _ a op b -> case op of Special{} -> depend (pretty a) (depend (prettyInfixOp op) (pretty b)) _ -> depend (do pretty a space) (depend (do prettyInfixOp op space) (pretty b)) PApp _ f args -> depend (do pretty f unless (null args) space) (spaced (map pretty args)) PTuple _ boxed pats -> depend (write (case boxed of Unboxed -> "(#" Boxed -> "(")) (do commas (map pretty pats) write (case boxed of Unboxed -> "#)" Boxed -> ")")) PList _ ps -> brackets (commas (map pretty ps)) PParen _ e -> parens (pretty e) PRec _ qname fields -> do indentSpaces <- getIndentSpaces depend (do pretty qname space) (braces (prefixedLined "," (map (indented indentSpaces . pretty) fields))) PAsPat _ n p -> depend (do pretty n write "@") (pretty p) PWildCard _ -> write "_" PIrrPat _ p -> depend (write "~") (pretty p) PatTypeSig _ p ty -> depend (do pretty p write " :: ") (pretty ty) PViewPat _ e p -> depend (do pretty e write " -> ") (pretty p) PQuasiQuote _ name str -> brackets (depend (do write "$" string name write "|") (string str)) PBangPat _ p -> depend (write "!") (pretty p) PRPat{} -> pretty' x PXTag{} -> pretty' x PXETag{} -> pretty' x PXPcdata{} -> pretty' x PXPatTag{} -> pretty' x PXRPats{} -> pretty' x PVar{} -> pretty' x -- | Pretty print a name for being an infix operator. prettyInfixOp :: MonadState (PrintState s) m => QName NodeInfo -> m () prettyInfixOp x = case x of Qual _ mn n -> case n of Ident _ i -> do write "`"; pretty mn; write "."; string i; write "`"; Symbol _ s -> do pretty mn; write "."; string s; UnQual _ n -> case n of Ident _ i -> string ("`" ++ i ++ "`") Symbol _ s -> string s Special _ s -> pretty s instance Pretty Type where prettyInternal x = case x of TyForall _ mbinds ctx ty -> depend (case mbinds of Nothing -> return () Just ts -> do write "forall " spaced (map pretty ts) write ". ") (withCtx ctx (pretty ty)) TyFun _ a b -> depend (do pretty a write " -> ") (pretty b) TyTuple _ boxed tys -> depend (write (case boxed of Unboxed -> "(#" Boxed -> "(")) (do commas (map pretty tys) write (case boxed of Unboxed -> "#)" Boxed -> ")")) TyList _ t -> brackets (pretty t) TyParArray _ t -> brackets (do write ":" pretty t write ":") TyApp _ f a -> spaced [pretty f,pretty a] TyVar _ n -> pretty n TyCon _ p -> pretty p TyParen _ e -> parens (pretty e) TyInfix _ a op b -> depend (do pretty a space) (depend (do prettyInfixOp op space) (pretty b)) TyKind _ ty k -> parens (do pretty ty write " :: " pretty k) TyBang _ bangty unpackty right -> do pretty unpackty pretty bangty pretty right TyEquals _ left right -> do pretty left write " ~ " pretty right ty@TyPromoted{} -> pretty' ty TySplice{} -> error "FIXME: No implementation for TySplice." TyWildCard _ name -> case name of Nothing -> write "_" Just n -> do write "_" pretty n instance Pretty Exp where prettyInternal = exp -- | Render an expression. exp :: MonadState (PrintState s) m => Exp NodeInfo -> m () exp (ExprHole {}) = write "_" exp (InfixApp _ a op b) = depend (do pretty a space pretty op space) (do pretty b) exp (App _ op a) = swing (do pretty f) (lined (map pretty args)) where (f,args) = flatten op [a] flatten :: Exp NodeInfo -> [Exp NodeInfo] -> (Exp NodeInfo,[Exp NodeInfo]) flatten (App _ f' a') b = flatten f' (a' : b) flatten f' as = (f',as) exp (NegApp _ e) = depend (write "-") (pretty e) exp (Lambda _ ps e) = depend (write "\\") (do spaced (map pretty ps) swing (write " -> ") (pretty e)) exp (Let _ binds e) = do depend (write "let ") (pretty binds) newline depend (write "in ") (pretty e) exp (If _ p t e) = do depend (write "if ") (do pretty p newline depend (write "then ") (pretty t) newline depend (write "else ") (pretty e)) exp (Paren _ e) = parens (pretty e) exp (Case _ e alts) = do depend (write "case ") (do pretty e write " of") newline indentedBlock (lined (map (withCaseContext True . pretty) alts)) exp (Do _ stmts) = depend (write "do ") (lined (map pretty stmts)) exp (MDo _ stmts) = depend (write "mdo ") (lined (map pretty stmts)) exp (Tuple _ boxed exps) = depend (write (case boxed of Unboxed -> "(#" Boxed -> "(")) (do prefixedLined "," (map pretty exps) write (case boxed of Unboxed -> "#)" Boxed -> ")")) exp (TupleSection _ boxed mexps) = depend (write (case boxed of Unboxed -> "(#" Boxed -> "(")) (do commas (map (maybe (return ()) pretty) mexps) write (case boxed of Unboxed -> "#)" Boxed -> ")")) exp (List _ es) = brackets (prefixedLined "," (map pretty es)) exp (LeftSection _ e op) = parens (depend (do pretty e space) (pretty op)) exp (RightSection _ e op) = parens (depend (do pretty e space) (pretty op)) exp (RecConstr _ n fs) = depend (do pretty n space) (braces (prefixedLined "," (map (indentedBlock . pretty) fs))) exp (RecUpdate _ n fs) = depend (do pretty n space) (braces (prefixedLined "," (map (indentedBlock . pretty) fs))) exp (EnumFrom _ e) = brackets (do pretty e write " ..") exp (EnumFromTo _ e f) = brackets (depend (do pretty e write " .. ") (pretty f)) exp (EnumFromThen _ e t) = brackets (depend (do pretty e write ",") (do pretty t write " ..")) exp (EnumFromThenTo _ e t f) = brackets (depend (do pretty e write ",") (depend (do pretty t write " .. ") (pretty f))) exp (ListComp _ e qstmt) = brackets (do pretty e unless (null qstmt) (do newline indented (-1) (write "|") prefixedLined "," (map pretty qstmt))) exp (ExpTypeSig _ e t) = depend (do pretty e write " :: ") (pretty t) exp (VarQuote _ x) = depend (write "'") (pretty x) exp (TypQuote _ x) = depend (write "''") (pretty x) exp (BracketExp _ b) = pretty b exp (SpliceExp _ s) = pretty s exp (QuasiQuote _ n s) = brackets (depend (do string n write "|") (do string s write "|")) exp (LCase _ alts) = do write "\\case" newline indentedBlock (lined (map (withCaseContext True . pretty) alts)) exp (MultiIf _ alts) = withCaseContext True (depend (write "if ") (lined (map (\p -> do write "| " pretty p) alts))) exp (Lit _ lit) = prettyInternal lit exp x@XTag{} = pretty' x exp x@XETag{} = pretty' x exp x@XPcdata{} = pretty' x exp x@XExpTag{} = pretty' x exp x@XChildTag{} = pretty' x exp x@Var{} = pretty' x exp x@IPVar{} = pretty' x exp x@Con{} = pretty' x exp x@CorePragma{} = pretty' x exp x@SCCPragma{} = pretty' x exp x@GenPragma{} = pretty' x exp x@Proc{} = pretty' x exp x@LeftArrApp{} = pretty' x exp x@RightArrApp{} = pretty' x exp x@LeftArrHighApp{} = pretty' x exp x@RightArrHighApp{} = pretty' x exp x@ParArray{} = pretty' x exp x@ParArrayFromTo{} = pretty' x exp x@ParArrayFromThenTo{} = pretty' x exp x@ParArrayComp{} = pretty' x exp ParComp{} = error "FIXME: No implementation for ParComp." instance Pretty Stmt where prettyInternal x = case x of Generator _ p e -> depend (do pretty p write " <- ") (pretty e) Qualifier _ e -> pretty e LetStmt _ binds -> depend (write "let ") (pretty binds) RecStmt{} -> error "FIXME: No implementation for RecStmt." instance Pretty QualStmt where prettyInternal x = case x of QualStmt _ s -> pretty s ThenTrans{} -> error "FIXME: No implementation for ThenTrans." ThenBy{} -> error "FIXME: No implementation for ThenBy." GroupBy{} -> error "FIXME: No implementation for GroupBy." GroupUsing{} -> error "FIXME: No implementation for GroupUsing." GroupByUsing{} -> error "FIXME: No implementation for GroupByUsing." instance Pretty Decl where prettyInternal = decl -- | Render a declaration. decl :: MonadState (PrintState s) m => Decl NodeInfo -> m () decl (PatBind _ pat rhs mbinds) = do pretty pat withCaseContext False (pretty rhs) case mbinds of Nothing -> return () Just binds -> do newline indentedBlock (depend (write "where ") (pretty binds)) decl (InstDecl _ moverlap dhead decls) = do depend (write "instance ") (depend (maybeOverlap moverlap) (depend (pretty dhead) (unless (null (fromMaybe [] decls)) (write " where")))) unless (null (fromMaybe [] decls)) (do newline indentedBlock (lined (map pretty (fromMaybe [] decls)))) decl (SpliceDecl _ e) = pretty e decl (TypeSig _ names ty) = depend (do inter (write ", ") (map pretty names) write " :: ") (pretty ty) decl (FunBind _ matches) = lined (map pretty matches) decl (ClassDecl _ ctx dhead fundeps decls) = do depend (write "class ") (withCtx ctx (depend (do pretty dhead space) (depend (unless (null fundeps) (do write " | " commas (map pretty fundeps))) (unless (null (fromMaybe [] decls)) (write " where"))))) unless (null (fromMaybe [] decls)) (do newline indentedBlock (lined (map pretty (fromMaybe [] decls)))) decl (TypeDecl _ typehead typ) = depend (write "type ") (depend (pretty typehead) (depend (write " = ") (pretty typ))) decl TypeFamDecl{} = error "FIXME: No implementation for TypeFamDecl." decl (DataDecl _ dataornew ctx dhead condecls mderivs) = do depend (do pretty dataornew space) (withCtx ctx (do pretty dhead case condecls of [] -> return () [x] -> singleCons x xs -> multiCons xs)) indentSpaces <- getIndentSpaces case mderivs of Nothing -> return () Just derivs -> do newline column indentSpaces (pretty derivs) where singleCons x = do write " =" indentSpaces <- getIndentSpaces column indentSpaces (do newline pretty x) multiCons xs = do newline indentSpaces <- getIndentSpaces column indentSpaces (depend (write "=") (prefixedLined "|" (map (depend space . pretty) xs))) decl (InlineSig _ inline _ name) = do write "{-# " unless inline $ write "NO" write "INLINE " pretty name write " #-}" decl x = pretty' x instance Pretty Deriving where prettyInternal (Deriving _ heads) = do write "deriving" space let heads' = if length heads == 1 then map stripParens heads else heads parens (commas (map pretty heads')) where stripParens (IParen _ iRule) = stripParens iRule stripParens x = x instance Pretty Alt where prettyInternal x = case x of Alt _ p galts mbinds -> do pretty p pretty galts case mbinds of Nothing -> return () Just binds -> do newline indentedBlock (depend (write "where ") (pretty binds)) instance Pretty Asst where prettyInternal x = case x of ClassA _ name types -> spaced (pretty name : map pretty types) i@InfixA{} -> pretty' i IParam{} -> error "FIXME: No implementation for IParam." EqualP _ a b -> do pretty a write " ~ " pretty b ParenA _ asst -> parens (pretty asst) AppA _ name tys -> spaced (pretty name : map pretty tys) WildCardA _ name -> case name of Nothing -> write "_" Just n -> do write "_" pretty n instance Pretty BangType where prettyInternal x = case x of BangedTy _ -> write "!" LazyTy _ -> write "~" NoStrictAnnot _ -> pure () instance Pretty Unpackedness where prettyInternal (Unpack _) = write "{-# UNPACK -#}" prettyInternal (NoUnpack _) = write "{-# NOUNPACK -#}" prettyInternal (NoUnpackPragma _) = pure () instance Pretty Binds where prettyInternal x = case x of BDecls _ ds -> lined (map pretty ds) IPBinds _ i -> lined (map pretty i) instance Pretty ClassDecl where prettyInternal x = case x of ClsDecl _ d -> pretty d ClsDataFam _ ctx h mkind -> depend (write "data ") (withCtx ctx (do pretty h (case mkind of Nothing -> return () Just kind -> do write " :: " pretty kind))) ClsTyFam _ h mkind minj -> depend (write "type ") (depend (pretty h) (depend (traverse_ (\kind -> write " :: " >> pretty kind) mkind) (traverse_ pretty minj))) ClsTyDef _ (TypeEqn _ this that) -> do write "type " pretty this write " = " pretty that ClsDefSig _ name ty -> do write "default " pretty name write " :: " pretty ty instance Pretty ConDecl where prettyInternal x = case x of ConDecl _ name bangty -> depend (do pretty name space) (lined (map pretty bangty)) InfixConDecl l a f b -> pretty (ConDecl l f [a,b]) RecDecl _ name fields -> depend (do pretty name write " ") (do depend (write "{") (prefixedLined "," (map pretty fields)) write "}") instance Pretty FieldDecl where prettyInternal (FieldDecl _ names ty) = depend (do commas (map pretty names) write " :: ") (pretty ty) instance Pretty FieldUpdate where prettyInternal x = case x of FieldUpdate _ n e -> swing (do pretty n write " = ") (pretty e) FieldPun _ n -> pretty n FieldWildcard _ -> write ".." instance Pretty GuardedRhs where prettyInternal x = case x of GuardedRhs _ stmts e -> do indented 1 (do prefixedLined "," (map (\p -> do space pretty p) stmts)) swing (write " " >> rhsSeparator >> write " ") (pretty e) instance Pretty InjectivityInfo where prettyInternal x = pretty' x instance Pretty InstDecl where prettyInternal i = case i of InsDecl _ d -> pretty d InsType _ name ty -> depend (do write "type " pretty name write " = ") (pretty ty) _ -> pretty' i instance Pretty Match where prettyInternal x = case x of Match _ name pats rhs mbinds -> do depend (do pretty name space) (spaced (map pretty pats)) withCaseContext False (pretty rhs) case mbinds of Nothing -> return () Just binds -> do newline indentedBlock (depend (write "where ") (pretty binds)) InfixMatch _ pat1 name pats rhs mbinds -> do depend (do pretty pat1 space case name of Ident _ i -> string ("`" ++ i ++ "`") Symbol _ s -> string s) (do space spaced (map pretty pats)) withCaseContext False (pretty rhs) case mbinds of Nothing -> return () Just binds -> do newline indentedBlock (depend (write "where ") (pretty binds)) instance Pretty PatField where prettyInternal x = case x of PFieldPat _ n p -> depend (do pretty n write " = ") (pretty p) PFieldPun _ n -> pretty n PFieldWildcard _ -> write ".." instance Pretty QualConDecl where prettyInternal x = case x of QualConDecl _ tyvars ctx d -> depend (unless (null (fromMaybe [] tyvars)) (do write "forall " spaced (map pretty (fromMaybe [] tyvars)) write ". ")) (withCtx ctx (pretty d)) instance Pretty Rhs where prettyInternal x = case x of UnGuardedRhs _ e -> do (swing (write " " >> rhsSeparator >> write " ") (pretty e)) GuardedRhss _ gas -> do newline indented 2 (lined (map (\p -> do write "|" pretty p) gas)) instance Pretty Splice where prettyInternal x = case x of IdSplice _ str -> do write "$" string str ParenSplice _ e -> depend (write "$") (parens (pretty e)) instance Pretty InstRule where prettyInternal (IParen _ rule) = parens $ pretty rule prettyInternal (IRule _ mvarbinds mctx ihead) = do case mvarbinds of Nothing -> return () Just xs -> spaced (map pretty xs) withCtx mctx (pretty ihead) instance Pretty InstHead where prettyInternal x = case x of -- Base cases IHCon _ name -> pretty name IHInfix _ typ name -> depend (pretty typ) (do space prettyInfixOp name) -- Recursive application IHApp _ ihead typ -> depend (pretty ihead) (do space pretty typ) -- Wrapping in parens IHParen _ h -> parens (pretty h) instance Pretty DeclHead where prettyInternal x = case x of DHead _ name -> pretty name DHParen _ h -> parens (pretty h) DHInfix _ var name -> do pretty var space write "`" pretty name write "`" DHApp _ dhead var -> depend (pretty dhead) (do space pretty var) instance Pretty SpecialCon where prettyInternal s = case s of UnitCon _ -> write "()" ListCon _ -> write "[]" FunCon _ -> write "->" TupleCon _ Boxed i -> string ("(" ++ replicate (i - 1) ',' ++ ")") TupleCon _ Unboxed i -> string ("(#" ++ replicate (i - 1) ',' ++ "#)") Cons _ -> write ":" UnboxedSingleCon _ -> write "(##)" instance Pretty Overlap where prettyInternal (Overlap _) = write "{-# OVERLAP #-}" prettyInternal (NoOverlap _) = write "{-# NO_OVERLAP #-}" prettyInternal (Incoherent _) = write "{-# INCOHERENT #-}" instance Pretty Sign where prettyInternal (Signless _) = return () prettyInternal (Negative _) = write "-" -------------------------------------------------------------------------------- -- * Unimplemented or incomplete printers instance Pretty Module where prettyInternal x = case x of Module _ mayModHead pragmas imps decls -> inter (do newline newline) (mapMaybe (\(isNull,r) -> if isNull then Nothing else Just r) [(null pragmas,inter newline (map pretty pragmas)) ,(case mayModHead of Nothing -> (True,return ()) Just modHead -> (False,pretty modHead)) ,(null imps,inter newline (map pretty imps)) ,(null decls ,interOf newline (map (\case r@TypeSig{} -> (1,pretty r) r -> (2,pretty r)) decls))]) where interOf i ((c,p):ps) = case ps of [] -> p _ -> do p replicateM_ c i interOf i ps interOf _ [] = return () XmlPage{} -> error "FIXME: No implementation for XmlPage." XmlHybrid{} -> error "FIXME: No implementation for XmlHybrid." instance Pretty Bracket where prettyInternal x = case x of ExpBracket _ p -> brackets (depend (write "|") (do pretty p write "|")) PatBracket _ _ -> error "FIXME: No implementation for PatBracket." TypeBracket _ _ -> error "FIXME: No implementation for TypeBracket." d@(DeclBracket _ _) -> pretty' d instance Pretty IPBind where prettyInternal x = case x of IPBind _ _ _ -> error "FIXME: No implementation for IPBind." -------------------------------------------------------------------------------- -- * Fallback printers instance Pretty DataOrNew where prettyInternal = pretty' instance Pretty FunDep where prettyInternal = pretty' instance Pretty Kind where prettyInternal = pretty' instance Pretty ResultSig where prettyInternal (KindSig _ kind) = pretty kind prettyInternal (TyVarSig _ tyVarBind) = pretty tyVarBind instance Pretty Literal where prettyInternal (String _ _ rep) = do write "\"" string rep write "\"" prettyInternal (Char _ _ rep) = do write "'" string rep write "'" prettyInternal (PrimString _ _ rep) = do write "\"" string rep write "\"#" prettyInternal (PrimChar _ _ rep) = do write "'" string rep write "'#" -- We print the original notation (because HSE doesn't track Hex -- vs binary vs decimal notation). prettyInternal (Int _l _i originalString) = string originalString prettyInternal (Frac _l _r originalString) = string originalString prettyInternal x = pretty' x instance Pretty Name where prettyInternal = pretty' instance Pretty QName where prettyInternal = pretty' instance Pretty QOp where prettyInternal = pretty' instance Pretty TyVarBind where prettyInternal = pretty' instance Pretty ModuleHead where prettyInternal (ModuleHead _ name mwarnings mexports) = do write "module " pretty name maybe (return ()) pretty mwarnings maybe (return ()) (\exports -> do newline indented 2 (pretty exports) newline space) mexports write " where" instance Pretty ModulePragma where prettyInternal = pretty' instance Pretty ImportDecl where prettyInternal = pretty' instance Pretty ModuleName where prettyInternal (ModuleName _ name) = write (T.fromString name) instance Pretty ImportSpecList where prettyInternal = pretty' instance Pretty ImportSpec where prettyInternal = pretty' instance Pretty WarningText where prettyInternal (DeprText _ s) = write "{-# DEPRECATED " >> string s >> write " #-}" prettyInternal (WarnText _ s) = write "{-# WARNING " >> string s >> write " #-}" instance Pretty ExportSpecList where prettyInternal (ExportSpecList _ es) = parens (prefixedLined "," (map pretty es)) instance Pretty ExportSpec where prettyInternal = pretty'
ennocramer/hindent
src/HIndent/Pretty.hs
Haskell
bsd-3-clause
40,383
{-# LANGUAGE MagicHash, UnboxedTuples, ScopedTypeVariables #-} module UU.Parsing.StateParser(StateParser(..)) where import GHC.Prim import UU.Parsing.MachineInterface import UU.Parsing.Machine(AnaParser, ParsRec(..),RealParser(..),RealRecogn(..), mkPR, anaDynE) instance (InputState inp s p) => InputState (inp, state) s p where splitStateE (inp, st) = case splitStateE inp of Left' x xs -> Left' x (xs, st) Right' xs -> Right' (xs, st) splitState (inp, st) = case splitState inp of (# x,xs #) -> (# x, (xs, st) #) getPosition (inp, _) = getPosition inp class StateParser p st | p -> st where change :: (st -> st) -> p st -- return the old state set :: st -> p st set x = change (const x) get :: p st get = change id fconst x y = y instance (InputState inp s p ,OutputState out) => StateParser (AnaParser (inp, st) out s p) st where get = anaDynE (mkPR (rp,rr)) where f addRes k state = (val (addRes (snd state)) (k state)) rp = P f rr = R (f fconst ) change ch = anaDynE (mkPR (rp,rr)) where f addRes k state = case state of (inp, st) -> val (addRes st) (k (inp, ch st)) rp = P f rr = R (f fconst) newtype Errors s p = Errors [[Message s p]]
UU-ComputerScience/uulib
src/UU/Parsing/StateParser.hs
Haskell
bsd-3-clause
1,343
module Syntax.Common ( module Syntax.Common , module Text.Megaparsec , module Syntax.ParseState , module Syntax.Tree ) where import Control.Monad (void) import Control.Monad.Trans.Class (lift) import Control.Monad.State.Lazy (put, get) import qualified Text.Megaparsec.Lexer as L import Text.Megaparsec hiding (State) import Syntax.ParseState import Syntax.Tree -- Produces a whitespace consumer using `sc` as the space consumer. Consumes -- whole line and in-line comments. The syntax for both comment types are the -- same as C, with '//' indicating a whole line comment and '/* ... */' -- indicating an in-line comment. whitespaceConsumer :: Parser Char -> Parser () whitespaceConsumer sc = L.space (void sc) lineCmnt blockCmnt where lineCmnt = L.skipLineComment "//" <* void (many newline) blockCmnt = L.skipBlockComment "/*" "*/" <* void (many newline) -- Comsumes whitespace and comments, but not newlines. whitespace :: Parser () whitespace = whitespaceConsumer (oneOf "\t ") lWhitespace :: ParserM () lWhitespace = lift whitespace whitespaceNewline :: Parser () whitespaceNewline = whitespaceConsumer spaceChar -- Consumes whitespace, comments, and newlines. lWhitespaceNewline :: ParserM () lWhitespaceNewline = lift whitespaceNewline -- Succeeds if the specified string can be parsed, followed by any ignored -- whitespace or comments. tok :: String -> Parser String tok s = string s <* whitespace -- Succeeds if the specified string can be parsed, followed by any ignored -- whitespace or comments. lTok :: String -> ParserM String lTok = lift . tok -- Parses a string enclosed in parenthesis. parens :: ParserM a -> ParserM a parens = between (lTok "(") (lTok ")") -- Parses a string enclosed in curly braces. braces :: ParserM a -> ParserM a braces = between (lTok "{" <* lWhitespaceNewline) (lTok "}") -- Allows any variables or functions inside the block to overwrite definitions -- outside the block. block :: ParserM a -> ParserM a block p = do savedState <- get descendScopeM x <- p put savedState return x quoted :: ParserM a -> ParserM a quoted = between (lTok "\"") (lTok "\"") -- Parses a string encased in double quotes. quotedString :: ParserM String quotedString = quoted (many (noneOf "\"")) -- Creates a parser for each member of expTypes. Useful for ensuring many -- parses have the correct type, e.g. when invoking a function. matchedTypes :: (DataType -> ParserM a) -> [DataType] -> ParserM [a] matchedTypes makeP expTypes = foldl combine (return []) ps where combine acc p = (++) <$> acc <*> (fmap (\x -> [x]) p) ps = zipWith (\x y -> x y) (repeat makeP) expTypes
BakerSmithA/Turing
src/Syntax/Common.hs
Haskell
bsd-3-clause
2,648
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ {-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-} #endif #if __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Trustworthy #-} #endif #include "containers.h" ----------------------------------------------------------------------------- -- | -- Module : Data.Tree -- Copyright : (c) The University of Glasgow 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : portable -- -- Multi-way trees (/aka/ rose trees) and forests. -- ----------------------------------------------------------------------------- module Data.Tree( Tree(..), Forest, -- * Two-dimensional drawing drawTree, drawForest, -- * Extraction flatten, levels, -- * Building trees unfoldTree, unfoldForest, unfoldTreeM, unfoldForestM, unfoldTreeM_BF, unfoldForestM_BF, ) where #if MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>)) import Data.Foldable (toList) #else import Control.Applicative (Applicative(..), (<$>)) import Data.Foldable (Foldable(foldMap), toList) import Data.Monoid (Monoid(..)) import Data.Traversable (Traversable(traverse)) #endif import Control.Monad (liftM) import Data.Sequence (Seq, empty, singleton, (<|), (|>), fromList, ViewL(..), ViewR(..), viewl, viewr) import Data.Typeable import Control.DeepSeq (NFData(rnf)) #ifdef __GLASGOW_HASKELL__ import Data.Data (Data) #endif #if MIN_VERSION_base(4,8,0) import Data.Coerce #endif -- | Multi-way trees, also known as /rose trees/. data Tree a = Node { rootLabel :: a, -- ^ label value subForest :: Forest a -- ^ zero or more child trees } #ifdef __GLASGOW_HASKELL__ deriving (Eq, Read, Show, Data) #else deriving (Eq, Read, Show) #endif type Forest a = [Tree a] INSTANCE_TYPEABLE1(Tree,treeTc,"Tree") instance Functor Tree where fmap = fmapTree fmapTree :: (a -> b) -> Tree a -> Tree b fmapTree f (Node x ts) = Node (f x) (map (fmapTree f) ts) #if MIN_VERSION_base(4,8,0) -- Safe coercions were introduced in 4.7.0, but I am not sure if they played -- well enough with RULES to do what we want. {-# NOINLINE [1] fmapTree #-} {-# RULES "fmapTree/coerce" fmapTree coerce = coerce #-} #endif instance Applicative Tree where pure x = Node x [] Node f tfs <*> tx@(Node x txs) = Node (f x) (map (f <$>) txs ++ map (<*> tx) tfs) instance Monad Tree where return x = Node x [] Node x ts >>= f = Node x' (ts' ++ map (>>= f) ts) where Node x' ts' = f x instance Traversable Tree where traverse f (Node x ts) = Node <$> f x <*> traverse (traverse f) ts instance Foldable Tree where foldMap f (Node x ts) = f x `mappend` foldMap (foldMap f) ts #if MIN_VERSION_base(4,8,0) null _ = False {-# INLINE null #-} toList = flatten {-# INLINE toList #-} #endif instance NFData a => NFData (Tree a) where rnf (Node x ts) = rnf x `seq` rnf ts -- | Neat 2-dimensional drawing of a tree. drawTree :: Tree String -> String drawTree = unlines . draw -- | Neat 2-dimensional drawing of a forest. drawForest :: Forest String -> String drawForest = unlines . map drawTree draw :: Tree String -> [String] draw (Node x ts0) = x : drawSubTrees ts0 where drawSubTrees [] = [] drawSubTrees [t] = "|" : shift "`- " " " (draw t) drawSubTrees (t:ts) = "|" : shift "+- " "| " (draw t) ++ drawSubTrees ts shift first other = zipWith (++) (first : repeat other) -- | The elements of a tree in pre-order. flatten :: Tree a -> [a] flatten t = squish t [] where squish (Node x ts) xs = x:Prelude.foldr squish xs ts -- | Lists of nodes at each level of the tree. levels :: Tree a -> [[a]] levels t = map (map rootLabel) $ takeWhile (not . null) $ iterate (concatMap subForest) [t] -- | Build a tree from a seed value unfoldTree :: (b -> (a, [b])) -> b -> Tree a unfoldTree f b = let (a, bs) = f b in Node a (unfoldForest f bs) -- | Build a forest from a list of seed values unfoldForest :: (b -> (a, [b])) -> [b] -> Forest a unfoldForest f = map (unfoldTree f) -- | Monadic tree builder, in depth-first order unfoldTreeM :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a) unfoldTreeM f b = do (a, bs) <- f b ts <- unfoldForestM f bs return (Node a ts) -- | Monadic forest builder, in depth-first order #ifndef __NHC__ unfoldForestM :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a) #endif unfoldForestM f = Prelude.mapM (unfoldTreeM f) -- | Monadic tree builder, in breadth-first order, -- using an algorithm adapted from -- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/, -- by Chris Okasaki, /ICFP'00/. unfoldTreeM_BF :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a) unfoldTreeM_BF f b = liftM getElement $ unfoldForestQ f (singleton b) where getElement xs = case viewl xs of x :< _ -> x EmptyL -> error "unfoldTreeM_BF" -- | Monadic forest builder, in breadth-first order, -- using an algorithm adapted from -- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/, -- by Chris Okasaki, /ICFP'00/. unfoldForestM_BF :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a) unfoldForestM_BF f = liftM toList . unfoldForestQ f . fromList -- takes a sequence (queue) of seeds -- produces a sequence (reversed queue) of trees of the same length unfoldForestQ :: Monad m => (b -> m (a, [b])) -> Seq b -> m (Seq (Tree a)) unfoldForestQ f aQ = case viewl aQ of EmptyL -> return empty a :< aQ' -> do (b, as) <- f a tQ <- unfoldForestQ f (Prelude.foldl (|>) aQ' as) let (tQ', ts) = splitOnto [] as tQ return (Node b ts <| tQ') where splitOnto :: [a'] -> [b'] -> Seq a' -> (Seq a', [a']) splitOnto as [] q = (q, as) splitOnto as (_:bs) q = case viewr q of q' :> a -> splitOnto (a:as) bs q' EmptyR -> error "unfoldForestQ"
shockkolate/containers
Data/Tree.hs
Haskell
bsd-3-clause
5,981
-- | Render some text to HTML, replacing any URIs with actual links. module Text.Blaze.Linkify where import Data.Text (Text) import Text.Blaze.Html5 import Text.Blaze.Html5.Attributes import Text.Links import Data.String.Extra -- | Render some text to HTML, replacing any URIs with actual links. linkify :: Text -> Html linkify = mapM_ renderOrLeave . explodeLinks where renderOrLeave (Right text) = toHtml text renderOrLeave (Left uri) = a ! href (toValue (show uri)) $ toHtml (limitLen 100 (show uri))
plow-technologies/ircbrowse
src/Text/Blaze/Linkify.hs
Haskell
bsd-3-clause
516
yes = map (\(a,_) -> a) xs
mpickering/hlint-refactor
tests/examples/Default22.hs
Haskell
bsd-3-clause
26
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts #-} ----------------------------------------------------------------------------- -- | -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : provisional -- Portability : portable -- -- Operations on affine spaces. ----------------------------------------------------------------------------- module Linear.Covector ( Covector(..) , ($*) ) where import Control.Applicative import Control.Monad import Data.Functor.Plus hiding (zero) import qualified Data.Functor.Plus as Plus import Data.Functor.Bind import Data.Functor.Rep as Rep import Linear.Algebra -- | Linear functionals from elements of an (infinite) free module to a scalar newtype Covector r a = Covector { runCovector :: (a -> r) -> r } infixr 0 $* ($*) :: Representable f => Covector r (Rep f) -> f r -> r Covector f $* m = f (Rep.index m) instance Functor (Covector r) where fmap f (Covector m) = Covector $ \k -> m (k . f) instance Apply (Covector r) where Covector mf <.> Covector ma = Covector $ \k -> mf $ \f -> ma (k . f) instance Applicative (Covector r) where pure a = Covector $ \k -> k a Covector mf <*> Covector ma = Covector $ \k -> mf $ \f -> ma $ k . f instance Bind (Covector r) where Covector m >>- f = Covector $ \k -> m $ \a -> runCovector (f a) k instance Monad (Covector r) where return a = Covector $ \k -> k a Covector m >>= f = Covector $ \k -> m $ \a -> runCovector (f a) k instance Num r => Alt (Covector r) where Covector m <!> Covector n = Covector $ \k -> m k + n k instance Num r => Plus (Covector r) where zero = Covector (const 0) instance Num r => Alternative (Covector r) where Covector m <|> Covector n = Covector $ \k -> m k + n k empty = Covector (const 0) instance Num r => MonadPlus (Covector r) where Covector m `mplus` Covector n = Covector $ \k -> m k + n k mzero = Covector (const 0) instance Coalgebra r m => Num (Covector r m) where Covector f + Covector g = Covector $ \k -> f k + g k Covector f - Covector g = Covector $ \k -> f k - g k Covector f * Covector g = Covector $ \k -> f $ \m -> g $ comult k m negate (Covector f) = Covector $ \k -> negate (f k) abs _ = error "Covector.abs: undefined" signum _ = error "Covector.signum: undefined" fromInteger n = Covector $ \ k -> fromInteger n * counital k
bgamari/linear
src/Linear/Covector.hs
Haskell
bsd-3-clause
2,413
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RankNTypes #-} module Main where import Control.Lens import qualified Graphics.Vty as V import qualified Brick.Main as M import qualified Brick.Types as T import Brick.Widgets.Core ( (<+>) , (<=>) , hLimit , vLimit , str ) import qualified Brick.Widgets.Center as C import qualified Brick.Widgets.Edit as E import qualified Brick.AttrMap as A import Brick.Util (on) data St = St { _currentEditor :: T.Name , _edit1 :: E.Editor , _edit2 :: E.Editor } makeLenses ''St firstEditor :: T.Name firstEditor = "edit1" secondEditor :: T.Name secondEditor = "edit2" switchEditors :: St -> St switchEditors st = let next = if st^.currentEditor == firstEditor then secondEditor else firstEditor in st & currentEditor .~ next currentEditorL :: St -> Lens' St E.Editor currentEditorL st = if st^.currentEditor == firstEditor then edit1 else edit2 drawUI :: St -> [T.Widget] drawUI st = [ui] where ui = C.center $ (str "Input 1 (unlimited): " <+> (hLimit 30 $ vLimit 5 $ E.renderEditor $ st^.edit1)) <=> str " " <=> (str "Input 2 (limited to 2 lines): " <+> (hLimit 30 $ E.renderEditor $ st^.edit2)) <=> str " " <=> str "Press Tab to switch between editors, Esc to quit." appEvent :: St -> V.Event -> T.EventM (T.Next St) appEvent st ev = case ev of V.EvKey V.KEsc [] -> M.halt st V.EvKey (V.KChar '\t') [] -> M.continue $ switchEditors st _ -> M.continue =<< T.handleEventLensed st (currentEditorL st) ev initialState :: St initialState = St firstEditor (E.editor firstEditor (str . unlines) Nothing "") (E.editor secondEditor (str . unlines) (Just 2) "") theMap :: A.AttrMap theMap = A.attrMap V.defAttr [ (E.editAttr, V.white `on` V.blue) ] appCursor :: St -> [T.CursorLocation] -> Maybe T.CursorLocation appCursor st = M.showCursorNamed (st^.currentEditor) theApp :: M.App St V.Event theApp = M.App { M.appDraw = drawUI , M.appChooseCursor = appCursor , M.appHandleEvent = appEvent , M.appStartEvent = return , M.appAttrMap = const theMap , M.appLiftVtyEvent = id } main :: IO () main = do st <- M.defaultMain theApp initialState putStrLn "In input 1 you entered:\n" putStrLn $ unlines $ E.getEditContents $ st^.edit1 putStrLn "In input 2 you entered:\n" putStrLn $ unlines $ E.getEditContents $ st^.edit2
sisirkoppaka/brick
programs/EditDemo.hs
Haskell
bsd-3-clause
2,609
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sk-SK"> <title>Code Dx | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_sk_SK/helpset_sk_SK.hs
Haskell
apache-2.0
968
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="en-GB"> <title>ViewState</title> <maps> <homeID>viewstate</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/viewstate/src/main/javahelp/help/helpset.hs
Haskell
apache-2.0
973
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Lens.Internal -- Copyright : (C) 2012-15 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : Rank2Types -- -- These are some of the explicit 'Functor' instances that leak into the -- type signatures of @Control.Lens@. You shouldn't need to import this -- module directly for most use-cases. -- ---------------------------------------------------------------------------- module Control.Lens.Internal ( module Control.Lens.Internal.Bazaar , module Control.Lens.Internal.Context , module Control.Lens.Internal.Fold , module Control.Lens.Internal.Getter , module Control.Lens.Internal.Indexed , module Control.Lens.Internal.Iso , module Control.Lens.Internal.Level , module Control.Lens.Internal.Magma , module Control.Lens.Internal.Prism , module Control.Lens.Internal.Review , module Control.Lens.Internal.Setter , module Control.Lens.Internal.Zoom ) where import Control.Lens.Internal.Bazaar import Control.Lens.Internal.Context import Control.Lens.Internal.Fold import Control.Lens.Internal.Getter import Control.Lens.Internal.Indexed import Control.Lens.Internal.Instances () import Control.Lens.Internal.Iso import Control.Lens.Internal.Level import Control.Lens.Internal.Magma import Control.Lens.Internal.Prism import Control.Lens.Internal.Review import Control.Lens.Internal.Setter import Control.Lens.Internal.Zoom #ifdef HLINT {-# ANN module "HLint: ignore Use import/export shortcut" #-} #endif
danidiaz/lens
src/Control/Lens/Internal.hs
Haskell
bsd-3-clause
1,676
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , ForeignFunctionInterface , MagicHash , UnboxedTuples , ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-deprecations #-} -- kludge for the Control.Concurrent.QSem, Control.Concurrent.QSemN -- and Control.Concurrent.SampleVar imports. ----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (concurrency) -- -- A common interface to a collection of useful concurrency -- abstractions. -- ----------------------------------------------------------------------------- module Control.Concurrent ( -- * Concurrent Haskell -- $conc_intro -- * Basic concurrency operations ThreadId, #ifdef __GLASGOW_HASKELL__ myThreadId, #endif forkIO, #ifdef __GLASGOW_HASKELL__ forkFinally, forkIOWithUnmask, killThread, throwTo, #endif -- ** Threads with affinity forkOn, forkOnWithUnmask, getNumCapabilities, setNumCapabilities, threadCapability, -- * Scheduling -- $conc_scheduling yield, -- :: IO () -- ** Blocking -- $blocking #ifdef __GLASGOW_HASKELL__ -- ** Waiting threadDelay, -- :: Int -> IO () threadWaitRead, -- :: Int -> IO () threadWaitWrite, -- :: Int -> IO () #endif -- * Communication abstractions module Control.Concurrent.MVar, module Control.Concurrent.Chan, module Control.Concurrent.QSem, module Control.Concurrent.QSemN, module Control.Concurrent.SampleVar, -- * Merging of streams #ifndef __HUGS__ mergeIO, -- :: [a] -> [a] -> IO [a] nmergeIO, -- :: [[a]] -> IO [a] #endif -- $merge #ifdef __GLASGOW_HASKELL__ -- * Bound Threads -- $boundthreads rtsSupportsBoundThreads, forkOS, isCurrentThreadBound, runInBoundThread, runInUnboundThread, #endif -- * Weak references to ThreadIds mkWeakThreadId, -- * GHC's implementation of concurrency -- |This section describes features specific to GHC's -- implementation of Concurrent Haskell. -- ** Haskell threads and Operating System threads -- $osthreads -- ** Terminating the program -- $termination -- ** Pre-emption -- $preemption -- * Deprecated functions forkIOUnmasked ) where import Prelude import Control.Exception.Base as Exception #ifdef __GLASGOW_HASKELL__ import GHC.Exception import GHC.Conc hiding (threadWaitRead, threadWaitWrite) import qualified GHC.Conc import GHC.IO ( IO(..), unsafeInterleaveIO, unsafeUnmask ) import GHC.IORef ( newIORef, readIORef, writeIORef ) import GHC.Base import System.Posix.Types ( Fd ) import Foreign.StablePtr import Foreign.C.Types import Control.Monad ( when ) #ifdef mingw32_HOST_OS import Foreign.C import System.IO #endif #endif #ifdef __HUGS__ import Hugs.ConcBase #endif import Control.Concurrent.MVar import Control.Concurrent.Chan import Control.Concurrent.QSem import Control.Concurrent.QSemN import Control.Concurrent.SampleVar #ifdef __HUGS__ type ThreadId = () #endif {- $conc_intro The concurrency extension for Haskell is described in the paper /Concurrent Haskell/ <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>. Concurrency is \"lightweight\", which means that both thread creation and context switching overheads are extremely low. Scheduling of Haskell threads is done internally in the Haskell runtime system, and doesn't make use of any operating system-supplied thread packages. However, if you want to interact with a foreign library that expects your program to use the operating system-supplied thread package, you can do so by using 'forkOS' instead of 'forkIO'. Haskell threads can communicate via 'MVar's, a kind of synchronised mutable variable (see "Control.Concurrent.MVar"). Several common concurrency abstractions can be built from 'MVar's, and these are provided by the "Control.Concurrent" library. In GHC, threads may also communicate via exceptions. -} {- $conc_scheduling Scheduling may be either pre-emptive or co-operative, depending on the implementation of Concurrent Haskell (see below for information related to specific compilers). In a co-operative system, context switches only occur when you use one of the primitives defined in this module. This means that programs such as: > main = forkIO (write 'a') >> write 'b' > where write c = putChar c >> write c will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@, instead of some random interleaving of @a@s and @b@s. In practice, cooperative multitasking is sufficient for writing simple graphical user interfaces. -} {- $blocking Different Haskell implementations have different characteristics with regard to which operations block /all/ threads. Using GHC without the @-threaded@ option, all foreign calls will block all other Haskell threads in the system, although I\/O operations will not. With the @-threaded@ option, only foreign calls with the @unsafe@ attribute will block all other threads. Using Hugs, all I\/O operations and foreign calls will block all other Haskell threads. -} -- | fork a thread and call the supplied function when the thread is about -- to terminate, with an exception or a returned value. The function is -- called with asynchronous exceptions masked. -- -- > forkFinally action and_then = -- > mask $ \restore -> -- > forkIO $ try (restore action) >>= and_then -- -- This function is useful for informing the parent when a child -- terminates, for example. -- forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkFinally action and_then = mask $ \restore -> forkIO $ try (restore action) >>= and_then -- ----------------------------------------------------------------------------- -- Merging streams #ifndef __HUGS__ max_buff_size :: Int max_buff_size = 1 {-# DEPRECATED mergeIO "Control.Concurrent.mergeIO will be removed in GHC 7.8. Please use an alternative, e.g. the SafeSemaphore package, instead." #-} {-# DEPRECATED nmergeIO "Control.Concurrent.nmergeIO will be removed in GHC 7.8. Please use an alternative, e.g. the SafeSemaphore package, instead." #-} mergeIO :: [a] -> [a] -> IO [a] nmergeIO :: [[a]] -> IO [a] -- $merge -- The 'mergeIO' and 'nmergeIO' functions fork one thread for each -- input list that concurrently evaluates that list; the results are -- merged into a single output list. -- -- Note: Hugs does not provide these functions, since they require -- preemptive multitasking. mergeIO ls rs = newEmptyMVar >>= \ tail_node -> newMVar tail_node >>= \ tail_list -> newQSem max_buff_size >>= \ e -> newMVar 2 >>= \ branches_running -> let buff = (tail_list,e) in forkIO (suckIO branches_running buff ls) >> forkIO (suckIO branches_running buff rs) >> takeMVar tail_node >>= \ val -> signalQSem e >> return val type Buffer a = (MVar (MVar [a]), QSem) suckIO :: MVar Int -> Buffer a -> [a] -> IO () suckIO branches_running buff@(tail_list,e) vs = case vs of [] -> takeMVar branches_running >>= \ val -> if val == 1 then takeMVar tail_list >>= \ node -> putMVar node [] >> putMVar tail_list node else putMVar branches_running (val-1) (x:xs) -> waitQSem e >> takeMVar tail_list >>= \ node -> newEmptyMVar >>= \ next_node -> unsafeInterleaveIO ( takeMVar next_node >>= \ y -> signalQSem e >> return y) >>= \ next_node_val -> putMVar node (x:next_node_val) >> putMVar tail_list next_node >> suckIO branches_running buff xs nmergeIO lss = let len = length lss in newEmptyMVar >>= \ tail_node -> newMVar tail_node >>= \ tail_list -> newQSem max_buff_size >>= \ e -> newMVar len >>= \ branches_running -> let buff = (tail_list,e) in mapIO (\ x -> forkIO (suckIO branches_running buff x)) lss >> takeMVar tail_node >>= \ val -> signalQSem e >> return val where mapIO f xs = sequence (map f xs) #endif /* __HUGS__ */ #ifdef __GLASGOW_HASKELL__ -- --------------------------------------------------------------------------- -- Bound Threads {- $boundthreads #boundthreads# Support for multiple operating system threads and bound threads as described below is currently only available in the GHC runtime system if you use the /-threaded/ option when linking. Other Haskell systems do not currently support multiple operating system threads. A bound thread is a haskell thread that is /bound/ to an operating system thread. While the bound thread is still scheduled by the Haskell run-time system, the operating system thread takes care of all the foreign calls made by the bound thread. To a foreign library, the bound thread will look exactly like an ordinary operating system thread created using OS functions like @pthread_create@ or @CreateThread@. Bound threads can be created using the 'forkOS' function below. All foreign exported functions are run in a bound thread (bound to the OS thread that called the function). Also, the @main@ action of every Haskell program is run in a bound thread. Why do we need this? Because if a foreign library is called from a thread created using 'forkIO', it won't have access to any /thread-local state/ - state variables that have specific values for each OS thread (see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some libraries (OpenGL, for example) will not work from a thread created using 'forkIO'. They work fine in threads created using 'forkOS' or when called from @main@ or from a @foreign export@. In terms of performance, 'forkOS' (aka bound) threads are much more expensive than 'forkIO' (aka unbound) threads, because a 'forkOS' thread is tied to a particular OS thread, whereas a 'forkIO' thread can be run by any OS thread. Context-switching between a 'forkOS' thread and a 'forkIO' thread is many times more expensive than between two 'forkIO' threads. Note in particular that the main program thread (the thread running @Main.main@) is always a bound thread, so for good concurrency performance you should ensure that the main thread is not doing repeated communication with other threads in the system. Typically this means forking subthreads to do the work using 'forkIO', and waiting for the results in the main thread. -} -- | 'True' if bound threads are supported. -- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound' -- will always return 'False' and both 'forkOS' and 'runInBoundThread' will -- fail. foreign import ccall rtsSupportsBoundThreads :: Bool {- | Like 'forkIO', this sparks off a new thread to run the 'IO' computation passed as the first argument, and returns the 'ThreadId' of the newly created thread. However, 'forkOS' creates a /bound/ thread, which is necessary if you need to call foreign (non-Haskell) libraries that make use of thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads"). Using 'forkOS' instead of 'forkIO' makes no difference at all to the scheduling behaviour of the Haskell runtime system. It is a common misconception that you need to use 'forkOS' instead of 'forkIO' to avoid blocking all the Haskell threads when making a foreign call; this isn't the case. To allow foreign calls to be made without blocking all the Haskell threads (with GHC), it is only necessary to use the @-threaded@ option when linking your program, and to make sure the foreign import is not marked @unsafe@. -} forkOS :: IO () -> IO ThreadId foreign export ccall forkOS_entry :: StablePtr (IO ()) -> IO () foreign import ccall "forkOS_entry" forkOS_entry_reimported :: StablePtr (IO ()) -> IO () forkOS_entry :: StablePtr (IO ()) -> IO () forkOS_entry stableAction = do action <- deRefStablePtr stableAction action foreign import ccall forkOS_createThread :: StablePtr (IO ()) -> IO CInt failNonThreaded :: IO a failNonThreaded = fail $ "RTS doesn't support multiple OS threads " ++"(use ghc -threaded when linking)" forkOS action0 | rtsSupportsBoundThreads = do mv <- newEmptyMVar b <- Exception.getMaskingState let -- async exceptions are masked in the child if they are masked -- in the parent, as for forkIO (see #1048). forkOS_createThread -- creates a thread with exceptions masked by default. action1 = case b of Unmasked -> unsafeUnmask action0 MaskedInterruptible -> action0 MaskedUninterruptible -> uninterruptibleMask_ action0 action_plus = Exception.catch action1 childHandler entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus) err <- forkOS_createThread entry when (err /= 0) $ fail "Cannot create OS thread." tid <- takeMVar mv freeStablePtr entry return tid | otherwise = failNonThreaded -- | Returns 'True' if the calling thread is /bound/, that is, if it is -- safe to use foreign libraries that rely on thread-local state from the -- calling thread. isCurrentThreadBound :: IO Bool isCurrentThreadBound = IO $ \ s# -> case isCurrentThreadBound# s# of (# s2#, flg #) -> (# s2#, not (isTrue# (flg ==# 0#)) #) {- | Run the 'IO' computation passed as the first argument. If the calling thread is not /bound/, a bound thread is created temporarily. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. You can wrap a series of foreign function calls that rely on thread-local state with @runInBoundThread@ so that you can use them without knowing whether the current thread is /bound/. -} runInBoundThread :: IO a -> IO a runInBoundThread action | rtsSupportsBoundThreads = do bound <- isCurrentThreadBound if bound then action else do ref <- newIORef undefined let action_plus = Exception.try action >>= writeIORef ref bracket (newStablePtr action_plus) freeStablePtr (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref) >>= unsafeResult | otherwise = failNonThreaded {- | Run the 'IO' computation passed as the first argument. If the calling thread is /bound/, an unbound thread is created temporarily using 'forkIO'. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. Use this function /only/ in the rare case that you have actually observed a performance loss due to the use of bound threads. A program that doesn't need it's main thread to be bound and makes /heavy/ use of concurrency (e.g. a web server), might want to wrap it's @main@ action in @runInUnboundThread@. Note that exceptions which are thrown to the current thread are thrown in turn to the thread that is executing the given computation. This ensures there's always a way of killing the forked thread. -} runInUnboundThread :: IO a -> IO a runInUnboundThread action = do bound <- isCurrentThreadBound if bound then do mv <- newEmptyMVar mask $ \restore -> do tid <- forkIO $ Exception.try (restore action) >>= putMVar mv let wait = takeMVar mv `Exception.catch` \(e :: SomeException) -> Exception.throwTo tid e >> wait wait >>= unsafeResult else action unsafeResult :: Either SomeException a -> IO a unsafeResult = either Exception.throwIO return #endif /* __GLASGOW_HASKELL__ */ #ifdef __GLASGOW_HASKELL__ -- --------------------------------------------------------------------------- -- threadWaitRead/threadWaitWrite -- | Block the current thread until data is available to read on the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitRead', use -- 'GHC.Conc.closeFdWith'. threadWaitRead :: Fd -> IO () threadWaitRead fd #ifdef mingw32_HOST_OS -- we have no IO manager implementing threadWaitRead on Windows. -- fdReady does the right thing, but we have to call it in a -- separate thread, otherwise threadWaitRead won't be interruptible, -- and this only works with -threaded. | threaded = withThread (waitFd fd 0) | otherwise = case fd of 0 -> do _ <- hWaitForInput stdin (-1) return () -- hWaitForInput does work properly, but we can only -- do this for stdin since we know its FD. _ -> error "threadWaitRead requires -threaded on Windows, or use System.IO.hWaitForInput" #else = GHC.Conc.threadWaitRead fd #endif -- | Block the current thread until data can be written to the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitWrite', use -- 'GHC.Conc.closeFdWith'. threadWaitWrite :: Fd -> IO () threadWaitWrite fd #ifdef mingw32_HOST_OS | threaded = withThread (waitFd fd 1) | otherwise = error "threadWaitWrite requires -threaded on Windows" #else = GHC.Conc.threadWaitWrite fd #endif #ifdef mingw32_HOST_OS foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool withThread :: IO a -> IO a withThread io = do m <- newEmptyMVar _ <- mask_ $ forkIO $ try io >>= putMVar m x <- takeMVar m case x of Right a -> return a Left e -> throwIO (e :: IOException) waitFd :: Fd -> CInt -> IO () waitFd fd write = do throwErrnoIfMinus1_ "fdReady" $ fdReady (fromIntegral fd) write iNFINITE 0 iNFINITE :: CInt iNFINITE = 0xFFFFFFFF -- urgh foreign import ccall safe "fdReady" fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt #endif -- --------------------------------------------------------------------------- -- More docs {- $osthreads #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and are managed entirely by the GHC runtime. Typically Haskell threads are an order of magnitude or two more efficient (in terms of both time and space) than operating system threads. The downside of having lightweight threads is that only one can run at a time, so if one thread blocks in a foreign call, for example, the other threads cannot continue. The GHC runtime works around this by making use of full OS threads where necessary. When the program is built with the @-threaded@ option (to link against the multithreaded version of the runtime), a thread making a @safe@ foreign call will not block the other threads in the system; another OS thread will take over running Haskell threads until the original call returns. The runtime maintains a pool of these /worker/ threads so that multiple Haskell threads can be involved in external calls simultaneously. The "System.IO" library manages multiplexing in its own way. On Windows systems it uses @safe@ foreign calls to ensure that threads doing I\/O operations don't block the whole runtime, whereas on Unix systems all the currently blocked I\/O requests are managed by a single thread (the /IO manager thread/) using a mechanism such as @epoll@ or @kqueue@, depending on what is provided by the host operating system. The runtime will run a Haskell thread using any of the available worker OS threads. If you need control over which particular OS thread is used to run a given Haskell thread, perhaps because you need to call a foreign library that uses OS-thread-local state, then you need bound threads (see "Control.Concurrent#boundthreads"). If you don't use the @-threaded@ option, then the runtime does not make use of multiple OS threads. Foreign calls will block all other running Haskell threads until the call returns. The "System.IO" library still does multiplexing, so there can be multiple threads doing I\/O, and this is handled internally by the runtime using @select@. -} {- $termination In a standalone GHC program, only the main thread is required to terminate in order for the process to terminate. Thus all other forked threads will simply terminate at the same time as the main thread (the terminology for this kind of behaviour is \"daemonic threads\"). If you want the program to wait for child threads to finish before exiting, you need to program this yourself. A simple mechanism is to have each child thread write to an 'MVar' when it completes, and have the main thread wait on all the 'MVar's before exiting: > myForkIO :: IO () -> IO (MVar ()) > myForkIO io = do > mvar <- newEmptyMVar > forkFinally io (\_ -> putMVar mvar ()) > return mvar Note that we use 'forkFinally' to make sure that the 'MVar' is written to even if the thread dies or is killed for some reason. A better method is to keep a global list of all child threads which we should wait for at the end of the program: > children :: MVar [MVar ()] > children = unsafePerformIO (newMVar []) > > waitForChildren :: IO () > waitForChildren = do > cs <- takeMVar children > case cs of > [] -> return () > m:ms -> do > putMVar children ms > takeMVar m > waitForChildren > > forkChild :: IO () -> IO ThreadId > forkChild io = do > mvar <- newEmptyMVar > childs <- takeMVar children > putMVar children (mvar:childs) > forkFinally io (\_ -> putMVar mvar ()) > > main = > later waitForChildren $ > ... The main thread principle also applies to calls to Haskell from outside, using @foreign export@. When the @foreign export@ed function is invoked, it starts a new main thread, and it returns when this main thread terminates. If the call causes new threads to be forked, they may remain in the system after the @foreign export@ed function has returned. -} {- $preemption GHC implements pre-emptive multitasking: the execution of threads are interleaved in a random fashion. More specifically, a thread may be pre-empted whenever it allocates some memory, which unfortunately means that tight loops which do no allocation tend to lock out other threads (this only seems to happen with pathological benchmark-style code, however). The rescheduling timer runs on a 20ms granularity by default, but this may be altered using the @-i\<n\>@ RTS option. After a rescheduling \"tick\" the running thread is pre-empted as soon as possible. One final note: the @aaaa@ @bbbb@ example may not work too well on GHC (see Scheduling, above), due to the locking on a 'System.IO.Handle'. Only one thread may hold the lock on a 'System.IO.Handle' at any one time, so if a reschedule happens while a thread is holding the lock, the other thread won't be able to run. The upshot is that the switch from @aaaa@ to @bbbbb@ happens infrequently. It can be improved by lowering the reschedule tick period. We also have a patch that causes a reschedule whenever a thread waiting on a lock is woken up, but haven't found it to be useful for anything other than this example :-) -} #endif /* __GLASGOW_HASKELL__ */
beni55/haste-compiler
libraries/ghc-7.8/base/Control/Concurrent.hs
Haskell
bsd-3-clause
24,702
module SPARC.CodeGen.Amode ( getAmode ) where import {-# SOURCE #-} SPARC.CodeGen.Gen32 import SPARC.CodeGen.Base import SPARC.AddrMode import SPARC.Imm import SPARC.Instr import SPARC.Regs import SPARC.Base import NCGMonad import Size import Cmm import OrdList -- | Generate code to reference a memory address. getAmode :: CmmExpr -- ^ expr producing an address -> NatM Amode getAmode tree@(CmmRegOff _ _) = do dflags <- getDynFlags getAmode (mangleIndexTree dflags tree) getAmode (CmmMachOp (MO_Sub _) [x, CmmLit (CmmInt i _)]) | fits13Bits (-i) = do (reg, code) <- getSomeReg x let off = ImmInt (-(fromInteger i)) return (Amode (AddrRegImm reg off) code) getAmode (CmmMachOp (MO_Add _) [x, CmmLit (CmmInt i _)]) | fits13Bits i = do (reg, code) <- getSomeReg x let off = ImmInt (fromInteger i) return (Amode (AddrRegImm reg off) code) getAmode (CmmMachOp (MO_Add _) [x, y]) = do (regX, codeX) <- getSomeReg x (regY, codeY) <- getSomeReg y let code = codeX `appOL` codeY return (Amode (AddrRegReg regX regY) code) getAmode (CmmLit lit) = do let imm__2 = litToImm lit tmp1 <- getNewRegNat II32 tmp2 <- getNewRegNat II32 let code = toOL [ SETHI (HI imm__2) tmp1 , OR False tmp1 (RIImm (LO imm__2)) tmp2] return (Amode (AddrRegReg tmp2 g0) code) getAmode other = do (reg, code) <- getSomeReg other let off = ImmInt 0 return (Amode (AddrRegImm reg off) code)
forked-upstream-packages-for-ghcjs/ghc
compiler/nativeGen/SPARC/CodeGen/Amode.hs
Haskell
bsd-3-clause
1,625
module Main where main = print (fib' 100) -- This will time out unless memoing works properly data Nat = Z | S Nat deriving (Show, Eq) memo f = g where fz = f Z fs = memo (f . S) g Z = fz g (S n) = fs n -- It is a BAD BUG to inline 'fs' inside g -- and that happened in 6.4.1, resulting in exponential behaviour -- memo f = g (f Z) (memo (f . S)) -- = g (f Z) (g (f (S Z)) (memo (f . S . S))) -- = g (f Z) (g (f (S Z)) (g (f (S (S Z))) (memo (f . S . S . S)))) fib' :: Nat -> Integer fib' = memo fib where fib Z = 0 fib (S Z) = 1 fib (S (S n)) = fib' (S n) + fib' n instance Num Nat where fromInteger 0 = Z fromInteger n = S (fromInteger (n - 1)) Z + n = n S m + n = S (m + n) Z * n = Z S m * n = (m * n) + n Z - n = Z S m - Z = S m S m - S n = m - n instance Enum Nat where succ = S pred Z = Z pred (S n) = n toEnum = fromInteger . toInteger fromEnum Z = 0 fromEnum (S n) = fromEnum n + 1
ezyang/ghc
testsuite/tests/simplCore/should_run/simplrun005.hs
Haskell
bsd-3-clause
1,232
import Control.Monad import Data.Word (Word8) import Foreign.Ptr import Foreign.Marshal.Array import GHC.Foreign (peekCStringLen, withCStringLen) import GHC.IO.Encoding.Failure (CodingFailureMode(..)) import qualified GHC.IO.Encoding.Latin1 as Latin1 import System.IO import System.IO.Error -- Tests for single-byte encodings that map directly to Unicode -- (module GHC.IO.Encoding.Latin1) eitherToMaybe :: Either a b -> Maybe b eitherToMaybe (Left _) = Nothing eitherToMaybe (Right b) = Just b decode :: TextEncoding -> [Word8] -> IO (Maybe String) decode enc xs = fmap eitherToMaybe . tryIOError $ withArrayLen xs (\sz p -> peekCStringLen enc (castPtr p, sz)) encode :: TextEncoding -> String -> IO (Maybe [Word8]) encode enc cs = fmap eitherToMaybe . tryIOError $ withCStringLen enc cs (\(p, sz) -> peekArray sz (castPtr p)) testIO :: (Eq a, Show a) => IO a -> a -> IO () testIO action expected = do result <- action when (result /= expected) $ putStrLn $ "Test failed: expected " ++ show expected ++ ", but got " ++ show result -- Test char8-like encodings test_char8 :: TextEncoding -> IO () test_char8 enc = do testIO (decode enc [0..0xff]) $ Just ['\0'..'\xff'] testIO (encode enc ['\0'..'\x200']) $ Just ([0..0xff] ++ [0..0xff] ++ [0]) -- Test latin1-like encodings test_latin1 :: CodingFailureMode -> TextEncoding -> IO () test_latin1 cfm enc = do testIO (decode enc [0..0xff]) $ Just ['\0'..'\xff'] testIO (encode enc ['\0'..'\xff']) $ Just [0..0xff] testIO (encode enc "\xfe\xff\x100\x101\x100\xff\xfe") $ case cfm of ErrorOnCodingFailure -> Nothing IgnoreCodingFailure -> Just [0xfe,0xff,0xff,0xfe] TransliterateCodingFailure -> Just [0xfe,0xff,0x3f,0x3f,0x3f,0xff,0xfe] -- N.B. The argument "latin1//TRANSLIT" to mkTextEncoding does not -- correspond to "latin1//TRANSLIT" in iconv! Instead GHC asks iconv -- to encode to "latin1" and uses its own "evil hack" to insert '?' -- (ASCII 0x3f) in place of failures. See GHC.IO.Encoding.recoverEncode. -- -- U+0100 is LATIN CAPITAL LETTER A WITH MACRON, which iconv would -- transliterate to 'A' (ASCII 0x41). Similarly iconv would -- transliterate U+0101 LATIN SMALL LETTER A WITH MACRON to 'a' -- (ASCII 0x61). RoundtripFailure -> Nothing test_ascii :: CodingFailureMode -> TextEncoding -> IO () test_ascii cfm enc = do testIO (decode enc [0..0x7f]) $ Just ['\0'..'\x7f'] testIO (decode enc [0x7e,0x7f,0x80,0x81,0x80,0x7f,0x7e]) $ case cfm of ErrorOnCodingFailure -> Nothing IgnoreCodingFailure -> Just "\x7e\x7f\x7f\x7e" TransliterateCodingFailure -> Just "\x7e\x7f\xfffd\xfffd\xfffd\x7f\x7e" -- Another GHC special: decode invalid input to the Char U+FFFD -- REPLACEMENT CHARACTER. RoundtripFailure -> Just "\x7e\x7f\xdc80\xdc81\xdc80\x7f\x7e" -- GHC's PEP383-style String-encoding of invalid input, -- see Note [Roundtripping] testIO (encode enc ['\0'..'\x7f']) $ Just [0..0x7f] testIO (encode enc "\x7e\x7f\x80\x81\x80\x7f\xe9") $ case cfm of ErrorOnCodingFailure -> Nothing IgnoreCodingFailure -> Just [0x7e,0x7f,0x7f] TransliterateCodingFailure -> Just [0x7e,0x7f,0x3f,0x3f,0x3f,0x7f,0x3f] -- See comment in test_latin1. iconv -t ASCII//TRANSLIT would encode -- U+00E9 LATIN SMALL LETTER E WITH ACUTE as 'e' (ASCII 0x65). RoundtripFailure -> Nothing -- Test roundtripping for good measure case cfm of RoundtripFailure -> do Just s <- decode enc [0..0xff] testIO (encode enc s) $ Just [0..0xff] _ -> return () main = do putStrLn "char8 tests" test_char8 char8 -- char8 never fails in either direction -- These use GHC's own implementation putStrLn "Latin1.ascii tests" test_ascii ErrorOnCodingFailure (Latin1.ascii) test_ascii IgnoreCodingFailure (Latin1.mkAscii IgnoreCodingFailure) test_ascii TransliterateCodingFailure (Latin1.mkAscii TransliterateCodingFailure) test_ascii RoundtripFailure (Latin1.mkAscii RoundtripFailure) putStrLn "Latin1.latin1_checked tests" test_latin1 ErrorOnCodingFailure (Latin1.latin1_checked) test_latin1 IgnoreCodingFailure (Latin1.mkLatin1_checked IgnoreCodingFailure) test_latin1 TransliterateCodingFailure (Latin1.mkLatin1_checked TransliterateCodingFailure) test_latin1 RoundtripFailure (Latin1.mkLatin1_checked RoundtripFailure) -- These use iconv (normally, unless it is broken) putStrLn "mkTextEncoding ASCII tests" test_ascii ErrorOnCodingFailure =<< mkTextEncoding "ASCII" test_ascii IgnoreCodingFailure =<< mkTextEncoding "ASCII//IGNORE" test_ascii TransliterateCodingFailure =<< mkTextEncoding "ASCII//TRANSLIT" test_ascii RoundtripFailure =<< mkTextEncoding "ASCII//ROUNDTRIP" putStrLn "mkTextEncoding latin1 tests" test_latin1 ErrorOnCodingFailure =<< mkTextEncoding "latin1" test_latin1 IgnoreCodingFailure =<< mkTextEncoding "latin1//IGNORE" test_latin1 TransliterateCodingFailure =<< mkTextEncoding "latin1//TRANSLIT" test_latin1 RoundtripFailure =<< mkTextEncoding "latin1//ROUNDTRIP"
ezyang/ghc
libraries/base/tests/IO/encoding005.hs
Haskell
bsd-3-clause
5,035
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-} {-# LANGUAGE FlexibleInstances, IncoherentInstances, PatternGuards #-} module Idris.IdeMode(parseMessage, convSExp, WhatDocs(..), IdeModeCommand(..), sexpToCommand, toSExp, SExp(..), SExpable, Opt(..), ideModeEpoch, getLen, getNChar, sExpToString) where import Text.Printf import Numeric import Data.List import Data.Maybe (isJust) import qualified Data.Binary as Binary import qualified Data.ByteString.Base64 as Base64 import qualified Data.ByteString.Lazy as Lazy import qualified Data.ByteString.UTF8 as UTF8 import qualified Data.Text as T import Text.Trifecta hiding (Err) import Text.Trifecta.Delta import System.IO import Idris.Core.TT import Idris.Core.Binary import Control.Applicative hiding (Const) getNChar :: Handle -> Int -> String -> IO (String) getNChar _ 0 s = return (reverse s) getNChar h n s = do c <- hGetChar h getNChar h (n - 1) (c : s) getLen :: Handle -> IO (Either Err Int) getLen h = do s <- getNChar h 6 "" case readHex s of ((num, ""):_) -> return $ Right num _ -> return $ Left . Msg $ "Couldn't read length " ++ s data SExp = SexpList [SExp] | StringAtom String | BoolAtom Bool | IntegerAtom Integer | SymbolAtom String deriving ( Eq, Show ) sExpToString :: SExp -> String sExpToString (StringAtom s) = "\"" ++ escape s ++ "\"" sExpToString (BoolAtom True) = ":True" sExpToString (BoolAtom False) = ":False" sExpToString (IntegerAtom i) = printf "%d" i sExpToString (SymbolAtom s) = ":" ++ s sExpToString (SexpList l) = "(" ++ intercalate " " (map sExpToString l) ++ ")" class SExpable a where toSExp :: a -> SExp instance SExpable SExp where toSExp a = a instance SExpable Bool where toSExp True = BoolAtom True toSExp False = BoolAtom False instance SExpable String where toSExp s = StringAtom s instance SExpable Integer where toSExp n = IntegerAtom n instance SExpable Int where toSExp n = IntegerAtom (toInteger n) instance SExpable Name where toSExp s = StringAtom (show s) instance (SExpable a) => SExpable (Maybe a) where toSExp Nothing = SexpList [SymbolAtom "Nothing"] toSExp (Just a) = SexpList [SymbolAtom "Just", toSExp a] instance (SExpable a) => SExpable [a] where toSExp l = SexpList (map toSExp l) instance (SExpable a, SExpable b) => SExpable (a, b) where toSExp (l, r) = SexpList [toSExp l, toSExp r] instance (SExpable a, SExpable b, SExpable c) => SExpable (a, b, c) where toSExp (l, m, n) = SexpList [toSExp l, toSExp m, toSExp n] instance (SExpable a, SExpable b, SExpable c, SExpable d) => SExpable (a, b, c, d) where toSExp (l, m, n, o) = SexpList [toSExp l, toSExp m, toSExp n, toSExp o] instance (SExpable a, SExpable b, SExpable c, SExpable d, SExpable e) => SExpable (a, b, c, d, e) where toSExp (l, m, n, o, p) = SexpList [toSExp l, toSExp m, toSExp n, toSExp o, toSExp p] instance SExpable NameOutput where toSExp TypeOutput = SymbolAtom "type" toSExp FunOutput = SymbolAtom "function" toSExp DataOutput = SymbolAtom "data" toSExp MetavarOutput = SymbolAtom "metavar" toSExp PostulateOutput = SymbolAtom "postulate" maybeProps :: SExpable a => [(String, Maybe a)] -> [(SExp, SExp)] maybeProps [] = [] maybeProps ((n, Just p):ps) = (SymbolAtom n, toSExp p) : maybeProps ps maybeProps ((n, Nothing):ps) = maybeProps ps constTy :: Const -> String constTy (I _) = "Int" constTy (BI _) = "Integer" constTy (Fl _) = "Double" constTy (Ch _) = "Char" constTy (Str _) = "String" constTy (B8 _) = "Bits8" constTy (B16 _) = "Bits16" constTy (B32 _) = "Bits32" constTy (B64 _) = "Bits64" constTy _ = "Type" namespaceOf :: Name -> Maybe String namespaceOf (NS _ ns) = Just (intercalate "." $ reverse (map T.unpack ns)) namespaceOf _ = Nothing instance SExpable OutputAnnotation where toSExp (AnnName n ty d t) = toSExp $ [(SymbolAtom "name", StringAtom (show n)), (SymbolAtom "implicit", BoolAtom False)] ++ maybeProps [("decor", ty)] ++ maybeProps [("doc-overview", d), ("type", t)] ++ maybeProps [("namespace", namespaceOf n)] toSExp (AnnBoundName n imp) = toSExp [(SymbolAtom "name", StringAtom (show n)), (SymbolAtom "decor", SymbolAtom "bound"), (SymbolAtom "implicit", BoolAtom imp)] toSExp (AnnConst c) = toSExp [(SymbolAtom "decor", SymbolAtom (if constIsType c then "type" else "data")), (SymbolAtom "type", StringAtom (constTy c)), (SymbolAtom "doc-overview", StringAtom (constDocs c)), (SymbolAtom "name", StringAtom (show c))] toSExp (AnnData ty doc) = toSExp [(SymbolAtom "decor", SymbolAtom "data"), (SymbolAtom "type", StringAtom ty), (SymbolAtom "doc-overview", StringAtom doc)] toSExp (AnnType name doc) = toSExp $ [(SymbolAtom "decor", SymbolAtom "type"), (SymbolAtom "type", StringAtom "Type"), (SymbolAtom "doc-overview", StringAtom doc)] ++ if not (null name) then [(SymbolAtom "name", StringAtom name)] else [] toSExp AnnKeyword = toSExp [(SymbolAtom "decor", SymbolAtom "keyword")] toSExp (AnnFC fc) = toSExp [(SymbolAtom "source-loc", toSExp fc)] toSExp (AnnTextFmt fmt) = toSExp [(SymbolAtom "text-formatting", SymbolAtom format)] where format = case fmt of BoldText -> "bold" ItalicText -> "italic" UnderlineText -> "underline" toSExp (AnnLink url) = toSExp [(SymbolAtom "link-href", StringAtom url)] toSExp (AnnTerm bnd tm) | termSmallerThan 1000 tm = toSExp [(SymbolAtom "tt-term", StringAtom (encodeTerm bnd tm))] | otherwise = SexpList [] toSExp (AnnSearchResult ordr) = toSExp [(SymbolAtom "doc-overview", StringAtom ("Result type is " ++ descr))] where descr = case ordr of EQ -> "isomorphic" LT -> "more general than searched type" GT -> "more specific than searched type" toSExp (AnnErr e) = toSExp [(SymbolAtom "error", StringAtom (encodeErr e))] toSExp (AnnNamespace ns file) = toSExp $ [(SymbolAtom "namespace", StringAtom (intercalate "." (map T.unpack ns)))] ++ [(SymbolAtom "decor", SymbolAtom $ if isJust file then "module" else "namespace")] ++ maybeProps [("source-file", file)] toSExp AnnQuasiquote = toSExp [(SymbolAtom "quasiquotation", True)] toSExp AnnAntiquote = toSExp [(SymbolAtom "antiquotation", True)] encodeTerm :: [(Name, Bool)] -> Term -> String encodeTerm bnd tm = UTF8.toString . Base64.encode . Lazy.toStrict . Binary.encode $ (bnd, tm) decodeTerm :: String -> ([(Name, Bool)], Term) decodeTerm = Binary.decode . Lazy.fromStrict . Base64.decodeLenient . UTF8.fromString encodeErr :: Err -> String encodeErr e = UTF8.toString . Base64.encode . Lazy.toStrict . Binary.encode $ e decodeErr :: String -> Err decodeErr = Binary.decode . Lazy.fromStrict . Base64.decodeLenient . UTF8.fromString instance SExpable FC where toSExp (FC f (sl, sc) (el, ec)) = toSExp ((SymbolAtom "filename", StringAtom f), (SymbolAtom "start", IntegerAtom (toInteger sl), IntegerAtom (toInteger sc)), (SymbolAtom "end", IntegerAtom (toInteger el), IntegerAtom (toInteger ec))) toSExp NoFC = toSExp ([] :: [String]) toSExp (FileFC f) = toSExp [(SymbolAtom "filename", StringAtom f)] escape :: String -> String escape = concatMap escapeChar where escapeChar '\\' = "\\\\" escapeChar '"' = "\\\"" escapeChar c = [c] pSExp = do xs <- between (char '(') (char ')') (pSExp `sepBy` (char ' ')) return (SexpList xs) <|> atom atom = do string "nil"; return (SexpList []) <|> do char ':'; x <- atomC; return x <|> do char '"'; xs <- many quotedChar; char '"'; return (StringAtom xs) <|> do ints <- some digit case readDec ints of ((num, ""):_) -> return (IntegerAtom (toInteger num)) _ -> return (StringAtom ints) atomC = do string "True"; return (BoolAtom True) <|> do string "False"; return (BoolAtom False) <|> do xs <- many (noneOf " \n\t\r\"()"); return (SymbolAtom xs) quotedChar = try (string "\\\\" >> return '\\') <|> try (string "\\\"" >> return '"') <|> noneOf "\"" parseSExp :: String -> Result SExp parseSExp = parseString pSExp (Directed (UTF8.fromString "(unknown)") 0 0 0 0) data Opt = ShowImpl | ErrContext deriving Show data WhatDocs = Overview | Full data IdeModeCommand = REPLCompletions String | Interpret String | TypeOf String | CaseSplit Int String | AddClause Int String | AddProofClause Int String | AddMissing Int String | MakeWithBlock Int String | MakeCaseBlock Int String | ProofSearch Bool Int String [String] (Maybe Int) -- ^^ Recursive?, line, name, hints, depth | MakeLemma Int String | LoadFile String (Maybe Int) | DocsFor String WhatDocs | Apropos String | GetOpts | SetOpt Opt Bool | Metavariables Int -- ^^ the Int is the column count for pretty-printing | WhoCalls String | CallsWho String | BrowseNS String | TermNormalise [(Name, Bool)] Term | TermShowImplicits [(Name, Bool)] Term | TermNoImplicits [(Name, Bool)] Term | TermElab [(Name, Bool)] Term | PrintDef String | ErrString Err | ErrPPrint Err | GetIdrisVersion sexpToCommand :: SExp -> Maybe IdeModeCommand sexpToCommand (SexpList (x:[])) = sexpToCommand x sexpToCommand (SexpList [SymbolAtom "interpret", StringAtom cmd]) = Just (Interpret cmd) sexpToCommand (SexpList [SymbolAtom "repl-completions", StringAtom prefix]) = Just (REPLCompletions prefix) sexpToCommand (SexpList [SymbolAtom "load-file", StringAtom filename, IntegerAtom line]) = Just (LoadFile filename (Just (fromInteger line))) sexpToCommand (SexpList [SymbolAtom "load-file", StringAtom filename]) = Just (LoadFile filename Nothing) sexpToCommand (SexpList [SymbolAtom "type-of", StringAtom name]) = Just (TypeOf name) sexpToCommand (SexpList [SymbolAtom "case-split", IntegerAtom line, StringAtom name]) = Just (CaseSplit (fromInteger line) name) sexpToCommand (SexpList [SymbolAtom "add-clause", IntegerAtom line, StringAtom name]) = Just (AddClause (fromInteger line) name) sexpToCommand (SexpList [SymbolAtom "add-proof-clause", IntegerAtom line, StringAtom name]) = Just (AddProofClause (fromInteger line) name) sexpToCommand (SexpList [SymbolAtom "add-missing", IntegerAtom line, StringAtom name]) = Just (AddMissing (fromInteger line) name) sexpToCommand (SexpList [SymbolAtom "make-with", IntegerAtom line, StringAtom name]) = Just (MakeWithBlock (fromInteger line) name) sexpToCommand (SexpList [SymbolAtom "make-case", IntegerAtom line, StringAtom name]) = Just (MakeCaseBlock (fromInteger line) name) -- The Boolean in ProofSearch means "search recursively" -- If it's False, that means "refine", i.e. apply the name and fill in any -- arguments which can be done by unification. sexpToCommand (SexpList (SymbolAtom "proof-search" : IntegerAtom line : StringAtom name : rest)) | [] <- rest = Just (ProofSearch True (fromInteger line) name [] Nothing) | [SexpList hintexp] <- rest , Just hints <- getHints hintexp = Just (ProofSearch True (fromInteger line) name hints Nothing) | [SexpList hintexp, IntegerAtom depth] <- rest , Just hints <- getHints hintexp = Just (ProofSearch True (fromInteger line) name hints (Just (fromInteger depth))) where getHints = mapM (\h -> case h of StringAtom s -> Just s _ -> Nothing) sexpToCommand (SexpList [SymbolAtom "make-lemma", IntegerAtom line, StringAtom name]) = Just (MakeLemma (fromInteger line) name) sexpToCommand (SexpList [SymbolAtom "refine", IntegerAtom line, StringAtom name, StringAtom hint]) = Just (ProofSearch False (fromInteger line) name [hint] Nothing) sexpToCommand (SexpList [SymbolAtom "docs-for", StringAtom name]) = Just (DocsFor name Full) sexpToCommand (SexpList [SymbolAtom "docs-for", StringAtom name, SymbolAtom s]) | Just w <- lookup s opts = Just (DocsFor name w) where opts = [("overview", Overview), ("full", Full)] sexpToCommand (SexpList [SymbolAtom "apropos", StringAtom search]) = Just (Apropos search) sexpToCommand (SymbolAtom "get-options") = Just GetOpts sexpToCommand (SexpList [SymbolAtom "set-option", SymbolAtom s, BoolAtom b]) | Just opt <- lookup s opts = Just (SetOpt opt b) where opts = [("show-implicits", ShowImpl), ("error-context", ErrContext)] --TODO support more options. Issue #1611 in the Issue tracker. https://github.com/idris-lang/Idris-dev/issues/1611 sexpToCommand (SexpList [SymbolAtom "metavariables", IntegerAtom cols]) = Just (Metavariables (fromIntegral cols)) sexpToCommand (SexpList [SymbolAtom "who-calls", StringAtom name]) = Just (WhoCalls name) sexpToCommand (SexpList [SymbolAtom "calls-who", StringAtom name]) = Just (CallsWho name) sexpToCommand (SexpList [SymbolAtom "browse-namespace", StringAtom ns]) = Just (BrowseNS ns) sexpToCommand (SexpList [SymbolAtom "normalise-term", StringAtom encoded]) = let (bnd, tm) = decodeTerm encoded in Just (TermNormalise bnd tm) sexpToCommand (SexpList [SymbolAtom "show-term-implicits", StringAtom encoded]) = let (bnd, tm) = decodeTerm encoded in Just (TermShowImplicits bnd tm) sexpToCommand (SexpList [SymbolAtom "hide-term-implicits", StringAtom encoded]) = let (bnd, tm) = decodeTerm encoded in Just (TermNoImplicits bnd tm) sexpToCommand (SexpList [SymbolAtom "elaborate-term", StringAtom encoded]) = let (bnd, tm) = decodeTerm encoded in Just (TermElab bnd tm) sexpToCommand (SexpList [SymbolAtom "print-definition", StringAtom name]) = Just (PrintDef name) sexpToCommand (SexpList [SymbolAtom "error-string", StringAtom encoded]) = Just . ErrString . decodeErr $ encoded sexpToCommand (SexpList [SymbolAtom "error-pprint", StringAtom encoded]) = Just . ErrPPrint . decodeErr $ encoded sexpToCommand (SymbolAtom "version") = Just GetIdrisVersion sexpToCommand _ = Nothing parseMessage :: String -> Either Err (SExp, Integer) parseMessage x = case receiveString x of Right (SexpList [cmd, (IntegerAtom id)]) -> Right (cmd, id) Right x -> Left . Msg $ "Invalid message " ++ show x Left err -> Left err receiveString :: String -> Either Err SExp receiveString x = case parseSExp x of Failure _ -> Left . Msg $ "parse failure" Success r -> Right r convSExp :: SExpable a => String -> a -> Integer -> String convSExp pre s id = let sex = SexpList [SymbolAtom pre, toSExp s, IntegerAtom id] in let str = sExpToString sex in (getHexLength str) ++ str getHexLength :: String -> String getHexLength s = printf "%06x" (1 + (length s)) -- | The version of the IDE mode command set. Increment this when you -- change it so clients can adapt. ideModeEpoch :: Int ideModeEpoch = 1
ExNexu/Idris-dev
src/Idris/IdeMode.hs
Haskell
bsd-3-clause
16,974
{-# LANGUAGE TypeFamilies #-} module Main where data A a type T a = A a f :: (A a ~ T Int) => a -> Int f x = x main :: IO () main = return ()
siddhanathan/ghc
testsuite/tests/typecheck/should_compile/GivenTypeSynonym.hs
Haskell
bsd-3-clause
163
import Control.Concurrent import Control.Monad import Control.Exception import System.Mem -- caused an assertion failure with -debug in 7.0.1 (#4813) main = do m <- newEmptyMVar ts <- replicateM 100 $ mask_ $ forkIO $ threadDelay 100000; putMVar m () mapM_ killThread (reverse (init ts)) takeMVar m
urbanslug/ghc
testsuite/tests/concurrent/should_run/T4813.hs
Haskell
bsd-3-clause
313
-- Copyright 2015-2016 Yury Gribov -- -- Use of this source code is governed by MIT license that can be -- found in the LICENSE.txt file. module Support where import qualified System.Environment import qualified System.Exit import qualified Data.Array import Debug.Trace (trace) -- Create Data.Array.Array with all elements initialized to some value filled :: (Data.Array.Ix a) => (a, a) -> b -> Data.Array.Array a b filled bnds x = Data.Array.array bnds [(i, x) | i <- Data.Array.range bnds] -- From http://www.haskell.org/ghc/docs/6.12.1/html/users_guide/assertions.html arsert :: Bool -> a -> a arsert False _ = error "assertion failed" arsert True x = x -- Inverse of Data.List.intersperse: split list at value deintersperse :: (Eq a) => a -> [a] -> [[a]] deintersperse x xs = let deintersperse' [] acc = [reverse acc] deintersperse' (y:ys) acc = if x == y then reverse acc : deintersperse' ys [] else deintersperse' ys (y:acc) in deintersperse' xs [] -- Same as deintersperse but treat multiple separators as single one deintersperse_multi :: (Eq a) => a -> [a] -> [[a]] deintersperse_multi x xs = filter (not . null) $ deintersperse x xs -- Helper for main functions: if cmdline args contain filename - read it, otherwise read stdin readFileOrStdin :: [String] -> IO String readFileOrStdin [] = getContents readFileOrStdin (arg:_) = readFile arg -- Print user-friendly error and exit report_error :: String -> IO a report_error msg = do progname <- System.Environment.getProgName putStrLn $ progname ++ ": " ++ msg _ <- System.Exit.exitFailure return undefined -- Drop last element of list drop_last :: [a] -> [a] drop_last [_] = [] drop_last (x:xs) = x:drop_last xs force :: a -> a force x = seq x x trace_it :: (Show a) => a -> a trace_it x = trace (show x) x -- Split list to equally-sized chunks chunks :: [a] -> Int -> [[a]] chunks [] _ = [] chunks xs n = take n xs : chunks (drop n xs) n -- Left-pad list to a given size pad :: Int -> a -> [a] -> [a] pad n x xs = replicate nx x ++ xs where nx = max 0 (n - length xs) -- Integer sqrt isqrt :: Int -> Int isqrt = floor . sqrt . fromIntegral
yugr/sudoku
src/Support.hs
Haskell
mit
2,176
module Philed.Data.List (module Data.List ,module Philed.Data.ListExtras) where import Data.List import Philed.Data.ListExtras
Chattered/PhilEdCommon
Philed/Data/List.hs
Haskell
mit
152
{-# LANGUAGE TemplateHaskell, FlexibleContexts #-} module Kachushi.KState ( KState (..) , boards , deck , initialState , putCard , putCards ) where import Kachushi.Cards (Card (..), fullDeck) import Kachushi.OFCP (Board (..), emptyBoard, Slot (..), Row (..)) import Control.Lens (over, makeLenses, element) import Control.Monad.State (MonadState (..), get, modify, forM_) import Data.List ((\\)) import Data.Array.ST (runSTArray, thaw, newListArray, STArray (..), readArray, writeArray) import Control.Monad.ST (ST (..)) import Control.Applicative ((<*>)) --------------------------- -- Types --------------------------- data KState = KState { _boards :: [Board] , _deck :: [Card] } deriving Show makeLenses ''KState --------------------------- -- Costructors --------------------------- initialState n = KState (replicate n emptyBoard) fullDeck --------------------------- -- State monad --------------------------- putCard :: MonadState KState m => Int -> Card -> Row -> m () putCard n card row = putCards n [(card, row)] putCards :: MonadState KState m => Int -> [(Card, Row)] -> m () putCards n crs = let boardArray brd = runSTArray $ do array <- thaw (asArray brd) empties <- newListArray (0,2) $ [nextTop, nextMiddle, nextBottom] <*> [brd] :: (ST s) ((STArray s) Int Int) forM_ crs $ \(card, row) -> do index <- readArray empties (fromEnum row) writeArray empties (fromEnum row) (index + 1) writeArray array index (Filled card) return array t brd = (nextTop brd) + (length . filter (== Top) . map snd $ crs) m brd = (nextMiddle brd) + (length . filter (== Middle) . map snd $ crs) b brd = (nextBottom brd) + (length . filter (== Bottom) . map snd $ crs) in do state <- get modify $ over deck (\\ (map fst crs) ) . over boards (over (element n) (\brd -> (Board (boardArray brd) (t brd) (m brd) (b brd))))
ScrambledEggsOnToast/Kachushi
Kachushi/KState.hs
Haskell
mit
2,114
{-# LANGUAGE CPP #-} module GHCJS.DOM.HTMLLegendElement ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.HTMLLegendElement #else module Graphics.UI.Gtk.WebKit.DOM.HTMLLegendElement #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.HTMLLegendElement #else import Graphics.UI.Gtk.WebKit.DOM.HTMLLegendElement #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/HTMLLegendElement.hs
Haskell
mit
470
{-# LANGUAGE RecordWildCards #-} module Lambency.Camera ( mkOrthoCamera, mkPerspCamera, getViewProjMatrix, getCamXForm, setCamXForm, getCamDist, setCamDist, getCamPos, setCamPos, getCamDir, setCamDir, getCamUp, setCamUp, getCamNear, setCamNear, getCamFar, setCamFar, camLookAt, mkFixedCam, mkViewerCam, mkFreeCam, mk2DCam, ) where -------------------------------------------------------------------------------- import Control.Wire import qualified Graphics.UI.GLFW as GLFW import FRP.Netwire.Input import GHC.Float import Lambency.Types import qualified Lambency.Transform as XForm import qualified Linear.Quaternion as Quat import Linear import Prelude hiding (id, (.)) -------------------------------------------------------------------------------- mkXForm :: Vec3f -> Vec3f -> Vec3f -> XForm.Transform mkXForm pos dir up = let r = signorm $ dir `cross` up u' = signorm $ r `cross` dir in XForm.translate pos $ XForm.fromCoordinateBasis (r, u', negate dir) mkOrthoCamera :: Vec3f -> Vec3f -> Vec3f -> Float -> Float -> Float -> Float -> Float -> Float -> Camera mkOrthoCamera pos dir up l r t b n f = Camera (mkXForm pos (signorm dir) (signorm up)) (Ortho l r t b) (CameraViewDistance n f) mkPerspCamera :: Vec3f -> Vec3f -> Vec3f -> Float -> Float -> Float -> Float -> Camera mkPerspCamera pos dir up fovy aspratio n f = Camera (mkXForm pos (signorm dir) (signorm up)) Persp { fovY = fovy, aspect = aspratio } CameraViewDistance { near = n, far = f } -- !FIXME! Change the following functions to val -> Camera -> Camera getCamXForm :: Camera -> XForm.Transform getCamXForm (Camera xf _ _) = xf setCamXForm :: Camera -> XForm.Transform -> Camera setCamXForm (Camera _ cam dist) xf = Camera xf cam dist getCamDist :: Camera -> CameraViewDistance getCamDist (Camera _ _ dist) = dist setCamDist :: Camera -> CameraViewDistance -> Camera setCamDist (Camera loc cam _) dist = Camera loc cam dist getCamPos :: Camera -> Vec3f getCamPos = XForm.position . getCamXForm setCamPos :: Camera -> Vec3f -> Camera setCamPos c p = let xf = getCamXForm c nd = XForm.forward xf u = XForm.up xf in setCamXForm c $ mkXForm p (negate nd) u getCamDir :: Camera -> Vec3f getCamDir = negate . XForm.forward . getCamXForm setCamDir :: Camera -> Vec3f -> Camera setCamDir c d = let xf = getCamXForm c u = XForm.up xf p = XForm.position xf in setCamXForm c $ mkXForm p d u getCamUp :: Camera -> Vec3f getCamUp = XForm.up . getCamXForm setCamUp :: Camera -> Vec3f -> Camera setCamUp c u = let xf = getCamXForm c nd = XForm.forward xf p = XForm.position xf in setCamXForm c $ mkXForm p (negate nd) u getCamNear :: Camera -> Float getCamNear = near . getCamDist setCamNear :: Camera -> Float -> Camera setCamNear c n = let dist = getCamDist c in setCamDist c $ (\d -> d { near = n }) dist getCamFar :: Camera -> Float getCamFar = (far . getCamDist) setCamFar :: Camera -> Float -> Camera setCamFar c f = let dist = getCamDist c in setCamDist c $ (\d -> d { far = f }) dist camLookAt :: Vec3f -> Camera -> Camera camLookAt focus (Camera xf ty dist) | focus == pos = Camera xf ty dist | otherwise = Camera (mkXForm pos dir up) ty dist where pos = XForm.position xf dir = signorm $ focus - pos up = XForm.up xf getViewMatrix :: Camera -> Mat4f getViewMatrix (Camera xf _ _) = let extendWith :: Float -> Vec3f -> Vec4f extendWith w (V3 x y z) = V4 x y z w pos = negate . XForm.position $ xf (V3 sx sy sz) = XForm.scale xf r = XForm.right xf u = XForm.up xf f = XForm.forward xf te :: Vec3f -> Float -> Vec4f te n sc = extendWith (pos `dot` n) (sc *^ n) in adjoint $ V4 (te r sx) (te u sy) (te f sz) (V4 0 0 0 1) mkProjMatrix :: CameraType -> CameraViewDistance -> Mat4f mkProjMatrix (Ortho l r t b) (CameraViewDistance{..}) = transpose $ ortho l r b t near far mkProjMatrix (Persp {..}) (CameraViewDistance{..}) = transpose $ perspective fovY aspect near far getProjMatrix :: Camera -> Mat4f getProjMatrix (Camera _ ty dist) = mkProjMatrix ty dist getViewProjMatrix :: Camera -> Mat4f getViewProjMatrix c = (getViewMatrix c) !*! (getProjMatrix c) -- mkFixedCam :: Camera -> ContWire a Camera mkFixedCam cam = CW $ mkConst $ Right cam type ViewCam = (Camera, Vec3f) mkViewerCam :: Camera -> Vec3f -> ContWire a Camera mkViewerCam initialCam initialFocus = let handleRotation :: ((Float, Float), ViewCam) -> ViewCam handleRotation ((0, 0), c) = c handleRotation ((mx, my), (c@(Camera xform _ _), focus)) = (setCamPos (setCamDir c (signorm $ negate newPos)) (newPos ^+^ focus), focus) where oldPos :: Vec3f oldPos = XForm.position xform ^-^ focus newPos :: Vec3f newPos = XForm.transformPoint rotation oldPos rotation :: XForm.Transform rotation = flip XForm.rotate XForm.identity $ foldl1 (*) [ Quat.axisAngle (XForm.up xform) (-asin mx), Quat.axisAngle (XForm.right xform) (-asin my)] dxScale :: Vec3f -> Vec3f -> Float dxScale pos focus = (0.4 *) $ distance pos focus handleScroll :: ((Double, Double), ViewCam) -> ViewCam handleScroll ((_, sy), (c, x)) = let camPos = getCamPos c camDir = getCamDir c dx = (dxScale camPos x * double2Float sy) *^ camDir -- !FIXME! We should really do mouse picking here to keep the focus -- on whatever point we're intersecting with the mesh... for right now -- just don't move the focus. -- in (setCamPos c $ camPos ^+^ dx, x ^+^ dx) in (setCamPos c $ camPos ^+^ dx, x) handlePanning :: ((Float, Float), ViewCam) -> ViewCam handlePanning ((0, 0), c) = c handlePanning ((mx, my), (c@(Camera xform _ _), focus)) = (setCamPos c (oldPos ^+^ dx), focus ^+^ dx) where oldPos = XForm.position xform dx = (dxScale oldPos focus *^) $ (-mx *^ (XForm.right xform)) ^+^ (my *^ (XForm.up xform)) {-- !TODO! This might be good to add to netwire-input --} mouseIfThen :: GLFW.MouseButton -> GameWire a b -> GameWire a b -> GameWire a b mouseIfThen mb ifPressed elsePressed = whilePressed where whilePressed = (mousePressed mb >>> ifPressed) --> whileNotPressed whileNotPressed = switch $ elsePressed &&& ((mousePressed mb >>> pure whilePressed >>> now) <|> never) mouseDeltas :: GLFW.MouseButton -> GameWire a (Float, Float) mouseDeltas mb = mouseIfThen mb getDelta $ pure (0, 0) where delayM :: Monad m => m a -> Wire s e m a a delayM x' = mkGenN $ \x -> do r <- x' return (Right r, delayM $ return x) delayCursor :: GameWire (Float, Float) (Float, Float) delayCursor = delayM cursor getDelta :: GameWire a (Float, Float) getDelta = loop $ (mouseCursor *** delayCursor) >>> (arr $ \((x, y), (x', y')) -> ((x - x', y - y'), (x, y))) rotationalDeltas :: GameWire a (Float, Float) rotationalDeltas = (keyPressed GLFW.Key'LeftShift >>> pure (0, 0)) <|> mouseDeltas GLFW.MouseButton'1 panningDeltas :: GameWire a (Float, Float) panningDeltas = (keyPressed GLFW.Key'LeftShift >>> mouseDeltas GLFW.MouseButton'1) <|> mouseDeltas GLFW.MouseButton'3 in CW $ loop $ second ( delay (initialCam, initialFocus) >>> (rotationalDeltas &&& id) >>> (arr handleRotation) >>> (panningDeltas &&& id) >>> (arr handlePanning) >>> (mouseScroll &&& id) >>> (arr handleScroll)) >>> (arr $ \(_, c@(cam, _)) -> (cam, c)) mkFreeCam :: Camera -> ContWire a Camera mkFreeCam initCam = CW $ loop ((second (delay initCam >>> updCam)) >>> feedback) where feedback :: GameWire (a, b) (b, b) feedback = mkPure_ $ \(_, x) -> Right (x, x) tr :: GLFW.Key -> Float -> (XForm.Transform -> Vec3f) -> GameWire XForm.Transform XForm.Transform tr key sc dir = (trans >>> (keyPressed key)) <|> id where trans :: GameWire XForm.Transform XForm.Transform trans = mkSF $ \ts xf -> (XForm.translate (3.0 * (dtime ts) * sc *^ (dir xf)) xf, trans) updCam :: GameWire Camera Camera updCam = (id &&& (arr getCamXForm >>> xfWire)) >>> (mkSF_ $ uncurry stepCam) where xfWire :: GameWire XForm.Transform XForm.Transform xfWire = (tr GLFW.Key'W (-1.0) XForm.forward) >>> (tr GLFW.Key'S (1.0) XForm.forward) >>> (tr GLFW.Key'A (-1.0) XForm.right) >>> (tr GLFW.Key'D (1.0) XForm.right) >>> (id &&& mouseMickies) >>> (mkSF_ $ \(xf, (mx, my)) -> XForm.rotate (foldl1 (*) [ Quat.axisAngle (XForm.up xf) (-asin mx), Quat.axisAngle (XForm.right xf) (-asin my)]) xf) stepCam :: Camera -> XForm.Transform -> Camera stepCam cam newXForm = setCamXForm cam finalXForm where finalXForm = mkXForm (XForm.position newXForm) (negate $ XForm.forward newXForm) (V3 0 1 0) mk2DCam :: Int -> Int -> ContWire Vec2f Camera mk2DCam sx sy = let toHalfF :: Integral a => a -> Float toHalfF x = 0.5 * (fromIntegral x) hx :: Float hx = toHalfF sx hy :: Float hy = toHalfF sy screenCenter :: V3 Float screenCenter = V3 hx hy 1 trPos :: Vec2f -> Vec3f trPos (V2 x y) = (V3 x y 0) ^+^ screenCenter in CW $ mkSF_ $ \vec -> mkOrthoCamera (trPos vec) (negate XForm.localForward) XForm.localUp (-hx) (hx) (hy) (-hy) 0.01 50.0
Mokosha/Lambency
lib/Lambency/Camera.hs
Haskell
mit
9,911
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} module Lib where import Alex import Control.Monad import Control.Monad.Except import Control.Monad.State (MonadState, get, state) import Control.Monad.Trans.State.Strict hiding (get, state) import Data.Coerce import Data.Functor.Identity import Data.Tuple import Token {- Let's do something interesting, say parse Java. Latest spec seems to be: - https://docs.oracle.com/javase/specs/jls/se15/html/index.html - https://docs.oracle.com/javase/specs/jls/se15/html/jls-3.html -} {- TODO: project idea: a super verbose tokenizer just to see what can be carried around? TODO: it seems both GHC and Agda are not using any wrappers - how does that work? TODO: find a way to use startcode. -} main :: IO () main = print $ runAlex "let xzzz = 1234 in ts" parseAll where parseAll = alexMonadScan >>= \case EOF -> pure [] x -> (x :) <$> parseAll newtype AlexWrappper a = AW (Alex a) deriving (Functor, Applicative, Monad) via Alex deriving (MonadError String, MonadState AlexState) via StateT' AlexState (Except String) newtype StateT' s m a = ST' (s -> m (s, a)) deriving (Functor) from' :: Functor m => StateT' s m a -> StateT s m a from' (ST' f) = StateT (fmap swap . f) to' :: Functor m => StateT s m a -> StateT' s m a to' (StateT f) = ST' (fmap swap . f) -- instance Functor m => Functor (StateT' s m) where -- fmap f a = to' $ fmap f (from' a) instance Monad m => Applicative (StateT' s m) where pure a = to' $ from' (pure a) f <*> a = to' $ from' f <*> from' a instance Monad m => Monad (StateT' s m) where m >>= f = to' $ from' m >>= \a -> from' $ f a instance MonadError e m => MonadError e (StateT' s m) where throwError a = to' $ from' (throwError a) m `catchError` h = to' $ from' m `catchError` (from' . h) instance Monad m => MonadState s (StateT' s m) where state f = ST' $ pure . swap . f {- instance MonadError String AlexWrappper where throwError e = AW $ Alex (const (Left e)) (AW (Alex m)) `catchError` h = AW $ Alex $ \s -> case m s of Left l | AW (Alex f) <- h l -> f s Right r -> pure r -} {- AlexInput is of type (this can be examined in GHCi): ( AlexPosn -- position in input? , Char -- char before input , Data.ByteString.Lazy.Internal.ByteString -- current input? , GHC.Int.Int64 -- this is "bpos", looks like byte consumed so far. ) -}
Javran/misc
alex-playground/src/Lib.hs
Haskell
mit
2,729
module Network.WebSockets.Messaging ( Connection(disconnected) , request , requestAsync , notify , onRequest , onNotify , onConnect , onDisconnect , startListening , Request(..) , Notify(..) , Some(..) , deriveRequest , deriveNotify , Future , get , foldFuture , clientLibraryPath , clientLibraryCode ) where import Network.WebSockets.Messaging.Connection import Network.WebSockets.Messaging.Message import Network.WebSockets.Messaging.Message.TH import Paths_ws_messaging clientLibraryPath :: IO FilePath clientLibraryPath = getDataFileName "client/messaging.js" clientLibraryCode :: IO String clientLibraryCode = readFile =<< clientLibraryPath
leonidas/ws-messaging
src/Network/WebSockets/Messaging.hs
Haskell
mit
732
module Rebase.Data.Vector.Storable.Mutable ( module Data.Vector.Storable.Mutable ) where import Data.Vector.Storable.Mutable
nikita-volkov/rebase
library/Rebase/Data/Vector/Storable/Mutable.hs
Haskell
mit
128
import Geometry import Drawing main = drawPicture myPicture myPicture points = undefined
alphalambda/k12math
contrib/MHills/GeometryLessons/code/student/lesson2e.hs
Haskell
mit
98
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} -- | Warning: This module should be considered highly experimental. module Data.Containers where import qualified Data.Map as Map import qualified Data.HashMap.Strict as HashMap import Data.Hashable (Hashable) import qualified Data.Set as Set import qualified Data.HashSet as HashSet import Data.Monoid (Monoid) import Data.MonoTraversable (MonoFoldable, MonoTraversable, Element) import qualified Data.IntMap as IntMap import Data.Function (on) import qualified Data.List as List import qualified Data.IntSet as IntSet class (Monoid set, MonoFoldable set) => Container set where type ContainerKey set member :: ContainerKey set -> set -> Bool notMember :: ContainerKey set -> set -> Bool union :: set -> set -> set difference :: set -> set -> set intersection :: set -> set -> set instance Ord k => Container (Map.Map k v) where type ContainerKey (Map.Map k v) = k member = Map.member notMember = Map.notMember union = Map.union difference = Map.difference intersection = Map.intersection instance (Eq k, Hashable k) => Container (HashMap.HashMap k v) where type ContainerKey (HashMap.HashMap k v) = k member = HashMap.member notMember k = not . HashMap.member k union = HashMap.union difference = HashMap.difference intersection = HashMap.intersection instance Container (IntMap.IntMap v) where type ContainerKey (IntMap.IntMap v) = Int member = IntMap.member notMember = IntMap.notMember union = IntMap.union difference = IntMap.difference intersection = IntMap.intersection instance Ord e => Container (Set.Set e) where type ContainerKey (Set.Set e) = e member = Set.member notMember = Set.notMember union = Set.union difference = Set.difference intersection = Set.intersection instance (Eq e, Hashable e) => Container (HashSet.HashSet e) where type ContainerKey (HashSet.HashSet e) = e member = HashSet.member notMember e = not . HashSet.member e union = HashSet.union difference = HashSet.difference intersection = HashSet.intersection instance Container IntSet.IntSet where type ContainerKey IntSet.IntSet = Int member = IntSet.member notMember = IntSet.notMember union = IntSet.union difference = IntSet.difference intersection = IntSet.intersection instance Ord k => Container [(k, v)] where type ContainerKey [(k, v)] = k member k = List.any ((== k) . fst) notMember k = not . member k union = List.unionBy ((==) `on` fst) x `difference` y = Map.toList (Map.fromList x `Map.difference` Map.fromList y) intersection = List.intersectBy ((==) `on` fst) class (MonoTraversable m, Container m) => IsMap m where -- | Using just @Element@ can lead to very confusing error messages. type MapValue m lookup :: ContainerKey m -> m -> Maybe (MapValue m) insertMap :: ContainerKey m -> MapValue m -> m -> m deleteMap :: ContainerKey m -> m -> m singletonMap :: ContainerKey m -> MapValue m -> m mapFromList :: [(ContainerKey m, MapValue m)] -> m mapToList :: m -> [(ContainerKey m, MapValue m)] instance Ord k => IsMap (Map.Map k v) where type MapValue (Map.Map k v) = v lookup = Map.lookup insertMap = Map.insert deleteMap = Map.delete singletonMap = Map.singleton mapFromList = Map.fromList mapToList = Map.toList instance (Eq k, Hashable k) => IsMap (HashMap.HashMap k v) where type MapValue (HashMap.HashMap k v) = v lookup = HashMap.lookup insertMap = HashMap.insert deleteMap = HashMap.delete singletonMap = HashMap.singleton mapFromList = HashMap.fromList mapToList = HashMap.toList instance IsMap (IntMap.IntMap v) where type MapValue (IntMap.IntMap v) = v lookup = IntMap.lookup insertMap = IntMap.insert deleteMap = IntMap.delete singletonMap = IntMap.singleton mapFromList = IntMap.fromList mapToList = IntMap.toList instance Ord k => IsMap [(k, v)] where type MapValue [(k, v)] = v lookup = List.lookup insertMap k v = ((k, v):) . deleteMap k deleteMap k = List.filter ((/= k) . fst) singletonMap k v = [(k, v)] mapFromList = id mapToList = id class (Container s, Element s ~ ContainerKey s) => IsSet s where insertSet :: Element s -> s -> s deleteSet :: Element s -> s -> s singletonSet :: Element s -> s setFromList :: [Element s] -> s setToList :: s -> [Element s] instance Ord e => IsSet (Set.Set e) where insertSet = Set.insert deleteSet = Set.delete singletonSet = Set.singleton setFromList = Set.fromList setToList = Set.toList instance (Eq e, Hashable e) => IsSet (HashSet.HashSet e) where insertSet = HashSet.insert deleteSet = HashSet.delete singletonSet = HashSet.singleton setFromList = HashSet.fromList setToList = HashSet.toList instance IsSet IntSet.IntSet where insertSet = IntSet.insert deleteSet = IntSet.delete singletonSet = IntSet.singleton setFromList = IntSet.fromList setToList = IntSet.toList
moonKimura/mono-traversable-0.1.0.0
src/Data/Containers.hs
Haskell
mit
5,148
module FSM ( FSM(..), mapTransitions, mapToFunc, accepts ) where import State (Token(..), State(..), TransitionFunction(..), Transition(..), TransitionMap) import Data.Set as Set (Set, elems, member) import Data.Map as Map (Map, (!), empty, insert, singleton, member) data FSM = FSM {states :: Set State, state0 :: State, accepting :: Set State, transitionFunction :: TransitionFunction, alphabet :: Set Token} -- Turns a set describing some transitions into a map of transitions mapTransitions :: Set Transition -> TransitionMap mapTransitions set = foldr addTransition Map.empty $ elems set where addTransition :: Transition -> Map State (Map Token State) -> Map State (Map Token State) addTransition (a, t, b) map = map' where map' = if a `Map.member` map then Map.insert a (Map.insert t b (map ! a)) map else Map.insert a (Map.singleton t b) map -- Turns a 2-nested map into a 2-arity function mapToFunc :: (Ord a, Ord b) => Map a (Map b c) -> (a -> b -> c) mapToFunc m a b = (m ! a) ! b accepts :: FSM -> [Token] -> Bool fsm `accepts` string = accepts' fsm (state0 fsm) string accepts' :: FSM -> State -> [Token] -> Bool accepts' fsm state [] = state `Set.member` (accepting fsm) accepts' fsm state (t:tt) = accepts' fsm state' tt where state' = transitionFunction fsm state t
wyager/NDFSMtoFSM
FSM.hs
Haskell
mit
1,310
-- Copyright 2013 Matthew Spellings -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- http://www.apache.org/licenses/LICENSE-2.0 -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. import Control.Applicative import Control.Monad import Data.Array.Accelerate as A import Data.Map as M import Data.Monoid import Data.Text.Lazy.IO (hPutStr) import Data.Text.Lazy.Builder (toLazyText) import System.Environment import System.IO (FilePath(..), IOMode(..), Handle(..), openFile, hFlush, hClose) import System.Random (randomRs, mkStdGen) import Data.Array.Accelerate.HasdyContrib as HC import Hasdy.Types import Hasdy.Prop import Hasdy.Prop.Bundle import Hasdy.Neighbor.Slow as Slow import Hasdy.Integrate.Leapfrog import Hasdy.Integrate.VelVerlet import Hasdy.Potentials.LJ import Hasdy.Potentials.Sigmoidal import Hasdy.Spatial import Hasdy.Vectors import Hasdy.Dump.Pos import Hasdy.Thermo import Hasdy.Thermostats import Hasdy.Utils import Hasdy.Utils.Sort import Hasdy.Neighbor.Fast as Fast import Data.Array.Accelerate.CUDA --import Data.Array.Accelerate.Interpreter -- global constants scale = 1.5 n = 8 v0 = 1e-1 box = A.constant box' box' = scale3' scale . pure3' $ Prelude.fromIntegral n rbuf = constToSingleProp 3 cellR = constToSingleProp 6 lj = LJ (unit 1) (unit 1) :: LJ Float sig = Sigmoidal (unit 1) (unit 1) (unit 3) :: Sigmoidal Float dt = constToSingleProp 0.005 typ = ParticleType 0 state = usePP typ <. newPP <. useNList typ <. newNList <. -- neighbor list + old positions usePP typ <. newPP <. -- accelerations usePP typ <. newPP <. -- velocities usePP typ <. newPP -- positions -- | a single timestep in terms of 'PerParticleProp's timestep::NList->(PerParticleProp (Vec3' Float), PerParticleProp (Vec3' Float), PerParticleProp (Vec3' Float))-> (PerParticleProp (Vec3' Float), PerParticleProp (Vec3' Float), PerParticleProp (Vec3' Float)) timestep nlist (pos, vel, acc) = velVerlet dt masses forceCalc (pos', vel', acc) where pos' = perParticleMap (wrapBox box id) pos vel' = rescale (constToSingleProp 1) masses vel force = makeAbsolute . wrapBox box . cutoff (A.constant (0, 0, 0)) (3**2) $ ljForce lj forceCalc p = Fast.foldNeighbors force plus3 (A.constant (0, 0, 0)) nlist typ typ p p masses = singleToParticleProp (constToSingleProp 1) pos -- | a group of timesteps glued together under accelerate's run1; also -- rebuilds neighbor lists if necessary runTimesteps = runBLens run1 (canal1 state . liftAccs $ f) state state where f = Prelude.foldr1 (>->) . Prelude.take 10 . Prelude.repeat $ unliftAccs . bridge1 state $ accTimestep accTimestep bundIn = bundOut where ((((((), positions), velocities), accelerations), nlist), oldPositions) = bundleProps bundIn (rebuilt, nlist', oldIdx) = maybeRebuildNList True cellR rbuf (constToSingleProp box') oldPositions positions nlist positions' = maybeGatherPerParticle rebuilt oldIdx positions velocities' = maybeGatherPerParticle rebuilt oldIdx velocities accelerations' = maybeGatherPerParticle rebuilt oldIdx accelerations oldPositions' = maybeGatherPerParticle rebuilt oldIdx positions (positions'', velocities'', accelerations'') = Prelude.iterate (timestep nlist') (positions', velocities', accelerations') Prelude.!! 10 :: (PerParticleProp (Vec3' Float), PerParticleProp (Vec3' Float), PerParticleProp (Vec3' Float)) bundOut = Bundle ((((((), positions''), velocities''), accelerations''), nlist'), oldPositions') (A.use ()) -- | several timesteps + dumping to file -- dumpTimesteps::Handle->(PerParticleProp' (Vec3' Float), PerParticleProp' (Vec3' Float), PerParticleProp' (Vec3' Float))-> -- IO (PerParticleProp' (Vec3' Float), PerParticleProp' (Vec3' Float), PerParticleProp' (Vec3' Float)) dumpTimesteps handle (positions, velocities, accelerations, nlist, oldPositions) = do let posvelaccIn = Bundle ((((((), positions), velocities), accelerations), nlist), oldPositions) () ((((((), positions''), velocities''), accelerations''), nlist''), oldPositions'') = bundleProps . runTimesteps $ posvelaccIn Data.Text.Lazy.IO.hPutStr handle $ toLazyText . posFrame box' $ unPerParticleProp' positions'' M.! typ hFlush handle return (positions'', velocities'', accelerations'', nlist'', oldPositions'') -- | run n groups of timesteps multitimestep n handle (pos, vel, acc, nl, oldP) = do (pos', vel', acc', nl', oldP') <- dumpTimesteps handle (pos, vel, acc, nl, oldP) if n <= 0 then return (pos, vel, acc, nl, oldP) else multitimestep (n-1) handle (pos', vel', acc', nl', oldP') main = do let grid idx = r `minus3` center where r = scale3 (A.constant scale) $ A.lift (A.fromIntegral x, A.fromIntegral y, A.fromIntegral z) (Z:.x:.y:.z) = A.unlift idx center = scale3 0.5 box positions' = run . A.flatten $ A.generate (A.constant $ (Z:.n:.n:.n) :: Exp DIM3) grid positions = PerParticleProp $ M.fromList [(ParticleType 0, use positions')] triplify (x:y:z:rest) = (x, y, z):(triplify rest) velocities' = A.fromList (Z:.(n*n*n)) . triplify $ randomRs (negate v0, v0) (mkStdGen 5337) :: Vector (Vec3' Float) velocities = PerParticleProp $ M.fromList [(ParticleType 0, use velocities')] :: PerParticleProp (Vec3' Float) accelerations = perParticleMap (scale3 0) velocities vel' = rescale (constToSingleProp 1e-3) masses velocities masses = singleToParticleProp (constToSingleProp 1) positions (n':_) <- getArgs handle <- openFile "dump.pos" WriteMode let n = read n'::Int positions' = runPerParticle run positions velocities' = runPerParticle run velocities accelerations' = runPerParticle run accelerations emptyIdx = A.fromList (Z:.0) [] :: A.Vector Int nlist0 = NList' . M.fromList $ [(typ, SNList' emptyIdx emptyIdx emptyIdx)] initState = (positions', velocities', accelerations', nlist0, accelerations') (positions, velocities, accelerations, _, _) <- multitimestep n handle initState hClose handle return ()
klarh/hasdy
test/test.hs
Haskell
apache-2.0
6,548
{-# LANGUAGE OverloadedStrings #-} module View.Index (render) where import Control.Monad (forM_) import Model.Definition import Text.Blaze.Html5.Attributes (href, class_) import Text.Blaze.Html.Renderer.Text import Data.Monoid((<>)) import View.Header import qualified Data.Text.Lazy as D import qualified Text.Blaze.Html5 as H -- $setup -- >>> :set -XOverloadedStrings -- >>> import Data.List(isPrefixOf, isSuffixOf) -- >>> import Test.QuickCheck -- >>> instance Arbitrary Definition where arbitrary = do a <- arbitrary; b <- arbitrary; return (Definition (D.pack a) (D.pack b)) -- | -- -- >>> render [] -- "<!DOCTYPE HTML>\n<html><head><title>Pirate Gold</title><link rel=\"stylesheet\" href=\"css/style.css\"></head><body class=\"main\"><div class=\"head\"><h1>Ahoy! Welcome to Pirate Gold.</h1><h2>&#39;ere be some golden terms ye ought to be using me hearties...</h2></div><p>There are no definitions yet.</p><p><a href=\"/add\">Add definition</a></p></body></html>" -- -- >>> render [Definition "abc" "def"] -- "<!DOCTYPE HTML>\n<html><head><title>Pirate Gold</title><link rel=\"stylesheet\" href=\"css/style.css\"></head><body class=\"main\"><div class=\"head\"><h1>Ahoy! Welcome to Pirate Gold.</h1><h2>&#39;ere be some golden terms ye ought to be using me hearties...</h2></div><ul><li><span class=\"phrase\">abc</span>: <span class=\"meaning\">def</span></li></ul><p><a href=\"/add\">Add definition</a></p></body></html>" -- -- >>> render [Definition "abc" "def", Definition "abc&def" "ghi&jkl\"mno"] -- "<!DOCTYPE HTML>\n<html><head><title>Pirate Gold</title><link rel=\"stylesheet\" href=\"css/style.css\"></head><body class=\"main\"><div class=\"head\"><h1>Ahoy! Welcome to Pirate Gold.</h1><h2>&#39;ere be some golden terms ye ought to be using me hearties...</h2></div><ul><li><span class=\"phrase\">abc</span>: <span class=\"meaning\">def</span></li><li><span class=\"phrase\">abc&amp;def</span>: <span class=\"meaning\">ghi&amp;jkl&quot;mno</span></li></ul><p><a href=\"/add\">Add definition</a></p></body></html>" -- -- prop> let r = D.unpack (render s) in "<!DOCTYPE HTML>\n<html><head><title>Pirate Gold</title><link rel=\"stylesheet\" href=\"css/style.css\"></head><body class=\"main\"><div class=\"head\"><h1>Ahoy! Welcome to Pirate Gold.</h1><h2>&#39;ere be some golden terms ye ought to be using me hearties...</h2>" `isPrefixOf` r -- -- prop> let r = D.unpack (render s) in "<p><a href=\"/add\">Add definition</a></p></body></html>" `isSuffixOf` r render :: [Definition] -> D.Text render definitions = renderHtml . H.docTypeHtml $ do header H.body H.! class_ "main" $ do H.div H.! class_ "head" $ do H.h1 "Ahoy! Welcome to Pirate Gold." H.h2 "'ere be some golden terms ye ought to be using me hearties..." if null definitions then H.p "There are no definitions yet." else H.ul . forM_ definitions $ (\def -> H.li $ do (H.span H.! class_ "phrase") (H.toHtml (phrase def)) <> ": " (H.span H.! class_ "meaning") (H.toHtml (meaning def))) H.p ((H.a H.! href "/add") "Add definition")
codemiller/fp-in-the-cloud
src/View/Index.hs
Haskell
apache-2.0
3,131
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoMonomorphismRestriction #-} -- * Demonstrating `non-compositional', context-sensitive processing -- * The final style -- * Flatten the additions module FlatF where import Intro2 hiding (main) import PushNegF as Neg hiding (main,Ctx) -- We are going to write flata as an interpreter. -- After all, that's all we can do with an expression in a final form. -- * The nested pattern-matching establishes a context: -- * flata :: Exp -> Exp -- * flata e@Lit{} = e -- * flata e@Neg{} = e -- * flata (Add (Add e1 e2) e3) = flata (Add e1 (Add e2 e3)) -- * flata (Add e1 e2) = Add e1 (flata e2) -- The processing is slightly different from push_neg, because we repeatedly -- process the transformed expression (the last-but one clause) -- The nested pattern-match again betrays the context-sensitivity. -- The context in question is expression being the left child of addition. -- * // -- So, we define the context -- (LCA e) means that the context (Add [] e), being the left immediate -- child of addition whose right child is e. NonLCA is any other context. data Ctx e = LCA e | NonLCA -- On other words, LCA e3 represents the context of adding e3 _to the right_ of -- the expression in focus. instance ExpSYM repr => ExpSYM (Ctx repr -> repr) where lit n NonLCA = lit n lit n (LCA e) = add (lit n) e neg e NonLCA = neg (e NonLCA) neg e (LCA e3) = add (neg (e NonLCA)) e3 -- assume only lits are negated add e1 e2 ctx = e1 (LCA (e2 ctx)) -- The last clause expresses the reassociation-to-the-right -- * C[Add e1 e2] -> Add e1 C[e2] -- Recall that after the negations are pushed down, expressions are -- described by the following grammar -- * e ::= factor | add e e -- * factor ::= int | neg int -- That is, C ::= [] | Add [] e -- Keep in mind the processing is done bottom-up! -- A general approach is to use continuations (or monads), -- or to encode the Ctx with zippers -- (the defunctionalized continuations, in the present -- case). -- The Ctx data type above is tuned to the present example, -- keeping only the data we need (e.g., we aren't interested -- in the context of Neg or of the addition on the left, -- and so we don't represent these cases in Ctx). -- Exercise: there are several clauses where lit, neg, or add -- appears on both sides of the definition. -- In which clause add is being used recursively? -- The `interpreter' for flattening flata :: (Ctx repr -> repr) -> repr flata e = e NonLCA --norm :: (Neg.Ctx -> Ctx c -> c) -> c norm = flata . Neg.push_neg -- Use our sample term -- We make it a bit complex tf3 = (add tf1 (neg (neg tf1))) tf3_view = view tf3 -- "((8 + (-(1 + 2))) + (-(-(8 + (-(1 + 2))))))" tf3_eval = eval tf3 -- 10 -- The normalized expression can be evaluated with any interpreter tf3_norm = norm tf3 tf3_norm_view = view tf3_norm -- "(8 + ((-1) + ((-2) + (8 + ((-1) + (-2))))))" -- The result of the standard evaluation (the `meaning') is preserved tf3_norm_eval = eval tf3_norm -- 10 tf4 = add t (neg t) where t = (add (add (lit 1) (lit 2)) (lit 3)) tf4_view = view tf4 -- "(((1 + 2) + 3) + (-((1 + 2) + 3)))" tf4_eval = eval tf4 -- 0 tf4_norm = norm tf4 tf4_norm_view = view tf4_norm -- "(1 + (2 + (3 + ((-1) + ((-2) + (-3))))))" -- The result of the standard evaluation (the `meaning') is preserved tf4_norm_eval = eval tf4_norm -- 0 main = do print tf3_view print tf3_eval print tf3_norm_view print tf3_norm_eval if tf3_eval == tf3_norm_eval then return () else error "Normalization" -- normalizing a normal form does not change it if (view . norm $ tf3_norm) == tf3_norm_view then return () else error "Normalization" print tf4_view print tf4_eval print tf4_norm_view print tf4_norm_eval if tf4_eval == tf4_norm_eval then return () else error "Normalization" if (view . norm $ tf4_norm) == tf4_norm_view then return () else error "Normalization"
mjhopkins/ttfi
src/haskell/FlatF.hs
Haskell
apache-2.0
4,020
{-# Language RecordWildCards #-} -- | -- Module : GRN.Sparse -- Copyright : (c) 2011 Jason Knight -- License : BSD3 -- -- Maintainer : jason@jasonknight.us -- Stability : experimental -- Portability : portable -- -- Provides sparse matrix capabilities for an attempt at speeding up the -- simulation of the Markov Chain. -- module GRN.Sparse ( calcSSAsDOK , simulateDOKUnif , simulateDOK , normalizeSSD , simulateCSC , kmapToDOK , ssdToSSA , weightedExpansion , getNSamples , module GRN.SparseLib ) where import GRN.Types import GRN.SparseLib import GRN.Utils import GRN.StateTransition import qualified Data.Vector as V import qualified Data.Vector.Generic as G import qualified Data.Vector.Unboxed as U import Data.Vector.Strategies import Control.Monad import Data.List import Data.Bits import Data.Ord (comparing) import qualified Data.Map as M import System.Console.ParseArgs import System.Random.MWC (withSystemRandom, initialize, uniformVector) import Data.Word (Word32) simulateDOKUnif :: Args String -> DOK -> SSD simulateDOKUnif args d@(DOK (m,n) _) = simulateDOK args d (U.replicate n (1.0/(fromIntegral n))) simulateDOK :: Args String -> DOK -> SSD -> SSD simulateDOK args d@(DOK (m,n) _) start = regSim (n1+n2) start where n1 = getRequiredArg args "n1" :: Int n2 = getRequiredArg args "n2" :: Int p = getRequiredArg args "perturb" csc = dokToCSC d regSim 0 v = v regSim n v | p < 1e-15 = regSim (n-1) (multiplyCSCVM csc v) | otherwise = regSim (n-1) (perturb p . multiplyCSCVM csc $ v) -- | Perturb an SSD by a small amount perturb :: Double -> SSD -> SSD perturb p sd = snd . normalizeSSD $ added where added = U.map (+p) sd normalizeSSD :: SSD -> (Double,SSA) normalizeSSD ssd = let fac=U.sum ssd in (fac, U.map (*(1/fac)) ssd) simulateCSC :: Args String -> CSC -> SSD -> SSD simulateCSC args csc start = regSim (n1+n2) start where n1 = getRequiredArg args "n1" :: Int n2 = getRequiredArg args "n2" :: Int avg = getRequiredArg args "avg" :: Int --norm xv = let fac = (U.sum xv) in (fac,U.map (*(1/fac)) xv) regSim 0 v = v regSim n v = regSim (n-1) (multiplyCSCVM csc v) kmapToDOK :: KmapSet -> Int -> DOK kmapToDOK kset x = DOK (nStates,nStates) (M.fromList edges) where genes = M.keys kset nGenes = length genes nStates = 2^nGenes intStates = [0..nStates-1] permedStates = map (dec2bin nGenes) intStates edges = concatMap genEdges permedStates genEdges :: [Int] -> [((Int,Int),Double)] genEdges st = map (\(val,to)-> ((from,bin2dec to),val)) tos where from = bin2dec st tos = [(1.0,[])] >>= foldr (>=>) return (stateKmapLus x st genes kset) calcSSAsDOK :: Args String -> ParseData -> KmapSet -> GeneMC calcSSAsDOK args p ks = zipNames . allgenes . ssaVec . simVec $ seedList where n3 = getRequiredArg args "n3" -- Number of simruns n4 = getRequiredArg args "n4" -- Starting Seed pass n f = last.take n.iterate f -- Get a new randomized graph and simulate seedList = V.enumFromN (n4) (n3+n4) simVec :: V.Vector Int -> V.Vector SSD simVec xv = G.map (simulateDOKUnif args.kmapToDOK ks) xv `using` (parVector 2) -- Now get the SSAs of these ssaVec :: V.Vector SSD -> V.Vector SSA ssaVec xv = G.map ssdToSSA xv `using` (parVector 2) -- Basically a transpose, to get a list of SSA for each gene instead of -- each simulation run allgenes :: V.Vector SSA -> V.Vector (U.Vector Double) allgenes ssas = G.map (\x-> G.convert $ G.map (G.!x) ssas) (V.fromList [0..(length $ M.keys p)-1]) zipNames :: V.Vector (U.Vector Double) -> M.Map Gene (U.Vector Double) zipNames xv = M.fromList $ zip (M.keys p) (G.toList xv) -- | Expands out all determistic networks for a given likelihood network. -- Number of networks grows superexponentially as (N+1)^(2^N) -- ie. for n={1-6}: 4, 81, 65536, 1.5e11 (100 billion), 8e24 (8 septillion), 1.2e54 (1.2 -- septendecillion)... weightedExpansion :: DOK -> V.Vector (Double, CSR) weightedExpansion dk@(DOK (m,n) _) = wtdlist where csr = toCSR dk cols = csrcolIndices csr rows = csrrowIndices csr vals = csrValues csr perrow = (rows U.! 1) - (U.head rows) cartesian = G.sequence . chunks perrow . G.convert $ cols cartvals = G.map G.product . G.sequence . chunks perrow . G.convert $ vals newnnz = G.length . G.head $ cartesian newrows = U.enumFromN 0 (newnnz+1) --NOTE the +1 here newvals = U.replicate newnnz 1.0 wtdlist = V.zip cartvals (G.map (\x -> CSR (m,n) newvals (G.convert x) newrows) cartesian) getNSamples :: Int -> DOK -> IO (V.Vector (Double,CSR)) getNSamples samps dk@(DOK (m,n) _) = do let csr = toCSR dk cols = csrcolIndices csr rows = csrrowIndices csr vals = csrValues csr perrow = (rows U.! 1) - (U.head rows) wtdvals = G.convert $ G.zip vals cols rowchunks = chunks perrow $ wtdvals newnnz = G.length rowchunks newrows = U.enumFromN 0 (newnnz+1) --NOTE +1 here newvals = U.replicate newnnz 1.0 go gen = do unifs <- uniformVector gen m :: IO (V.Vector Double) let pickedcols = V.zipWith pick unifs rowchunks weight = G.product . fst . G.unzip $ pickedcols network = CSR (m,n) newvals (G.convert . snd . G.unzip $ pickedcols) newrows return (weight, network) pick :: Double -> V.Vector (Double,Int) -> (Double,Int) pick t vec | G.null vec = error "Pick used with empty list" | t <= w = (w,x) | otherwise = pick (t-w) xs where (w,x) = G.head vec xs = G.tail vec -- Now ,get a list of generators, one for each sample gen <- withSystemRandom (\gen -> initialize =<< (uniformVector gen 256 :: IO (U.Vector Word32))) gens <- V.replicateM samps (initialize =<< (uniformVector gen 256 :: IO (U.Vector Word32))) G.mapM go gens ssdToSSA :: SSD -> SSA ssdToSSA ssd = U.reverse $ U.generate ngenes count where n = U.length ssd ngenes = round $ logBase 2 (fromIntegral n) count i = U.sum $ U.ifilter (\ind _-> testBit ind i) ssd
binarybana/grn-pathways
GRN/Sparse.hs
Haskell
bsd-2-clause
6,308
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QTextLength.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:35 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QTextLength ( QTextLengthType, eVariableLength, eFixedLength, ePercentageLength ) where import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CQTextLengthType a = CQTextLengthType a type QTextLengthType = QEnum(CQTextLengthType Int) ieQTextLengthType :: Int -> QTextLengthType ieQTextLengthType x = QEnum (CQTextLengthType x) instance QEnumC (CQTextLengthType Int) where qEnum_toInt (QEnum (CQTextLengthType x)) = x qEnum_fromInt x = QEnum (CQTextLengthType x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> QTextLengthType -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eVariableLength :: QTextLengthType eVariableLength = ieQTextLengthType $ 0 eFixedLength :: QTextLengthType eFixedLength = ieQTextLengthType $ 1 ePercentageLength :: QTextLengthType ePercentageLength = ieQTextLengthType $ 2
uduki/hsQt
Qtc/Enums/Gui/QTextLength.hs
Haskell
bsd-2-clause
2,552
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Opaleye.TF.BaseTypes where import qualified Data.Aeson as Aeson import Data.ByteString (ByteString) import Data.Fixed (E0, E1, E2, E3, E6, E9, Fixed) import Data.Int (Int32, Int64) import Data.Text import Data.Time (LocalTime, UTCTime) import Data.UUID (UUID) import GHC.TypeLits (Nat) import qualified Opaleye.Internal.Column as Op import qualified Opaleye.PGTypes as Op import Opaleye.TF.Col import Opaleye.TF.Expr import Opaleye.TF.Interpretation import Opaleye.TF.Lit import Opaleye.TF.Nullable import Opaleye.TF.Machinery data WithTimeZone = WithTimeZone | WithoutTimeZone deriving (Eq,Ord,Read,Show,Enum,Bounded) -- | The universe of base types known about by PostgreSQL. data PGType = PGBigint -- ^ @bigint@ | PGBigserial -- ^ @bigserial@ | PGBit (Maybe Nat) -- ^ @bit [ (n) ]@ | PGBitVarying (Maybe Nat) -- ^ @bit varying [ (n) ]@ | PGBoolean -- ^ @boolean@ | PGBox -- ^ @box@ | PGBytea -- ^ @bytea@ | PGCharacter (Maybe Nat) -- ^ @character [ (n) ]@ | PGVarchar Nat -- ^ @character varying (n)@ (unbound @character varying@ is 'PGText') | PGCidr -- ^ @cidr@ | PGCircle -- ^ @circle@ | PGDate -- ^ @date@ | PGDouble -- ^ @double precision@ | PGInet -- ^ @inet@ | PGInteger -- ^ @integer@ | PGInterval -- ^ @interval@. There is no ability to specify the precision or fields, if you require this please open a feature request. | PGJSON -- ^ @json@ | PGJSONB -- ^ @jsonb@ | PGLine -- ^ @line@ | PGLseg -- ^ @lseg@ | PGMacaddr -- ^ @macaddr@ | PGMoney -- ^ @money@ | PGNumeric Nat Nat -- ^ @numeric(p,s)@ | PGPath -- ^ @path@ | PGPGLSN -- ^ @pg_lsn@ | PGPoint -- ^ @point@ | PGPolygon -- ^ @polygon@ | PGReal -- ^ @real@ | PGSmallint -- ^ @smallint@ | PGSmallserial -- ^ @smallserial@ | PGSerial -- ^ @serial@ | PGText -- ^ @text@ and @character varying@ | PGTime WithTimeZone -- ^ @time with/without time zone@ | PGTimestamp WithTimeZone -- ^ @timestamp with/without time zone@ | PGTSQuery -- ^ @tsquery@ | PGTSVector -- ^ @tsvector@ | PGTXIDSnapshot -- ^ @txid_sapnshot@ | PGUUID -- ^ @uuid@ | PGXML -- ^ @xml@ type instance Col (Expr s) (t :: PGType) = Expr s t type instance Col (Compose (Expr s) 'Nullable) (a :: PGType) = Expr s ('Nullable a) type instance Col (Compose (Expr s) 'NotNullable) (a :: PGType) = Expr s a type instance Col Interpret 'PGBigint = Int64 type instance Col Interpret 'PGBoolean = Bool type instance Col Interpret 'PGInteger = Int32 type instance Col Interpret 'PGReal = Float type instance Col Interpret 'PGText = Text type instance Col Interpret ('PGTimestamp 'WithoutTimeZone) = LocalTime type instance Col Interpret ('PGTimestamp 'WithTimeZone) = UTCTime type instance Col Interpret 'PGDouble = Double type instance Col Interpret ('PGNumeric p 0) = Fixed E0 type instance Col Interpret ('PGNumeric p 1) = Fixed E1 type instance Col Interpret ('PGNumeric p 2) = Fixed E2 type instance Col Interpret ('PGNumeric p 3) = Fixed E3 type instance Col Interpret ('PGNumeric p 6) = Fixed E6 type instance Col Interpret ('PGNumeric p 9) = Fixed E9 type instance Col Interpret 'PGBytea = ByteString type instance Col Interpret ('PGCharacter len) = Text type instance Col Interpret ('PGVarchar len) = Text type instance Col Interpret 'PGJSON = Aeson.Value type instance Col Interpret 'PGJSONB = Aeson.Value type instance Col Interpret 'PGUUID = UUID instance Lit 'PGBigint where lit = Expr . Op.unColumn . Op.pgInt8 instance Lit 'PGBoolean where lit = Expr . Op.unColumn . Op.pgBool instance Lit 'PGInteger where lit = Expr . Op.unColumn . Op.pgInt4 . fromIntegral instance Lit 'PGReal where lit = Expr . Op.unColumn . Op.pgDouble . realToFrac instance Lit 'PGText where lit = Expr . Op.unColumn . Op.pgStrictText instance Lit ('PGCharacter n) where lit = Expr . Op.unColumn . Op.pgStrictText instance Lit ('PGVarchar n) where lit = Expr . Op.unColumn . Op.pgStrictText instance Lit ('PGTimestamp 'WithoutTimeZone) where lit = Expr . Op.unColumn . Op.pgLocalTime instance Lit ('PGTimestamp 'WithTimeZone) where lit = Expr . Op.unColumn . Op.pgUTCTime instance Lit 'PGDouble where lit = Expr . Op.unColumn . Op.pgDouble instance Lit 'PGJSON where lit = Expr . Op.unColumn . Op.pgValueJSON instance Lit 'PGJSONB where lit = Expr . Op.unColumn . Op.pgValueJSON instance Lit 'PGUUID where lit = Expr . Op.unColumn . Op.pgUUID pgNow :: Expr s ('PGTimestamp 'WithTimeZone) pgNow = mapExpr Cast (lit (pack "now") :: Expr s 'PGText)
ocharles/opaleye-tf
src/Opaleye/TF/BaseTypes.hs
Haskell
bsd-3-clause
5,425
module Main where import Test.Framework (defaultMain) import Circular.Syntax.Concrete.Tests main = defaultMain Main.tests tests = [ Circular.Syntax.Concrete.Tests.tests ]
Toxaris/circular
src/tests.hs
Haskell
bsd-3-clause
189
------------------------------------------------------------------------------ -- | -- Module : Data.TokyoDystopia.IDB -- Copyright : 8c6794b6 <8c6794b6@gmail.com> -- License : BSD3 -- Maintainer : 8c6794b6 -- Stability : experimental -- Portability : non-portable -- -- Haskell binding for tokyodystopia TCIDB interface. -- module Database.TokyoDystopia.IDB ( -- * Type IDB() -- * Basic functions , close , copy , del , ecode , fsiz , get , iterinit , iternext , new , open , optimize , out , path , put , rnum , search , search2 , setcache , setfwmmax , sync , tune , vanish -- * Advanced functions , setdbgfd , getdbgfd , memsync , inode , mtime , opts , setsynccb , setexopts ) where import Data.ByteString (ByteString) import Data.Int (Int64) import Data.Time (UTCTime) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Foreign (Ptr, maybePeek) import Database.TokyoCabinet.Storable (Storable) import Database.TokyoCabinet (ECODE(..)) import Database.TokyoDystopia.Internal (bitOr, toTuningOptions) import Database.TokyoDystopia.Types ( OpenMode(..) , GetMode(..) , TuningOption(..) ) import qualified Data.ByteString.Char8 as C8 import qualified Foreign.C.String as CS import qualified Database.TokyoCabinet.Error as TCE import qualified Database.TokyoCabinet.Storable as TCS import qualified Database.TokyoDystopia.FFI.IDB as FI import qualified Database.TokyoDystopia.Internal as I -- | Wrapper for TCIDB. newtype IDB = IDB { unIDB :: Ptr FI.TCIDB } -- | Creates new IDB. new :: IO IDB new = IDB `fmap` FI.c_new -- | Open database from given path and open modes. open :: IDB -> FilePath -> [OpenMode] -> IO Bool open = I.mkOpen FI.c_open unIDB (FI.unOpenMode . f) where f OREADER = FI.omReader f OWRITER = FI.omWriter f OCREAT = FI.omCreat f OTRUNC = FI.omTrunc f ONOLCK = FI.omNolck f OLCKNB = FI.omLcknb -- | Closes database close :: IDB -> IO Bool close = FI.c_close . unIDB -- | Put data with given key and value. put :: (Storable k) => IDB -> k -> ByteString -> IO Bool put db k v = C8.useAsCString v (\str -> FI.c_put (unIDB db) (TCS.toInt64 k) str) -- | Get data with given key. get :: (Storable k, Storable v) => IDB -> k -> IO (Maybe v) get db i = do val <- FI.c_get (unIDB db) (TCS.toInt64 i) str <- maybePeek CS.peekCString val return $ fmap TCS.fromString str -- | Search with GetMode options. search :: IDB -> String -> [GetMode] -> IO [Int64] search = I.mkSearch FI.c_search unIDB g where g = bitOr . map (FI.unGetMode . f) f GMSUBSTR = FI.gmSubstr f GMPREFIX = FI.gmPrefix f GMSUFFIX = FI.gmSuffix f GMFULL = FI.gmFull f GMTOKEN = FI.gmToken f GMTOKPRE = FI.gmTokPre f GMTOKSUF = FI.gmTokSuf -- | Search with given query and returns list of id keys. search2 :: IDB -> String -> IO [Int64] search2 = I.mkSearch2 FI.c_search2 unIDB -- | Delete database, from memory. del :: IDB -> IO () del = FI.c_del . unIDB -- | Get the last happened error code of an indexed database object. ecode :: IDB -> IO ECODE ecode db = fmap TCE.cintToError (FI.c_ecode $ unIDB db) -- | Tune the database. Must be used before opening database. tune :: IDB -> Int64 -> Int64 -> Int64 -> [TuningOption] -> IO Bool tune db ernum etnum iusiz os = FI.c_tune (unIDB db) ernum etnum iusiz os' where os' = fromIntegral $ bitOr $ map (FI.unTuningOption . f) os f TLARGE = FI.toLarge f TDEFLATE = FI.toDeflate f TBZIP = FI.toBzip f TTCBS = FI.toTcbs f _ = FI.TuningOption 0 -- | Set caching parameters. Must be used before opening database. setcache :: IDB -> Int64 -> Int -> IO Bool setcache db icsiz lcnum = FI.c_setcache (unIDB db) icsiz (fromIntegral lcnum) -- | Set maximum number of forward matching expansion. Must be used before -- opening database. setfwmmax :: IDB -> Int -> IO Bool setfwmmax db fwmmax = FI.c_setfwmmax (unIDB db) (fromIntegral fwmmax) -- | Initialize the iterator. iterinit :: IDB -> IO Bool iterinit = FI.c_iterinit . unIDB -- | Get next key for iterator iternext :: IDB -> IO Int64 iternext = FI.c_iternext . unIDB -- | Sync database. sync :: IDB -> IO Bool sync = FI.c_sync . unIDB -- | Optimize database. optimize :: IDB -> IO Bool optimize = FI.c_optimize . unIDB -- | Removes record with given key out :: (Storable k) => IDB -> k -> IO Bool out db key = FI.c_out (unIDB db) (TCS.toInt64 key) -- | Delete the database from disk. vanish :: IDB -> IO Bool vanish = FI.c_vanish . unIDB -- | Copy the database to given filepath. copy :: IDB -> FilePath -> IO Bool copy db file = FI.c_copy (unIDB db) =<< CS.newCString file -- | Get filepath of the database path :: IDB -> IO FilePath path db = FI.c_path (unIDB db) >>= CS.peekCString -- | Get number of records in database. rnum :: IDB -> IO Int64 rnum = FI.c_rnum . unIDB -- | Get filesize of the database. fsiz :: IDB -> IO Int64 fsiz = FI.c_fsiz . unIDB -- -- Advanced features -- -- | Set file descriptor for debugging output. setdbgfd :: IDB -> Int -> IO () setdbgfd db dbg = FI.c_setdbgfd (unIDB db) (fromIntegral dbg) -- | Get file descriptor for debugging output getdbgfd :: IDB -> IO Int getdbgfd = fmap fromIntegral . FI.c_dbgfd . unIDB -- | Synchronize updating contents on memory of an indexed database object memsync :: IDB -> Int -> IO Bool memsync db level = FI.c_memsync (unIDB db) (fromIntegral level) -- | Get the inode number of the database dictionary of an indexed database -- object. inode :: IDB -> IO Int64 inode = FI.c_inode . unIDB -- | Get the modificatoin time of the database directory of an indexed database -- object. mtime :: IDB -> IO UTCTime mtime = fmap (posixSecondsToUTCTime . realToFrac) . FI.c_mtime . unIDB -- | Get the options of an indexed database object. opts :: IDB -> IO [TuningOption] opts = fmap toTuningOptions . FI.c_opts . unIDB -- | Set the callback function for sync progression. setsynccb :: IDB -> (Int -> Int -> String -> IO Bool) -> IO Bool setsynccb db cb = do cb' <- FI.c_setsynccb_wrapper (\i1 i2 s -> do s' <- CS.peekCString s let i1' = fromIntegral i1 i2' = fromIntegral i2 cb i1' i2' s') FI.c_setsynccb (unIDB db) cb' -- | Set the expert options. setexopts :: IDB -> [FI.ExpertOption] -> IO () setexopts db os = FI.c_setexopts (unIDB db) . fromIntegral . sum $ map FI.unExpertOption os
8c6794b6/tokyodystopia-haskell
Database/TokyoDystopia/IDB.hs
Haskell
bsd-3-clause
6,697
{-# LANGUAGE ForeignFunctionInterface #-} ------------------------------------------------------------------------------- -- | -- Copyright : (c) 2015 Michael Carpenter -- License : BSD3 -- Maintainer : Michael Carpenter <oldmanmike.dev@gmail.com> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module Sound.Csound.Debugger ( csoundDebuggerInit, csoundDebuggerClean, --csoundSetInstrumentBreakpoint, --csoundRemoveInstrumentBreakpoint, csoundClearBreakpoints, --csoundSetBreakpointCallback, csoundDebuggerContinue, csoundDebugStop, --csoundDebugGetInstrument ) where import Control.Monad.IO.Class import Foreign import Foreign.Ptr import Foreign.C.Types foreign import ccall "csdebug.h csoundDebuggerInit" csoundDebuggerInit' :: Ptr () -> IO () foreign import ccall "csdebug.h csoundDebuggerClean" csoundDebuggerClean' :: Ptr () -> IO () --foreign import ccall "csdebug.h csoundSetInstrumentBreakpoint" csoundSetInstrumentBreakpoint' --foreign import ccall "csdebug.h csoundRemoveInstrumentBreakpoint" csoundRemoveInstrumentBreakpoint' foreign import ccall "csdebug.h csoundClearBreakpoints" csoundClearBreakpoints' :: Ptr () -> IO () --foreign import ccall "csdebug.h csoundSetBreakpointCallback" csoundSetBreakpointCallback' foreign import ccall "csdebug.h csoundDebugContinue" csoundDebugContinue' :: Ptr () -> IO () foreign import ccall "csdebug.h csoundDebugStop" csoundDebugStop' :: Ptr () -> IO () --foreign import ccall "csdebug.h csoundDebugGetInstrument" csoundDebugGetInstrument' csoundDebuggerInit :: MonadIO m => Ptr () -> m () csoundDebuggerInit csnd = liftIO (csoundDebuggerInit' csnd) csoundDebuggerClean :: MonadIO m => Ptr () -> m () csoundDebuggerClean csnd = liftIO (csoundDebuggerClean' csnd) --csoundSetInstrumentBreakpoint --csoundSetInstrumentBreakpoint --csoundRemoveInstrumentBreakpoint --csoundRemoveInstrumentBreakpoint csoundClearBreakpoints :: MonadIO m => Ptr () -> m () csoundClearBreakpoints csnd = liftIO (csoundClearBreakpoints' csnd) --csoundSetBreakpointCallback --csoundSetBreakpointCallback csoundDebuggerContinue :: MonadIO m => Ptr () -> m () csoundDebuggerContinue csnd = liftIO (csoundDebuggerContinue' csnd) csoundDebugStop :: MonadIO m => Ptr () -> m () csoundDebugStop csnd = liftIO (csoundDebugStop' csnd) --csoundDebugGetInstrument --csoundDebugGetInstrument
oldmanmike/CsoundRaw
src/Sound/Csound/Debugger.hs
Haskell
bsd-3-clause
2,460
module Main ( main ) where import Control.DeepSeq import Control.Exception import qualified Data.Map as Map import qualified Data.Set as Set import Distribution.Nixpkgs.Haskell.FromCabal.Configuration.GHC7102 import Distribution.Nixpkgs.License import Distribution.Nixpkgs.Meta import Internal.Lens import Test.Hspec main :: IO () main = do hspec $ do describe "DeepSeq instances work properly for" $ do it "License" $ mapM_ hitsBottom [Known undefined, Unknown (Just undefined)] it "Meta" $ do mapM_ hitsBottom [ def & homepage .~ undefined , def & description .~ undefined , def & license .~ undefined , def & platforms .~ undefined , def & maintainers .~ undefined , def & broken .~ undefined ] describe "Configuration records are consistent" $ it "No maintained package is marked as \"dont-distribute\"" $ Map.keysSet (packageMaintainers ghc7102) `Set.intersection` (dontDistributePackages ghc7102) `shouldSatisfy` Set.null hitsBottom :: NFData a => a -> Expectation hitsBottom x = evaluate (rnf x) `shouldThrow` anyErrorCall
psibi/cabal2nix
test/spec.hs
Haskell
bsd-3-clause
1,231
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.DeepSeq(module Idris.DeepSeq, module Idris.Core.DeepSeq) where import Idris.Core.DeepSeq import Idris.Docstrings import Idris.Core.TT import Idris.AbsSyntaxTree import Control.DeepSeq import qualified Cheapskate.Types as CT import qualified Idris.Docstrings as D instance NFData a => NFData (D.Docstring a) where rnf (D.DocString opts contents) = rnf opts `seq` rnf contents `seq` () instance NFData CT.Options where rnf (CT.Options x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () instance NFData a => NFData (D.Block a) where rnf (D.Para lines) = rnf lines `seq` () rnf (D.Header i lines) = rnf i `seq` rnf lines `seq` () rnf (D.Blockquote bs) = rnf bs `seq` () rnf (D.List b t xs) = rnf b `seq` rnf t `seq` rnf xs `seq` () rnf (D.CodeBlock attr txt tm) = rnf attr `seq` rnf txt `seq` () rnf (D.HtmlBlock txt) = rnf txt `seq` () rnf D.HRule = () instance NFData a => NFData (D.Inline a) where rnf (D.Str txt) = rnf txt `seq` () rnf D.Space = () rnf D.SoftBreak = () rnf D.LineBreak = () rnf (D.Emph xs) = rnf xs `seq` () rnf (D.Strong xs) = rnf xs `seq` () rnf (D.Code xs tm) = rnf xs `seq` rnf tm `seq` () rnf (D.Link a b xs) = rnf a `seq` rnf b `seq` rnf xs `seq` () rnf (D.Image a b c) = rnf a `seq` rnf b `seq` rnf c `seq` () rnf (D.Entity a) = rnf a `seq` () rnf (D.RawHtml x) = rnf x `seq` () instance NFData CT.ListType where rnf (CT.Bullet c) = rnf c `seq` () rnf (CT.Numbered nw i) = rnf nw `seq` rnf i `seq` () instance NFData CT.CodeAttr where rnf (CT.CodeAttr a b) = rnf a `seq` rnf b `seq` () instance NFData CT.NumWrapper where rnf CT.PeriodFollowing = () rnf CT.ParenFollowing = () instance NFData DocTerm where rnf Unchecked = () rnf (Checked x1) = rnf x1 `seq` () rnf (Example x1) = rnf x1 `seq` () rnf (Failing x1) = rnf x1 `seq` () -- All generated by 'derive' instance NFData SizeChange where rnf Smaller = () rnf Same = () rnf Bigger = () rnf Unknown = () instance NFData FnInfo where rnf (FnInfo x1) = rnf x1 `seq` () instance NFData Codegen where rnf (Via x1) = rnf x1 `seq` () rnf Bytecode = () instance NFData CGInfo where rnf (CGInfo x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () instance NFData Fixity where rnf (Infixl x1) = rnf x1 `seq` () rnf (Infixr x1) = rnf x1 `seq` () rnf (InfixN x1) = rnf x1 `seq` () rnf (PrefixN x1) = rnf x1 `seq` () instance NFData FixDecl where rnf (Fix x1 x2) = rnf x1 `seq` rnf x2 `seq` () instance NFData Static where rnf Static = () rnf Dynamic = () instance NFData ArgOpt where rnf _ = () instance NFData Plicity where rnf (Imp x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (Exp x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (Constraint x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (TacImp x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () instance NFData FnOpt where rnf Inlinable = () rnf TotalFn = () rnf PartialFn = () rnf CoveringFn = () rnf Coinductive = () rnf AssertTotal = () rnf Dictionary = () rnf Implicit = () rnf NoImplicit = () rnf (CExport x1) = rnf x1 `seq` () rnf ErrorHandler = () rnf ErrorReverse = () rnf Reflection = () rnf (Specialise x1) = rnf x1 `seq` () rnf Constructor = () rnf AutoHint = () rnf PEGenerated = () instance NFData DataOpt where rnf Codata = () rnf DefaultEliminator = () rnf DefaultCaseFun = () rnf DataErrRev = () instance (NFData t) => NFData (PDecl' t) where rnf (PFix x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PTy x1 x2 x3 x4 x5 x6 x7 x8) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` () rnf (PPostulate x1 x2 x3 x4 x5 x6 x7 x8) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` () rnf (PClauses x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PCAF x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PData x1 x2 x3 x4 x5 x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` () rnf (PParams x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PNamespace x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` rnf x9 `seq` rnf x10 `seq` rnf x11 `seq` rnf x12 `seq` () rnf (PClass x1 x2 x3 x4 x5 x6 x8 x7 x9 x10 x11 x12) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` rnf x9 `seq` rnf x10 `seq` rnf x11 `seq` rnf x12 `seq` () rnf (PInstance x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` rnf x9 `seq` rnf x10 `seq` rnf x11 `seq` () rnf (PDSL x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PSyntax x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PMutual x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PDirective x1) = () rnf (PProvider x1 x2 x3 x4 x5 x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` () rnf (PTransform x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () instance NFData t => NFData (ProvideWhat' t) where rnf (ProvTerm ty tm) = rnf ty `seq` rnf tm `seq` () rnf (ProvPostulate tm) = rnf tm `seq` () instance NFData PunInfo where rnf x = x `seq` () instance (NFData t) => NFData (PClause' t) where rnf (PClause x1 x2 x3 x4 x5 x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` () rnf (PWith x1 x2 x3 x4 x5 x6 x7) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` () rnf (PClauseR x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PWithR x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () instance (NFData t) => NFData (PData' t) where rnf (PDatadecl x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PLaterdecl x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () instance NFData PTerm where rnf (PQuote x1) = rnf x1 `seq` () rnf (PRef x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PInferRef x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PPatvar x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PLam _ x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PPi x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () rnf (PLet _ x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () rnf (PTyped x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PAppImpl x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PApp x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PAppBind x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PMatchApp x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PCase x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PIfThenElse x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PTrue x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PResolveTC x1) = rnf x1 `seq` () rnf (PRewrite x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PPair x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PDPair x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () rnf (PAs x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PAlternative x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PHidden x1) = rnf x1 `seq` () rnf (PType fc) = rnf fc `seq` () rnf (PUniverse _) = () rnf (PGoal x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PConstant x1 x2) = x1 `seq` x2 `seq` () rnf Placeholder = () rnf (PDoBlock x1) = rnf x1 `seq` () rnf (PIdiom x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PReturn x1) = rnf x1 `seq` () rnf (PMetavar x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PProof x1) = rnf x1 `seq` () rnf (PTactics x1) = rnf x1 `seq` () rnf (PElabError x1) = rnf x1 `seq` () rnf PImpossible = () rnf (PCoerced x1) = rnf x1 `seq` () rnf (PDisamb x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PUnifyLog x1) = rnf x1 `seq` () rnf (PNoImplicits x1) = rnf x1 `seq` () rnf (PQuasiquote x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PUnquote x1) = rnf x1 `seq` () rnf (PQuoteName x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PRunElab x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () instance NFData PAltType where rnf (ExactlyOne x1) = rnf x1 `seq` () rnf FirstSuccess = () instance (NFData t) => NFData (PTactic' t) where rnf (Intro x1) = rnf x1 `seq` () rnf Intros = () rnf (Focus x1) = rnf x1 `seq` () rnf (Refine x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (Rewrite x1) = rnf x1 `seq` () rnf DoUnify = () rnf (Induction x1) = rnf x1 `seq` () rnf (CaseTac x1) = rnf x1 `seq` () rnf (Equiv x1) = rnf x1 `seq` () rnf (Claim x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (MatchRefine x1) = rnf x1 `seq` () rnf (LetTac x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (LetTacTy x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (Exact x1) = rnf x1 `seq` () rnf Compute = () rnf Trivial = () rnf TCInstance = () rnf (ProofSearch r r1 r2 x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf Solve = () rnf Attack = () rnf ProofState = () rnf ProofTerm = () rnf Undo = () rnf (Try x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (TSeq x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (ApplyTactic x1) = rnf x1 `seq` () rnf (ByReflection x1) = rnf x1 `seq` () rnf (Reflect x1) = rnf x1 `seq` () rnf (Fill x1) = rnf x1 `seq` () rnf (GoalType x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf Qed = () rnf Abandon = () rnf (TCheck x1) = rnf x1 `seq` () rnf (TEval x1) = rnf x1 `seq` () rnf (TDocStr x1) = x1 `seq` () rnf (TSearch x1) = rnf x1 `seq` () rnf Skip = () rnf (TFail x1) = rnf x1 `seq` () rnf SourceFC = () rnf Unfocus = () instance (NFData t) => NFData (PDo' t) where rnf (DoExp x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (DoBind x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (DoBindP x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (DoLet x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () rnf (DoLetP x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () instance (NFData t) => NFData (PArg' t) where rnf (PImp x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () rnf (PExp x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PConstraint x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PTacImplicit x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () instance NFData ClassInfo where rnf (CI x1 x2 x3 x4 x5 x6 x7) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` () instance NFData OptInfo where rnf (Optimise x1 x2) = rnf x1 `seq` rnf x2 `seq` () instance NFData TypeInfo where rnf (TI x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () instance (NFData t) => NFData (DSL' t) where rnf (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` rnf x9 `seq` rnf x10 `seq` () instance NFData SynContext where rnf PatternSyntax = () rnf TermSyntax = () rnf AnySyntax = () instance NFData Syntax where rnf (Rule x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () instance NFData SSymbol where rnf (Keyword x1) = rnf x1 `seq` () rnf (Symbol x1) = rnf x1 `seq` () rnf (Binding x1) = rnf x1 `seq` () rnf (Expr x1) = rnf x1 `seq` () rnf (SimpleExpr x1) = rnf x1 `seq` () instance NFData Using where rnf (UImplicit x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (UConstraint x1 x2) = rnf x1 `seq` rnf x2 `seq` () instance NFData SyntaxInfo where rnf (Syn x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` rnf x9 `seq` rnf x10 `seq` rnf x11 `seq` rnf x12 `seq` ()
bkoropoff/Idris-dev
src/Idris/DeepSeq.hs
Haskell
bsd-3-clause
14,948
module Main(main) where import MonadPoint -- titlePage title name = scale 0.9 $ do scaleh 0.65 $ do scalehu 0.7 $ do holstack $ mapM_ txtc $ lines title scalehd 0.2 $ do txtc name tmpl title m = page $ do scale 0.9 $ do scalehu 0.2 $ do txtc title scalehd 0.75 $ do m -- myPresen = pages $ do titlePage "Super Presentation" "hoge" tmpl "Introduction..." $ do list $ do li "I love Haskell." li "I always use Haskell." li "About Haskel" ul $ do li "functional" li "lazy" li "super language!" tmpl "continue..." $ do list $ do li "continue..." return () -- cfg = Config "./dat" "ARISAKA.ttf" "ARISAKA_fix.ttf" main :: IO () main = runPresentation cfg myPresen
tanakh/MonadPoint
test/Main.hs
Haskell
bsd-3-clause
868
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : dave.laing.80@gmail.com Stability : experimental Portability : non-portable -} module Fragment.Fix.Helpers ( tmFix ) where import Control.Lens (review) import Ast.Term import Fragment.Fix.Ast.Term tmFix :: AsTmFix ki ty pt tm => Term ki ty pt tm a -> Term ki ty pt tm a tmFix = review _TmFix
dalaing/type-systems
src/Fragment/Fix/Helpers.hs
Haskell
bsd-3-clause
388
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ScopedTypeVariables #-} -- | -- Module: $HEADER$ -- Description: Abstract API for DHT implementations. -- Copyright: (c) 2015, Jan Šipr, Matej Kollár, Peter Trško -- License: BSD3 -- -- Stability: experimental -- Portability: NoImplicitPrelude -- -- Abstract API for DHT implementations. module Data.DHT.Core ( -- * DHT Handle -- -- | Specific DHT implementation should provide equivalent of -- @open\/create\/new@. Such function returns 'DhtHandle'. DhtHandle -- * DHT Operations , DhtResult , DhtKey , Encoding , join , leave , lookup , insert ) where import Control.Monad.IO.Class (MonadIO(liftIO)) import Data.Function (($), (.)) import Data.DHT.Type.Handle (DhtHandle) import qualified Data.DHT.Type.Handle as Internal ( forDhtHandle , hash , insert , join , leave , lookup , withDhtHandle ) import Data.DHT.Type.Key (DhtKey) import Data.DHT.Type.Result (DhtResult) import Data.DHT.Type.Encoding (Encoding) -- | Join DHT overlay. join :: MonadIO m => DhtHandle -> DhtResult m () join = liftIO . Internal.withDhtHandle Internal.join -- | Leave DHT overlay. leave :: MonadIO m => DhtHandle -> DhtResult m () leave = liftIO . Internal.withDhtHandle Internal.leave -- | Lookup specified 'DhtKey' in DHT and provide its value as a result, if it -- is available. lookup :: MonadIO m => DhtHandle -> DhtKey -> DhtResult m Encoding lookup h k = liftIO $ Internal.forDhtHandle h $ \h' s -> Internal.lookup h' s (Internal.hash h' s k) -- | Insert 'DhtKey' with associated value of type 'Encoding' in DHT. insert :: MonadIO m => DhtHandle -> DhtKey -> Encoding -> DhtResult m () insert h k e = liftIO $ Internal.forDhtHandle h $ \h' s -> Internal.insert h' s (Internal.hash h' s k) e
FPBrno/dht-api
src/Data/DHT/Core.hs
Haskell
bsd-3-clause
1,861
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} module ZM.Type.Float32(IEEE_754_binary32(..)) where import Data.Model import ZM.Type.Bits8 import ZM.Type.Bits23 import ZM.Type.Words -- |An IEEE-754 Big Endian 32 bits Float data IEEE_754_binary32 = IEEE_754_binary32 { sign :: Sign , exponent :: MostSignificantFirst Bits8 , fraction :: MostSignificantFirst Bits23 } deriving (Eq, Ord, Show, Generic, Model) -- Low Endian -- data IEEE_754_binary32_LE = -- IEEE_754_binary32_LE -- { fractionLE :: LeastSignificantFirst Bits23 -- , exponentLE :: LeastSignificantFirst Bits8 -- , signLE :: Sign -- } -- or data IEEE_754_binary32_LE = IEEE_754_binary32 Word64
tittoassini/typed
src/ZM/Type/Float32.hs
Haskell
bsd-3-clause
811
module Atomo.Parser.Expr where import Control.Arrow (first, second) import Control.Monad.State import Data.Maybe (fromJust, isJust) import Text.Parsec import qualified Control.Monad.Trans as MTL import Atomo.Environment import Atomo.Helpers (toPattern', toMacroPattern') import Atomo.Parser.Base import Atomo.Parser.Expand import Atomo.Parser.Primitive import Atomo.Types hiding (keyword, string) import qualified Atomo.Types as T -- | The types of values in Dispatch syntax. data Dispatch = DParticle (Particle Expr) | DNormal Expr deriving Show -- | The default precedence for an operator (5). defaultPrec :: Integer defaultPrec = 5 -- | Parses any Atomo expression. pExpr :: Parser Expr pExpr = choice [ pOperator , pMacro , pForMacro , try pDispatch , pLiteral , parens pExpr ] <?> "expression" -- | Parses any Atomo literal value. pLiteral :: Parser Expr pLiteral = choice [ pThis , pBlock , pList , pParticle , pQuoted , pQuasiQuoted , pUnquoted , pPrimitive ] <?> "literal" -- | Parses a primitive value. -- -- Examples: @1@, @2.0@, @3\/4@, @$d@, @\"foo\"@, @True@, @False@ pPrimitive :: Parser Expr pPrimitive = tagged $ liftM (Primitive Nothing) pPrim -- | The @this@ keyword, i.e. the toplevel object literal. pThis :: Parser Expr pThis = tagged $ reserved "this" >> return (ETop Nothing) -- | An expression literal. -- -- Example: @'1@, @'(2 + 2)@ pQuoted :: Parser Expr pQuoted = tagged $ do char '\'' e <- pSpacedExpr return (Primitive Nothing (Expression e)) -- | An expression literal that may contain "unquotes" - expressions to splice -- in to yield a different expression. -- -- Examples: @`a@, @`(1 + ~(2 + 2))@ pQuasiQuoted :: Parser Expr pQuasiQuoted = tagged $ do char '`' modifyState $ \ps -> ps { psInQuote = True } e <- pSpacedExpr modifyState $ \ps -> ps { psInQuote = False } return (EQuote Nothing e) -- | An unquote expression, used inside a quasiquote. -- -- Examples: @~1@, @~(2 + 2)@ pUnquoted :: Parser Expr pUnquoted = tagged $ do char '~' iq <- fmap psInQuote getState modifyState $ \ps -> ps { psInQuote = False } e <- pSpacedExpr modifyState $ \ps -> ps { psInQuote = iq } return (EUnquote Nothing e) -- | Any expression that fits into one lexical "space" - either a simple -- literal value, a single dispatch to the toplevel object, or an expression in -- parentheses. -- -- Examples: @1@, @[1, 2]@, @a@, @(2 + 2)@ pSpacedExpr :: Parser Expr pSpacedExpr = pLiteral <|> simpleDispatch <|> parens pExpr where simpleDispatch = tagged $ do name <- ident notFollowedBy (char ':') spacing return (Dispatch Nothing (single name (ETop Nothing))) -- | The for-macro "pragma." -- -- Example: @for-macro 1 print@ pForMacro :: Parser Expr pForMacro = tagged (do reserved "for-macro" whiteSpace e <- pExpr return (EForMacro Nothing e)) <?> "for-macro expression" -- | A macro definition. -- -- Example: @macro (n squared) `(~n * ~n)@ pMacro :: Parser Expr pMacro = tagged (do reserved "macro" whiteSpace p <- parens (pExpr >>= MTL.lift . toMacroPattern') whiteSpace e <- pExpr return (EMacro Nothing p e)) <?> "macro definition" -- | An operator "pragma" - tells the parser about precedence and associativity -- for the given operator(s). -- -- Examples: @operator right 0 ->@, @operator 7 * /@ pOperator :: Parser Expr pOperator = tagged (do reserved "operator" whiteSpace info <- choice [ do a <- choice [ symbol "right" >> return ARight , symbol "left" >> return ALeft ] prec <- option defaultPrec (try integer) return (a, prec) , liftM ((,) ALeft) integer ] ops <- operator `sepBy1` spacing forM_ ops $ \name -> modifyState $ \ps -> ps { psOperators = (name, info) : psOperators ps } return (uncurry (Operator Nothing ops) info)) <?> "operator pragma" -- | A particle literal. -- -- Examples: @\@foo@, @\@(bar: 2)@, @\@bar:@, @\@(foo: 2 bar: _)@ pParticle :: Parser Expr pParticle = tagged (do char '@' c <- choice [ cKeyword True , binary , try (cSingle True) , symbols ] return (EParticle Nothing c)) <?> "particle" where binary = do op <- operator return $ PMKeyword [op] [Nothing, Nothing] symbols = do names <- many1 (anyIdent >>= \n -> char ':' >> return n) spacing return $ PMKeyword names (replicate (length names + 1) Nothing) -- | Any dispatch, both single and keyword. pDispatch :: Parser Expr pDispatch = try pdKeys <|> pdChain <?> "dispatch" -- | A keyword dispatch. -- -- Examples: @1 foo: 2@, @1 + 2@ pdKeys :: Parser Expr pdKeys = do pos <- getPosition msg <- keywords T.keyword (ETop (Just pos)) (try pdChain <|> headless) ops <- liftM psOperators getState return $ Dispatch (Just pos) (toBinaryOps ops msg) <?> "keyword dispatch" where headless = do p <- getPosition msg <- ckeywd p ops <- liftM psOperators getState return (Dispatch (Just p) (toBinaryOps ops msg)) ckeywd pos = do ks <- wsMany1 $ keyword pdChain let (ns, es) = unzip ks return $ T.keyword ns (ETop (Just pos):es) <?> "keyword segment" -- | A chain of message sends, both single and chained keywords. -- -- Example: @1 sqrt (* 2) floor@ pdChain :: Parser Expr pdChain = do pos <- getPosition chain <- wsManyStart (liftM DNormal (try pLiteral <|> pThis <|> parens pExpr) <|> chained) chained return $ dispatches pos chain <?> "single dispatch" where chained = liftM DParticle $ choice [ cKeyword False , cSingle False ] -- start off by dispatching on either a primitive or Top dispatches :: SourcePos -> [Dispatch] -> Expr dispatches p (DNormal e:ps) = dispatches' p ps e dispatches p (DParticle (PMSingle n):ps) = dispatches' p ps (Dispatch (Just p) $ single n (ETop (Just p))) dispatches p (DParticle (PMKeyword ns (Nothing:es)):ps) = dispatches' p ps (Dispatch (Just p) $ T.keyword ns (ETop (Just p):map fromJust es)) dispatches _ ds = error $ "impossible: dispatches on " ++ show ds -- roll a list of partial messages into a bunch of dispatches dispatches' :: SourcePos -> [Dispatch] -> Expr -> Expr dispatches' _ [] acc = acc dispatches' p (DParticle (PMKeyword ns (Nothing:es)):ps) acc = dispatches' p ps (Dispatch (Just p) $ T.keyword ns (acc : map fromJust es)) dispatches' p (DParticle (PMSingle n):ps) acc = dispatches' p ps (Dispatch (Just p) $ single n acc) dispatches' _ x y = error $ "impossible: dispatches' on " ++ show (x, y) -- | A comma-separated list of zero or more expressions, surrounded by square -- brackets. -- -- Examples: @[]@, @[1, $a]@ pList :: Parser Expr pList = (tagged . liftM (EList Nothing) $ brackets (wsDelim "," pExpr)) <?> "list" -- | A block of expressions, surrounded by braces and optionally having -- arguments. -- -- Examples: @{ }@, @{ a b | a + b }@, @{ a = 1; a + 1 }@ pBlock :: Parser Expr pBlock = tagged (braces $ do arguments <- option [] . try $ do ps <- many1 pSpacedExpr whiteSpace string "|" whiteSpace1 mapM (MTL.lift . toPattern') ps code <- wsBlock pExpr return $ EBlock Nothing arguments code) <?> "block" -- | A general "single dispatch" form, without a target. -- -- Used for both chaines and particles. cSingle :: Bool -> Parser (Particle Expr) cSingle p = do n <- if p then anyIdent else ident notFollowedBy colon spacing return (PMSingle n) <?> "single segment" -- | A general "keyword dispatch" form, without a head. -- -- Used for both chaines and particles. cKeyword :: Bool -> Parser (Particle Expr) cKeyword wc = do ks <- parens $ many1 keyword' let (ns, mvs) = second (Nothing:) $ unzip ks if any isOperator (tail ns) then toDispatch ns mvs else return $ PMKeyword ns mvs <?> "keyword segment" where keywordVal | wc = wildcard <|> value | otherwise = value keywordDispatch | wc = wildcard <|> disp | otherwise = disp value = liftM Just pdChain disp = liftM Just pDispatch keyword' = do name <- try (do name <- ident char ':' return name) <|> operator whiteSpace1 target <- if isOperator name then keywordDispatch else keywordVal return (name, target) wildcard = symbol "_" >> return Nothing toDispatch [] mvs = error $ "impossible: toDispatch on [] and " ++ show mvs toDispatch (n:ns) mvs | all isJust opVals = do os <- getState pos <- getPosition let msg = toBinaryOps (psOperators os) $ T.keyword opers (map fromJust opVals) return . PMKeyword nonOpers $ partVals ++ [Just $ Dispatch (Just pos) msg] | otherwise = fail "invalid particle; toplevel operator with wildcards as values" where (nonOpers, opers) = first (n:) $ break isOperator ns (partVals, opVals) = splitAt (length nonOpers) mvs -- | Work out precadence, associativity, etc. for a keyword dispatch. -- -- The input is a keyword EMessage with a mix of operators and identifiers as -- its name, e.g. @keyword { emNames = ["+", "*", "remainder"] }@. toBinaryOps :: Operators -> Message Expr -> Message Expr toBinaryOps _ done@(Keyword _ [_] [_, _]) = done toBinaryOps ops (Keyword h (n:ns) (v:vs)) | nextFirst = T.keyword [n] [ v , Dispatch (eLocation v) (toBinaryOps ops (T.keyword ns vs)) ] | isOperator n = toBinaryOps ops . T.keyword ns $ (Dispatch (eLocation v) (T.keyword [n] [v, head vs]):tail vs) | nonOperators == ns = Keyword h (n:ns) (v:vs) | null nonOperators && length vs > 2 = T.keyword [head ns] [ Dispatch (eLocation v) $ T.keyword [n] [v, head vs] , Dispatch (eLocation v) $ toBinaryOps ops (T.keyword (tail ns) (tail vs)) ] | otherwise = toBinaryOps ops . T.keyword (drop numNonOps ns) $ (Dispatch (eLocation v) $ T.keyword (n : nonOperators) (v : take (numNonOps + 1) vs)) : drop (numNonOps + 1) vs where numNonOps = length nonOperators nonOperators = takeWhile (not . isOperator) ns nextFirst = isOperator n && or [ null ns , prec next > prec n , assoc n == ARight && prec next == prec n ] where next = head ns assoc n' = case lookup n' ops of Nothing -> ALeft Just (a, _) -> a prec n' = case lookup n' ops of Nothing -> defaultPrec Just (_, p) -> p toBinaryOps _ u = error $ "cannot toBinaryOps: " ++ show u -- | Parse a block of expressions from a given input string. parser :: Parser [Expr] parser = do whiteSpace es <- wsBlock pExpr whiteSpace eof return es -- | Same as `parser', but ignores a shebang at the start of the source. fileParser :: Parser [Expr] fileParser = do optional (string "#!" >> manyTill anyToken (eol <|> eof)) parser
Mathnerd314/atomo
src/Atomo/Parser/Expr.hs
Haskell
bsd-3-clause
11,644
-- | Mutually recursive types. module Data.Aeson.Validation.Internal.Types where import Data.Aeson.Validation.Internal.Prelude import Data.List.NonEmpty ((<|)) import qualified GHC.Exts as GHC -- $setup -- >>> import Data.Aeson.Validation.Internal.Schema data Demand = Opt | Req deriving Eq instance Hashable Demand where hash Opt = 0 hash Req = 1 -- Stolen from @hashable@ hashWithSalt s x = s * 16777619 `xor` hash x -- | An opaque object 'Field'. -- -- Create a 'Field' with '.:' or '.:?', and bundle it into a 'Schema' using -- 'object' or 'object'' data Field = Field !Demand !(NonEmpty Text) !Schema -- | An opaque JSON 'Schema'. data Schema = SBool | STrue | SFalse | SNumber | SInteger | STheNumber !Scientific | STheInteger !Integer | SSomeNumber !Text {- error msg -} (Scientific -> Bool) {- predicate -} | SString | STheString !Text | SSomeString !Text {- error msg -} (Text -> Bool) {- predicate -} | SDateTime | SObject !Strict ![ShallowField] | SArray !Unique !Int {- min len -} !Int {- max len -} !Schema | STuple ![Schema] | SAnything | SNullable !Schema | SAlts !(NonEmpty Schema) | SNegate !Schema -- | The 'Num' instance only defines two functions; all other 'Num' functions -- call 'error'. -- -- (1) 'fromInteger' is provided for integer-literal syntax. -- -- @ -- 'fromInteger' = 'theInteger' -- @ -- -- Examples: -- -- >>> validate 1 (Number 1) -- [] -- -- (2) @'negate' s@ succeeds whenever @s@ fails. -- -- 'negate' is its own inverse: -- -- @ -- 'negate' . 'negate' = 'id' -- @ -- -- Examples: -- -- >>> validate (negate bool) (String "foo") -- [] -- -- >>> validate (negate bool) (Bool True) -- ["expected anything but a bool but found true"] instance Num Schema where (+) = error "Data.Aeson.Validation: (+) not implemented for Schema" (-) = error "Data.Aeson.Validation: (-) not implemented for Schema" (*) = error "Data.Aeson.Validation: (*) not implemented for Schema" abs = error "Data.Aeson.Validation: abs not implemented for Schema" signum = error "Data.Aeson.Validation: signum not implemented for Schema" fromInteger = STheInteger negate = SNegate -- | The 'Fractional' instance only defines one function; all other 'Fractional' -- functions call 'error'. -- -- (1) 'fromRational' is provided for floating point-literal syntax. -- -- @ -- 'fromRational' = 'theNumber' . 'fromRational' -- @ -- -- Examples: -- -- >>> validate 1.5 (Number 1.5) -- [] -- -- >>> validate 2.5 (Number 2.500000001) -- [] instance Fractional Schema where (/) = error "Data.Aeson.Validation: (/) not implemented for Schema" recip = error "Data.Aeson.Validation: recip not implemented for Schema" fromRational = STheNumber . fromRational -- | The '<>' operator is used to create a /sum/ 'Schema' that, when applied to -- a 'Value', first tries the left 'Schema', then falls back on the right one if -- the left one fails. -- -- For 'validate', if any 'Schema's emits no violations, then no violations are -- emitted. Otherwise, all violations are emitted. -- -- Examples: -- -- >>> validate (bool <> string) (Bool True) -- [] -- -- >>> validate (bool <> string) (String "foo") -- [] -- -- >>> validate (bool <> string) (Number 1) -- ["expected a bool but found a number","expected a string but found a number"] instance Semigroup Schema where SAlts xs <> SAlts ys = SAlts (xs <> ys) SAlts (x:|xs) <> y = SAlts (x :| xs ++ [y]) -- Won't happen naturally (infixr) x <> SAlts ys = SAlts (x <| ys) x <> y = SAlts (x :| [y]) -- | 'GHC.fromString' is provided for string-literal syntax. -- -- @ -- 'GHC.fromString' = 'theString' . 'Data.Text.pack' -- @ -- -- Examples: -- -- >>> validate "foo" (String "foo") -- [] instance GHC.IsString Schema where fromString = STheString . GHC.fromString data ShallowField = ShallowField { fieldDemand :: !Demand , fieldKey :: !Text , fieldSchema :: !Schema } -- Are extra properties of an object allowed? data Strict = Strict | NotStrict -- Are duplicate elements in an array allowed? data Unique = Unique | NotUnique deriving Eq
mitchellwrosen/json-validation
src/internal/Data/Aeson/Validation/Internal/Types.hs
Haskell
bsd-3-clause
4,349
module AddressUtils ( adjustAddr , adjustAmount , IsBitcoinAddress ) where import qualified Data.Text as T import qualified Network.BitcoinRPC as RPC import qualified Network.MtGoxAPI as MtGox class IsBitcoinAddress a where addrToText :: a -> T.Text textToAddr :: T.Text -> a instance IsBitcoinAddress RPC.BitcoinAddress where addrToText = RPC.btcAddress textToAddr = RPC.BitcoinAddress instance IsBitcoinAddress MtGox.BitcoinAddress where addrToText = MtGox.baAddress textToAddr = MtGox.BitcoinAddress instance IsBitcoinAddress MtGox.BitcoinDepositAddress where addrToText = addrToText . MtGox.bdaAddr textToAddr = MtGox.BitcoinDepositAddress . textToAddr instance IsBitcoinAddress T.Text where addrToText = id textToAddr = id class IsBitcoinAmount a where amountToInteger :: a -> Integer integerToAmount :: Integer -> a instance IsBitcoinAmount Integer where amountToInteger = id integerToAmount = id instance IsBitcoinAmount RPC.BitcoinAmount where amountToInteger = RPC.btcAmount integerToAmount = RPC.BitcoinAmount adjustAddr :: (IsBitcoinAddress a, IsBitcoinAddress b) => a -> b adjustAddr = textToAddr . addrToText adjustAmount :: (IsBitcoinAmount a, IsBitcoinAmount b) => a -> b adjustAmount = integerToAmount . amountToInteger
javgh/bridgewalker
src/AddressUtils.hs
Haskell
bsd-3-clause
1,340
{-# LANGUAGE CPP #-} -- This module deliberately defines orphan instances for now (Binary Version). {-# OPTIONS_GHC -fno-warn-orphans -fno-warn-name-shadowing #-} ----------------------------------------------------------------------------- -- | -- Module : ETA.PackageDb -- Copyright : (c) The University of Glasgow 2009, Duncan Coutts 2014 -- -- Maintainer : ghc-devs@haskell.org -- Portability : portable -- -- This module provides the view of GHC's database of registered packages that -- is shared between GHC the compiler\/library, and the ghc-pkg program. It -- defines the database format that is shared between GHC and ghc-pkg. -- -- The database format, and this library are constructed so that GHC does not -- have to depend on the Cabal library. The ghc-pkg program acts as the -- gateway between the external package format (which is defined by Cabal) and -- the internal package format which is specialised just for GHC. -- -- GHC the compiler only needs some of the information which is kept about -- registerd packages, such as module names, various paths etc. On the other -- hand ghc-pkg has to keep all the information from Cabal packages and be able -- to regurgitate it for users and other tools. -- -- The first trick is that we duplicate some of the information in the package -- database. We essentially keep two versions of the datbase in one file, one -- version used only by ghc-pkg which keeps the full information (using the -- serialised form of the 'InstalledPackageInfo' type defined by the Cabal -- library); and a second version written by ghc-pkg and read by GHC which has -- just the subset of information that GHC needs. -- -- The second trick is that this module only defines in detail the format of -- the second version -- the bit GHC uses -- and the part managed by ghc-pkg -- is kept in the file but here we treat it as an opaque blob of data. That way -- this library avoids depending on Cabal. -- module ETA.PackageDb ( InstalledPackageInfo(..), ExposedModule(..), OriginalModule(..), BinaryStringRep(..), emptyInstalledPackageInfo, readPackageDbForGhc, readPackageDbForGhcPkg, writePackageDb ) where import Data.Version (Version(..)) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BS.Char8 import qualified Data.ByteString.Lazy as BS.Lazy import qualified Data.ByteString.Lazy.Internal as BS.Lazy (defaultChunkSize) import Data.Binary as Bin import Data.Binary.Put as Bin import Data.Binary.Get as Bin import Control.Exception as Exception import Control.Monad (when) import System.FilePath import System.IO import System.IO.Error import GHC.IO.Exception (IOErrorType(InappropriateType)) import System.Directory -- | This is a subset of Cabal's 'InstalledPackageInfo', with just the bits -- that GHC is interested in. -- data InstalledPackageInfo instpkgid srcpkgid srcpkgname pkgkey modulename = InstalledPackageInfo { installedPackageId :: instpkgid, sourcePackageId :: srcpkgid, packageName :: srcpkgname, packageVersion :: Version, packageKey :: pkgkey, depends :: [instpkgid], importDirs :: [FilePath], hsLibraries :: [String], extraLibraries :: [String], extraGHCiLibraries :: [String], libraryDirs :: [FilePath], frameworks :: [String], frameworkDirs :: [FilePath], ldOptions :: [String], ccOptions :: [String], includes :: [String], includeDirs :: [FilePath], haddockInterfaces :: [FilePath], haddockHTMLs :: [FilePath], exposedModules :: [ExposedModule instpkgid modulename], hiddenModules :: [modulename], instantiatedWith :: [(modulename,OriginalModule instpkgid modulename)], exposed :: Bool, trusted :: Bool } deriving (Eq, Show) -- | An original module is a fully-qualified module name (installed package ID -- plus module name) representing where a module was *originally* defined -- (i.e., the 'exposedReexport' field of the original ExposedModule entry should -- be 'Nothing'). Invariant: an OriginalModule never points to a reexport. data OriginalModule instpkgid modulename = OriginalModule { originalPackageId :: instpkgid, originalModuleName :: modulename } deriving (Eq, Show) -- | Represents a module name which is exported by a package, stored in the -- 'exposedModules' field. A module export may be a reexport (in which -- case 'exposedReexport' is filled in with the original source of the module), -- and may be a signature (in which case 'exposedSignature is filled in with -- what the signature was compiled against). Thus: -- -- * @ExposedModule n Nothing Nothing@ represents an exposed module @n@ which -- was defined in this package. -- -- * @ExposedModule n (Just o) Nothing@ represents a reexported module @n@ -- which was originally defined in @o@. -- -- * @ExposedModule n Nothing (Just s)@ represents an exposed signature @n@ -- which was compiled against the implementation @s@. -- -- * @ExposedModule n (Just o) (Just s)@ represents a reexported signature -- which was originally defined in @o@ and was compiled against the -- implementation @s@. -- -- We use two 'Maybe' data types instead of an ADT with four branches or -- four fields because this representation allows us to treat -- reexports/signatures uniformly. data ExposedModule instpkgid modulename = ExposedModule { exposedName :: modulename, exposedReexport :: Maybe (OriginalModule instpkgid modulename), exposedSignature :: Maybe (OriginalModule instpkgid modulename) } deriving (Eq, Show) class BinaryStringRep a where fromStringRep :: BS.ByteString -> a toStringRep :: a -> BS.ByteString emptyInstalledPackageInfo :: (BinaryStringRep a, BinaryStringRep b, BinaryStringRep c, BinaryStringRep d) => InstalledPackageInfo a b c d e emptyInstalledPackageInfo = InstalledPackageInfo { installedPackageId = fromStringRep BS.empty, sourcePackageId = fromStringRep BS.empty, packageName = fromStringRep BS.empty, packageVersion = Version [] [], packageKey = fromStringRep BS.empty, depends = [], importDirs = [], hsLibraries = [], extraLibraries = [], extraGHCiLibraries = [], libraryDirs = [], frameworks = [], frameworkDirs = [], ldOptions = [], ccOptions = [], includes = [], includeDirs = [], haddockInterfaces = [], haddockHTMLs = [], exposedModules = [], hiddenModules = [], instantiatedWith = [], exposed = False, trusted = False } -- | Read the part of the package DB that GHC is interested in. -- readPackageDbForGhc :: (BinaryStringRep a, BinaryStringRep b, BinaryStringRep c, BinaryStringRep d, BinaryStringRep e) => FilePath -> IO [InstalledPackageInfo a b c d e] readPackageDbForGhc file = decodeFromFile file getDbForGhc where getDbForGhc = do _version <- getHeader _ghcPartLen <- get :: Get Word32 ghcPart <- get -- the next part is for ghc-pkg, but we stop here. return ghcPart -- | Read the part of the package DB that ghc-pkg is interested in -- -- Note that the Binary instance for ghc-pkg's representation of packages -- is not defined in this package. This is because ghc-pkg uses Cabal types -- (and Binary instances for these) which this package does not depend on. -- readPackageDbForGhcPkg :: Binary pkgs => FilePath -> IO pkgs readPackageDbForGhcPkg file = decodeFromFile file getDbForGhcPkg where getDbForGhcPkg = do _version <- getHeader -- skip over the ghc part ghcPartLen <- get :: Get Word32 _ghcPart <- skip (fromIntegral ghcPartLen) -- the next part is for ghc-pkg ghcPkgPart <- get return ghcPkgPart -- | Write the whole of the package DB, both parts. -- writePackageDb :: (Binary pkgs, BinaryStringRep a, BinaryStringRep b, BinaryStringRep c, BinaryStringRep d, BinaryStringRep e) => FilePath -> [InstalledPackageInfo a b c d e] -> pkgs -> IO () writePackageDb file ghcPkgs ghcPkgPart = writeFileAtomic file (runPut putDbForGhcPkg) where putDbForGhcPkg = do putHeader put ghcPartLen putLazyByteString ghcPart put ghcPkgPart where ghcPartLen :: Word32 ghcPartLen = fromIntegral (BS.Lazy.length ghcPart) ghcPart = encode ghcPkgs getHeader :: Get (Word32, Word32) getHeader = do magic <- getByteString (BS.length headerMagic) when (magic /= headerMagic) $ fail "not a ghc-pkg db file, wrong file magic number" majorVersion <- get :: Get Word32 -- The major version is for incompatible changes minorVersion <- get :: Get Word32 -- The minor version is for compatible extensions when (majorVersion /= 1) $ fail "unsupported ghc-pkg db format version" -- If we ever support multiple major versions then we'll have to change -- this code -- The header can be extended without incrementing the major version, -- we ignore fields we don't know about (currently all). headerExtraLen <- get :: Get Word32 skip (fromIntegral headerExtraLen) return (majorVersion, minorVersion) putHeader :: Put putHeader = do putByteString headerMagic put majorVersion put minorVersion put headerExtraLen where majorVersion = 1 :: Word32 minorVersion = 0 :: Word32 headerExtraLen = 0 :: Word32 headerMagic :: BS.ByteString headerMagic = BS.Char8.pack "\0ghcpkg\0" -- TODO: we may be able to replace the following with utils from the binary -- package in future. -- | Feed a 'Get' decoder with data chunks from a file. -- decodeFromFile :: FilePath -> Get a -> IO a decodeFromFile file decoder = withBinaryFile file ReadMode $ \hnd -> feed hnd (runGetIncremental decoder) where feed hnd (Partial k) = do chunk <- BS.hGet hnd BS.Lazy.defaultChunkSize if BS.null chunk then feed hnd (k Nothing) else feed hnd (k (Just chunk)) feed _ (Done _ _ res) = return res feed _ (Fail _ _ msg) = ioError err where err = mkIOError InappropriateType loc Nothing (Just file) `ioeSetErrorString` msg loc = "ETA.PackageDb.readPackageDb" writeFileAtomic :: FilePath -> BS.Lazy.ByteString -> IO () writeFileAtomic targetPath content = do let (targetDir, targetName) = splitFileName targetPath Exception.bracketOnError (openBinaryTempFileWithDefaultPermissions targetDir $ targetName <.> "tmp") (\(tmpPath, hnd) -> hClose hnd >> removeFile tmpPath) (\(tmpPath, hnd) -> do BS.Lazy.hPut hnd content hClose hnd #if mingw32_HOST_OS || mingw32_TARGET_OS renameFile tmpPath targetPath -- If the targetPath exists then renameFile will fail `catch` \err -> do exists <- doesFileExist targetPath if exists then do removeFile targetPath -- Big fat hairy race condition renameFile tmpPath targetPath -- If the removeFile succeeds and the renameFile fails -- then we've lost the atomic property. else throwIO (err :: IOException) #else renameFile tmpPath targetPath #endif ) instance (BinaryStringRep a, BinaryStringRep b, BinaryStringRep c, BinaryStringRep d, BinaryStringRep e) => Binary (InstalledPackageInfo a b c d e) where put (InstalledPackageInfo installedPackageId sourcePackageId packageName packageVersion packageKey depends importDirs hsLibraries extraLibraries extraGHCiLibraries libraryDirs frameworks frameworkDirs ldOptions ccOptions includes includeDirs haddockInterfaces haddockHTMLs exposedModules hiddenModules instantiatedWith exposed trusted) = do put (toStringRep installedPackageId) put (toStringRep sourcePackageId) put (toStringRep packageName) put packageVersion put (toStringRep packageKey) put (map toStringRep depends) put importDirs put hsLibraries put extraLibraries put extraGHCiLibraries put libraryDirs put frameworks put frameworkDirs put ldOptions put ccOptions put includes put includeDirs put haddockInterfaces put haddockHTMLs put exposedModules put (map toStringRep hiddenModules) put (map (\(k,v) -> (toStringRep k, v)) instantiatedWith) put exposed put trusted get = do installedPackageId <- get sourcePackageId <- get packageName <- get packageVersion <- get packageKey <- get depends <- get importDirs <- get hsLibraries <- get extraLibraries <- get extraGHCiLibraries <- get libraryDirs <- get frameworks <- get frameworkDirs <- get ldOptions <- get ccOptions <- get includes <- get includeDirs <- get haddockInterfaces <- get haddockHTMLs <- get exposedModules <- get hiddenModules <- get instantiatedWith <- get exposed <- get trusted <- get return (InstalledPackageInfo (fromStringRep installedPackageId) (fromStringRep sourcePackageId) (fromStringRep packageName) packageVersion (fromStringRep packageKey) (map fromStringRep depends) importDirs hsLibraries extraLibraries extraGHCiLibraries libraryDirs frameworks frameworkDirs ldOptions ccOptions includes includeDirs haddockInterfaces haddockHTMLs exposedModules (map fromStringRep hiddenModules) (map (\(k,v) -> (fromStringRep k, v)) instantiatedWith) exposed trusted) instance Binary Version where put (Version a b) = do put a put b get = do a <- get b <- get return (Version a b) instance (BinaryStringRep a, BinaryStringRep b) => Binary (OriginalModule a b) where put (OriginalModule originalPackageId originalModuleName) = do put (toStringRep originalPackageId) put (toStringRep originalModuleName) get = do originalPackageId <- get originalModuleName <- get return (OriginalModule (fromStringRep originalPackageId) (fromStringRep originalModuleName)) instance (BinaryStringRep a, BinaryStringRep b) => Binary (ExposedModule a b) where put (ExposedModule exposedName exposedReexport exposedSignature) = do put (toStringRep exposedName) put exposedReexport put exposedSignature get = do exposedName <- get exposedReexport <- get exposedSignature <- get return (ExposedModule (fromStringRep exposedName) exposedReexport exposedSignature)
alexander-at-github/eta
utils/eta-pkgdb/ETA/PackageDb.hs
Haskell
bsd-3-clause
15,693
{-# OPTIONS_GHC -Wall #-} module Atmosphere.Atmosphere( siAtmosphere , usAtmosphere ) where -- 1976 US Standard Atmosphere -- Adapted by -- Greg Horn -- Adapted by -- Richard J. Kwan, Lightsaber Computing -- from original programs by -- Ralph L. Carmichael, Public Domain Aeronautical Software -- -- Revision History -- Date Vers Person Statement of Changes -- 2004 Oct 04 1.0 RJK Initial program -- P H Y S I C A L C O N S T A N T S _FT2METERS :: (Ord a, Floating a) => a _KELVIN2RANKINE :: (Ord a, Floating a) => a _PSF2NSM :: (Ord a, Floating a) => a _SCF2KCM :: (Ord a, Floating a) => a _TZERO :: (Ord a, Floating a) => a _PZERO :: (Ord a, Floating a) => a _RHOZERO :: (Ord a, Floating a) => a _AZERO :: (Ord a, Floating a) => a _BETAVISC :: (Ord a, Floating a) => a _SUTH :: (Ord a, Floating a) => a _FT2METERS = 0.3048 -- mult. ft. to get meters (exact) _KELVIN2RANKINE = 1.8 -- mult deg K to get deg R _PSF2NSM = 47.880258 -- mult lb/sq.ft to get sq.m _SCF2KCM = 515.379 -- mult slugs/cu.ft to get kg/cu.m _TZERO = 288.15 -- sea-level temperature, kelvins _PZERO = 101325.0 -- sea-level pressure, N/sq.m _RHOZERO = 1.225 -- sea-level density, kg/cu.m _AZERO = 340.294 -- speed of sound at S.L. m/sec _BETAVISC = 1.458E-6 -- viscosity constant _SUTH = 110.4 -- Sutherland's constant, kelvins {- input: altitude in ft outputs: temperature in Rankine pressure in lb/ft^2 density in slugs/ft^3 speed of sound in ft/sec viscosity in slugs/(ft-sec) kinematic viscosity in ft^2/s -} usAtmosphere :: (Floating a, Ord a) => a -> (a,a,a,a,a,a) usAtmosphere alt_ft = (temp, pressure, density, asound, viscosity, kinematicViscosity) where alt_km = _FT2METERS*0.001*alt_ft (sigma, delta, theta) = simpleAtmosphere alt_km temp = _KELVIN2RANKINE*_TZERO*theta pressure = _PZERO*delta/47.88 density = _RHOZERO*sigma/515.379 asound = (_AZERO/_FT2METERS)*sqrt(theta) viscosity=(1.0/_PSF2NSM)*metricViscosity(theta) kinematicViscosity = viscosity/density siAtmosphere :: (Floating a, Ord a) => a -> (a,a,a,a,a,a) siAtmosphere alt_m = (temp, pressure, density, asound, viscosity, kinematicViscosity) where alt_km = 0.001*alt_m (sigma, delta, theta) = simpleAtmosphere alt_km temp = _TZERO * theta pressure = _PZERO * delta density = _RHOZERO * sigma asound = _AZERO * sqrt(theta) viscosity = metricViscosity theta kinematicViscosity = viscosity/density simpleAtmosphere :: (Floating a, Ord a) => a -> (a,a,a) simpleAtmosphere alt = (sigma, delta, theta) where {- Compute temperature, density, and pressure in simplified standard atmosphere. Correct to 20 km. Only approximate thereafter. Input: alt geometric altitude, km. Return: (sigma, delta, theta) sigma density/sea-level standard density delta pressure/sea-level standard pressure theta temperature/sea-level std. temperature -} _REARTH = 6369.0 -- radius of the Earth (km) _GMR = 34.163195 -- gas constant h = alt*_REARTH/(alt+_REARTH) -- geometric to geopotential altitude (theta, delta) -- troposphere | h < 11.0 = ( (288.15 - 6.5*h)/288.15, theta**(_GMR/6.5) ) -- stratosphere | h < 20.0 = (216.65/288.15, 0.2233611*exp(-_GMR*(h-11.0)/216.65)) | otherwise = error "simpleAtmosphere invalid higher than 20 km" sigma = delta/theta metricViscosity :: (Floating a, Ord a) => a -> a metricViscosity theta = _BETAVISC*sqrt(t*t*t)/(t+_SUTH) where t = theta * _TZERO
ghorn/conceptual-design
Atmosphere/Atmosphere.hs
Haskell
bsd-3-clause
3,780
{-# LANGUAGE DataKinds , FlexibleContexts , LambdaCase , TupleSections #-} module Language.HM.Rename ( NameError (..) , rename ) where import Control.Applicative import Control.Category import Control.Comonad.Cofree import Control.Monad.Error.Class import Control.Monad.Name.Class import Control.Monad.Reader import Control.Monad.Wrap import Data.Fix import Data.Flip import Data.Hashable import Data.HashMap.Lazy (HashMap) import qualified Data.HashMap.Lazy as Map import Data.Monoid import Data.Tagged import Data.Text import Language.HM.Exp import Language.HM.Parse import Language.HM.Type (Mono) import Language.HM.Var import Prelude hiding ((.)) type Map = HashMap type RenamedExp name = Cofree (Exp Curry name (Fix (Mono name))) Loc data NameError = NotInScope Text deriving Show rename :: ( Eq (name Value) , Hashable (name Value) , MonadError (NameError, Loc) m , MonadName name m ) => ParsedExp -> m (RenamedExp name) rename = unwrapMonadT . flip runReaderT mempty . loop where loop (a :< f) = (a :<) <$> case f of Lit i -> pure $ Lit i Var x -> Var <$> lookupName' x Abs x e -> bindName x $ \ x' -> Abs x' <$> loop e App e1 e2 -> App <$> loop e1 <*> loop e2 Let x e1 e2 -> do e1' <- loop e1 (bindName x $ \ x' -> Let x' e1' <$> loop e2) where lookupName' = either (throwError . (, a)) return <=< lookupName lookupName :: MonadReader (R name) m => Flip Tagged Text Value -> m (Either NameError (name Value)) lookupName (Flip (Tagged name)) = asks (Map.lookup name) >>= \ case Nothing -> return . Left $ NotInScope name Just name' -> return $ Right name' bindName :: ( MonadName name m , MonadReader (R name) m ) => Flip Tagged Text Value -> (name Value -> m a) -> m a bindName (Flip (Tagged name)) f = do name' <- newVar local (Map.insert name name') $ f name' type R name = Map Text (name Value)
sonyandy/unify
examples/unify-hm/Language/HM/Rename.hs
Haskell
bsd-3-clause
2,058
{- | Copyright : Copyright (C) 2011 Bjorn Buckwalter License : BSD3 Maintainer : bjorn.buckwalter@gmail.com Stability : Stable Portability: Haskell 98 This purpose of this library is to have a simple API and no dependencies beyond Haskell 98 in order to let you produce normally distributed random values with a minimum of fuss. This library does /not/ attempt to be blazingly fast nor to pass stringent tests of randomness. It attempts to be very easy to install and use while being \"good enough\" for many applications (simulations, games, etc.). The API builds upon and is largely analogous to that of the Haskell 98 @Random@ module (more recently @System.Random@). Pure: > (sample,g) = normal myRandomGen -- using a Random.RandomGen > samples = normals myRandomGen -- infinite list > samples2 = mkNormals 10831452 -- infinite list using a seed In the IO monad: > sample <- normalIO > samples <- normalsIO -- infinite list With custom mean and standard deviation: > (sample,g) = normal' (mean,sigma) myRandomGen > samples = normals' (mean,sigma) myRandomGen > samples2 = mkNormals' (mean,sigma) 10831452 > sample <- normalIO' (mean,sigma) > samples <- normalsIO' (mean,sigma) Internally the library uses the Box-Muller method to generate normally distributed values from uniformly distributed random values. If more than one sample is needed taking samples off an infinite list (created by e.g. 'normals') will be roughly twice as efficient as repeatedly generating individual samples with e.g. 'normal'. -} module Data.Random.Normal ( -- * Pure interface normal , normals , mkNormals -- ** Custom mean and standard deviation , normal' , normals' , mkNormals' -- * Using the global random number generator , normalIO , normalsIO -- ** Custom mean and standard deviation , normalIO' , normalsIO' ) where import Data.List (mapAccumL) import System.Random -- Normal distribution approximation -- --------------------------------- -- | Box-Muller method for generating two normally distributed -- independent random values from two uniformly distributed -- independent random values. boxMuller :: Floating a => a -> a -> (a,a) boxMuller u1 u2 = (r * cos t, r * sin t) where r = sqrt (-2 * log u1) t = 2 * pi * u2 -- | Convert a list of uniformly distributed random values into a -- list of normally distributed random values. The Box-Muller -- algorithms converts values two at a time, so if the input list -- has an uneven number of element the last one will be discarded. boxMullers :: Floating a => [a] -> [a] boxMullers (u1:u2:us) = n1:n2:boxMullers us where (n1,n2) = boxMuller u1 u2 boxMullers _ = [] -- API -- === -- | Takes a random number generator g, and returns a random value -- normally distributed with mean 0 and standard deviation 1, -- together with a new generator. This function is analogous to -- 'Random.random'. normal :: (RandomGen g, Random a, Floating a) => g -> (a,g) normal g0 = (fst $ boxMuller u1 u2, g2) -- While The Haskell 98 report says "For fractional types, the -- range is normally the semi-closed interval [0,1)" we will -- specify the range explicitly just to be sure. where (u1,g1) = randomR (0,1) g0 (u2,g2) = randomR (0,1) g1 -- | Plural variant of 'normal', producing an infinite list of -- random values instead of returning a new generator. This function -- is analogous to 'Random.randoms'. normals :: (RandomGen g, Random a, Floating a) => g -> [a] normals = boxMullers . randoms -- | Creates a infinite list of normally distributed random values -- from the provided random generator seed. (In the implementation -- the seed is fed to 'Random.mkStdGen' to produce the random -- number generator.) mkNormals :: (Random a, Floating a) => Int -> [a] mkNormals = normals . mkStdGen -- | A variant of 'normal' that uses the global random number -- generator. This function is analogous to 'Random.randomIO'. normalIO :: (Random a, Floating a) => IO a normalIO = do u1 <- randomRIO (0,1) u2 <- randomRIO (0,1) return $ fst $ boxMuller u1 u2 -- | Creates a infinite list of normally distributed random values -- using the global random number generator. (In the implementation -- 'Random.newStdGen' is used.) normalsIO :: (Random a, Floating a) => IO [a] normalsIO = fmap normals newStdGen -- With mean and standard deviation -- -------------------------------- -- | Analogous to 'normal' but uses the supplied (mean, standard -- deviation). normal' :: (RandomGen g, Random a, Floating a) => (a,a) -> g -> (a,g) normal' (mean, sigma) g = (x * sigma + mean, g') where (x, g') = normal g -- | Analogous to 'normals' but uses the supplied (mean, standard -- deviation). normals' :: (RandomGen g, Random a, Floating a) => (a,a) -> g -> [a] normals' (mean, sigma) g = map (\x -> x * sigma + mean) (normals g) -- | Analogous to 'mkNormals' but uses the supplied (mean, standard -- deviation). mkNormals' :: (Random a, Floating a) => (a,a) -> Int -> [a] mkNormals' ms = normals' ms . mkStdGen -- | Analogous to 'normalIO' but uses the supplied (mean, standard -- deviation). normalIO' ::(Random a, Floating a) => (a,a) -> IO a normalIO' (mean,sigma) = fmap (\x -> x * sigma + mean) normalIO -- | Analogous to 'normalsIO' but uses the supplied (mean, standard -- deviation). normalsIO' :: (Random a, Floating a) => (a,a) -> IO [a] normalsIO' ms = fmap (normals' ms) newStdGen
bjornbm/normaldistribution
Data/Random/Normal.hs
Haskell
bsd-3-clause
5,529
--file: Main.hs module AnsiExample where import Prelude hiding (Either(..)) import System.Console.ANSI import System.IO type Coord = (Int, Int) data World = World { wHero :: Coord } data Input = Up | Down | Left | Right | Exit deriving (Eq) anotherMain = do hSetEcho stdin False hSetBuffering stdin NoBuffering hSetBuffering stdout NoBuffering hideCursor setTitle "Thieflike" gameLoop $ World (0, 0) drawHero (heroX, heroY) = do clearScreen setCursorPosition heroY heroX setSGR [ SetConsoleIntensity BoldIntensity , SetColor Foreground Vivid Blue ] putStr "@" -- receive a character and return our Input data structure, -- recursing on invalid input getInput = do char <- getChar case char of 'q' -> return Exit 'w' -> return Up 's' -> return Down 'a' -> return Left 'd' -> return Right _ -> getInput -- operator to add 2 coordinates together (|+|) :: Coord -> Coord -> Coord (|+|) (x1, y1) (x2, y2) = (x1 + x2, y1 + y2) dirToCoord d | d == Up = (0, -1) | d == Down = (0, 1) | d == Left = (-1, 0) | d == Right = (1, 0) | otherwise = (0, 0) -- add the supplied direction to the hero's position, and set that -- to be the hero's new position, making sure to limit the hero's -- position between 0 and 80 in either direction handleDir w@(World hero) input = gameLoop (w { wHero = newCoord }) where newCoord = (newX, newY) (heroX, heroY) = hero |+| (dirToCoord input) hConst i = max 0 (min i 80) newX = hConst heroX newY = hConst heroY -- update the game loop to add in the goodbye message gameLoop world@(World hero) = do drawHero hero input <- getInput case input of Exit -> handleExit _ -> handleDir world input -- when the user wants to exit we give them a thank you -- message and then reshow the cursor handleExit = do clearScreen setCursorPosition 0 0 showCursor putStrLn "Thank you for playing!"
JobaerChowdhury/game-of-life
app/AnsiExample.hs
Haskell
bsd-3-clause
2,040
module Handler.Board where import Import import qualified Data.Text as T import qualified Data.List.Split as S import Board import NeuralNets import CommonDatatypes getBoardR :: Text -> Handler RepHtml getBoardR boardRepr = do ag'white <- liftIO $ mkAgent White ag'black <- liftIO $ mkAgent Black let denseRepr = map read $ S.splitOn "," $ T.unpack $ boardRepr board = denseReprToBoard denseRepr moves'white = getMoves White board moves'black = getMoves Black board -- moves'white'repr = map boardToLink moves'white -- moves'black'repr = map boardToLink moves'black boardToLink = T.pack . reprToRow . boardToDense eval b c = evaluateBoard (if c == White then ag'white :: AgentNNSimple else ag'black :: AgentNNSimple) b defaultLayout $ do setTitle "So abaloney..." $(widgetFile "board")
Tener/deeplearning-thesis
yesod/abaloney/Handler/Board.hs
Haskell
bsd-3-clause
859
-- | Provides a set implementation for machine CSP sets. This relies heavily -- on the type checking and assumes in many places that the sets being operated -- on are suitable for the opertion in question. -- -- We cannot just use the built in set implementation as FDR assumes in several -- places that infinite sets are allowed. module CSPM.Evaluator.ValueSet ( -- * Construction ValueSet(..), emptySet, fromList, toList, toSeq, singleton, -- * Basic Functions compareValueSets, member, card, empty, union, unions, infiniteUnions, intersection, intersections, difference, -- * Derived functions CartProductType(..), cartesianProduct, powerset, allSequences, allMaps, fastUnDotCartProduct, -- * Specialised Functions singletonValue, valueSetToEventSet, unDotProduct, ) where import Control.Monad import qualified Data.Foldable as F import Data.Hashable import Data.List (sort) import qualified Data.Map as M import qualified Data.Set as S import qualified Data.Sequence as Sq import qualified Data.Traversable as T import {-# SOURCE #-} CSPM.Evaluator.Exceptions import CSPM.Evaluator.Values --import qualified CSPM.Evaluator.ProcessValues as CE import Util.Exception import qualified Util.List as UL import Util.Prelude data CartProductType = CartDot | CartTuple deriving (Eq, Ord) data ValueSet = -- | Set of all integers Integers -- | Set of all processes | Processes -- | An explicit set of values | ExplicitSet (S.Set Value) -- | The infinite set of integers starting at lb. | IntSetFrom Int -- | A union of several sets. | CompositeSet (Sq.Seq ValueSet) -- | A set containing all sequences over the given set. | AllSequences ValueSet -- | A cartesian product of several sets. | CartesianProduct [ValueSet] CartProductType -- | The powerset of the given set | Powerset ValueSet -- | The set of all maps from the given domain to the given image. | AllMaps ValueSet ValueSet instance Hashable ValueSet where hashWithSalt s Integers = s `hashWithSalt` (1 :: Int) hashWithSalt s Processes = s `hashWithSalt` (2 :: Int) hashWithSalt s (IntSetFrom lb) = s `hashWithSalt` (3 :: Int) `hashWithSalt` lb hashWithSalt s (AllSequences vs) = s `hashWithSalt` (4 :: Int) `hashWithSalt` vs -- All the above are the ONLY possible representations of the sets (as the -- sets are infinite). However, other sets can be represented in multiple -- ways so we have to normalise to an explicit set, essentially. -- This is already guaranteed to be sorted hashWithSalt s (ExplicitSet vs) = s `hashWithSalt` (5 :: Int) `hashWithSalt` (S.toList vs) hashWithSalt s set = s `hashWithSalt` (sort $ toList set) instance Eq ValueSet where s1 == s2 = compare s1 s2 == EQ instance Ord ValueSet where -- Basic (possibly)-infinite cases compare Integers Integers = EQ compare Integers _ = GT compare _ Integers = LT compare Processes Processes = EQ compare Processes _ = GT compare _ Processes = LT compare (IntSetFrom lb1) (IntSetFrom lb2) = compare lb1 lb2 compare (CartesianProduct vs1 cp1) (CartesianProduct vs2 cp2) = compare cp1 cp2 `thenCmp` compare vs1 vs2 -- Mixed infinite cases -- Explicitly finite cases compare (CompositeSet s1) (CompositeSet s2) = compare s1 s2 compare (AllSequences s1) (AllSequences s2) = compare s1 s2 compare (ExplicitSet s1) (ExplicitSet s2) = compare s1 s2 compare (Powerset s1) (Powerset s2) = compare s1 s2 compare (AllMaps k1 v1) (AllMaps k2 v2) = compare k1 k2 `thenCmp` compare v1 v2 -- Fallback to comparing the lists compare s1 s2 = compare (sort $ toList s1) (sort $ toList s2) flipOrder :: Maybe Ordering -> Maybe Ordering flipOrder Nothing = Nothing flipOrder (Just EQ) = Just EQ flipOrder (Just LT) = Just GT flipOrder (Just GT) = Just LT -- | Compares two value sets using subseteq (as per the specification). compareValueSets :: ValueSet -> ValueSet -> Maybe Ordering -- Processes compareValueSets Processes Processes = Just EQ compareValueSets _ Processes = Just LT compareValueSets Processes _ = Just GT -- Integers compareValueSets Integers Integers = Just EQ compareValueSets _ Integers = Just LT compareValueSets Integers _ = Just GT -- IntSetFrom compareValueSets (IntSetFrom lb1) (IntSetFrom lb2) = Just (compare lb1 lb2) -- ExplicitSet compareValueSets (ExplicitSet s1) (ExplicitSet s2) = if s1 == s2 then Just EQ else if S.isProperSubsetOf s1 s2 then Just LT else if S.isProperSubsetOf s2 s1 then Just GT else Nothing -- IntSetFrom+ExplicitSet compareValueSets (IntSetFrom lb1) (ExplicitSet s2) = let VInt lb2 = S.findMin s2 VInt ub2 = S.findMax s2 in if lb1 <= lb2 then Just GT else Nothing compareValueSets (ExplicitSet s1) (IntSetFrom lb1) = flipOrder (compareValueSets (IntSetFrom lb1) (ExplicitSet s1)) -- Composite Sets compareValueSets (CompositeSet ss) s = compareValueSets (fromList (toList (CompositeSet ss))) s compareValueSets s (CompositeSet ss) = flipOrder (compareValueSets (CompositeSet ss) s) compareValueSets s1 s2 | empty s1 && empty s2 = Just EQ compareValueSets s1 s2 | empty s1 && not (empty s2) = Just LT compareValueSets s1 s2 | not (empty s1) && empty s2 = Just GT -- AllSequences+ExplicitSet sets compareValueSets (AllSequences vs1) (AllSequences vs2) = compareValueSets vs1 vs2 compareValueSets (ExplicitSet vs) (AllSequences vss) = if and (map (flip member (AllSequences vss)) (S.toList vs)) then Just LT -- Otherwise, there is some item in vs that is not in vss. However, unless -- vss is empty there must be some value in the second set that is not in -- the first, since (AllSequences vss) is infinite and, if the above -- finishes, we know the first set is finite. Hence, they would be -- incomparable. else Nothing compareValueSets (AllSequences vss) (ExplicitSet vs) = flipOrder (compareValueSets (ExplicitSet vs) (AllSequences vss)) -- CartesianProduct+ExplicitSet sets compareValueSets (CartesianProduct vss1 vc1) (CartesianProduct vss2 vc2) | vc1 == vc2 = let os = zipWith compareValueSets vss1 vss2 order v [] = v order (Just LT) (Just x : xs) | x /= GT = order (Just LT) xs order (Just EQ) (Just x : xs) = order (Just x) xs order (Just GT) (Just x : xs) | x /= LT = order (Just GT) xs order _ _ = Nothing in order (head os) os compareValueSets (ExplicitSet vs) (CartesianProduct vsets vc) = compareValueSets (ExplicitSet vs) (fromList (toList (CartesianProduct vsets vc))) compareValueSets (CartesianProduct vsets vc) (ExplicitSet vs) = flipOrder (compareValueSets (ExplicitSet vs) (CartesianProduct vsets vc)) compareValueSets (Powerset vs1) (Powerset vs2) = compareValueSets vs1 vs2 compareValueSets s1 (Powerset s2) = compareValueSets s1 (fromList (toList (Powerset s2))) compareValueSets (Powerset s1) s2 = flipOrder (compareValueSets s2 (Powerset s1)) compareValueSets s1 (AllMaps ks vs) = compareValueSets s1 (fromList (toList (AllMaps ks vs))) compareValueSets (AllMaps ks vs) s2 = flipOrder (compareValueSets s2 (AllMaps ks vs)) -- Anything else is incomparable compareValueSets _ _ = Nothing -- | Produces a ValueSet of the carteisan product of several ValueSets, -- using 'vc' to convert each sequence of values into a single value. cartesianProduct :: CartProductType -> [ValueSet] -> ValueSet cartesianProduct vc vss = CartesianProduct vss vc powerset :: ValueSet -> ValueSet powerset = Powerset -- | Returns the set of all sequences over the input set. This is infinite -- so we use a CompositeSet. allSequences :: ValueSet -> ValueSet allSequences s = AllSequences s allMaps :: ValueSet -> ValueSet -> ValueSet allMaps ks vs = AllMaps ks vs -- | The empty set emptySet :: ValueSet emptySet = ExplicitSet S.empty -- | Converts a list to a set fromList :: [Value] -> ValueSet fromList = ExplicitSet . S.fromList -- | Constructs a singleton set singleton :: Value -> ValueSet singleton = ExplicitSet . S.singleton -- | Converts a set to list. toList :: ValueSet -> [Value] toList (ExplicitSet s) = S.toList s toList (IntSetFrom lb) = map VInt [lb..] toList (CompositeSet ss) = F.msum (fmap toList ss) toList Integers = let merge (x:xs) ys = x:merge ys xs in map VInt $ merge [0..] [(-1),(-2)..] toList Processes = throwSourceError [cannotConvertProcessesToListMessage] toList (AllSequences vs) = if empty vs then [] else let itemsAsList :: [Value] itemsAsList = toList vs list :: Integer -> [Value] list 0 = [VList []] list n = concatMap (\x -> map (app x) (list (n-1))) itemsAsList where app :: Value -> Value -> Value app x (VList xs) = VList $ x:xs allSequences :: [Value] allSequences = concatMap list [0..] in allSequences toList (CartesianProduct vss ct) = let cp = UL.cartesianProduct (map toList vss) in case ct of CartTuple -> map tupleFromList cp CartDot -> map VDot cp toList (Powerset vs) = (map (VSet . fromList) . filterM (\x -> [True, False]) . toList) vs toList (AllMaps ks' vs') = let ks = toList (Powerset ks') vs = toList vs' -- | Creates all maps that have the given set as its domain makeMaps :: [Value] -> [Value] makeMaps [] = [VMap $ M.empty] makeMaps (k:ks) = map (\ [VMap m, v] -> VMap $ M.insert k v m) (UL.cartesianProduct [makeMaps ks, vs]) in concatMap (\ (VSet s) -> makeMaps (toList s)) ks toSeq :: ValueSet -> Sq.Seq Value toSeq (ExplicitSet s) = F.foldMap Sq.singleton s toSeq (IntSetFrom lb) = fmap VInt (Sq.fromList [lb..]) toSeq (CompositeSet ss) = F.msum (fmap toSeq ss) toSeq (AllSequences vs) = Sq.fromList (toList (AllSequences vs)) toSeq (CartesianProduct vss ct) = Sq.fromList (toList (CartesianProduct vss ct)) toSeq (Powerset vs) = Sq.fromList (toList (Powerset vs)) toSeq (AllMaps ks vs) = Sq.fromList (toList (AllMaps ks vs)) toSeq Integers = throwSourceError [cannotConvertIntegersToListMessage] toSeq Processes = throwSourceError [cannotConvertProcessesToListMessage] -- | Returns the value iff the set contains one item only. singletonValue :: ValueSet -> Maybe Value singletonValue s = case toList s of [x] -> Just x _ -> Nothing -- | Is the specified value a member of the set. member :: Value -> ValueSet -> Bool member v (ExplicitSet s) = S.member v s member (VInt i) Integers = True member (VInt i) (IntSetFrom lb) = i >= lb member v (CompositeSet ss) = F.or (fmap (member v) ss) -- FDR does actually try and given the correct value here. member (VProc p) Processes = True member (VList vs) (AllSequences s) = and (map (flip member s) vs) member (VDot vs) (CartesianProduct vss CartDot) = and (zipWith member vs vss) member (VTuple vs) (CartesianProduct vss CartTuple) = and (zipWith member (elems vs) vss) member (VSet s) (Powerset vs) = and (map (\v -> member v vs) (toList s)) member (VMap m) (AllMaps ks vs) = and (map (flip member ks) (map fst (M.toList m))) && and (map (flip member vs) (map snd (M.toList m))) member v s1 = throwSourceError [cannotCheckSetMembershipError v s1] -- | The cardinality of the set. Throws an error if the set is infinite. card :: ValueSet -> Integer card (ExplicitSet s) = toInteger (S.size s) card (CompositeSet ss) = F.sum (fmap card ss) card (CartesianProduct vss _) = product (map card vss) card (Powerset s) = 2^(card s) card (AllMaps ks vs) = -- For each key, we can either not map it to anything, or map it to one -- of the values (card vs + 1) ^ (card ks) card s = throwSourceError [cardOfInfiniteSetMessage s] -- | Is the specified set empty? empty :: ValueSet -> Bool empty (ExplicitSet s) = S.null s empty (CompositeSet ss) = F.and (fmap empty ss) empty (IntSetFrom lb) = False empty (AllSequences s) = empty s empty (CartesianProduct vss _) = or (map empty vss) empty Processes = False empty Integers = False empty (Powerset s) = False empty (AllMaps ks vs) = False -- | Replicated union. unions :: [ValueSet] -> ValueSet unions [] = emptySet unions vs = foldr1 union vs infiniteUnions :: [ValueSet] -> ValueSet infiniteUnions [vs] = vs infiniteUnions vs = let extract (CompositeSet s) = s extract s = Sq.singleton s in CompositeSet (F.msum (map extract vs)) -- | Replicated intersection. intersections :: [ValueSet] -> ValueSet intersections [] = emptySet intersections (v:vs) = foldr1 intersection vs -- | Union two sets throwing an error if it cannot be done in a way that will -- terminate. union :: ValueSet -> ValueSet -> ValueSet -- Process unions union _ Processes = Processes union Processes _ = Processes -- Integer unions union (IntSetFrom lb1) (IntSetFrom lb2) = IntSetFrom (min lb1 lb2) union _ Integers = Integers union Integers _ = Integers -- Explicit unions union (ExplicitSet s1) (ExplicitSet s2) = ExplicitSet (S.union s1 s2) union (CompositeSet s1) (CompositeSet s2) = CompositeSet (s1 Sq.>< s2) union (CompositeSet s1) s2 = CompositeSet (s2 Sq.<| s1) union s1 (CompositeSet s2) = CompositeSet (s1 Sq.<| s2) union (IntSetFrom lb) s = CompositeSet (Sq.fromList [IntSetFrom lb, s]) union s (IntSetFrom lb) = CompositeSet (Sq.fromList [IntSetFrom lb, s]) union (AllSequences s1) s2 = CompositeSet (Sq.fromList [AllSequences s1, s2]) union s2 (AllSequences s1) = CompositeSet (Sq.fromList [AllSequences s1, s2]) union (AllMaps k v) s2 = CompositeSet (Sq.fromList [AllMaps k v, s2]) union s2 (AllMaps k v) = CompositeSet (Sq.fromList [AllMaps k v, s2]) -- Otherwise, we force to an explicit set (this has better performance than -- always forming an explicit set) union s1 s2 = ExplicitSet $ S.union (S.fromList (toList s1)) (S.fromList (toList s2)) -- | Intersects two sets throwing an error if it cannot be done in a way that -- will terminate. intersection :: ValueSet -> ValueSet -> ValueSet -- Explicit intersections intersection (ExplicitSet s1) (ExplicitSet s2) = ExplicitSet (S.intersection s1 s2) -- Integer intersections intersection (IntSetFrom lb1) (IntSetFrom lb2) = IntSetFrom (max lb1 lb2) intersection Integers Integers = Integers intersection x Integers = x intersection Integers x = x -- Integer+ExplicitSet intersection (ExplicitSet s1) (IntSetFrom lb1) = let VInt ubs = S.findMax s1 VInt lbs = S.findMin s1 in if lbs >= lb1 then ExplicitSet s1 else ExplicitSet (S.intersection (S.fromList (map VInt [lbs..ubs])) s1) intersection (IntSetFrom lb1) (ExplicitSet s2) = intersection (ExplicitSet s2) (IntSetFrom lb1) -- Process intersection intersection Processes Processes = Processes intersection Processes x = x intersection x Processes = x -- Composite Sets intersection (CompositeSet ss) s = CompositeSet (fmap (intersection s) ss) intersection s (CompositeSet ss) = CompositeSet (fmap (intersection s) ss) -- Cartesian product and all sequences - here we simpy convert to a list and -- compare. intersection (CartesianProduct vss vc) s = intersection (fromList (toList (CartesianProduct vss vc))) s intersection s (CartesianProduct vss vc) = intersection (fromList (toList (CartesianProduct vss vc))) s intersection (AllSequences vs) s = intersection (fromList (toList (AllSequences vs))) s intersection s (AllSequences vs) = intersection (fromList (toList (AllSequences vs))) s intersection (AllMaps ks vs) s = intersection (fromList (toList (AllMaps ks vs))) s intersection s (AllMaps ks vs) = intersection (fromList (toList (AllMaps ks vs))) s intersection (Powerset s1) (Powerset s2) = Powerset (intersection s1 s2) intersection (Powerset s1) s2 = intersection (fromList (toList (Powerset s1))) s2 intersection s2 (Powerset s1) = intersection (fromList (toList (Powerset s1))) s2 difference :: ValueSet -> ValueSet -> ValueSet difference (ExplicitSet s1) (ExplicitSet s2) = ExplicitSet (S.difference s1 s2) difference (IntSetFrom lb1) (IntSetFrom lb2) = fromList (map VInt [lb1..(lb2-1)]) difference _ Integers = ExplicitSet S.empty difference (IntSetFrom lb1) (ExplicitSet s1) = let VInt ubs = S.findMax s1 VInt lbs = S.findMin s1 card = S.size s1 rangeSize = 1+(ubs-lbs) s1' = IntSetFrom lb1 s2' = ExplicitSet s1 in if fromIntegral rangeSize == card then -- is contiguous if lb1 == lbs then IntSetFrom (ubs+1) else throwSourceError [cannotDifferenceSetsMessage s1' s2'] else -- is not contiguous throwSourceError [cannotDifferenceSetsMessage s1' s2'] difference (ExplicitSet s1) (IntSetFrom lb1) = ExplicitSet (S.fromList [VInt i | VInt i <- S.toList s1, i < lb1]) difference (CompositeSet ss) s = CompositeSet (fmap (\s1 -> difference s1 s) ss) difference s (CompositeSet ss) = F.foldl difference s ss difference s1 s2 = difference (fromList (toList s1)) (fromList (toList s2)) valueSetToEventSet :: ValueSet -> EventSet valueSetToEventSet = eventSetFromList . map valueEventToEvent . toList -- | Attempts to decompose the set into a cartesian product, returning Nothing -- if it cannot. unDotProduct :: ValueSet -> Maybe [ValueSet] unDotProduct (CartesianProduct vs CartTuple) = return [CartesianProduct vs CartTuple] unDotProduct (CartesianProduct (s1:ss) CartDot) = -- This is reducible only if this set doesn't represent a set of datatype/ -- channel items. If this is the case recursively express as a CartDot -- though case singletonValue s1 of Just (VDataType _) -> return [CartesianProduct (s1:ss) CartDot] Just (VChannel _) -> return [CartesianProduct (s1:ss) CartDot] _ -> return (s1:ss) unDotProduct (AllSequences vs) = return [AllSequences vs] unDotProduct (AllMaps ks vs) = return [AllMaps ks vs] unDotProduct (IntSetFrom i1) = return [IntSetFrom i1] unDotProduct (Powerset s) = return [Powerset s] unDotProduct Integers = return [Integers] unDotProduct Processes = return [Processes] unDotProduct (CompositeSet ss) = do vs <- T.mapM unDotProduct ss let ok [_] = True ok _ = False ex [x] = x if F.and (fmap ok vs) then Just [CompositeSet (fmap ex vs)] else Nothing unDotProduct (ExplicitSet s) | S.null s = return [ExplicitSet s] unDotProduct (ExplicitSet s) = case head (S.toList s) of VDot _ -> Nothing _ -> Just [ExplicitSet s] fastUnDotCartProduct :: ValueSet -> Value -> Maybe [ValueSet] fastUnDotCartProduct (CartesianProduct s CartDot) _ = Just s fastUnDotCartProduct (CompositeSet ss) (VDot (h:vs)) = let sq = Sq.filter isInteresting ss isInteresting (CartesianProduct (hset:_) CartDot) = case singletonValue hset of Just h' | h == h' -> True _ -> False isInteresting _ = False in if Sq.null sq then Nothing else case Sq.index sq 0 of CartesianProduct s CartDot -> Just s _ -> Nothing fastUnDotCartProduct _ _ = Nothing
sashabu/libcspm
src/CSPM/Evaluator/ValueSet.hs
Haskell
bsd-3-clause
19,163
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances, TypeOperators, ScopedTypeVariables, NamedFieldPuns #-} {-# LANGUAGE GADTs, GeneralizedNewtypeDeriving, DeriveDataTypeable, RecordWildCards #-} -- | This module provides functions for calling command line programs, primarily -- 'command' and 'cmd'. As a simple example: -- -- @ -- 'command' [] \"gcc\" [\"-c\",myfile] -- @ -- -- The functions from this module are now available directly from "Development.Shake". -- You should only need to import this module if you are using the 'cmd' function in the 'IO' monad. module Development.Shake.Command( command, command_, cmd, cmd_, unit, CmdArgument(..), CmdArguments(..), IsCmdArgument(..), (:->), Stdout(..), StdoutTrim(..), Stderr(..), Stdouterr(..), Exit(..), Process(..), CmdTime(..), CmdLine(..), FSATrace(..), CmdResult, CmdString, CmdOption(..), addPath, addEnv, ) where import Data.Tuple.Extra import Control.Monad.Extra import Control.Monad.IO.Class import Control.Exception.Extra import Data.Char import Data.Either.Extra import Data.Foldable (toList) import Data.List.Extra import Data.List.NonEmpty (NonEmpty) import qualified Data.HashSet as Set import Data.Maybe import Data.Data import Data.Semigroup import System.Directory import qualified System.IO.Extra as IO import System.Environment import System.Exit import System.IO.Extra hiding (withTempFile, withTempDir) import System.Process import System.Info.Extra import System.Time.Extra import System.IO.Unsafe (unsafeInterleaveIO) import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy.Char8 as LBS import qualified Data.ByteString.UTF8 as UTF8 import General.Extra import General.Process import Prelude import Development.Shake.Internal.CmdOption import Development.Shake.Internal.Core.Action import Development.Shake.Internal.Core.Types hiding (Result) import Development.Shake.FilePath import Development.Shake.Internal.Options import Development.Shake.Internal.Rules.File import Development.Shake.Internal.Derived --------------------------------------------------------------------- -- ACTUAL EXECUTION -- | /Deprecated:/ Use 'AddPath'. This function will be removed in a future version. -- -- Add a prefix and suffix to the @$PATH@ environment variable. For example: -- -- @ -- opt <- 'addPath' [\"\/usr\/special\"] [] -- 'cmd' opt \"userbinary --version\" -- @ -- -- Would prepend @\/usr\/special@ to the current @$PATH@, and the command would pick -- @\/usr\/special\/userbinary@, if it exists. To add other variables see 'addEnv'. addPath :: MonadIO m => [String] -> [String] -> m CmdOption addPath pre post = do args <- liftIO getEnvironment let (path,other) = partition ((== "PATH") . (if isWindows then upper else id) . fst) args pure $ Env $ [("PATH",intercalate [searchPathSeparator] $ pre ++ post) | null path] ++ [(a,intercalate [searchPathSeparator] $ pre ++ [b | b /= ""] ++ post) | (a,b) <- path] ++ other -- | /Deprecated:/ Use 'AddEnv'. This function will be removed in a future version. -- -- Add a single variable to the environment. For example: -- -- @ -- opt <- 'addEnv' [(\"CFLAGS\",\"-O2\")] -- 'cmd' opt \"gcc -c main.c\" -- @ -- -- Would add the environment variable @$CFLAGS@ with value @-O2@. If the variable @$CFLAGS@ -- was already defined it would be overwritten. If you wish to modify @$PATH@ see 'addPath'. addEnv :: MonadIO m => [(String, String)] -> m CmdOption addEnv extra = do args <- liftIO getEnvironment pure $ Env $ extra ++ filter (\(a,_) -> a `notElem` map fst extra) args data Str = Str String | BS BS.ByteString | LBS LBS.ByteString | Unit deriving (Eq,Show) strTrim :: Str -> Str strTrim (Str x) = Str $ trim x strTrim (BS x) = BS $ fst $ BS.spanEnd isSpace $ BS.dropWhile isSpace x strTrim (LBS x) = LBS $ trimEnd $ LBS.dropWhile isSpace x where trimEnd x = case LBS.uncons x of Just (c, x2) | isSpace c -> trimEnd x2 _ -> x strTrim Unit = Unit data Result = ResultStdout Str | ResultStderr Str | ResultStdouterr Str | ResultCode ExitCode | ResultTime Double | ResultLine String | ResultProcess PID | ResultFSATrace [FSATrace FilePath] | ResultFSATraceBS [FSATrace BS.ByteString] deriving (Eq,Show) data PID = PID0 | PID ProcessHandle instance Eq PID where _ == _ = True instance Show PID where show PID0 = "PID0"; show _ = "PID" data Params = Params {funcName :: String ,opts :: [CmdOption] ,results :: [Result] ,prog :: String ,args :: [String] } deriving Show class MonadIO m => MonadTempDir m where runWithTempDir :: (FilePath -> m a) -> m a runWithTempFile :: (FilePath -> m a) -> m a instance MonadTempDir IO where runWithTempDir = IO.withTempDir runWithTempFile = IO.withTempFile instance MonadTempDir Action where runWithTempDir = withTempDir runWithTempFile = withTempFile --------------------------------------------------------------------- -- DEAL WITH Shell removeOptionShell :: MonadTempDir m => Params -- ^ Given the parameter -> (Params -> m a) -- ^ Call with the revised params, program name and command line -> m a removeOptionShell params@Params{..} call | Shell `elem` opts = do -- put our UserCommand first, as the last one wins, and ours is lowest priority let userCmdline = unwords $ prog : args params <- pure params{opts = UserCommand userCmdline : filter (/= Shell) opts} prog <- liftIO $ if isFSATrace params then copyFSABinary prog else pure prog let realCmdline = unwords $ prog : args if not isWindows then call params{prog = "/bin/sh", args = ["-c",realCmdline]} else -- On Windows the Haskell behaviour isn't that clean and is very fragile, so we try and do better. runWithTempDir $ \dir -> do let file = dir </> "s.bat" writeFile' file realCmdline call params{prog = "cmd.exe", args = ["/d/q/c",file]} | otherwise = call params --------------------------------------------------------------------- -- DEAL WITH FSATrace isFSATrace :: Params -> Bool isFSATrace Params{..} = any isResultFSATrace results || any isFSAOptions opts -- Mac disables tracing on system binaries, so we copy them over, yurk copyFSABinary :: FilePath -> IO FilePath copyFSABinary prog | not isMac = pure prog | otherwise = do progFull <- findExecutable prog case progFull of Just x | any (`isPrefixOf` x) ["/bin/","/usr/","/sbin/"] -> do -- The file is one of the ones we can't trace, so we make a copy of it in $TMP and run that -- We deliberately don't clean up this directory, since otherwise we spend all our time copying binaries over tmpdir <- getTemporaryDirectory let fake = tmpdir </> "fsatrace-fakes" ++ x -- x is absolute, so must use ++ unlessM (doesFileExist fake) $ do createDirectoryRecursive $ takeDirectory fake copyFile x fake pure fake _ -> pure prog removeOptionFSATrace :: MonadTempDir m => Params -- ^ Given the parameter -> (Params -> m [Result]) -- ^ Call with the revised params, program name and command line -> m [Result] removeOptionFSATrace params@Params{..} call | not $ isFSATrace params = call params | ResultProcess PID0 `elem` results = -- This is a bad state to get into, you could technically just ignore the tracing, but that's a bit dangerous liftIO $ errorIO "Asyncronous process execution combined with FSATrace is not support" | otherwise = runWithTempFile $ \file -> do liftIO $ writeFile file "" -- ensures even if we fail before fsatrace opens the file, we can still read it params <- liftIO $ fsaParams file params res <- call params{opts = UserCommand (showCommandForUser2 prog args) : filter (not . isFSAOptions) opts} fsaResBS <- liftIO $ parseFSA <$> BS.readFile file let fsaRes = map (fmap UTF8.toString) fsaResBS pure $ flip map res $ \case ResultFSATrace [] -> ResultFSATrace fsaRes ResultFSATraceBS [] -> ResultFSATraceBS fsaResBS x -> x where fsaFlags = lastDef "rwmdqt" [x | FSAOptions x <- opts] fsaParams file Params{..} = do prog <- copyFSABinary prog pure params{prog = "fsatrace", args = fsaFlags : file : "--" : prog : args } isFSAOptions FSAOptions{} = True isFSAOptions _ = False isResultFSATrace ResultFSATrace{} = True isResultFSATrace ResultFSATraceBS{} = True isResultFSATrace _ = False addFSAOptions :: String -> [CmdOption] -> [CmdOption] addFSAOptions x opts | any isFSAOptions opts = map f opts where f (FSAOptions y) = FSAOptions $ nubOrd $ y ++ x f x = x addFSAOptions x opts = FSAOptions x : opts -- | The results produced by @fsatrace@. All files will be absolute paths. -- You can get the results for a 'cmd' by requesting a value of type -- @['FSATrace']@. data FSATrace a = -- | Writing to a file FSAWrite a | -- | Reading from a file FSARead a | -- | Deleting a file FSADelete a | -- | Moving, arguments destination, then source FSAMove a a | -- | Querying\/stat on a file FSAQuery a | -- | Touching a file FSATouch a deriving (Show,Eq,Ord,Data,Typeable,Functor) -- | Parse the 'FSATrace' entries, ignoring anything you don't understand. parseFSA :: BS.ByteString -> [FSATrace BS.ByteString] parseFSA = mapMaybe (f . dropR) . BS.lines where -- deal with CRLF on Windows dropR x = case BS.unsnoc x of Just (x, '\r') -> x _ -> x f x | Just (k, x) <- BS.uncons x , Just ('|', x) <- BS.uncons x = case k of 'w' -> Just $ FSAWrite x 'r' -> Just $ FSARead x 'd' -> Just $ FSADelete x 'm' | (xs, ys) <- BS.break (== '|') x, Just ('|',ys) <- BS.uncons ys -> Just $ FSAMove xs ys 'q' -> Just $ FSAQuery x 't' -> Just $ FSATouch x _ -> Nothing | otherwise = Nothing --------------------------------------------------------------------- -- ACTION EXPLICIT OPERATION -- | Given explicit operations, apply the Action ones, like skip/trace/track/autodep commandExplicitAction :: Partial => Params -> Action [Result] commandExplicitAction oparams = do ShakeOptions{shakeCommandOptions,shakeRunCommands,shakeLint,shakeLintInside} <- getShakeOptions params@Params{..}<- pure $ oparams{opts = shakeCommandOptions ++ opts oparams} let skipper act = if null results && not shakeRunCommands then pure [] else act let verboser act = do let cwd = listToMaybe $ reverse [x | Cwd x <- opts] putVerbose $ maybe "" (\x -> "cd " ++ x ++ "; ") cwd ++ last (showCommandForUser2 prog args : [x | UserCommand x <- opts]) verb <- getVerbosity -- run quietly to suppress the tracer (don't want to print twice) (if verb >= Verbose then quietly else id) act let tracer act = do -- note: use the oparams - find a good tracing before munging it for shell stuff let msg = lastDef (defaultTraced oparams) [x | Traced x <- opts] if msg == "" then liftIO act else traced msg act let async = ResultProcess PID0 `elem` results let tracker act | AutoDeps `elem` opts = if async then liftIO $ errorIO "Can't use AutoDeps and asyncronous execution" else autodeps act | shakeLint == Just LintFSATrace && not async = fsalint act | otherwise = act params autodeps act = do ResultFSATrace pxs : res <- act params{opts = addFSAOptions "rwm" opts, results = ResultFSATrace [] : results} let written = Set.fromList $ [x | FSAMove x _ <- pxs] ++ [x | FSAWrite x <- pxs] -- If something both reads and writes to a file, it isn't eligible to be an autodeps xs <- liftIO $ filterM doesFileExist [x | FSARead x <- pxs, not $ x `Set.member` written] cwd <- liftIO getCurrentDirectory temp <- fixPaths cwd xs unsafeAllowApply $ need temp pure res fixPaths cwd xs = liftIO $ do xs<- pure $ map toStandard xs xs<- pure $ filter (\x -> any (`isPrefixOf` x) shakeLintInside) xs mapM (\x -> fromMaybe x <$> makeRelativeEx cwd x) xs fsalint act = do ResultFSATrace xs : res <- act params{opts = addFSAOptions "rwm" opts, results = ResultFSATrace [] : results} let reader (FSARead x) = Just x; reader _ = Nothing writer (FSAWrite x) = Just x; writer (FSAMove x _) = Just x; writer _ = Nothing existing f = liftIO . filterM doesFileExist . nubOrd . mapMaybe f cwd <- liftIO getCurrentDirectory trackRead =<< fixPaths cwd =<< existing reader xs trackWrite =<< fixPaths cwd =<< existing writer xs pure res skipper $ tracker $ \params -> verboser $ tracer $ commandExplicitIO params defaultTraced :: Params -> String defaultTraced Params{..} = takeBaseName $ if Shell `elem` opts then fst (word1 prog) else prog --------------------------------------------------------------------- -- IO EXPLICIT OPERATION -- | Given a very explicit set of CmdOption, translate them to a General.Process structure commandExplicitIO :: Partial => Params -> IO [Result] commandExplicitIO params = removeOptionShell params $ \params -> removeOptionFSATrace params $ \Params{..} -> do let (grabStdout, grabStderr) = both or $ unzip $ flip map results $ \case ResultStdout{} -> (True, False) ResultStderr{} -> (False, True) ResultStdouterr{} -> (True, True) _ -> (False, False) optEnv <- resolveEnv opts let optCwd = mergeCwd [x | Cwd x <- opts] let optStdin = flip mapMaybe opts $ \case Stdin x -> Just $ SrcString x StdinBS x -> Just $ SrcBytes x FileStdin x -> Just $ SrcFile x InheritStdin -> Just SrcInherit _ -> Nothing let optBinary = BinaryPipes `elem` opts let optAsync = ResultProcess PID0 `elem` results let optTimeout = listToMaybe $ reverse [x | Timeout x <- opts] let optWithStdout = lastDef False [x | WithStdout x <- opts] let optWithStderr = lastDef True [x | WithStderr x <- opts] let optFileStdout = [x | FileStdout x <- opts] let optFileStderr = [x | FileStderr x <- opts] let optEchoStdout = lastDef (not grabStdout && null optFileStdout) [x | EchoStdout x <- opts] let optEchoStderr = lastDef (not grabStderr && null optFileStderr) [x | EchoStderr x <- opts] let optRealCommand = showCommandForUser2 prog args let optUserCommand = lastDef optRealCommand [x | UserCommand x <- opts] let optCloseFds = CloseFileHandles `elem` opts let optProcessGroup = NoProcessGroup `notElem` opts let bufLBS f = do (a,b) <- buf $ LBS LBS.empty; pure (a, (\(LBS x) -> f x) <$> b) buf Str{} | optBinary = bufLBS (Str . LBS.unpack) buf Str{} = do x <- newBuffer; pure ([DestString x | not optAsync], Str . concat <$> readBuffer x) buf LBS{} = do x <- newBuffer; pure ([DestBytes x | not optAsync], LBS . LBS.fromChunks <$> readBuffer x) buf BS {} = bufLBS (BS . BS.concat . LBS.toChunks) buf Unit = pure ([], pure Unit) (dStdout, dStderr, resultBuild) :: ([[Destination]], [[Destination]], [Double -> ProcessHandle -> ExitCode -> IO Result]) <- fmap unzip3 $ forM results $ \case ResultCode _ -> pure ([], [], \_ _ ex -> pure $ ResultCode ex) ResultTime _ -> pure ([], [], \dur _ _ -> pure $ ResultTime dur) ResultLine _ -> pure ([], [], \_ _ _ -> pure $ ResultLine optUserCommand) ResultProcess _ -> pure ([], [], \_ pid _ -> pure $ ResultProcess $ PID pid) ResultStdout s -> do (a,b) <- buf s; pure (a , [], \_ _ _ -> fmap ResultStdout b) ResultStderr s -> do (a,b) <- buf s; pure ([], a , \_ _ _ -> fmap ResultStderr b) ResultStdouterr s -> do (a,b) <- buf s; pure (a , a , \_ _ _ -> fmap ResultStdouterr b) ResultFSATrace _ -> pure ([], [], \_ _ _ -> pure $ ResultFSATrace []) -- filled in elsewhere ResultFSATraceBS _ -> pure ([], [], \_ _ _ -> pure $ ResultFSATraceBS []) -- filled in elsewhere exceptionBuffer <- newBuffer po <- resolvePath ProcessOpts {poCommand = RawCommand prog args ,poCwd = optCwd, poEnv = optEnv, poTimeout = optTimeout ,poStdin = [SrcBytes LBS.empty | optBinary && not (null optStdin)] ++ optStdin ,poStdout = [DestEcho | optEchoStdout] ++ map DestFile optFileStdout ++ [DestString exceptionBuffer | optWithStdout && not optAsync] ++ concat dStdout ,poStderr = [DestEcho | optEchoStderr] ++ map DestFile optFileStderr ++ [DestString exceptionBuffer | optWithStderr && not optAsync] ++ concat dStderr ,poAsync = optAsync ,poCloseFds = optCloseFds ,poGroup = optProcessGroup } (dur,(pid,exit)) <- duration $ process po if exit == ExitSuccess || ResultCode ExitSuccess `elem` results then mapM (\f -> f dur pid exit) resultBuild else do exceptionBuffer <- readBuffer exceptionBuffer let captured = ["Stderr" | optWithStderr] ++ ["Stdout" | optWithStdout] cwd <- case optCwd of Nothing -> pure "" Just v -> do v <- canonicalizePath v `catchIO` const (pure v) pure $ "Current directory: " ++ v ++ "\n" liftIO $ errorIO $ "Development.Shake." ++ funcName ++ ", system command failed\n" ++ "Command line: " ++ optRealCommand ++ "\n" ++ (if optRealCommand /= optUserCommand then "Original command line: " ++ optUserCommand ++ "\n" else "") ++ cwd ++ "Exit code: " ++ show (case exit of ExitFailure i -> i; _ -> 0) ++ "\n" ++ if null captured then "Stderr not captured because WithStderr False was used\n" else if null exceptionBuffer then intercalate " and " captured ++ " " ++ (if length captured == 1 then "was" else "were") ++ " empty" else intercalate " and " captured ++ ":\n" ++ unlines (dropWhile null $ lines $ concat exceptionBuffer) mergeCwd :: [FilePath] -> Maybe FilePath mergeCwd [] = Nothing mergeCwd xs = Just $ foldl1 (</>) xs -- | Apply all environment operations, to produce a new environment to use. resolveEnv :: [CmdOption] -> IO (Maybe [(String, String)]) resolveEnv opts | null env, null addEnv, null addPath, null remEnv = pure Nothing | otherwise = Just . unique . tweakPath . (++ addEnv) . filter (flip notElem remEnv . fst) <$> if null env then getEnvironment else pure (concat env) where env = [x | Env x <- opts] addEnv = [(x,y) | AddEnv x y <- opts] remEnv = [x | RemEnv x <- opts] addPath = [(x,y) | AddPath x y <- opts] newPath mid = intercalate [searchPathSeparator] $ concat (reverse $ map fst addPath) ++ [mid | mid /= ""] ++ concatMap snd addPath isPath x = (if isWindows then upper else id) x == "PATH" tweakPath xs | not $ any (isPath . fst) xs = ("PATH", newPath "") : xs | otherwise = map (\(a,b) -> (a, if isPath a then newPath b else b)) xs unique = reverse . nubOrdOn (if isWindows then upper . fst else fst) . reverse -- | If the user specifies a custom $PATH, and not Shell, then try and resolve their prog ourselves. -- Tricky, because on Windows it doesn't look in the $PATH first. resolvePath :: ProcessOpts -> IO ProcessOpts resolvePath po | Just e <- poEnv po , Just (_, path) <- find ((==) "PATH" . (if isWindows then upper else id) . fst) e , RawCommand prog args <- poCommand po = do let progExe = if prog == prog -<.> exe then prog else prog <.> exe -- use unsafeInterleaveIO to allow laziness to skip the queries we don't use pathOld <- unsafeInterleaveIO $ fromMaybe "" <$> lookupEnv "PATH" old <- unsafeInterleaveIO $ findExecutable prog new <- unsafeInterleaveIO $ findExecutableWith (splitSearchPath path) progExe old2 <- unsafeInterleaveIO $ findExecutableWith (splitSearchPath pathOld) progExe switch<- pure $ case () of _ | path == pathOld -> False -- The state I can see hasn't changed | Nothing <- new -> False -- I have nothing to offer | Nothing <- old -> True -- I failed last time, so this must be an improvement | Just old <- old, Just new <- new, equalFilePath old new -> False -- no different | Just old <- old, Just old2 <- old2, equalFilePath old old2 -> True -- I could predict last time | otherwise -> False pure $ case new of Just new | switch -> po{poCommand = RawCommand new args} _ -> po resolvePath po = pure po -- | Given a list of directories, and a file name, return the complete path if you can find it. -- Like findExecutable, but with a custom PATH. findExecutableWith :: [FilePath] -> String -> IO (Maybe FilePath) findExecutableWith path x = flip firstJustM (map (</> x) path) $ \s -> ifM (doesFileExist s) (pure $ Just s) (pure Nothing) --------------------------------------------------------------------- -- FIXED ARGUMENT WRAPPER -- | Collect the @stdout@ of the process. -- If used, the @stdout@ will not be echoed to the terminal, unless you include 'EchoStdout'. -- The value type may be either 'String', or either lazy or strict 'ByteString'. -- -- Note that most programs end their output with a trailing newline, so calling -- @ghc --numeric-version@ will result in 'Stdout' of @\"6.8.3\\n\"@. If you want to automatically -- trim the resulting string, see 'StdoutTrim'. newtype Stdout a = Stdout {fromStdout :: a} -- | Like 'Stdout' but remove all leading and trailing whitespaces. newtype StdoutTrim a = StdoutTrim {fromStdoutTrim :: a} -- | Collect the @stderr@ of the process. -- If used, the @stderr@ will not be echoed to the terminal, unless you include 'EchoStderr'. -- The value type may be either 'String', or either lazy or strict 'ByteString'. newtype Stderr a = Stderr {fromStderr :: a} -- | Collect the @stdout@ and @stderr@ of the process. -- If used, the @stderr@ and @stdout@ will not be echoed to the terminal, unless you include 'EchoStdout' and 'EchoStderr'. -- The value type may be either 'String', or either lazy or strict 'ByteString'. newtype Stdouterr a = Stdouterr {fromStdouterr :: a} -- | Collect the 'ExitCode' of the process. -- If you do not collect the exit code, any 'ExitFailure' will cause an exception. newtype Exit = Exit {fromExit :: ExitCode} -- | Collect the 'ProcessHandle' of the process. -- If you do collect the process handle, the command will run asyncronously and the call to 'cmd' \/ 'command' -- will return as soon as the process is spawned. Any 'Stdout' \/ 'Stderr' captures will return empty strings. newtype Process = Process {fromProcess :: ProcessHandle} -- | Collect the time taken to execute the process. Can be used in conjunction with 'CmdLine' to -- write helper functions that print out the time of a result. -- -- @ -- timer :: ('CmdResult' r, MonadIO m) => (forall r . 'CmdResult' r => m r) -> m r -- timer act = do -- ('CmdTime' t, 'CmdLine' x, r) <- act -- liftIO $ putStrLn $ \"Command \" ++ x ++ \" took \" ++ show t ++ \" seconds\" -- pure r -- -- run :: IO () -- run = timer $ 'cmd' \"ghc --version\" -- @ newtype CmdTime = CmdTime {fromCmdTime :: Double} -- | Collect the command line used for the process. This command line will be approximate - -- suitable for user diagnostics, but not for direct execution. newtype CmdLine = CmdLine {fromCmdLine :: String} -- | The allowable 'String'-like values that can be captured. class CmdString a where cmdString :: (Str, Str -> a) instance CmdString () where cmdString = (Unit, \Unit -> ()) instance CmdString String where cmdString = (Str "", \(Str x) -> x) instance CmdString BS.ByteString where cmdString = (BS BS.empty, \(BS x) -> x) instance CmdString LBS.ByteString where cmdString = (LBS LBS.empty, \(LBS x) -> x) class Unit a instance {-# OVERLAPPING #-} Unit b => Unit (a -> b) instance {-# OVERLAPPABLE #-} a ~ () => Unit (m a) -- | A class for specifying what results you want to collect from a process. -- Values are formed of 'Stdout', 'Stderr', 'Exit' and tuples of those. class CmdResult a where -- Return a list of results (with the right type but dummy data) -- and a function to transform a populated set of results into a value cmdResult :: ([Result], [Result] -> a) instance CmdResult Exit where cmdResult = ([ResultCode ExitSuccess], \[ResultCode x] -> Exit x) instance CmdResult ExitCode where cmdResult = ([ResultCode ExitSuccess], \[ResultCode x] -> x) instance CmdResult Process where cmdResult = ([ResultProcess PID0], \[ResultProcess (PID x)] -> Process x) instance CmdResult ProcessHandle where cmdResult = ([ResultProcess PID0], \[ResultProcess (PID x)] -> x) instance CmdResult CmdLine where cmdResult = ([ResultLine ""], \[ResultLine x] -> CmdLine x) instance CmdResult CmdTime where cmdResult = ([ResultTime 0], \[ResultTime x] -> CmdTime x) instance CmdResult [FSATrace FilePath] where cmdResult = ([ResultFSATrace []], \[ResultFSATrace x] -> x) instance CmdResult [FSATrace BS.ByteString] where cmdResult = ([ResultFSATraceBS []], \[ResultFSATraceBS x] -> x) instance CmdString a => CmdResult (Stdout a) where cmdResult = let (a,b) = cmdString in ([ResultStdout a], \[ResultStdout x] -> Stdout $ b x) instance CmdString a => CmdResult (StdoutTrim a) where cmdResult = let (a,b) = cmdString in ([ResultStdout a], \[ResultStdout x] -> StdoutTrim $ b $ strTrim x) instance CmdString a => CmdResult (Stderr a) where cmdResult = let (a,b) = cmdString in ([ResultStderr a], \[ResultStderr x] -> Stderr $ b x) instance CmdString a => CmdResult (Stdouterr a) where cmdResult = let (a,b) = cmdString in ([ResultStdouterr a], \[ResultStdouterr x] -> Stdouterr $ b x) instance CmdResult () where cmdResult = ([], \[] -> ()) instance (CmdResult x1, CmdResult x2) => CmdResult (x1,x2) where cmdResult = (a1++a2, \rs -> let (r1,r2) = splitAt (length a1) rs in (b1 r1, b2 r2)) where (a1,b1) = cmdResult (a2,b2) = cmdResult cmdResultWith :: forall b c. CmdResult b => (b -> c) -> ([Result], [Result] -> c) cmdResultWith f = second (f .) cmdResult instance (CmdResult x1, CmdResult x2, CmdResult x3) => CmdResult (x1,x2,x3) where cmdResult = cmdResultWith $ \(a,(b,c)) -> (a,b,c) instance (CmdResult x1, CmdResult x2, CmdResult x3, CmdResult x4) => CmdResult (x1,x2,x3,x4) where cmdResult = cmdResultWith $ \(a,(b,c,d)) -> (a,b,c,d) instance (CmdResult x1, CmdResult x2, CmdResult x3, CmdResult x4, CmdResult x5) => CmdResult (x1,x2,x3,x4,x5) where cmdResult = cmdResultWith $ \(a,(b,c,d,e)) -> (a,b,c,d,e) -- | Execute a system command. Before running 'command' make sure you 'Development.Shake.need' any files -- that are used by the command. -- -- This function takes a list of options (often just @[]@, see 'CmdOption' for the available -- options), the name of the executable (either a full name, or a program on the @$PATH@) and -- a list of arguments. The result is often @()@, but can be a tuple containg any of 'Stdout', -- 'Stderr' and 'Exit'. Some examples: -- -- @ -- 'command_' [] \"gcc\" [\"-c\",\"myfile.c\"] -- compile a file, throwing an exception on failure -- 'Exit' c <- 'command' [] \"gcc\" [\"-c\",myfile] -- run a command, recording the exit code -- ('Exit' c, 'Stderr' err) <- 'command' [] \"gcc\" [\"-c\",\"myfile.c\"] -- run a command, recording the exit code and error output -- 'Stdout' out <- 'command' [] \"gcc\" [\"-MM\",\"myfile.c\"] -- run a command, recording the output -- 'command_' ['Cwd' \"generated\"] \"gcc\" [\"-c\",myfile] -- run a command in a directory -- @ -- -- Unless you retrieve the 'ExitCode' using 'Exit', any 'ExitFailure' will throw an error, including -- the 'Stderr' in the exception message. If you capture the 'Stdout' or 'Stderr', that stream will not be echoed to the console, -- unless you use the option 'EchoStdout' or 'EchoStderr'. -- -- If you use 'command' inside a @do@ block and do not use the result, you may get a compile-time error about being -- unable to deduce 'CmdResult'. To avoid this error, use 'command_'. -- -- By default the @stderr@ stream will be captured for use in error messages, and also echoed. To only echo -- pass @'WithStderr' 'False'@, which causes no streams to be captured by Shake, and certain programs (e.g. @gcc@) -- to detect they are running in a terminal. command :: (Partial, CmdResult r) => [CmdOption] -> String -> [String] -> Action r command opts x xs = withFrozenCallStack $ b <$> commandExplicitAction (Params "command" opts a x xs) where (a,b) = cmdResult -- | A version of 'command' where you do not require any results, used to avoid errors about being unable -- to deduce 'CmdResult'. command_ :: Partial => [CmdOption] -> String -> [String] -> Action () command_ opts x xs = withFrozenCallStack $ void $ commandExplicitAction (Params "command_" opts [] x xs) --------------------------------------------------------------------- -- VARIABLE ARGUMENT WRAPPER -- | A type annotation, equivalent to the first argument, but in variable argument contexts, -- gives a clue as to what return type is expected (not actually enforced). type a :-> t = a -- | Build or execute a system command. Before using 'cmd' to run a command, make sure you 'Development.Shake.need' any files -- that are used by the command. -- -- * @String@ arguments are treated as a list of whitespace separated arguments. -- -- * @[String]@ arguments are treated as a list of literal arguments. -- -- * 'CmdOption' arguments are used as options. -- -- * 'CmdArgument' arguments, which can be built by 'cmd' itself, are spliced into the containing command. -- -- Typically only string literals should be passed as @String@ arguments. When using variables -- prefer @[myvar]@ so that if @myvar@ contains spaces they are properly escaped. -- -- As some examples, here are some calls, and the resulting command string: -- -- @ -- 'cmd_' \"git log --pretty=\" \"oneline\" -- git log --pretty= oneline -- 'cmd_' \"git log --pretty=\" [\"oneline\"] -- git log --pretty= oneline -- 'cmd_' \"git log\" (\"--pretty=\" ++ \"oneline\") -- git log --pretty=oneline -- 'cmd_' \"git log\" (\"--pretty=\" ++ \"one line\") -- git log --pretty=one line -- 'cmd_' \"git log\" [\"--pretty=\" ++ \"one line\"] -- git log "--pretty=one line" -- @ -- -- More examples, including return values, see this translation of the examples given for the 'command' function: -- -- @ -- 'cmd_' \"gcc -c myfile.c\" -- compile a file, throwing an exception on failure -- 'Exit' c <- 'cmd' \"gcc -c\" [myfile] -- run a command, recording the exit code -- ('Exit' c, 'Stderr' err) <- 'cmd' \"gcc -c myfile.c\" -- run a command, recording the exit code and error output -- 'Stdout' out <- 'cmd' \"gcc -MM myfile.c\" -- run a command, recording the output -- 'cmd' ('Cwd' \"generated\") \"gcc -c\" [myfile] :: 'Action' () -- run a command in a directory -- -- let gccCommand = 'cmd' \"gcc -c\" :: 'CmdArgument' -- build a sub-command. 'cmd' can return 'CmdArgument' values as well as execute commands -- cmd ('Cwd' \"generated\") gccCommand [myfile] -- splice that command into a greater command -- @ -- -- If you use 'cmd' inside a @do@ block and do not use the result, you may get a compile-time error about being -- unable to deduce 'CmdResult'. To avoid this error, use 'cmd_'. If you enable @OverloadedStrings@ or @OverloadedLists@ -- you may have to give type signatures to the arguments, or use the more constrained 'command' instead. -- -- The 'cmd' function can also be run in the 'IO' monad, but then 'Traced' is ignored and command lines are not echoed. -- As an example: -- -- @ -- 'cmd' ('Cwd' \"generated\") 'Shell' \"gcc -c myfile.c\" :: IO () -- @ cmd :: (Partial, CmdArguments args) => args :-> Action r cmd = withFrozenCallStack $ cmdArguments mempty -- | See 'cmd'. Same as 'cmd' except with a unit result. -- 'cmd' is to 'cmd_' as 'command' is to 'command_'. cmd_ :: (Partial, CmdArguments args, Unit args) => args :-> Action () cmd_ = withFrozenCallStack cmd -- | The arguments to 'cmd' - see 'cmd' for examples and semantics. newtype CmdArgument = CmdArgument [Either CmdOption String] deriving (Eq, Semigroup, Monoid, Show) -- | The arguments to 'cmd' - see 'cmd' for examples and semantics. class CmdArguments t where -- | Arguments to cmd cmdArguments :: Partial => CmdArgument -> t instance (IsCmdArgument a, CmdArguments r) => CmdArguments (a -> r) where cmdArguments xs x = cmdArguments $ xs `mappend` toCmdArgument x instance CmdResult r => CmdArguments (Action r) where cmdArguments (CmdArgument x) = case partitionEithers x of (opts, x:xs) -> let (a,b) = cmdResult in b <$> commandExplicitAction (Params "cmd" opts a x xs) _ -> error "Error, no executable or arguments given to Development.Shake.cmd" instance CmdResult r => CmdArguments (IO r) where cmdArguments (CmdArgument x) = case partitionEithers x of (opts, x:xs) -> let (a,b) = cmdResult in b <$> commandExplicitIO (Params "cmd" opts a x xs) _ -> error "Error, no executable or arguments given to Development.Shake.cmd" instance CmdArguments CmdArgument where cmdArguments = id -- | Class to convert an a to a CmdArgument class IsCmdArgument a where -- | Conversion to a CmdArgument toCmdArgument :: a -> CmdArgument instance IsCmdArgument () where toCmdArgument = mempty instance IsCmdArgument String where toCmdArgument = CmdArgument . map Right . words instance IsCmdArgument [String] where toCmdArgument = CmdArgument . map Right instance IsCmdArgument (NonEmpty String) where toCmdArgument = toCmdArgument . toList instance IsCmdArgument CmdOption where toCmdArgument = CmdArgument . pure . Left instance IsCmdArgument [CmdOption] where toCmdArgument = CmdArgument . map Left instance IsCmdArgument CmdArgument where toCmdArgument = id instance IsCmdArgument a => IsCmdArgument (Maybe a) where toCmdArgument = maybe mempty toCmdArgument --------------------------------------------------------------------- -- UTILITIES -- A better version of showCommandForUser, which doesn't escape so much on Windows showCommandForUser2 :: FilePath -> [String] -> String showCommandForUser2 cmd args = unwords $ map (\x -> if safe x then x else showCommandForUser x []) $ cmd : args where safe xs = xs /= "" && not (any bad xs) bad x = isSpace x || (x == '\\' && not isWindows) || x `elem` ("\"\'" :: String)
ndmitchell/shake
src/Development/Shake/Command.hs
Haskell
bsd-3-clause
35,626
{-# LINE 1 "Control.Concurrent.hs" #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , MagicHash , UnboxedTuples , ScopedTypeVariables , RankNTypes #-} {-# OPTIONS_GHC -Wno-deprecations #-} -- kludge for the Control.Concurrent.QSem, Control.Concurrent.QSemN -- and Control.Concurrent.SampleVar imports. ----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (concurrency) -- -- A common interface to a collection of useful concurrency -- abstractions. -- ----------------------------------------------------------------------------- module Control.Concurrent ( -- * Concurrent Haskell -- $conc_intro -- * Basic concurrency operations ThreadId, myThreadId, forkIO, forkFinally, forkIOWithUnmask, killThread, throwTo, -- ** Threads with affinity forkOn, forkOnWithUnmask, getNumCapabilities, setNumCapabilities, threadCapability, -- * Scheduling -- $conc_scheduling yield, -- ** Blocking -- $blocking -- ** Waiting threadDelay, threadWaitRead, threadWaitWrite, threadWaitReadSTM, threadWaitWriteSTM, -- * Communication abstractions module Control.Concurrent.MVar, module Control.Concurrent.Chan, module Control.Concurrent.QSem, module Control.Concurrent.QSemN, -- * Bound Threads -- $boundthreads rtsSupportsBoundThreads, forkOS, forkOSWithUnmask, isCurrentThreadBound, runInBoundThread, runInUnboundThread, -- * Weak references to ThreadIds mkWeakThreadId, -- * GHC's implementation of concurrency -- |This section describes features specific to GHC's -- implementation of Concurrent Haskell. -- ** Haskell threads and Operating System threads -- $osthreads -- ** Terminating the program -- $termination -- ** Pre-emption -- $preemption -- ** Deadlock -- $deadlock ) where import Control.Exception.Base as Exception import GHC.Conc hiding (threadWaitRead, threadWaitWrite, threadWaitReadSTM, threadWaitWriteSTM) import GHC.IO ( unsafeUnmask, catchException ) import GHC.IORef ( newIORef, readIORef, writeIORef ) import GHC.Base import System.Posix.Types ( Fd ) import Foreign.StablePtr import Foreign.C.Types import qualified GHC.Conc import Control.Concurrent.MVar import Control.Concurrent.Chan import Control.Concurrent.QSem import Control.Concurrent.QSemN {- $conc_intro The concurrency extension for Haskell is described in the paper /Concurrent Haskell/ <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>. Concurrency is \"lightweight\", which means that both thread creation and context switching overheads are extremely low. Scheduling of Haskell threads is done internally in the Haskell runtime system, and doesn't make use of any operating system-supplied thread packages. However, if you want to interact with a foreign library that expects your program to use the operating system-supplied thread package, you can do so by using 'forkOS' instead of 'forkIO'. Haskell threads can communicate via 'MVar's, a kind of synchronised mutable variable (see "Control.Concurrent.MVar"). Several common concurrency abstractions can be built from 'MVar's, and these are provided by the "Control.Concurrent" library. In GHC, threads may also communicate via exceptions. -} {- $conc_scheduling Scheduling may be either pre-emptive or co-operative, depending on the implementation of Concurrent Haskell (see below for information related to specific compilers). In a co-operative system, context switches only occur when you use one of the primitives defined in this module. This means that programs such as: > main = forkIO (write 'a') >> write 'b' > where write c = putChar c >> write c will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@, instead of some random interleaving of @a@s and @b@s. In practice, cooperative multitasking is sufficient for writing simple graphical user interfaces. -} {- $blocking Different Haskell implementations have different characteristics with regard to which operations block /all/ threads. Using GHC without the @-threaded@ option, all foreign calls will block all other Haskell threads in the system, although I\/O operations will not. With the @-threaded@ option, only foreign calls with the @unsafe@ attribute will block all other threads. -} -- | Fork a thread and call the supplied function when the thread is about -- to terminate, with an exception or a returned value. The function is -- called with asynchronous exceptions masked. -- -- > forkFinally action and_then = -- > mask $ \restore -> -- > forkIO $ try (restore action) >>= and_then -- -- This function is useful for informing the parent when a child -- terminates, for example. -- -- @since 4.6.0.0 forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkFinally action and_then = mask $ \restore -> forkIO $ try (restore action) >>= and_then -- --------------------------------------------------------------------------- -- Bound Threads {- $boundthreads #boundthreads# Support for multiple operating system threads and bound threads as described below is currently only available in the GHC runtime system if you use the /-threaded/ option when linking. Other Haskell systems do not currently support multiple operating system threads. A bound thread is a haskell thread that is /bound/ to an operating system thread. While the bound thread is still scheduled by the Haskell run-time system, the operating system thread takes care of all the foreign calls made by the bound thread. To a foreign library, the bound thread will look exactly like an ordinary operating system thread created using OS functions like @pthread_create@ or @CreateThread@. Bound threads can be created using the 'forkOS' function below. All foreign exported functions are run in a bound thread (bound to the OS thread that called the function). Also, the @main@ action of every Haskell program is run in a bound thread. Why do we need this? Because if a foreign library is called from a thread created using 'forkIO', it won't have access to any /thread-local state/ - state variables that have specific values for each OS thread (see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some libraries (OpenGL, for example) will not work from a thread created using 'forkIO'. They work fine in threads created using 'forkOS' or when called from @main@ or from a @foreign export@. In terms of performance, 'forkOS' (aka bound) threads are much more expensive than 'forkIO' (aka unbound) threads, because a 'forkOS' thread is tied to a particular OS thread, whereas a 'forkIO' thread can be run by any OS thread. Context-switching between a 'forkOS' thread and a 'forkIO' thread is many times more expensive than between two 'forkIO' threads. Note in particular that the main program thread (the thread running @Main.main@) is always a bound thread, so for good concurrency performance you should ensure that the main thread is not doing repeated communication with other threads in the system. Typically this means forking subthreads to do the work using 'forkIO', and waiting for the results in the main thread. -} -- | 'True' if bound threads are supported. -- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound' -- will always return 'False' and both 'forkOS' and 'runInBoundThread' will -- fail. foreign import ccall rtsSupportsBoundThreads :: Bool {- | Like 'forkIO', this sparks off a new thread to run the 'IO' computation passed as the first argument, and returns the 'ThreadId' of the newly created thread. However, 'forkOS' creates a /bound/ thread, which is necessary if you need to call foreign (non-Haskell) libraries that make use of thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads"). Using 'forkOS' instead of 'forkIO' makes no difference at all to the scheduling behaviour of the Haskell runtime system. It is a common misconception that you need to use 'forkOS' instead of 'forkIO' to avoid blocking all the Haskell threads when making a foreign call; this isn't the case. To allow foreign calls to be made without blocking all the Haskell threads (with GHC), it is only necessary to use the @-threaded@ option when linking your program, and to make sure the foreign import is not marked @unsafe@. -} forkOS :: IO () -> IO ThreadId foreign export ccall forkOS_entry :: StablePtr (IO ()) -> IO () foreign import ccall "forkOS_entry" forkOS_entry_reimported :: StablePtr (IO ()) -> IO () forkOS_entry :: StablePtr (IO ()) -> IO () forkOS_entry stableAction = do action <- deRefStablePtr stableAction action foreign import ccall forkOS_createThread :: StablePtr (IO ()) -> IO CInt failNonThreaded :: IO a failNonThreaded = fail $ "RTS doesn't support multiple OS threads " ++"(use ghc -threaded when linking)" forkOS action0 | rtsSupportsBoundThreads = do mv <- newEmptyMVar b <- Exception.getMaskingState let -- async exceptions are masked in the child if they are masked -- in the parent, as for forkIO (see #1048). forkOS_createThread -- creates a thread with exceptions masked by default. action1 = case b of Unmasked -> unsafeUnmask action0 MaskedInterruptible -> action0 MaskedUninterruptible -> uninterruptibleMask_ action0 action_plus = catchException action1 childHandler entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus) err <- forkOS_createThread entry when (err /= 0) $ fail "Cannot create OS thread." tid <- takeMVar mv freeStablePtr entry return tid | otherwise = failNonThreaded -- | Like 'forkIOWithUnmask', but the child thread is a bound thread, -- as with 'forkOS'. forkOSWithUnmask :: ((forall a . IO a -> IO a) -> IO ()) -> IO ThreadId forkOSWithUnmask io = forkOS (io unsafeUnmask) -- | Returns 'True' if the calling thread is /bound/, that is, if it is -- safe to use foreign libraries that rely on thread-local state from the -- calling thread. isCurrentThreadBound :: IO Bool isCurrentThreadBound = IO $ \ s# -> case isCurrentThreadBound# s# of (# s2#, flg #) -> (# s2#, isTrue# (flg /=# 0#) #) {- | Run the 'IO' computation passed as the first argument. If the calling thread is not /bound/, a bound thread is created temporarily. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. You can wrap a series of foreign function calls that rely on thread-local state with @runInBoundThread@ so that you can use them without knowing whether the current thread is /bound/. -} runInBoundThread :: IO a -> IO a runInBoundThread action | rtsSupportsBoundThreads = do bound <- isCurrentThreadBound if bound then action else do ref <- newIORef undefined let action_plus = Exception.try action >>= writeIORef ref bracket (newStablePtr action_plus) freeStablePtr (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref) >>= unsafeResult | otherwise = failNonThreaded {- | Run the 'IO' computation passed as the first argument. If the calling thread is /bound/, an unbound thread is created temporarily using 'forkIO'. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. Use this function /only/ in the rare case that you have actually observed a performance loss due to the use of bound threads. A program that doesn't need its main thread to be bound and makes /heavy/ use of concurrency (e.g. a web server), might want to wrap its @main@ action in @runInUnboundThread@. Note that exceptions which are thrown to the current thread are thrown in turn to the thread that is executing the given computation. This ensures there's always a way of killing the forked thread. -} runInUnboundThread :: IO a -> IO a runInUnboundThread action = do bound <- isCurrentThreadBound if bound then do mv <- newEmptyMVar mask $ \restore -> do tid <- forkIO $ Exception.try (restore action) >>= putMVar mv let wait = takeMVar mv `catchException` \(e :: SomeException) -> Exception.throwTo tid e >> wait wait >>= unsafeResult else action unsafeResult :: Either SomeException a -> IO a unsafeResult = either Exception.throwIO return -- --------------------------------------------------------------------------- -- threadWaitRead/threadWaitWrite -- | Block the current thread until data is available to read on the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitRead', use -- 'GHC.Conc.closeFdWith'. threadWaitRead :: Fd -> IO () threadWaitRead fd = GHC.Conc.threadWaitRead fd -- | Block the current thread until data can be written to the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitWrite', use -- 'GHC.Conc.closeFdWith'. threadWaitWrite :: Fd -> IO () threadWaitWrite fd = GHC.Conc.threadWaitWrite fd -- | Returns an STM action that can be used to wait for data -- to read from a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. -- -- @since 4.7.0.0 threadWaitReadSTM :: Fd -> IO (STM (), IO ()) threadWaitReadSTM fd = GHC.Conc.threadWaitReadSTM fd -- | Returns an STM action that can be used to wait until data -- can be written to a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. -- -- @since 4.7.0.0 threadWaitWriteSTM :: Fd -> IO (STM (), IO ()) threadWaitWriteSTM fd = GHC.Conc.threadWaitWriteSTM fd -- --------------------------------------------------------------------------- -- More docs {- $osthreads #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and are managed entirely by the GHC runtime. Typically Haskell threads are an order of magnitude or two more efficient (in terms of both time and space) than operating system threads. The downside of having lightweight threads is that only one can run at a time, so if one thread blocks in a foreign call, for example, the other threads cannot continue. The GHC runtime works around this by making use of full OS threads where necessary. When the program is built with the @-threaded@ option (to link against the multithreaded version of the runtime), a thread making a @safe@ foreign call will not block the other threads in the system; another OS thread will take over running Haskell threads until the original call returns. The runtime maintains a pool of these /worker/ threads so that multiple Haskell threads can be involved in external calls simultaneously. The "System.IO" library manages multiplexing in its own way. On Windows systems it uses @safe@ foreign calls to ensure that threads doing I\/O operations don't block the whole runtime, whereas on Unix systems all the currently blocked I\/O requests are managed by a single thread (the /IO manager thread/) using a mechanism such as @epoll@ or @kqueue@, depending on what is provided by the host operating system. The runtime will run a Haskell thread using any of the available worker OS threads. If you need control over which particular OS thread is used to run a given Haskell thread, perhaps because you need to call a foreign library that uses OS-thread-local state, then you need bound threads (see "Control.Concurrent#boundthreads"). If you don't use the @-threaded@ option, then the runtime does not make use of multiple OS threads. Foreign calls will block all other running Haskell threads until the call returns. The "System.IO" library still does multiplexing, so there can be multiple threads doing I\/O, and this is handled internally by the runtime using @select@. -} {- $termination In a standalone GHC program, only the main thread is required to terminate in order for the process to terminate. Thus all other forked threads will simply terminate at the same time as the main thread (the terminology for this kind of behaviour is \"daemonic threads\"). If you want the program to wait for child threads to finish before exiting, you need to program this yourself. A simple mechanism is to have each child thread write to an 'MVar' when it completes, and have the main thread wait on all the 'MVar's before exiting: > myForkIO :: IO () -> IO (MVar ()) > myForkIO io = do > mvar <- newEmptyMVar > forkFinally io (\_ -> putMVar mvar ()) > return mvar Note that we use 'forkFinally' to make sure that the 'MVar' is written to even if the thread dies or is killed for some reason. A better method is to keep a global list of all child threads which we should wait for at the end of the program: > children :: MVar [MVar ()] > children = unsafePerformIO (newMVar []) > > waitForChildren :: IO () > waitForChildren = do > cs <- takeMVar children > case cs of > [] -> return () > m:ms -> do > putMVar children ms > takeMVar m > waitForChildren > > forkChild :: IO () -> IO ThreadId > forkChild io = do > mvar <- newEmptyMVar > childs <- takeMVar children > putMVar children (mvar:childs) > forkFinally io (\_ -> putMVar mvar ()) > > main = > later waitForChildren $ > ... The main thread principle also applies to calls to Haskell from outside, using @foreign export@. When the @foreign export@ed function is invoked, it starts a new main thread, and it returns when this main thread terminates. If the call causes new threads to be forked, they may remain in the system after the @foreign export@ed function has returned. -} {- $preemption GHC implements pre-emptive multitasking: the execution of threads are interleaved in a random fashion. More specifically, a thread may be pre-empted whenever it allocates some memory, which unfortunately means that tight loops which do no allocation tend to lock out other threads (this only seems to happen with pathological benchmark-style code, however). The rescheduling timer runs on a 20ms granularity by default, but this may be altered using the @-i\<n\>@ RTS option. After a rescheduling \"tick\" the running thread is pre-empted as soon as possible. One final note: the @aaaa@ @bbbb@ example may not work too well on GHC (see Scheduling, above), due to the locking on a 'System.IO.Handle'. Only one thread may hold the lock on a 'System.IO.Handle' at any one time, so if a reschedule happens while a thread is holding the lock, the other thread won't be able to run. The upshot is that the switch from @aaaa@ to @bbbbb@ happens infrequently. It can be improved by lowering the reschedule tick period. We also have a patch that causes a reschedule whenever a thread waiting on a lock is woken up, but haven't found it to be useful for anything other than this example :-) -} {- $deadlock GHC attempts to detect when threads are deadlocked using the garbage collector. A thread that is not reachable (cannot be found by following pointers from live objects) must be deadlocked, and in this case the thread is sent an exception. The exception is either 'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM', 'NonTermination', or 'Deadlock', depending on the way in which the thread is deadlocked. Note that this feature is intended for debugging, and should not be relied on for the correct operation of your program. There is no guarantee that the garbage collector will be accurate enough to detect your deadlock, and no guarantee that the garbage collector will run in a timely enough manner. Basically, the same caveats as for finalizers apply to deadlock detection. There is a subtle interaction between deadlock detection and finalizers (as created by 'Foreign.Concurrent.newForeignPtr' or the functions in "System.Mem.Weak"): if a thread is blocked waiting for a finalizer to run, then the thread will be considered deadlocked and sent an exception. So preferably don't do this, but if you have no alternative then it is possible to prevent the thread from being considered deadlocked by making a 'StablePtr' pointing to it. Don't forget to release the 'StablePtr' later with 'freeStablePtr'. -}
phischu/fragnix
builtins/base/Control.Concurrent.hs
Haskell
bsd-3-clause
21,926
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} ------------------------------------------------------------------------------------- -- | -- Copyright : (c) Hans Hoglund 2012-2014 -- -- License : BSD-style -- -- Maintainer : hans@hanshoglund.se -- Stability : experimental -- Portability : non-portable (TF,GNTD) -- -- Provides key signature meta-data. -- ------------------------------------------------------------------------------------- module Music.Score.Meta.Key ( -- * Key signature type Fifths, KeySignature, key, isMajorKey, isMinorKey, -- * Adding key signatures to scores keySignature, keySignatureDuring, -- * Extracting key signatures withKeySignature, ) where import Control.Lens (view) import Control.Monad.Plus import Data.Foldable (Foldable) import qualified Data.Foldable as F import qualified Data.List as List import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Data.Semigroup import Data.Set (Set) import qualified Data.Set as Set import Data.String import Data.Traversable (Traversable) import qualified Data.Traversable as T import Data.Typeable import Music.Pitch.Literal import Music.Score.Meta import Music.Score.Part import Music.Score.Pitch import Music.Score.Internal.Util import Music.Time import Music.Time.Reactive newtype Fifths = Fifths Integer deriving (Eq, Ord, Num, Enum, Integral, Real) instance IsPitch Fifths where fromPitch (PitchL (d, fromMaybe 0 -> c, _)) = case (d,c) of (0,-1) -> (-7) (0, 0) -> 0 (0, 1) -> 7 (1,-1) -> (-5) (1, 0) -> 2 (1, 1) -> 9 (2,-1) -> (-3) (2, 0) -> 4 (2, 1) -> 11 (3,-1) -> (-8) (3, 0) -> (-1) (3, 1) -> 6 (4,-1) -> (-6) (4, 0) -> 1 (4, 1) -> 8 (5,-1) -> (-4) (5, 0) -> 3 (5, 1) -> 10 (6,-1) -> (-2) (6, 0) -> 5 (6, 1) -> 12 _ -> error "Strange number of Fifths" -- | A key signature, represented by number of fifths from C and mode. newtype KeySignature = KeySignature (Fifths, Bool) deriving (Eq, Ord, Typeable) -- | Create a major or minor signature. key :: Fifths -> Bool -> KeySignature key fifths mode = KeySignature (fifths, mode) isMajorKey :: KeySignature -> Bool isMajorKey (KeySignature (_,x)) = x isMinorKey :: KeySignature -> Bool isMinorKey = not . isMajorKey -- | Set the key signature of the given score. keySignature :: (HasMeta a, HasPosition a) => KeySignature -> a -> a keySignature c x = keySignatureDuring (_era x) c x -- | Set the key signature of the given part of a score. keySignatureDuring :: HasMeta a => Span -> KeySignature -> a -> a keySignatureDuring s c = addMetaNote $ view event (s, (Option $ Just $ Last c)) -- | Extract all key signatures from the given score, using the given default key signature. withKeySignature :: KeySignature -> (KeySignature -> Score a -> Score a) -> Score a -> Score a withKeySignature def f = withMeta (f . fromMaybe def . fmap getLast . getOption)
FranklinChen/music-score
src/Music/Score/Meta/Key.hs
Haskell
bsd-3-clause
3,917
{-# LANGUAGE LambdaCase #-} {-| Module : Lib Description : Lib's main module This is a haddock comment describing your library For more information on how to write Haddock comments check the user guide: <https://www.haskell.org/haddock/doc/html/index.html> -} module Lib ( slaskellbot ) where import Control.Concurrent import Control.Concurrent.STM import Control.Monad import Control.Monad.IO.Class import Data.Maybe (isJust) import qualified Data.Text as T import Parser as P import qualified Plugin.Dice as Dice import qualified Plugin.Jira as Jira import Text.Megaparsec (parseMaybe) import Types import Web.Slack hiding (Event) import Web.Slack.Handle (SlackHandle, withSlackHandle) import Web.Slack.Monad (monadicToHandled) pluginHandlers :: [BotResponse] pluginHandlers = [ Jira.respond, Dice.respond ] pluginListeners :: [BotResponse] pluginListeners = [ Jira.hear ] slaskellbot :: Slack () slaskellbot = do me <- _selfUserId . _slackSelf <$> getSession conf <- getConfig incomingCommand <- liftIO $ atomically newBroadcastTChan incomingListen <- liftIO $ atomically newBroadcastTChan outgoing <- liftIO $ atomically newTChan _ <- mapM (liftIO . runPlugin incomingCommand) pluginHandlers _ <- mapM (liftIO . runPlugin incomingListen) pluginListeners _ <- liftIO $ withSlackHandle conf $ relayMessage outgoing forever $ getNextEvent >>= \case Message cid (UserComment uid) msg _ _ _ | uid /= me -> do let parsedCmd = parseMaybe P.commandParser msg case parsedCmd of Just c -> liftIO $ print c Nothing -> pure () let evt = Event msg uid cid parsedCmd let response = OutputResponse outgoing evt NoMessage let chan = if isJust parsedCmd then incomingCommand else incomingListen liftIO $ atomically $ writeTChan chan (evt, response) _ -> pure () runPlugin :: TChan BotInput -> BotResponse -> IO ThreadId runPlugin chan f = do myChan <- atomically $ dupTChan chan forkIO $ forever $ do msg <- atomically $ readTChan myChan f msg relayMessage :: TChan OutputResponse -> SlackHandle -> IO ThreadId relayMessage chan h = do forkIO $ forever $ do resp <- atomically $ readTChan chan monadicToHandled (publishMessage resp) h publishMessage :: OutputResponse -> Slack () publishMessage resp = do let cid = channel $ event resp case (message resp) of SimpleMessage txt -> slackSendMsg cid txt [] QuotedSimpleMessage txt -> slackSendMsg cid (T.concat ["`", txt, "`"]) [] RichMessage rmsg -> slackSendMsg cid "" [rmsg] NoMessage -> pure () slackSendMsg :: ChannelId -> T.Text -> [Attachment] -> Slack () slackSendMsg cid msg att = do send <- sendRichMessage cid msg att either (liftIO . putStrLn . T.unpack) pure send
wamaral/slaskellbot
src/Lib.hs
Haskell
bsd-3-clause
2,995
{-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MultiParamTypeClasses #-} module Meadowstalk.Foundation where import Data.Text (Text) import Text.Hamlet import Database.Persist.Sql import Yesod.Core import Yesod.Persist import Yesod.Form import Yesod.Static import Meadowstalk.Model import Meadowstalk.Static import Meadowstalk.Template ------------------------------------------------------------------------------- data Meadowstalk = Meadowstalk { siteStatic :: Static , sitePool :: ConnectionPool } ------------------------------------------------------------------------------- mkYesodData "Meadowstalk" $(parseRoutesFile "config/routes") mkMessage "Meadowstalk" "messages" "en" ------------------------------------------------------------------------------- instance Yesod Meadowstalk where defaultLayout widget = do current <- getCurrentRoute let isCurrent route = Just route == current PageContent title htags btags <- widgetToPageContent $ do $(lessFile "templates/bootstrap/bootstrap.less") $(lessFile "templates/font-awesome/font-awesome.less") $(lessFile "templates/layout/default-layout.less") #ifndef YESOD_DEVEL addScript (StaticR ga_js) #endif widget withUrlRenderer $(hamletFile "templates/layout/default-layout.hamlet") ------------------------------------------------------------------------------- instance YesodPersist Meadowstalk where type YesodPersistBackend Meadowstalk = SqlBackend runDB action = do pool <- fmap sitePool getYesod runSqlPool action pool ------------------------------------------------------------------------------- instance RenderMessage Meadowstalk FormMessage where renderMessage _ _ = defaultFormMessage
HalfWayMan/meadowstalk
src/Meadowstalk/Foundation.hs
Haskell
bsd-3-clause
2,117
{-# LANGUAGE OverloadedStrings #-} module Deviser.Parser ( readExpr , readExprFile ) where import Data.Array (listArray) import Data.Complex import Data.Functor.Identity (Identity) import Data.Ratio ((%)) import qualified Data.Text as T import Numeric (readFloat, readHex, readOct) import Text.Parsec hiding (spaces) import qualified Text.Parsec.Language as Language import Text.Parsec.Text import qualified Text.Parsec.Token as Token import Deviser.Types -- Lexer symbol :: Parser Char symbol = oneOf "!$%&|*+-/:<=>?@^_~" schemeDef :: Token.GenLanguageDef T.Text () Identity schemeDef = Language.emptyDef { Token.commentStart = "" , Token.commentEnd = "" , Token.commentLine = ";" , Token.opStart = Token.opLetter schemeDef , Token.opLetter = symbol , Token.identStart = letter <|> symbol , Token.identLetter = letter <|> symbol <|> digit , Token.reservedOpNames = ["'", "\"", ".", "+", "-"] } lexer :: Token.GenTokenParser T.Text () Identity lexer = Token.makeTokenParser schemeDef reservedOp :: T.Text -> Parser () reservedOp op = Token.reservedOp lexer (T.unpack op) identifier :: Parser String identifier = Token.identifier lexer spaces :: Parser () spaces = Token.whiteSpace lexer parens :: Parser a -> Parser a parens = Token.parens lexer stringLiteral :: Parser String stringLiteral = Token.stringLiteral lexer -- Atom parseAtom :: Parser LispVal parseAtom = identifier >>= \i -> return (Atom (T.pack i)) -- Lists parseQuoted :: Parser LispVal parseQuoted = do _ <- char '\'' x <- parseExpr return (List [Atom "quote", x]) parseQuasiquoted :: Parser LispVal parseQuasiquoted = do _ <- char '`' x <- parseExpr return (List [Atom "quasiquote", x]) parseUnquoted :: Parser LispVal parseUnquoted = do _ <- char ',' x <- parseExpr return (List [Atom "unquote", x]) parseList :: Parser LispVal parseList = List <$> (spaces *> many (parseExpr <* spaces)) parseDottedList :: Parser LispVal parseDottedList = do h <- endBy parseExpr spaces t <- char '.' >> spaces >> parseExpr return (DottedList h t) parseListOrDottedList :: Parser LispVal parseListOrDottedList = parens (spaces *> (parseList <|> parseDottedList <* spaces)) -- Vector parseVector :: Parser LispVal parseVector = try $ do _ <- string "#(" xs <- spaces *> many (parseExpr <* spaces) _ <- char ')' return (Vector (listArray (0, length xs - 1) xs)) -- Number parseDigit1 :: Parser LispVal parseDigit1 = (Number . read) <$> many1 digit parseDigit2 :: Parser LispVal parseDigit2 = do _ <- try (string "#d") x <- many1 digit return (Number (read x)) hexDigitToNum :: (Num a, Eq a) => String -> a hexDigitToNum = fst . head . readHex parseHex :: Parser LispVal parseHex = do _ <- try (string "#x") x <- many1 hexDigit return (Number (hexDigitToNum x)) octDigitToNum :: (Num a, Eq a) => String -> a octDigitToNum = fst . head . readOct parseOct :: Parser LispVal parseOct = do _ <- try (string "#o") x <- many1 octDigit return (Number (octDigitToNum x)) binDigitsToNum :: String -> Integer binDigitsToNum = binDigitsToNum' 0 where binDigitsToNum' :: Num t => t -> String -> t binDigitsToNum' digint xs = case xs of "" -> digint (y:ys) -> binDigitsToNum' (2 * digint + (if y == '0' then 0 else 1)) ys parseBin :: Parser LispVal parseBin = do _ <- try (string "#b") x <- many1 (oneOf "10") return (Number (binDigitsToNum x)) -- Float floatDigitsToDouble :: String -> String -> Double floatDigitsToDouble i d = fst (head (readFloat (i ++ "." ++ d))) parseFloat :: Parser LispVal parseFloat = do i <- many1 digit _ <- char '.' d <- many1 digit return (Float (floatDigitsToDouble i d)) -- Ratio ratioDigitsToRational :: String -> String -> Rational ratioDigitsToRational n d = read n % read d parseRatio :: Parser LispVal parseRatio = do n <- many1 digit _ <- char '/' d <- many1 digit return (Ratio (ratioDigitsToRational n d)) -- Complex toDouble :: LispVal -> Double toDouble (Float f) = realToFrac f toDouble (Number n) = fromIntegral n toDouble x = error ("toDouble not implemented for " ++ show x) lispValsToComplex :: LispVal -> LispVal -> Complex Double lispValsToComplex x y = toDouble x :+ toDouble y parseComplex :: Parser LispVal parseComplex = do x <- try parseFloat <|> parseDigit1 _ <- char '+' y <- try parseFloat <|> parseDigit1 _ <- char 'i' return (Complex (lispValsToComplex x y)) -- String parseString :: Parser LispVal parseString = stringLiteral >>= \x -> return (String (T.pack x)) -- Character parseCharacter :: Parser LispVal parseCharacter = do _ <- try (string "#\\") value <- try (string "newline" <|> string "space") <|> do x <- anyChar _ <- notFollowedBy alphaNum return [x] return $ case value of "space" -> Character ' ' "newline" -> Character '\n' _ -> Character (T.head (T.pack value)) -- Boolean parseBool :: Parser LispVal parseBool = char '#' *> ((char 't' *> return (Bool True)) <|> (char 'f' *> return (Bool False))) -- Composed parsers parseNumber :: Parser LispVal parseNumber = try parseComplex <|> try parseRatio <|> try parseFloat <|> parseDigit1 <|> parseDigit2 <|> parseHex <|> parseOct <|> parseBin parseExpr :: Parser LispVal parseExpr = parseAtom <|> parseString <|> try parseNumber <|> try parseBool <|> try parseCharacter <|> parseQuoted <|> parseListOrDottedList <|> parseQuasiquoted <|> parseUnquoted <|> parseVector withSpaces :: Parser a -> Parser a withSpaces p = spaces *> p <* spaces readExpr :: T.Text -> Either ParseError LispVal readExpr = parse (withSpaces parseExpr) "<stdin>" readExprFile :: T.Text -> Either ParseError LispVal readExprFile = parse (withSpaces parseList) "<file>"
henrytill/deviser
src/Deviser/Parser.hs
Haskell
bsd-3-clause
5,903
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module TW.CodeGen.PureScript ( makeFileName, makeModule , libraryInfo ) where import TW.Ast import TW.BuiltIn import TW.JsonRepr import TW.Types import TW.Utils import Data.Maybe import Data.Monoid import System.FilePath import qualified Data.List as L import qualified Data.Text as T libraryInfo :: LibraryInfo libraryInfo = LibraryInfo "Purescript" "purescript-typed-wire" "0.2.0" makeFileName :: ModuleName -> FilePath makeFileName (ModuleName parts) = (L.foldl' (</>) "" $ map T.unpack parts) ++ ".purs" makeModule :: Module -> T.Text makeModule m = T.unlines [ "module " <> printModuleName (m_name m) <> " where" , "" , T.intercalate "\n" (map makeImport $ m_imports m) , "" , "import Data.TypedWire.Prelude" , if not (null (m_apis m)) then "import Data.TypedWire.Api" else "" , "" , T.intercalate "\n" (map makeTypeDef $ m_typeDefs m) , T.intercalate "\n" (map makeApiDef $ m_apis m) ] makeApiDef :: ApiDef -> T.Text makeApiDef ad = T.unlines $ catMaybes [ apiHeader , Just $ T.intercalate "\n" (map makeEndPoint (ad_endpoints ad)) ] where apiHeader = case not (null (ad_headers ad)) of True -> Just $ makeHeaderType apiHeaderType (ad_headers ad) False -> Nothing apiCapitalized = capitalizeText (unApiName $ ad_name ad) handlerType = "ApiHandler" <> apiCapitalized apiHeaderType = handlerType <> "Headers" headerType ep = handlerType <> capitalizeText (unEndpointName (aed_name ep)) <> "Headers" makeHeaderName hdr = uncapitalizeText $ makeSafePrefixedFieldName (ah_name hdr) makeHeaderType ty headers = T.unlines [ "type " <> ty <> " = " , " { " <> T.intercalate "\n , " (map makeHeaderField headers) , " }" ] makeHeaderField hdr = makeHeaderName hdr <> " :: String" makeEndPoint ep = T.unlines $ catMaybes [ epHeader , Just $ funName <> " :: forall m. (Monad m) => " <> (maybe "" (const $ apiHeaderType <> " -> ") apiHeader) <> (maybe "" (const $ headerType ep <> " -> ") epHeader) <> urlParamSig <> (maybe "" (\t -> makeType t <> " -> ") $ aed_req ep) <> "ApiCall m " <> (maybe "Unit" makeType $ aed_req ep) <> " " <> makeType (aed_resp ep) , Just $ funName <> " " <> (maybe "" (const "apiHeaders ") apiHeader) <> (maybe "" (const "endpointHeaders ") epHeader) <> urlParams <> (maybe "" (const "reqBody ") $ aed_req ep) <> "runRequest = do" , Just $ " let coreHeaders = [" <> T.intercalate ", " (map (headerPacker "apiHeaders") $ ad_headers ad) <> "]" , Just $ " let fullHeaders = coreHeaders ++ [" <> T.intercalate ", " (map (headerPacker "endpointHeaders") $ aed_headers ep) <> "]" , Just $ " let url = " <> T.intercalate " ++ \"/\" ++ " (map urlPacker routeInfo) , Just $ " let method = " <> T.pack (show $ aed_verb ep) , Just $ " let body = " <> (maybe "Nothing" (const "Just $ encodeJson reqBody") $ aed_req ep) , Just $ " let req = { headers: fullHeaders, method: method, body: body, url: url }" , Just $ " resp <- runRequest req" , Just $ " return $ if (resp.statusCode /= 200) then Left \"Return code was not 200\" else decodeJson resp.body" ] where urlPacker (r, p) = case r of ApiRouteStatic t -> T.pack (show t) ApiRouteDynamic _ -> "toPathPiece p" <> T.pack (show p) <> "" headerPacker apiVar hdr = "{ key: " <> T.pack (show $ ah_name hdr) <> ", value: " <> apiVar <> "." <> makeHeaderName hdr <> " }" funName = unApiName (ad_name ad) <> capitalizeText (unEndpointName $ aed_name ep) routeInfo = zip (aed_route ep) ([0..] :: [Int]) urlParams = T.concat $ flip mapMaybe routeInfo $ \(r,p) -> case r of ApiRouteStatic _ -> Nothing ApiRouteDynamic _ -> Just $ "p" <> T.pack (show p) <> " " urlParamSig = T.concat $ flip mapMaybe (aed_route ep) $ \r -> case r of ApiRouteStatic _ -> Nothing ApiRouteDynamic ty -> Just (makeType ty <> " -> ") epHeader = case not (null (aed_headers ep)) of True -> Just $ makeHeaderType (headerType ep) (aed_headers ep) False -> Nothing makeImport :: ModuleName -> T.Text makeImport m = "import qualified " <> printModuleName m <> " as " <> printModuleName m makeTypeDef :: TypeDef -> T.Text makeTypeDef td = case td of TypeDefEnum ed -> makeEnumDef ed TypeDefStruct sd -> makeStructDef sd decoderName :: TypeName -> T.Text decoderName ty = "dec" <> unTypeName ty encoderName :: TypeName -> T.Text encoderName ty = "enc" <> unTypeName ty eqName :: TypeName -> T.Text eqName ty = "eq" <> unTypeName ty showName :: TypeName -> T.Text showName ty = "show" <> unTypeName ty makeStructDef :: StructDef -> T.Text makeStructDef sd = T.unlines [ "data " <> fullType , " = " <> unTypeName (sd_name sd) , " { " <> T.intercalate "\n , " (map makeStructField $ sd_fields sd) , " }" , "" , "instance " <> eqName (sd_name sd) <> " :: " <> tcPreds (sd_args sd) ["Eq"] <> "Eq (" <> fullType <> ") where " <> "eq (" <> justType <> " a) (" <> justType <> " b) = " <> T.intercalate " && " (map makeFieldEq (sd_fields sd)) , "instance " <> showName (sd_name sd) <> " :: " <> tcPreds (sd_args sd) ["Show"] <> "Show (" <> fullType <> ") where " <> "show (" <> justType <> " a) = " <> T.pack (show justType) <> " ++ \"{\" ++ " <> T.intercalate " ++ \", \" ++ " (map makeFieldShow (sd_fields sd)) <> " ++ \"}\"" , "instance " <> encoderName (sd_name sd) <> " :: " <> tcPreds (sd_args sd) ["EncodeJson"] <> "EncodeJson" <> " (" <> fullType <> ") where" , " encodeJson (" <> unTypeName (sd_name sd) <> " objT) =" , " " <> T.intercalate "\n ~> " (map makeToJsonFld $ sd_fields sd) , " ~> jsonEmptyObject" , "instance " <> decoderName (sd_name sd) <> " :: " <> tcPreds (sd_args sd) ["DecodeJson"] <> "DecodeJson" <> " (" <> fullType <> ") where" , " decodeJson jsonT = do" , " objT <- decodeJson jsonT" , " " <> T.intercalate "\n " (map makeFromJsonFld $ sd_fields sd) , " pure $ " <> unTypeName (sd_name sd) <> " { " <> T.intercalate ", " (map makeFieldSetter $ sd_fields sd) <> " }" ] where makeFieldShow fld = let name = unFieldName $ sf_name fld in T.pack (show name) <> " ++ \": \" ++ show a." <> name makeFieldEq fld = let name = unFieldName $ sf_name fld in "a." <> name <> " == " <> "b." <> name makeFieldSetter fld = let name = unFieldName $ sf_name fld in name <> " : " <> "v" <> name makeFromJsonFld fld = let name = unFieldName $ sf_name fld in case sf_type fld of (TyCon q _) | q == bi_name tyMaybe -> "v" <> name <> " <- objT .?? " <> T.pack (show name) _ -> "v" <> name <> " <- objT .? " <> T.pack (show name) makeToJsonFld fld = let name = unFieldName $ sf_name fld in T.pack (show name) <> " " <> ":=" <> " objT." <> name justType = unTypeName (sd_name sd) fullType = unTypeName (sd_name sd) <> " " <> T.intercalate " " (map unTypeVar $ sd_args sd) makeStructField :: StructField -> T.Text makeStructField sf = unFieldName (sf_name sf) <> " :: " <> makeType (sf_type sf) tcPreds :: [TypeVar] -> [T.Text] -> T.Text tcPreds args tyClasses = if null args then "" else let mkPred (TypeVar tv) = T.intercalate "," $ flip map tyClasses $ \tyClass -> tyClass <> " " <> tv in "(" <> T.intercalate "," (map mkPred args) <> ") => " makeEnumDef :: EnumDef -> T.Text makeEnumDef ed = T.unlines [ "data " <> fullType , " = " <> T.intercalate "\n | " (map makeEnumChoice $ ed_choices ed) , "" , "instance " <> eqName (ed_name ed) <> " :: " <> tcPreds (ed_args ed) ["Eq"] <> "Eq (" <> fullType <> ") where " , " " <> T.intercalate "\n " (map makeChoiceEq $ ed_choices ed) , " eq _ _ = false" , "instance " <> showName (ed_name ed) <> " :: " <> tcPreds (ed_args ed) ["Show"] <> "Show (" <> fullType <> ") where " , " " <> T.intercalate "\n " (map makeChoiceShow $ ed_choices ed) , "instance " <> encoderName (ed_name ed) <> " :: " <> tcPreds (ed_args ed) ["EncodeJson"] <> "EncodeJson" <> " (" <> fullType <> ") where" , " encodeJson x =" , " case x of" , " " <> T.intercalate "\n " (map mkToJsonChoice $ ed_choices ed) , "instance " <> decoderName (ed_name ed) <> " :: " <> tcPreds (ed_args ed) ["DecodeJson"] <> "DecodeJson" <> " (" <> fullType <> ") where" , " decodeJson jsonT =" , " decodeJson jsonT >>= \\objT -> " , " " <> T.intercalate "\n <|> " (map mkFromJsonChoice $ ed_choices ed) ] where makeChoiceShow ec = let constr = unChoiceName $ ec_name ec in case ec_arg ec of Nothing -> "show (" <> constr <> ") = " <> T.pack (show constr) Just _ -> "show (" <> constr <> " a) = " <> T.pack (show constr) <> " ++ \" \" ++ show a" makeChoiceEq ec = let constr = unChoiceName $ ec_name ec in case ec_arg ec of Nothing -> "eq (" <> constr <> ") (" <> constr <> ") = true" Just _ -> "eq (" <> constr <> " a) (" <> constr <> " b) = a == b" mkFromJsonChoice ec = let constr = unChoiceName $ ec_name ec tag = camelTo2 '_' $ T.unpack constr (op, opEnd) = case ec_arg ec of Nothing -> ("<$ (eatBool <$> (", "))") Just _ -> ("<$>", "") in "(" <> constr <> " " <> op <> " objT " <> ".?" <> " " <> T.pack (show tag) <> opEnd <> ")" mkToJsonChoice ec = let constr = unChoiceName $ ec_name ec tag = camelTo2 '_' $ T.unpack constr (argParam, argVal) = case ec_arg ec of Nothing -> ("", "true") Just _ -> ("y", "y") in constr <> " " <> argParam <> " -> " <> " " <> T.pack (show tag) <> " " <> " := " <> " " <> argVal <> " ~> jsonEmptyObject" fullType = unTypeName (ed_name ed) <> " " <> T.intercalate " " (map unTypeVar $ ed_args ed) makeEnumChoice :: EnumChoice -> T.Text makeEnumChoice ec = (unChoiceName $ ec_name ec) <> fromMaybe "" (fmap ((<>) " " . makeType) $ ec_arg ec) makeType :: Type -> T.Text makeType t = case isBuiltIn t of Nothing -> case t of TyVar (TypeVar x) -> x TyCon qt args -> let ty = makeQualTypeName qt in case args of [] -> ty _ -> "(" <> ty <> " " <> T.intercalate " " (map makeType args) <> ")" Just (bi, tvars) | bi == tyString -> "String" | bi == tyInt -> "Int" | bi == tyBool -> "Boolean" | bi == tyFloat -> "Number" | bi == tyMaybe -> "(Maybe " <> T.intercalate " " (map makeType tvars) <> ")" | bi == tyBytes -> "AsBase64" | bi == tyList -> "(Array " <> T.intercalate " " (map makeType tvars) <> ")" | bi == tyDateTime -> "DateTime" | bi == tyTime -> "TimeOfDay" | bi == tyDate -> "Day" | otherwise -> error $ "Haskell: Unimplemented built in type: " ++ show t makeQualTypeName :: QualTypeName -> T.Text makeQualTypeName qtn = case unModuleName $ qtn_module qtn of [] -> ty _ -> printModuleName (qtn_module qtn) <> "." <> ty where ty = unTypeName $ qtn_type qtn
agrafix/typed-wire
src/TW/CodeGen/PureScript.hs
Haskell
mit
12,260
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} module Bead.Config.Parser where import Control.Applicative import Data.ByteString.Char8 (pack) import Data.Maybe import Data.String import Data.Yaml import Bead.Config.Configuration #ifdef TEST import Test.Tasty.TestSet #endif -- * JSON instances instance FromJSON Config where parseJSON (Object v) = Config <$> v.: "user-actions-log" <*> v.: "session-timeout" #ifdef EmailEnabled <*> v.: "hostname-for-emails" <*> v.: "from-email-address" #endif <*> v.: "default-login-language" <*> v.: "default-timezone" <*> v.: "timezone-info-directory" <*> v.: "max-upload-size" <*> v.: "login-config" #ifdef MYSQL <*> v.: "mysql-config" #else <*> pure FilePersistConfig #endif parseJSON _ = error "Config is not parsed" #ifdef SSO instance FromJSON SSOLoginConfig where parseJSON (Object v) = SSOLoginConfig <$> (withDefault 5 <$> v .:? "timeout") <*> (withDefault 4 <$> v .:? "threads") <*> (withDefault "ldapsearch -Q -LLL" <$> v .:? "query-command") <*> v .: "uid-key" <*> v .: "name-key" <*> v .: "email-key" <*> (withDefault False <$> v .:? "developer") where withDefault = flip maybe id parseJSON _ = error "SSO login config is not parsed" #else instance FromJSON StandaloneLoginConfig where parseJSON (Object v) = StandaloneLoginConfig <$> v .: "username-regexp" <*> v .: "username-regexp-example" parseJSON _ = error "Standalone login config is not parsed" #endif #ifdef MYSQL instance FromJSON MySQLConfig where parseJSON (Object v) = MySQLConfig <$> v.: "database" <*> v.: "hostname" <*> v.: "port" <*> v.: "username" <*> v.: "password" <*> v.: "pool-size" parseJSON _ = error "MySQL config is not parsed" #endif parseYamlConfig :: String -> Either String Config parseYamlConfig = decodeEither . pack #ifdef TEST parseTests = group "parserTests" $ do #ifdef SSO let sSOConfig1 = SSOLoginConfig 5 4 "ldapsearch -Q -LLL" "uid" "name" "email" False assertEquals "SSO login config #1" (Right sSOConfig1) (decodeEither $ fromString $ unlines [ "uid-key: 'uid'", "name-key: 'name'", "email-key: 'email'" ]) "SSO config is not parsed correctly" let sSOConfig2 = SSOLoginConfig 5 4 "ldapsearch -Q" "uid" "name" "email" True assertEquals "SSO login config #2" (Right sSOConfig2) (decodeEither $ fromString $ unlines [ "timeout: 5", "threads: 4", "query-command: 'ldapsearch -Q'", "uid-key: 'uid'", "name-key: 'name'", "email-key: 'email'", "developer: yes" ]) "SSO config is not parsed correctly" #else let standaloneConfig1 = StandaloneLoginConfig "REGEXP" "REGEXP-EXAMPLE" assertEquals "Standalone login config" (Right standaloneConfig1) (decodeEither $ fromString $ unlines [ "username-regexp: 'REGEXP'", "username-regexp-example: 'REGEXP-EXAMPLE'" ]) "Standalone config is not parsed correctly" #endif let configStr loginCfg persistCfg = unlines [ "user-actions-log: 'actions'", "session-timeout: 10", #ifdef EmailEnabled "hostname-for-emails: 'www.google.com'", "from-email-address: 'mail@google.com'", #endif "default-login-language: 'en'", "default-timezone: 'Europe/Budapest'", "timezone-info-directory: '/opt/some'", "max-upload-size: 150", "login-config:", loginCfg, #ifdef MYSQL "mysql-config:", persistCfg, #endif ""   ] let config lcf pcfg = Config { userActionLogFile = "actions" , sessionTimeout = 10 #ifdef EmailEnabled , emailHostname = "www.google.com" , emailFromAddress = "mail@google.com" #endif , defaultLoginLanguage = "en" , defaultRegistrationTimezone = "Europe/Budapest" , timeZoneInfoDirectory = "/opt/some" , maxUploadSizeInKb = 150 , loginConfig = lcf , persistConfig = pcfg } let persistConfig = #ifdef MYSQL MySQLConfig { mySQLDbName = "bead-test-db" , mySQLHost = "mysql.server.com" , mySQLPort = 3308 , mySQLUser = "bead" , mySQLPass = "secret" , mySQLPoolSize = 30 } #else FilePersistConfig #endif let persistConfigStr = #ifdef MYSQL unlines [ " database: bead-test-db", " hostname: mysql.server.com", " port: 3308", " username: bead", " password: secret", " pool-size: 30" ] #else "" #endif #ifdef SSO assertEquals "Config with SSO #1" (Right $ config sSOConfig1 persistConfig) (parseYamlConfig . fromString $ configStr (unlines [ " uid-key: 'uid'", " name-key: 'name'", " email-key: 'email'" ]) persistConfigStr) "Config with SSO is not parsed correctly" assertEquals "Config with SSO #2" (Right $ config sSOConfig2 persistConfig) (parseYamlConfig . fromString $ configStr (unlines [ " timeout: 5", " threads: 4", " query-command: 'ldapsearch -Q'", " uid-key: 'uid'", " name-key: 'name'", " email-key: 'email'", " developer: yes" ]) persistConfigStr) "Config with SSO is not parsed correctly" #else assertEquals "Config with standalone" (Right $ config standaloneConfig1 persistConfig) (parseYamlConfig . fromString $ configStr (unlines [ " username-regexp: 'REGEXP'", " username-regexp-example: 'REGEXP-EXAMPLE'"]) persistConfigStr) "Config with standalone is not parsed correctly" #endif #endif
andorp/bead
src/Bead/Config/Parser.hs
Haskell
bsd-3-clause
5,778
module ShowRepoEvents where import qualified Github.Issues.Events as Github import Data.List (intercalate) import Data.Maybe (fromJust) main = do possibleEvents <- Github.eventsForRepo "thoughtbot" "paperclip" case possibleEvents of (Left error) -> putStrLn $ "Error: " ++ show error (Right events) -> do putStrLn $ intercalate "\n" $ map formatEvent events formatEvent event = "Issue #" ++ issueNumber event ++ ": " ++ formatEvent' event (Github.eventType event) where formatEvent' event Github.Closed = "closed on " ++ createdAt event ++ " by " ++ loginName event ++ withCommitId event (\commitId -> " in the commit " ++ commitId) formatEvent' event Github.Reopened = "reopened on " ++ createdAt event ++ " by " ++ loginName event formatEvent' event Github.Subscribed = loginName event ++ " is subscribed to receive notifications" formatEvent' event Github.Unsubscribed = loginName event ++ " is unsubscribed from notifications" formatEvent' event Github.Merged = "merged by " ++ loginName event ++ " on " ++ createdAt event ++ (withCommitId event $ \commitId -> " in the commit " ++ commitId) formatEvent' event Github.Referenced = withCommitId event $ \commitId -> "referenced from " ++ commitId ++ " by " ++ loginName event formatEvent' event Github.Mentioned = loginName event ++ " was mentioned in the issue's body" formatEvent' event Github.Assigned = "assigned to " ++ loginName event ++ " on " ++ createdAt event loginName = Github.githubOwnerLogin . Github.eventActor createdAt = show . Github.fromDate . Github.eventCreatedAt withCommitId event f = maybe "" f (Github.eventCommitId event) issueNumber = show . Github.issueNumber . fromJust . Github.eventIssue
jwiegley/github
samples/Issues/Events/ShowRepoEvents.hs
Haskell
bsd-3-clause
1,777
module Opaleye.Column (module Opaleye.Column, Column, Nullable, unsafeCoerce, unsafeCoerceColumn, unsafeCompositeField) where import Opaleye.Internal.Column (Column, Nullable, unsafeCoerce, unsafeCoerceColumn, unsafeCompositeField) import qualified Opaleye.Internal.Column as C import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ import qualified Opaleye.PGTypes as T import Prelude hiding (null) -- | A NULL of any type null :: Column (Nullable a) null = C.Column (HPQ.ConstExpr HPQ.NullLit) isNull :: Column (Nullable a) -> Column T.PGBool isNull = C.unOp HPQ.OpIsNull -- | If the @Column (Nullable a)@ is NULL then return the @Column b@ -- otherwise map the underlying @Column a@ using the provided -- function. -- -- The Opaleye equivalent of the 'Data.Maybe.maybe' function. matchNullable :: Column b -> (Column a -> Column b) -> Column (Nullable a) -> Column b matchNullable replacement f x = C.unsafeIfThenElse (isNull x) replacement (f (unsafeCoerceColumn x)) -- | If the @Column (Nullable a)@ is NULL then return the provided -- @Column a@ otherwise return the underlying @Column a@. -- -- The Opaleye equivalent of the 'Data.Maybe.fromMaybe' function fromNullable :: Column a -> Column (Nullable a) -> Column a fromNullable = flip matchNullable id -- | The Opaleye equivalent of 'Data.Maybe.Just' toNullable :: Column a -> Column (Nullable a) toNullable = unsafeCoerceColumn -- | If the argument is 'Data.Maybe.Nothing' return NULL otherwise return the -- provided value coerced to a nullable type. maybeToNullable :: Maybe (Column a) -> Column (Nullable a) maybeToNullable = maybe null toNullable -- | Cast a column to any other type. This is safe for some conversions such as uuid to text. unsafeCast :: String -> C.Column a -> Column b unsafeCast = mapColumn . HPQ.CastExpr where mapColumn :: (HPQ.PrimExpr -> HPQ.PrimExpr) -> Column c -> Column a mapColumn primExpr c = C.Column (primExpr (C.unColumn c))
benkolera/haskell-opaleye
src/Opaleye/Column.hs
Haskell
bsd-3-clause
2,189
-- | -- Module: Network.FastIRC.ServerSet -- Copyright: (c) 2010 Ertugrul Soeylemez -- License: BSD3 -- Maintainer: Ertugrul Soeylemez <es@ertes.de> -- Stability: alpha -- -- Functions for dealing with sets of IRC servers. Note that servers -- are compared case-insensitively. module Network.FastIRC.ServerSet ( -- * The server set type ServerSet, -- * Manipulation addServer, delServer, emptyServers, isServer, -- * Conversion serversFromList, serversToList ) where import qualified Data.ByteString.Char8 as B import qualified Data.Set as S import Data.Char import Network.FastIRC.Types -- | A set of servers. This data type uses 'S.Set' internally, but -- the strings are handled case-insensitively. newtype ServerSet = ServerSet (S.Set ServerName) -- | Empty set of servers. emptyServers :: ServerSet emptyServers = ServerSet S.empty -- | Add a server to a 'ServerSet'. addServer :: ServerName -> ServerSet -> ServerSet addServer s (ServerSet ss) = ServerSet $ S.insert (B.map toLower s) ss -- | Remove a server from a 'ServerSet'. delServer :: ServerName -> ServerSet -> ServerSet delServer s (ServerSet ss) = ServerSet $ S.delete (B.map toLower s) ss -- | Check whether specified server is in the set. isServer :: ServerName -> ServerSet -> Bool isServer s (ServerSet ss) = S.member (B.map toLower s) ss -- | Build from list. serversFromList :: [ServerName] -> ServerSet serversFromList = ServerSet . S.fromList -- | Convert to list. serversToList :: ServerSet -> [ServerName] serversToList (ServerSet ss) = S.toList ss
chrisdone/hulk
fastirc-0.2.0/Network/FastIRC/ServerSet.hs
Haskell
bsd-3-clause
1,603
-- This is a modification of the calendar program described in section 4.5 -- of Bird and Wadler's ``Introduction to functional programming'', with -- two ways of printing the calendar ... as in B+W, or like UNIX `cal': -- Run using: calFor "1996" -- or: putStr (calendar 1996) -- or: putStr (cal 1996) module Calendar( calendar, cal, calFor, calProg ) where import Gofer import List(zip4) import IO(hPutStr,stderr) import System( getArgs, getProgName, exitWith, ExitCode(..) ) import Char (digitToInt, isDigit) -- Picture handling: infixr 5 `above`, `beside` type Picture = [[Char]] height, width :: Picture -> Int height p = length p width p = length (head p) above, beside :: Picture -> Picture -> Picture above = (++) beside = zipWith (++) stack, spread :: [Picture] -> Picture stack = foldr1 above spread = foldr1 beside empty :: (Int,Int) -> Picture empty (h,w) = replicate h (replicate w ' ') block, blockT :: Int -> [Picture] -> Picture block n = stack . map spread . groupsOf n blockT n = spread . map stack . groupsOf n groupsOf :: Int -> [a] -> [[a]] groupsOf n [] = [] groupsOf n xs = take n xs : groupsOf n (drop n xs) lframe :: (Int,Int) -> Picture -> Picture lframe (m,n) p = (p `beside` empty (h,n-w)) `above` empty (m-h,n) where h = height p w = width p -- Information about the months in a year: monthLengths year = [31,feb,31,30,31,30,31,31,30,31,30,31] where feb | leap year = 29 | otherwise = 28 leap year = if year`mod`100 == 0 then year`mod`400 == 0 else year`mod`4 == 0 monthNames = ["January","February","March","April", "May","June","July","August", "September","October","November","December"] jan1st year = (year + last`div`4 - last`div`100 + last`div`400) `mod` 7 where last = year - 1 firstDays year = take 12 (map (`mod`7) (scanl (+) (jan1st year) (monthLengths year))) -- Producing the information necessary for one month: dates fd ml = map (date ml) [1-fd..42-fd] where date ml d | d<1 || ml<d = [" "] | otherwise = [rjustify 3 (show d)] -- The original B+W calendar: calendar :: Int -> String calendar = unlines . block 3 . map picture . months where picture (mn,yr,fd,ml) = title mn yr `above` table fd ml title mn yr = lframe (2,25) [mn ++ " " ++ show yr] table fd ml = lframe (8,25) (daynames `beside` entries fd ml) daynames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] entries fd ml = blockT 7 (dates fd ml) months year = zip4 monthNames (replicate 12 year) (firstDays year) (monthLengths year) -- In a format somewhat closer to UNIX cal: cal year = unlines (banner year `above` body year) where banner yr = [cjustify 75 (show yr)] `above` empty (1,75) body = block 3 . map (pad . pic) . months pic (mn,fd,ml) = title mn `above` table fd ml pad p = (side`beside`p`beside`side)`above`end side = empty (8,2) end = empty (1,25) title mn = [cjustify 21 mn] table fd ml = daynames `above` entries fd ml daynames = [" Su Mo Tu We Th Fr Sa"] entries fd ml = block 7 (dates fd ml) months year = zip3 monthNames (firstDays year) (monthLengths year) -- For a standalone calendar program: -- -- To use this with "runhugs" on Unix: -- -- cat >cal -- #! /usr/local/bin/runhugs -- -- > module Main( main ) where -- > import Calendar -- > main = calProg -- <ctrl-D> -- -- chmod 755 cal -- -- ./cal 1997 calProg = do args <- getArgs case args of [year] -> calFor year _ -> do putStr "Usage: " getProgName >>= putStr putStrLn " year" exitWith (ExitFailure 1) calFor year | illFormed = hPutStr stderr "Bad argument" >> exitWith (ExitFailure 1) | otherwise = putStr (cal yr) where illFormed = null ds || not (null rs) (ds,rs) = span isDigit year yr = atoi ds atoi s = foldl (\a d -> 10*a+d) 0 (map digitToInt s) -- End of calendar program
OS2World/DEV-UTIL-HUGS
demos/Calendar.hs
Haskell
bsd-3-clause
4,964
module C3 (module D, module C3) where import D3 as D hiding (anotherFun) anotherFun (x:xs) = sq x + anotherFun xs anotherFun [] = 0
RefactoringTools/HaRe
old/testing/duplication/C3_TokOut.hs
Haskell
bsd-3-clause
144
{-# LANGUAGE GADTs, TypeOperators, PolyKinds #-} module T16074 where import GHC.Types data a :~: b where Refl :: a :~: a foo :: TYPE a :~: TYPE b foo = Refl
sdiehl/ghc
testsuite/tests/typecheck/should_fail/T16074.hs
Haskell
bsd-3-clause
161
module RecNat where {- imports will be added for the PointlessP librasies -} recNat :: Int -> (Int -> a -> a) -> a -> a recNat 0 f z = z recNat n f z = f (n-1) (recNat (n-1) f z) --Programatica parser can't read: -- recNat (n+1) f z = f n (recNat n f z) -- the whole expression will be selected for translation. -- note that recNat can be converted into a paramorphism because -- the 2nd and 3rd arguments don't have free variables double = \n -> recNat n (\pred rec -> succ (succ rec)) 0
kmate/HaRe
old/testing/pointwiseToPointfree/RecNat.hs
Haskell
bsd-3-clause
511
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash, UnboxedTuples #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Word -- Copyright : (c) The University of Glasgow, 1997-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- Sized unsigned integral types: 'Word', 'Word8', 'Word16', 'Word32', and -- 'Word64'. -- ----------------------------------------------------------------------------- #include "MachDeps.h" -- #hide module GHC.Word ( Word(..), Word8(..), Word16(..), Word32(..), Word64(..), uncheckedShiftL64#, uncheckedShiftRL64# ) where import Data.Bits #if WORD_SIZE_IN_BITS < 64 import GHC.IntWord64 #endif import GHC.HasteWordInt import GHC.Base import GHC.Enum import GHC.Num import GHC.Real import GHC.Read import GHC.Arr import GHC.Show import GHC.Err import GHC.Float () -- for RealFrac methods ------------------------------------------------------------------------ -- type Word8 ------------------------------------------------------------------------ -- Word8 is represented in the same way as Word. Operations may assume -- and must ensure that it holds only values from its logical range. #if __GLASGOW_HASKELL__ >= 706 data {-# CTYPE "HsWord8" #-} Word8 = W8# Word# deriving (Eq, Ord) #else data Word8 = W8# Word# deriving (Eq, Ord) #endif -- ^ 8-bit unsigned integer type instance Show Word8 where showsPrec p x = showsPrec p (fromIntegral x :: Int) instance Num Word8 where (W8# x#) + (W8# y#) = W8# (narrow8Word# (x# `plusWord#` y#)) (W8# x#) - (W8# y#) = W8# (narrow8Word# (x# `minusWord#` y#)) (W8# x#) * (W8# y#) = W8# (narrow8Word# (x# `timesWord#` y#)) negate (W8# x#) = W8# (narrow8Word# (i2w (negateInt# (w2i x#)))) abs x = x signum 0 = 0 signum _ = 1 fromInteger i = W8# (narrow8Word# (integerToWord i)) instance Real Word8 where toRational x = toInteger x % 1 instance Enum Word8 where succ x | x /= maxBound = x + 1 | otherwise = succError "Word8" pred x | x /= minBound = x - 1 | otherwise = predError "Word8" toEnum i@(I# i#) | i >= 0 && i <= fromIntegral (maxBound::Word8) = W8# (i2w i#) | otherwise = toEnumError "Word8" i (minBound::Word8, maxBound::Word8) fromEnum (W8# x#) = I# (w2i x#) enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen instance Integral Word8 where quot (W8# x#) y@(W8# y#) | y /= 0 = W8# (x# `quotWord#` y#) | otherwise = divZeroError rem (W8# x#) y@(W8# y#) | y /= 0 = W8# (x# `remWord#` y#) | otherwise = divZeroError div (W8# x#) y@(W8# y#) | y /= 0 = W8# (x# `quotWord#` y#) | otherwise = divZeroError mod (W8# x#) y@(W8# y#) | y /= 0 = W8# (x# `remWord#` y#) | otherwise = divZeroError quotRem (W8# x#) y@(W8# y#) | y /= 0 = case x# `quotRemWord#` y# of (# q, r #) -> (W8# q, W8# r) | otherwise = divZeroError divMod (W8# x#) y@(W8# y#) | y /= 0 = (W8# (x# `quotWord#` y#), W8# (x# `remWord#` y#)) | otherwise = divZeroError toInteger (W8# x#) = smallInteger (w2i x#) instance Bounded Word8 where minBound = 0 maxBound = 0xFF instance Ix Word8 where range (m,n) = [m..n] unsafeIndex (m,_) i = fromIntegral (i - m) inRange (m,n) i = m <= i && i <= n instance Read Word8 where readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s] instance Bits Word8 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (W8# x#) .&. (W8# y#) = W8# (x# `and#` y#) (W8# x#) .|. (W8# y#) = W8# (x# `or#` y#) (W8# x#) `xor` (W8# y#) = W8# (x# `xor#` y#) complement (W8# x#) = W8# (x# `xor#` mb#) where !(W8# mb#) = maxBound (W8# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = W8# (narrow8Word# (x# `shiftL#` i#)) | otherwise = W8# (x# `shiftRL#` negateInt# i#) (W8# x#) `shiftL` (I# i#) = W8# (narrow8Word# (x# `shiftL#` i#)) (W8# x#) `unsafeShiftL` (I# i#) = W8# (narrow8Word# (x# `uncheckedShiftL#` i#)) (W8# x#) `shiftR` (I# i#) = W8# (x# `shiftRL#` i#) (W8# x#) `unsafeShiftR` (I# i#) = W8# (x# `uncheckedShiftRL#` i#) (W8# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = W8# x# | otherwise = W8# (narrow8Word# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (8# -# i'#)))) where !i'# = w2i (i2w i# `and#` 7##) bitSize _ = 8 isSigned _ = False popCount (W8# x#) = I# (w2i (popCnt8# x#)) bit = bitDefault testBit = testBitDefault {-# RULES "fromIntegral/Word8->Word8" fromIntegral = id :: Word8 -> Word8 "fromIntegral/Word8->Integer" fromIntegral = toInteger :: Word8 -> Integer "fromIntegral/a->Word8" fromIntegral = \x -> case fromIntegral x of W# x# -> W8# (narrow8Word# x#) "fromIntegral/Word8->a" fromIntegral = \(W8# x#) -> fromIntegral (W# x#) #-} {-# RULES "properFraction/Float->(Word8,Float)" forall x. properFraction (x :: Float) = case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Word8) n, y) } "truncate/Float->Word8" forall x. truncate (x :: Float) = (fromIntegral :: Int -> Word8) (truncate x) "floor/Float->Word8" forall x. floor (x :: Float) = (fromIntegral :: Int -> Word8) (floor x) "ceiling/Float->Word8" forall x. ceiling (x :: Float) = (fromIntegral :: Int -> Word8) (ceiling x) "round/Float->Word8" forall x. round (x :: Float) = (fromIntegral :: Int -> Word8) (round x) #-} {-# RULES "properFraction/Double->(Word8,Double)" forall x. properFraction (x :: Double) = case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Word8) n, y) } "truncate/Double->Word8" forall x. truncate (x :: Double) = (fromIntegral :: Int -> Word8) (truncate x) "floor/Double->Word8" forall x. floor (x :: Double) = (fromIntegral :: Int -> Word8) (floor x) "ceiling/Double->Word8" forall x. ceiling (x :: Double) = (fromIntegral :: Int -> Word8) (ceiling x) "round/Double->Word8" forall x. round (x :: Double) = (fromIntegral :: Int -> Word8) (round x) #-} ------------------------------------------------------------------------ -- type Word16 ------------------------------------------------------------------------ -- Word16 is represented in the same way as Word. Operations may assume -- and must ensure that it holds only values from its logical range. #if __GLASGOW_HASKELL__ >= 706 data {-# CTYPE "HsWord16" #-} Word16 = W16# Word# deriving (Eq, Ord) #else data Word16 = W16# Word# deriving (Eq, Ord) #endif -- ^ 16-bit unsigned integer type instance Show Word16 where showsPrec p x = showsPrec p (fromIntegral x :: Int) instance Num Word16 where (W16# x#) + (W16# y#) = W16# (narrow16Word# (x# `plusWord#` y#)) (W16# x#) - (W16# y#) = W16# (narrow16Word# (x# `minusWord#` y#)) (W16# x#) * (W16# y#) = W16# (narrow16Word# (x# `timesWord#` y#)) negate (W16# x#) = W16# (narrow16Word# (i2w (negateInt# (w2i x#)))) abs x = x signum 0 = 0 signum _ = 1 fromInteger i = W16# (narrow16Word# (integerToWord i)) instance Real Word16 where toRational x = toInteger x % 1 instance Enum Word16 where succ x | x /= maxBound = x + 1 | otherwise = succError "Word16" pred x | x /= minBound = x - 1 | otherwise = predError "Word16" toEnum i@(I# i#) | i >= 0 && i <= fromIntegral (maxBound::Word16) = W16# (i2w i#) | otherwise = toEnumError "Word16" i (minBound::Word16, maxBound::Word16) fromEnum (W16# x#) = I# (w2i x#) enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen instance Integral Word16 where quot (W16# x#) y@(W16# y#) | y /= 0 = W16# (x# `quotWord#` y#) | otherwise = divZeroError rem (W16# x#) y@(W16# y#) | y /= 0 = W16# (x# `remWord#` y#) | otherwise = divZeroError div (W16# x#) y@(W16# y#) | y /= 0 = W16# (x# `quotWord#` y#) | otherwise = divZeroError mod (W16# x#) y@(W16# y#) | y /= 0 = W16# (x# `remWord#` y#) | otherwise = divZeroError quotRem (W16# x#) y@(W16# y#) | y /= 0 = case x# `quotRemWord#` y# of (# q, r #) -> (W16# q, W16# r) | otherwise = divZeroError divMod (W16# x#) y@(W16# y#) | y /= 0 = (W16# (x# `quotWord#` y#), W16# (x# `remWord#` y#)) | otherwise = divZeroError toInteger (W16# x#) = smallInteger (w2i x#) instance Bounded Word16 where minBound = 0 maxBound = 0xFFFF instance Ix Word16 where range (m,n) = [m..n] unsafeIndex (m,_) i = fromIntegral (i - m) inRange (m,n) i = m <= i && i <= n instance Read Word16 where readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s] instance Bits Word16 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (W16# x#) .&. (W16# y#) = W16# (x# `and#` y#) (W16# x#) .|. (W16# y#) = W16# (x# `or#` y#) (W16# x#) `xor` (W16# y#) = W16# (x# `xor#` y#) complement (W16# x#) = W16# (x# `xor#` mb#) where !(W16# mb#) = maxBound (W16# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = W16# (narrow16Word# (x# `shiftL#` i#)) | otherwise = W16# (x# `shiftRL#` negateInt# i#) (W16# x#) `shiftL` (I# i#) = W16# (narrow16Word# (x# `shiftL#` i#)) (W16# x#) `unsafeShiftL` (I# i#) = W16# (narrow16Word# (x# `uncheckedShiftL#` i#)) (W16# x#) `shiftR` (I# i#) = W16# (x# `shiftRL#` i#) (W16# x#) `unsafeShiftR` (I# i#) = W16# (x# `uncheckedShiftRL#` i#) (W16# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = W16# x# | otherwise = W16# (narrow16Word# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (16# -# i'#)))) where !i'# = w2i (i2w i# `and#` 15##) bitSize _ = 16 isSigned _ = False popCount (W16# x#) = I# (w2i (popCnt16# x#)) bit = bitDefault testBit = testBitDefault {-# RULES "fromIntegral/Word8->Word16" fromIntegral = \(W8# x#) -> W16# x# "fromIntegral/Word16->Word16" fromIntegral = id :: Word16 -> Word16 "fromIntegral/Word16->Integer" fromIntegral = toInteger :: Word16 -> Integer "fromIntegral/a->Word16" fromIntegral = \x -> case fromIntegral x of W# x# -> W16# (narrow16Word# x#) "fromIntegral/Word16->a" fromIntegral = \(W16# x#) -> fromIntegral (W# x#) #-} {-# RULES "properFraction/Float->(Word16,Float)" forall x. properFraction (x :: Float) = case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Word16) n, y) } "truncate/Float->Word16" forall x. truncate (x :: Float) = (fromIntegral :: Int -> Word16) (truncate x) "floor/Float->Word16" forall x. floor (x :: Float) = (fromIntegral :: Int -> Word16) (floor x) "ceiling/Float->Word16" forall x. ceiling (x :: Float) = (fromIntegral :: Int -> Word16) (ceiling x) "round/Float->Word16" forall x. round (x :: Float) = (fromIntegral :: Int -> Word16) (round x) #-} {-# RULES "properFraction/Double->(Word16,Double)" forall x. properFraction (x :: Double) = case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Word16) n, y) } "truncate/Double->Word16" forall x. truncate (x :: Double) = (fromIntegral :: Int -> Word16) (truncate x) "floor/Double->Word16" forall x. floor (x :: Double) = (fromIntegral :: Int -> Word16) (floor x) "ceiling/Double->Word16" forall x. ceiling (x :: Double) = (fromIntegral :: Int -> Word16) (ceiling x) "round/Double->Word16" forall x. round (x :: Double) = (fromIntegral :: Int -> Word16) (round x) #-} ------------------------------------------------------------------------ -- type Word32 ------------------------------------------------------------------------ -- Word32 is represented in the same way as Word. #if WORD_SIZE_IN_BITS > 32 -- Operations may assume and must ensure that it holds only values -- from its logical range. -- We can use rewrite rules for the RealFrac methods {-# RULES "properFraction/Float->(Word32,Float)" forall x. properFraction (x :: Float) = case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Word32) n, y) } "truncate/Float->Word32" forall x. truncate (x :: Float) = (fromIntegral :: Int -> Word32) (truncate x) "floor/Float->Word32" forall x. floor (x :: Float) = (fromIntegral :: Int -> Word32) (floor x) "ceiling/Float->Word32" forall x. ceiling (x :: Float) = (fromIntegral :: Int -> Word32) (ceiling x) "round/Float->Word32" forall x. round (x :: Float) = (fromIntegral :: Int -> Word32) (round x) #-} {-# RULES "properFraction/Double->(Word32,Double)" forall x. properFraction (x :: Double) = case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Word32) n, y) } "truncate/Double->Word32" forall x. truncate (x :: Double) = (fromIntegral :: Int -> Word32) (truncate x) "floor/Double->Word32" forall x. floor (x :: Double) = (fromIntegral :: Int -> Word32) (floor x) "ceiling/Double->Word32" forall x. ceiling (x :: Double) = (fromIntegral :: Int -> Word32) (ceiling x) "round/Double->Word32" forall x. round (x :: Double) = (fromIntegral :: Int -> Word32) (round x) #-} #endif #if __GLASGOW_HASKELL__ >= 706 data {-# CTYPE "HsWord32" #-} Word32 = W32# Word# deriving (Eq, Ord) #else data Word32 = W32# Word# deriving (Eq, Ord) #endif -- ^ 32-bit unsigned integer type instance Num Word32 where (W32# x#) + (W32# y#) = W32# (narrow32Word# (x# `plusWord#` y#)) (W32# x#) - (W32# y#) = W32# (narrow32Word# (x# `minusWord#` y#)) (W32# x#) * (W32# y#) = W32# (narrow32Word# (x# `timesWord#` y#)) negate (W32# x#) = W32# (narrow32Word# (i2w (negateInt# (w2i x#)))) abs x = x signum 0 = 0 signum _ = 1 fromInteger i = W32# (narrow32Word# (integerToWord i)) instance Enum Word32 where succ x | x /= maxBound = x + 1 | otherwise = succError "Word32" pred x | x /= minBound = x - 1 | otherwise = predError "Word32" toEnum i@(I# i#) | i >= 0 #if WORD_SIZE_IN_BITS > 32 && i <= fromIntegral (maxBound::Word32) #endif = W32# (i2w i#) | otherwise = toEnumError "Word32" i (minBound::Word32, maxBound::Word32) #if WORD_SIZE_IN_BITS == 32 fromEnum x@(W32# x#) | x <= fromIntegral (maxBound::Int) = I# (w2i x#) | otherwise = fromEnumError "Word32" x enumFrom = integralEnumFrom enumFromThen = integralEnumFromThen enumFromTo = integralEnumFromTo enumFromThenTo = integralEnumFromThenTo #else fromEnum (W32# x#) = I# (w2i x#) enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen #endif instance Integral Word32 where quot (W32# x#) y@(W32# y#) | y /= 0 = W32# (x# `quotWord#` y#) | otherwise = divZeroError rem (W32# x#) y@(W32# y#) | y /= 0 = W32# (x# `remWord#` y#) | otherwise = divZeroError div (W32# x#) y@(W32# y#) | y /= 0 = W32# (x# `quotWord#` y#) | otherwise = divZeroError mod (W32# x#) y@(W32# y#) | y /= 0 = W32# (x# `remWord#` y#) | otherwise = divZeroError quotRem (W32# x#) y@(W32# y#) | y /= 0 = case x# `quotRemWord#` y# of (# q, r #) -> (W32# q, W32# r) | otherwise = divZeroError divMod (W32# x#) y@(W32# y#) | y /= 0 = (W32# (x# `quotWord#` y#), W32# (x# `remWord#` y#)) | otherwise = divZeroError toInteger (W32# x#) #if WORD_SIZE_IN_BITS == 32 | isTrue# (i# >=# 0#) = smallInteger i# | otherwise = wordToInteger x# where !i# = w2i x# #else = smallInteger (w2i x#) #endif instance Bits Word32 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (W32# x#) .&. (W32# y#) = W32# (x# `and#` y#) (W32# x#) .|. (W32# y#) = W32# (x# `or#` y#) (W32# x#) `xor` (W32# y#) = W32# (x# `xor#` y#) complement (W32# x#) = W32# (x# `xor#` mb#) where !(W32# mb#) = maxBound (W32# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = W32# (narrow32Word# (x# `shiftL#` i#)) | otherwise = W32# (x# `shiftRL#` negateInt# i#) (W32# x#) `shiftL` (I# i#) = W32# (narrow32Word# (x# `shiftL#` i#)) (W32# x#) `unsafeShiftL` (I# i#) = W32# (narrow32Word# (x# `uncheckedShiftL#` i#)) (W32# x#) `shiftR` (I# i#) = W32# (x# `shiftRL#` i#) (W32# x#) `unsafeShiftR` (I# i#) = W32# (x# `uncheckedShiftRL#` i#) (W32# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = W32# x# | otherwise = W32# (narrow32Word# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (32# -# i'#)))) where !i'# = w2i (i2w i# `and#` 31##) bitSize _ = 32 isSigned _ = False popCount (W32# x#) = I# (w2i (popCnt32# x#)) bit = bitDefault testBit = testBitDefault {-# RULES "fromIntegral/Word8->Word32" fromIntegral = \(W8# x#) -> W32# x# "fromIntegral/Word16->Word32" fromIntegral = \(W16# x#) -> W32# x# "fromIntegral/Word32->Word32" fromIntegral = id :: Word32 -> Word32 "fromIntegral/Word32->Integer" fromIntegral = toInteger :: Word32 -> Integer "fromIntegral/a->Word32" fromIntegral = \x -> case fromIntegral x of W# x# -> W32# (narrow32Word# x#) "fromIntegral/Word32->a" fromIntegral = \(W32# x#) -> fromIntegral (W# x#) #-} instance Show Word32 where #if WORD_SIZE_IN_BITS < 33 showsPrec p x = showsPrec p (toInteger x) #else showsPrec p x = showsPrec p (fromIntegral x :: Int) #endif instance Real Word32 where toRational x = toInteger x % 1 instance Bounded Word32 where minBound = 0 maxBound = 0xFFFFFFFF instance Ix Word32 where range (m,n) = [m..n] unsafeIndex (m,_) i = fromIntegral (i - m) inRange (m,n) i = m <= i && i <= n instance Read Word32 where #if WORD_SIZE_IN_BITS < 33 readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s] #else readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s] #endif ------------------------------------------------------------------------ -- type Word64 ------------------------------------------------------------------------ #if __GLASGOW_HASKELL__ >= 706 data {-# CTYPE "HsWord64" #-} Word64 = W64# Word64# #else data Word64 = W64# Word64# #endif -- ^ 64-bit unsigned integer type instance Eq Word64 where (W64# x#) == (W64# y#) = x# `eqWord64#` y# (W64# x#) /= (W64# y#) = x# `neWord64#` y# instance Ord Word64 where (W64# x#) < (W64# y#) = x# `ltWord64#` y# (W64# x#) <= (W64# y#) = x# `leWord64#` y# (W64# x#) > (W64# y#) = x# `gtWord64#` y# (W64# x#) >= (W64# y#) = x# `geWord64#` y# instance Num Word64 where (W64# x#) + (W64# y#) = W64# (int64ToWord64# (word64ToInt64# x# `plusInt64#` word64ToInt64# y#)) (W64# x#) - (W64# y#) = W64# (int64ToWord64# (word64ToInt64# x# `minusInt64#` word64ToInt64# y#)) (W64# x#) * (W64# y#) = W64# (int64ToWord64# (word64ToInt64# x# `timesInt64#` word64ToInt64# y#)) negate (W64# x#) = W64# (int64ToWord64# (negateInt64# (word64ToInt64# x#))) abs x = x signum 0 = 0 signum _ = 1 fromInteger i = W64# (integerToWord64 i) instance Enum Word64 where succ x | x /= maxBound = x + 1 | otherwise = succError "Word64" pred x | x /= minBound = x - 1 | otherwise = predError "Word64" toEnum i@(I# i#) | i >= 0 = W64# (wordToWord64# (i2w i#)) | otherwise = toEnumError "Word64" i (minBound::Word64, maxBound::Word64) fromEnum x@(W64# x#) | x <= fromIntegral (maxBound::Int) = I# (w2i (word64ToWord# x#)) | otherwise = fromEnumError "Word64" x enumFrom = integralEnumFrom enumFromThen = integralEnumFromThen enumFromTo = integralEnumFromTo enumFromThenTo = integralEnumFromThenTo instance Integral Word64 where quot (W64# x#) y@(W64# y#) | y /= 0 = W64# (x# `quotWord64#` y#) | otherwise = divZeroError rem (W64# x#) y@(W64# y#) | y /= 0 = W64# (x# `remWord64#` y#) | otherwise = divZeroError div (W64# x#) y@(W64# y#) | y /= 0 = W64# (x# `quotWord64#` y#) | otherwise = divZeroError mod (W64# x#) y@(W64# y#) | y /= 0 = W64# (x# `remWord64#` y#) | otherwise = divZeroError quotRem (W64# x#) y@(W64# y#) | y /= 0 = (W64# (x# `quotWord64#` y#), W64# (x# `remWord64#` y#)) | otherwise = divZeroError divMod (W64# x#) y@(W64# y#) | y /= 0 = (W64# (x# `quotWord64#` y#), W64# (x# `remWord64#` y#)) | otherwise = divZeroError toInteger (W64# x#) = word64ToInteger x# instance Bits Word64 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (W64# x#) .&. (W64# y#) = W64# (x# `and64#` y#) (W64# x#) .|. (W64# y#) = W64# (x# `or64#` y#) (W64# x#) `xor` (W64# y#) = W64# (x# `xor64#` y#) complement (W64# x#) = W64# (not64# x#) (W64# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = W64# (x# `shiftL64#` i#) | otherwise = W64# (x# `shiftRL64#` negateInt# i#) (W64# x#) `shiftL` (I# i#) = W64# (x# `shiftL64#` i#) (W64# x#) `unsafeShiftL` (I# i#) = W64# (x# `uncheckedShiftL64#` i#) (W64# x#) `shiftR` (I# i#) = W64# (x# `shiftRL64#` i#) (W64# x#) `unsafeShiftR` (I# i#) = W64# (x# `uncheckedShiftRL64#` i#) (W64# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = W64# x# | otherwise = W64# ((x# `uncheckedShiftL64#` i'#) `or64#` (x# `uncheckedShiftRL64#` (64# -# i'#))) where !i'# = w2i (i2w i# `and#` 63##) bitSize _ = 64 isSigned _ = False popCount = popcnt bit = bitDefault testBit = testBitDefault -- Count bits manually, since we don't have any appropriate primops available -- when the host machine is 64 bit and we're compiling to 32. :( popcnt :: Word64 -> Int popcnt 0 = 0 popcnt x | x .&. 1 == 1 = 1 + popcnt (x `shiftR` 1) | otherwise = popcnt (x `shiftR` 1) -- give the 64-bit shift operations the same treatment as the 32-bit -- ones (see GHC.Base), namely we wrap them in tests to catch the -- cases when we're shifting more than 64 bits to avoid unspecified -- behaviour in the C shift operations. shiftL64#, shiftRL64# :: Word64# -> Int# -> Word64# a `shiftL64#` b | isTrue# (b >=# 64#) = wordToWord64# 0## | otherwise = a `uncheckedShiftL64#` b a `shiftRL64#` b | isTrue# (b >=# 64#) = wordToWord64# 0## | otherwise = a `uncheckedShiftRL64#` b {-# RULES "fromIntegral/Int->Word64" fromIntegral = \(I# x#) -> W64# (int64ToWord64# (intToInt64# x#)) "fromIntegral/Word->Word64" fromIntegral = \(W# x#) -> W64# (wordToWord64# x#) "fromIntegral/Word64->Int" fromIntegral = \(W64# x#) -> I# (w2i (word64ToWord# x#)) "fromIntegral/Word64->Word" fromIntegral = \(W64# x#) -> W# (word64ToWord# x#) "fromIntegral/Word64->Word64" fromIntegral = id :: Word64 -> Word64 #-} instance Show Word64 where showsPrec p x = showsPrec p (toInteger x) instance Real Word64 where toRational x = toInteger x % 1 instance Bounded Word64 where minBound = 0 maxBound = 0xFFFFFFFFFFFFFFFF instance Ix Word64 where range (m,n) = [m..n] unsafeIndex (m,_) i = fromIntegral (i - m) inRange (m,n) i = m <= i && i <= n instance Read Word64 where readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
beni55/haste-compiler
libraries/ghc-7.8/base/GHC/Word.hs
Haskell
bsd-3-clause
26,222