code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
class P a where
foo :: a
instance P () where
foo = ()
data (P a, Q a) => X a = B [a]
a = B[()]
(a,b) = B[()]
[C a b, A (b,B c), c,b] = B[()]
f x y = x + y
x + y = x * y
(x+y) = 4
| forste/haReFork | tools/base/tests/pTest1.hs | bsd-3-clause | 195 | 1 | 8 | 73 | 180 | 94 | 86 | -1 | -1 |
module ListOrgRepos where
import qualified Github.Repos as Github
import Data.List
import Data.Maybe
main = do
possibleRepos <- Github.organizationRepos "thoughtbot"
case possibleRepos of
(Left error) -> putStrLn $ "Error: " ++ (show error)
(Right repos) -> putStrLn $ intercalate "\n\n" $ map formatRepo repos
formatRepo repo =
(Github.repoName repo) ++ "\t" ++
(fromMaybe "" $ Github.repoDescription repo) ++ "\n" ++
(Github.repoHtmlUrl repo) ++ "\n" ++
(Github.repoCloneUrl repo) ++ "\t" ++
(formatDate $ Github.repoUpdatedAt repo) ++ "\n" ++
formatLanguage (Github.repoLanguage repo) ++
"watchers: " ++ (show $ Github.repoWatchers repo) ++ "\t" ++
"forks: " ++ (show $ Github.repoForks repo)
formatDate = show . Github.fromGithubDate
formatLanguage (Just language) = "language: " ++ language ++ "\t"
formatLanguage Nothing = ""
| mavenraven/github | samples/Repos/ListOrgRepos.hs | bsd-3-clause | 886 | 0 | 22 | 170 | 295 | 149 | 146 | 21 | 2 |
{-# LANGUAGE CPP, RankNTypes #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2010
--
-- The Session type and related functionality
--
-- -----------------------------------------------------------------------------
module GhcMonad (
-- * 'Ghc' monad stuff
GhcMonad(..),
Ghc(..),
GhcT(..), liftGhcT,
reflectGhc, reifyGhc,
getSessionDynFlags,
liftIO,
Session(..), withSession, modifySession, withTempSession,
-- ** Warnings
logWarnings, printException,
WarnErrLogger, defaultWarnErrLogger
) where
import MonadUtils
import HscTypes
import DynFlags
import Exception
import ErrUtils
import Data.IORef
-- -----------------------------------------------------------------------------
-- | A monad that has all the features needed by GHC API calls.
--
-- In short, a GHC monad
--
-- - allows embedding of IO actions,
--
-- - can log warnings,
--
-- - allows handling of (extensible) exceptions, and
--
-- - maintains a current session.
--
-- If you do not use 'Ghc' or 'GhcT', make sure to call 'GHC.initGhcMonad'
-- before any call to the GHC API functions can occur.
--
class (Functor m, MonadIO m, ExceptionMonad m, HasDynFlags m) => GhcMonad m where
getSession :: m HscEnv
setSession :: HscEnv -> m ()
-- | Call the argument with the current session.
withSession :: GhcMonad m => (HscEnv -> m a) -> m a
withSession f = getSession >>= f
-- | Grabs the DynFlags from the Session
getSessionDynFlags :: GhcMonad m => m DynFlags
getSessionDynFlags = withSession (return . hsc_dflags)
-- | Set the current session to the result of applying the current session to
-- the argument.
modifySession :: GhcMonad m => (HscEnv -> HscEnv) -> m ()
modifySession f = do h <- getSession
setSession $! f h
withSavedSession :: GhcMonad m => m a -> m a
withSavedSession m = do
saved_session <- getSession
m `gfinally` setSession saved_session
-- | Call an action with a temporarily modified Session.
withTempSession :: GhcMonad m => (HscEnv -> HscEnv) -> m a -> m a
withTempSession f m =
withSavedSession $ modifySession f >> m
-- -----------------------------------------------------------------------------
-- | A monad that allows logging of warnings.
logWarnings :: GhcMonad m => WarningMessages -> m ()
logWarnings warns = do
dflags <- getSessionDynFlags
liftIO $ printOrThrowWarnings dflags warns
-- -----------------------------------------------------------------------------
-- | A minimal implementation of a 'GhcMonad'. If you need a custom monad,
-- e.g., to maintain additional state consider wrapping this monad or using
-- 'GhcT'.
newtype Ghc a = Ghc { unGhc :: Session -> IO a }
-- | The Session is a handle to the complete state of a compilation
-- session. A compilation session consists of a set of modules
-- constituting the current program or library, the context for
-- interactive evaluation, and various caches.
data Session = Session !(IORef HscEnv)
instance Functor Ghc where
fmap f m = Ghc $ \s -> f `fmap` unGhc m s
instance Applicative Ghc where
pure = return
g <*> m = do f <- g; a <- m; return (f a)
instance Monad Ghc where
return a = Ghc $ \_ -> return a
m >>= g = Ghc $ \s -> do a <- unGhc m s; unGhc (g a) s
instance MonadIO Ghc where
liftIO ioA = Ghc $ \_ -> ioA
instance MonadFix Ghc where
mfix f = Ghc $ \s -> mfix (\x -> unGhc (f x) s)
instance ExceptionMonad Ghc where
gcatch act handle =
Ghc $ \s -> unGhc act s `gcatch` \e -> unGhc (handle e) s
gmask f =
Ghc $ \s -> gmask $ \io_restore ->
let
g_restore (Ghc m) = Ghc $ \s -> io_restore (m s)
in
unGhc (f g_restore) s
instance HasDynFlags Ghc where
getDynFlags = getSessionDynFlags
instance GhcMonad Ghc where
getSession = Ghc $ \(Session r) -> readIORef r
setSession s' = Ghc $ \(Session r) -> writeIORef r s'
-- | Reflect a computation in the 'Ghc' monad into the 'IO' monad.
--
-- You can use this to call functions returning an action in the 'Ghc' monad
-- inside an 'IO' action. This is needed for some (too restrictive) callback
-- arguments of some library functions:
--
-- > libFunc :: String -> (Int -> IO a) -> IO a
-- > ghcFunc :: Int -> Ghc a
-- >
-- > ghcFuncUsingLibFunc :: String -> Ghc a -> Ghc a
-- > ghcFuncUsingLibFunc str =
-- > reifyGhc $ \s ->
-- > libFunc $ \i -> do
-- > reflectGhc (ghcFunc i) s
--
reflectGhc :: Ghc a -> Session -> IO a
reflectGhc m = unGhc m
-- > Dual to 'reflectGhc'. See its documentation.
reifyGhc :: (Session -> IO a) -> Ghc a
reifyGhc act = Ghc $ act
-- -----------------------------------------------------------------------------
-- | A monad transformer to add GHC specific features to another monad.
--
-- Note that the wrapped monad must support IO and handling of exceptions.
newtype GhcT m a = GhcT { unGhcT :: Session -> m a }
liftGhcT :: m a -> GhcT m a
liftGhcT m = GhcT $ \_ -> m
instance Functor m => Functor (GhcT m) where
fmap f m = GhcT $ \s -> f `fmap` unGhcT m s
instance Applicative m => Applicative (GhcT m) where
pure x = GhcT $ \_ -> pure x
g <*> m = GhcT $ \s -> unGhcT g s <*> unGhcT m s
instance Monad m => Monad (GhcT m) where
return x = GhcT $ \_ -> return x
m >>= k = GhcT $ \s -> do a <- unGhcT m s; unGhcT (k a) s
instance MonadIO m => MonadIO (GhcT m) where
liftIO ioA = GhcT $ \_ -> liftIO ioA
instance ExceptionMonad m => ExceptionMonad (GhcT m) where
gcatch act handle =
GhcT $ \s -> unGhcT act s `gcatch` \e -> unGhcT (handle e) s
gmask f =
GhcT $ \s -> gmask $ \io_restore ->
let
g_restore (GhcT m) = GhcT $ \s -> io_restore (m s)
in
unGhcT (f g_restore) s
#if __GLASGOW_HASKELL__ < 710
-- Pre-AMP change
instance (ExceptionMonad m, Functor m) => HasDynFlags (GhcT m) where
#else
instance (ExceptionMonad m) => HasDynFlags (GhcT m) where
#endif
getDynFlags = getSessionDynFlags
#if __GLASGOW_HASKELL__ < 710
-- Pre-AMP change
instance (ExceptionMonad m, Functor m) => GhcMonad (GhcT m) where
#else
instance (ExceptionMonad m) => GhcMonad (GhcT m) where
#endif
getSession = GhcT $ \(Session r) -> liftIO $ readIORef r
setSession s' = GhcT $ \(Session r) -> liftIO $ writeIORef r s'
-- | Print the error message and all warnings. Useful inside exception
-- handlers. Clears warnings after printing.
printException :: GhcMonad m => SourceError -> m ()
printException err = do
dflags <- getSessionDynFlags
liftIO $ printBagOfErrors dflags (srcErrorMessages err)
-- | A function called to log warnings and errors.
type WarnErrLogger = forall m. GhcMonad m => Maybe SourceError -> m ()
defaultWarnErrLogger :: WarnErrLogger
defaultWarnErrLogger Nothing = return ()
defaultWarnErrLogger (Just e) = printException e
| urbanslug/ghc | compiler/main/GhcMonad.hs | bsd-3-clause | 7,086 | 0 | 18 | 1,651 | 1,729 | 912 | 817 | 106 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-
Copyright (C) 2008-2015 John MacFarlane <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Writers.ODT
Copyright : Copyright (C) 2008-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to ODT.
-}
module Text.Pandoc.Writers.ODT ( writeODT ) where
import Data.IORef
import Data.List ( isPrefixOf )
import Data.Maybe ( fromMaybe )
import Text.XML.Light.Output
import Text.TeXMath
import qualified Data.ByteString.Lazy as B
import Text.Pandoc.UTF8 ( fromStringLazy )
import Codec.Archive.Zip
import Control.Applicative ((<$>))
import Text.Pandoc.Options ( WriterOptions(..) )
import Text.Pandoc.Shared ( stringify, fetchItem', warn,
getDefaultReferenceODT )
import Text.Pandoc.ImageSize ( imageSize, sizeInPoints )
import Text.Pandoc.MIME ( getMimeType, extensionFromMimeType )
import Text.Pandoc.Definition
import Text.Pandoc.Walk
import Text.Pandoc.Writers.Shared ( fixDisplayMath )
import Text.Pandoc.Writers.OpenDocument ( writeOpenDocument )
import Control.Monad (liftM)
import Text.Pandoc.XML
import Text.Pandoc.Pretty
import qualified Control.Exception as E
import Data.Time.Clock.POSIX ( getPOSIXTime )
import System.FilePath ( takeExtension, takeDirectory, (<.>))
-- | Produce an ODT file from a Pandoc document.
writeODT :: WriterOptions -- ^ Writer options
-> Pandoc -- ^ Document to convert
-> IO B.ByteString
writeODT opts doc@(Pandoc meta _) = do
let datadir = writerUserDataDir opts
let title = docTitle meta
refArchive <-
case writerReferenceODT opts of
Just f -> liftM toArchive $ B.readFile f
Nothing -> getDefaultReferenceODT datadir
-- handle formulas and pictures
picEntriesRef <- newIORef ([] :: [Entry])
doc' <- walkM (transformPicMath opts picEntriesRef) $ walk fixDisplayMath doc
let newContents = writeOpenDocument opts{writerWrapText = False} doc'
epochtime <- floor `fmap` getPOSIXTime
let contentEntry = toEntry "content.xml" epochtime
$ fromStringLazy newContents
picEntries <- readIORef picEntriesRef
let archive = foldr addEntryToArchive refArchive
$ contentEntry : picEntries
-- construct META-INF/manifest.xml based on archive
let toFileEntry fp = case getMimeType fp of
Nothing -> empty
Just m -> selfClosingTag "manifest:file-entry"
[("manifest:media-type", m)
,("manifest:full-path", fp)
,("manifest:version", "1.2")
]
let files = [ ent | ent <- filesInArchive archive,
not ("META-INF" `isPrefixOf` ent) ]
let formulas = [ takeDirectory ent ++ "/" | ent <- filesInArchive archive,
"Formula-" `isPrefixOf` ent, takeExtension ent == ".xml" ]
let manifestEntry = toEntry "META-INF/manifest.xml" epochtime
$ fromStringLazy $ render Nothing
$ text "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
$$
( inTags True "manifest:manifest"
[("xmlns:manifest","urn:oasis:names:tc:opendocument:xmlns:manifest:1.0")
,("manifest:version","1.2")]
$ ( selfClosingTag "manifest:file-entry"
[("manifest:media-type","application/vnd.oasis.opendocument.text")
,("manifest:full-path","/")]
$$ vcat ( map toFileEntry $ files )
$$ vcat ( map toFileEntry $ formulas )
)
)
let archive' = addEntryToArchive manifestEntry archive
let metaEntry = toEntry "meta.xml" epochtime
$ fromStringLazy $ render Nothing
$ text "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
$$
( inTags True "office:document-meta"
[("xmlns:office","urn:oasis:names:tc:opendocument:xmlns:office:1.0")
,("xmlns:xlink","http://www.w3.org/1999/xlink")
,("xmlns:dc","http://purl.org/dc/elements/1.1/")
,("xmlns:meta","urn:oasis:names:tc:opendocument:xmlns:meta:1.0")
,("xmlns:ooo","http://openoffice.org/2004/office")
,("xmlns:grddl","http://www.w3.org/2003/g/data-view#")
,("office:version","1.2")]
$ ( inTagsSimple "office:meta"
$ ( inTagsSimple "dc:title" (text $ escapeStringForXML (stringify title))
)
)
)
-- make sure mimetype is first
let mimetypeEntry = toEntry "mimetype" epochtime
$ fromStringLazy "application/vnd.oasis.opendocument.text"
let archive'' = addEntryToArchive mimetypeEntry
$ addEntryToArchive metaEntry archive'
return $ fromArchive archive''
transformPicMath :: WriterOptions -> IORef [Entry] -> Inline -> IO Inline
transformPicMath opts entriesRef (Image lab (src,t)) = do
res <- fetchItem' (writerMediaBag opts) (writerSourceURL opts) src
case res of
Left (_ :: E.SomeException) -> do
warn $ "Could not find image `" ++ src ++ "', skipping..."
return $ Emph lab
Right (img, mbMimeType) -> do
(w,h) <- case imageSize img of
Right size -> return $ sizeInPoints size
Left msg -> do
warn $ "Could not determine image size in `" ++
src ++ "': " ++ msg
return (0,0)
let tit' = show w ++ "x" ++ show h
entries <- readIORef entriesRef
let extension = fromMaybe (takeExtension $ takeWhile (/='?') src)
(mbMimeType >>= extensionFromMimeType)
let newsrc = "Pictures/" ++ show (length entries) <.> extension
let toLazy = B.fromChunks . (:[])
epochtime <- floor `fmap` getPOSIXTime
let entry = toEntry newsrc epochtime $ toLazy img
modifyIORef entriesRef (entry:)
let fig | "fig:" `isPrefixOf` t = "fig:"
| otherwise = ""
return $ Image lab (newsrc, fig++tit')
transformPicMath _ entriesRef (Math t math) = do
entries <- readIORef entriesRef
let dt = if t == InlineMath then DisplayInline else DisplayBlock
case writeMathML dt <$> readTeX math of
Left _ -> return $ Math t math
Right r -> do
let conf = useShortEmptyTags (const False) defaultConfigPP
let mathml = ppcTopElement conf r
epochtime <- floor `fmap` getPOSIXTime
let dirname = "Formula-" ++ show (length entries) ++ "/"
let fname = dirname ++ "content.xml"
let entry = toEntry fname epochtime (fromStringLazy mathml)
modifyIORef entriesRef (entry:)
return $ RawInline (Format "opendocument") $ render Nothing $
inTags False "draw:frame" [("text:anchor-type",
if t == DisplayMath
then "paragraph"
else "as-char")
,("style:vertical-pos", "middle")
,("style:vertical-rel", "text")] $
selfClosingTag "draw:object" [("xlink:href", dirname)
, ("xlink:type", "simple")
, ("xlink:show", "embed")
, ("xlink:actuate", "onLoad")]
transformPicMath _ _ x = return x
| mindriot101/pandoc | src/Text/Pandoc/Writers/ODT.hs | gpl-2.0 | 8,274 | 0 | 21 | 2,414 | 1,778 | 926 | 852 | 138 | 6 |
-- !!! THIS TEST IS FOR TYPE SYNONYMS AND FACTORISATION IN THEIR PRESENCE.
module Test where
data M a = A | B a (M a)
data L a = N | C a (Syn a)
type Syn b = L b
idL :: L (Syn c) -> L (Syn c)
idL N = N
idL (C x l) = C x (idL l)
idM:: M (L (Syn x)) -> M (L (Syn x))
idM A = A
idM (B x l) = B (idL x) (idM l)
| ezyang/ghc | testsuite/tests/stranal/should_compile/syn.hs | bsd-3-clause | 325 | 0 | 10 | 106 | 199 | 103 | 96 | 10 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Webbing.Database (Database, postgresql, sqlite) where
import Control.Monad.Logger (NoLoggingT, runNoLoggingT)
import Control.Monad.Trans.Resource (runResourceT, ResourceT)
import Data.ByteString (ByteString)
import Data.Monoid ((<>))
import Data.Text (pack)
import Data.Text.Encoding (encodeUtf8)
import Database.Persist.Sql (runSqlConn, SqlPersistT)
import Database.Persist.Postgresql (withPostgresqlConn)
import Database.Persist.Sqlite (withSqliteConn)
import Webbing.WebHerokuCopy (dbConnParams)
type Database a = SqlPersistT (ResourceT (NoLoggingT IO)) a -> IO a
sqlite :: String -> Database a
sqlite name = runNoLoggingT . runResourceT . withSqliteConn (pack name) . runSqlConn
connStr :: IO ByteString
connStr = do
params <- dbConnParams
return $ foldr (\(k,v) t -> t <> (encodeUtf8 $ k <> "=" <> v <> " ")) "" params
postgresql' :: ByteString -> Database a
postgresql' cs = runNoLoggingT . runResourceT . withPostgresqlConn cs . runSqlConn
postgresql :: IO (Database a)
postgresql = fmap postgresql' connStr
| ejconlon/webbing | src/Webbing/Database.hs | mit | 1,073 | 0 | 16 | 146 | 340 | 190 | 150 | 23 | 1 |
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.ClientNamenodeProtocolProtos.GetCurrentEditLogTxidRequestProto (GetCurrentEditLogTxidRequestProto(..)) where
import Prelude ((+), (/))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data GetCurrentEditLogTxidRequestProto = GetCurrentEditLogTxidRequestProto{}
deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable GetCurrentEditLogTxidRequestProto where
mergeAppend GetCurrentEditLogTxidRequestProto GetCurrentEditLogTxidRequestProto = GetCurrentEditLogTxidRequestProto
instance P'.Default GetCurrentEditLogTxidRequestProto where
defaultValue = GetCurrentEditLogTxidRequestProto
instance P'.Wire GetCurrentEditLogTxidRequestProto where
wireSize ft' self'@(GetCurrentEditLogTxidRequestProto)
= case ft' of
10 -> calc'Size
11 -> P'.prependMessageSize calc'Size
_ -> P'.wireSizeErr ft' self'
where
calc'Size = 0
wirePut ft' self'@(GetCurrentEditLogTxidRequestProto)
= case ft' of
10 -> put'Fields
11 -> do
P'.putSize (P'.wireSize 10 self')
put'Fields
_ -> P'.wirePutErr ft' self'
where
put'Fields
= do
Prelude'.return ()
wireGet ft'
= case ft' of
10 -> P'.getBareMessageWith update'Self
11 -> P'.getMessageWith update'Self
_ -> P'.wireGetErr ft'
where
update'Self wire'Tag old'Self
= case wire'Tag of
_ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
instance P'.MessageAPI msg' (msg' -> GetCurrentEditLogTxidRequestProto) GetCurrentEditLogTxidRequestProto where
getVal m' f' = f' m'
instance P'.GPB GetCurrentEditLogTxidRequestProto
instance P'.ReflectDescriptor GetCurrentEditLogTxidRequestProto where
getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [])
reflectDescriptorInfo _
= Prelude'.read
"DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.hdfs.GetCurrentEditLogTxidRequestProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"ClientNamenodeProtocolProtos\"], baseName = MName \"GetCurrentEditLogTxidRequestProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"ClientNamenodeProtocolProtos\",\"GetCurrentEditLogTxidRequestProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
instance P'.TextType GetCurrentEditLogTxidRequestProto where
tellT = P'.tellSubMessage
getT = P'.getSubMessage
instance P'.TextMsg GetCurrentEditLogTxidRequestProto where
textPut msg = Prelude'.return ()
textGet = Prelude'.return P'.defaultValue | alexbiehl/hoop | hadoop-protos/src/Hadoop/Protos/ClientNamenodeProtocolProtos/GetCurrentEditLogTxidRequestProto.hs | mit | 3,137 | 1 | 16 | 543 | 554 | 291 | 263 | 53 | 0 |
{-# htermination group :: (Eq a, Eq k) => [(a, k)] -> [[(a, k)]] #-}
import List
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/List_group_12.hs | mit | 81 | 0 | 3 | 17 | 5 | 3 | 2 | 1 | 0 |
import System.IO
import System.Environment
import Data.List
import Data.List.Split
import Data.Bits
import Data.Function
import Data.Time.Clock.POSIX
import Data.Time.Format
import Data.Time
import System.Posix.Files
import System.Posix.Directory
import System.Locale
main = do
args <- getArgs
let f = getFlags $ filter isFlag args
let paths = filter (not.isFlag) args
if (paths == [])
then printAllFiles "." f
else do
let mult = f .|. if length paths == 2 then 8 else 0
mapM_ (`printAllFiles` mult) paths
isFlag :: String -> Bool
isFlag ('-':a:xs) = a /= '-'
isFlag _ = False
getFlags :: [String] -> Int
getFlags [] = 0
getFlags a = foldl (.|.) 0 $ map getFlagValue $ concat a
getFlagValue :: Char -> Int
getFlagValue f
| f == 'a' = 1
| f == 'l' = 2
| f == 'R' = 12
| otherwise = 0
printAllFiles :: FilePath -> Int -> IO()
printAllFiles p f = do
if (f .&. 8 /= 0)
then putStrLn (p ++ ":")
else return ()
strm <- openDirStream p
files <- listAllFiles strm f
if (f .&. 2 /= 0)
then printDetailList p (sort files)
else printList files 80
closeDirStream strm
if (f .&. 8 /= 0) then putStrLn "" else return ()
if (f .&. 4 /= 0)
then do
recursivePrint p files f
else return()
recursivePrint :: FilePath -> [String] -> Int -> IO ()
recursivePrint p [] f = return ()
recursivePrint p (x:xs) f = do
let path = (p ++ "/" ++ x)
status <- getFileStatus path
if (isDirectory status && x /= "." && x /= "..")
then do
printAllFiles path f
recursivePrint p xs f
else do recursivePrint p xs f
printDetailList :: FilePath -> [String] -> IO ()
printDetailList _ [] = return()
printDetailList p (x:xs) = do
let path = (p ++ "/" ++ x)
status <- getFileStatus path
let mode = fileMode status
putChar $ getFileType status
putChar (if ownerReadMode .&. mode == 0 then 'r' else '-')
putChar (if ownerWriteMode .&. mode == 0 then 'w' else '-')
putChar (if ownerExecuteMode .&. mode == 0 then 'x' else '-')
putChar (if groupReadMode .&. mode == 0 then 'r' else '-')
putChar (if groupWriteMode .&. mode == 0 then 'w' else '-')
putChar (if groupExecuteMode .&. mode == 0 then 'x' else '-')
putChar (if otherReadMode .&. mode == 0 then 'r' else '-')
putChar (if otherWriteMode .&. mode == 0 then 'w' else '-')
putChar (if otherExecuteMode .&. mode == 0 then 'x' else '-')
putChar ' '
putStr $ padString 2 $ show $ linkCount status
putChar ' '
putStr $ padString 8 $ show $ fileOwner status
putChar ' '
putStr $ padString 8 $ show $ fileGroup status
putChar ' '
putStr $ padString 10 $ show $ fileSize status
putChar ' '
let time = posixSecondsToUTCTime.fromIntegral.fromEnum $ modificationTime status
putStr $ formatTime defaultTimeLocale "%h %d %H:%M" time
putChar ' '
putStrLn x
printDetailList p xs
printList :: [String] -> Int -> IO ()
printList f w = do
let max = (+) 1 $ maximum $ map length f
let cols = div w max
let files = map (padString max) $ sort f
mapM_ putStrLn $ map concat (chunksOf cols files)
getFileType :: FileStatus -> Char
getFileType s
| isBlockDevice s = 'b'
| isCharacterDevice s = 'c'
| isNamedPipe s = 'p'
| isDirectory s = 'd'
| isSymbolicLink s = 'l'
| isSocket s = 's'
| isRegularFile s = '-'
| otherwise = '?'
padString :: Int -> String -> String
padString w s =
s ++ (replicate x ' ')
where
x = w-length s
listAllFiles :: DirStream -> Int -> IO [String]
listAllFiles s f = do
file <- readDirStream s
if (file == "")
then return []
else do
list <- listAllFiles s f
if (file !! 0 /= '.' || f .&. 1 /= 0)
then return $ file:list
else return list
| Liniarc/rshell | src/ls.hs | mit | 3,941 | 0 | 16 | 1,147 | 1,583 | 768 | 815 | 119 | 10 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE UndecidableSuperClasses #-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}
module AI.Funn.CL.Layers.Misc where
import Control.Monad
import Control.Monad.IO.Class
import Data.Foldable
import Data.List
import Data.Monoid
import Data.Proxy
import Data.Traversable
import GHC.TypeLits
import qualified AI.Funn.CL.DSL.AST as AST
import AI.Funn.CL.DSL.Array
import AI.Funn.CL.DSL.Code as C
import AI.Funn.CL.DSL.Tensor
import AI.Funn.CL.Function
import AI.Funn.CL.MonadCL
import AI.Funn.CL.Tensor (Tensor, MTensor)
import qualified AI.Funn.CL.Tensor as Tensor
import AI.Funn.Diff.Diff (Derivable(..), Diff(..))
import AI.Funn.Space
import AI.Funn.TypeLits
{-# NOINLINE fillSquare #-}
fillSquare :: KernelProgram '[MTensorCL [w,h]]
fillSquare = compile $ \arr -> do
~[x, y] <- traverse get_global_id [0,1]
arr ! [x,y] .= castExpr x + castExpr y
{-# NOINLINE iconv2dForward #-}
iconv2dForward :: KernelProgram '[TensorCL [k, k, c1, c2],
TensorCL [ow + k - 1, oh + k - 1, c1],
MTensorCL [ow, oh, c2]]
iconv2dForward = compile $ \flt input output -> do
~[ox, oy, oc] <- traverse get_global_id [0, 1, 2]
let [k, _, c1, c2] = dimsOf flt
acc <- eval 0
forEach 0 k $ \kx -> do
forEach 0 k $ \ky -> do
forEach 0 c1 $ \ic -> do
acc .= acc + flt![kx, ky, ic, oc] * input![ox + kx, oy + ky, ic]
output![ox, oy, oc] .= acc
{-# NOINLINE iconv2dBackward #-}
iconv2dBackward :: KernelProgram '[TensorCL [k, k, c1, c2],
MTensorCL [ow + k - 1, oh + k - 1, c1],
TensorCL [ow, oh, c2]]
iconv2dBackward = compile $ \flt d_input d_output -> do
~[ix, iy, ic] <- traverse get_global_id [0, 1, 2]
let [kw, kh, c1, c2] = dimsOf flt
let [iw, ih, _] = dimsOf d_input
acc <- eval 0
kernel_x1 <- eval $ fmax 0 (kw - (iw - ix))
kernel_x2 <- eval $ fmin kw (ix + 1)
kernel_y1 <- eval $ fmax 0 (kh - (ih - iy))
kernel_y2 <- eval $ fmin kh (iy + 1)
forEach kernel_x1 kernel_x2 $ \kx -> do
forEach kernel_y1 kernel_y2 $ \ky -> do
forEach 0 c2 $ \oc -> do
acc .= acc + flt![kx, ky, ic, oc] * d_output![ix - kx, iy - ky, oc]
d_input![ix, iy, ic] .= acc
{-# NOINLINE iconv2dFilter #-}
iconv2dFilter :: KernelProgram '[MTensorCL [k, k, c1, c2],
TensorCL [ow + k - 1, oh + k - 1, c1],
TensorCL [ow, oh, c2]]
iconv2dFilter = compile $ \d_flt input d_output -> do
~[kx, ky, ic, oc] <- get_global_id 0 >>= splitIndex (dimsOf d_flt)
let [ow, oh, _] = dimsOf d_output
acc <- eval 0
forEach 0 ow $ \ox -> do
forEach 0 oh $ \oy -> do
acc .= acc + input![ox + kx, oy + ky, ic] * d_output![ox, oy, oc]
d_flt![kx, ky, ic, oc] .= acc
iconv2dDiff :: forall k ow oh c1 c2 m. (MonadIO m, KnownDims [k, ow, oh, c1, c2],
(1 <=? k) ~ 'True)
=> Diff m
(Tensor [k, k, c1, c2], Tensor [ow + k - 1, oh + k - 1, c1])
(Tensor [ow, oh, c2])
iconv2dDiff = Diff run
where
run (flt, input) = do
output <- Tensor.new @ [ow, oh, c2]
liftIO (clfun iconv2dForward (dimVal output) flt input output :: IO ())
return (Tensor.unsafeFreeze output, backward flt input)
backward flt input d_output = do
d_input <- Tensor.new
liftIO (clfun iconv2dBackward (dimVal d_input) flt d_input d_output :: IO ())
d_flt <- Tensor.new
liftIO (clfun iconv2dFilter [dimSize d_flt] d_flt input d_output :: IO ())
return (Tensor.unsafeFreeze d_flt, Tensor.unsafeFreeze d_input)
| nshepperd/funn | AI/Funn/CL/Layers/Misc.hs | mit | 4,285 | 0 | 25 | 1,220 | 1,582 | 869 | 713 | 100 | 1 |
module Main where
main:: IO ()
main = do
check
putStrLn $ show "Hello??"
checkNum :: Num a => [a] -> Int -> Bool
checkNum [] _ = False
checkNum xs limit = let x = length $ filter (\ x -> x >= 0) xs in x > limit | funfunStudy/algorithm | haskell/src/main/haskell/angryProfessor/Main.hs | mit | 216 | 0 | 13 | 55 | 113 | 57 | 56 | 8 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module GitIssues.Types
where
import Data.Aeson (FromJSON, ToJSON, decode, encode)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy as ByteStringL
import GHC.Generics (Generic)
import System.Directory
import System.FilePath
data IssueState = IssueStateOpen
| IssueStateClosed
deriving(Eq, Generic, Show)
instance ToJSON IssueState
instance FromJSON IssueState
-- data IssueProvider = IssueProviderGithub
-- deriving(Generic, Show)
-- instance ToJSON IssueProvider
-- instance FromJSON IssueProvider
-- type IssueId = Int
data Issue = Issue { issueTitle :: String
, issueBody :: String
, issueNumber :: Int
, issueState :: IssueState
-- , issueOrigin :: (IssueProvider, IssueId)
}
deriving(Generic, Show)
instance ToJSON Issue
instance FromJSON Issue
data Store = Store { storeLatestIssue :: Int
, storeIssues :: [Issue]
}
deriving(Generic, Show)
instance ToJSON Store
instance FromJSON Store
readOrCreateStore :: String -> IO Store
readOrCreateStore repo = do
storeExists <- doesFileExist (repo </> ".issues.json")
if storeExists
then readStore repo
else createStore repo
readStore :: String -> IO Store
readStore repo = do
mstore <- decode <$> ByteStringL.readFile (repo </> ".issues.json")
case mstore of
Just store -> return store
Nothing -> error "Failed to parse .issues.json"
createStore :: String -> IO Store
createStore repo = do
let store = Store { storeLatestIssue = 0
, storeIssues = []
}
writeStore repo store
return store
writeStore :: String -> Store -> IO ()
writeStore repo store =
ByteStringL.writeFile (repo </> ".issues.json") $
encodePretty' defConfig { confIndent = 2 } store
| yamadapc/git-issues | src/GitIssues/Types.hs | mit | 2,022 | 0 | 12 | 603 | 455 | 244 | 211 | 47 | 2 |
module Main where
import System.Exit
import EndOfCentralDirectoryRecord
import LocalFileHeader
import Util
import qualified Data.Vector.Unboxed as Vec
main = do
print $ intToBytes (256*256+2) 4
print $ bytesToInt $ Vec.fromList [2,0,1,0]
exitFailure
| kaisellgren/zip.hs | src/Main.hs | mit | 264 | 0 | 11 | 45 | 86 | 49 | 37 | 10 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Helper (
module Test.Hspec
, module Control.Applicative
, module Network.HTTP.Types
, Req (..)
, withHttpServer
) where
import Test.Hspec
import Control.Applicative
import Control.Exception
import Control.Concurrent
import Data.IORef
import Control.Monad.IO.Class (liftIO)
import Network.HTTP.Types
import Network.Wai
import Network.Wai.Handler.Warp
import Data.ByteString.Lazy
import Data.Conduit.Lazy
import Control.DeepSeq
data Req = Req {
reqMethod :: Method
, reqHeaders :: RequestHeaders
, reqBody :: ByteString
} deriving (Eq, Show)
toReq :: Request -> IO Req
toReq r = do
b <- body r
b `deepseq` (return $ Req (requestMethod r) (requestHeaders r) b)
where
body :: Request -> IO ByteString
body = fmap fromChunks . lazyConsume . requestBody
withHttpServer :: Status -> ResponseHeaders -> ByteString -> (IO Req -> IO a) -> IO a
withHttpServer status headers body action = do
ref <- newIORef (error "No request received!")
withApplication (app ref) $ do
action (readIORef ref)
where
app :: IORef Req -> Application
app ref request = do
liftIO $ toReq request >>= writeIORef ref
return (responseLBS status headers body)
withApplication :: Application -> IO a -> IO a
withApplication app action = do
started <- newEmptyMVar
stopped <- newEmptyMVar
threadId <- forkIO $
runSettings defaultSettings {settingsPort = 3000, settingsBeforeMainLoop = putMVar started ()} app `finally` putMVar stopped ()
takeMVar started
action `finally` (killThread threadId >> takeMVar stopped)
| sol/rest-client | test/Helper.hs | mit | 1,705 | 0 | 14 | 403 | 514 | 270 | 244 | 47 | 1 |
{-|
Module : CodeGen.LLVM.Prep
Description : Map a module to a syntax more amenable to LLVM translation.
Copyright : (c) Michael Lopez, 2017
License : MIT
Maintainer : m-lopez (github)
Stability : unstable
Portability : non-portable
LLVM IR is a simple language containing functions, declarations, and
simple expressions in SSA form. Toaster has exotic high-level objects
such as closures. This file contains a mapping from elaborated expressions
and a C-like IR called PreLLVM.
-}
module CodeGen.LLVM.Prep ( prep ) where
import Expressions (
CType(..),
Expr(..),
ExprName(..),
QType(..),
TlExpr(..),
TypeName(..) )
import qualified LLVM.AST.Type as T
import Util.DebugOr ( DebugOr, mkSuccess, fromDebugOr )
import Builtins ( builtinsCtx )
import Context ( Ctx, lookupSignature, varValue )
import Data.List ( intercalate )
import Data.Maybe ( mapMaybe )
-- | Transforms a Toaster program to a C-like representation for LLVM code
-- generation.
prep :: [TlExpr] -> DebugOr [TlExpr]
prep tls = do
let tls' = correctMain tls
cs <- removeNonConcrete tls'
resolved <- resolve builtinsCtx cs
mangled <- mangle resolved
return $ delambdaTopLevel mangled
-- | Removes all non-concrete code.
removeNonConcrete :: [TlExpr] -> DebugOr [TlExpr]
removeNonConcrete = mkSuccess . mapMaybe onlyIfConcrete
where
onlyIfConcrete tl = case tl of
TlDef _ (Unquantified _) _ -> Just tl
TlFuncDef {} -> Just tl
_ -> Nothing
-- | Transform constants that have a lambda initializers to functions.
delambdaTopLevel :: [TlExpr] -> [TlExpr]
delambdaTopLevel = map delambda
where
delambda tl = case tl of
TlDef x (Unquantified (CTArrow _ t)) (EAbs bs e) ->
TlFuncDef x (deExprName bs) t e
_ -> tl
deExprName = map (\(ExprName x, t) -> (x,t))
-- | Transform main into a function.
correctMain :: [TlExpr] -> [TlExpr]
correctMain = map replaceIfMain
where
replaceIfMain tl = case tl of
TlDef "main" (Unquantified t) e -> TlFuncDef "main" [] t e
_ -> tl
-- | Mangles all names by type to ensure uniqueness.
mangle :: [TlExpr] -> DebugOr [TlExpr]
mangle = traverse mangleTopLevel
where
mangleTopLevel (TlDef x qt@(Unquantified ct) e) =
TlDef <$> name <*> typ <*> expr
where
name = appendTypeSuffix x ct
typ = return qt
expr = mangleExpr e
mangleTopLevel (TlFuncDef x bs ct e) =
TlFuncDef <$> name <*> bindings <*> retType <*> expr
where
arrowT = CTArrow (map snd bs) ct
name = if x == "main" then return x else appendTypeSuffix x arrowT
bindings = traverse mangleBinding bs
retType = return ct
expr = mangleExpr e
mangleTopLevel (TlDef _ (Quantified _ _ _) _) =
fail "mangler found a quantified top-level definition"
-- | Appends a type suffix to a string.
-- I would really like `$` to delimit names from types, but Haskell shorts are
-- messed up.
appendTypeSuffix :: String -> CType -> DebugOr String
appendTypeSuffix x t = mangleCType t >>= (\y -> return $ x ++ "." ++ y)
-- | Mangles an expression.
mangleExpr :: Expr -> DebugOr Expr
mangleExpr e = case e of
EVar (ExprName x) qt@(Unquantified t) -> EVar <$> name <*> return qt
where
name = ExprName <$> appendTypeSuffix x t
EAbs bs e' -> EAbs <$> bs' <*> mangleExpr e'
where
bs' = traverse mangleExprBinding bs
EApp e' es -> EApp <$> mangleExpr e' <*> traverse mangleExpr es
EIf e1 e2 e3 -> EIf <$> mangleExpr e1 <*> mangleExpr e2 <*> mangleExpr e3
_ -> mkSuccess e
mangleBinding :: (String, CType) -> DebugOr (String, CType)
mangleBinding (s, t) = do
s' <- appendTypeSuffix s t
return (s', t)
mangleExprBinding :: (ExprName, CType) -> DebugOr (ExprName, CType)
mangleExprBinding (ExprName s, t) = do
s' <- appendTypeSuffix s t
return (ExprName s', t)
-- | Transform a `CType` to a `String`.
mangleCType :: CType -> DebugOr String
mangleCType t = case t of
CTBool -> mkSuccess "b"
CTI32 -> mkSuccess "i32"
CTArrow argTs resT -> do
argStrs <- traverse mangleCType argTs
let argsStr = intercalate "." argStrs
resStr <- mangleCType resT
return $ "arrow" ++ argsStr ++ "." ++ resStr ++ ".."
CTVar (TypeName s) -> fail $ "found type variable `" ++ s ++ "` while mangling"
-- | Transform a CType into an LLVM.AST.Type.
toLlvmType :: CType -> T.Type
toLlvmType t = case t of
CTBool -> T.IntegerType 32
CTI32 -> T.IntegerType 32
CTArrow _ _ -> T.IntegerType 32
CTVar _ -> T.IntegerType 32
-- | Resolve built-ins with respect to a context.
resolve :: Ctx -> [TlExpr] -> DebugOr [TlExpr]
resolve ctx = traverse (resolveDef ctx)
where
resolveDef :: Ctx -> TlExpr -> DebugOr TlExpr
resolveDef ctx tl = case tl of
TlDef x ct e -> TlDef x ct <$> resolveExpr ctx e
TlFuncDef x bs ct e -> TlFuncDef x bs ct <$> resolveExpr ctx e
resolveExpr :: Ctx -> Expr -> DebugOr Expr
resolveExpr ctx e = case e of
ELitBool _ -> mkSuccess e
ELitInt _ -> mkSuccess e
EVar x (Unquantified ct) -> resolveVar ctx x ct
EVar x Quantified {} -> fail "found a quantified variable while resolving"
EAbs bs e' -> EAbs bs <$> resolveExpr ctx e'
EApp e' es ->
EApp <$> resolveExpr ctx e' <*> traverse (resolveExpr ctx) es
EIf e1 e2 e3 ->
EIf <$> resolveExpr ctx e1 <*> resolveExpr ctx e2 <*> resolveExpr ctx e3
EUnBuiltin {} -> mkSuccess e
EBinBuiltin {} -> mkSuccess e
resolveVar :: Ctx -> ExprName -> CType -> DebugOr Expr
resolveVar ctx x ct = case maybeGetInit ctx x ct of
Just e@(EUnBuiltin {}) -> mkSuccess e
Just e@(EBinBuiltin {}) -> mkSuccess e
_ -> mkSuccess $ EVar x (Unquantified ct)
maybeGetInit :: Ctx -> ExprName -> CType -> Maybe Expr
maybeGetInit ctx x ct = fromDebugOr lkp varValue (const Nothing)
where
lkp = lookupSignature ctx x (Unquantified ct)
| m-lopez/jack | src/CodeGen/LLVM/Prep.hs | mit | 5,917 | 0 | 14 | 1,410 | 1,835 | 922 | 913 | 117 | 12 |
module BadMonad where
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes
data CountMe a =
CountMe Integer a
deriving (Eq, Show)
instance Functor CountMe where
fmap f (CountMe i a) = CountMe i (f a)
instance Applicative CountMe where
pure = CountMe 0
(<*>) (CountMe n f) (CountMe n' a) = CountMe (n + n') (f a)
instance Monad CountMe where
return = pure
(>>=) (CountMe n a) f =
let CountMe n' b = f a
in CountMe (n + n') b
instance Arbitrary a => Arbitrary (CountMe a) where
arbitrary = CountMe <$> arbitrary <*> arbitrary
instance Eq a => EqProp (CountMe a) where
(=-=) = eq
main :: IO ()
main = do
let trigger = undefined :: CountMe (Int, String, Int)
quickBatch $ functor trigger
quickBatch $ applicative trigger
quickBatch $ monad trigger
| andrewMacmurray/haskell-book-solutions | src/ch18/BadMonad.hs | mit | 820 | 0 | 11 | 178 | 339 | 174 | 165 | 27 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module: Network.SIP.Type.Message
-- Description: Core type of SIP parser.
-- Copyright: Copyright (c) 2015-2016 Jan Sipr
-- License: MIT
--
-- Message type is core type of the whole parser. This type is the output from
-- parser and it is also the input to serialization.
module Network.SIP.Type.Message
( Message (..)
, MessageType (..)
)
where
import Data.ByteString (ByteString)
import Data.Data (Data)
import Data.Eq (Eq)
import Data.Maybe (Maybe)
import GHC.Generics (Generic)
import Text.Show (Show)
import Network.SIP.Type.Header (Header)
import Network.SIP.Type.RequestMethod (RequestMethod)
import Network.SIP.Type.ResponseStatus (Status)
import Network.SIP.Type.Uri (Uri)
-- Performance test
import Control.DeepSeq (NFData)
data MessageType =
Request
{ rqMethod :: RequestMethod
, rqUri :: Uri
}
| Response
{ rspStatus :: Status
}
deriving (Show, Generic, Data, NFData, Eq)
data Message = Message
{ msgType :: MessageType
, msgHeaders :: [Header]
, msgBody :: Maybe ByteString
}
deriving (Show, Generic, Data, NFData, Eq)
| Siprj/ragnarok | src/Network/SIP/Type/Message.hs | mit | 1,311 | 0 | 9 | 267 | 267 | 169 | 98 | 31 | 0 |
{-|
Module : Database.Orville.PostgreSQL.Internal.RelationalMap
Copyright : Flipstone Technology Partners 2016-2018
License : MIT
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RecordWildCards #-}
module Database.Orville.PostgreSQL.Internal.RelationalMap
( mkTableDefinition
, TableParams(..)
, RelationalMap
, fields
, mapAttr
, mapField
, attrField
, maybeMapper
, prefixMap
, partialMap
, readOnlyMap
, readOnlyField
) where
import Control.Monad (join, when)
import Control.Monad.Reader (ask)
import Control.Monad.State (modify)
import Data.Profunctor (Profunctor(lmap, rmap))
import Database.Orville.PostgreSQL.Internal.FieldDefinition
import Database.Orville.PostgreSQL.Internal.FromSql
import Database.Orville.PostgreSQL.Internal.Types
{-|
'TableParams' is the simplest way to make a 'TableDefinition'. You
can use 'mkTableDefinition' to make a definition from the simplified
params. Where 'TableDefinition' requires the 'tableFields', 'tableFromSql',
and 'tableToSql' to all be defined separately and kept in sync, 'TableParams'
provides a single 'tblMapper' field that specifies all three simultaneously
and ensures they are consistent with one another.
-}
data TableParams readEntity writeEntity key = TableParams
{ tblName :: String
-- ^ The name of the table in the database
, tblMapper :: RelationalMap writeEntity readEntity
-- ^ The relational mapping that defines how the Haskell entity type
-- is converted both to and from sql. The fields utilized in the mapping
-- are used to automatically build the list of 'FieldDefinitions' that
-- define the structure of the table in the database.
, tblSafeToDelete :: [String]
-- ^ A list of any columns that may be deleted from the table by Orville.
-- (Orville will never delete a column without being told it is safe)
, tblPrimaryKey :: PrimaryKey key
-- ^ A function to set the key on the entity
, tblGetKey :: readEntity -> key
-- ^ A function to get the key on the entity
, tblComments :: TableComments ()
-- ^ Any comments that might be interesting for developers to see. These
-- comments will get printed in the log if there is an erro while attempting
-- to migrate the table.
}
{-|
'mkTableDefinition' converts a 'TableParams' to 'TableDefinition'. Usually
this is used directly on a record literal of the 'TableParams'. For
example:
@
data Foo key = Foo key { fooId :: Record }
myTable :: TableDefinition Foo
myTable = mkTableDefinition $
TableParams
{ tblName = "foo"
, tblMapper = User <$> attrField fooId idField
, tableSafeToDelete = []
, tblSetKey = \key foo -> foo { fooId = key }
, tblGetKey = fooId
, tblComments = []
}
@
-}
mkTableDefinition ::
TableParams readEntity writeEntity key
-> TableDefinition readEntity writeEntity key
mkTableDefinition (TableParams {..}) =
TableDefinition
{ tableFields = fields tblMapper
, tableFromSql = mkFromSql tblPrimaryKey tblMapper
, tableToSql = mkToSql tblMapper
, tablePrimaryKey = tblPrimaryKey
, tableName = tblName
, tableSafeToDelete = tblSafeToDelete
, tableGetKey = tblGetKey
, tableComments = tblComments
}
data RelationalMap a b where
RM_Field :: FieldDefinition nullability a -> RelationalMap a a
RM_Nest :: (a -> b) -> RelationalMap b c -> RelationalMap a c
RM_Pure :: b -> RelationalMap a b
RM_Apply
:: RelationalMap a (b -> c) -> RelationalMap a b -> RelationalMap a c
RM_Partial :: RelationalMap a (Either String a) -> RelationalMap a a
RM_ReadOnly :: RelationalMap a b -> RelationalMap c b
RM_MaybeTag
:: RelationalMap (Maybe a) (Maybe b) -> RelationalMap (Maybe a) (Maybe b)
instance Functor (RelationalMap a) where
fmap f rm = pure f <*> rm
instance Applicative (RelationalMap a) where
pure = RM_Pure
(<*>) = RM_Apply
instance Profunctor RelationalMap where
rmap = fmap
lmap = mapAttr
mapAttr :: (a -> b) -> RelationalMap b c -> RelationalMap a c
mapAttr = RM_Nest
mapField :: FieldDefinition nullability a -> RelationalMap a a
mapField = RM_Field
partialMap :: RelationalMap a (Either String a) -> RelationalMap a a
partialMap = RM_Partial
readOnlyMap :: RelationalMap a b -> RelationalMap c b
readOnlyMap = RM_ReadOnly
attrField :: (a -> b) -> FieldDefinition nullability b -> RelationalMap a b
attrField get = mapAttr get . mapField
readOnlyField :: FieldDefinition nullability a -> RelationalMap b a
readOnlyField = readOnlyMap . mapField
prefixMap :: String -> RelationalMap a b -> RelationalMap a b
prefixMap prefix (RM_Nest f rm) = RM_Nest f (prefixMap prefix rm)
prefixMap prefix (RM_Field f) = RM_Field (f `withPrefix` prefix)
prefixMap prefix (RM_Apply rmF rmA) =
RM_Apply (prefixMap prefix rmF) (prefixMap prefix rmA)
prefixMap prefix (RM_Partial rm) = RM_Partial (prefixMap prefix rm)
prefixMap prefix (RM_ReadOnly rm) = RM_ReadOnly (prefixMap prefix rm)
prefixMap prefix (RM_MaybeTag rm) = RM_MaybeTag (prefixMap prefix rm)
prefixMap _ rm@(RM_Pure _) = rm
maybeMapper :: RelationalMap a b -> RelationalMap (Maybe a) (Maybe b)
maybeMapper
-- rewrite the mapper to handle null fields, then tag
-- it as having been done so we don't double-map it
-- in a future `maybeMapper` call.
--
= RM_MaybeTag . go
where
go :: RelationalMap a b -> RelationalMap (Maybe a) (Maybe b)
go (RM_Nest f rm) = RM_Nest (fmap f) (go rm)
go (RM_Field f) =
case checkNullability f of
NotNullField notNullField ->
RM_Field (nullableField notNullField)
NullableField nullField ->
-- When the underlying field is already nullable we need to make sure
-- that 'NULL' is decoded to a 'Just'. Otherwise when the field is
-- 'NULL' it causes the entire 'RelationalMap' to resolve to a
-- 'Nothing' as if _all_ fields were 'NULL', even if they were not.
RM_Field (asymmetricNullableField nullField)
go (RM_Pure a) = RM_Pure (pure a)
go (RM_Apply rmF rmA) = RM_Apply (fmap (<*>) $ go rmF) (go rmA)
go (RM_Partial rm) = RM_Partial (flipError <$> go rm)
where
flipError :: Maybe (Either String a) -> Either String (Maybe a)
flipError (Just (Right a)) = Right (Just a)
flipError (Just (Left err)) = Left err
flipError Nothing = Right Nothing
go (RM_ReadOnly rm) = RM_ReadOnly (go rm)
go rm@(RM_MaybeTag _) = fmap Just $ mapAttr join $ rm
fields :: RelationalMap a b -> [SomeField]
fields (RM_Field field) = [SomeField field]
fields (RM_Apply rm1 rm2) = fields rm1 ++ fields rm2
fields (RM_Nest _ rm) = fields rm
fields (RM_Partial rm) = fields rm
fields (RM_MaybeTag rm) = fields rm
fields (RM_Pure _) = []
fields (RM_ReadOnly rm) =
map (someFieldWithFlag AssignedByDatabase) (fields rm)
where
someFieldWithFlag flag (SomeField f) = SomeField (f `withFlag` flag)
mkFromSql :: PrimaryKey key -> RelationalMap a b -> FromSql b
mkFromSql (PrimaryKey pKeyPart pKeyParts) relMap =
fromSql
{ runFromSql = \columns ->
-- lookup the primary key columns
let keyNames = map getColName (pKeyPart : pKeyParts)
primKeys = filter ((`elem` keyNames) . fst) columns
in case runFromSql fromSql columns of
-- Add the primary key(s) to relevant error messages
Left (RowDataError details) ->
Left $ RowDataError details
{ rowErrorPrimaryKeys = primKeys }
Left (ConversionError details) ->
Left $ ConversionError details
{ convErrorPrimaryKeys = primKeys }
x -> x
}
where
fromSql = fromRelMap relMap
getColName (PrimaryKeyPart _ fieldDef) = fieldName fieldDef
fromRelMap :: RelationalMap a b -> FromSql b
fromRelMap (RM_Field field) = fieldFromSql field
fromRelMap (RM_Nest _ rm) = fromRelMap rm
fromRelMap (RM_ReadOnly rm) = fromRelMap rm
fromRelMap (RM_MaybeTag rm) = fromRelMap rm
fromRelMap (RM_Pure b) = pure b
fromRelMap (RM_Apply rmF rmC) = fromRelMap rmF <*> fromRelMap rmC
fromRelMap (RM_Partial rm) = do
joinFromSqlError (wrapError <$> fromRelMap rm)
wrapError = either (Left . simpleConversionError) Right
mkToSql :: RelationalMap a b -> ToSql a ()
mkToSql (RM_Field field) =
when (not $ isAssignedByDatabaseField field) $ do
value <- ask
modify (fieldToSqlValue field value :)
mkToSql (RM_Nest f rm) = getComponent f (mkToSql rm)
mkToSql (RM_Apply rmF rmC) = mkToSql rmF >> mkToSql rmC
mkToSql (RM_Partial rm) = mkToSql rm
mkToSql (RM_MaybeTag rm) = mkToSql rm
mkToSql (RM_ReadOnly _) = pure ()
mkToSql (RM_Pure _) = pure ()
| flipstone/orville | orville-postgresql/src/Database/Orville/PostgreSQL/Internal/RelationalMap.hs | mit | 8,768 | 0 | 16 | 1,963 | 2,179 | 1,123 | 1,056 | 149 | 10 |
{-# LANGUAGE FlexibleInstances #-}
module JavaScript.Cocos2d.Types where
import Data.Time
import qualified Data.Aeson as A
import qualified Data.JSString as JS
import qualified Data.Text as T
import Data.Word
import Data.Colour as C
import Data.Colour.SRGB
import Diagrams
import GHCJS.Types
import GHCJS.Marshal
import GHCJS.Marshal.Pure
----- Helpers
-- copied from JavaScript.JSON.Types.Instances
formatMillis :: (FormatTime t) => t -> String
formatMillis t = take 3 . formatTime defaultTimeLocale "%q" $ t
foreign import javascript unsafe "$1.toISOString()" date_toISOString :: JSVal -> IO JSString
-- Point
foreign import javascript unsafe "$1.x" cc_getX :: JSVal -> IO Double
foreign import javascript unsafe "$1.y" cc_getY :: JSVal -> IO Double
foreign import javascript unsafe "cc.p($1, $2)" cc_p :: Double -> Double -> IO JSVal
-- Color
foreign import javascript unsafe "$1.r" cc_getR :: JSVal -> IO Word8
foreign import javascript unsafe "$1.g" cc_getG :: JSVal -> IO Word8
foreign import javascript unsafe "$1.b" cc_getB :: JSVal -> IO Word8
foreign import javascript unsafe "$1.a" cc_getA :: JSVal -> IO Word8
foreign import javascript unsafe "cc.color($1, $2, $3, $4)" cc_color :: Word8 -> Word8 -> Word8 -> Word8 -> IO JSVal
----- Types
-- P2 Double <-> cc.Point
instance FromJSVal (P2 Double) where
fromJSVal v = Just <$> ((^&) <$> cc_getX v <*> cc_getY v)
instance FromJSVal (V2 Double) where
fromJSVal v = Just <$> ((^&) <$> cc_getX v <*> cc_getY v)
instance ToJSVal (P2 Double) where
toJSVal p = cc_p x y
where (x, y) = unp2 p
instance ToJSVal (V2 Double) where
toJSVal p = cc_p x y
where (x, y) = unr2 p
-- NominalDiffTime <> float (in seconds)
instance FromJSVal NominalDiffTime where
fromJSVal = return . Just . (realToFrac :: Double -> NominalDiffTime) . pFromJSVal
instance ToJSVal NominalDiffTime where
toJSVal = toJSVal . (realToFrac :: NominalDiffTime -> Double)
-- UTCTime <-> Date
instance FromJSVal UTCTime where
fromJSVal v = do
jsstr <- date_toISOString v
case A.fromJSON . A.String .T.pack . JS.unpack $ jsstr of
A.Success t -> return $ Just t
_ -> return Nothing
instance ToJSVal UTCTime where
toJSVal t = toJSVal . JS.pack $ formatTime defaultTimeLocale format t
where format = "%FT%T." ++ formatMillis t ++ "Z"
-- Colour Double/AlphaColour Double <> cc.Color
instance FromJSVal (Colour Double) where
fromJSVal v = Just <$> (sRGB24 <$> cc_getR v <*> cc_getG v <*> cc_getB v)
instance ToJSVal (Colour Double) where
toJSVal c = cc_color r g b 255
where RGB r g b = toSRGB24 c
instance FromJSVal (AlphaColour Double) where
fromJSVal v = do
a <- cc_getA v
Just c <- fromJSVal v
return . Just $ withOpacity c (fromIntegral a / 255)
instance ToJSVal (AlphaColour Double) where
toJSVal c = cc_color r g b (round $ a * 255)
where a = alphaChannel c
pureC | a > 0 = darken (recip a) (c `C.over` black)
| otherwise = black
RGB r g b = toSRGB24 pureC
| lynnard/ghcjs-cocos2d | JavaScript/Cocos2d/Types.hs | mit | 3,085 | 24 | 13 | 683 | 998 | 511 | 487 | 63 | 1 |
-- | This module provides a function for converting a full URL into an IP address.
module YesWeScan.IpAddress (ipAddress) where
import YesWeScan.DomainName (domainName)
import Data.IP (IP(IPv4))
import System.Process (readProcess)
-- | Return the `IP` address associated with a URL.
ipAddress :: String -> IO IP
ipAddress url =
IPv4 . read . ipFirstLine
<$> readProcess "host" [domainName url] []
where ipFirstLine = last . words . head . lines
| kmein/yes-we-scan | YesWeScan/IpAddress.hs | mit | 459 | 0 | 9 | 83 | 113 | 63 | 50 | 9 | 1 |
prepend :: [a]->a->[a]
prepend xs a = a:xs
revList xs = foldl prepend [] xs
main=print(revList [2,3,4,2,1,8])
| manuchandel/Academics | Principles-Of-Programming-Languages/revListFoldl.hs | mit | 112 | 2 | 8 | 19 | 85 | 46 | 39 | 4 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar
import Control.Exception (catch)
import Control.Monad
import Data.Unique
import System.IO
import Control.Lens
import qualified Data.ByteString.Char8 as B
import Data.IntMap (IntMap)
import qualified Data.IntMap as M
import Data.Serialize (decode)
import Network
import qualified Network.HTTP.Conduit as C
import qualified Network.HTTP.Types as C
import Network.Lastfm
import Network.Lastfm.Internal
type Job = R JSON Send Ready
type Pool = MVar (IntMap Job)
main :: IO ()
main = do
sock <- listenOn lohPort
rpoo <- newMVar M.empty
forkIO $ forever $ forkIO (runJobs rpoo) >> threadDelay 60000000
forever $ do
(h, _, _) <- accept sock
forkIO $ getJob h rpoo
where
lohPort = PortNumber 9114
runJobs :: Pool -> IO ()
runJobs rpoo = report rpoo >> modifyMVar_ rpoo batch
where
batch jobs = M.differenceWith (\j b -> if b then Nothing else Just j) jobs <$> traverse runJob jobs
report :: Pool -> IO ()
report rpoo = withMVar rpoo $ \pool ->
putStrLn $ "there are " ++ show (M.size pool) ++ " jobs currently pending."
runJob :: Job -> IO Bool
runJob j =
catch (lastfm' j >> return True) (return . badJob)
where
badJob :: C.HttpException -> Bool
badJob (C.StatusCodeException s _ _) = C.statusIsClientError s
badJob (C.ResponseTimeout) = False
badJob _ = True
getJob :: Handle -> Pool -> IO ()
getJob h rpoo = do
msgSize <- decode <$> B.hGet h 8
case msgSize of
Left _ -> return ()
Right size -> do
eej <- decode <$> B.hGet h size
case eej of
Left _ -> return ()
Right j -> unless (broken j) $ do
unique <- hashUnique <$> newUnique
modifyMVar_ rpoo (return . M.insert unique j)
B.hPut h (B.pack $ show unique)
hClose h
broken :: R JSON Send Ready -> Bool
broken r = view (query . ix "method") r `notElem`
[ "track.scrobble"
, "track.updateNowPlaying"
, "track.love"
]
| dmalikov/loh | src/Loh/Server.hs | mit | 2,111 | 0 | 22 | 511 | 758 | 388 | 370 | 62 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Text.LambdaPass.Argument.Parser where
import Text.LambdaPass.Types
import Text.LambdaPass.Config
import Control.Monad (join)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Options.Applicative
import System.Directory
import System.FilePath
import System.IO
data AccountFields = UserField
| PassField
| LocField
| NotesField
deriving (Show, Eq, Ord)
data Command
= Add Username (Maybe Location) (Maybe Notes)
| View (Maybe Username) (Maybe Location) (Maybe Notes) [AccountFields]
| ViewAll [AccountFields]
| Update { selUser :: Maybe Username
, selLoc :: Maybe Location
, selNotes :: Maybe Notes
, upUser :: Maybe Username
, upPass :: Maybe (IO Password)
, upLoc :: Maybe Location
, upNotes :: Maybe Notes
}
| Remove (Maybe Username) (Maybe Location) (Maybe Notes)
| Migrate -- Remove by 1.0
data Options = Options FilePath Fingerprint KeyLocation Command
-- General Options
parseOptions :: IO (Parser Options)
parseOptions = do
baseConfPath <- getXdgDirectory XdgConfig "lambdaPass"
createDirectoryIfMissing True baseConfPath
let configPath = baseConfPath </> "lambdaPass.yml"
configExists <- doesFileExist configPath
if configExists then return () else do
newFile <- openFile configPath AppendMode
hPutStrLn newFile "base:"
hClose newFile
config <- loadConfig configPath
return $ Options <$> parseFile (join . fmap (passFile . base) $ config)
<*> parseFingerprint (join . fmap (gpgKey . base) $ config)
<*> parseKey (join . fmap (gpgDir . base) $ config)
<*> parseCommand
parseFile
:: Maybe FilePath
-> Parser FilePath
parseFile fn =
strOption $ short 'f' <> long "file" <> metavar "FILE" <> case fn of
Just x -> value x <> h
_ -> h
where h = help "Encrypted file that contains passwords."
parseFingerprint
:: Maybe Fingerprint
-> Parser Fingerprint
parseFingerprint fpr =
strOption $ short 'p' <> long "fpr" <> metavar "FINGERPRINT" <> case fpr of
Just x -> value x <> h
_ -> h
where h = help "The fingerprint for the key you will use to encrypt the passwords file."
parseKey
:: Maybe KeyLocation
-> Parser KeyLocation
parseKey keyDir =
strOption $ short 'k' <> long "key" <> metavar "GPGKEY" <> case keyDir of
Just x -> value x <> h
_ -> h
where h = help "This is the path to where your GPG key is."
-- Option primitives
parseUsername :: Parser Username
parseUsername = fieldWrapperParser (Username) $ short 'u' <> long "username" <> metavar "USERNAME"
parseLocation :: Parser Location
parseLocation = fieldWrapperParser (Location) $ short 'l' <> long "location" <> metavar "LOCATION"
parseNotes :: Parser Notes
parseNotes = fieldWrapperParser (Notes) $ short 'n' <> long "notes" <> metavar "NOTES"
parseUpdateUsername :: Parser Username
parseUpdateUsername = fieldWrapperParser (Username) $ long "uU" <> long "updateUser" <> metavar "NEWUSER" <> help "Update the username with the new username as the argument."
parseUpdateLocation :: Parser Location
parseUpdateLocation = fieldWrapperParser (Location) $ long "uL" <> long "updateLoc" <> metavar "NEWLOC"
<> help "Update the location with the new location as the argument."
parseUpdateNotes :: Parser Notes
parseUpdateNotes = fieldWrapperParser (Notes) $ long "uN" <> long "updateNotes" <> metavar "NEWNOTES" <> help "Update notes with new notes as the argument."
fieldWrapperParser :: (T.Text -> a) -> Mod OptionFields String -> Parser a
fieldWrapperParser c ms = c . T.pack <$> (strOption ms)
-- Commands
parseCommand :: Parser Command
parseCommand = subparser $
command "add" (parseAdd `withInfo` "Add a username, location and password to your datastore.") <>
command "view" (parseView `withInfo` "View account info.") <>
command "update" (parseUpdate `withInfo` "Update account info.") <>
command "remove" (parseRemove `withInfo` "Remove a username and password from the datastor.") <>
command "migrate" (parseMigrate `withInfo` "Migrate old account data from initial release to new data structure. Only use this for data created before 2016-10-18.")
-- remove migrate by 1.0
parseAdd :: Parser Command
parseAdd = Add
<$> parseUsername
<*> optional parseLocation
<*> optional parseNotes
parseView :: Parser Command
parseView =
(View
<$> optional parseUsername
<*> optional parseLocation
<*> optional parseNotes
<*> parseFields "p")
<|>
(subparser $ command "all" (parserViewAll `withInfo` "View all accounts."))
parserViewAll :: Parser Command
parserViewAll =
ViewAll
<$> parseFields "ul"
-- parseFields takes a string that contains the default fields you wish to display.
-- It then returns the fields the user requested or that you set as default.
parseFields
:: String
-> Parser [AccountFields]
parseFields def =
foldr f [] <$> strOption (short 'f' <> long "fields" <> value def <> metavar "FIELDS"
<> help ("These are the account fields you wish displayed. Use 'u' for user, 'l' for location "
++ "'n' for notes and 'p' for password. Default behavior will be to just show password."))
where f x acc = case x of
'u' -> UserField : acc
'p' -> PassField : acc
'l' -> LocField : acc
'n' -> NotesField : acc
_ -> acc
parseUpdate :: Parser Command
parseUpdate =
Update
<$> optional parseUsername
<*> optional parseLocation
<*> optional parseNotes
<*> optional parseUpdateUsername
<*> optional ((\x -> case x of
True -> passPrompt
False -> return $ Password T.empty) <$> switch (long "uP" <> long "updatePass"
<> help "Update the password with a new password that will be prompted for."))
<*> optional parseUpdateLocation
<*> optional parseUpdateNotes
-- remove before 1.0
parseMigrate :: Parser Command
parseMigrate = pure Migrate
passPrompt :: IO Password
passPrompt = do
TIO.putStr "What password do you wish to store? "
hFlush stdout
hSetEcho stdin False
p <- TIO.getLine
hSetEcho stdin True
return . Password $ p
parseRemove :: Parser Command
parseRemove = Remove
<$> optional parseUsername
<*> optional parseLocation
<*> optional parseNotes
-- Helper Functions
withInfo
:: Parser a
-> String
-> ParserInfo a
withInfo opts desc = info (helper <*> opts) $ progDesc desc
| flounders/lambdaPass | src/Text/LambdaPass/Argument/Parser.hs | gpl-2.0 | 7,062 | 0 | 18 | 1,978 | 1,717 | 855 | 862 | 155 | 5 |
import Probability
import Data.Frame
import qualified Data.Map as M
-- When we get polymorphism, maybe we can create an temporary array as a view on xs'
-- I presume that using n directly is more efficient that using [length xs']
orderedSample n dist = do
xs' <- iid n dist
let xs = sort xs'
return $ listArray n xs
get_intervals (r:[]) (t:[]) tend = [(r,t,tend)]
get_intervals (r:rs) (t1:ts@(t2:_)) tend = (r,t1,t2):get_intervals rs ts tend
model (t1,t2) times = do
let lam = 3.0; nMax = 30; a = 1.0; b = 365.0/200.0
-- n change points, n+1 intervals
n <- min nMax <$> poisson lam
-- even numbered order statistics over the interval [t1,t2]
s' <- orderedSample (2*n+1) (uniform t1 t2)
let s = t1:[s'!(2*i-1) | i <- [1..n]]
-- n+1 rates
g <- iid (n+1) (gamma a b)
let intervals = get_intervals g s t2
times ~> poisson_processes intervals
return [ "n" %=% n, "s" %=% s, "g" %=% g, "intervals" %=% intervals]
main = do
frame <- readTable "coal-times.csv"
let times = frame $$ ("time", AsDouble)
mcmc $ model (1851.0,1963.0) times
| bredelings/BAli-Phy | tests/prob_prog/coal_mining/Coal.hs | gpl-2.0 | 1,076 | 0 | 15 | 232 | 444 | 231 | 213 | 22 | 1 |
{-
Copyright (C) 2005 John Goerzen <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
module Main where
import Config
import Types
import Control.Monad(when, unless)
import Control.Exception(finally, bracket)
import System.Directory
import DB
import Database.HDBC
import Utils
import MissingH.Path.FilePath
import MissingH.Network
import NetClient
import DirParser
import Control.Concurrent
import Data.List
import Control.Exception(bracket_)
import RobotsTxt
import Control.Concurrent
import System.IO
import qualified Data.Map as Map
{- | Main entry point for the program. -}
main = niceSocketsDo $ -- Prepare things for sockets
do setCurrentDirectory baseDir -- chdir to the working dir
l <- newLock -- Global lock for db updates
initdb -- Initialize the database and get a conn
gasupply <- newMVar Map.empty -- Global MVar for current status
runScan gasupply l -- main scanner
{- | Set up all the threads and get them going. -}
runScan gasupply l =
do c <- dbconnect
n <- numToProc c
msg $ (show n) ++ " items to process"
when (n == 0) -- Nothing to do: prime the db
(mapM_ (\g -> updateItem l c g NotVisited "") startingAddresses)
{- Fork off the childthreads. Each one goes into a loop
of waiting for new items to process and processing them. -}
disconnect c
children <- mapM
(\_ -> myForkOS (procLoop l gasupply)) [1..numThreads]
-- This is the thread that displays status updates every so often
--stats <- forkOS (statsthread l)
-- When the main thread exits, so does the program, so
-- we wait for all children before exiting.
waitForChildren children
{- | A simple wrapper around forkOS to notify the main thread when each
individual thread dies. -}
myForkOS :: IO () -> IO (MVar ThreadId)
myForkOS io =
do mvar <- newEmptyMVar
forkIO (action `finally` (myThreadId >>= putMVar mvar))
return mvar
where action = do msg "started."
io
{- | Wait for child threads to die.
This should only happen when there is nothing else to spider. -}
waitForChildren :: [MVar ThreadId] -> IO ()
waitForChildren [] = msg $ "All children died; exiting."
waitForChildren (c:xs) =
do t <- takeMVar c
msg $ " *********** Thread died: " ++ (show t)
waitForChildren xs
{- | Main entry point for each worker thread. We just pop the first item,
then call procLoop'. -}
procLoop lock gasupply =
do bracket dbconnect disconnect (\c -> do
i <- popItem lock gasupply c
procLoop' lock gasupply c i
)
{- | Main worker loop. We receive an item and process it. If it's
Nothing, there is nothing else to do, so the thread shuts down.
Otherwise, call procItem, pop the next, and then call itself. -}
procLoop' lock gasupply c i =
do case i of
Nothing -> msg $ "Exiting"
Just item -> do procItem lock gasupply c item
-- Popping the next item before releasing the current
-- host is a simple form of being nice to remotes
i <- popItem lock gasupply c
procLoop' lock gasupply c i
{- | What happened when we checked the robots.txt file? -}
data RobotStatus = RobotsOK -- ^ Proceed
| RobotsDeny -- ^ Do not download this file
| RobotsError -- ^ Error occured; abort.
{- | Given a 'GAddress' (corresponding to a single item),
check to see if it's OK to download according to robots.txt.
-}
checkRobots :: Lock -> GASupply -> Connection -> GAddress -> IO RobotStatus
checkRobots lock gasupply c ga =
do let fspath = getFSPath garobots
dfe <- doesFileExist fspath
unless (dfe) (procItem lock gasupply c garobots) -- Download file if needed
dfe2 <- doesFileExist fspath -- Do we have it yet?
if dfe2
then -- Yes. Parse it, and see what happened.
do r <- parseRobots fspath
return $ case isURLAllowed r "gopherbot" (path ga) of
True -> RobotsOK
False -> RobotsDeny
else return RobotsError -- No. TCP error occured.
where garobots = ga {path = "robots.txt", dtype = '0'}
{- | Run an IO action, but only if it's OK according to robots.txt. -}
procIfRobotsOK :: Lock -> GASupply -> Connection -> GAddress -> IO () -> IO ()
procIfRobotsOK lock gasupply c item action =
do r <- if (path item /= "robots.txt")
then checkRobots lock gasupply c item
else -- Don't try to check if robots.txt itself is ok
return RobotsOK
case r of
RobotsOK -> action -- OK per robots.txt; run it.
RobotsDeny -> do msg $ "Excluded by robots.txt: " ++
(show item)
updateItem lock c item Excluded ""
RobotsError -> do msg $ "Problem getting robots.txt: " ++
host item
-- Next line not necessary; procItem
-- on robots.txt will have done it
-- already.
--noteErrorOnHost lock c (host item) (show msg)
-- TODO: better crash handling on robots.txt
{- | OK, we have an item. If it's OK according to robots.txt, download
and process it. -}
procItem lock gasupply c item = procIfRobotsOK lock gasupply c item $
do msg $ show item -- Show what we're up to
let fspath = getFSPath item
-- Create the directory for the file to go in, if necessary.
catch (bracket_ (acquire lock)
(release lock)
(createDirectoryIfMissing True
(fst . splitFileName $ fspath)))
(\e -> -- If we got an exception here, note an error for this item
do msg $ "Single-Item Error on " ++ (show item) ++ ": "
++ (show e)
updateItem lock c item ErrorState (show e)
)
fh <- catch ((openFile fspath WriteMode >>= (return . Just)))
(\e -> do msg $ "Single-item error on " ++ (show item) ++ ": " ++
(show e)
updateItem lock c item ErrorState (show e)
return Nothing
)
case fh of
Nothing -> return ()
Just h -> -- Now, download it. If it's a menu
--(item type 1), check it for links
-- (spider it). Error here means a TCP
-- problem, so mark every
-- item on this host as having the error.
catch (do dlItem item h
when (dtype item == '1') (spider lock c fspath)
updateItem lock c item Visited ""
)
(\e -> do msg $ "Error on " ++ (show item)
++ ": " ++ (show e)
noteErrorOnHost lock gasupply c
(host item) (show e)
)
{- | This function is called by procItem whenever it downloads a
menu. This function calles the parser, extracts items, and calles
DB.queueItems to handle them. (Insert into DB if new) -}
spider l c fspath =
do netreferences <- parseGMap fspath
let refs = filter filt netreferences
queueItems l c refs
where filt a = (not ((dtype a) `elem` ['i', '3', '8', '7', '2'])) &&
not (host a `elem` excludeServers)
{- | This thread prints a periodic status update. -}
statsthread :: Lock -> IO ()
statsthread l =
do c <- dbconnect
statsthread' l c
disconnect c
statsthread' l c =
do res <- quickQuery c "SELECT state, COUNT(*) from files group by state order by state" []
let counts = map (\[thiss, thisc] -> (fromSql thiss,
(fromSql thisc)::Integer)) res
let total = sum (map snd counts)
let totaltext = "Total " ++ show total
let statetxts = map (\(h, c) -> h ++ " " ++ show c) counts
let disp = concat . intersperse ", " $ totaltext : statetxts
msg disp
threadDelay (120 * 1000000)
statsthread' l c
| jgoerzen/gopherbot | gopherbot.hs | gpl-2.0 | 9,396 | 0 | 20 | 3,358 | 1,740 | 871 | 869 | 135 | 4 |
-- Copyright (c) 2015, Sven Thiele <[email protected]>
--
-- -- This file is part of hasple.
--
-- -- hasple is free software: you can redistribute it and/or modify
-- -- it under the terms of the GNU General Public License as published by
-- -- the Free Software Foundation, either version 3 of the License, or
-- -- (at your option) any later version.
--
-- -- hasple is distributed in the hope that it will be useful,
-- -- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- -- GNU General Public License for more details.
--
-- -- You should have received a copy of the GNU General Public License
-- -- along with hasple. If not, see <http://www.gnu.org/licenses/>.
module SPVar (
SPVar(..),
-- __bottom,
bodies2vars,
atomsfromvar,
bodies,
external_bodies,
get_vars,
CClause,
nogoods_of_lp,
loop_nogoods,
SVar,
SignedVar(..),
unsign,
invert,
SymbolTable,
get_lit
) where
import ASP
import Data.List (nub, delete, intersect, (++), map)
import Data.Vector as BVec
data SPVar = ALit Atom -- Solver-Variable
| BLit [Literal]
deriving (Show,Eq,Ord)
__bottom :: SPVar
-- returns the of Solver-variable representing a conflict
__bottom = ALit __conflict
atoms2vars :: [Atom] -> [SPVar]
-- returns a list of Solver-variables
atoms2vars as = [ ALit a | a <- as ]
bodies2vars :: [[Literal]] -> [SPVar]
-- returns a list of Solver-variables
bodies2vars bs = [ BLit b | b <- bs ]
atomsfromvar :: SPVar -> [Atom]
--
atomsfromvar (ALit a) = [a]
atomsfromvar (BLit b) = [ a | PAtom a <- b]
bodies_p :: [Rule] -> [[Literal]]
-- returns all bodies of a program
bodies_p p = [ body r | r <-p ]
bodies :: [Rule] -> Atom -> [[Literal]]
-- returns all bodies of rules with the atom as head
bodies p a = [ body r | r<-p , (kopf r)==a ]
-- ---------------------------------------------------------------------------------
type CClause = ([SPVar],[SPVar])
get_vars :: [CClause] -> [SPVar]
get_vars cs = nub (Prelude.concatMap get_varsc cs)
get_varsc :: CClause -> [SPVar]
get_varsc (t,f) = nub (t Prelude.++ f)
nogoods_of_lp :: [Rule] -> [CClause]
nogoods_of_lp p =
let a = (atoms_p p)Prelude.++[__conflict]
b = bodies_p p
ng1 = Prelude.map get_ng1 b -- body is true if all lits of it are true -- not ( body=false and all lits=true)
ng2 = Prelude.concatMap get_ng2 b -- body is true if all lits of it are true -- not ( body=true and one lit=false)
ng3 = Prelude.concatMap (get_ng3 p) a -- a head is true if one body is true -- not ( head=false and one body=true)
ng4 = Prelude.map (get_ng4 p) a -- a head is true if one body is true -- not ( head=true and all bodies=false)
ngx = [([__bottom],[])] -- no conflict literal
in
ng1 Prelude.++ ng2 Prelude.++ ng3 Prelude.++ ng4 Prelude.++ ngx
get_ng1 :: [Literal] -> CClause
get_ng1 b =
let pb = [ a | PAtom a <- b ]
nb = [ a | NAtom a <- b ]
in
((atoms2vars pb), ((BLit b):(atoms2vars nb)))
get_ng2 :: [Literal] -> [CClause]
get_ng2 b =
let
pb = [ a | PAtom a <- b ]
nb = [ a | NAtom a <- b ]
clauses1 = [ ([BLit b], [ALit atom]) | atom <- pb ]
clauses2 = [ ([BLit b, ALit atom],[]) | atom <- nb ]
in
clauses1 Prelude.++ clauses2
get_ng3 :: [Rule] -> Atom -> [CClause]
get_ng3 p a = [ ([BLit b], [ALit a]) | b <- (bodies p a) ]
get_ng4 :: [Rule] -> Atom -> CClause
get_ng4 p a = ([ALit a], bodies2vars (bodies p a))
external_bodies :: [Rule] -> [Atom] -> [[Literal]]
-- returns the external bodies
external_bodies p u =
[ body r | r <- p, Prelude.elem (kopf r) u, Prelude.null (intersect (pbody r) u) ]
loop_nogood :: Atom -> [[Literal]] -> CClause
-- returns the loop nogood for an atom in an unfounded set(characterized by the external bodies)
loop_nogood a bodies = ([ALit a], bodies2vars bodies)
loop_nogoods :: [Rule] -> [Atom] -> [CClause]
-- return the loop nogoods of the program for a given unfounded set
loop_nogoods p u = [ loop_nogood atom (external_bodies p u) | atom<-u ]
type SVar = Int
data SignedVar = T SVar
| F SVar
deriving (Show,Eq,Ord)
unsign :: SignedVar -> SVar
unsign (T l) = l
unsign (F l) = l
invert :: SignedVar -> SignedVar
invert (T l) = F l
invert (F l) = T l
type SymbolTable = BVec.Vector SPVar
get_lit :: SymbolTable -> SVar -> SPVar
get_lit st i = st BVec.! i
| sthiele/hasple | SPVar.hs | gpl-3.0 | 4,526 | 0 | 12 | 1,087 | 1,354 | 753 | 601 | 87 | 1 |
-- Copyright 2017 John F. Miller
{-# LANGUAGE OverloadedStrings #-}
-- | Functions for working with "Parameters".
module Eval.Parameters
( match, arity, checkArity
, module Parameters
)
where
import Control.Monad.Except
import Data.String
import Data.List
import Parameters
import Object hiding (arity)
import Name
import Scope
import Array
-- | Given some 'Parameter' set and the arguments, match attempts to assign
-- local variables to these arguments base on the parameters described.
-- The result an action yielding an Int which is the zero-index of the
-- alternative which succeeded. If there are no alternatives it returns 0.
-- If the match fails a PatternMatchError is thrown.
match :: Scope m => Parameter -> [Object] -> m (Int)
match = match' 0
where
match' :: Scope m => Int -> Parameter -> [Object] -> m (Int)
match' i Empty [] = return i
match' _ Empty xs = throwError "PatternMatchError: Too many parameters"
match' _ (P _ _) [] = throwError "PatternMatchError: Too few parameters"
match' i (P n next) (x:xs) = setLocal n x >> match' i next xs
match' i (Asterisk n) xs = setLocal n (varray xs) >> return i
match' i (Default n _ next) (x:xs) = setLocal n x >> match' i next xs
match' i (Default n x next) [] = setLocal n x >> match' i next []
match' _ (Pattern _ _ _) [] = throwError "PatternMatchError: Too few parameters"
match' i (Pattern cls n next) (x:xs) = do
r <- call (Just $ RO x) "kind_of" [fromString cls]
case (o r) of
TrueClass -> setLocal n x >> match' i next xs
otherwise -> throwError "PatternMatchError: Pattern failed" -- todo add information n is not a cls
match' i (Alternatives xs) ps = alternatives i [] xs ps
alternitives :: Scope m => Int -> [Object] -> [Parameter] -> [Object] -> m ()
alternitives _ errs [] _ = throwError $ varray ("PatternMatchError: No matching pattern":errs)
alternatives i [] [p] ps = match' i p ps
alternatives i errs (x:xs) ps = match' i x ps `catchError` (\err -> alternatives (i+1) (err:errs) xs ps)
-- | determines the posible arity of a parameter set
arity :: Parameter -> Arity
arity ps = arity' (0,Just 0) ps
where
arity' x Empty = x
arity' (a,_) (Asterisk _) = (a, Nothing)
arity' (a, Just b) (Default _ _ x) = arity' (a,Just (b+1)) x
arity' (a, Just b) (P _ x) = arity' (a+1, Just (b+1)) x
arity' (a, Just b) (Pattern _ _ x) = arity' (a+1, Just (b+1)) x
arity' x (Alternatives []) = x
arity' _ (Alternatives ps) = (a', b')
where
ps' = map (arity' (0,Just 0)) ps
a' = minimum $ map fst ps'
b' = foldl max' (Just 0) (map snd ps')
max' Nothing _ = Nothing -- Nothing represents no limit (i.e. infinity) so it is the maximal value
max' _ Nothing = Nothing
max' (Just a) (Just b) = Just (max a b)
arity' a (Guard _ x) = arity' a x
-- | Will n parameters match the given Arity
checkArity :: Arity -> Int -> Bool
checkArity (min, Just max) x | (min <= x) && (x <= max) = True
checkArity (min, Nothing) x | (min <= x) = True
checkArity _ _ = False
setLocal ::Scope m => Name -> Object -> m ()
setLocal n x = setVar Local n x
| antarestrader/sapphire | Eval/Parameters.hs | gpl-3.0 | 3,200 | 0 | 13 | 779 | 1,234 | 635 | 599 | 55 | 12 |
{-# LANGUAGE GADTs, BangPatterns #-}
-- (C) Copyright Collin J. Doering 2014
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
-- File: NFA.hs
-- Author: Collin J. Doering <[email protected]>
-- Date: May 26, 2014
-- | TODO: Comment
module NFA
( NFA (NFA)
, NFAState (NFAState,NFAEndState)
, NFAStartState (NFAStartState)
, nextNFAStates
, computeNFA
, convertNFAToDFA
) where
import DFA
-- | TODO: Comment
newtype NFA a = NFA { runNFA :: NFAStartState a }
-- | TODO: Comment
newtype NFAStartState a = NFAStartState { runNFAStartState :: NFAState a }
-- | TODO: Comment
-- data NFAState a = NFAState { runNFAState :: a -> [NFAState a] }
-- | NFAEndState { runNFAState :: a -> [NFAState a] }
-- | TODO: Comment
data NFAState a where
NFAState :: (Enum a, Bounded a) => { runNFAState :: a -> [NFAState a] } -> NFAState a
NFAEndState :: (Enum a, Bounded a) => { runNFAState :: a -> [NFAState a] } -> NFAState a
-- data NFAEState a = NFAEState
-- | TODO: Comment
nextNFAStates :: a -> [NFAState a] -> [NFAState a]
nextNFAStates x = concatMap (($ x) . runNFAState)
-- | TODO: Comment
computeNFA :: [a] -> NFA a -> Bool
computeNFA ys y = computeNFA' ys [runNFAStartState . runNFA $ y]
where computeNFA' [] cs = flip any cs $ \s -> case s of
(NFAState _) -> False
(NFAEndState _) -> True
computeNFA' (x:xs) !cs = computeNFA' xs $ nextNFAStates x cs
-- | TODO: Comment
convertNFAToDFA :: (Enum a, Bounded a) => NFA a -> DFA a
convertNFAToDFA n = convertNFAToDFA' $ runNFAStartState . runNFA $ n
where convertNFAToDFA' = undefined
| rekahsoft/HS-FSM | src/NFA.hs | gpl-3.0 | 2,246 | 0 | 13 | 496 | 428 | 249 | 179 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Ch_GeomCut_Opts where
import System.Console.CmdArgs
import Algebra
data Ch_GeomCut_Opts = Ch_GeomCut_Opts
{ input :: FilePath
, output :: FilePath
, shape :: String
, geomparam :: Float
, centre :: String
, verbose :: Bool
}
deriving (Show,Data,Typeable)
ch_GeomCut_Opts = Ch_GeomCut_Opts
{ input = def &= help "trajectory in XYZ format" &= typ "INPUT"
, output = "stdout" &= help "output file" &= typ "OUTPUT"
, shape = "s" &= help "shape of remaining cut body"
, geomparam = def &= help "radius or similiar parameter"
, centre = def &= help "coordinates of the centre"
, verbose = False &= help "print additional output"
}
mode = cmdArgsMode ch_GeomCut_Opts
| sheepforce/Haskell-Tools | ch_geomcut/Ch_GeomCut_Opts.hs | gpl-3.0 | 736 | 0 | 9 | 147 | 181 | 103 | 78 | 20 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Content.Products.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists the products in your Merchant Center account. This method can only
-- be called for non-multi-client accounts.
--
-- /See:/ <https://developers.google.com/shopping-content Content API for Shopping Reference> for @content.products.list@.
module Network.Google.Resource.Content.Products.List
(
-- * REST Resource
ProductsListResource
-- * Creating a Request
, productsList
, ProductsList
-- * Request Lenses
, proMerchantId
, proIncludeInvalidInsertedItems
, proPageToken
, proMaxResults
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.products.list@ method which the
-- 'ProductsList' request conforms to.
type ProductsListResource =
"content" :>
"v2" :>
Capture "merchantId" (Textual Word64) :>
"products" :>
QueryParam "includeInvalidInsertedItems" Bool :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] ProductsListResponse
-- | Lists the products in your Merchant Center account. This method can only
-- be called for non-multi-client accounts.
--
-- /See:/ 'productsList' smart constructor.
data ProductsList = ProductsList'
{ _proMerchantId :: !(Textual Word64)
, _proIncludeInvalidInsertedItems :: !(Maybe Bool)
, _proPageToken :: !(Maybe Text)
, _proMaxResults :: !(Maybe (Textual Word32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ProductsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'proMerchantId'
--
-- * 'proIncludeInvalidInsertedItems'
--
-- * 'proPageToken'
--
-- * 'proMaxResults'
productsList
:: Word64 -- ^ 'proMerchantId'
-> ProductsList
productsList pProMerchantId_ =
ProductsList'
{ _proMerchantId = _Coerce # pProMerchantId_
, _proIncludeInvalidInsertedItems = Nothing
, _proPageToken = Nothing
, _proMaxResults = Nothing
}
-- | The ID of the managing account.
proMerchantId :: Lens' ProductsList Word64
proMerchantId
= lens _proMerchantId
(\ s a -> s{_proMerchantId = a})
. _Coerce
-- | Flag to include the invalid inserted items in the result of the list
-- request. By default the invalid items are not shown (the default value
-- is false).
proIncludeInvalidInsertedItems :: Lens' ProductsList (Maybe Bool)
proIncludeInvalidInsertedItems
= lens _proIncludeInvalidInsertedItems
(\ s a -> s{_proIncludeInvalidInsertedItems = a})
-- | The token returned by the previous request.
proPageToken :: Lens' ProductsList (Maybe Text)
proPageToken
= lens _proPageToken (\ s a -> s{_proPageToken = a})
-- | The maximum number of products to return in the response, used for
-- paging.
proMaxResults :: Lens' ProductsList (Maybe Word32)
proMaxResults
= lens _proMaxResults
(\ s a -> s{_proMaxResults = a})
. mapping _Coerce
instance GoogleRequest ProductsList where
type Rs ProductsList = ProductsListResponse
type Scopes ProductsList =
'["https://www.googleapis.com/auth/content"]
requestClient ProductsList'{..}
= go _proMerchantId _proIncludeInvalidInsertedItems
_proPageToken
_proMaxResults
(Just AltJSON)
shoppingContentService
where go
= buildClient (Proxy :: Proxy ProductsListResource)
mempty
| rueshyna/gogol | gogol-shopping-content/gen/Network/Google/Resource/Content/Products/List.hs | mpl-2.0 | 4,439 | 0 | 15 | 1,049 | 586 | 343 | 243 | 86 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Gmail.Users.Settings.SendAs.Create
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a custom \"from\" send-as alias. If an SMTP MSA is specified,
-- Gmail will attempt to connect to the SMTP service to validate the
-- configuration before creating the alias. If ownership verification is
-- required for the alias, a message will be sent to the email address and
-- the resource\'s verification status will be set to \`pending\`;
-- otherwise, the resource will be created with verification status set to
-- \`accepted\`. If a signature is provided, Gmail will sanitize the HTML
-- before saving it with the alias. This method is only available to
-- service account clients that have been delegated domain-wide authority.
--
-- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.settings.sendAs.create@.
module Network.Google.Resource.Gmail.Users.Settings.SendAs.Create
(
-- * REST Resource
UsersSettingsSendAsCreateResource
-- * Creating a Request
, usersSettingsSendAsCreate
, UsersSettingsSendAsCreate
-- * Request Lenses
, ussacXgafv
, ussacUploadProtocol
, ussacAccessToken
, ussacUploadType
, ussacPayload
, ussacUserId
, ussacCallback
) where
import Network.Google.Gmail.Types
import Network.Google.Prelude
-- | A resource alias for @gmail.users.settings.sendAs.create@ method which the
-- 'UsersSettingsSendAsCreate' request conforms to.
type UsersSettingsSendAsCreateResource =
"gmail" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"settings" :>
"sendAs" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] SendAs :> Post '[JSON] SendAs
-- | Creates a custom \"from\" send-as alias. If an SMTP MSA is specified,
-- Gmail will attempt to connect to the SMTP service to validate the
-- configuration before creating the alias. If ownership verification is
-- required for the alias, a message will be sent to the email address and
-- the resource\'s verification status will be set to \`pending\`;
-- otherwise, the resource will be created with verification status set to
-- \`accepted\`. If a signature is provided, Gmail will sanitize the HTML
-- before saving it with the alias. This method is only available to
-- service account clients that have been delegated domain-wide authority.
--
-- /See:/ 'usersSettingsSendAsCreate' smart constructor.
data UsersSettingsSendAsCreate =
UsersSettingsSendAsCreate'
{ _ussacXgafv :: !(Maybe Xgafv)
, _ussacUploadProtocol :: !(Maybe Text)
, _ussacAccessToken :: !(Maybe Text)
, _ussacUploadType :: !(Maybe Text)
, _ussacPayload :: !SendAs
, _ussacUserId :: !Text
, _ussacCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UsersSettingsSendAsCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ussacXgafv'
--
-- * 'ussacUploadProtocol'
--
-- * 'ussacAccessToken'
--
-- * 'ussacUploadType'
--
-- * 'ussacPayload'
--
-- * 'ussacUserId'
--
-- * 'ussacCallback'
usersSettingsSendAsCreate
:: SendAs -- ^ 'ussacPayload'
-> UsersSettingsSendAsCreate
usersSettingsSendAsCreate pUssacPayload_ =
UsersSettingsSendAsCreate'
{ _ussacXgafv = Nothing
, _ussacUploadProtocol = Nothing
, _ussacAccessToken = Nothing
, _ussacUploadType = Nothing
, _ussacPayload = pUssacPayload_
, _ussacUserId = "me"
, _ussacCallback = Nothing
}
-- | V1 error format.
ussacXgafv :: Lens' UsersSettingsSendAsCreate (Maybe Xgafv)
ussacXgafv
= lens _ussacXgafv (\ s a -> s{_ussacXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ussacUploadProtocol :: Lens' UsersSettingsSendAsCreate (Maybe Text)
ussacUploadProtocol
= lens _ussacUploadProtocol
(\ s a -> s{_ussacUploadProtocol = a})
-- | OAuth access token.
ussacAccessToken :: Lens' UsersSettingsSendAsCreate (Maybe Text)
ussacAccessToken
= lens _ussacAccessToken
(\ s a -> s{_ussacAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ussacUploadType :: Lens' UsersSettingsSendAsCreate (Maybe Text)
ussacUploadType
= lens _ussacUploadType
(\ s a -> s{_ussacUploadType = a})
-- | Multipart request metadata.
ussacPayload :: Lens' UsersSettingsSendAsCreate SendAs
ussacPayload
= lens _ussacPayload (\ s a -> s{_ussacPayload = a})
-- | User\'s email address. The special value \"me\" can be used to indicate
-- the authenticated user.
ussacUserId :: Lens' UsersSettingsSendAsCreate Text
ussacUserId
= lens _ussacUserId (\ s a -> s{_ussacUserId = a})
-- | JSONP
ussacCallback :: Lens' UsersSettingsSendAsCreate (Maybe Text)
ussacCallback
= lens _ussacCallback
(\ s a -> s{_ussacCallback = a})
instance GoogleRequest UsersSettingsSendAsCreate
where
type Rs UsersSettingsSendAsCreate = SendAs
type Scopes UsersSettingsSendAsCreate =
'["https://www.googleapis.com/auth/gmail.settings.sharing"]
requestClient UsersSettingsSendAsCreate'{..}
= go _ussacUserId _ussacXgafv _ussacUploadProtocol
_ussacAccessToken
_ussacUploadType
_ussacCallback
(Just AltJSON)
_ussacPayload
gmailService
where go
= buildClient
(Proxy :: Proxy UsersSettingsSendAsCreateResource)
mempty
| brendanhay/gogol | gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Settings/SendAs/Create.hs | mpl-2.0 | 6,549 | 0 | 20 | 1,456 | 802 | 474 | 328 | 117 | 1 |
-- Hoff -- A gatekeeper for your commits
-- Copyright 2016 Ruud van Asseldonk
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- A copy of the License has been included in the root of the repository.
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DuplicateRecordFields #-}
import Control.Monad.Free (Free (..))
import Data.Aeson (decode, encode)
import Data.ByteString.Lazy (readFile)
import Data.Foldable (foldlM)
import Data.Maybe (fromJust, isJust, isNothing)
import Data.Text (Text)
import Prelude hiding (readFile)
import System.Directory (getTemporaryDirectory, removeFile)
import System.FilePath ((</>))
import Test.Hspec
import qualified Data.IntMap.Strict as IntMap
import qualified Data.UUID.V4 as Uuid
import Configuration (ProjectConfiguration)
import EventLoop (convertGithubEvent)
import Git (Branch (..), PushResult(..), Sha (..))
import Github (CommentPayload, CommitStatusPayload, PullRequestPayload)
import Logic hiding (runAction)
import Project (ProjectState (ProjectState), PullRequest (PullRequest), PullRequestId (PullRequestId))
import qualified Configuration as Config
import qualified Github
import qualified Project
-- Project config used throughout these tests.
testProjectConfig :: ProjectConfiguration
testProjectConfig = Config.ProjectConfiguration {
Config.owner = "deckard",
Config.repository = "voight-kampff",
Config.branch = "master",
Config.testBranch = "testing",
Config.checkout = "/tmp/deckard/voight-kampff",
Config.reviewers = ["deckard"],
Config.stateFile = "/tmp/state/deckard/voight-kampff.json"
}
-- Functions to prepare certain test states.
singlePullRequestState :: PullRequestId -> Branch -> Sha -> Text -> ProjectState
singlePullRequestState pr prBranch prSha prAuthor =
let event = PullRequestOpened pr prBranch prSha "Untitled" prAuthor
in handleEventFlat event Project.emptyProjectState
candidateState :: PullRequestId -> Branch -> Sha -> Text -> Sha -> ProjectState
candidateState pr prBranch prSha prAuthor candidateSha =
let state0 = singlePullRequestState pr prBranch prSha prAuthor
state1 = Project.setIntegrationStatus pr (Project.Integrated candidateSha) state0
in state1 { Project.integrationCandidate = Just pr }
-- Types and functions to mock running an action without actually doing anything.
data ActionFlat
= ATryIntegrate Text (Branch, Sha)
| ATryPromote Branch Sha
| ALeaveComment PullRequestId Text
deriving (Eq, Show)
-- This function simulates running the actions, and returns the final state,
-- together with a list of all actions that would have been performed. Some
-- actions require input from the outside world. Simulating these actions will
-- return the pushResult and rebaseResult passed in here.
runActionWithInit :: Maybe Sha -> PushResult -> [ActionFlat] -> Action a -> (a, [ActionFlat])
runActionWithInit integrateResult pushResult actions action =
let
prepend cont act =
let (result, acts') = runActionWithInit integrateResult pushResult actions cont
in (result, act : acts')
in
case action of
Pure result -> (result, [])
Free (TryIntegrate msg candi h) -> prepend (h integrateResult) $ ATryIntegrate msg candi
Free (TryPromote prBranch headSha h) -> prepend (h pushResult) $ ATryPromote prBranch headSha
Free (LeaveComment pr body x) -> prepend x $ ALeaveComment pr body
-- Simulates running the action. Pretends that integration always conflicts.
-- Pretends that pushing is always successful.
runAction :: Action a -> (a, [ActionFlat])
runAction = runActionWithInit Nothing PushOk []
-- TODO: Do not ignore actions information, assert that certain events do not
-- have undesirable side effects.
getState :: Action ProjectState -> ProjectState
getState = fst . runAction
-- Handle an event and simulate its side effects, then ignore the side effects
-- and return the new state.
handleEventFlat :: Event -> ProjectState -> ProjectState
handleEventFlat event state =
getState $ handleEvent testProjectConfig event state
-- Handle events and simulate their side effects, then ignore the side effects
-- and return the new state.
handleEventsFlat :: [Event] -> ProjectState -> ProjectState
handleEventsFlat events state =
getState $ foldlM (flip $ handleEvent testProjectConfig) state events
-- Proceed with a state until a fixed point, simulate and collect the side
-- effects.
proceedUntilFixedPointFlat :: Maybe Sha -> PushResult -> ProjectState -> (ProjectState, [ActionFlat])
proceedUntilFixedPointFlat integrateResult pushResult state =
runActionWithInit integrateResult pushResult [] $ proceedUntilFixedPoint state
main :: IO ()
main = hspec $ do
describe "Logic.handleEvent" $ do
it "handles PullRequestOpened" $ do
let event = PullRequestOpened (PullRequestId 3) (Branch "p") (Sha "e0f") "title" "lisa"
state = handleEventFlat event Project.emptyProjectState
state `shouldSatisfy` Project.existsPullRequest (PullRequestId 3)
let pr = fromJust $ Project.lookupPullRequest (PullRequestId 3) state
Project.sha pr `shouldBe` Sha "e0f"
Project.author pr `shouldBe` "lisa"
Project.approvedBy pr `shouldBe` Nothing
Project.buildStatus pr `shouldBe` Project.BuildNotStarted
it "handles PullRequestClosed" $ do
let event1 = PullRequestOpened (PullRequestId 1) (Branch "p") (Sha "abc") "title" "peter"
event2 = PullRequestOpened (PullRequestId 2) (Branch "q") (Sha "def") "title" "jack"
event3 = PullRequestClosed (PullRequestId 1)
state = handleEventsFlat [event1, event2, event3] Project.emptyProjectState
state `shouldSatisfy` not . Project.existsPullRequest (PullRequestId 1)
state `shouldSatisfy` Project.existsPullRequest (PullRequestId 2)
it "handles closing the integration candidate PR" $ do
let event = PullRequestClosed (PullRequestId 1)
state = candidateState (PullRequestId 1) (Branch "p") (Sha "ea0") "frank" (Sha "cf4")
state' = handleEventFlat event state
Project.integrationCandidate state' `shouldBe` Nothing
it "does not modify the integration candidate if a different PR was closed" $ do
let event = PullRequestClosed (PullRequestId 1)
state = candidateState (PullRequestId 2) (Branch "p") (Sha "a38") "franz" (Sha "ed0")
state' = handleEventFlat event state
Project.integrationCandidate state' `shouldBe` (Just $ PullRequestId 2)
it "loses approval after the PR commit has changed" $ do
let event = PullRequestCommitChanged (PullRequestId 1) (Sha "def")
state0 = singlePullRequestState (PullRequestId 1) (Branch "p") (Sha "abc") "alice"
state1 = Project.setApproval (PullRequestId 1) (Just "hatter") state0
state2 = handleEventFlat event state1
pr1 = fromJust $ Project.lookupPullRequest (PullRequestId 1) state1
pr2 = fromJust $ Project.lookupPullRequest (PullRequestId 1) state2
Project.approvedBy pr1 `shouldBe` Just "hatter"
Project.approvedBy pr2 `shouldBe` Nothing
it "resets the build status after the PR commit has changed" $ do
let event = PullRequestCommitChanged (PullRequestId 1) (Sha "def")
state0 = singlePullRequestState (PullRequestId 1) (Branch "p") (Sha "abc") "thomas"
state1 = Project.setBuildStatus (PullRequestId 1) Project.BuildPending state0
state2 = handleEventFlat event state1
pr1 = fromJust $ Project.lookupPullRequest (PullRequestId 1) state1
pr2 = fromJust $ Project.lookupPullRequest (PullRequestId 1) state2
Project.buildStatus pr1 `shouldBe` Project.BuildPending
Project.buildStatus pr2 `shouldBe` Project.BuildNotStarted
it "ignores false positive commit changed events" $ do
let event = PullRequestCommitChanged (PullRequestId 1) (Sha "000")
state0 = singlePullRequestState (PullRequestId 1) (Branch "p") (Sha "000") "cindy"
state1 = Project.setApproval (PullRequestId 1) (Just "daniel") state0
state2 = Project.setBuildStatus (PullRequestId 1) Project.BuildPending state1
state3 = handleEventFlat event state2
state3 `shouldBe` state2
-- TODO: Also assert that no actions are performed.
it "sets approval after a stamp from a reviewer" $ do
let state = singlePullRequestState (PullRequestId 1) (Branch "p") (Sha "6412ef5") "toby"
-- Note: "deckard" is marked as reviewer in the test config.
event = CommentAdded (PullRequestId 1) "deckard" "LGTM 6412ef5"
state' = handleEventFlat event state
pr = fromJust $ Project.lookupPullRequest (PullRequestId 1) state'
Project.approvedBy pr `shouldBe` Just "deckard"
it "does not set approval after a stamp from a non-reviewer" $ do
let state = singlePullRequestState (PullRequestId 1) (Branch "p") (Sha "6412ef5") "toby"
-- Note: the comment is a valid LGTM stamp, but "rachael" is not
-- marked as reviewer in the test config.
event = CommentAdded (PullRequestId 1) "rachael" "LGTM 6412ef5"
state' = handleEventFlat event state
pr = fromJust $ Project.lookupPullRequest (PullRequestId 1) state'
Project.approvedBy pr `shouldBe` Nothing
it "does not set approval after a random comment" $ do
let state = singlePullRequestState (PullRequestId 1) (Branch "p") (Sha "6412ef5") "patrick"
-- Test coments with 2 words and more or less. (The stamp expects
-- exactly two words.)
event1 = CommentAdded (PullRequestId 1) "thomas" "We're up all night"
event2 = CommentAdded (PullRequestId 1) "guyman" "to get"
event3 = CommentAdded (PullRequestId 1) "thomas" "lucky."
state' = handleEventsFlat [event1, event2, event3] state
pr = fromJust $ Project.lookupPullRequest (PullRequestId 1) state'
Project.approvedBy pr `shouldBe` Nothing
it "requires a long enough sha for approval" $ do
let state = singlePullRequestState (PullRequestId 1) (Branch "p") (Sha "6412ef5") "sacha"
-- A 6-character sha is not long enough for approval.
event = CommentAdded (PullRequestId 1) "richard" "LGTM 6412ef"
state' = handleEventFlat event state
pr = fromJust $ Project.lookupPullRequest (PullRequestId 1) state'
Project.approvedBy pr `shouldBe` Nothing
it "handles a build status change of the integration candidate" $ do
let event = BuildStatusChanged (Sha "84c") Project.BuildSucceeded
state = candidateState (PullRequestId 1) (Branch "p") (Sha "a38") "johanna" (Sha "84c")
state' = handleEventFlat event state
pr = fromJust $ Project.lookupPullRequest (PullRequestId 1) state'
Project.buildStatus pr `shouldBe` Project.BuildSucceeded
it "ignores a build status change of random shas" $ do
let event0 = PullRequestOpened (PullRequestId 2) (Branch "p") (Sha "0ad") "title" "harry"
event1 = BuildStatusChanged (Sha "0ad") Project.BuildSucceeded
state = candidateState (PullRequestId 1) (Branch "p") (Sha "a38") "harry" (Sha "84c")
state' = handleEventsFlat [event0, event1] state
pr1 = fromJust $ Project.lookupPullRequest (PullRequestId 1) state'
pr2 = fromJust $ Project.lookupPullRequest (PullRequestId 2) state'
-- Even though the build status changed for "0ad" which is a known commit,
-- only the build status of the integration candidate can be changed.
Project.buildStatus pr1 `shouldBe` Project.BuildNotStarted
Project.buildStatus pr2 `shouldBe` Project.BuildNotStarted
describe "Logic.proceedUntilFixedPoint" $ do
it "finds a new candidate" $ do
let state = Project.setApproval (PullRequestId 1) (Just "fred") $
singlePullRequestState (PullRequestId 1) (Branch "p") (Sha "f34") "sally"
(state', actions) = proceedUntilFixedPointFlat (Just (Sha "38c")) PushRejected state
(prId, pullRequest) = fromJust $ Project.getIntegrationCandidate state'
Project.integrationStatus pullRequest `shouldBe` Project.Integrated (Sha "38c")
Project.buildStatus pullRequest `shouldBe` Project.BuildPending
prId `shouldBe` PullRequestId 1
actions `shouldBe`
[ ATryIntegrate "Merge #1\n\nApproved-by: fred" (Branch "refs/pull/1/head", Sha "f34")
, ALeaveComment (PullRequestId 1) "Rebased as 38c, waiting for CI \x2026"
]
it "pushes after a successful build" $ do
let pullRequest = PullRequest
{
Project.branch = Branch "results/rachael",
Project.sha = Sha "f35",
Project.title = "Add my test results",
Project.author = "rachael",
Project.approvedBy = Just "deckard",
Project.buildStatus = Project.BuildSucceeded,
Project.integrationStatus = Project.Integrated (Sha "38d")
}
state = ProjectState
{
Project.pullRequests = IntMap.singleton 1 pullRequest,
Project.integrationCandidate = Just $ PullRequestId 1
}
(state', actions) = proceedUntilFixedPointFlat (Just (Sha "38e")) PushOk state
candidate = Project.getIntegrationCandidate state'
-- After a successful push, the candidate should be gone.
candidate `shouldBe` Nothing
actions `shouldBe` [ATryPromote (Branch "results/rachael") (Sha "38d")]
it "restarts the sequence after a rejected push" $ do
-- Set up a pull request that has gone through the review and build cycle,
-- and is ready to be pushed to master.
let pullRequest = PullRequest
{
Project.branch = Branch "results/rachael",
Project.sha = Sha "f35",
Project.title = "Add my test results",
Project.author = "rachael",
Project.approvedBy = Just "deckard",
Project.buildStatus = Project.BuildSucceeded,
Project.integrationStatus = Project.Integrated (Sha "38d")
}
state = ProjectState
{
Project.pullRequests = IntMap.singleton 1 pullRequest,
Project.integrationCandidate = Just $ PullRequestId 1
}
-- Run 'proceedUntilFixedPoint', and pretend that pushes fail (because
-- something was pushed in the mean time, for instance).
(state', actions) = proceedUntilFixedPointFlat (Just (Sha "38e")) PushRejected state
(_, pullRequest') = fromJust $ Project.getIntegrationCandidate state'
Project.integrationStatus pullRequest' `shouldBe` Project.Integrated (Sha "38e")
Project.buildStatus pullRequest' `shouldBe` Project.BuildPending
actions `shouldBe`
[ ATryPromote (Branch "results/rachael") (Sha "38d")
, ATryIntegrate "Merge #1\n\nApproved-by: deckard" (Branch "refs/pull/1/head", Sha "f35")
, ALeaveComment (PullRequestId 1) "Rebased as 38e, waiting for CI \x2026"
]
it "picks a new candidate from the queue after a successful push" $ do
let pullRequest1 = PullRequest
{
Project.branch = Branch "results/leon",
Project.sha = Sha "f35",
Project.title = "Add Leon test results",
Project.author = "rachael",
Project.approvedBy = Just "deckard",
Project.buildStatus = Project.BuildSucceeded,
Project.integrationStatus = Project.Integrated (Sha "38d")
}
pullRequest2 = PullRequest
{
Project.branch = Branch "results/rachael",
Project.sha = Sha "f37",
Project.title = "Add my test results",
Project.author = "rachael",
Project.approvedBy = Just "deckard",
Project.buildStatus = Project.BuildNotStarted,
Project.integrationStatus = Project.NotIntegrated
}
prMap = IntMap.fromList [(1, pullRequest1), (2, pullRequest2)]
-- After a successful push, the state of pull request 1 will still be
-- BuildSucceeded and Integrated, but the candidate will be Nothing.
state = ProjectState
{
Project.pullRequests = prMap,
Project.integrationCandidate = Nothing
}
-- Proceeding should pick the next pull request as candidate.
(state', actions) = proceedUntilFixedPointFlat (Just (Sha "38e")) PushOk state
Just (cId, _candidate) = Project.getIntegrationCandidate state'
cId `shouldBe` PullRequestId 2
actions `shouldBe`
[ ATryIntegrate "Merge #2\n\nApproved-by: deckard" (Branch "refs/pull/2/head", Sha "f37")
, ALeaveComment (PullRequestId 2) "Rebased as 38e, waiting for CI \x2026"
]
describe "Github._Payload" $ do
it "parses a PullRequestPayload correctly" $ do
examplePayload <- readFile "tests/data/pull-request-payload.json"
let maybePayload :: Maybe PullRequestPayload
maybePayload = decode examplePayload
maybePayload `shouldSatisfy` isJust
let payload = fromJust maybePayload
action = Github.action (payload :: PullRequestPayload)
owner = Github.owner (payload :: PullRequestPayload)
repository = Github.repository (payload :: PullRequestPayload)
number = Github.number (payload :: PullRequestPayload)
headSha = Github.sha (payload :: PullRequestPayload)
title = Github.title (payload :: PullRequestPayload)
prAuthor = Github.author (payload :: PullRequestPayload)
prBranch = Github.branch (payload :: PullRequestPayload)
action `shouldBe` Github.Opened
owner `shouldBe` "baxterthehacker"
repository `shouldBe` "public-repo"
number `shouldBe` 1
headSha `shouldBe` (Sha "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c")
prBranch `shouldBe` (Branch "changes")
title `shouldBe` "Update the README with new information"
prAuthor `shouldBe` "baxterthehacker2"
it "parses a CommentPayload correctly" $ do
examplePayload <- readFile "tests/data/issue-comment-payload.json"
let maybePayload :: Maybe CommentPayload
maybePayload = decode examplePayload
maybePayload `shouldSatisfy` isJust
let payload = fromJust maybePayload
action = Github.action (payload :: CommentPayload)
owner = Github.owner (payload :: CommentPayload)
repository = Github.repository (payload :: CommentPayload)
number = Github.number (payload :: CommentPayload)
commentAuthor = Github.author (payload :: CommentPayload)
commentBody = Github.body (payload :: CommentPayload)
action `shouldBe` Github.Created
owner `shouldBe` "baxterthehacker"
repository `shouldBe` "public-repo"
number `shouldBe` 2
commentAuthor `shouldBe` "baxterthehacker2"
commentBody `shouldBe` "You are totally right! I'll get this fixed right away."
it "parses a CommitStatusPayload correctly" $ do
examplePayload <- readFile "tests/data/status-payload.json"
let maybePayload :: Maybe CommitStatusPayload
maybePayload = decode examplePayload
maybePayload `shouldSatisfy` isJust
let payload = fromJust maybePayload
owner = Github.owner (payload :: CommitStatusPayload)
repository = Github.repository (payload :: CommitStatusPayload)
status = Github.status (payload :: CommitStatusPayload)
url = Github.url (payload :: CommitStatusPayload)
commitSha = Github.sha (payload :: CommitStatusPayload)
owner `shouldBe` "baxterthehacker"
repository `shouldBe` "public-repo"
status `shouldBe` Github.Success
url `shouldBe` Nothing
commitSha `shouldBe` (Sha "9049f1265b7d61be4a8904a9a27120d2064dab3b")
describe "Configuration" $ do
it "loads the example config file correctly" $ do
-- This test loads the example configuration file that is packaged. It
-- serves two purposes: to test that loading a config file works, but
-- mainly, to enforce that the example file is kept up to date.
Right cfg <- Config.loadConfiguration "package/example-config.json"
Config.secret cfg `shouldBe` "run 'head --bytes 32 /dev/urandom | base64' and paste output here"
Config.accessToken cfg `shouldBe` "paste a personal access token for a bot user here"
Config.port cfg `shouldBe` 1979
Config.tls cfg `shouldSatisfy` isNothing
let
projects = Config.projects cfg
project = head projects
user = Config.user cfg
Config.owner project `shouldBe` "your-github-username-or-organization"
Config.repository project `shouldBe` "your-repo"
Config.branch project `shouldBe` "master"
Config.testBranch project `shouldBe` "testing"
Config.checkout project `shouldBe` "/var/lib/hoff/checkouts/your-username/your-repo"
Config.reviewers project `shouldBe` ["your-github-username"]
Config.stateFile project `shouldBe` "/var/lib/hoff/state/your-username/your-repo.json"
Config.name user `shouldBe` "CI Bot"
Config.email user `shouldBe` "[email protected]"
Config.sshConfigFile user `shouldBe` "/etc/hoff/ssh_config"
describe "EventLoop.convertGithubEvent" $ do
let testPullRequestPayload action = Github.PullRequestPayload
{ action = action
, owner = "deckard"
, repository = "repo"
, number = 1
, branch = Branch "results"
, sha = Sha "b26354"
, title = "Add test results"
, author = "rachael"
}
it "converts a pull request opened event" $ do
let payload = testPullRequestPayload Github.Opened
Just event = convertGithubEvent $ Github.PullRequest payload
event `shouldBe`
(PullRequestOpened (PullRequestId 1) (Branch "results") (Sha "b26354") "Add test results" "rachael")
it "converts a pull request reopened event" $ do
let payload = testPullRequestPayload Github.Reopened
Just event = convertGithubEvent $ Github.PullRequest payload
-- Reopened is treated just like opened, there is no memory in the system.
event `shouldBe`
(PullRequestOpened (PullRequestId 1) (Branch "results") (Sha "b26354") "Add test results" "rachael")
it "converts a pull request closed event" $ do
let payload = testPullRequestPayload Github.Closed
Just event = convertGithubEvent $ Github.PullRequest payload
event `shouldBe` (PullRequestClosed (PullRequestId 1))
it "converts a pull request synchronize event" $ do
let payload = testPullRequestPayload Github.Synchronize
Just event = convertGithubEvent $ Github.PullRequest payload
event `shouldBe` (PullRequestCommitChanged (PullRequestId 1) (Sha "b26354"))
let testCommentPayload action = Github.CommentPayload
{ action = action
, owner = "rachael"
, repository = "owl"
, number = 1
, author = "deckard"
, body = "Must be expensive."
}
it "converts a comment created event" $ do
let payload = testCommentPayload Github.Created
Just event = convertGithubEvent $ Github.Comment payload
event `shouldBe` (CommentAdded (PullRequestId 1) "deckard" "Must be expensive.")
it "ignores a comment edited event" $ do
let payload = testCommentPayload Github.Edited
event = convertGithubEvent $ Github.Comment payload
event `shouldBe` Nothing
it "ignores a comment deleted event" $ do
let payload = testCommentPayload Github.Deleted
event = convertGithubEvent $ Github.Comment payload
event `shouldBe` Nothing
let testCommitStatusPayload status = Github.CommitStatusPayload
{ owner = "rachael"
, repository = "owl"
, status = status
, url = Just "https://travis-ci.org/rachael/owl/builds/1982"
, sha = Sha "b26354"
}
it "converts a commit status pending event" $ do
let payload = testCommitStatusPayload Github.Pending
Just event = convertGithubEvent $ Github.CommitStatus payload
event `shouldBe` (BuildStatusChanged (Sha "b26354") Project.BuildPending)
it "converts a commit status success event" $ do
let payload = testCommitStatusPayload Github.Success
Just event = convertGithubEvent $ Github.CommitStatus payload
event `shouldBe` (BuildStatusChanged (Sha "b26354") Project.BuildSucceeded)
it "converts a commit status failure event" $ do
let payload = testCommitStatusPayload Github.Failure
Just event = convertGithubEvent $ Github.CommitStatus payload
event `shouldBe` (BuildStatusChanged (Sha "b26354") Project.BuildFailed)
it "converts a commit status error event" $ do
let payload = testCommitStatusPayload Github.Error
Just event = convertGithubEvent $ Github.CommitStatus payload
-- The error and failure statuses are both converted to "failed".
event `shouldBe` (BuildStatusChanged (Sha "b26354") Project.BuildFailed)
describe "ProjectState" $ do
it "can be restored exactly after roundtripping through json" $ do
let emptyState = Project.emptyProjectState
singleState = singlePullRequestState (PullRequestId 1) (Branch "p") (Sha "071") "deckard"
candState = candidateState (PullRequestId 2) (Branch "p") (Sha "073") "rachael" (Sha "079")
Just emptyState' = decode $ encode emptyState
Just singleState' = decode $ encode singleState
Just candState' = decode $ encode candState
emptyState `shouldBe` emptyState'
singleState `shouldBe` singleState'
candState `shouldBe` candState'
it "loads correctly after persisting to disk" $ do
-- Generate a random filename in /tmp (or equivalent) to persist the state
-- to during the test.
uuid <- Uuid.nextRandom
tmpBaseDir <- getTemporaryDirectory
let fname = tmpBaseDir </> ("state-" ++ (show uuid) ++ ".json")
state = singlePullRequestState (PullRequestId 1) (Branch "p") (Sha "071") "deckard"
Project.saveProjectState fname state
Just state' <- Project.loadProjectState fname
state `shouldBe` state'
removeFile fname
| ruuda/hoff | tests/Spec.hs | apache-2.0 | 27,376 | 0 | 22 | 6,967 | 6,078 | 3,106 | 2,972 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module Openshift.V1.DeploymentTriggerPolicy where
import GHC.Generics
import Data.Text
import Openshift.V1.DeploymentTriggerImageChangeParams
import Data.Aeson.TH (deriveJSON, defaultOptions, fieldLabelModifier)
-- |
data DeploymentTriggerPolicy = DeploymentTriggerPolicy
{ type_ :: Maybe Text -- ^ the type of the trigger
, imageChangeParams :: Maybe DeploymentTriggerImageChangeParams -- ^ input to the ImageChange trigger
} deriving (Show, Eq, Generic)
$(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if Prelude.last n == '_' then Prelude.take ((Prelude.length n) - 1 ) n else n)} ''DeploymentTriggerPolicy)
| minhdoboi/deprecated-openshift-haskell-api | openshift/lib/Openshift/V1/DeploymentTriggerPolicy.hs | apache-2.0 | 839 | 0 | 18 | 113 | 160 | 94 | 66 | 16 | 0 |
module Main where
import Crypto.Classes
import Crypto.Hash.MD4 (MD4)
import qualified Data.ByteString as B
import Data.Word (Word8)
import System.Exit
testHash :: [Word8]
testHash = [191,149,85,7,66,43,39,195,223,16,218,220,213,120,39,11]
main :: IO ()
main = do
testData <- B.readFile "testData.bin"
let testHash' = B.unpack $ encode ((hash' testData) :: MD4)
if testHash' == testHash
then exitSuccess
else do
print testHash'
exitFailure
| nullref/haskell-hash-ed2k | Benchmark/StrictMD4.hs | bsd-2-clause | 468 | 0 | 14 | 85 | 185 | 107 | 78 | 17 | 2 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : Script.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:14
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Script (
module Qtc.ClassTypes.Script
, module Qtc.Classes.Script
)
where
import Foreign.C.Types
import Qtc.ClassTypes.Script
import Qtc.Classes.Script
| keera-studios/hsQt | Qtc/Script.hs | bsd-2-clause | 582 | 0 | 5 | 100 | 44 | 31 | 13 | 7 | 0 |
-- http://www.codewars.com/kata/53da6a7e112bd15cbc000012
module Dictionaries where
import Data.List
import Data.Ord
sortDict :: Ord v => [(k,v)] -> [(k,v)]
sortDict = sortBy (flip $ comparing snd) | Bodigrim/katas | src/haskell/7-Sorting-Dictionaries.hs | bsd-2-clause | 198 | 0 | 8 | 25 | 67 | 39 | 28 | 5 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Numeric.Interval.Exception
( EmptyInterval(..)
, AmbiguousComparison(..)
) where
import Control.Exception
import Data.Data
data EmptyInterval = EmptyInterval
deriving (Eq,Ord,Typeable,Data)
instance Show EmptyInterval where
show EmptyInterval = "empty interval"
instance Exception EmptyInterval
data AmbiguousComparison = AmbiguousComparison
deriving (Eq,Ord,Typeable,Data)
instance Show AmbiguousComparison where
show AmbiguousComparison = "ambiguous comparison"
instance Exception AmbiguousComparison
| ekmett/intervals | src/Numeric/Interval/Exception.hs | bsd-2-clause | 567 | 0 | 6 | 73 | 132 | 73 | 59 | 16 | 0 |
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : Application.HXournal.Coroutine.Window
-- Copyright : (c) 2011, 2012 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module Application.HXournal.Coroutine.Window where
import Application.HXournal.Type.Canvas
import Application.HXournal.Type.Event
import Application.HXournal.Type.Window
import Application.HXournal.Type.XournalState
import Application.HXournal.Type.Coroutine
import Application.HXournal.Type.PageArrangement
import Application.HXournal.Type.Predefined
import Application.HXournal.Util
import Control.Monad.Trans
import Application.HXournal.ModelAction.Window
import Application.HXournal.ModelAction.Page
import Application.HXournal.Coroutine.Page
import Application.HXournal.Coroutine.Draw
import Application.HXournal.Accessor
import Control.Monad.Coroutine.SuspensionFunctors
import Control.Category
import Data.Label
import Graphics.UI.Gtk hiding (get,set)
import qualified Data.IntMap as M
import Data.Maybe
import Data.Time.Clock
import Data.Xournal.Simple (Dimension(..))
import Data.Xournal.Generic
import Prelude hiding ((.),id)
-- | canvas configure with general zoom update func
canvasConfigureGenUpdate :: MainCoroutine ()
-> CanvasId
-> CanvasDimension
-> MainCoroutine ()
canvasConfigureGenUpdate updatefunc cid cdim
= (updateXState $ selectBoxAction fsingle fcont . getCanvasInfo cid )
>> updatefunc
where fsingle cinfo = do
xstate <- getSt
let cinfo' = updateCanvasDimForSingle cdim cinfo
return $ setCanvasInfo (cid,CanvasInfoBox cinfo') xstate
fcont cinfo = do
xstate <- getSt
page <- getCurrentPageCvsId cid
let pdim = PageDimension (get g_dimension page)
let cinfo' = updateCanvasDimForContSingle pdim cdim cinfo
return $ setCanvasInfo (cid,CanvasInfoBox cinfo') xstate
-- |
doCanvasConfigure :: CanvasId
-> CanvasDimension
-> MainCoroutine ()
doCanvasConfigure = canvasConfigureGenUpdate canvasZoomUpdateAll
-- |
canvasConfigure' :: CanvasId -> CanvasDimension -> MainCoroutine ()
canvasConfigure' cid cdim = do
xstate <- getSt
ctime <- liftIO getCurrentTime
maybe defaction (chkaction ctime) (get lastTimeCanvasConfigure xstate)
where defaction = do
ntime <- liftIO getCurrentTime
doCanvasConfigure cid cdim
updateXState (return . set lastTimeCanvasConfigure (Just ntime))
chkaction ctime otime = do
let dtime = diffUTCTime ctime otime
if dtime > predefinedWinReconfTimeBound
then defaction
else return ()
-- |
eitherSplit :: SplitType -> MainCoroutine ()
eitherSplit stype = do
xstate <- getSt
let cmap = getCanvasInfoMap xstate
currcid = getCurrentCanvasId xstate
newcid = newCanvasId cmap
fstate = get frameState xstate
enewfstate = splitWindow currcid (newcid,stype) fstate
case enewfstate of
Left _ -> return ()
Right fstate' -> do
case maybeError "eitherSplit" . M.lookup currcid $ cmap of
CanvasInfoBox oldcinfo -> do
liftIO $ putStrLn "called here"
let rtwin = get rootWindow xstate
rtcntr = get rootContainer xstate
liftIO $ containerRemove rtcntr rtwin
(xstate'',win,fstate'') <-
liftIO $ constructFrame' (CanvasInfoBox oldcinfo) xstate fstate'
let xstate3 = set frameState fstate''
. set rootWindow win
$ xstate''
putSt xstate3
liftIO $ boxPackEnd rtcntr win PackGrow 0
liftIO $ widgetShowAll rtcntr
(xstate4,_wconf) <- liftIO $ eventConnect xstate3 (get frameState xstate3)
xstate5 <- liftIO $ updatePageAll (get xournalstate xstate4) xstate4
putSt xstate5
canvasZoomUpdateAll
invalidateAll
-- |
deleteCanvas :: MainCoroutine ()
deleteCanvas = do
xstate <- getSt
let cmap = getCanvasInfoMap xstate
currcid = getCurrentCanvasId xstate
fstate = get frameState xstate
enewfstate = removeWindow currcid fstate
case enewfstate of
Left _ -> return ()
Right Nothing -> return ()
Right (Just fstate') -> do
case maybeError "deleteCanvas" (M.lookup currcid cmap) of
CanvasInfoBox _oldcinfo -> do
let cmap' = M.delete currcid cmap
newcurrcid = maximum (M.keys cmap')
xstate0 <- changeCurrentCanvasId newcurrcid
let xstate1 = maybe xstate0 id $ setCanvasInfoMap cmap' xstate0
putSt xstate1
let rtwin = get rootWindow xstate1
rtcntr = get rootContainer xstate1
liftIO $ containerRemove rtcntr rtwin
(xstate'',win,fstate'') <- liftIO $ constructFrame xstate1 fstate'
let xstate3 = set frameState fstate''
. set rootWindow win
$ xstate''
putSt xstate3
liftIO $ boxPackEnd rtcntr win PackGrow 0
liftIO $ widgetShowAll rtcntr
(xstate4,_wconf) <- liftIO $ eventConnect xstate3 (get frameState xstate3)
canvasZoomUpdateAll
xstate5 <- liftIO $ updatePageAll (get xournalstate xstate4) xstate4
putSt xstate5
invalidateAll
-- |
paneMoveStart :: MainCoroutine ()
paneMoveStart = do
ev <- await
case ev of
UpdateCanvas cid -> invalidateWithBuf cid >> paneMoveStart
PaneMoveEnd -> do
-- canvasZoomUpdateAll
return ()
CanvasConfigure cid w' h'-> do
canvasConfigureGenUpdate canvasZoomUpdateBufAll cid (CanvasDimension (Dim w' h'))
>> paneMoveStart
_ -> paneMoveStart
-- |
paneMoved :: MainCoroutine ()
paneMoved = do
liftIO $ putStrLn "pane moved called"
| wavewave/hxournal | lib/Application/HXournal/Coroutine/Window.hs | bsd-2-clause | 6,382 | 0 | 23 | 1,833 | 1,475 | 733 | 742 | 138 | 4 |
module Language.Drasil.Code.Imperative.Descriptions (
modDesc, inputParametersDesc, inputConstructorDesc, inputFormatDesc,
derivedValuesDesc, inputConstraintsDesc, constModDesc, outputFormatDesc,
inputClassDesc, constClassDesc, inFmtFuncDesc, inConsFuncDesc, dvFuncDesc,
woFuncDesc
) where
import Utils.Drasil (stringList)
import Language.Drasil
import Language.Drasil.Code.Imperative.DrasilState (DrasilState(..), inMod)
import Language.Drasil.Chunk.Code (CodeIdea(codeName))
import Language.Drasil.CodeSpec (CodeSpec(..), CodeSystInfo(..),
InputModule(..), Structure(..))
import Data.Map (member)
import qualified Data.Map as Map (filter, lookup, elems)
import Control.Monad.Reader (Reader, ask)
modDesc :: Reader DrasilState [String] -> Reader DrasilState String
modDesc = fmap ((++) "Provides " . stringList)
inputParametersDesc :: Reader DrasilState [String]
inputParametersDesc = do
g <- ask
ifDesc <- inputFormatDesc
dvDesc <- derivedValuesDesc
icDesc <- inputConstraintsDesc
let im = inMod g
st = inStruct g
ipDesc Separated = inDesc st
ipDesc Combined = inDesc st ++ [ifDesc, dvDesc, icDesc]
inDesc Bundled = ["the structure for holding input values"]
inDesc Unbundled = [""]
return $ ipDesc im
inputConstructorDesc :: Reader DrasilState String
inputConstructorDesc = do
g <- ask
pAndS <- physAndSfwrCons
let ifDesc False = ""
ifDesc True = "reading inputs"
idDesc False = ""
idDesc True = "calculating derived values"
icDesc False = ""
icDesc True = "checking " ++ pAndS ++ " on the input"
dl = defList $ codeSpec g
return $ "Initializes input object by " ++ stringList [
ifDesc ("get_input" `elem` dl),
idDesc ("derived_values" `elem` dl),
icDesc ("input_constraints" `elem` dl)]
inputFormatDesc :: Reader DrasilState String
inputFormatDesc = do
g <- ask
let ifDesc Nothing = ""
ifDesc _ = "the function for reading inputs"
return $ ifDesc $ Map.lookup "get_input" (eMap $ codeSpec g)
derivedValuesDesc :: Reader DrasilState String
derivedValuesDesc = do
g <- ask
let dvDesc Nothing = ""
dvDesc _ = "the function for calculating derived values"
return $ dvDesc $ Map.lookup "derived_values" (eMap $ codeSpec g)
inputConstraintsDesc :: Reader DrasilState String
inputConstraintsDesc = do
g <- ask
pAndS <- physAndSfwrCons
let icDesc Nothing = ""
icDesc _ = "the function for checking the " ++ pAndS ++
" on the input"
return $ icDesc $ Map.lookup "input_constraints" (eMap $ codeSpec g)
constModDesc :: Reader DrasilState String
constModDesc = do
g <- ask
let cDesc [] = ""
cDesc _ = "the structure for holding constant values"
return $ cDesc $ filter (flip member (eMap $ codeSpec g) . codeName)
(constants $ csi $ codeSpec g)
outputFormatDesc :: Reader DrasilState String
outputFormatDesc = do
g <- ask
let ofDesc Nothing = ""
ofDesc _ = "the function for writing outputs"
return $ ofDesc $ Map.lookup "write_output" (eMap $ codeSpec g)
inputClassDesc :: Reader DrasilState String
inputClassDesc = do
g <- ask
let cname = "InputParameters"
inClassD [] = ""
inClassD _ = "Structure for holding the " ++ stringList [
inPs $ extInputs $ csi $ codeSpec g,
dVs $ "derived_values" `elem` defList (codeSpec g),
cVs $ filter (flip member (Map.filter (cname ==)
(eMap $ codeSpec g)) . codeName) (constants $ csi $ codeSpec g)]
inPs [] = ""
inPs _ = "input values"
dVs False = ""
dVs _ = "derived values"
cVs [] = ""
cVs _ = "constant values"
return $ inClassD $ inputs $ csi $ codeSpec g
constClassDesc :: Reader DrasilState String
constClassDesc = do
g <- ask
let ccDesc [] = ""
ccDesc _ = "Structure for holding the constant values"
return $ ccDesc $ filter (flip member (eMap $ codeSpec g) . codeName)
(constants $ csi $ codeSpec g)
inFmtFuncDesc :: Reader DrasilState String
inFmtFuncDesc = do
g <- ask
let ifDesc False = ""
ifDesc _ = "Reads input from a file with the given file name"
return $ ifDesc $ "get_input" `elem` defList (codeSpec g)
inConsFuncDesc :: Reader DrasilState String
inConsFuncDesc = do
g <- ask
pAndS <- physAndSfwrCons
let icDesc False = ""
icDesc _ = "Verifies that input values satisfy the " ++ pAndS
return $ icDesc $ "input_constraints" `elem` defList (codeSpec g)
dvFuncDesc :: Reader DrasilState String
dvFuncDesc = do
g <- ask
let dvDesc False = ""
dvDesc _ = "Calculates values that can be immediately derived from the" ++
" inputs"
return $ dvDesc $ "derived_values" `elem` defList (codeSpec g)
woFuncDesc :: Reader DrasilState String
woFuncDesc = do
g <- ask
let woDesc False = ""
woDesc _ = "Writes the output values to output.txt"
return $ woDesc $ "write_output" `elem` defList (codeSpec g)
physAndSfwrCons :: Reader DrasilState String
physAndSfwrCons = do
g <- ask
let cns = concat $ Map.elems (cMap $ csi $ codeSpec g)
return $ stringList [
if null (map isPhysC cns) then "" else "physical constraints",
if null (map isSfwrC cns) then "" else "software constraints"] | JacquesCarette/literate-scientific-software | code/drasil-code/Language/Drasil/Code/Imperative/Descriptions.hs | bsd-2-clause | 5,197 | 0 | 22 | 1,128 | 1,632 | 832 | 800 | 134 | 5 |
module Core.DrawInterval where
import Core.Interval
import Core.CommonData
import Core.Replace
-- base
import Numeric (showFFloat)
-- SVGFonts
import Graphics.SVGFonts
-- diagrams-svg
import Diagrams.Prelude hiding (Duration, interval)
import Diagrams.Backend.SVG
import Diagrams.Core.Points
show2Digit d = showFFloat (Just 2) d ""
-- Draw
textDef t = scale textSize $ fc black $ lc black $ stroke $ textSVG' (TextOpts t lin INSIDE_H KERN False 1 1)
textSize = 25
drawGrads :: [GradData] -> Diagram SVG R2
drawGrads itvls = mconcat (map drawGrad itvls) <> lastKm
where lastKm = translateX e $ rotate (1/4 @@ turn) $ textDef (showKm e)
((_,e), Grad _ _ _) = last itvls
drawGrad :: GradData -> Diagram SVG R2
drawGrad ((s,e), Grad n d _) = pathImg <> km
where title = translateX mid $ textDef n === textDef (show2Digit d)
mid = (s + e) / 2
km = translateX s $ rotate (1/4 @@ turn) $ textDef (showKm s)
pathImg | 0 /= d = (scaleY (signum d) $ p2 (s,25) ~~ p2 (e,-25)) <> title
| d == 0 = p2 (s, 0) ~~ p2 (e, 0)
drawRadis :: [RadiData] -> Diagram SVG R2
drawRadis itvls = mconcat (map drawRadi itvls) <> lastKm
where lastKm = translateX e $ rotate (1/4 @@ turn) $ textDef (showKm e)
((_, e), Radi _ _ _) = last itvls
drawRadi :: RadiData -> Diagram SVG R2
drawRadi ((s,e), Radi n d _) = translateX s $ pathImg <> km
where unitArc = scaleY 50 $ centerY $ scaleX (1/2) $ align unit_X $ arc (0 @@ turn) (1/2 @@ turn)
dist = e - s
title = translateX (dist / 2) $ textDef n === textDef (show2Digit d)
km = rotate (1/4 @@ turn) $ (textDef (showKm s))
pathImg | (1/0) /= d = (scaleY (signum d) $ scaleX dist unitArc) <> title
| d == (1/0) = fromOffsets [dist *^ unitX]
| wkoiking/fieldequip | src/Core/DrawInterval.hs | bsd-3-clause | 1,767 | 0 | 14 | 422 | 856 | 440 | 416 | 35 | 1 |
module BowlingGame.KataSpec (spec) where
import Test.Hspec
import BowlingGame.Kata(score, roll, startGame, Game)
spec :: Spec
spec =
describe "Bowling Game" $ do
it "processes gutter game" $
score (rollMany 20 0 startGame) `shouldBe` 0
it "processes all ones" $
score (rollMany 20 1 startGame) `shouldBe` 20
it "processes one spare" $
score (rollSpare $ roll 3 $ rollMany 17 0 startGame) `shouldBe` 16
it "processes one strike" $
score (rollStrike $ roll 4 $ roll 3 $ rollMany 16 0 startGame) `shouldBe` 24
it "processes perfect game" $
score (rollMany 12 10 startGame) `shouldBe` 300
rollMany :: Int -> Int -> Game -> Game
rollMany times pin game
| times == 0 = game
| otherwise = rollMany (times - 1) pin (roll pin game)
rollSpare :: Game -> Game
rollSpare = roll 4 . roll 6
rollStrike :: Game -> Game
rollStrike = roll 10
| Alex-Diez/haskell-tdd-kata | BowlingGameKata/BowlingGameDay08/test/BowlingGame/KataSpec.hs | bsd-3-clause | 939 | 0 | 15 | 259 | 337 | 169 | 168 | 24 | 1 |
{-# LANGUAGE RankNTypes, PolyKinds, DataKinds, ConstraintKinds, ScopedTypeVariables, KindSignatures, TypeFamilies, MultiParamTypeClasses, UndecidableInstances, UndecidableSuperClasses, GADTs, AllowAmbiguousTypes, FlexibleInstances, NoImplicitPrelude #-}
module Hask.Category.Polynomial
(
-- * Product Category
Product(..), ProductOb, Fst, Snd
-- * Coproduct Category
, Coproduct(..), CoproductOb(..)
-- * Unit Category
, Unit(..)
-- * Empty Category
, Empty
, Void, absurd
) where
import Hask.Category
import Data.Void
import Hask.Functor.Faithful
--------------------------------------------------------------------------------
-- * Products
--------------------------------------------------------------------------------
-- TODO: do this as a product of profunctors instead?
data Product (p :: i -> i -> *) (q :: j -> j -> *) (a :: (i, j)) (b :: (i, j)) =
Product (p (Fst a) (Fst b)) (q (Snd a) (Snd b))
type family Fst (p :: (i,j)) :: i
type instance Fst '(a,b) = a
type family Snd (q :: (i,j)) :: j
type instance Snd '(a,b) = b
class (Ob p (Fst a), Ob q (Snd a)) => ProductOb (p :: i -> i -> *) (q :: j -> j -> *) (a :: (i,j))
instance (Ob p (Fst a), Ob q (Snd a)) => ProductOb (p :: i -> i -> *) (q :: j -> j -> *) (a :: (i,j))
instance (Category p, Category q) => Functor (Product p q) where
type Dom (Product p q) = Op (Product (Opd p) (Opd q))
type Cod (Product p q) = Nat (Product (Dom2 p) (Dom2 q)) (->)
fmap f = case observe f of
Dict -> Nat (. unop f)
instance (Category p, Category q, ProductOb p q a) => Functor (Product p q a) where
type Dom (Product p q a) = Product (Dom2 p) (Dom2 q)
type Cod (Product p q a) = (->)
fmap = (.)
instance (Category p, Category q) => Category' (Product p q) where
type Ob (Product p q) = ProductOb p q
id = Product id id
Product f f' . Product g g' = Product (f . g) (f' . g')
observe (Product f g) = case observe f of
Dict -> case observe g of
Dict -> Dict
--------------------------------------------------------------------------------
-- * Coproducts
--------------------------------------------------------------------------------
data Coproduct (c :: i -> i -> *) (d :: j -> j -> *) (a :: Either i j) (b :: Either i j) where
Inl :: c x y -> Coproduct c d ('Left x) ('Left y)
Inr :: d x y -> Coproduct c d ('Right x) ('Right y)
class CoproductOb (p :: i -> i -> *) (q :: j -> j -> *) (a :: Either i j) where
side :: Endo (Coproduct p q) a -> (forall x. (a ~ 'Left x, Ob p x) => r) -> (forall y. (a ~ 'Right y, Ob q y) => r) -> r
coproductId :: Endo (Coproduct p q) a
instance (Category p, Ob p x) => CoproductOb (p :: i -> i -> *) (q :: j -> j -> *) ('Left x :: Either i j) where
side _ r _ = r
coproductId = Inl id
instance (Category q, Ob q y) => CoproductOb (p :: i -> i -> *) (q :: j -> j -> *) ('Right y :: Either i j) where
side _ _ r = r
coproductId = Inr id
instance (Category p, Category q) => Functor (Coproduct p q) where
type Dom (Coproduct p q) = Op (Coproduct p q)
type Cod (Coproduct p q) = Nat (Coproduct p q) (->)
fmap (Op f) = Nat (. f)
instance (Category p, Category q) => Functor (Coproduct p q a) where
type Dom (Coproduct p q a) = Coproduct p q
type Cod (Coproduct p q a) = (->)
fmap = (.)
instance (Category p, Category q) => Category' (Coproduct p q) where
type Ob (Coproduct p q) = CoproductOb p q
id = coproductId
observe (Inl f) = case observe f of
Dict -> Dict
observe (Inr f) = case observe f of
Dict -> Dict
Inl f . Inl g = Inl (f . g)
Inr f . Inr g = Inr (f . g)
--------------------------------------------------------------------------------
-- * The Unit category
--------------------------------------------------------------------------------
data Unit a b = Unit
instance Functor Unit where
type Dom Unit = Op Unit
type Cod Unit = Nat Unit (->)
fmap _ = Nat $ \_ -> Unit
instance Functor (Unit a) where
type Dom (Unit a) = Unit
type Cod (Unit a) = (->)
fmap _ _ = Unit
instance Category' Unit where
type Ob Unit = Vacuous Unit
id = Unit
Unit . Unit = Unit
observe _ = Dict
instance FullyFaithful Unit where
unfmap _ = Op Unit
instance FullyFaithful (Unit a) where
unfmap _ = Unit
--------------------------------------------------------------------------------
-- * The Empty category
--------------------------------------------------------------------------------
data Empty (a :: Void) (b :: Void)
{-
instance Functor Empty where
type Dom Empty = Op Empty
type Cod Empty = Nat Empty (->)
fmap f = case f of {}
instance No (:-) a => Functor (Empty a) where
type Dom (Empty a) = Empty
type Cod (Empty a) = (->)
fmap f = case f of {}
data NO = No
-- | the functor from the empty category to every category
type No = (Any 'No :: (i -> i -> *) -> Void -> i)
-- | the empty category
instance Category' c => Functor (No c) where
type Dom (No c) = Empty
type Cod (No c) = c
fmap f = case f of {}
instance Category' Empty where
type Ob Empty = No (:-)
id = undefined -- no
f . _ = case f of {}
observe f = case f of {}
-}
| ekmett/hask | src/Hask/Category/Polynomial.hs | bsd-3-clause | 5,102 | 42 | 16 | 1,131 | 1,908 | 1,030 | 878 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>), (<*>))
#endif
import Data.Attoparsec.Text (parseOnly)
import qualified Data.Text.IO as Text
import Test.Tasty (defaultMain)
import Test.Tasty.HUnit
import qualified Data.GraphQL.Parser as Parser
import qualified Data.GraphQL.Encoder as Encoder
import Paths_graphql (getDataFileName)
main :: IO ()
main = defaultMain =<< testCase "Kitchen Sink"
<$> (assertEqual "Encode" <$> expected <*> actual)
where
expected = Text.readFile
=<< getDataFileName "tests/data/kitchen-sink.min.graphql"
actual = either (error "Parsing error!") Encoder.document
<$> parseOnly Parser.document
<$> expected
| timmytofu/graphql-haskell | tests/tasty.hs | bsd-3-clause | 787 | 0 | 11 | 145 | 174 | 105 | 69 | 19 | 1 |
-- | This module provides flags for the problem type.
module Tct.Trs.Data.ProblemKind
(
StartTerms (..)
, isStartTerm
, mapStartTerms
, Strategy (..)
) where
import Data.Monoid
import qualified Data.Set as S
import qualified Data.Rewriting.Term as R
import qualified Tct.Core.Common.Pretty as PP
import qualified Tct.Core.Common.Xml as Xml
import Tct.Trs.Data.Signature (Signature, Symbols, restrictSignature)
-- | Defineds the start terms.
data StartTerms f
= AllTerms
{ alls :: Symbols f }
| BasicTerms
{ defineds :: Symbols f
, constructors :: Symbols f }
deriving (Show, Eq)
-- | Checks wether a given term is a start term.
isStartTerm :: Ord f => StartTerms f -> R.Term f v -> Bool
isStartTerm (AllTerms fs) t = case t of
(R.Var _) -> True
(R.Fun f _) -> f `S.member` fs
isStartTerm (BasicTerms ds cs) t = case t of
(R.Var _) -> True
(R.Fun f ts) -> f `S.member` ds && all (`S.member` cs) (concatMap R.funs ts)
mapStartTerms :: Ord f' => (f -> f') -> StartTerms f -> StartTerms f'
mapStartTerms f (AllTerms fs) = AllTerms (f `S.map` fs)
mapStartTerms f (BasicTerms ds cs) = BasicTerms (f `S.map` ds) (f `S.map` cs)
-- | Defineds the rewriting Strategy.
data Strategy = Innermost | Outermost | Full deriving (Show, Eq)
--- * proof data -----------------------------------------------------------------------------------------------------
instance PP.Pretty Strategy where
pretty = PP.text . show
instance (Ord f, PP.Pretty f) => PP.Pretty (StartTerms f) where
pretty st@AllTerms{} = PP.text "all terms: " <> PP.set' (alls st)
pretty st@BasicTerms{} = PP.text "basic terms: " <> PP.set' (defineds st) <> PP.char '/' <> PP.set' (constructors st)
instance Xml.Xml Strategy where
toXml s = Xml.elt "strategy" $ (:[]) $ case s of
Innermost -> Xml.elt "innermost" []
Outermost -> Xml.elt "outermost" []
Full -> Xml.elt "full" []
toCeTA s = case s of
Innermost -> Xml.elt "strategy" [Xml.elt "innermost" []]
Outermost -> Xml.elt "strategy" [Xml.elt "outermost" []]
Full -> Xml.empty
instance (Xml.Xml f, Ord f) => Xml.Xml (StartTerms f, Signature f) where
toXml (st,sig) = case st of
(AllTerms fs) -> Xml.elt "derivationalComplexity" [Xml.toXml $ restrictSignature sig fs]
(BasicTerms ds cs) -> Xml.elt "runtimeComplexity" $ map Xml.toXml [restrictSignature sig cs, restrictSignature sig ds]
toCeTA = Xml.toXml
| ComputationWithBoundedResources/tct-trs | src/Tct/Trs/Data/ProblemKind.hs | bsd-3-clause | 2,491 | 0 | 12 | 542 | 902 | 482 | 420 | 49 | 3 |
{-# LANGUAGE PackageImports #-}
module Control.Monad.Fix (module M) where
import "base" Control.Monad.Fix as M
| silkapp/base-noprelude | src/Control/Monad/Fix.hs | bsd-3-clause | 116 | 0 | 4 | 18 | 23 | 17 | 6 | 3 | 0 |
{-# LANGUAGE OverloadedStrings #-}
import System.Keeper
import Database.Persist
import Data.Int
import qualified Data.ByteString.Char8 as BS
import Options.Applicative
import System.Posix.Env.ByteString
data Command = CmdCreate
| CmdAdd String String
| CmdClear String
| CmdDel String
| CmdShow (Maybe String)
cmdCreate :: Parser Command
cmdCreate = pure CmdCreate
cmdAdd :: Parser Command
cmdAdd = CmdAdd <$> (argument str (metavar "name")) <*> (argument str (metavar "key"))
cmdClear :: Parser Command
cmdClear = CmdClear <$> (argument str (metavar "name"))
cmdDel :: Parser Command
cmdDel = CmdDel <$> (argument str (metavar "identifier"))
cmdShow :: Parser Command
cmdShow = CmdShow <$> optional (argument str (metavar "name"))
sample :: Parser Command
sample = subparser
( command "init" (info cmdCreate
( progDesc "initialize the authorized keys base"))
<> command "add" (info cmdAdd
( progDesc "add a new entry"))
<> command "clear" (info cmdClear
( progDesc "delete all entries"))
<> command "del" (info cmdDel
( progDesc "delete a specific entry"))
<> command "show" (info cmdShow
( progDesc "show the content of the authorized keys base"))
)
version :: Parser (a -> a)
version = infoOption ("Keeper, version: " ++ (show keeperVersion))
( long "version"
<> short 'v'
<> help "print current Keeper's version")
doInsertionKey home name key = do
entEither <- insertKeeperKey home name key
False Nothing Nothing Nothing
False False False False False
Nothing Nothing Nothing
case entEither of
(Right _) -> putStrLn "key added"
(Left _) -> error "key already presents in the database"
doListKeys home = do
listRes <- selectAuthorizedKeys home
Prelude.mapM_ showKeyOf listRes
where
showKeyOf ent =
let val = entityVal ent
keyId = unKey $ entityKey ent
in putStrLn $ "id(" ++ (show keyId) ++ ") "
++ "user(" ++ (BS.unpack $ keeperKeyName val) ++ ") "
++ "key(" ++ (BS.unpack $ keeperKeyPubKey val) ++ ")"
doListKeysOf home name = do
listRes <- selectAuthorizedKeysOf home name
Prelude.mapM_ showKeyOf listRes
where
showKeyOf ent =
let val = entityVal ent
keyId = unKey $ entityKey ent
in putStrLn $ "id(" ++ (show keyId) ++ ") "
++ "user(" ++ (BS.unpack $ keeperKeyName val) ++ ") "
++ "key(" ++ (BS.unpack $ keeperKeyPubKey val) ++ ")"
dispatchOptions :: BS.ByteString -> Command -> IO ()
dispatchOptions home (CmdCreate) = createKeeperTable home
dispatchOptions home (CmdAdd name key) = doInsertionKey home (BS.pack name) (BS.pack key)
dispatchOptions home (CmdClear name) = deleteKeeperKeys home (BS.pack name)
dispatchOptions home (CmdDel kid) = deleteKeeperKey home (Key $ toPersistValue (read kid :: Int64))
dispatchOptions home (CmdShow Nothing) = doListKeys home
dispatchOptions home (CmdShow (Just name)) = doListKeysOf home (BS.pack name)
main = do
env <- getEnv "HOME"
case env of
Nothing -> error "can't find environment variable HOME"
Just home -> execParser opts >>= dispatchOptions home
where
opts = info (helper <*> version <*> sample)
( fullDesc
<> progDesc "This is the default Command Line Interface for Keeper"
<> header ("Command Line Interface for Keeper\n" ++
"Keeper is a SSH Keys Database manager" ))
| NicolasDP/keeper | Keeper/KeeperDB.hs | bsd-3-clause | 3,690 | 0 | 18 | 1,041 | 1,070 | 530 | 540 | 82 | 2 |
{-# LANGUAGE OverloadedStrings #-}
-- | Bootstrap layout elements. See
-- <http://getbootstrap.com/2.3.2/scaffolding.html> for more
-- information.
module Blaze.Bootstrap
(
-- * Containers
container
,containerFluid
-- * Rows
,row
,rowFluid
-- * Spans
,span1
,span2
,span3
,span4
,span5
,span6
,span7
,span8
,span9
,span10
,span11
,span12
)
where
import Prelude hiding (div)
import Blaze.Html5
-- | A grid container.
container :: Html -> Html
container x = div !. "container" $ x
-- | A fluid grid container.
containerFluid :: Html -> Html
containerFluid x = div !. "container-fluid" $ x
-- | A grid row.
row :: Html -> Html
row x = div !. "row" $ x
-- | A fluid grid row.
rowFluid :: Html -> Html
rowFluid x = div !. "row-fluid" $ x
-- | A span of 1 columns.
span1 :: Html -> Html
span1 x = div !. "span1" $ x
-- | A span of 2 columns.
span2 :: Html -> Html
span2 x = div !. "span2" $ x
-- | A span of 3 columns.
span3 :: Html -> Html
span3 x = div !. "span3" $ x
-- | A span of 4 columns.
span4 :: Html -> Html
span4 x = div !. "span4" $ x
-- | A span of 5 columns.
span5 :: Html -> Html
span5 x = div !. "span5" $ x
-- | A span of 6 columns.
span6 :: Html -> Html
span6 x = div !. "span6" $ x
-- | A span of 7 columns.
span7 :: Html -> Html
span7 x = div !. "span7" $ x
-- | A span of 8 columns.
span8 :: Html -> Html
span8 x = div !. "span8" $ x
-- | A span of 9 columns.
span9 :: Html -> Html
span9 x = div !. "span9" $ x
-- | A span of 10 columns.
span10 :: Html -> Html
span10 x = div !. "span10" $ x
-- | A span of 11 columns.
span11 :: Html -> Html
span11 x = div !. "span11" $ x
-- | A span of 12 columns.
span12 :: Html -> Html
span12 x = div !. "span12" $ x
| chrisdone/blaze | src/Blaze/Bootstrap.hs | bsd-3-clause | 1,713 | 0 | 6 | 410 | 493 | 277 | 216 | 53 | 1 |
module Rubik.Key where
class Ord k => Key k where
universe :: [k]
instance Key Bool where
universe = [False,True]
instance (Key a, Key b) => Key (a,b) where
universe = [ (a,b) | a <- universe, b <- universe ]
elems :: Key k => (k -> a) -> [a]
elems f = map f universe
toList :: Key k => (k -> a) -> [(k,a)]
toList f = [ (k,f k) | k <- universe ]
newtype Finite a b = Finite (a -> b)
instance (Show a, Key a, Show b) => Show (Finite a b) where
show (Finite f) = show [ (a,f a) | a <- universe ]
instance Functor (Finite a) where
fmap f (Finite g) = Finite (f . g) | andygill/rubik-solver | src/Rubik/Key.hs | bsd-3-clause | 591 | 0 | 9 | 155 | 338 | 182 | 156 | 16 | 1 |
--
-- EnglishTokenizer.hs
-- Copyright (C) 2017 jragonfyre <jragonfyre@jragonfyre>
--
-- Distributed under terms of the MIT license.
--
module English.Tokenizer where
-- (
-- ) where
import Text.Megaparsec
import Text.Megaparsec.String
import Text.Megaparsec.Char
import qualified Data.List.NonEmpty as NE
import Control.Monad (join)
import Control.Monad.Reader
-- takes a string representing a word and produces
-- a collection of dictionary entries corresponding to that
-- word.
type Dictionary a = String -> [a]
-- MASSIVE problem: currently no support for compound words. English is filled with these, like "pick up"
data EngToken a
= Word
{ pos :: SourcePos
, text :: String
, entries :: [a]
}
| Comma SourcePos
| Semicolon SourcePos
| Period SourcePos
| QuestionMark SourcePos
deriving (Show, Eq)--, Generic)
tokenText :: EngToken a -> String
tokenText w@(Word _ _ _) = text w
tokenText (Comma _) = ","
tokenText (Semicolon _) = ";"
tokenText (Period _) = "."
tokenText (QuestionMark _) = "?"
isWord :: EngToken a -> Bool
isWord (Word _ _ _) = True
isWord _ = False
tokenPos :: EngToken a -> SourcePos
tokenPos w@(Word _ _ _) = pos w
tokenPos (Comma p) = p
tokenPos (Semicolon p) = p
tokenPos (Period p) = p
tokenPos (QuestionMark p) = p
tokenEntries :: EngToken a -> [a]
tokenEntries w@(Word _ _ _) = entries w
tokenEntries _ = []
-- parses a word from the input
word :: (ErrorComponent e, Monad m) => ParsecT e String m (SourcePos, String)
word = do
st <- getParserState
res <- some (letterChar <|> (oneOf ("'-"::[Char])))
return (NE.head $ statePos st, res)
wordToken :: (ErrorComponent e) => ParsecT e String (Reader (Dictionary a)) (EngToken a)
wordToken = do
dict <- ask
fmap (\(pos, t) -> Word pos t (dict t)) word
punctuationToken :: (ErrorComponent e) => ParsecT e String (Reader (Dictionary a)) (EngToken a)
punctuationToken = do
st <- getParserState
ch <- oneOf (",;.?"::[Char]) <?> "punctuation"
let
tmap = if | ch == ',' -> Comma
| ch == ';' -> Semicolon
| ch == '.' -> Period
| ch == '?' -> QuestionMark
return . tmap . NE.head $ statePos st
tokenRec :: (ErrorComponent e) => ParsecT e String (Reader (Dictionary a)) (EngToken a)
tokenRec = wordToken <|> punctuationToken
tokenize :: (ErrorComponent e) => ParsecT e String (Reader (Dictionary a)) [EngToken a]
tokenize = fmap join $ sepBy (some tokenRec) (some spaceChar)
makeTokens :: Dictionary a -> String -> String -> Either (ParseError Char Dec) [EngToken a]
makeTokens dict srcname src = flip runReader dict $ runParserT tokenize srcname src
| jragonfyre/TRPG | src/English/Tokenizer.hs | bsd-3-clause | 2,636 | 0 | 14 | 539 | 941 | 495 | 446 | -1 | -1 |
module T296 where
import Data.Kind
import Data.Singletons.TH
$(singletons [d|
data MyProxy (a :: Type) = MyProxy
f :: forall a. MyProxy a -> MyProxy a
f MyProxy =
let x = let z :: MyProxy a
z = MyProxy in z
in x
|])
| goldfirere/singletons | singletons-base/tests/compile-and-dump/Singletons/T296.hs | bsd-3-clause | 251 | 0 | 7 | 79 | 29 | 18 | 11 | -1 | -1 |
-- | The Unparse type class and its 'ParseTree' instance, as well as some text manipulation.
module Language.GroteTrap.Unparse (
-- * Class Unparse
Unparse(..),
-- * Text utility functions
merge, over
) where
import Language.GroteTrap.Range
import Language.GroteTrap.ParseTree
------------------------------------
-- Class Unparse
------------------------------------
-- | Types that are unparsable. Unparsing is like prettyprinting, except that instead of pretty source the original source code is retrieved. This means unparsing is only possible for values that were the result of an earlier parse.
class Unparse p where
unparse :: p -> String
------------------------------------
-- instance Unparse ParseTree
------------------------------------
instance Unparse ParseTree where
unparse = foldParseTree $ ParseTreeAlg
( \pos name -> indent pos name )
( \pos value -> indent pos $ show value )
unparseUnary
unparseBinary
unparseNary
unparseCall
unparseParens
indent :: Pos -> String -> String
indent n s = replicate n ' ' ++ s
unparseUnary :: Range -> String -> String -> String
unparseUnary (begin, _) op sub = indent begin op `over` sub
unparseBinary :: Range -> String -> String -> String -> String
unparseBinary (begin, _) op left right = left `over` indent begin op `over` right
unparseNary :: [Range] -> String -> [String] -> String
unparseNary ranges op children = foldl over "" children `over` foldl over "" (map place ranges)
where place (begin, _) = indent begin op
unparseParens :: Range -> String -> String
unparseParens (begin, end) sub = indent begin "(" `over` sub `over` indent (end - 1) ")"
unparseCall = error "Whoops! Not implemented"
------------------------------------
-- Text utility functions
------------------------------------
-- | @over upper lower@ places @upper@ over @lower@. The resulting string has the same characters as @upper@ does, except where @upper@ contains spaces; at those positions, the character from @lower@ shows. If @lower@ is longer than @upper@, @upper@ is padded with enough spaces to show all rest of @lower@.
over :: String -> String -> String
over upper lower = take n $ zipWith f (pad upper) (pad lower)
where f ' ' b = b
f a _ = a
pad = (++ repeat ' ')
n = length upper `max` length lower
-- | Merge folds many strings 'over' each other.
merge :: [String] -> String
merge = foldr over ""
| MedeaMelana/GroteTrap | Language/GroteTrap/Unparse.hs | bsd-3-clause | 2,450 | 0 | 11 | 474 | 542 | 297 | 245 | 36 | 2 |
module Network.HTTP.Types.Request
( IsRequest(..)
, requestBodyConsumed
) where
------------------------------------------------------------------------------
import Control.Applicative
------------------------------------------------------------------------------
import qualified Data.ByteString as BS (ByteString)
import qualified Data.ByteString.Lazy as BL (ByteString, fromChunks)
import qualified Data.Conduit as C
import qualified Data.Conduit.List as C
import qualified Data.Text as TS (Text)
------------------------------------------------------------------------------
import Network.HTTP.Types
------------------------------------------------------------------------------
class IsRequest req where
requestMethod :: req -> Method
requestHeaders :: req -> RequestHeaders
requestQuery :: req -> Query
requestPath :: req -> [TS.Text]
requestBody :: req -> C.Source (C.ResourceT IO) BS.ByteString
requestBodyConsumed :: IsRequest req => req -> C.ResourceT IO BL.ByteString
requestBodyConsumed req = BL.fromChunks <$> (requestBody req C.$$ C.consume)
| Palmik/wai-sockjs | src/Network/HTTP/Types/Request.hs | bsd-3-clause | 1,137 | 0 | 11 | 175 | 224 | 134 | 90 | 18 | 1 |
{-# LANGUAGE FlexibleContexts #-}
-- | Variation of "Futhark.CodeGen.ImpCode" that contains the notion
-- of a kernel invocation.
module Futhark.CodeGen.ImpCode.Kernels
( Program
, Function
, FunctionT (Function)
, Code
, KernelCode
, HostOp (..)
, KernelOp (..)
, CallKernel (..)
, MapKernel (..)
, Kernel (..)
, LocalMemoryUse
, KernelUse (..)
, module Futhark.CodeGen.ImpCode
-- * Utility functions
, getKernels
)
where
import Control.Monad.Writer
import Data.List
import qualified Data.HashSet as HS
import Data.Traversable
import Prelude
import Futhark.CodeGen.ImpCode hiding (Function, Code)
import qualified Futhark.CodeGen.ImpCode as Imp
import Futhark.Representation.AST.Attributes.Names
import Futhark.Representation.AST.Pretty ()
import Futhark.Util.Pretty
type Program = Functions HostOp
type Function = Imp.Function HostOp
-- | Host-level code that can call kernels.
type Code = Imp.Code CallKernel
-- | Code inside a kernel.
type KernelCode = Imp.Code KernelOp
data HostOp = CallKernel CallKernel
| GetNumGroups VName
| GetGroupSize VName
deriving (Show)
data CallKernel = Map MapKernel
| AnyKernel Kernel
| MapTranspose PrimType VName Exp VName Exp Exp Exp Exp Exp Exp
deriving (Show)
-- | A generic kernel containing arbitrary kernel code.
data MapKernel = MapKernel { mapKernelThreadNum :: VName
-- ^ Binding position - also serves as a unique
-- name for the kernel.
, mapKernelBody :: Imp.Code KernelOp
, mapKernelUses :: [KernelUse]
, mapKernelNumGroups :: DimSize
, mapKernelGroupSize :: DimSize
, mapKernelSize :: Imp.Exp
-- ^ Do not actually execute threads past this.
}
deriving (Show)
data Kernel = Kernel
{ kernelBody :: Imp.Code KernelOp
, kernelLocalMemory :: [LocalMemoryUse]
-- ^ The local memory used by this kernel.
, kernelUses :: [KernelUse]
-- ^ The host variables referenced by the kernel.
, kernelNumGroups :: DimSize
, kernelGroupSize :: DimSize
, kernelName :: VName
-- ^ Unique name for the kernel.
, kernelDesc :: Maybe String
-- ^ An optional short descriptive name - should be
-- alphanumeric and without spaces.
}
deriving (Show)
-- ^ In-kernel name, per-workgroup size in bytes, and
-- alignment restriction.
type LocalMemoryUse = (VName, MemSize, PrimType)
data KernelUse = ScalarUse VName PrimType
| MemoryUse VName Imp.DimSize
deriving (Eq, Show)
getKernels :: Program -> [CallKernel]
getKernels = nubBy sameKernel . execWriter . traverse getFunKernels
where getFunKernels (CallKernel kernel) =
tell [kernel]
getFunKernels _ =
return ()
sameKernel (MapTranspose bt1 _ _ _ _ _ _ _ _ _) (MapTranspose bt2 _ _ _ _ _ _ _ _ _) =
bt1 == bt2
sameKernel _ _ = False
instance Pretty KernelUse where
ppr (ScalarUse name t) =
text "scalar_copy" <> parens (commasep [ppr name, ppr t])
ppr (MemoryUse name size) =
text "mem_copy" <> parens (commasep [ppr name, ppr size])
instance Pretty HostOp where
ppr (GetNumGroups dest) =
ppr dest <+> text "<-" <+>
text "get_num_groups()"
ppr (GetGroupSize dest) =
ppr dest <+> text "<-" <+>
text "get_group_size()"
ppr (CallKernel c) =
ppr c
instance Pretty CallKernel where
ppr (Map k) = ppr k
ppr (AnyKernel k) = ppr k
ppr (MapTranspose bt dest destoffset src srcoffset num_arrays size_x size_y in_size out_size) =
text "mapTranspose" <>
parens (ppr bt <> comma </>
ppMemLoc dest destoffset <> comma </>
ppMemLoc src srcoffset <> comma </>
ppr num_arrays <> comma <+>
ppr size_x <> comma <+>
ppr size_y <> comma <+>
ppr in_size <> comma <+>
ppr out_size)
where ppMemLoc base offset =
ppr base <+> text "+" <+> ppr offset
instance Pretty MapKernel where
ppr kernel =
text "mapKernel" <+> brace
(text "uses" <+> brace (commasep $ map ppr $ mapKernelUses kernel) </>
text "body" <+> brace (ppr (mapKernelThreadNum kernel) <+>
text "<- get_thread_number()" </>
ppr (mapKernelBody kernel)))
instance Pretty Kernel where
ppr kernel =
text "kernel" <+> brace
(text "groups" <+> brace (ppr $ kernelNumGroups kernel) </>
text "group_size" <+> brace (ppr $ kernelGroupSize kernel) </>
text "local_memory" <+> brace (commasep $
map ppLocalMemory $
kernelLocalMemory kernel) </>
text "uses" <+> brace (commasep $ map ppr $ kernelUses kernel) </>
text "body" <+> brace (ppr $ kernelBody kernel))
where ppLocalMemory (name, size, bt) =
ppr name <+> parens (ppr size <+> text "bytes" <> comma <+>
text "align to" <+> ppr bt)
instance FreeIn MapKernel where
freeIn kernel =
mapKernelThreadNum kernel `HS.delete` freeIn (mapKernelBody kernel)
data KernelOp = GetGroupId VName Int
| GetLocalId VName Int
| GetLocalSize VName Int
| GetGlobalSize VName Int
| GetGlobalId VName Int
| GetLockstepWidth VName
| Barrier
deriving (Show)
instance Pretty KernelOp where
ppr (GetGroupId dest i) =
ppr dest <+> text "<-" <+>
text "get_group_id" <> parens (ppr i)
ppr (GetLocalId dest i) =
ppr dest <+> text "<-" <+>
text "get_local_id" <> parens (ppr i)
ppr (GetLocalSize dest i) =
ppr dest <+> text "<-" <+>
text "get_local_size" <> parens (ppr i)
ppr (GetGlobalSize dest i) =
ppr dest <+> text "<-" <+>
text "get_global_size" <> parens (ppr i)
ppr (GetGlobalId dest i) =
ppr dest <+> text "<-" <+>
text "get_global_id" <> parens (ppr i)
ppr (GetLockstepWidth dest) =
ppr dest <+> text "<-" <+>
text "get_lockstep_width()"
ppr Barrier =
text "barrier()"
instance FreeIn KernelOp where
freeIn = const mempty
brace :: Doc -> Doc
brace body = text " {" </> indent 2 body </> text "}"
| mrakgr/futhark | src/Futhark/CodeGen/ImpCode/Kernels.hs | bsd-3-clause | 6,568 | 0 | 23 | 2,078 | 1,732 | 898 | 834 | 155 | 3 |
-- | = Introduction
--
-- <<https://api.travis-ci.org/rzetterberg/orgmode-sql.svg Travis CI status>>
--
-- A library that facilitates import\/export orgmode data into\/out of SQL
-- databases, provide common queries and specialized summaries of the data.
--
-- Supports using MySQL, PostgreSQL or SQLite as storage backend.
--
-- == Importing, manipulating and exporting
--
-- Using this library you can grab one of your orgmode files and this library
-- will parse the file, create the database schema and import the data into the
-- database. You can then proceed to manipulate the data in the database and
-- when you are done you can use this library to export the data back to orgmode
-- plain text.
--
-- Since all data exists in a SQL database you could write custom SQL queries
-- that manipulate the data, or you could access the data in any other
-- programming language that has support for the chosen SQL database.
--
-- == Presenting data
--
-- This library also supplies different types of summaries that can be created
-- from parsed data.
--
-- For example if you want to show a summary of what time is
-- spent on, you can generate a 'ClockTable'.
--
-- Another example would be that you want to build a web site that can display
-- data as graphs using Javascript. Then you can use this library to produce
-- JSON output.
--
-- Maybe you want to create your own summaries and reports, then this library
-- can help you do that too.
module Database.OrgMode
( textImportDocument
, textExportDocument
) where
import Database.OrgMode.Import.Text (textImportDocument)
import Database.OrgMode.Export.Text (textExportDocument)
| rzetterberg/orgmode-sql | lib/Database/OrgMode.hs | bsd-3-clause | 1,681 | 0 | 5 | 316 | 73 | 60 | 13 | 5 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
{-|
Module: Graphics.Blank.Style
Copyright: (C) 2014-2015, The University of Kansas
License: BSD-style (see the file LICENSE)
Maintainer: Andy Gill
Stability: Beta
Portability: GHC
This module exposes overloaded versions of @blank-canvas@ functions that take a
style or color as an argument, which may be of interest if you desire stronger
type safety than @Text@ provides.
Note that this module exports function names that conflict with "Graphics.Blank".
Make sure to hide any functions from "Graphics.Blank" that you use from this
module.
-}
module Graphics.Blank.Style
( -- * Overloaded versions of 'Canvas' functions
strokeStyle
, fillStyle
, shadowColor
, addColorStop
, Style(..)
, CanvasColor
-- * 'CanvasColor' creation
, rgb
, rgbPercent
, rgba
, rgbaPercent
, hsl
, hsla
-- * @colour@ reexports
-- ** 'Colour' and 'AlphaColour'
, Colour
, AlphaColour
, transparent
, readColourName
-- ** CSS Level 1 colors
, aqua
, black
, blue
, fuchsia
, gray
, green
, lime
, maroon
, navy
, olive
, purple
, red
, silver
, teal
, white
, yellow
-- ** CSS Level 2 color
, orange
-- ** CSS Color Module Level 3 colors
, aliceblue
, antiquewhite
, aquamarine
, azure
, beige
, bisque
, blanchedalmond
, blueviolet
, brown
, burlywood
, cadetblue
, chartreuse
, chocolate
, coral
, cornflowerblue
, cornsilk
, crimson
, cyan
, darkblue
, darkcyan
, darkgoldenrod
, darkgray
, darkgreen
, darkgrey
, darkkhaki
, darkmagenta
, darkolivegreen
, darkorange
, darkorchid
, darkred
, darksalmon
, darkseagreen
, darkslateblue
, darkslategray
, darkslategrey
, darkturquoise
, darkviolet
, deeppink
, deepskyblue
, dimgray
, dimgrey
, dodgerblue
, firebrick
, floralwhite
, forestgreen
, gainsboro
, ghostwhite
, gold
, goldenrod
, grey
, greenyellow
, honeydew
, hotpink
, indianred
, indigo
, ivory
, khaki
, lavender
, lavenderblush
, lawngreen
, lemonchiffon
, lightblue
, lightcoral
, lightcyan
, lightgoldenrodyellow
, lightgray
, lightgreen
, lightgrey
, lightpink
, lightsalmon
, lightseagreen
, lightskyblue
, lightslategray
, lightslategrey
, lightsteelblue
, lightyellow
, limegreen
, linen
, magenta
, mediumaquamarine
, mediumblue
, mediumorchid
, mediumpurple
, mediumseagreen
, mediumslateblue
, mediumspringgreen
, mediumturquoise
, mediumvioletred
, midnightblue
, mintcream
, mistyrose
, moccasin
, navajowhite
, oldlace
, olivedrab
, orangered
, orchid
, palegoldenrod
, palegreen
, paleturquoise
, palevioletred
, papayawhip
, peachpuff
, peru
, pink
, plum
, powderblue
, rosybrown
, royalblue
, saddlebrown
, salmon
, sandybrown
, seagreen
, seashell
, sienna
, skyblue
, slateblue
, slategray
, slategrey
, snow
, springgreen
, steelblue
, tan
, thistle
, tomato
, turquoise
, violet
, wheat
, whitesmoke
, yellowgreen
-- ** CSS Color Module Level 4 color
, rebeccapurple
) where
import qualified Data.Colour as Colour
import Data.Colour hiding (black, transparent)
import qualified Data.Colour.Names as Names
import Data.Colour.RGBSpace
import qualified Data.Colour.RGBSpace.HSL as HSL
import Data.Colour.SRGB
import Data.Word
import Graphics.Blank.Canvas
import Graphics.Blank.Generated
import Graphics.Blank.JavaScript
import Graphics.Blank.Types
import Prelude.Compat hiding (tan)
-- | Specifies a 'Colour' by its red, green, and blue components, where each component
-- is an integer between 0 and 255.
rgb :: Word8 -> Word8 -> Word8 -> Colour Double
rgb = sRGB24
-- | Specifies a 'Colour' by its red, green, and blue components, where each component
-- is given by a percentage (which should be between 0% to 100%) of 255.
rgbPercent :: Percentage -> Percentage -> Percentage -> Colour Double
rgbPercent r g b = sRGB (r/100) (g/100) (b/100)
-- | Specifies an 'AlphaColour' by its RGB components and an alpha value.
--
-- @
-- 'rgba' r g b 0.0 = 'transparent'
-- @
rgba :: Word8 -> Word8 -> Word8 -> Alpha -> AlphaColour Double
rgba r g b = withOpacity $ rgb r g b
-- | Specifies an 'AlphaColour' by its RGB component percentages (which should be
-- between 0% and 100%) and an alpha value.
--
-- @
-- 'rgbaPercent' r g b 0.0 = 'transparent'
-- @
rgbaPercent :: Percentage -> Percentage -> Percentage -> Alpha -> AlphaColour Double
rgbaPercent r g b = withOpacity $ rgbPercent r g b
-- | Specifies a 'Colour' by its hue, saturation, and lightness value, where
-- saturation and lightness are percentages between 0% and 100%.
hsl :: Degrees -> Percentage -> Percentage -> Colour Double
hsl h s l = uncurryRGB sRGB $ HSL.hsl (realToFrac h) (s/100) (l/100)
-- |
-- Specifies an 'AlphaColour' by its HSL values and an alpha value.
--
-- @
-- 'hsla' h s v 0.0 = 'transparent'
-- @
hsla :: Degrees -> Percentage -> Percentage -> Alpha -> AlphaColour Double
hsla h s l = withOpacity $ hsl h s l
-- |
-- Takes a string naming a 'Colour' (must be all lowercase) and returns it. Fails if
-- the name is not recognized.
readColourName :: MonadFail m => String -> m (Colour Double)
readColourName "rebeccapurple" = return rebeccapurple
readColourName name = Names.readColourName name
-- | @#F0F8FF@, @rgb(240, 248, 255)@, @hsl(208, 100%, 97%)@
aliceblue :: Colour Double
aliceblue = Names.aliceblue
-- | @#FAEBD7@, @rgb(250, 235, 215)@, @hsl(34, 78%, 91%)@
antiquewhite :: Colour Double
antiquewhite = Names.antiquewhite
-- | @#00FFFF@, @rgb(0, 255, 255)@, @hsl(180, 100%, 50%)@. Same as 'cyan'.
aqua :: Colour Double
aqua = Names.aqua
-- | @#7FFFD4@, @rgb(127, 255, 212)@, @hsl(160, 100%, 75%)@
aquamarine :: Colour Double
aquamarine = Names.aquamarine
-- | @#F0FFFF@, @rgb(240, 255, 255)@, @hsl(180, 100%, 97%)@
azure :: Colour Double
azure = Names.azure
-- | @#F5F5DC@, @rgb(245, 245, 220)@, @hsl(60, 56%, 91%)@
beige :: Colour Double
beige = Names.beige
-- | @#FFE4C4@, @rgb(255, 228, 196)@, @hsl(33, 100%, 88%)@
bisque :: Colour Double
bisque = Names.bisque
-- | @#000000@, @rgb(0, 0, 0)@, @hsl(0, 0%, 0%)@
black :: Colour Double
black = Colour.black
-- | @#FFEBCD@, @rgb(255, 235, 205)@, @hsl(36, 100%, 90%)@
blanchedalmond :: Colour Double
blanchedalmond = Names.blanchedalmond
-- | @#0000FF@, @rgb(0, 0, 255)@, @hsl(240, 100%, 50%)@
blue :: Colour Double
blue = Names.blue
-- | @#8A2BE2@, @rgb(138, 43, 226)@, @hsl(271, 76%, 53%)@
blueviolet :: Colour Double
blueviolet = Names.blueviolet
-- | @#A52A2A@, @rgb(165, 42, 42)@, @hsl(0, 59%, 41%)@
brown :: Colour Double
brown = Names.brown
-- | @#DEB887@, @rgb(222, 184, 135)@, @hsl(34, 57%, 70%)@
burlywood :: Colour Double
burlywood = Names.burlywood
-- | @#5F9EA0@, @rgb(95, 158, 160)@, @hsl(182, 25%, 50%)@
cadetblue :: Colour Double
cadetblue = Names.cadetblue
-- | @#7FFF00@, @rgb(127, 255, 0)@, @hsl(90, 100%, 50%)@
chartreuse :: Colour Double
chartreuse = Names.chartreuse
-- | @#D2691E@, @rgb(210, 105, 30)@, @hsl(25, 75%, 47%)@
chocolate :: Colour Double
chocolate = Names.chocolate
-- | @#FF7F50@, @rgb(255, 127, 80)@, @hsl(16, 100%, 66%)@
coral :: Colour Double
coral = Names.coral
-- | @#6495ED@, @rgb(100, 149, 237)@, @hsl(219, 79%, 66%)@
cornflowerblue :: Colour Double
cornflowerblue = Names.cornflowerblue
-- | @#FFF8DC@, @rgb(255, 248, 220)@, @hsl(48, 100%, 93%)@
cornsilk :: Colour Double
cornsilk = Names.cornsilk
-- | @#DC143C@, @rgb(220, 20, 60)@, @hsl(348, 83%, 58%)@
crimson :: Colour Double
crimson = Names.crimson
-- | @#00FFFF@, @rgb(0, 255, 255)@, @hsl(180, 100%, 50%)@. Same as 'aqua'.
cyan :: Colour Double
cyan = Names.cyan
-- | @#00008B@, @rgb(0, 0, 139)@, @hsl(240, 100%, 27%)@
darkblue :: Colour Double
darkblue = Names.darkblue
-- | @#008B8B@, @rgb(0, 139, 139)@, @hsl(180, 100%, 27%)@
darkcyan :: Colour Double
darkcyan = Names.darkcyan
-- | @#B8860B@, @rgb(184, 134, 11)@, @hsl(43, 89%, 38%)@
darkgoldenrod :: Colour Double
darkgoldenrod = Names.darkgoldenrod
-- | @#A9A9A9@, @rgb(169, 169, 169)@, @hsl(0, 0%, 66%)@. Same as 'darkgrey'.
darkgray :: Colour Double
darkgray = Names.darkgray
-- | @#006400@, @rgb(0, 100, 0)@, @hsl(120, 100%, 20%)@
darkgreen :: Colour Double
darkgreen = Names.darkgreen
-- | @#A9A9A9@, @rgb(169, 169, 169)@, @hsl(0, 0%, 66%)@. Same as 'darkgray'.
darkgrey :: Colour Double
darkgrey = Names.darkgrey
-- | @#BDB76B@, @rgb(189, 183, 107)@, @hsl(56, 38%, 58%)@
darkkhaki :: Colour Double
darkkhaki = Names.darkkhaki
-- | @#8B008B@, @rgb(139, 0, 139)@, @hsl(300, 100%, 27%)@
darkmagenta :: Colour Double
darkmagenta = Names.darkmagenta
-- | @#556B2F@, @rgb(85, 107, 47)@, @hsl(82, 39%, 30%)@
darkolivegreen :: Colour Double
darkolivegreen = Names.darkolivegreen
-- | @#FF8C00@, @rgb(255, 140, 0)@, @hsl(33, 100%, 50%)@
darkorange :: Colour Double
darkorange = Names.darkorange
-- | @#9932CC@, @rgb(153, 50, 204)@, @hsl(280, 61%, 50%)@
darkorchid :: Colour Double
darkorchid = Names.darkorchid
-- | @#8B0000@, @rgb(139, 0, 0)@, @hsl(0, 100%, 27%)@
darkred :: Colour Double
darkred = Names.darkred
-- | @#E9967A@, @rgb(233, 150, 122)@, @hsl(15, 72%, 70%)@
darksalmon :: Colour Double
darksalmon = Names.darksalmon
-- | @#8FBC8F@, @rgb(143, 188, 143)@, @hsl(120, 25%, 65%)@
darkseagreen :: Colour Double
darkseagreen = Names.darkseagreen
-- | @#483D8B@, @rgb(72, 61, 139)@, @hsl(248, 39%, 39%)@
darkslateblue :: Colour Double
darkslateblue = Names.darkslateblue
-- | @#2F4F4F@, @rgb(47, 79, 79)@, @hsl(180, 25%, 25%)@. Same as 'darkslategrey'.
darkslategray :: Colour Double
darkslategray = Names.darkslategray
-- | @#2F4F4F@, @rgb(47, 79, 79)@, @hsl(180, 25%, 25%)@. Same as 'darkslategray'.
darkslategrey :: Colour Double
darkslategrey = Names.darkslategrey
-- | @#00CED1@, @rgb(0, 206, 209)@, @hsl(181, 100%, 41%)@
darkturquoise :: Colour Double
darkturquoise = Names.darkturquoise
-- | @#9400D3@, @rgb(148, 0, 211)@, @hsl(282, 100%, 41%)@
darkviolet :: Colour Double
darkviolet = Names.darkviolet
-- | @#FF1493@, @rgb(255, 20, 147)@, @hsl(328, 100%, 54%)@
deeppink :: Colour Double
deeppink = Names.deeppink
-- | @#00BFFF@, @rgb(0, 191, 255)@, @hsl(195, 100%, 50%)@
deepskyblue :: Colour Double
deepskyblue = Names.deepskyblue
-- | @#696969@, @rgb(105, 105, 105)@, @hsl(0, 0%, 41%)@. Same as 'darkgrey'.
dimgray :: Colour Double
dimgray = Names.dimgray
-- | @#696969@, @rgb(105, 105, 105)@, @hsl(0, 0%, 41%)@. Same as 'darkgray'.
dimgrey :: Colour Double
dimgrey = Names.dimgrey
-- | @#1E90FF@, @rgb(30, 144, 255)@, @hsl(210, 100%, 56%)@
dodgerblue :: Colour Double
dodgerblue = Names.dodgerblue
-- | @#B22222@, @rgb(178, 34, 34)@, @hsl(0, 68%, 42%)@
firebrick :: Colour Double
firebrick = Names.firebrick
-- | @#FFFAF0@, @rgb(255, 250, 240)@, @hsl(40, 100%, 97%)@
floralwhite :: Colour Double
floralwhite = Names.floralwhite
-- | @#228B22@, @rgb(34, 139, 34)@, @hsl(120, 61%, 34%)@
forestgreen :: Colour Double
forestgreen = Names.forestgreen
-- | @#FF00FF@, @rgb(255, 0, 255)@, @hsl(300, 100%, 50%)@. Same as 'magenta'.
fuchsia :: Colour Double
fuchsia = Names.fuchsia
-- | @#DCDCDC@, @rgb(220, 220, 220)@, @hsl(0, 0%, 86%)@
gainsboro :: Colour Double
gainsboro = Names.gainsboro
-- | @#F8F8FF@, @rgb(248, 248, 255)@, @hsl(240, 100%, 99%)@
ghostwhite :: Colour Double
ghostwhite = Names.ghostwhite
-- | @#FFD700@, @rgb(255, 215, 0)@, @hsl(51, 100%, 50%)@
gold :: Colour Double
gold = Names.gold
-- | @#DAA520@, @rgb(218, 165, 32)@, @hsl(43, 74%, 49%)@
goldenrod :: Colour Double
goldenrod = Names.goldenrod
-- | @#808080@, @rgb(128, 128, 128)@, @hsl(0, 0%, 50%)@. Same as 'grey'.
gray :: Colour Double
gray = Names.gray
-- | @#008000@, @rgb(0, 128, 0)@, @hsl(120, 100%, 25%)@
green :: Colour Double
green = Names.green
-- | @#808080@, @rgb(128, 128, 128)@, @hsl(0, 0%, 50%)@. Same as 'gray'.
grey :: Colour Double
grey = Names.grey
-- | @#ADFF2F@, @rgb(173, 255, 47)@, @hsl(84, 100%, 59%)@
greenyellow :: Colour Double
greenyellow = Names.greenyellow
-- | @#F0FFF0@, @rgb(240, 255, 240)@, @hsl(120, 100%, 97%)@
honeydew :: Colour Double
honeydew = Names.honeydew
-- | @#FF69B4@, @rgb(255, 105, 180)@, @hsl(330, 100%, 71%)@
hotpink :: Colour Double
hotpink = Names.hotpink
-- | @#CD5C5C@, @rgb(205, 92, 92)@, @hsl(0, 53%, 58%)@
indianred :: Colour Double
indianred = Names.indianred
-- | @#4B0082@, @rgb(75, 0, 130)@, @hsl(275, 100%, 25%)@
indigo :: Colour Double
indigo = Names.indigo
-- | @#FFFFF0@, @rgb(255, 255, 240)@, @hsl(60, 100%, 97%)@
ivory :: Colour Double
ivory = Names.ivory
-- | @#F0E68C@, @rgb(240, 230, 140)@, @hsl(54, 77%, 75%)@
khaki :: Colour Double
khaki = Names.khaki
-- | @#E6E6FA@, @rgb(230, 230, 250)@, @hsl(240, 67%, 94%)@
lavender :: Colour Double
lavender = Names.lavender
-- | @#FFF0F5@, @rgb(255, 240, 245)@, @hsl(340, 100%, 97%)@
lavenderblush :: Colour Double
lavenderblush = Names.lavenderblush
-- | @#7CFC00@, @rgb(124, 252, 0)@, @hsl(90, 100%, 49%)@
lawngreen :: Colour Double
lawngreen = Names.lawngreen
-- | @#FFFACD@, @rgb(255, 250, 205)@, @hsl(54, 100%, 90%)@
lemonchiffon :: Colour Double
lemonchiffon = Names.lemonchiffon
-- | @#ADD8E6@, @rgb(173, 216, 230)@, @hsl(195, 53%, 79%)@
lightblue :: Colour Double
lightblue = Names.lightblue
-- | @#F08080@, @rgb(240, 128, 128)@, @hsl(0, 79%, 72%)@
lightcoral :: Colour Double
lightcoral = Names.lightcoral
-- | @#E0FFFF@, @rgb(224, 255, 255)@, @hsl(180, 100%, 94%)@
lightcyan :: Colour Double
lightcyan = Names.lightcyan
-- | @#FAFAD2@, @rgb(250, 250, 210)@, @hsl(60, 80%, 90%)@
lightgoldenrodyellow :: Colour Double
lightgoldenrodyellow = Names.lightgoldenrodyellow
-- | @#D3D3D3@, @rgb(211, 211, 211)@, @hsl(0, 0%, 83%)@. Same as 'lightgrey'.
lightgray :: Colour Double
lightgray = Names.lightgray
-- | @#90EE90@, @rgb(144, 238, 144)@, @hsl(120, 73%, 75%)@
lightgreen :: Colour Double
lightgreen = Names.lightgreen
-- | @#D3D3D3@, @rgb(211, 211, 211)@, @hsl(0, 0%, 83%)@. Same as 'lightgray'.
lightgrey :: Colour Double
lightgrey = Names.lightgrey
-- | @#FFB6C1@, @rgb(255, 182, 193)@, @hsl(351, 100%, 86%)@
lightpink :: Colour Double
lightpink = Names.lightpink
-- | @#FFA07A@, @rgb(255, 160, 122)@, @hsl(17, 100%, 74%)@
lightsalmon :: Colour Double
lightsalmon = Names.lightsalmon
-- | @#20B2AA@, @rgb(32, 178, 170)@, @hsl(177, 70%, 41%)@
lightseagreen :: Colour Double
lightseagreen = Names.lightseagreen
-- | @#87CEFA@, @rgb(135, 206, 250)@, @hsl(203, 92%, 75%)@
lightskyblue :: Colour Double
lightskyblue = Names.lightskyblue
-- | @#778899@, @rgb(119, 136, 153)@, @hsl(210, 14%, 53%)@. Same as 'lightslategrey'.
lightslategray :: Colour Double
lightslategray = Names.lightslategray
-- | @#778899@, @rgb(119, 136, 153)@, @hsl(210, 14%, 53%)@. Same as 'lightslategray'.
lightslategrey :: Colour Double
lightslategrey = Names.lightslategrey
-- | @#B0C4DE@, @rgb(176, 196, 222)@, @hsl(214, 41%, 78%)@
lightsteelblue :: Colour Double
lightsteelblue = Names.lightsteelblue
-- | @#FFFFE0@, @rgb(255, 255, 224)@, @hsl(60, 100%, 94%)@
lightyellow :: Colour Double
lightyellow = Names.lightyellow
-- | @#00FF00@, @rgb(0, 255, 0)@, @hsl(120, 100%, 50%)@
lime :: Colour Double
lime = Names.lime
-- | @#32CD32@, @rgb(50, 205, 50)@, @hsl(120, 61%, 50%)@
limegreen :: Colour Double
limegreen = Names.limegreen
-- | @#FAF0E6@, @rgb(250, 240, 230)@, @hsl(30, 67%, 94%)@
linen :: Colour Double
linen = Names.linen
-- | @#FF00FF@, @rgb(255, 0, 255)@, @hsl(300, 100%, 50%)@. Same as 'fuchsia'.
magenta :: Colour Double
magenta = Names.magenta
-- | @#800000@, @rgb(128, 0, 0)@, @hsl(0, 100%, 25%)@
maroon :: Colour Double
maroon = Names.maroon
-- | @#66CDAA@, @rgb(102, 205, 170)@, @hsl(160, 51%, 60%)@
mediumaquamarine :: Colour Double
mediumaquamarine = Names.mediumaquamarine
-- | @#0000CD@, @rgb(0, 0, 205)@, @hsl(240, 100%, 40%)@
mediumblue :: Colour Double
mediumblue = Names.mediumblue
-- | @#BA55D3@, @rgb(186, 85, 211)@, @hsl(288, 59%, 58%)@
mediumorchid :: Colour Double
mediumorchid = Names.mediumorchid
-- | @#9370DB@, @rgb(147, 112, 219)@, @hsl(260, 60%, 65%)@
mediumpurple :: Colour Double
mediumpurple = Names.mediumpurple
-- | @#3CB371@, @rgb(60, 179, 113)@, @hsl(147, 50%, 47%)@
mediumseagreen :: Colour Double
mediumseagreen = Names.mediumseagreen
-- | @#7B68EE@, @rgb(123, 104, 238)@, @hsl(249, 80%, 67%)@
mediumslateblue :: Colour Double
mediumslateblue = Names.mediumslateblue
-- | @#00FA9A@, @rgb(0, 250, 154)@, @hsl(157, 100%, 49%)@
mediumspringgreen :: Colour Double
mediumspringgreen = Names.mediumspringgreen
-- | @#48D1CC@, @rgb(72, 209, 204)@, @hsl(178, 60%, 55%)@
mediumturquoise :: Colour Double
mediumturquoise = Names.turquoise
-- | @#C71585@, @rgb(199, 21, 133)@, @hsl(322, 81%, 43%)@
mediumvioletred :: Colour Double
mediumvioletred = Names.mediumvioletred
-- | @#191970@, @rgb(25, 25, 112)@, @hsl(240, 64%, 27%)@
midnightblue :: Colour Double
midnightblue = Names.midnightblue
-- | @#F5FFFA@, @rgb(245, 255, 250)@, @hsl(150, 100%, 98%)@
mintcream :: Colour Double
mintcream = Names.mintcream
-- | @#FFE4E1@, @rgb(255, 228, 225)@, @hsl(6, 100%, 94%)@
mistyrose :: Colour Double
mistyrose = Names.mistyrose
-- | @#FFE4B5@, @rgb(255, 228, 181)@, @hsl(38, 100%, 85%)@
moccasin :: Colour Double
moccasin = Names.moccasin
-- | @#FFDEAD@, @rgb(255, 222, 173)@, @hsl(36, 100%, 84%)@
navajowhite :: Colour Double
navajowhite = Names.navajowhite
-- | @#000080@, @rgb(0, 0, 128)@, @hsl(240, 100%, 25%)@
navy :: Colour Double
navy = Names.navy
-- | @#FDF5E6@, @rgb(253, 245, 230)@, @hsl(39, 85%, 95%)@
oldlace :: Colour Double
oldlace = Names.oldlace
-- | @#808000@, @rgb(128, 128, 0)@, @hsl(60, 100%, 25%)@
olive :: Colour Double
olive = Names.olive
-- | @#6B8E23@, @rgb(107, 142, 35)@, @hsl(80, 60%, 35%)@
olivedrab :: Colour Double
olivedrab = Names.olivedrab
-- | @#FFA500@, @rgb(255, 165, 0)@, @hsl(39, 100%, 50%)@
orange :: Colour Double
orange = Names.orange
-- | @#FF4500@, @rgb(255, 69, 0)@, @hsl(16, 100%, 50%)@
orangered :: Colour Double
orangered = Names.orangered
-- | @#DA70D6@, @rgb(218, 112, 214)@, @hsl(302, 59%, 65%)@
orchid :: Colour Double
orchid = Names.orchid
-- | @#EEE8AA@, @rgb(238, 232, 170)@, @hsl(55, 67%, 80%)@
palegoldenrod :: Colour Double
palegoldenrod = Names.palegoldenrod
-- | @#98FB98@, @rgb(152, 251, 152)@, @hsl(120, 93%, 79%)@
palegreen :: Colour Double
palegreen = Names.palegreen
-- | @#AFEEEE@, @rgb(175, 238, 238)@, @hsl(180, 65%, 81%)@
paleturquoise :: Colour Double
paleturquoise = Names.paleturquoise
-- | @#DB7093@, @rgb(219, 112, 147)@, @hsl(340, 60%, 65%)@
palevioletred :: Colour Double
palevioletred = Names.palevioletred
-- | @#FFEFD5@, @rgb(255, 239, 213)@, @hsl(37, 100%, 92%)@
papayawhip :: Colour Double
papayawhip = Names.papayawhip
-- | @#FFDAB9@, @rgb(255, 218, 185)@, @hsl(28, 100%, 86%)@
peachpuff :: Colour Double
peachpuff = Names.peachpuff
-- | @#CD853F@, @rgb(205, 133, 63)@, @hsl(30, 59%, 53%)@
peru :: Colour Double
peru = Names.peru
-- | @#FFC0CB@, @rgb(255, 192, 203)@, @hsl(350, 100%, 88%)@
pink :: Colour Double
pink = Names.pink
-- | @#DDA0DD@, @rgb(221, 160, 221)@, @hsl(300, 47%, 75%)@
plum :: Colour Double
plum = Names.plum
-- | @#B0E0E6@, @rgb(176, 224, 230)@, @hsl(187, 52%, 80%)@
powderblue :: Colour Double
powderblue = Names.powderblue
-- | @#800080@, @rgb(128, 0, 128)@, @hsl(300, 100%, 25%)@
purple :: Colour Double
purple = Names.purple
-- | @#FF0000@, @rgb(255, 0, 0)@, @hsl(0, 100%, 50%)@
red :: Colour Double
red = Names.red
-- | @#BC8F8F@, @rgb(188, 143, 143)@, @hsl(0, 25%, 65%)@
rosybrown :: Colour Double
rosybrown = Names.rosybrown
-- | @#4169E1@, @rgb(65, 105, 225)@, @hsl(225, 73%, 57%)@
royalblue :: Colour Double
royalblue = Names.royalblue
-- | @#8B4513@, @rgb(139, 69, 19)@, @hsl(25, 76%, 31%)@
saddlebrown :: Colour Double
saddlebrown = Names.saddlebrown
-- | @#FA8072@, @rgb(250, 128, 114)@, @hsl(6, 93%, 71%)@
salmon :: Colour Double
salmon = Names.salmon
-- | @#F4A460@, @rgb(244, 164, 96)@, @hsl(28, 87%, 67%)@
sandybrown :: Colour Double
sandybrown = Names.sandybrown
-- | @#2E8B57@, @rgb(46, 139, 87)@, @hsl(146, 50%, 36%)@
seagreen :: Colour Double
seagreen = Names.seagreen
-- | @#FFF5EE@, @rgb(255, 245, 238)@, @hsl(25, 100%, 97%)@
seashell :: Colour Double
seashell = Names.seashell
-- | @#A0522D@, @rgb(160, 82, 45)@, @hsl(19, 56%, 40%)@
sienna :: Colour Double
sienna = Names.sienna
-- | @#C0C0C0@, @rgb(192, 192, 192)@, @hsl(0, 0%, 75%)@
silver :: Colour Double
silver = Names.silver
-- | @#87CEEB@, @rgb(135, 206, 235)@, @hsl(197, 71%, 73%)@
skyblue :: Colour Double
skyblue = Names.skyblue
-- | @#6A5ACD@, @rgb(106, 90, 205)@, @hsl(248, 53%, 58%)@
slateblue :: Colour Double
slateblue = Names.slateblue
-- | @#708090@, @rgb(112, 128, 144)@, @hsl(210, 13%, 50%)@. Same as 'slategrey'.
slategray :: Colour Double
slategray = Names.slategray
-- | @#708090@, @rgb(112, 128, 144)@, @hsl(210, 13%, 50%)@. Same as 'slategray'.
slategrey :: Colour Double
slategrey = Names.slategrey
-- | @#FFFAFA@, @rgb(255, 250, 250)@, @hsl(0, 100%, 99%)@
snow :: Colour Double
snow = Names.snow
-- | @#00FF7F@, @rgb(0, 255, 127)@, @hsl(150, 100%, 50%)@
springgreen :: Colour Double
springgreen = Names.springgreen
-- | @#4682B4@, @rgb(70, 130, 180)@, @hsl(207, 44%, 49%)@
steelblue :: Colour Double
steelblue = Names.steelblue
-- | @#D2B48C@, @rgb(210, 180, 140)@, @hsl(34, 44%, 69%)@
tan :: Colour Double
tan = Names.tan
-- | @#008080@, @rgb(0, 128, 128)@, @hsl(180, 100%, 25%)@
teal :: Colour Double
teal = Names.teal
-- | @#D8BFD8@, @rgb(216, 191, 216)@, @hsl(300, 24%, 80%)@
thistle :: Colour Double
thistle = Names.thistle
-- | @#FF6347@, @rgb(255, 99, 71)@, @hsl(9, 100%, 64%)@
tomato :: Colour Double
tomato = Names.tomato
-- | @#40E0D0@, @rgb(64, 224, 208)@, @hsl(174, 72%, 56%)@
turquoise :: Colour Double
turquoise = Names.turquoise
-- | @#EE82EE@, @rgb(238, 130, 238)@, @hsl(300, 76%, 72%)@
violet :: Colour Double
violet = Names.violet
-- | @#F5DEB3@, @rgb(245, 222, 179)@, @hsl(39, 77%, 83%)@
wheat :: Colour Double
wheat = Names.wheat
-- | @#FFFFFF@, @rgb(255, 255, 255)@, @hsl(0, 100%, 100%)@
white :: Colour Double
white = Names.white
-- | @#F5F5F5@, @rgb(245, 245, 245)@, @hsl(0, 0%, 96%)@
whitesmoke :: Colour Double
whitesmoke = Names.whitesmoke
-- | @#FFFF00@, @rgb(255, 255, 0)@, @hsl(60, 100%, 50%)@
yellow :: Colour Double
yellow = Names.yellow
-- | @#9ACD32@, @rgb(154, 205, 50)@, @hsl(80, 61%, 50%)@
yellowgreen :: Colour Double
yellowgreen = Names.yellowgreen
-- | @#663399@, @rgb(102, 51, 153)@, @hsl(270, 50%, 40%)@
rebeccapurple :: Colour Double
rebeccapurple = sRGB24 102 51 153
-- |
-- This 'AlphaColour' is entirely transparent and has no associated
-- color channel (i.e., @rgba(0, 0, 0, 0.0)@ or @hsla(0, 0%, 0%, 0.0)@).
transparent :: AlphaColour Double
transparent = Colour.transparent
| ku-fpg/blank-canvas | Graphics/Blank/Style.hs | bsd-3-clause | 23,250 | 0 | 9 | 4,276 | 3,368 | 1,952 | 1,416 | 492 | 1 |
module Main where
import Divisors (isPrime)
import Data.List (inits,tails)
primes = filter isPrime [10..]
isFunnyPrime p = all isPrime $ map read $ filter (/="") $ inits (show p) ++ tails (show p)
main :: IO ()
main = print $ sum $ take 11 $ filter isFunnyPrime [10..]
| stulli/projectEuler | eu37.hs | bsd-3-clause | 273 | 0 | 9 | 53 | 131 | 68 | 63 | 7 | 1 |
-- | Some utility functions for using hxt picklers.
module Text.Xml.Pickle
( toXML
, fromXML
, maybeFromXML
, eitherFromXML
) where
import Control.Monad.Identity
import Control.Category
import Prelude hiding ((.))
import Text.XML.HXT.Core
-- | Convert a value to an XML string.
toXML :: XmlPickler p => p -> String
toXML = showPickled []
-- | Parse a string containing xml to a value. On parse failure, will
-- call `error`.
fromXML :: XmlPickler a => String -> a
fromXML = runIdentity . fromXMLM
-- | Parse a string containing xml to a value, or `Nothing` if the
-- parse fails.
maybeFromXML :: XmlPickler a => String -> Maybe a
maybeFromXML = fromXMLM
-- | Parse a string containing xml to a value, or an error message on
-- failure.
eitherFromXML :: XmlPickler a => String -> Either String a
eitherFromXML text =
case runLA (removeAllWhiteSpace . xread) text of
[] -> Left "Failed to parse XML in eitherFromXML."
[x] -> unpickleDoc' xpickle x
(_:_) -> Left "Multiple parses in eitherFromXML."
fromXMLM :: (Monad m, XmlPickler a) => String -> m a
fromXMLM text = case runLA (removeAllWhiteSpace . xread) text of
[] -> fail "Failed to parse XML in fromXMLM."
[x] -> either fail return $ unpickleDoc' xpickle x
(_:_) -> fail "Multiple parses in fromXMLM."
| silkapp/hxt-pickle-utils | src/Text/Xml/Pickle.hs | bsd-3-clause | 1,302 | 0 | 9 | 261 | 320 | 172 | 148 | 26 | 3 |
{-# LANGUAGE LambdaCase #-}
module Cardano.Wallet.WalletLayer.Kernel.Transactions (
getTransactions
, toTransaction
) where
import Universum
import Control.Monad.Except
import Formatting (build, sformat)
import GHC.TypeLits (symbolVal)
import Pos.Chain.Txp (TxId)
import Pos.Core (Address, Coin, SlotCount, SlotId, Timestamp,
decodeTextAddress, flattenSlotId, getBlockCount)
import Pos.Util.Wlog (Severity (..))
import Cardano.Wallet.API.Indices
import Cardano.Wallet.API.Request
import qualified Cardano.Wallet.API.Request.Filter as F
import Cardano.Wallet.API.Request.Pagination
import qualified Cardano.Wallet.API.Request.Sort as S
import Cardano.Wallet.API.Response
import Cardano.Wallet.API.V1.Types (V1 (..), unV1)
import qualified Cardano.Wallet.API.V1.Types as V1
import qualified Cardano.Wallet.Kernel.DB.HdWallet as HD
import Cardano.Wallet.Kernel.DB.InDb (InDb (..))
import Cardano.Wallet.Kernel.DB.TxMeta (TxMeta (..))
import qualified Cardano.Wallet.Kernel.DB.TxMeta as TxMeta
import qualified Cardano.Wallet.Kernel.Internal as Kernel
import qualified Cardano.Wallet.Kernel.NodeStateAdaptor as Node
import qualified Cardano.Wallet.Kernel.Read as Kernel
import Cardano.Wallet.WalletLayer (GetTxError (..))
import UTxO.Util (exceptT)
getTransactions :: MonadIO m
=> Kernel.PassiveWallet
-> Maybe V1.WalletId
-> Maybe V1.AccountIndex
-> Maybe (V1 Address)
-> RequestParams
-> FilterOperations '[V1 TxId, V1 Timestamp] V1.Transaction
-> SortOperations V1.Transaction
-> m (Either GetTxError (APIResponse [V1.Transaction]))
getTransactions wallet mbWalletId mbAccountIndex mbAddress params fop sop = liftIO $ runExceptT $ do
let PaginationParams{..} = rpPaginationParams params
let PerPage pp = ppPerPage
let Page cp = ppPage
(txs, total) <- go cp pp ([], Nothing)
return $ respond params txs total
where
-- NOTE: See cardano-wallet#141
--
-- We may end up with some inconsistent metadata in the store. When fetching
-- them all, instead of failing with a non very helpful 'WalletNotfound' or
-- 'AccountNotFound' error because one or more metadata in the list contains
-- unknown ids, we simply discard them from what we fetched and we fetch
-- another batch up until we have enough (== pp).
go cp pp (acc, total)
| length acc >= pp =
return $ (take pp acc, total)
| otherwise = do
accountFops <- castAccountFiltering mbWalletId mbAccountIndex
mbSorting <- castSorting sop
(metas, mbTotalEntries) <- liftIO $ TxMeta.getTxMetas
(wallet ^. Kernel.walletMeta)
(TxMeta.Offset . fromIntegral $ (cp - 1) * pp)
(TxMeta.Limit . fromIntegral $ pp)
accountFops
(unV1 <$> mbAddress)
(castFiltering $ mapIx unV1 <$> F.findMatchingFilterOp fop)
(castFiltering $ mapIx unV1 <$> F.findMatchingFilterOp fop)
mbSorting
db <- liftIO $ Kernel.getWalletSnapshot wallet
sc <- liftIO $ Node.getSlotCount (wallet ^. Kernel.walletNode)
currentSlot <- liftIO $ Node.getTipSlotId (wallet ^. Kernel.walletNode)
if null metas then
-- A bit artificial, but we force the termination and make sure
-- in the meantime that the algorithm only exits by one and only
-- one branch.
go cp (min pp $ length acc) (acc, total <|> mbTotalEntries)
else do
txs <- catMaybes <$> forM metas (\meta -> do
runExceptT (metaToTx db sc currentSlot meta) >>= \case
Left e -> do
let warn = lift . ((wallet ^. Kernel.walletLogMessage) Warning)
warn $ "Inconsistent entry in the metadata store: " <> sformat build e
return Nothing
Right tx ->
return (Just tx)
)
go (cp + 1) pp (acc ++ txs, total <|> mbTotalEntries)
toTransaction :: MonadIO m
=> Kernel.PassiveWallet
-> TxMeta
-> m (Either HD.UnknownHdAccount V1.Transaction)
toTransaction wallet meta = liftIO $ do
db <- liftIO $ Kernel.getWalletSnapshot wallet
sc <- liftIO $ Node.getSlotCount (wallet ^. Kernel.walletNode)
currentSlot <- Node.getTipSlotId (wallet ^. Kernel.walletNode)
return $ runExcept $ metaToTx db sc currentSlot meta
-- | Type Casting for Account filtering from V1 to MetaData Types.
castAccountFiltering :: Monad m => Maybe V1.WalletId -> Maybe V1.AccountIndex -> ExceptT GetTxError m TxMeta.AccountFops
castAccountFiltering mbWalletId mbAccountIndex =
case (mbWalletId, mbAccountIndex) of
(Nothing, Nothing) -> return TxMeta.Everything
(Nothing, Just _) -> throwError GetTxMissingWalletIdError
-- AccountIndex doesn`t uniquely identify an Account, so we shouldn`t continue without a WalletId.
(Just (V1.WalletId wId), _) ->
case decodeTextAddress wId of
Left _ -> throwError $ GetTxAddressDecodingFailed wId
Right rootAddr -> return $ TxMeta.AccountFops rootAddr (V1.getAccIndex <$> mbAccountIndex)
-- This function reads at most the head of the SortOperations and expects to find "created_at".
castSorting :: Monad m => S.SortOperations V1.Transaction -> ExceptT GetTxError m (Maybe TxMeta.Sorting)
castSorting S.NoSorts = return Nothing
castSorting (S.SortOp (sop :: S.SortOperation ix V1.Transaction) _) =
case symbolVal (Proxy @(IndexToQueryParam V1.Transaction ix)) of
"created_at" -> return $ Just $ TxMeta.Sorting TxMeta.SortByCreationAt (castSortingDirection sop)
txt -> throwError $ GetTxInvalidSortingOperation txt
castSortingDirection :: S.SortOperation ix a -> TxMeta.SortDirection
castSortingDirection (S.SortByIndex srt _) = case srt of
S.SortAscending -> TxMeta.Ascending
S.SortDescending -> TxMeta.Descending
castFiltering :: Maybe (F.FilterOperation ix V1.Transaction) -> TxMeta.FilterOperation ix
castFiltering mfop = case mfop of
Nothing -> TxMeta.NoFilterOp
Just fop -> case fop of
(F.FilterByIndex q) -> TxMeta.FilterByIndex q
(F.FilterByPredicate prd q) -> TxMeta.FilterByPredicate (castFilterOrd prd) q
(F.FilterByRange q w) -> TxMeta.FilterByRange q w
(F.FilterIn ls) -> TxMeta.FilterIn ls
castFilterOrd :: F.FilterOrdering -> TxMeta.FilterOrdering
castFilterOrd pr = case pr of
F.Equal -> TxMeta.Equal
F.GreaterThan -> TxMeta.GreaterThan
F.GreaterThanEqual -> TxMeta.GreaterThanEqual
F.LesserThan -> TxMeta.LesserThan
F.LesserThanEqual -> TxMeta.LesserThanEqual
metaToTx :: Monad m => Kernel.DB -> SlotCount -> SlotId -> TxMeta -> ExceptT HD.UnknownHdAccount m V1.Transaction
metaToTx db slotCount current TxMeta{..} = do
mSlotwithState <- withExceptT identity $ exceptT $
Kernel.currentTxSlotId db _txMetaId hdAccountId
isPending <- withExceptT identity $ exceptT $
Kernel.currentTxIsPending db _txMetaId hdAccountId
assuranceLevel <- withExceptT HD.embedUnknownHdRoot $ exceptT $
Kernel.rootAssuranceLevel db hdRootId
let (status, confirmations) = buildDynamicTxMeta assuranceLevel slotCount mSlotwithState current isPending
return V1.Transaction {
txId = V1 _txMetaId,
txConfirmations = fromIntegral confirmations,
txAmount = V1 _txMetaAmount,
txInputs = inputsToPayDistr <$> _txMetaInputs,
txOutputs = outputsToPayDistr <$> _txMetaOutputs,
txType = if _txMetaIsLocal then V1.LocalTransaction else V1.ForeignTransaction,
txDirection = if _txMetaIsOutgoing then V1.OutgoingTransaction else V1.IncomingTransaction,
txCreationTime = V1 _txMetaCreationAt,
txStatus = status
}
where
hdRootId = HD.HdRootId $ InDb _txMetaWalletId
hdAccountId = HD.HdAccountId hdRootId (HD.HdAccountIx _txMetaAccountIx)
inputsToPayDistr :: (a , b, Address, Coin) -> V1.PaymentDistribution
inputsToPayDistr (_, _, addr, c) = V1.PaymentDistribution (V1 addr) (V1 c)
outputsToPayDistr :: (Address, Coin) -> V1.PaymentDistribution
outputsToPayDistr (addr, c) = V1.PaymentDistribution (V1 addr) (V1 c)
buildDynamicTxMeta :: HD.AssuranceLevel -> SlotCount -> HD.CombinedWithAccountState (Maybe SlotId) -> SlotId -> Bool -> (V1.TransactionStatus, Word64)
buildDynamicTxMeta assuranceLevel slotCount mSlotwithState currentSlot isPending =
let currentSlot' = flattenSlotId slotCount currentSlot
goWithSlot confirmedIn =
let confirmedIn' = flattenSlotId slotCount confirmedIn
confirmations = currentSlot' - confirmedIn'
in case (confirmations < getBlockCount (HD.assuredBlockDepth assuranceLevel)) of
True -> (V1.InNewestBlocks, confirmations)
False -> (V1.Persisted, confirmations)
in case isPending of
True -> (V1.Applying, 0)
False ->
case mSlotwithState of
HD.UpToDate Nothing -> (V1.WontApply, 0)
HD.Incomplete Nothing -> (V1.Applying, 0) -- during restoration, we report txs not found yet as Applying.
HD.UpToDate (Just sl) -> goWithSlot sl
HD.Incomplete (Just sl) -> goWithSlot sl
-- | We don`t fitler in memory, so totalEntries is unknown, unless TxMeta Database counts them for us.
-- It is possible due to some error, to have length ls < Page.
-- This can happen when a Tx is found without Inputs.
respond :: RequestParams -> [a] -> Maybe Int -> (APIResponse [a])
respond RequestParams{..} ls mbTotalEntries =
let totalEntries = fromMaybe 0 mbTotalEntries
PaginationParams{..} = rpPaginationParams
perPage@(PerPage pp) = ppPerPage
currentPage = ppPage
totalPages = max 1 $ ceiling (fromIntegral totalEntries / (fromIntegral pp :: Double))
metadata = PaginationMetadata {
metaTotalPages = totalPages
, metaPage = currentPage
, metaPerPage = perPage
, metaTotalEntries = totalEntries
}
in APIResponse {
wrData = ls
, wrStatus = SuccessStatus
, wrMeta = Metadata metadata
}
| input-output-hk/pos-haskell-prototype | wallet/src/Cardano/Wallet/WalletLayer/Kernel/Transactions.hs | mit | 10,953 | 0 | 34 | 3,090 | 2,630 | 1,381 | 1,249 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : FuncTorrent.Peer
--
-- Module to handle operations with one peer.
--
-- Peer talks peer protocol with one remote peer and reports the availability of
-- blocks to the control thread via `availability` channel. Control thread can
-- schedule block downloads taking into consideration the state of all active
-- peers. Requests to fetch blocks arrive via the `reader` channel, and
-- retrieved blocks are written to `writer` channel. This module is stateless
-- and is perfectly safe to be killed anytime. The only requirement is to close
-- inbound channels, such that control threads cannot request for more downloads
-- after its shutdown.
--
-----------------------------------------------------------------------------
module FuncTorrent.Peer
(
Peer(..),
PeerMsg(..),
PeerState(..),
PeerThread(..),
PieceState(..),
initPeerThread,
-- Testing
handShake,
) where
import Prelude hiding (lookup, concat, replicate, splitAt)
import Control.Applicative (liftA3)
import Control.Concurrent
import Control.Exception.Base (bracket)
import Control.Monad (replicateM, liftM)
import Data.Binary (Binary(..), decode)
import Data.Binary.Get (getWord32be, getWord16be, getWord8, runGet)
import Data.Binary.Put (putWord32be, putWord16be, putWord8)
import Data.ByteString (ByteString, pack, unpack, concat, hGet, hPut, singleton)
import Data.ByteString.Lazy (fromStrict, fromChunks)
import Data.List (nub)
import Network (connectTo, PortID(..))
import System.IO
import System.Random (newStdGen, randomRs)
import qualified Data.ByteString.Char8 as BC (replicate, pack)
import FuncTorrent.Core (Block(..), Peer(..), PeerThread(..),
AvailabilityChannel, DataChannel)
data PeerState = PeerState {
handle :: Handle
, amChoking :: Bool
, amInterested :: Bool
, peerChoking :: Bool
, peerInterested :: Bool}
data PieceState = Pending
| InProgress
| Have
deriving (Show)
data PeerMsg = KeepAliveMsg
| ChokeMsg
| UnChokeMsg
| InterestedMsg
| NotInterestedMsg
| HaveMsg Integer
| BitFieldMsg ByteString
| RequestMsg Integer Integer Integer
| PieceMsg Integer Integer ByteString
| CancelMsg Integer Integer Integer
| PortMsg Integer
deriving (Show)
-- Peer thread implementation
-- | Spawns a new peer thread
--
-- Requests for fetching new blocks can be sent to the channel and those blocks
-- will be eventually written to the writer channel.
initPeerThread :: Peer -> AvailabilityChannel -> DataChannel -> IO (ThreadId, PeerThread)
initPeerThread p availChan dataChan = do
putStrLn $ "Spawning peer thread for " ++ show p
requestChan <- newChan :: IO (Chan Integer)
let pt = PeerThread p availChan requestChan dataChan
-- bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
tid <- forkIO $ bracket (initialize pt) cleanup action
return (tid, pt)
where
-- | Spawns two threads to talk peer protocol and download requested blocks
action :: PeerThread -> IO ()
action pt = do
_ <- forkIO $ loop pt
_ <- forkIO $ downloader pt
return ()
-- |Initialize module. Resources allocated here must be cleaned up in cleanup
initialize :: PeerThread -> IO PeerThread
initialize pt = putStrLn "Initializing peer" >> return pt
-- [todo] - Implement the peer protocol here
-- | Talks peer protocol to one peer
--
-- Reports the list of available pieces back to the control thread, which
-- eventually schedules the pieces to be downloaded depending on various
-- prioritization techniques.
loop :: PeerThread -> IO ()
loop pt@(PeerThread _ availabilityChan _ _) = do
-- Assume a torrent with 32 pieces and the remote peer has a few of them.
-- Report those to the control thread.
g <- newStdGen
let available = nub $ take 4 (randomRs (0, 31) g) :: [Integer]
mapM_ report available
where
report :: Integer -> IO ()
report block = writeChan availabilityChan (pt, block)
-- Drains the block request channel and writes contents to writer channel.
downloader :: PeerThread -> IO ()
downloader (PeerThread _ _ requestChan dataChan) = do
putStrLn "Draining reader"
requests <- getChanContents requestChan
mapM_ download requests
where
download :: Integer -> IO ()
download x = do
-- [todo] - Replace with real download implementation
-- | Download a piece and write to writer channel
putStrLn $ "Download block " ++ show x
threadDelay 1000000
writeChan dataChan $ Block x "hello world"
-- [todo] - Close the channel on shutdown.
--
-- The writer might be down and the channel will keep accepting more data,
-- leading to ugly hard to track down bugs.
--
-- | Called by bracket before the writer is shutdown
cleanup :: PeerThread -> IO ()
cleanup (PeerThread peer _ _ _) = putStrLn $ "Clean up peer thread for " ++ show peer
-- Protocol implementation
genHandShakeMsg :: ByteString -> String -> ByteString
genHandShakeMsg infoHash peer_id = concat [pstrlen, pstr, reserved, infoHash, peerID]
where pstrlen = singleton 19
pstr = BC.pack "BitTorrent protocol"
reserved = BC.replicate 8 '\0'
peerID = BC.pack peer_id
handShake :: Peer -> ByteString -> String -> IO Handle
handShake (Peer ip port) infoHash peerid = do
let hs = genHandShakeMsg infoHash peerid
h <- connectTo ip (PortNumber (fromIntegral port))
hSetBuffering h LineBuffering
hPut h hs
rlenBS <- hGet h (length (unpack hs))
putStrLn $ "got handshake from peer: " ++ show rlenBS
return h
instance Binary PeerMsg where
put msg = case msg of
KeepAliveMsg -> putWord32be 0
ChokeMsg -> do putWord32be 1
putWord8 0
UnChokeMsg -> do putWord32be 1
putWord8 1
InterestedMsg -> do putWord32be 1
putWord8 2
NotInterestedMsg -> do putWord32be 1
putWord8 3
HaveMsg i -> do putWord32be 5
putWord8 4
putWord32be (fromIntegral i)
BitFieldMsg bf -> do putWord32be $ fromIntegral (1 + bfListLen)
putWord8 5
mapM_ putWord8 bfList
where bfList = unpack bf
bfListLen = length bfList
RequestMsg i o l -> do putWord32be 13
putWord8 6
putWord32be (fromIntegral i)
putWord32be (fromIntegral o)
putWord32be (fromIntegral l)
PieceMsg i o b -> do putWord32be $ fromIntegral (9 + blocklen)
putWord8 7
putWord32be (fromIntegral i)
putWord32be (fromIntegral o)
mapM_ putWord8 blockList
where blockList = unpack b
blocklen = length blockList
CancelMsg i o l -> do putWord32be 13
putWord8 8
putWord32be (fromIntegral i)
putWord32be (fromIntegral o)
putWord32be (fromIntegral l)
PortMsg p -> do putWord32be 3
putWord8 9
putWord16be (fromIntegral p)
get = do
l <- getWord32be
msgid <- getWord8
case msgid of
0 -> return ChokeMsg
1 -> return UnChokeMsg
2 -> return InterestedMsg
3 -> return NotInterestedMsg
4 -> liftM (HaveMsg . fromIntegral) getWord32be
5 -> liftM (BitFieldMsg . pack) (replicateM (fromIntegral l - 1) getWord8)
6 -> liftA3 RequestMsg getInteger getInteger getInteger
where getInteger = fromIntegral <$> getWord32be
7 -> liftA3 PieceMsg getInteger getInteger (pack <$> replicateM (fromIntegral l - 9) getWord8)
where getInteger = fromIntegral <$> getWord32be
8 -> liftA3 CancelMsg getInteger getInteger getInteger
where getInteger = fromIntegral <$> getWord32be
9 -> liftM (PortMsg . fromIntegral) getWord16be
_ -> error ("unknown message ID: " ++ show msgid)
getMsg :: Handle -> IO PeerMsg
getMsg h = do
lBS <- hGet h 4
let l = bsToInt lBS
if l == 0
then return KeepAliveMsg
else do
putStrLn $ "len: " ++ show l
msgID <- hGet h 1
putStrLn $ "msg Type: " ++ show msgID
msg <- hGet h (l - 1)
return $ decode $ fromStrict $ concat [lBS, msgID, msg]
bsToInt :: ByteString -> Int
bsToInt x = fromIntegral (runGet getWord32be (fromChunks (return x)))
| bangalore-haskell-user-group/functorrent | src/FuncTorrent/Peer.hs | gpl-3.0 | 9,324 | 0 | 17 | 3,005 | 2,065 | 1,054 | 1,011 | 168 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
-- from https://ocharles.org.uk/blog/guest-posts/2014-12-20-scoped-type-variables.html
import qualified Data.Map as Map
insertMany :: forall k v . Ord k => (v -> v -> v) -> [(k,v)] -> Map.Map k v -> Map.Map k v
insertMany f vs m = foldr f1 m vs
where
f1 :: (k, v) -> Map.Map k v -> Map.Map k v
f1 (k,v) m = Map.insertWith f k v m
| mpickering/ghc-exactprint | tests/examples/ghc710/ScopedTypeVariables.hs | bsd-3-clause | 380 | 0 | 11 | 80 | 156 | 83 | 73 | 6 | 1 |
{-
(c) Bartosz Nitka, Facebook, 2015
UniqDFM: Specialised deterministic finite maps, for things with @Uniques@.
Basically, the things need to be in class @Uniquable@, and we use the
@getUnique@ method to grab their @Uniques@.
This is very similar to @UniqFM@, the major difference being that the order of
folding is not dependent on @Unique@ ordering, giving determinism.
Currently the ordering is determined by insertion order.
See Note [Unique Determinism] in Unique for explanation why @Unique@ ordering
is not deterministic.
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -Wall #-}
module ETA.Utils.UniqDFM (
-- * Unique-keyed deterministic mappings
UniqDFM, -- abstract type
-- ** Manipulating those mappings
emptyUDFM,
unitUDFM,
addToUDFM,
addToUDFM_C,
addListToUDFM,
delFromUDFM,
delListFromUDFM,
adjustUDFM,
alterUDFM,
mapUDFM,
plusUDFM,
plusUDFM_C,
lookupUDFM, lookupUDFM_Directly,
elemUDFM,
foldUDFM,
eltsUDFM,
filterUDFM, filterUDFM_Directly,
isNullUDFM,
sizeUDFM,
intersectUDFM, udfmIntersectUFM,
intersectsUDFM,
disjointUDFM, disjointUdfmUfm,
minusUDFM,
listToUDFM,
udfmMinusUFM,
partitionUDFM,
anyUDFM, allUDFM,
pprUDFM,
udfmToList,
udfmToUfm,
nonDetFoldUDFM,
alwaysUnsafeUfmToUdfm,
) where
import ETA.BasicTypes.Unique ( Uniquable(..), Unique, getKey )
import ETA.Utils.Outputable
import qualified Data.IntMap as M
import Data.Data
import Data.List (sortBy)
import Data.Function (on)
import ETA.Utils.UniqFM (UniqFM, listToUFM_Directly, nonDetUFMToList, ufmToIntMap)
-- Note [Deterministic UniqFM]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- A @UniqDFM@ is just like @UniqFM@ with the following additional
-- property: the function `udfmToList` returns the elements in some
-- deterministic order not depending on the Unique key for those elements.
--
-- If the client of the map performs operations on the map in deterministic
-- order then `udfmToList` returns them in deterministic order.
--
-- There is an implementation cost: each element is given a serial number
-- as it is added, and `udfmToList` sorts it's result by this serial
-- number. So you should only use `UniqDFM` if you need the deterministic
-- property.
--
-- `foldUDFM` also preserves determinism.
--
-- Normal @UniqFM@ when you turn it into a list will use
-- Data.IntMap.toList function that returns the elements in the order of
-- the keys. The keys in @UniqFM@ are always @Uniques@, so you end up with
-- with a list ordered by @Uniques@.
-- The order of @Uniques@ is known to be not stable across rebuilds.
-- See Note [Unique Determinism] in Unique.
--
--
-- There's more than one way to implement this. The implementation here tags
-- every value with the insertion time that can later be used to sort the
-- values when asked to convert to a list.
--
-- An alternative would be to have
--
-- data UniqDFM ele = UDFM (M.IntMap ele) [ele]
--
-- where the list determines the order. This makes deletion tricky as we'd
-- only accumulate elements in that list, but makes merging easier as you
-- can just merge both structures independently.
-- Deletion can probably be done in amortized fashion when the size of the
-- list is twice the size of the set.
-- | A type of values tagged with insertion time
data TaggedVal val =
TaggedVal
val
{-# UNPACK #-} !Int -- ^ insertion time
deriving Data
taggedFst :: TaggedVal val -> val
taggedFst (TaggedVal v _) = v
taggedSnd :: TaggedVal val -> Int
taggedSnd (TaggedVal _ i) = i
instance Eq val => Eq (TaggedVal val) where
(TaggedVal v1 _) == (TaggedVal v2 _) = v1 == v2
instance Functor TaggedVal where
fmap f (TaggedVal val i) = TaggedVal (f val) i
-- | Type of unique deterministic finite maps
data UniqDFM ele =
UDFM
!(M.IntMap (TaggedVal ele)) -- A map where keys are Unique's values and
-- values are tagged with insertion time.
-- The invariant is that all the tags will
-- be distinct within a single map
{-# UNPACK #-} !Int -- Upper bound on the values' insertion
-- time. See Note [Overflow on plusUDFM]
deriving (Data, Functor)
emptyUDFM :: UniqDFM elt
emptyUDFM = UDFM M.empty 0
unitUDFM :: Uniquable key => key -> elt -> UniqDFM elt
unitUDFM k v = UDFM (M.singleton (getKey $ getUnique k) (TaggedVal v 0)) 1
addToUDFM :: Uniquable key => UniqDFM elt -> key -> elt -> UniqDFM elt
addToUDFM m k v = addToUDFM_Directly m (getUnique k) v
addToUDFM_Directly :: UniqDFM elt -> Unique -> elt -> UniqDFM elt
addToUDFM_Directly (UDFM m i) u v
= UDFM (M.insertWith tf (getKey u) (TaggedVal v i) m) (i + 1)
where
tf (TaggedVal new_v _) (TaggedVal _ old_i) = TaggedVal new_v old_i
-- Keep the old tag, but insert the new value
-- This means that udfmToList typically returns elements
-- in the order of insertion, rather than the reverse
addToUDFM_Directly_C
:: (elt -> elt -> elt) -- old -> new -> result
-> UniqDFM elt
-> Unique -> elt
-> UniqDFM elt
addToUDFM_Directly_C f (UDFM m i) u v
= UDFM (M.insertWith tf (getKey u) (TaggedVal v i) m) (i + 1)
where
tf (TaggedVal new_v _) (TaggedVal old_v old_i)
= TaggedVal (f old_v new_v) old_i
-- Flip the arguments, because M.insertWith uses (new->old->result)
-- but f needs (old->new->result)
-- Like addToUDFM_Directly, keep the old tag
addToUDFM_C
:: Uniquable key => (elt -> elt -> elt) -- old -> new -> result
-> UniqDFM elt -- old
-> key -> elt -- new
-> UniqDFM elt -- result
addToUDFM_C f m k v = addToUDFM_Directly_C f m (getUnique k) v
addListToUDFM :: Uniquable key => UniqDFM elt -> [(key,elt)] -> UniqDFM elt
addListToUDFM = foldl (\m (k, v) -> addToUDFM m k v)
addListToUDFM_Directly :: UniqDFM elt -> [(Unique,elt)] -> UniqDFM elt
addListToUDFM_Directly = foldl (\m (k, v) -> addToUDFM_Directly m k v)
addListToUDFM_Directly_C
:: (elt -> elt -> elt) -> UniqDFM elt -> [(Unique,elt)] -> UniqDFM elt
addListToUDFM_Directly_C f = foldl (\m (k, v) -> addToUDFM_Directly_C f m k v)
delFromUDFM :: Uniquable key => UniqDFM elt -> key -> UniqDFM elt
delFromUDFM (UDFM m i) k = UDFM (M.delete (getKey $ getUnique k) m) i
plusUDFM_C :: (elt -> elt -> elt) -> UniqDFM elt -> UniqDFM elt -> UniqDFM elt
plusUDFM_C f udfml@(UDFM _ i) udfmr@(UDFM _ j)
-- we will use the upper bound on the tag as a proxy for the set size,
-- to insert the smaller one into the bigger one
| i > j = insertUDFMIntoLeft_C f udfml udfmr
| otherwise = insertUDFMIntoLeft_C f udfmr udfml
-- Note [Overflow on plusUDFM]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- There are multiple ways of implementing plusUDFM.
-- The main problem that needs to be solved is overlap on times of
-- insertion between different keys in two maps.
-- Consider:
--
-- A = fromList [(a, (x, 1))]
-- B = fromList [(b, (y, 1))]
--
-- If you merge them naively you end up with:
--
-- C = fromList [(a, (x, 1)), (b, (y, 1))]
--
-- Which loses information about ordering and brings us back into
-- non-deterministic world.
--
-- The solution I considered before would increment the tags on one of the
-- sets by the upper bound of the other set. The problem with this approach
-- is that you'll run out of tags for some merge patterns.
-- Say you start with A with upper bound 1, you merge A with A to get A' and
-- the upper bound becomes 2. You merge A' with A' and the upper bound
-- doubles again. After 64 merges you overflow.
-- This solution would have the same time complexity as plusUFM, namely O(n+m).
--
-- The solution I ended up with has time complexity of
-- O(m log m + m * min (n+m, W)) where m is the smaller set.
-- It simply inserts the elements of the smaller set into the larger
-- set in the order that they were inserted into the smaller set. That's
-- O(m log m) for extracting the elements from the smaller set in the
-- insertion order and O(m * min(n+m, W)) to insert them into the bigger
-- set.
plusUDFM :: UniqDFM elt -> UniqDFM elt -> UniqDFM elt
plusUDFM udfml@(UDFM _ i) udfmr@(UDFM _ j)
-- we will use the upper bound on the tag as a proxy for the set size,
-- to insert the smaller one into the bigger one
| i > j = insertUDFMIntoLeft udfml udfmr
| otherwise = insertUDFMIntoLeft udfmr udfml
insertUDFMIntoLeft :: UniqDFM elt -> UniqDFM elt -> UniqDFM elt
insertUDFMIntoLeft udfml udfmr = addListToUDFM_Directly udfml $ udfmToList udfmr
insertUDFMIntoLeft_C
:: (elt -> elt -> elt) -> UniqDFM elt -> UniqDFM elt -> UniqDFM elt
insertUDFMIntoLeft_C f udfml udfmr =
addListToUDFM_Directly_C f udfml $ udfmToList udfmr
lookupUDFM :: Uniquable key => UniqDFM elt -> key -> Maybe elt
lookupUDFM (UDFM m _i) k = taggedFst `fmap` M.lookup (getKey $ getUnique k) m
lookupUDFM_Directly :: UniqDFM elt -> Unique -> Maybe elt
lookupUDFM_Directly (UDFM m _i) k = taggedFst `fmap` M.lookup (getKey k) m
elemUDFM :: Uniquable key => key -> UniqDFM elt -> Bool
elemUDFM k (UDFM m _i) = M.member (getKey $ getUnique k) m
-- | Performs a deterministic fold over the UniqDFM.
-- It's O(n log n) while the corresponding function on `UniqFM` is O(n).
foldUDFM :: (elt -> a -> a) -> a -> UniqDFM elt -> a
foldUDFM k z m = foldr k z (eltsUDFM m)
-- | Performs a nondeterministic fold over the UniqDFM.
-- It's O(n), same as the corresponding function on `UniqFM`.
-- If you use this please provide a justification why it doesn't introduce
-- nondeterminism.
nonDetFoldUDFM :: (elt -> a -> a) -> a -> UniqDFM elt -> a
nonDetFoldUDFM k z (UDFM m _i) = foldr k z $ map taggedFst $ M.elems m
eltsUDFM :: UniqDFM elt -> [elt]
eltsUDFM (UDFM m _i) =
map taggedFst $ sortBy (compare `on` taggedSnd) $ M.elems m
filterUDFM :: (elt -> Bool) -> UniqDFM elt -> UniqDFM elt
filterUDFM p (UDFM m i) = UDFM (M.filter (\(TaggedVal v _) -> p v) m) i
filterUDFM_Directly :: (Unique -> elt -> Bool) -> UniqDFM elt -> UniqDFM elt
filterUDFM_Directly p (UDFM m i) = UDFM (M.filterWithKey p' m) i
where
p' k (TaggedVal v _) = p (getUnique k) v
-- | Converts `UniqDFM` to a list, with elements in deterministic order.
-- It's O(n log n) while the corresponding function on `UniqFM` is O(n).
udfmToList :: UniqDFM elt -> [(Unique, elt)]
udfmToList (UDFM m _i) =
[ (getUnique k, taggedFst v)
| (k, v) <- sortBy (compare `on` (taggedSnd . snd)) $ M.toList m ]
isNullUDFM :: UniqDFM elt -> Bool
isNullUDFM (UDFM m _) = M.null m
sizeUDFM :: UniqDFM elt -> Int
sizeUDFM (UDFM m _i) = M.size m
intersectUDFM :: UniqDFM elt -> UniqDFM elt -> UniqDFM elt
intersectUDFM (UDFM x i) (UDFM y _j) = UDFM (M.intersection x y) i
-- M.intersection is left biased, that means the result will only have
-- a subset of elements from the left set, so `i` is a good upper bound.
udfmIntersectUFM :: UniqDFM elt -> UniqFM elt -> UniqDFM elt
udfmIntersectUFM (UDFM x i) y = UDFM (M.intersection x (ufmToIntMap y)) i
-- M.intersection is left biased, that means the result will only have
-- a subset of elements from the left set, so `i` is a good upper bound.
intersectsUDFM :: UniqDFM elt -> UniqDFM elt -> Bool
intersectsUDFM x y = isNullUDFM (x `intersectUDFM` y)
disjointUDFM :: UniqDFM elt -> UniqDFM elt -> Bool
disjointUDFM (UDFM x _i) (UDFM y _j) = M.null (M.intersection x y)
disjointUdfmUfm :: UniqDFM elt -> UniqFM elt2 -> Bool
disjointUdfmUfm (UDFM x _i) y = M.null (M.intersection x (ufmToIntMap y))
minusUDFM :: UniqDFM elt1 -> UniqDFM elt2 -> UniqDFM elt1
minusUDFM (UDFM x i) (UDFM y _j) = UDFM (M.difference x y) i
-- M.difference returns a subset of a left set, so `i` is a good upper
-- bound.
udfmMinusUFM :: UniqDFM elt1 -> UniqFM elt2 -> UniqDFM elt1
udfmMinusUFM (UDFM x i) y = UDFM (M.difference x (ufmToIntMap y)) i
-- M.difference returns a subset of a left set, so `i` is a good upper
-- bound.
-- | Partition UniqDFM into two UniqDFMs according to the predicate
partitionUDFM :: (elt -> Bool) -> UniqDFM elt -> (UniqDFM elt, UniqDFM elt)
partitionUDFM p (UDFM m i) =
case M.partition (p . taggedFst) m of
(left, right) -> (UDFM left i, UDFM right i)
-- | Delete a list of elements from a UniqDFM
delListFromUDFM :: Uniquable key => UniqDFM elt -> [key] -> UniqDFM elt
delListFromUDFM = foldl delFromUDFM
-- | This allows for lossy conversion from UniqDFM to UniqFM
udfmToUfm :: UniqDFM elt -> UniqFM elt
udfmToUfm (UDFM m _i) =
listToUFM_Directly [(getUnique k, taggedFst tv) | (k, tv) <- M.toList m]
listToUDFM :: Uniquable key => [(key,elt)] -> UniqDFM elt
listToUDFM = foldl (\m (k, v) -> addToUDFM m k v) emptyUDFM
listToUDFM_Directly :: [(Unique, elt)] -> UniqDFM elt
listToUDFM_Directly = foldl (\m (u, v) -> addToUDFM_Directly m u v) emptyUDFM
-- | Apply a function to a particular element
adjustUDFM :: Uniquable key => (elt -> elt) -> UniqDFM elt -> key -> UniqDFM elt
adjustUDFM f (UDFM m i) k = UDFM (M.adjust (fmap f) (getKey $ getUnique k) m) i
-- | The expression (alterUDFM f k map) alters value x at k, or absence
-- thereof. alterUDFM can be used to insert, delete, or update a value in
-- UniqDFM. Use addToUDFM, delFromUDFM or adjustUDFM when possible, they are
-- more efficient.
alterUDFM
:: Uniquable key
=> (Maybe elt -> Maybe elt) -- How to adjust
-> UniqDFM elt -- old
-> key -- new
-> UniqDFM elt -- result
alterUDFM f (UDFM m i) k =
UDFM (M.alter alterf (getKey $ getUnique k) m) (i + 1)
where
alterf Nothing = inject $ f Nothing
alterf (Just (TaggedVal v _)) = inject $ f (Just v)
inject Nothing = Nothing
inject (Just v) = Just $ TaggedVal v i
-- | Map a function over every value in a UniqDFM
mapUDFM :: (elt1 -> elt2) -> UniqDFM elt1 -> UniqDFM elt2
mapUDFM f (UDFM m i) = UDFM (M.map (fmap f) m) i
anyUDFM :: (elt -> Bool) -> UniqDFM elt -> Bool
anyUDFM p (UDFM m _i) = M.foldr ((||) . p . taggedFst) False m
allUDFM :: (elt -> Bool) -> UniqDFM elt -> Bool
allUDFM p (UDFM m _i) = M.foldr ((&&) . p . taggedFst) True m
instance Monoid (UniqDFM a) where
mempty = emptyUDFM
mappend = plusUDFM
-- This should not be used in commited code, provided for convenience to
-- make ad-hoc conversions when developing
alwaysUnsafeUfmToUdfm :: UniqFM elt -> UniqDFM elt
alwaysUnsafeUfmToUdfm = listToUDFM_Directly . nonDetUFMToList
-- Output-ery
instance Outputable a => Outputable (UniqDFM a) where
ppr ufm = pprUniqDFM ppr ufm
pprUniqDFM :: (a -> SDoc) -> UniqDFM a -> SDoc
pprUniqDFM ppr_elt ufm
= brackets $ fsep $ punctuate comma $
[ ppr uq <+> text ":->" <+> ppr_elt elt
| (uq, elt) <- udfmToList ufm ]
pprUDFM :: UniqDFM a -- ^ The things to be pretty printed
-> ([a] -> SDoc) -- ^ The pretty printing function to use on the elements
-> SDoc -- ^ 'SDoc' where the things have been pretty
-- printed
pprUDFM ufm pp = pp (eltsUDFM ufm)
| pparkkin/eta | compiler/ETA/Utils/UniqDFM.hs | bsd-3-clause | 15,206 | 0 | 13 | 3,391 | 3,677 | 1,931 | 1,746 | 202 | 3 |
-- | module Differential provides functions for finding the derivatives of standard one variable functions
-- functions implemented currently are constant, polynomial, sin, cos, tan, cosec, sec, cot, log, exponential and their compositions.
-- Also, the functions formed by addition, subtraction, product and division of these functions are allowed
module Differential
(
-- * Types
-- ** Polynomial type
Polynomial,
-- * Data Types
-- ** Expr
Expr(Const,Poly,Sin,Cos,Tan,Cosec,Sec,Cot,Log,Exp,Sum,Product,Diff,Div),
-- * Funtions
diff,
deriv,
)where
import Data.String.Utils
type Polynomial = [Float] -- ^ List of float elements [1,3,2] means 1 + 3x + 2x^2
-- |Expr data type contains expressions for the mathematical expressions
data Expr
-- | To define an expression as a constant float number
= Const Float
-- | To define an expression as a polynomial
| Poly Polynomial
-- | To define an expression as Sin function
| Sin Expr
-- | To define an expression as Cos function
| Cos Expr
-- | To define an expression as Tan function
| Tan Expr
-- | To define an expression as Cosec function
| Cosec Expr
-- | To define an expression as Sec function
| Sec Expr
-- | To define an expression as Cot function
| Cot Expr
-- | To define an expression as Log function
| Log Expr
-- | To define an expression as Exponential function
| Exp Expr
-- | To define an expression as a sum of two expressions
| Sum Expr Expr
-- | To define an expression as a product of two expressions
| Product Expr Expr
-- | To define an expression as a difference of two expressions
| Diff Expr Expr
-- | To define an expression as a divison of two expressions
| Div Expr Expr
instance Show Expr where
show (Const x) = show x
show (Poly x) = show x
show (Sin e) = "(sin $ " ++ show(e) ++ ")"
show (Cos e) = "(cos $ " ++ show(e) ++ ")"
show (Tan e) = "(tan $ " ++ show(e) ++ ")"
show (Cosec e) = "(1/sin $ " ++ show(e) ++ ")"
show (Sec e) = "(1/cos $ " ++ show(e) ++ ")"
show (Cot e) = "(1/tan $ " ++ show(e) ++ ")"
show (Log e) = "(log $ " ++ show(e) ++ ")"
show (Exp e) = "(exp $ " ++ show(e) ++ ")"
show (Sum t1 t2) = "(" ++ (show t1) ++ " + " ++ (show t2) ++ ")"
show (Diff t1 t2) = "(" ++ (show t1) ++ " - " ++ (show t2) ++ ")"
show (Product t1 t2) = "(" ++ (show t1) ++ " * " ++ (show t2) ++ ")"
show (Div t1 t2) = "(" ++ (show t1) ++ " / " ++ (show t2) ++ ")"
eval :: Expr -> Float -> Float
eval (Const x) a = x
eval (Poly x) a = evalPoly x a
eval (Sin x) a = (sin (eval x a))
eval (Cos x) a = (cos (eval x a))
eval (Tan x) a = (tan (eval x a))
eval (Sec x) a = (1 / cos (eval x a))
eval (Cosec x) a = (1 / sin (eval x a))
eval (Cot x) a = (1 / tan (eval x a))
eval (Exp x) a = (exp (eval x a))
eval (Log x) a = (log (eval x a))
eval (Sum f g) a = (eval f a) + (eval g a)
eval (Diff f g) a = (eval f a) - (eval g a)
eval (Product f g) a = (eval f a) * (eval g a)
eval (Div f g) a = (eval f a) / (eval g a)
evalPoly :: Polynomial -> Float -> Float
evalPoly [a] x = a
evalPoly a x = eval' (tail y) (head y) x
where y = reverse a
-- helping function for eval
eval' :: Polynomial -> Float -> Float -> Float
eval' [a] acc x = a + acc*x
eval' (a:as) acc x = eval' as (x*acc+a) x
-- |The 'diff' function takes an expression and a point and evaluates its differential at the given point
diff :: Expr -- ^ Input Expression
-> Float -- ^ value where derivative is needed
-> Float -- ^ return value of derivative
diff (Const x) a = 0
diff (Poly x) a = evalPoly (diffPoly x) a
diff (Sin x) a = (eval (Cos x) a) * (diff x a)
diff (Cos x) a = (eval (Const (-1)) a) * (eval (Sin x) a) * (diff x a)
diff (Tan x) a = (eval (Sec x) a) * (eval (Sec x) a) * (diff x a)
diff (Sec x) a = (eval (Sec x) a) * (eval (Tan x) a) * (diff x a)
diff (Cosec x) a = (eval (Const (-1)) a) * (eval (Cosec x) a) * (eval (Cot x) a) * (diff x a)
diff (Cot x) a = (eval (Const (-1)) a) * (eval (Cosec x) a) * (eval (Cosec x) a) * (diff x a)
diff (Exp x) a = (eval (Exp x) a) * (diff x a)
diff (Log x) a = (eval (Log x) a) * (diff x a)
diff (Sum f g) a = sumRule f g a
diff (Diff f g) a = diffrenceRule f g a
diff (Product f g) a = productRule f g a
diff (Div f g) a = divRule f g a
sumRule :: Expr -> Expr -> Float -> Float
sumRule f g a = (diff f a) + (diff g a)
diffrenceRule :: Expr -> Expr -> Float -> Float
diffrenceRule f g a = (diff f a) - (diff g a)
productRule :: Expr -> Expr -> Float -> Float
productRule f g a = (eval f a) * (diff g a) + (eval g a) * (diff f a)
divRule :: Expr -> Expr -> Float -> Float
divRule f g a = ((diff f a) * (eval g a) - (diff g a) * (eval f a)) / ((eval g a)* (eval g a))
diffPoly :: Polynomial -> Polynomial
diffPoly a = diffPoly' (tail a) 1
-- helping function for deriv
diffPoly' :: Polynomial -> Float -> Polynomial
diffPoly' [x] i = [x*i]
diffPoly' (x:xs) i = (x*i) : (diffPoly' xs (i+1))
deriv' :: Expr -> String
deriv' (Const _) = show(Const 0)
deriv' (Poly x) = show(diffPoly x)
deriv' (Sin x) = show(Cos x) ++ " * " ++ (deriv' x)
deriv' (Cos x) = show(Const (-1)) ++ " * " ++ show(Sin x) ++ " * " ++ (deriv' x)
deriv' (Tan x) = show(Sec x) ++ " * " ++ show(Sec x) ++ " * " ++ (deriv' x)
deriv' (Sec x) = show(Sec x) ++ " * " ++ show(Tan x) ++ " * " ++ (deriv' x)
deriv' (Cosec x) = show(Const (-1)) ++ " * " ++ show(Cosec x) ++ " * " ++ show(Cot x) ++ " * " ++ (deriv' x)
deriv' (Cot x) = show(Const (-1)) ++ " * " ++ show(Cosec x) ++ " * " ++ show(Cosec x) ++ " * " ++ (deriv' x)
deriv' (Exp x) = show(Exp x) ++ " * " ++ (deriv' x)
deriv' (Log x) = "1/(" ++ show(x) ++ ") * " ++ (deriv' x)
deriv' (Sum f g) = "(" ++ (deriv' f) ++ " + " ++ (deriv' g) ++ ")"
deriv' (Product f g) = "(" ++ show(f) ++ " * " ++ (deriv' g) ++ " + " ++ (deriv' f) ++ " * " ++ show(g) ++ ")"
-- |The 'deriv' function takes an expression gives its derivative in symbolic notation
-- for example, for sin, it gives cos
deriv :: Expr -- ^ Input Expression
-> String -- ^ Return derivative in the form of a string which can be evaluated.
deriv e = (replace "\"" "" str)
where str = deriv' e
| ankeshs/numerikell | tmp/Differential.hs | bsd-3-clause | 6,131 | 3 | 15 | 1,515 | 2,871 | 1,481 | 1,390 | 109 | 1 |
{-# LANGUAGE CPP, MagicHash, NondecreasingIndentation, TupleSections #-}
{-# OPTIONS -fno-cse #-}
-- -fno-cse is needed for GLOBAL_VAR's to behave properly
-----------------------------------------------------------------------------
--
-- GHC Interactive User Interface
--
-- (c) The GHC Team 2005-2006
--
-----------------------------------------------------------------------------
module InteractiveUI (
interactiveUI,
GhciSettings(..),
defaultGhciSettings,
ghciCommands,
ghciWelcomeMsg
) where
#include "HsVersions.h"
-- GHCi
import qualified GhciMonad ( args, runStmt )
import GhciMonad hiding ( args, runStmt )
import GhciTags
import Debugger
-- The GHC interface
import DynFlags
import ErrUtils
import GhcMonad ( modifySession )
import qualified GHC
import GHC ( LoadHowMuch(..), Target(..), TargetId(..), InteractiveImport(..),
TyThing(..), Phase, BreakIndex, Resume, SingleStep, Ghc,
handleSourceError )
import HsImpExp
import HscTypes ( tyThingParent_maybe, handleFlagWarnings, getSafeMode, hsc_IC,
setInteractivePrintName )
import Module
import Name
import Packages ( trusted, getPackageDetails, listVisibleModuleNames, pprFlag )
import PprTyThing
import RdrName ( getGRE_NameQualifier_maybes )
import SrcLoc
import qualified Lexer
import StringBuffer
import Outputable hiding ( printForUser, printForUserPartWay, bold )
-- Other random utilities
import BasicTypes hiding ( isTopLevel )
import Config
import Digraph
import Encoding
import FastString
import Linker
import Maybes ( orElse, expectJust )
import NameSet
import Panic hiding ( showException )
import Util
-- Haskell Libraries
import System.Console.Haskeline as Haskeline
import Control.Monad as Monad
import Control.Applicative hiding (empty)
import Control.Monad.Trans.Class
import Control.Monad.IO.Class
import Data.Array
import qualified Data.ByteString.Char8 as BS
import Data.Char
import Data.Function
import Data.IORef ( IORef, modifyIORef, newIORef, readIORef, writeIORef )
import Data.List ( find, group, intercalate, intersperse, isPrefixOf, nub,
partition, sort, sortBy )
import Data.Maybe
import Exception hiding (catch)
import Foreign.C
#if __GLASGOW_HASKELL__ >= 709
import Foreign
#else
import Foreign.Safe
#endif
import System.Directory
import System.Environment
import System.Exit ( exitWith, ExitCode(..) )
import System.FilePath
import System.IO
import System.IO.Error
import System.IO.Unsafe ( unsafePerformIO )
import System.Process
import Text.Printf
import Text.Read ( readMaybe )
#ifndef mingw32_HOST_OS
import System.Posix hiding ( getEnv )
#else
import qualified System.Win32
#endif
import GHC.Exts ( unsafeCoerce# )
import GHC.IO.Exception ( IOErrorType(InvalidArgument) )
import GHC.IO.Handle ( hFlushAll )
import GHC.TopHandler ( topHandler )
-----------------------------------------------------------------------------
data GhciSettings = GhciSettings {
availableCommands :: [Command],
shortHelpText :: String,
fullHelpText :: String,
defPrompt :: String,
defPrompt2 :: String
}
defaultGhciSettings :: GhciSettings
defaultGhciSettings =
GhciSettings {
availableCommands = ghciCommands,
shortHelpText = defShortHelpText,
fullHelpText = defFullHelpText,
defPrompt = default_prompt,
defPrompt2 = default_prompt2
}
ghciWelcomeMsg :: String
ghciWelcomeMsg = "GHCi, version " ++ cProjectVersion ++
": http://www.haskell.org/ghc/ :? for help"
cmdName :: Command -> String
cmdName (n,_,_) = n
GLOBAL_VAR(macros_ref, [], [Command])
ghciCommands :: [Command]
ghciCommands = [
-- Hugs users are accustomed to :e, so make sure it doesn't overlap
("?", keepGoing help, noCompletion),
("add", keepGoingPaths addModule, completeFilename),
("abandon", keepGoing abandonCmd, noCompletion),
("break", keepGoing breakCmd, completeIdentifier),
("back", keepGoing backCmd, noCompletion),
("browse", keepGoing' (browseCmd False), completeModule),
("browse!", keepGoing' (browseCmd True), completeModule),
("cd", keepGoing' changeDirectory, completeFilename),
("check", keepGoing' checkModule, completeHomeModule),
("continue", keepGoing continueCmd, noCompletion),
("complete", keepGoing completeCmd, noCompletion),
("cmd", keepGoing cmdCmd, completeExpression),
("ctags", keepGoing createCTagsWithLineNumbersCmd, completeFilename),
("ctags!", keepGoing createCTagsWithRegExesCmd, completeFilename),
("def", keepGoing (defineMacro False), completeExpression),
("def!", keepGoing (defineMacro True), completeExpression),
("delete", keepGoing deleteCmd, noCompletion),
("edit", keepGoing' editFile, completeFilename),
("etags", keepGoing createETagsFileCmd, completeFilename),
("force", keepGoing forceCmd, completeExpression),
("forward", keepGoing forwardCmd, noCompletion),
("help", keepGoing help, noCompletion),
("history", keepGoing historyCmd, noCompletion),
("info", keepGoing' (info False), completeIdentifier),
("info!", keepGoing' (info True), completeIdentifier),
("issafe", keepGoing' isSafeCmd, completeModule),
("kind", keepGoing' (kindOfType False), completeIdentifier),
("kind!", keepGoing' (kindOfType True), completeIdentifier),
("load", keepGoingPaths loadModule_, completeHomeModuleOrFile),
("list", keepGoing' listCmd, noCompletion),
("module", keepGoing moduleCmd, completeSetModule),
("main", keepGoing runMain, completeFilename),
("print", keepGoing printCmd, completeExpression),
("quit", quit, noCompletion),
("reload", keepGoing' reloadModule, noCompletion),
("run", keepGoing runRun, completeFilename),
("script", keepGoing' scriptCmd, completeFilename),
("set", keepGoing setCmd, completeSetOptions),
("seti", keepGoing setiCmd, completeSeti),
("show", keepGoing showCmd, completeShowOptions),
("showi", keepGoing showiCmd, completeShowiOptions),
("sprint", keepGoing sprintCmd, completeExpression),
("step", keepGoing stepCmd, completeIdentifier),
("steplocal", keepGoing stepLocalCmd, completeIdentifier),
("stepmodule",keepGoing stepModuleCmd, completeIdentifier),
("type", keepGoing' typeOfExpr, completeExpression),
("trace", keepGoing traceCmd, completeExpression),
("undef", keepGoing undefineMacro, completeMacro),
("unset", keepGoing unsetOptions, completeSetOptions)
]
-- We initialize readline (in the interactiveUI function) to use
-- word_break_chars as the default set of completion word break characters.
-- This can be overridden for a particular command (for example, filename
-- expansion shouldn't consider '/' to be a word break) by setting the third
-- entry in the Command tuple above.
--
-- NOTE: in order for us to override the default correctly, any custom entry
-- must be a SUBSET of word_break_chars.
word_break_chars :: String
word_break_chars = let symbols = "!#$%&*+/<=>?@\\^|-~"
specials = "(),;[]`{}"
spaces = " \t\n"
in spaces ++ specials ++ symbols
flagWordBreakChars :: String
flagWordBreakChars = " \t\n"
keepGoing :: (String -> GHCi ()) -> (String -> InputT GHCi Bool)
keepGoing a str = keepGoing' (lift . a) str
keepGoing' :: Monad m => (String -> m ()) -> String -> m Bool
keepGoing' a str = a str >> return False
keepGoingPaths :: ([FilePath] -> InputT GHCi ()) -> (String -> InputT GHCi Bool)
keepGoingPaths a str
= do case toArgs str of
Left err -> liftIO $ hPutStrLn stderr err
Right args -> a args
return False
defShortHelpText :: String
defShortHelpText = "use :? for help.\n"
defFullHelpText :: String
defFullHelpText =
" Commands available from the prompt:\n" ++
"\n" ++
" <statement> evaluate/run <statement>\n" ++
" : repeat last command\n" ++
" :{\\n ..lines.. \\n:}\\n multiline command\n" ++
" :add [*]<module> ... add module(s) to the current target set\n" ++
" :browse[!] [[*]<mod>] display the names defined by module <mod>\n" ++
" (!: more details; *: all top-level names)\n" ++
" :cd <dir> change directory to <dir>\n" ++
" :cmd <expr> run the commands returned by <expr>::IO String\n" ++
" :complete <dom> [<rng>] <s> list completions for partial input string\n" ++
" :ctags[!] [<file>] create tags file for Vi (default: \"tags\")\n" ++
" (!: use regex instead of line number)\n" ++
" :def <cmd> <expr> define command :<cmd> (later defined command has\n" ++
" precedence, ::<cmd> is always a builtin command)\n" ++
" :edit <file> edit file\n" ++
" :edit edit last module\n" ++
" :etags [<file>] create tags file for Emacs (default: \"TAGS\")\n" ++
" :help, :? display this list of commands\n" ++
" :info[!] [<name> ...] display information about the given names\n" ++
" (!: do not filter instances)\n" ++
" :issafe [<mod>] display safe haskell information of module <mod>\n" ++
" :kind[!] <type> show the kind of <type>\n" ++
" (!: also print the normalised type)\n" ++
" :load [*]<module> ... load module(s) and their dependents\n" ++
" :main [<arguments> ...] run the main function with the given arguments\n" ++
" :module [+/-] [*]<mod> ... set the context for expression evaluation\n" ++
" :quit exit GHCi\n" ++
" :reload reload the current module set\n" ++
" :run function [<arguments> ...] run the function with the given arguments\n" ++
" :script <filename> run the script <filename>\n" ++
" :type <expr> show the type of <expr>\n" ++
" :undef <cmd> undefine user-defined command :<cmd>\n" ++
" :!<command> run the shell command <command>\n" ++
"\n" ++
" -- Commands for debugging:\n" ++
"\n" ++
" :abandon at a breakpoint, abandon current computation\n" ++
" :back go back in the history (after :trace)\n" ++
" :break [<mod>] <l> [<col>] set a breakpoint at the specified location\n" ++
" :break <name> set a breakpoint on the specified function\n" ++
" :continue resume after a breakpoint\n" ++
" :delete <number> delete the specified breakpoint\n" ++
" :delete * delete all breakpoints\n" ++
" :force <expr> print <expr>, forcing unevaluated parts\n" ++
" :forward go forward in the history (after :back)\n" ++
" :history [<n>] after :trace, show the execution history\n" ++
" :list show the source code around current breakpoint\n" ++
" :list <identifier> show the source code for <identifier>\n" ++
" :list [<module>] <line> show the source code around line number <line>\n" ++
" :print [<name> ...] show a value without forcing its computation\n" ++
" :sprint [<name> ...] simplified version of :print\n" ++
" :step single-step after stopping at a breakpoint\n"++
" :step <expr> single-step into <expr>\n"++
" :steplocal single-step within the current top-level binding\n"++
" :stepmodule single-step restricted to the current module\n"++
" :trace trace after stopping at a breakpoint\n"++
" :trace <expr> evaluate <expr> with tracing on (see :history)\n"++
"\n" ++
" -- Commands for changing settings:\n" ++
"\n" ++
" :set <option> ... set options\n" ++
" :seti <option> ... set options for interactive evaluation only\n" ++
" :set args <arg> ... set the arguments returned by System.getArgs\n" ++
" :set prog <progname> set the value returned by System.getProgName\n" ++
" :set prompt <prompt> set the prompt used in GHCi\n" ++
" :set prompt2 <prompt> set the continuation prompt used in GHCi\n" ++
" :set editor <cmd> set the command used for :edit\n" ++
" :set stop [<n>] <cmd> set the command to run when a breakpoint is hit\n" ++
" :unset <option> ... unset options\n" ++
"\n" ++
" Options for ':set' and ':unset':\n" ++
"\n" ++
" +m allow multiline commands\n" ++
" +r revert top-level expressions after each evaluation\n" ++
" +s print timing/memory stats after each evaluation\n" ++
" +t print type after evaluation\n" ++
" -<flags> most GHC command line flags can also be set here\n" ++
" (eg. -v2, -XFlexibleInstances, etc.)\n" ++
" for GHCi-specific flags, see User's Guide,\n"++
" Flag reference, Interactive-mode options\n" ++
"\n" ++
" -- Commands for displaying information:\n" ++
"\n" ++
" :show bindings show the current bindings made at the prompt\n" ++
" :show breaks show the active breakpoints\n" ++
" :show context show the breakpoint context\n" ++
" :show imports show the current imports\n" ++
" :show linker show current linker state\n" ++
" :show modules show the currently loaded modules\n" ++
" :show packages show the currently active package flags\n" ++
" :show paths show the currently active search paths\n" ++
" :show language show the currently active language flags\n" ++
" :show <setting> show value of <setting>, which is one of\n" ++
" [args, prog, prompt, editor, stop]\n" ++
" :showi language show language flags for interactive evaluation\n" ++
"\n"
findEditor :: IO String
findEditor = do
getEnv "EDITOR"
`catchIO` \_ -> do
#if mingw32_HOST_OS
win <- System.Win32.getWindowsDirectory
return (win </> "notepad.exe")
#else
return ""
#endif
foreign import ccall unsafe "rts_isProfiled" isProfiled :: IO CInt
default_progname, default_prompt, default_prompt2, default_stop :: String
default_progname = "<interactive>"
default_prompt = "%s> "
default_prompt2 = "%s| "
default_stop = ""
default_args :: [String]
default_args = []
interactiveUI :: GhciSettings -> [(FilePath, Maybe Phase)] -> Maybe [String]
-> Ghc ()
interactiveUI config srcs maybe_exprs = do
-- although GHCi compiles with -prof, it is not usable: the byte-code
-- compiler and interpreter don't work with profiling. So we check for
-- this up front and emit a helpful error message (#2197)
i <- liftIO $ isProfiled
when (i /= 0) $
throwGhcException (InstallationError "GHCi cannot be used when compiled with -prof")
-- HACK! If we happen to get into an infinite loop (eg the user
-- types 'let x=x in x' at the prompt), then the thread will block
-- on a blackhole, and become unreachable during GC. The GC will
-- detect that it is unreachable and send it the NonTermination
-- exception. However, since the thread is unreachable, everything
-- it refers to might be finalized, including the standard Handles.
-- This sounds like a bug, but we don't have a good solution right
-- now.
_ <- liftIO $ newStablePtr stdin
_ <- liftIO $ newStablePtr stdout
_ <- liftIO $ newStablePtr stderr
-- Initialise buffering for the *interpreted* I/O system
initInterpBuffering
-- The initial set of DynFlags used for interactive evaluation is the same
-- as the global DynFlags, plus -XExtendedDefaultRules and
-- -XNoMonomorphismRestriction.
dflags <- getDynFlags
let dflags' = (`xopt_set` Opt_ExtendedDefaultRules)
. (`xopt_unset` Opt_MonomorphismRestriction)
$ dflags
GHC.setInteractiveDynFlags dflags'
lastErrLocationsRef <- liftIO $ newIORef []
progDynFlags <- GHC.getProgramDynFlags
_ <- GHC.setProgramDynFlags $
progDynFlags { log_action = ghciLogAction lastErrLocationsRef }
liftIO $ when (isNothing maybe_exprs) $ do
-- Only for GHCi (not runghc and ghc -e):
-- Turn buffering off for the compiled program's stdout/stderr
turnOffBuffering
-- Turn buffering off for GHCi's stdout
hFlush stdout
hSetBuffering stdout NoBuffering
-- We don't want the cmd line to buffer any input that might be
-- intended for the program, so unbuffer stdin.
hSetBuffering stdin NoBuffering
hSetBuffering stderr NoBuffering
#if defined(mingw32_HOST_OS)
-- On Unix, stdin will use the locale encoding. The IO library
-- doesn't do this on Windows (yet), so for now we use UTF-8,
-- for consistency with GHC 6.10 and to make the tests work.
hSetEncoding stdin utf8
#endif
default_editor <- liftIO $ findEditor
startGHCi (runGHCi srcs maybe_exprs)
GHCiState{ progname = default_progname,
GhciMonad.args = default_args,
prompt = defPrompt config,
prompt2 = defPrompt2 config,
stop = default_stop,
editor = default_editor,
options = [],
line_number = 1,
break_ctr = 0,
breaks = [],
tickarrays = emptyModuleEnv,
ghci_commands = availableCommands config,
last_command = Nothing,
cmdqueue = [],
remembered_ctx = [],
transient_ctx = [],
ghc_e = isJust maybe_exprs,
short_help = shortHelpText config,
long_help = fullHelpText config,
lastErrorLocations = lastErrLocationsRef
}
return ()
resetLastErrorLocations :: GHCi ()
resetLastErrorLocations = do
st <- getGHCiState
liftIO $ writeIORef (lastErrorLocations st) []
ghciLogAction :: IORef [(FastString, Int)] -> LogAction
ghciLogAction lastErrLocations dflags severity srcSpan style msg = do
defaultLogAction dflags severity srcSpan style msg
case severity of
SevError -> case srcSpan of
RealSrcSpan rsp -> modifyIORef lastErrLocations
(++ [(srcLocFile (realSrcSpanStart rsp), srcLocLine (realSrcSpanStart rsp))])
_ -> return ()
_ -> return ()
withGhcAppData :: (FilePath -> IO a) -> IO a -> IO a
withGhcAppData right left = do
either_dir <- tryIO (getAppUserDataDirectory "ghc")
case either_dir of
Right dir ->
do createDirectoryIfMissing False dir `catchIO` \_ -> return ()
right dir
_ -> left
runGHCi :: [(FilePath, Maybe Phase)] -> Maybe [String] -> GHCi ()
runGHCi paths maybe_exprs = do
dflags <- getDynFlags
let
read_dot_files = not (gopt Opt_IgnoreDotGhci dflags)
current_dir = return (Just ".ghci")
app_user_dir = liftIO $ withGhcAppData
(\dir -> return (Just (dir </> "ghci.conf")))
(return Nothing)
home_dir = do
either_dir <- liftIO $ tryIO (getEnv "HOME")
case either_dir of
Right home -> return (Just (home </> ".ghci"))
_ -> return Nothing
canonicalizePath' :: FilePath -> IO (Maybe FilePath)
canonicalizePath' fp = liftM Just (canonicalizePath fp)
`catchIO` \_ -> return Nothing
sourceConfigFile :: (FilePath, Bool) -> GHCi ()
sourceConfigFile (file, check_perms) = do
exists <- liftIO $ doesFileExist file
when exists $ do
perms_ok <-
if not check_perms
then return True
else do
dir_ok <- liftIO $ checkPerms (getDirectory file)
file_ok <- liftIO $ checkPerms file
return (dir_ok && file_ok)
when perms_ok $ do
either_hdl <- liftIO $ tryIO (openFile file ReadMode)
case either_hdl of
Left _e -> return ()
-- NOTE: this assumes that runInputT won't affect the terminal;
-- can we assume this will always be the case?
-- This would be a good place for runFileInputT.
Right hdl ->
do runInputTWithPrefs defaultPrefs defaultSettings $
runCommands $ fileLoop hdl
liftIO (hClose hdl `catchIO` \_ -> return ())
where
getDirectory f = case takeDirectory f of "" -> "."; d -> d
--
setGHCContextFromGHCiState
when (read_dot_files) $ do
mcfgs0 <- catMaybes <$> sequence [ current_dir, app_user_dir, home_dir ]
let mcfgs1 = zip mcfgs0 (repeat True)
++ zip (ghciScripts dflags) (repeat False)
-- False says "don't check permissions". We don't
-- require that a script explicitly added by
-- -ghci-script is owned by the current user. (#6017)
mcfgs <- liftIO $ mapM (\(f, b) -> (,b) <$> canonicalizePath' f) mcfgs1
mapM_ sourceConfigFile $ nub $ [ (f,b) | (Just f, b) <- mcfgs ]
-- nub, because we don't want to read .ghci twice if the
-- CWD is $HOME.
-- Perform a :load for files given on the GHCi command line
-- When in -e mode, if the load fails then we want to stop
-- immediately rather than going on to evaluate the expression.
when (not (null paths)) $ do
ok <- ghciHandle (\e -> do showException e; return Failed) $
-- TODO: this is a hack.
runInputTWithPrefs defaultPrefs defaultSettings $
loadModule paths
when (isJust maybe_exprs && failed ok) $
liftIO (exitWith (ExitFailure 1))
installInteractivePrint (interactivePrint dflags) (isJust maybe_exprs)
-- if verbosity is greater than 0, or we are connected to a
-- terminal, display the prompt in the interactive loop.
is_tty <- liftIO (hIsTerminalDevice stdin)
let show_prompt = verbosity dflags > 0 || is_tty
-- reset line number
getGHCiState >>= \st -> setGHCiState st{line_number=1}
case maybe_exprs of
Nothing ->
do
-- enter the interactive loop
runGHCiInput $ runCommands $ nextInputLine show_prompt is_tty
Just exprs -> do
-- just evaluate the expression we were given
enqueueCommands exprs
let hdle e = do st <- getGHCiState
-- flush the interpreter's stdout/stderr on exit (#3890)
flushInterpBuffers
-- Jump through some hoops to get the
-- current progname in the exception text:
-- <progname>: <exception>
liftIO $ withProgName (progname st)
$ topHandler e
-- this used to be topHandlerFastExit, see #2228
runInputTWithPrefs defaultPrefs defaultSettings $ do
-- make `ghc -e` exit nonzero on invalid input, see Trac #7962
runCommands' hdle (Just $ hdle (toException $ ExitFailure 1) >> return ()) (return Nothing)
-- and finally, exit
liftIO $ when (verbosity dflags > 0) $ putStrLn "Leaving GHCi."
runGHCiInput :: InputT GHCi a -> GHCi a
runGHCiInput f = do
dflags <- getDynFlags
histFile <- if gopt Opt_GhciHistory dflags
then liftIO $ withGhcAppData (\dir -> return (Just (dir </> "ghci_history")))
(return Nothing)
else return Nothing
runInputT
(setComplete ghciCompleteWord $ defaultSettings {historyFile = histFile})
f
-- | How to get the next input line from the user
nextInputLine :: Bool -> Bool -> InputT GHCi (Maybe String)
nextInputLine show_prompt is_tty
| is_tty = do
prmpt <- if show_prompt then lift mkPrompt else return ""
r <- getInputLine prmpt
incrementLineNo
return r
| otherwise = do
when show_prompt $ lift mkPrompt >>= liftIO . putStr
fileLoop stdin
-- NOTE: We only read .ghci files if they are owned by the current user,
-- and aren't world writable (files owned by root are ok, see #9324).
-- Otherwise, we could be accidentally running code planted by
-- a malicious third party.
-- Furthermore, We only read ./.ghci if . is owned by the current user
-- and isn't writable by anyone else. I think this is sufficient: we
-- don't need to check .. and ../.. etc. because "." always refers to
-- the same directory while a process is running.
checkPerms :: String -> IO Bool
#ifdef mingw32_HOST_OS
checkPerms _ = return True
#else
checkPerms name =
handleIO (\_ -> return False) $ do
st <- getFileStatus name
me <- getRealUserID
let mode = System.Posix.fileMode st
ok = (fileOwner st == me || fileOwner st == 0) &&
groupWriteMode /= mode `intersectFileModes` groupWriteMode &&
otherWriteMode /= mode `intersectFileModes` otherWriteMode
unless ok $
putStrLn $ "*** WARNING: " ++ name ++
" is writable by someone else, IGNORING!"
return ok
#endif
incrementLineNo :: InputT GHCi ()
incrementLineNo = do
st <- lift $ getGHCiState
let ln = 1+(line_number st)
lift $ setGHCiState st{line_number=ln}
fileLoop :: Handle -> InputT GHCi (Maybe String)
fileLoop hdl = do
l <- liftIO $ tryIO $ hGetLine hdl
case l of
Left e | isEOFError e -> return Nothing
| -- as we share stdin with the program, the program
-- might have already closed it, so we might get a
-- handle-closed exception. We therefore catch that
-- too.
isIllegalOperation e -> return Nothing
| InvalidArgument <- etype -> return Nothing
| otherwise -> liftIO $ ioError e
where etype = ioeGetErrorType e
-- treat InvalidArgument in the same way as EOF:
-- this can happen if the user closed stdin, or
-- perhaps did getContents which closes stdin at
-- EOF.
Right l' -> do
incrementLineNo
return (Just l')
mkPrompt :: GHCi String
mkPrompt = do
st <- getGHCiState
imports <- GHC.getContext
resumes <- GHC.getResumeContext
context_bit <-
case resumes of
[] -> return empty
r:_ -> do
let ix = GHC.resumeHistoryIx r
if ix == 0
then return (brackets (ppr (GHC.resumeSpan r)) <> space)
else do
let hist = GHC.resumeHistory r !! (ix-1)
pan <- GHC.getHistorySpan hist
return (brackets (ppr (negate ix) <> char ':'
<+> ppr pan) <> space)
let
dots | _:rs <- resumes, not (null rs) = text "... "
| otherwise = empty
rev_imports = reverse imports -- rightmost are the most recent
modules_bit =
hsep [ char '*' <> ppr m | IIModule m <- rev_imports ] <+>
hsep (map ppr [ myIdeclName d | IIDecl d <- rev_imports ])
-- use the 'as' name if there is one
myIdeclName d | Just m <- ideclAs d = m
| otherwise = unLoc (ideclName d)
deflt_prompt = dots <> context_bit <> modules_bit
f ('%':'l':xs) = ppr (1 + line_number st) <> f xs
f ('%':'s':xs) = deflt_prompt <> f xs
f ('%':'%':xs) = char '%' <> f xs
f (x:xs) = char x <> f xs
f [] = empty
dflags <- getDynFlags
return (showSDoc dflags (f (prompt st)))
queryQueue :: GHCi (Maybe String)
queryQueue = do
st <- getGHCiState
case cmdqueue st of
[] -> return Nothing
c:cs -> do setGHCiState st{ cmdqueue = cs }
return (Just c)
-- Reconfigurable pretty-printing Ticket #5461
installInteractivePrint :: Maybe String -> Bool -> GHCi ()
installInteractivePrint Nothing _ = return ()
installInteractivePrint (Just ipFun) exprmode = do
ok <- trySuccess $ do
(name:_) <- GHC.parseName ipFun
modifySession (\he -> let new_ic = setInteractivePrintName (hsc_IC he) name
in he{hsc_IC = new_ic})
return Succeeded
when (failed ok && exprmode) $ liftIO (exitWith (ExitFailure 1))
-- | The main read-eval-print loop
runCommands :: InputT GHCi (Maybe String) -> InputT GHCi ()
runCommands = runCommands' handler Nothing
runCommands' :: (SomeException -> GHCi Bool) -- ^ Exception handler
-> Maybe (GHCi ()) -- ^ Source error handler
-> InputT GHCi (Maybe String) -> InputT GHCi ()
runCommands' eh sourceErrorHandler gCmd = do
b <- ghandle (\e -> case fromException e of
Just UserInterrupt -> return $ Just False
_ -> case fromException e of
Just ghce ->
do liftIO (print (ghce :: GhcException))
return Nothing
_other ->
liftIO (Exception.throwIO e))
(runOneCommand eh gCmd)
case b of
Nothing -> return ()
Just success -> do
when (not success) $ maybe (return ()) lift sourceErrorHandler
runCommands' eh sourceErrorHandler gCmd
-- | Evaluate a single line of user input (either :<command> or Haskell code).
-- A result of Nothing means there was no more input to process.
-- Otherwise the result is Just b where b is True if the command succeeded;
-- this is relevant only to ghc -e, which will exit with status 1
-- if the commmand was unsuccessful. GHCi will continue in either case.
runOneCommand :: (SomeException -> GHCi Bool) -> InputT GHCi (Maybe String)
-> InputT GHCi (Maybe Bool)
runOneCommand eh gCmd = do
-- run a previously queued command if there is one, otherwise get new
-- input from user
mb_cmd0 <- noSpace (lift queryQueue)
mb_cmd1 <- maybe (noSpace gCmd) (return . Just) mb_cmd0
case mb_cmd1 of
Nothing -> return Nothing
Just c -> ghciHandle (\e -> lift $ eh e >>= return . Just) $
handleSourceError printErrorAndFail
(doCommand c)
-- source error's are handled by runStmt
-- is the handler necessary here?
where
printErrorAndFail err = do
GHC.printException err
return $ Just False -- Exit ghc -e, but not GHCi
noSpace q = q >>= maybe (return Nothing)
(\c -> case removeSpaces c of
"" -> noSpace q
":{" -> multiLineCmd q
_ -> return (Just c) )
multiLineCmd q = do
st <- lift getGHCiState
let p = prompt st
lift $ setGHCiState st{ prompt = prompt2 st }
mb_cmd <- collectCommand q "" `GHC.gfinally` lift (getGHCiState >>= \st' -> setGHCiState st' { prompt = p })
return mb_cmd
-- we can't use removeSpaces for the sublines here, so
-- multiline commands are somewhat more brittle against
-- fileformat errors (such as \r in dos input on unix),
-- we get rid of any extra spaces for the ":}" test;
-- we also avoid silent failure if ":}" is not found;
-- and since there is no (?) valid occurrence of \r (as
-- opposed to its String representation, "\r") inside a
-- ghci command, we replace any such with ' ' (argh:-(
collectCommand q c = q >>=
maybe (liftIO (ioError collectError))
(\l->if removeSpaces l == ":}"
then return (Just c)
else collectCommand q (c ++ "\n" ++ map normSpace l))
where normSpace '\r' = ' '
normSpace x = x
-- SDM (2007-11-07): is userError the one to use here?
collectError = userError "unterminated multiline command :{ .. :}"
-- | Handle a line of input
doCommand :: String -> InputT GHCi (Maybe Bool)
-- command
doCommand stmt | (':' : cmd) <- removeSpaces stmt = do
result <- specialCommand cmd
case result of
True -> return Nothing
_ -> return $ Just True
-- haskell
doCommand stmt = do
-- if 'stmt' was entered via ':{' it will contain '\n's
let stmt_nl_cnt = length [ () | '\n' <- stmt ]
ml <- lift $ isOptionSet Multiline
if ml && stmt_nl_cnt == 0 -- don't trigger automatic multi-line mode for ':{'-multiline input
then do
fst_line_num <- lift (line_number <$> getGHCiState)
mb_stmt <- checkInputForLayout stmt gCmd
case mb_stmt of
Nothing -> return $ Just True
Just ml_stmt -> do
-- temporarily compensate line-number for multi-line input
result <- timeIt $ lift $ runStmtWithLineNum fst_line_num ml_stmt GHC.RunToCompletion
return $ Just result
else do -- single line input and :{-multiline input
last_line_num <- lift (line_number <$> getGHCiState)
-- reconstruct first line num from last line num and stmt
let fst_line_num | stmt_nl_cnt > 0 = last_line_num - (stmt_nl_cnt2 + 1)
| otherwise = last_line_num -- single line input
stmt_nl_cnt2 = length [ () | '\n' <- stmt' ]
stmt' = dropLeadingWhiteLines stmt -- runStmt doesn't like leading empty lines
-- temporarily compensate line-number for multi-line input
result <- timeIt $ lift $ runStmtWithLineNum fst_line_num stmt' GHC.RunToCompletion
return $ Just result
-- runStmt wrapper for temporarily overridden line-number
runStmtWithLineNum :: Int -> String -> SingleStep -> GHCi Bool
runStmtWithLineNum lnum stmt step = do
st0 <- getGHCiState
setGHCiState st0 { line_number = lnum }
result <- runStmt stmt step
-- restore original line_number
getGHCiState >>= \st -> setGHCiState st { line_number = line_number st0 }
return result
-- note: this is subtly different from 'unlines . dropWhile (all isSpace) . lines'
dropLeadingWhiteLines s | (l0,'\n':r) <- break (=='\n') s
, all isSpace l0 = dropLeadingWhiteLines r
| otherwise = s
-- #4316
-- lex the input. If there is an unclosed layout context, request input
checkInputForLayout :: String -> InputT GHCi (Maybe String)
-> InputT GHCi (Maybe String)
checkInputForLayout stmt getStmt = do
dflags' <- lift $ getDynFlags
let dflags = xopt_set dflags' Opt_AlternativeLayoutRule
st0 <- lift $ getGHCiState
let buf' = stringToStringBuffer stmt
loc = mkRealSrcLoc (fsLit (progname st0)) (line_number st0) 1
pstate = Lexer.mkPState dflags buf' loc
case Lexer.unP goToEnd pstate of
(Lexer.POk _ False) -> return $ Just stmt
_other -> do
st1 <- lift getGHCiState
let p = prompt st1
lift $ setGHCiState st1{ prompt = prompt2 st1 }
mb_stmt <- ghciHandle (\ex -> case fromException ex of
Just UserInterrupt -> return Nothing
_ -> case fromException ex of
Just ghce ->
do liftIO (print (ghce :: GhcException))
return Nothing
_other -> liftIO (Exception.throwIO ex))
getStmt
lift $ getGHCiState >>= \st' -> setGHCiState st'{ prompt = p }
-- the recursive call does not recycle parser state
-- as we use a new string buffer
case mb_stmt of
Nothing -> return Nothing
Just str -> if str == ""
then return $ Just stmt
else do
checkInputForLayout (stmt++"\n"++str) getStmt
where goToEnd = do
eof <- Lexer.nextIsEOF
if eof
then Lexer.activeContext
else Lexer.lexer False return >> goToEnd
enqueueCommands :: [String] -> GHCi ()
enqueueCommands cmds = do
st <- getGHCiState
setGHCiState st{ cmdqueue = cmds ++ cmdqueue st }
-- | If we one of these strings prefixes a command, then we treat it as a decl
-- rather than a stmt. NB that the appropriate decl prefixes depends on the
-- flag settings (Trac #9915)
declPrefixes :: DynFlags -> [String]
declPrefixes dflags = keywords ++ concat opt_keywords
where
keywords = [ "class ", "instance "
, "data ", "newtype ", "type "
, "default ", "default("
]
opt_keywords = [ ["foreign " | xopt Opt_ForeignFunctionInterface dflags]
, ["deriving " | xopt Opt_StandaloneDeriving dflags]
, ["pattern " | xopt Opt_PatternSynonyms dflags]
]
-- | Entry point to execute some haskell code from user.
-- The return value True indicates success, as in `runOneCommand`.
runStmt :: String -> SingleStep -> GHCi Bool
runStmt stmt step
-- empty; this should be impossible anyways since we filtered out
-- whitespace-only input in runOneCommand's noSpace
| null (filter (not.isSpace) stmt)
= return True
-- import
| stmt `looks_like` "import "
= do addImportToContext stmt; return True
| otherwise
= do dflags <- getDynFlags
if any (stmt `looks_like`) (declPrefixes dflags)
then run_decl
else run_stmt
where
run_decl =
do _ <- liftIO $ tryIO $ hFlushAll stdin
result <- GhciMonad.runDecls stmt
afterRunStmt (const True) (GHC.RunOk result)
run_stmt =
do -- In the new IO library, read handles buffer data even if the Handle
-- is set to NoBuffering. This causes problems for GHCi where there
-- are really two stdin Handles. So we flush any bufferred data in
-- GHCi's stdin Handle here (only relevant if stdin is attached to
-- a file, otherwise the read buffer can't be flushed).
_ <- liftIO $ tryIO $ hFlushAll stdin
m_result <- GhciMonad.runStmt stmt step
case m_result of
Nothing -> return False
Just result -> afterRunStmt (const True) result
s `looks_like` prefix = prefix `isPrefixOf` dropWhile isSpace s
-- Ignore leading spaces (see Trac #9914), so that
-- ghci> data T = T
-- (note leading spaces) works properly
-- | Clean up the GHCi environment after a statement has run
afterRunStmt :: (SrcSpan -> Bool) -> GHC.RunResult -> GHCi Bool
afterRunStmt _ (GHC.RunException e) = liftIO $ Exception.throwIO e
afterRunStmt step_here run_result = do
resumes <- GHC.getResumeContext
case run_result of
GHC.RunOk names -> do
show_types <- isOptionSet ShowType
when show_types $ printTypeOfNames names
GHC.RunBreak _ names mb_info
| isNothing mb_info ||
step_here (GHC.resumeSpan $ head resumes) -> do
mb_id_loc <- toBreakIdAndLocation mb_info
let bCmd = maybe "" ( \(_,l) -> onBreakCmd l ) mb_id_loc
if (null bCmd)
then printStoppedAtBreakInfo (head resumes) names
else enqueueCommands [bCmd]
-- run the command set with ":set stop <cmd>"
st <- getGHCiState
enqueueCommands [stop st]
return ()
| otherwise -> resume step_here GHC.SingleStep >>=
afterRunStmt step_here >> return ()
_ -> return ()
flushInterpBuffers
liftIO installSignalHandlers
b <- isOptionSet RevertCAFs
when b revertCAFs
return (case run_result of GHC.RunOk _ -> True; _ -> False)
toBreakIdAndLocation ::
Maybe GHC.BreakInfo -> GHCi (Maybe (Int, BreakLocation))
toBreakIdAndLocation Nothing = return Nothing
toBreakIdAndLocation (Just inf) = do
let md = GHC.breakInfo_module inf
nm = GHC.breakInfo_number inf
st <- getGHCiState
return $ listToMaybe [ id_loc | id_loc@(_,loc) <- breaks st,
breakModule loc == md,
breakTick loc == nm ]
printStoppedAtBreakInfo :: Resume -> [Name] -> GHCi ()
printStoppedAtBreakInfo res names = do
printForUser $ ptext (sLit "Stopped at") <+>
ppr (GHC.resumeSpan res)
-- printTypeOfNames session names
let namesSorted = sortBy compareNames names
tythings <- catMaybes `liftM` mapM GHC.lookupName namesSorted
docs <- mapM pprTypeAndContents [i | AnId i <- tythings]
printForUserPartWay $ vcat docs
printTypeOfNames :: [Name] -> GHCi ()
printTypeOfNames names
= mapM_ (printTypeOfName ) $ sortBy compareNames names
compareNames :: Name -> Name -> Ordering
n1 `compareNames` n2 = compareWith n1 `compare` compareWith n2
where compareWith n = (getOccString n, getSrcSpan n)
printTypeOfName :: Name -> GHCi ()
printTypeOfName n
= do maybe_tything <- GHC.lookupName n
case maybe_tything of
Nothing -> return ()
Just thing -> printTyThing thing
data MaybeCommand = GotCommand Command | BadCommand | NoLastCommand
-- | Entry point for execution a ':<command>' input from user
specialCommand :: String -> InputT GHCi Bool
specialCommand ('!':str) = lift $ shellEscape (dropWhile isSpace str)
specialCommand str = do
let (cmd,rest) = break isSpace str
maybe_cmd <- lift $ lookupCommand cmd
htxt <- lift $ short_help `fmap` getGHCiState
case maybe_cmd of
GotCommand (_,f,_) -> f (dropWhile isSpace rest)
BadCommand ->
do liftIO $ hPutStr stdout ("unknown command ':" ++ cmd ++ "'\n"
++ htxt)
return False
NoLastCommand ->
do liftIO $ hPutStr stdout ("there is no last command to perform\n"
++ htxt)
return False
shellEscape :: String -> GHCi Bool
shellEscape str = liftIO (system str >> return False)
lookupCommand :: String -> GHCi (MaybeCommand)
lookupCommand "" = do
st <- getGHCiState
case last_command st of
Just c -> return $ GotCommand c
Nothing -> return NoLastCommand
lookupCommand str = do
mc <- lookupCommand' str
st <- getGHCiState
setGHCiState st{ last_command = mc }
return $ case mc of
Just c -> GotCommand c
Nothing -> BadCommand
lookupCommand' :: String -> GHCi (Maybe Command)
lookupCommand' ":" = return Nothing
lookupCommand' str' = do
macros <- liftIO $ readIORef macros_ref
ghci_cmds <- ghci_commands `fmap` getGHCiState
let (str, xcmds) = case str' of
':' : rest -> (rest, []) -- "::" selects a builtin command
_ -> (str', macros) -- otherwise include macros in lookup
lookupExact s = find $ (s ==) . cmdName
lookupPrefix s = find $ (s `isPrefixOf`) . cmdName
builtinPfxMatch = lookupPrefix str ghci_cmds
-- first, look for exact match (while preferring macros); then, look
-- for first prefix match (preferring builtins), *unless* a macro
-- overrides the builtin; see #8305 for motivation
return $ lookupExact str xcmds <|>
lookupExact str ghci_cmds <|>
(builtinPfxMatch >>= \c -> lookupExact (cmdName c) xcmds) <|>
builtinPfxMatch <|>
lookupPrefix str xcmds
getCurrentBreakSpan :: GHCi (Maybe SrcSpan)
getCurrentBreakSpan = do
resumes <- GHC.getResumeContext
case resumes of
[] -> return Nothing
(r:_) -> do
let ix = GHC.resumeHistoryIx r
if ix == 0
then return (Just (GHC.resumeSpan r))
else do
let hist = GHC.resumeHistory r !! (ix-1)
pan <- GHC.getHistorySpan hist
return (Just pan)
getCurrentBreakModule :: GHCi (Maybe Module)
getCurrentBreakModule = do
resumes <- GHC.getResumeContext
case resumes of
[] -> return Nothing
(r:_) -> do
let ix = GHC.resumeHistoryIx r
if ix == 0
then return (GHC.breakInfo_module `liftM` GHC.resumeBreakInfo r)
else do
let hist = GHC.resumeHistory r !! (ix-1)
return $ Just $ GHC.getHistoryModule hist
-----------------------------------------------------------------------------
--
-- Commands
--
-----------------------------------------------------------------------------
noArgs :: GHCi () -> String -> GHCi ()
noArgs m "" = m
noArgs _ _ = liftIO $ putStrLn "This command takes no arguments"
withSandboxOnly :: String -> GHCi () -> GHCi ()
withSandboxOnly cmd this = do
dflags <- getDynFlags
if not (gopt Opt_GhciSandbox dflags)
then printForUser (text cmd <+>
ptext (sLit "is not supported with -fno-ghci-sandbox"))
else this
-----------------------------------------------------------------------------
-- :help
help :: String -> GHCi ()
help _ = do
txt <- long_help `fmap` getGHCiState
liftIO $ putStr txt
-----------------------------------------------------------------------------
-- :info
info :: Bool -> String -> InputT GHCi ()
info _ "" = throwGhcException (CmdLineError "syntax: ':i <thing-you-want-info-about>'")
info allInfo s = handleSourceError GHC.printException $ do
unqual <- GHC.getPrintUnqual
dflags <- getDynFlags
sdocs <- mapM (infoThing allInfo) (words s)
mapM_ (liftIO . putStrLn . showSDocForUser dflags unqual) sdocs
infoThing :: GHC.GhcMonad m => Bool -> String -> m SDoc
infoThing allInfo str = do
names <- GHC.parseName str
mb_stuffs <- mapM (GHC.getInfo allInfo) names
let filtered = filterOutChildren (\(t,_f,_ci,_fi) -> t) (catMaybes mb_stuffs)
return $ vcat (intersperse (text "") $ map pprInfo filtered)
-- Filter out names whose parent is also there Good
-- example is '[]', which is both a type and data
-- constructor in the same type
filterOutChildren :: (a -> TyThing) -> [a] -> [a]
filterOutChildren get_thing xs
= filterOut has_parent xs
where
all_names = mkNameSet (map (getName . get_thing) xs)
has_parent x = case tyThingParent_maybe (get_thing x) of
Just p -> getName p `elemNameSet` all_names
Nothing -> False
pprInfo :: (TyThing, Fixity, [GHC.ClsInst], [GHC.FamInst]) -> SDoc
pprInfo (thing, fixity, cls_insts, fam_insts)
= pprTyThingInContextLoc thing
$$ show_fixity
$$ vcat (map GHC.pprInstance cls_insts)
$$ vcat (map GHC.pprFamInst fam_insts)
where
show_fixity
| fixity == GHC.defaultFixity = empty
| otherwise = ppr fixity <+> pprInfixName (GHC.getName thing)
-----------------------------------------------------------------------------
-- :main
runMain :: String -> GHCi ()
runMain s = case toArgs s of
Left err -> liftIO (hPutStrLn stderr err)
Right args ->
do dflags <- getDynFlags
let main = fromMaybe "main" (mainFunIs dflags)
-- Wrap the main function in 'void' to discard its value instead
-- of printing it (#9086). See Haskell 2010 report Chapter 5.
doWithArgs args $ "Control.Monad.void (" ++ main ++ ")"
-----------------------------------------------------------------------------
-- :run
runRun :: String -> GHCi ()
runRun s = case toCmdArgs s of
Left err -> liftIO (hPutStrLn stderr err)
Right (cmd, args) -> doWithArgs args cmd
doWithArgs :: [String] -> String -> GHCi ()
doWithArgs args cmd = enqueueCommands ["System.Environment.withArgs " ++
show args ++ " (" ++ cmd ++ ")"]
-----------------------------------------------------------------------------
-- :cd
changeDirectory :: String -> InputT GHCi ()
changeDirectory "" = do
-- :cd on its own changes to the user's home directory
either_dir <- liftIO $ tryIO getHomeDirectory
case either_dir of
Left _e -> return ()
Right dir -> changeDirectory dir
changeDirectory dir = do
graph <- GHC.getModuleGraph
when (not (null graph)) $
liftIO $ putStrLn "Warning: changing directory causes all loaded modules to be unloaded,\nbecause the search path has changed."
GHC.setTargets []
_ <- GHC.load LoadAllTargets
lift $ setContextAfterLoad False []
GHC.workingDirectoryChanged
dir' <- expandPath dir
liftIO $ setCurrentDirectory dir'
trySuccess :: GHC.GhcMonad m => m SuccessFlag -> m SuccessFlag
trySuccess act =
handleSourceError (\e -> do GHC.printException e
return Failed) $ do
act
-----------------------------------------------------------------------------
-- :edit
editFile :: String -> InputT GHCi ()
editFile str =
do file <- if null str then lift chooseEditFile else expandPath str
st <- lift getGHCiState
errs <- liftIO $ readIORef $ lastErrorLocations st
let cmd = editor st
when (null cmd)
$ throwGhcException (CmdLineError "editor not set, use :set editor")
lineOpt <- liftIO $ do
curFileErrs <- filterM (\(f, _) -> unpackFS f `sameFile` file) errs
return $ case curFileErrs of
(_, line):_ -> " +" ++ show line
_ -> ""
let cmdArgs = ' ':(file ++ lineOpt)
code <- liftIO $ system (cmd ++ cmdArgs)
when (code == ExitSuccess)
$ reloadModule ""
-- The user didn't specify a file so we pick one for them.
-- Our strategy is to pick the first module that failed to load,
-- or otherwise the first target.
--
-- XXX: Can we figure out what happened if the depndecy analysis fails
-- (e.g., because the porgrammeer mistyped the name of a module)?
-- XXX: Can we figure out the location of an error to pass to the editor?
-- XXX: if we could figure out the list of errors that occured during the
-- last load/reaload, then we could start the editor focused on the first
-- of those.
chooseEditFile :: GHCi String
chooseEditFile =
do let hasFailed x = fmap not $ GHC.isLoaded $ GHC.ms_mod_name x
graph <- GHC.getModuleGraph
failed_graph <- filterM hasFailed graph
let order g = flattenSCCs $ GHC.topSortModuleGraph True g Nothing
pick xs = case xs of
x : _ -> GHC.ml_hs_file (GHC.ms_location x)
_ -> Nothing
case pick (order failed_graph) of
Just file -> return file
Nothing ->
do targets <- GHC.getTargets
case msum (map fromTarget targets) of
Just file -> return file
Nothing -> throwGhcException (CmdLineError "No files to edit.")
where fromTarget (GHC.Target (GHC.TargetFile f _) _ _) = Just f
fromTarget _ = Nothing -- when would we get a module target?
-----------------------------------------------------------------------------
-- :def
defineMacro :: Bool{-overwrite-} -> String -> GHCi ()
defineMacro _ (':':_) =
liftIO $ putStrLn "macro name cannot start with a colon"
defineMacro overwrite s = do
let (macro_name, definition) = break isSpace s
macros <- liftIO (readIORef macros_ref)
let defined = map cmdName macros
if (null macro_name)
then if null defined
then liftIO $ putStrLn "no macros defined"
else liftIO $ putStr ("the following macros are defined:\n" ++
unlines defined)
else do
if (not overwrite && macro_name `elem` defined)
then throwGhcException (CmdLineError
("macro '" ++ macro_name ++ "' is already defined"))
else do
let filtered = [ cmd | cmd <- macros, cmdName cmd /= macro_name ]
-- give the expression a type signature, so we can be sure we're getting
-- something of the right type.
let new_expr = '(' : definition ++ ") :: String -> IO String"
-- compile the expression
handleSourceError (\e -> GHC.printException e) $
do
hv <- GHC.compileExpr new_expr
liftIO (writeIORef macros_ref -- later defined macros have precedence
((macro_name, lift . runMacro hv, noCompletion) : filtered))
runMacro :: GHC.HValue{-String -> IO String-} -> String -> GHCi Bool
runMacro fun s = do
str <- liftIO ((unsafeCoerce# fun :: String -> IO String) s)
-- make sure we force any exceptions in the result, while we are still
-- inside the exception handler for commands:
seqList str (return ())
enqueueCommands (lines str)
return False
-----------------------------------------------------------------------------
-- :undef
undefineMacro :: String -> GHCi ()
undefineMacro str = mapM_ undef (words str)
where undef macro_name = do
cmds <- liftIO (readIORef macros_ref)
if (macro_name `notElem` map cmdName cmds)
then throwGhcException (CmdLineError
("macro '" ++ macro_name ++ "' is not defined"))
else do
liftIO (writeIORef macros_ref (filter ((/= macro_name) . cmdName) cmds))
-----------------------------------------------------------------------------
-- :cmd
cmdCmd :: String -> GHCi ()
cmdCmd str = do
let expr = '(' : str ++ ") :: IO String"
handleSourceError (\e -> GHC.printException e) $
do
hv <- GHC.compileExpr expr
cmds <- liftIO $ (unsafeCoerce# hv :: IO String)
enqueueCommands (lines cmds)
return ()
-----------------------------------------------------------------------------
-- :check
checkModule :: String -> InputT GHCi ()
checkModule m = do
let modl = GHC.mkModuleName m
ok <- handleSourceError (\e -> GHC.printException e >> return False) $ do
r <- GHC.typecheckModule =<< GHC.parseModule =<< GHC.getModSummary modl
dflags <- getDynFlags
liftIO $ putStrLn $ showSDoc dflags $
case GHC.moduleInfo r of
cm | Just scope <- GHC.modInfoTopLevelScope cm ->
let
(loc, glob) = ASSERT( all isExternalName scope )
partition ((== modl) . GHC.moduleName . GHC.nameModule) scope
in
(text "global names: " <+> ppr glob) $$
(text "local names: " <+> ppr loc)
_ -> empty
return True
afterLoad (successIf ok) False
-----------------------------------------------------------------------------
-- :load, :add, :reload
loadModule :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule fs = timeIt (loadModule' fs)
loadModule_ :: [FilePath] -> InputT GHCi ()
loadModule_ fs = loadModule (zip fs (repeat Nothing)) >> return ()
loadModule' :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule' files = do
let (filenames, phases) = unzip files
exp_filenames <- mapM expandPath filenames
let files' = zip exp_filenames phases
targets <- mapM (uncurry GHC.guessTarget) files'
-- NOTE: we used to do the dependency anal first, so that if it
-- fails we didn't throw away the current set of modules. This would
-- require some re-working of the GHC interface, so we'll leave it
-- as a ToDo for now.
-- unload first
_ <- GHC.abandonAll
lift discardActiveBreakPoints
GHC.setTargets []
_ <- GHC.load LoadAllTargets
GHC.setTargets targets
doLoad False LoadAllTargets
-- :add
addModule :: [FilePath] -> InputT GHCi ()
addModule files = do
lift revertCAFs -- always revert CAFs on load/add.
files' <- mapM expandPath files
targets <- mapM (\m -> GHC.guessTarget m Nothing) files'
-- remove old targets with the same id; e.g. for :add *M
mapM_ GHC.removeTarget [ tid | Target tid _ _ <- targets ]
mapM_ GHC.addTarget targets
_ <- doLoad False LoadAllTargets
return ()
-- :reload
reloadModule :: String -> InputT GHCi ()
reloadModule m = do
_ <- doLoad True $
if null m then LoadAllTargets
else LoadUpTo (GHC.mkModuleName m)
return ()
doLoad :: Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoad retain_context howmuch = do
-- turn off breakpoints before we load: we can't turn them off later, because
-- the ModBreaks will have gone away.
lift discardActiveBreakPoints
lift resetLastErrorLocations
-- Enable buffering stdout and stderr as we're compiling. Keeping these
-- handles unbuffered will just slow the compilation down, especially when
-- compiling in parallel.
gbracket (liftIO $ do hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering)
(\_ ->
liftIO $ do hSetBuffering stdout NoBuffering
hSetBuffering stderr NoBuffering) $ \_ -> do
ok <- trySuccess $ GHC.load howmuch
afterLoad ok retain_context
return ok
afterLoad :: SuccessFlag
-> Bool -- keep the remembered_ctx, as far as possible (:reload)
-> InputT GHCi ()
afterLoad ok retain_context = do
lift revertCAFs -- always revert CAFs on load.
lift discardTickArrays
loaded_mod_summaries <- getLoadedModules
let loaded_mods = map GHC.ms_mod loaded_mod_summaries
modulesLoadedMsg ok loaded_mods
lift $ setContextAfterLoad retain_context loaded_mod_summaries
setContextAfterLoad :: Bool -> [GHC.ModSummary] -> GHCi ()
setContextAfterLoad keep_ctxt [] = do
setContextKeepingPackageModules keep_ctxt []
setContextAfterLoad keep_ctxt ms = do
-- load a target if one is available, otherwise load the topmost module.
targets <- GHC.getTargets
case [ m | Just m <- map (findTarget ms) targets ] of
[] ->
let graph' = flattenSCCs (GHC.topSortModuleGraph True ms Nothing) in
load_this (last graph')
(m:_) ->
load_this m
where
findTarget mds t
= case filter (`matches` t) mds of
[] -> Nothing
(m:_) -> Just m
summary `matches` Target (TargetModule m) _ _
= GHC.ms_mod_name summary == m
summary `matches` Target (TargetFile f _) _ _
| Just f' <- GHC.ml_hs_file (GHC.ms_location summary) = f == f'
_ `matches` _
= False
load_this summary | m <- GHC.ms_mod summary = do
is_interp <- GHC.moduleIsInterpreted m
dflags <- getDynFlags
let star_ok = is_interp && not (safeLanguageOn dflags)
-- We import the module with a * iff
-- - it is interpreted, and
-- - -XSafe is off (it doesn't allow *-imports)
let new_ctx | star_ok = [mkIIModule (GHC.moduleName m)]
| otherwise = [mkIIDecl (GHC.moduleName m)]
setContextKeepingPackageModules keep_ctxt new_ctx
-- | Keep any package modules (except Prelude) when changing the context.
setContextKeepingPackageModules
:: Bool -- True <=> keep all of remembered_ctx
-- False <=> just keep package imports
-> [InteractiveImport] -- new context
-> GHCi ()
setContextKeepingPackageModules keep_ctx trans_ctx = do
st <- getGHCiState
let rem_ctx = remembered_ctx st
new_rem_ctx <- if keep_ctx then return rem_ctx
else keepPackageImports rem_ctx
setGHCiState st{ remembered_ctx = new_rem_ctx,
transient_ctx = filterSubsumed new_rem_ctx trans_ctx }
setGHCContextFromGHCiState
-- | Filters a list of 'InteractiveImport', clearing out any home package
-- imports so only imports from external packages are preserved. ('IIModule'
-- counts as a home package import, because we are only able to bring a
-- full top-level into scope when the source is available.)
keepPackageImports :: [InteractiveImport] -> GHCi [InteractiveImport]
keepPackageImports = filterM is_pkg_import
where
is_pkg_import :: InteractiveImport -> GHCi Bool
is_pkg_import (IIModule _) = return False
is_pkg_import (IIDecl d)
= do e <- gtry $ GHC.findModule mod_name (ideclPkgQual d)
case e :: Either SomeException Module of
Left _ -> return False
Right m -> return (not (isHomeModule m))
where
mod_name = unLoc (ideclName d)
modulesLoadedMsg :: SuccessFlag -> [Module] -> InputT GHCi ()
modulesLoadedMsg ok mods = do
dflags <- getDynFlags
unqual <- GHC.getPrintUnqual
let mod_commas
| null mods = text "none."
| otherwise = hsep (
punctuate comma (map ppr mods)) <> text "."
status = case ok of
Failed -> text "Failed"
Succeeded -> text "Ok"
msg = status <> text ", modules loaded:" <+> mod_commas
when (verbosity dflags > 0) $
liftIO $ putStrLn $ showSDocForUser dflags unqual msg
-----------------------------------------------------------------------------
-- :type
typeOfExpr :: String -> InputT GHCi ()
typeOfExpr str
= handleSourceError GHC.printException
$ do
ty <- GHC.exprType str
printForUser $ sep [text str, nest 2 (dcolon <+> pprTypeForUser ty)]
-----------------------------------------------------------------------------
-- :kind
kindOfType :: Bool -> String -> InputT GHCi ()
kindOfType norm str
= handleSourceError GHC.printException
$ do
(ty, kind) <- GHC.typeKind norm str
printForUser $ vcat [ text str <+> dcolon <+> pprTypeForUser kind
, ppWhen norm $ equals <+> pprTypeForUser ty ]
-----------------------------------------------------------------------------
-- :quit
quit :: String -> InputT GHCi Bool
quit _ = return True
-----------------------------------------------------------------------------
-- :script
-- running a script file #1363
scriptCmd :: String -> InputT GHCi ()
scriptCmd ws = do
case words ws of
[s] -> runScript s
_ -> throwGhcException (CmdLineError "syntax: :script <filename>")
runScript :: String -- ^ filename
-> InputT GHCi ()
runScript filename = do
filename' <- expandPath filename
either_script <- liftIO $ tryIO (openFile filename' ReadMode)
case either_script of
Left _err -> throwGhcException (CmdLineError $ "IO error: \""++filename++"\" "
++(ioeGetErrorString _err))
Right script -> do
st <- lift $ getGHCiState
let prog = progname st
line = line_number st
lift $ setGHCiState st{progname=filename',line_number=0}
scriptLoop script
liftIO $ hClose script
new_st <- lift $ getGHCiState
lift $ setGHCiState new_st{progname=prog,line_number=line}
where scriptLoop script = do
res <- runOneCommand handler $ fileLoop script
case res of
Nothing -> return ()
Just s -> if s
then scriptLoop script
else return ()
-----------------------------------------------------------------------------
-- :issafe
-- Displaying Safe Haskell properties of a module
isSafeCmd :: String -> InputT GHCi ()
isSafeCmd m =
case words m of
[s] | looksLikeModuleName s -> do
md <- lift $ lookupModule s
isSafeModule md
[] -> do md <- guessCurrentModule "issafe"
isSafeModule md
_ -> throwGhcException (CmdLineError "syntax: :issafe <module>")
isSafeModule :: Module -> InputT GHCi ()
isSafeModule m = do
mb_mod_info <- GHC.getModuleInfo m
when (isNothing mb_mod_info)
(throwGhcException $ CmdLineError $ "unknown module: " ++ mname)
dflags <- getDynFlags
let iface = GHC.modInfoIface $ fromJust mb_mod_info
when (isNothing iface)
(throwGhcException $ CmdLineError $ "can't load interface file for module: " ++
(GHC.moduleNameString $ GHC.moduleName m))
(msafe, pkgs) <- GHC.moduleTrustReqs m
let trust = showPpr dflags $ getSafeMode $ GHC.mi_trust $ fromJust iface
pkg = if packageTrusted dflags m then "trusted" else "untrusted"
(good, bad) = tallyPkgs dflags pkgs
-- print info to user...
liftIO $ putStrLn $ "Trust type is (Module: " ++ trust ++ ", Package: " ++ pkg ++ ")"
liftIO $ putStrLn $ "Package Trust: " ++ (if packageTrustOn dflags then "On" else "Off")
when (not $ null good)
(liftIO $ putStrLn $ "Trusted package dependencies (trusted): " ++
(intercalate ", " $ map (showPpr dflags) good))
case msafe && null bad of
True -> liftIO $ putStrLn $ mname ++ " is trusted!"
False -> do
when (not $ null bad)
(liftIO $ putStrLn $ "Trusted package dependencies (untrusted): "
++ (intercalate ", " $ map (showPpr dflags) bad))
liftIO $ putStrLn $ mname ++ " is NOT trusted!"
where
mname = GHC.moduleNameString $ GHC.moduleName m
packageTrusted dflags md
| thisPackage dflags == modulePackageKey md = True
| otherwise = trusted $ getPackageDetails dflags (modulePackageKey md)
tallyPkgs dflags deps | not (packageTrustOn dflags) = ([], [])
| otherwise = partition part deps
where part pkg = trusted $ getPackageDetails dflags pkg
-----------------------------------------------------------------------------
-- :browse
-- Browsing a module's contents
browseCmd :: Bool -> String -> InputT GHCi ()
browseCmd bang m =
case words m of
['*':s] | looksLikeModuleName s -> do
md <- lift $ wantInterpretedModule s
browseModule bang md False
[s] | looksLikeModuleName s -> do
md <- lift $ lookupModule s
browseModule bang md True
[] -> do md <- guessCurrentModule ("browse" ++ if bang then "!" else "")
browseModule bang md True
_ -> throwGhcException (CmdLineError "syntax: :browse <module>")
guessCurrentModule :: String -> InputT GHCi Module
-- Guess which module the user wants to browse. Pick
-- modules that are interpreted first. The most
-- recently-added module occurs last, it seems.
guessCurrentModule cmd
= do imports <- GHC.getContext
when (null imports) $ throwGhcException $
CmdLineError (':' : cmd ++ ": no current module")
case (head imports) of
IIModule m -> GHC.findModule m Nothing
IIDecl d -> GHC.findModule (unLoc (ideclName d)) (ideclPkgQual d)
-- without bang, show items in context of their parents and omit children
-- with bang, show class methods and data constructors separately, and
-- indicate import modules, to aid qualifying unqualified names
-- with sorted, sort items alphabetically
browseModule :: Bool -> Module -> Bool -> InputT GHCi ()
browseModule bang modl exports_only = do
-- :browse reports qualifiers wrt current context
unqual <- GHC.getPrintUnqual
mb_mod_info <- GHC.getModuleInfo modl
case mb_mod_info of
Nothing -> throwGhcException (CmdLineError ("unknown module: " ++
GHC.moduleNameString (GHC.moduleName modl)))
Just mod_info -> do
dflags <- getDynFlags
let names
| exports_only = GHC.modInfoExports mod_info
| otherwise = GHC.modInfoTopLevelScope mod_info
`orElse` []
-- sort alphabetically name, but putting locally-defined
-- identifiers first. We would like to improve this; see #1799.
sorted_names = loc_sort local ++ occ_sort external
where
(local,external) = ASSERT( all isExternalName names )
partition ((==modl) . nameModule) names
occ_sort = sortBy (compare `on` nameOccName)
-- try to sort by src location. If the first name in our list
-- has a good source location, then they all should.
loc_sort ns
| n:_ <- ns, isGoodSrcSpan (nameSrcSpan n)
= sortBy (compare `on` nameSrcSpan) ns
| otherwise
= occ_sort ns
mb_things <- mapM GHC.lookupName sorted_names
let filtered_things = filterOutChildren (\t -> t) (catMaybes mb_things)
rdr_env <- GHC.getGRE
let things | bang = catMaybes mb_things
| otherwise = filtered_things
pretty | bang = pprTyThing
| otherwise = pprTyThingInContext
labels [] = text "-- not currently imported"
labels l = text $ intercalate "\n" $ map qualifier l
qualifier :: Maybe [ModuleName] -> String
qualifier = maybe "-- defined locally"
(("-- imported via "++) . intercalate ", "
. map GHC.moduleNameString)
importInfo = RdrName.getGRE_NameQualifier_maybes rdr_env
modNames :: [[Maybe [ModuleName]]]
modNames = map (importInfo . GHC.getName) things
-- annotate groups of imports with their import modules
-- the default ordering is somewhat arbitrary, so we group
-- by header and sort groups; the names themselves should
-- really come in order of source appearance.. (trac #1799)
annotate mts = concatMap (\(m,ts)->labels m:ts)
$ sortBy cmpQualifiers $ grp mts
where cmpQualifiers =
compare `on` (map (fmap (map moduleNameFS)) . fst)
grp [] = []
grp mts@((m,_):_) = (m,map snd g) : grp ng
where (g,ng) = partition ((==m).fst) mts
let prettyThings, prettyThings' :: [SDoc]
prettyThings = map pretty things
prettyThings' | bang = annotate $ zip modNames prettyThings
| otherwise = prettyThings
liftIO $ putStrLn $ showSDocForUser dflags unqual (vcat prettyThings')
-- ToDo: modInfoInstances currently throws an exception for
-- package modules. When it works, we can do this:
-- $$ vcat (map GHC.pprInstance (GHC.modInfoInstances mod_info))
-----------------------------------------------------------------------------
-- :module
-- Setting the module context. For details on context handling see
-- "remembered_ctx" and "transient_ctx" in GhciMonad.
moduleCmd :: String -> GHCi ()
moduleCmd str
| all sensible strs = cmd
| otherwise = throwGhcException (CmdLineError "syntax: :module [+/-] [*]M1 ... [*]Mn")
where
(cmd, strs) =
case str of
'+':stuff -> rest addModulesToContext stuff
'-':stuff -> rest remModulesFromContext stuff
stuff -> rest setContext stuff
rest op stuff = (op as bs, stuffs)
where (as,bs) = partitionWith starred stuffs
stuffs = words stuff
sensible ('*':m) = looksLikeModuleName m
sensible m = looksLikeModuleName m
starred ('*':m) = Left (GHC.mkModuleName m)
starred m = Right (GHC.mkModuleName m)
-- -----------------------------------------------------------------------------
-- Four ways to manipulate the context:
-- (a) :module +<stuff>: addModulesToContext
-- (b) :module -<stuff>: remModulesFromContext
-- (c) :module <stuff>: setContext
-- (d) import <module>...: addImportToContext
addModulesToContext :: [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext starred unstarred = restoreContextOnFailure $ do
addModulesToContext_ starred unstarred
addModulesToContext_ :: [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext_ starred unstarred = do
mapM_ addII (map mkIIModule starred ++ map mkIIDecl unstarred)
setGHCContextFromGHCiState
remModulesFromContext :: [ModuleName] -> [ModuleName] -> GHCi ()
remModulesFromContext starred unstarred = do
-- we do *not* call restoreContextOnFailure here. If the user
-- is trying to fix up a context that contains errors by removing
-- modules, we don't want GHC to silently put them back in again.
mapM_ rm (starred ++ unstarred)
setGHCContextFromGHCiState
where
rm :: ModuleName -> GHCi ()
rm str = do
m <- moduleName <$> lookupModuleName str
let filt = filter ((/=) m . iiModuleName)
modifyGHCiState $ \st ->
st { remembered_ctx = filt (remembered_ctx st)
, transient_ctx = filt (transient_ctx st) }
setContext :: [ModuleName] -> [ModuleName] -> GHCi ()
setContext starred unstarred = restoreContextOnFailure $ do
modifyGHCiState $ \st -> st { remembered_ctx = [], transient_ctx = [] }
-- delete the transient context
addModulesToContext_ starred unstarred
addImportToContext :: String -> GHCi ()
addImportToContext str = restoreContextOnFailure $ do
idecl <- GHC.parseImportDecl str
addII (IIDecl idecl) -- #5836
setGHCContextFromGHCiState
-- Util used by addImportToContext and addModulesToContext
addII :: InteractiveImport -> GHCi ()
addII iidecl = do
checkAdd iidecl
modifyGHCiState $ \st ->
st { remembered_ctx = addNotSubsumed iidecl (remembered_ctx st)
, transient_ctx = filter (not . (iidecl `iiSubsumes`))
(transient_ctx st)
}
-- Sometimes we can't tell whether an import is valid or not until
-- we finally call 'GHC.setContext'. e.g.
--
-- import System.IO (foo)
--
-- will fail because System.IO does not export foo. In this case we
-- don't want to store the import in the context permanently, so we
-- catch the failure from 'setGHCContextFromGHCiState' and set the
-- context back to what it was.
--
-- See #6007
--
restoreContextOnFailure :: GHCi a -> GHCi a
restoreContextOnFailure do_this = do
st <- getGHCiState
let rc = remembered_ctx st; tc = transient_ctx st
do_this `gonException` (modifyGHCiState $ \st' ->
st' { remembered_ctx = rc, transient_ctx = tc })
-- -----------------------------------------------------------------------------
-- Validate a module that we want to add to the context
checkAdd :: InteractiveImport -> GHCi ()
checkAdd ii = do
dflags <- getDynFlags
let safe = safeLanguageOn dflags
case ii of
IIModule modname
| safe -> throwGhcException $ CmdLineError "can't use * imports with Safe Haskell"
| otherwise -> wantInterpretedModuleName modname >> return ()
IIDecl d -> do
let modname = unLoc (ideclName d)
pkgqual = ideclPkgQual d
m <- GHC.lookupModule modname pkgqual
when safe $ do
t <- GHC.isModuleTrusted m
when (not t) $ throwGhcException $ ProgramError $ ""
-- -----------------------------------------------------------------------------
-- Update the GHC API's view of the context
-- | Sets the GHC context from the GHCi state. The GHC context is
-- always set this way, we never modify it incrementally.
--
-- We ignore any imports for which the ModuleName does not currently
-- exist. This is so that the remembered_ctx can contain imports for
-- modules that are not currently loaded, perhaps because we just did
-- a :reload and encountered errors.
--
-- Prelude is added if not already present in the list. Therefore to
-- override the implicit Prelude import you can say 'import Prelude ()'
-- at the prompt, just as in Haskell source.
--
setGHCContextFromGHCiState :: GHCi ()
setGHCContextFromGHCiState = do
st <- getGHCiState
-- re-use checkAdd to check whether the module is valid. If the
-- module does not exist, we do *not* want to print an error
-- here, we just want to silently keep the module in the context
-- until such time as the module reappears again. So we ignore
-- the actual exception thrown by checkAdd, using tryBool to
-- turn it into a Bool.
iidecls <- filterM (tryBool.checkAdd) (transient_ctx st ++ remembered_ctx st)
dflags <- GHC.getSessionDynFlags
GHC.setContext $
if xopt Opt_ImplicitPrelude dflags && not (any isPreludeImport iidecls)
then iidecls ++ [implicitPreludeImport]
else iidecls
-- XXX put prel at the end, so that guessCurrentModule doesn't pick it up.
-- -----------------------------------------------------------------------------
-- Utils on InteractiveImport
mkIIModule :: ModuleName -> InteractiveImport
mkIIModule = IIModule
mkIIDecl :: ModuleName -> InteractiveImport
mkIIDecl = IIDecl . simpleImportDecl
iiModules :: [InteractiveImport] -> [ModuleName]
iiModules is = [m | IIModule m <- is]
iiModuleName :: InteractiveImport -> ModuleName
iiModuleName (IIModule m) = m
iiModuleName (IIDecl d) = unLoc (ideclName d)
preludeModuleName :: ModuleName
preludeModuleName = GHC.mkModuleName "Prelude"
implicitPreludeImport :: InteractiveImport
implicitPreludeImport = IIDecl (simpleImportDecl preludeModuleName)
isPreludeImport :: InteractiveImport -> Bool
isPreludeImport (IIModule {}) = True
isPreludeImport (IIDecl d) = unLoc (ideclName d) == preludeModuleName
addNotSubsumed :: InteractiveImport
-> [InteractiveImport] -> [InteractiveImport]
addNotSubsumed i is
| any (`iiSubsumes` i) is = is
| otherwise = i : filter (not . (i `iiSubsumes`)) is
-- | @filterSubsumed is js@ returns the elements of @js@ not subsumed
-- by any of @is@.
filterSubsumed :: [InteractiveImport] -> [InteractiveImport]
-> [InteractiveImport]
filterSubsumed is js = filter (\j -> not (any (`iiSubsumes` j) is)) js
-- | Returns True if the left import subsumes the right one. Doesn't
-- need to be 100% accurate, conservatively returning False is fine.
-- (EXCEPT: (IIModule m) *must* subsume itself, otherwise a panic in
-- plusProv will ensue (#5904))
--
-- Note that an IIModule does not necessarily subsume an IIDecl,
-- because e.g. a module might export a name that is only available
-- qualified within the module itself.
--
-- Note that 'import M' does not necessarily subsume 'import M(foo)',
-- because M might not export foo and we want an error to be produced
-- in that case.
--
iiSubsumes :: InteractiveImport -> InteractiveImport -> Bool
iiSubsumes (IIModule m1) (IIModule m2) = m1==m2
iiSubsumes (IIDecl d1) (IIDecl d2) -- A bit crude
= unLoc (ideclName d1) == unLoc (ideclName d2)
&& ideclAs d1 == ideclAs d2
&& (not (ideclQualified d1) || ideclQualified d2)
&& (ideclHiding d1 `hidingSubsumes` ideclHiding d2)
where
_ `hidingSubsumes` Just (False,L _ []) = True
Just (False, L _ xs) `hidingSubsumes` Just (False,L _ ys)
= all (`elem` xs) ys
h1 `hidingSubsumes` h2 = h1 == h2
iiSubsumes _ _ = False
----------------------------------------------------------------------------
-- :set
-- set options in the interpreter. Syntax is exactly the same as the
-- ghc command line, except that certain options aren't available (-C,
-- -E etc.)
--
-- This is pretty fragile: most options won't work as expected. ToDo:
-- figure out which ones & disallow them.
setCmd :: String -> GHCi ()
setCmd "" = showOptions False
setCmd "-a" = showOptions True
setCmd str
= case getCmd str of
Right ("args", rest) ->
case toArgs rest of
Left err -> liftIO (hPutStrLn stderr err)
Right args -> setArgs args
Right ("prog", rest) ->
case toArgs rest of
Right [prog] -> setProg prog
_ -> liftIO (hPutStrLn stderr "syntax: :set prog <progname>")
Right ("prompt", rest) -> setPrompt $ dropWhile isSpace rest
Right ("prompt2", rest) -> setPrompt2 $ dropWhile isSpace rest
Right ("editor", rest) -> setEditor $ dropWhile isSpace rest
Right ("stop", rest) -> setStop $ dropWhile isSpace rest
_ -> case toArgs str of
Left err -> liftIO (hPutStrLn stderr err)
Right wds -> setOptions wds
setiCmd :: String -> GHCi ()
setiCmd "" = GHC.getInteractiveDynFlags >>= liftIO . showDynFlags False
setiCmd "-a" = GHC.getInteractiveDynFlags >>= liftIO . showDynFlags True
setiCmd str =
case toArgs str of
Left err -> liftIO (hPutStrLn stderr err)
Right wds -> newDynFlags True wds
showOptions :: Bool -> GHCi ()
showOptions show_all
= do st <- getGHCiState
dflags <- getDynFlags
let opts = options st
liftIO $ putStrLn (showSDoc dflags (
text "options currently set: " <>
if null opts
then text "none."
else hsep (map (\o -> char '+' <> text (optToStr o)) opts)
))
getDynFlags >>= liftIO . showDynFlags show_all
showDynFlags :: Bool -> DynFlags -> IO ()
showDynFlags show_all dflags = do
showLanguages' show_all dflags
putStrLn $ showSDoc dflags $
text "GHCi-specific dynamic flag settings:" $$
nest 2 (vcat (map (setting gopt) ghciFlags))
putStrLn $ showSDoc dflags $
text "other dynamic, non-language, flag settings:" $$
nest 2 (vcat (map (setting gopt) others))
putStrLn $ showSDoc dflags $
text "warning settings:" $$
nest 2 (vcat (map (setting wopt) DynFlags.fWarningFlags))
where
setting test flag
| quiet = empty
| is_on = fstr name
| otherwise = fnostr name
where name = flagSpecName flag
f = flagSpecFlag flag
is_on = test f dflags
quiet = not show_all && test f default_dflags == is_on
default_dflags = defaultDynFlags (settings dflags)
fstr str = text "-f" <> text str
fnostr str = text "-fno-" <> text str
(ghciFlags,others) = partition (\f -> flagSpecFlag f `elem` flgs)
DynFlags.fFlags
flgs = [ Opt_PrintExplicitForalls
, Opt_PrintExplicitKinds
, Opt_PrintBindResult
, Opt_BreakOnException
, Opt_BreakOnError
, Opt_PrintEvldWithShow
]
setArgs, setOptions :: [String] -> GHCi ()
setProg, setEditor, setStop :: String -> GHCi ()
setArgs args = do
st <- getGHCiState
setGHCiState st{ GhciMonad.args = args }
setProg prog = do
st <- getGHCiState
setGHCiState st{ progname = prog }
setEditor cmd = do
st <- getGHCiState
setGHCiState st{ editor = cmd }
setStop str@(c:_) | isDigit c
= do let (nm_str,rest) = break (not.isDigit) str
nm = read nm_str
st <- getGHCiState
let old_breaks = breaks st
if all ((/= nm) . fst) old_breaks
then printForUser (text "Breakpoint" <+> ppr nm <+>
text "does not exist")
else do
let new_breaks = map fn old_breaks
fn (i,loc) | i == nm = (i,loc { onBreakCmd = dropWhile isSpace rest })
| otherwise = (i,loc)
setGHCiState st{ breaks = new_breaks }
setStop cmd = do
st <- getGHCiState
setGHCiState st{ stop = cmd }
setPrompt :: String -> GHCi ()
setPrompt = setPrompt_ f err
where
f v st = st { prompt = v }
err st = "syntax: :set prompt <prompt>, currently \"" ++ prompt st ++ "\""
setPrompt2 :: String -> GHCi ()
setPrompt2 = setPrompt_ f err
where
f v st = st { prompt2 = v }
err st = "syntax: :set prompt2 <prompt>, currently \"" ++ prompt2 st ++ "\""
setPrompt_ :: (String -> GHCiState -> GHCiState) -> (GHCiState -> String) -> String -> GHCi ()
setPrompt_ f err value = do
st <- getGHCiState
if null value
then liftIO $ hPutStrLn stderr $ err st
else case value of
'\"' : _ -> case reads value of
[(value', xs)] | all isSpace xs ->
setGHCiState $ f value' st
_ ->
liftIO $ hPutStrLn stderr "Can't parse prompt string. Use Haskell syntax."
_ -> setGHCiState $ f value st
setOptions wds =
do -- first, deal with the GHCi opts (+s, +t, etc.)
let (plus_opts, minus_opts) = partitionWith isPlus wds
mapM_ setOpt plus_opts
-- then, dynamic flags
newDynFlags False minus_opts
newDynFlags :: Bool -> [String] -> GHCi ()
newDynFlags interactive_only minus_opts = do
let lopts = map noLoc minus_opts
idflags0 <- GHC.getInteractiveDynFlags
(idflags1, leftovers, warns) <- GHC.parseDynamicFlags idflags0 lopts
liftIO $ handleFlagWarnings idflags1 warns
when (not $ null leftovers)
(throwGhcException . CmdLineError
$ "Some flags have not been recognized: "
++ (concat . intersperse ", " $ map unLoc leftovers))
when (interactive_only &&
packageFlags idflags1 /= packageFlags idflags0) $ do
liftIO $ hPutStrLn stderr "cannot set package flags with :seti; use :set"
GHC.setInteractiveDynFlags idflags1
installInteractivePrint (interactivePrint idflags1) False
dflags0 <- getDynFlags
when (not interactive_only) $ do
(dflags1, _, _) <- liftIO $ GHC.parseDynamicFlags dflags0 lopts
new_pkgs <- GHC.setProgramDynFlags dflags1
-- if the package flags changed, reset the context and link
-- the new packages.
dflags2 <- getDynFlags
when (packageFlags dflags2 /= packageFlags dflags0) $ do
when (verbosity dflags2 > 0) $
liftIO . putStrLn $
"package flags have changed, resetting and loading new packages..."
GHC.setTargets []
_ <- GHC.load LoadAllTargets
liftIO $ linkPackages dflags2 new_pkgs
-- package flags changed, we can't re-use any of the old context
setContextAfterLoad False []
-- and copy the package state to the interactive DynFlags
idflags <- GHC.getInteractiveDynFlags
GHC.setInteractiveDynFlags
idflags{ pkgState = pkgState dflags2
, pkgDatabase = pkgDatabase dflags2
, packageFlags = packageFlags dflags2 }
let ld0length = length $ ldInputs dflags0
fmrk0length = length $ cmdlineFrameworks dflags0
newLdInputs = drop ld0length (ldInputs dflags2)
newCLFrameworks = drop fmrk0length (cmdlineFrameworks dflags2)
when (not (null newLdInputs && null newCLFrameworks)) $
liftIO $ linkCmdLineLibs $
dflags2 { ldInputs = newLdInputs
, cmdlineFrameworks = newCLFrameworks }
return ()
unsetOptions :: String -> GHCi ()
unsetOptions str
= -- first, deal with the GHCi opts (+s, +t, etc.)
let opts = words str
(minus_opts, rest1) = partition isMinus opts
(plus_opts, rest2) = partitionWith isPlus rest1
(other_opts, rest3) = partition (`elem` map fst defaulters) rest2
defaulters =
[ ("args" , setArgs default_args)
, ("prog" , setProg default_progname)
, ("prompt" , setPrompt default_prompt)
, ("prompt2", setPrompt2 default_prompt2)
, ("editor" , liftIO findEditor >>= setEditor)
, ("stop" , setStop default_stop)
]
no_flag ('-':'f':rest) = return ("-fno-" ++ rest)
no_flag ('-':'X':rest) = return ("-XNo" ++ rest)
no_flag f = throwGhcException (ProgramError ("don't know how to reverse " ++ f))
in if (not (null rest3))
then liftIO (putStrLn ("unknown option: '" ++ head rest3 ++ "'"))
else do
mapM_ (fromJust.flip lookup defaulters) other_opts
mapM_ unsetOpt plus_opts
no_flags <- mapM no_flag minus_opts
newDynFlags False no_flags
isMinus :: String -> Bool
isMinus ('-':_) = True
isMinus _ = False
isPlus :: String -> Either String String
isPlus ('+':opt) = Left opt
isPlus other = Right other
setOpt, unsetOpt :: String -> GHCi ()
setOpt str
= case strToGHCiOpt str of
Nothing -> liftIO (putStrLn ("unknown option: '" ++ str ++ "'"))
Just o -> setOption o
unsetOpt str
= case strToGHCiOpt str of
Nothing -> liftIO (putStrLn ("unknown option: '" ++ str ++ "'"))
Just o -> unsetOption o
strToGHCiOpt :: String -> (Maybe GHCiOption)
strToGHCiOpt "m" = Just Multiline
strToGHCiOpt "s" = Just ShowTiming
strToGHCiOpt "t" = Just ShowType
strToGHCiOpt "r" = Just RevertCAFs
strToGHCiOpt _ = Nothing
optToStr :: GHCiOption -> String
optToStr Multiline = "m"
optToStr ShowTiming = "s"
optToStr ShowType = "t"
optToStr RevertCAFs = "r"
-- ---------------------------------------------------------------------------
-- :show
showCmd :: String -> GHCi ()
showCmd "" = showOptions False
showCmd "-a" = showOptions True
showCmd str = do
st <- getGHCiState
case words str of
["args"] -> liftIO $ putStrLn (show (GhciMonad.args st))
["prog"] -> liftIO $ putStrLn (show (progname st))
["prompt"] -> liftIO $ putStrLn (show (prompt st))
["prompt2"] -> liftIO $ putStrLn (show (prompt2 st))
["editor"] -> liftIO $ putStrLn (show (editor st))
["stop"] -> liftIO $ putStrLn (show (stop st))
["imports"] -> showImports
["modules" ] -> showModules
["bindings"] -> showBindings
["linker"] ->
do dflags <- getDynFlags
liftIO $ showLinkerState dflags
["breaks"] -> showBkptTable
["context"] -> showContext
["packages"] -> showPackages
["paths"] -> showPaths
["languages"] -> showLanguages -- backwards compat
["language"] -> showLanguages
["lang"] -> showLanguages -- useful abbreviation
_ -> throwGhcException (CmdLineError ("syntax: :show [ args | prog | prompt | prompt2 | editor | stop | modules\n" ++
" | bindings | breaks | context | packages | language ]"))
showiCmd :: String -> GHCi ()
showiCmd str = do
case words str of
["languages"] -> showiLanguages -- backwards compat
["language"] -> showiLanguages
["lang"] -> showiLanguages -- useful abbreviation
_ -> throwGhcException (CmdLineError ("syntax: :showi language"))
showImports :: GHCi ()
showImports = do
st <- getGHCiState
dflags <- getDynFlags
let rem_ctx = reverse (remembered_ctx st)
trans_ctx = transient_ctx st
show_one (IIModule star_m)
= ":module +*" ++ moduleNameString star_m
show_one (IIDecl imp) = showPpr dflags imp
prel_imp
| any isPreludeImport (rem_ctx ++ trans_ctx) = []
| not (xopt Opt_ImplicitPrelude dflags) = []
| otherwise = ["import Prelude -- implicit"]
trans_comment s = s ++ " -- added automatically"
--
liftIO $ mapM_ putStrLn (prel_imp ++ map show_one rem_ctx
++ map (trans_comment . show_one) trans_ctx)
showModules :: GHCi ()
showModules = do
loaded_mods <- getLoadedModules
-- we want *loaded* modules only, see #1734
let show_one ms = do m <- GHC.showModule ms; liftIO (putStrLn m)
mapM_ show_one loaded_mods
getLoadedModules :: GHC.GhcMonad m => m [GHC.ModSummary]
getLoadedModules = do
graph <- GHC.getModuleGraph
filterM (GHC.isLoaded . GHC.ms_mod_name) graph
showBindings :: GHCi ()
showBindings = do
bindings <- GHC.getBindings
(insts, finsts) <- GHC.getInsts
docs <- mapM makeDoc (reverse bindings)
-- reverse so the new ones come last
let idocs = map GHC.pprInstanceHdr insts
fidocs = map GHC.pprFamInst finsts
mapM_ printForUserPartWay (docs ++ idocs ++ fidocs)
where
makeDoc (AnId i) = pprTypeAndContents i
makeDoc tt = do
mb_stuff <- GHC.getInfo False (getName tt)
return $ maybe (text "") pprTT mb_stuff
pprTT :: (TyThing, Fixity, [GHC.ClsInst], [GHC.FamInst]) -> SDoc
pprTT (thing, fixity, _cls_insts, _fam_insts)
= pprTyThing thing
$$ show_fixity
where
show_fixity
| fixity == GHC.defaultFixity = empty
| otherwise = ppr fixity <+> ppr (GHC.getName thing)
printTyThing :: TyThing -> GHCi ()
printTyThing tyth = printForUser (pprTyThing tyth)
showBkptTable :: GHCi ()
showBkptTable = do
st <- getGHCiState
printForUser $ prettyLocations (breaks st)
showContext :: GHCi ()
showContext = do
resumes <- GHC.getResumeContext
printForUser $ vcat (map pp_resume (reverse resumes))
where
pp_resume res =
ptext (sLit "--> ") <> text (GHC.resumeStmt res)
$$ nest 2 (ptext (sLit "Stopped at") <+> ppr (GHC.resumeSpan res))
showPackages :: GHCi ()
showPackages = do
dflags <- getDynFlags
let pkg_flags = packageFlags dflags
liftIO $ putStrLn $ showSDoc dflags $
text ("active package flags:"++if null pkg_flags then " none" else "") $$
nest 2 (vcat (map pprFlag pkg_flags))
showPaths :: GHCi ()
showPaths = do
dflags <- getDynFlags
liftIO $ do
cwd <- getCurrentDirectory
putStrLn $ showSDoc dflags $
text "current working directory: " $$
nest 2 (text cwd)
let ipaths = importPaths dflags
putStrLn $ showSDoc dflags $
text ("module import search paths:"++if null ipaths then " none" else "") $$
nest 2 (vcat (map text ipaths))
showLanguages :: GHCi ()
showLanguages = getDynFlags >>= liftIO . showLanguages' False
showiLanguages :: GHCi ()
showiLanguages = GHC.getInteractiveDynFlags >>= liftIO . showLanguages' False
showLanguages' :: Bool -> DynFlags -> IO ()
showLanguages' show_all dflags =
putStrLn $ showSDoc dflags $ vcat
[ text "base language is: " <>
case language dflags of
Nothing -> text "Haskell2010"
Just Haskell98 -> text "Haskell98"
Just Haskell2010 -> text "Haskell2010"
, (if show_all then text "all active language options:"
else text "with the following modifiers:") $$
nest 2 (vcat (map (setting xopt) DynFlags.xFlags))
]
where
setting test flag
| quiet = empty
| is_on = text "-X" <> text name
| otherwise = text "-XNo" <> text name
where name = flagSpecName flag
f = flagSpecFlag flag
is_on = test f dflags
quiet = not show_all && test f default_dflags == is_on
default_dflags =
defaultDynFlags (settings dflags) `lang_set`
case language dflags of
Nothing -> Just Haskell2010
other -> other
-- -----------------------------------------------------------------------------
-- Completion
completeCmd :: String -> GHCi ()
completeCmd argLine0 = case parseLine argLine0 of
Just ("repl", resultRange, left) -> do
(unusedLine,compls) <- ghciCompleteWord (reverse left,"")
let compls' = takeRange resultRange compls
liftIO . putStrLn $ unwords [ show (length compls'), show (length compls), show (reverse unusedLine) ]
forM_ (takeRange resultRange compls) $ \(Completion r _ _) -> do
liftIO $ print r
_ -> throwGhcException (CmdLineError "Syntax: :complete repl [<range>] <quoted-string-to-complete>")
where
parseLine argLine
| null argLine = Nothing
| null rest1 = Nothing
| otherwise = (,,) dom <$> resRange <*> s
where
(dom, rest1) = breakSpace argLine
(rng, rest2) = breakSpace rest1
resRange | head rest1 == '"' = parseRange ""
| otherwise = parseRange rng
s | head rest1 == '"' = readMaybe rest1 :: Maybe String
| otherwise = readMaybe rest2
breakSpace = fmap (dropWhile isSpace) . break isSpace
takeRange (lb,ub) = maybe id (drop . pred) lb . maybe id take ub
-- syntax: [n-][m] with semantics "drop (n-1) . take m"
parseRange :: String -> Maybe (Maybe Int,Maybe Int)
parseRange s = case span isDigit s of
(_, "") ->
-- upper limit only
Just (Nothing, bndRead s)
(s1, '-' : s2)
| all isDigit s2 ->
Just (bndRead s1, bndRead s2)
_ ->
Nothing
where
bndRead x = if null x then Nothing else Just (read x)
completeGhciCommand, completeMacro, completeIdentifier, completeModule,
completeSetModule, completeSeti, completeShowiOptions,
completeHomeModule, completeSetOptions, completeShowOptions,
completeHomeModuleOrFile, completeExpression
:: CompletionFunc GHCi
ghciCompleteWord :: CompletionFunc GHCi
ghciCompleteWord line@(left,_) = case firstWord of
':':cmd | null rest -> completeGhciCommand line
| otherwise -> do
completion <- lookupCompletion cmd
completion line
"import" -> completeModule line
_ -> completeExpression line
where
(firstWord,rest) = break isSpace $ dropWhile isSpace $ reverse left
lookupCompletion ('!':_) = return completeFilename
lookupCompletion c = do
maybe_cmd <- lookupCommand' c
case maybe_cmd of
Just (_,_,f) -> return f
Nothing -> return completeFilename
completeGhciCommand = wrapCompleter " " $ \w -> do
macros <- liftIO $ readIORef macros_ref
cmds <- ghci_commands `fmap` getGHCiState
let macro_names = map (':':) . map cmdName $ macros
let command_names = map (':':) . map cmdName $ cmds
let{ candidates = case w of
':' : ':' : _ -> map (':':) command_names
_ -> nub $ macro_names ++ command_names }
return $ filter (w `isPrefixOf`) candidates
completeMacro = wrapIdentCompleter $ \w -> do
cmds <- liftIO $ readIORef macros_ref
return (filter (w `isPrefixOf`) (map cmdName cmds))
completeIdentifier = wrapIdentCompleter $ \w -> do
rdrs <- GHC.getRdrNamesInScope
dflags <- GHC.getSessionDynFlags
return (filter (w `isPrefixOf`) (map (showPpr dflags) rdrs))
completeModule = wrapIdentCompleter $ \w -> do
dflags <- GHC.getSessionDynFlags
let pkg_mods = allVisibleModules dflags
loaded_mods <- liftM (map GHC.ms_mod_name) getLoadedModules
return $ filter (w `isPrefixOf`)
$ map (showPpr dflags) $ loaded_mods ++ pkg_mods
completeSetModule = wrapIdentCompleterWithModifier "+-" $ \m w -> do
dflags <- GHC.getSessionDynFlags
modules <- case m of
Just '-' -> do
imports <- GHC.getContext
return $ map iiModuleName imports
_ -> do
let pkg_mods = allVisibleModules dflags
loaded_mods <- liftM (map GHC.ms_mod_name) getLoadedModules
return $ loaded_mods ++ pkg_mods
return $ filter (w `isPrefixOf`) $ map (showPpr dflags) modules
completeHomeModule = wrapIdentCompleter listHomeModules
listHomeModules :: String -> GHCi [String]
listHomeModules w = do
g <- GHC.getModuleGraph
let home_mods = map GHC.ms_mod_name g
dflags <- getDynFlags
return $ sort $ filter (w `isPrefixOf`)
$ map (showPpr dflags) home_mods
completeSetOptions = wrapCompleter flagWordBreakChars $ \w -> do
return (filter (w `isPrefixOf`) opts)
where opts = "args":"prog":"prompt":"prompt2":"editor":"stop":flagList
flagList = map head $ group $ sort allFlags
completeSeti = wrapCompleter flagWordBreakChars $ \w -> do
return (filter (w `isPrefixOf`) flagList)
where flagList = map head $ group $ sort allFlags
completeShowOptions = wrapCompleter flagWordBreakChars $ \w -> do
return (filter (w `isPrefixOf`) opts)
where opts = ["args", "prog", "prompt", "prompt2", "editor", "stop",
"modules", "bindings", "linker", "breaks",
"context", "packages", "paths", "language", "imports"]
completeShowiOptions = wrapCompleter flagWordBreakChars $ \w -> do
return (filter (w `isPrefixOf`) ["language"])
completeHomeModuleOrFile = completeWord Nothing filenameWordBreakChars
$ unionComplete (fmap (map simpleCompletion) . listHomeModules)
listFiles
unionComplete :: Monad m => (a -> m [b]) -> (a -> m [b]) -> a -> m [b]
unionComplete f1 f2 line = do
cs1 <- f1 line
cs2 <- f2 line
return (cs1 ++ cs2)
wrapCompleter :: String -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapCompleter breakChars fun = completeWord Nothing breakChars
$ fmap (map simpleCompletion . nubSort) . fun
wrapIdentCompleter :: (String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleter = wrapCompleter word_break_chars
wrapIdentCompleterWithModifier :: String -> (Maybe Char -> String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleterWithModifier modifChars fun = completeWordWithPrev Nothing word_break_chars
$ \rest -> fmap (map simpleCompletion . nubSort) . fun (getModifier rest)
where
getModifier = find (`elem` modifChars)
-- | Return a list of visible module names for autocompletion.
-- (NB: exposed != visible)
allVisibleModules :: DynFlags -> [ModuleName]
allVisibleModules dflags = listVisibleModuleNames dflags
completeExpression = completeQuotedWord (Just '\\') "\"" listFiles
completeIdentifier
-- -----------------------------------------------------------------------------
-- commands for debugger
sprintCmd, printCmd, forceCmd :: String -> GHCi ()
sprintCmd = pprintCommand False False
printCmd = pprintCommand True False
forceCmd = pprintCommand False True
pprintCommand :: Bool -> Bool -> String -> GHCi ()
pprintCommand bind force str = do
pprintClosureCommand bind force str
stepCmd :: String -> GHCi ()
stepCmd arg = withSandboxOnly ":step" $ step arg
where
step [] = doContinue (const True) GHC.SingleStep
step expression = runStmt expression GHC.SingleStep >> return ()
stepLocalCmd :: String -> GHCi ()
stepLocalCmd arg = withSandboxOnly ":steplocal" $ step arg
where
step expr
| not (null expr) = stepCmd expr
| otherwise = do
mb_span <- getCurrentBreakSpan
case mb_span of
Nothing -> stepCmd []
Just loc -> do
Just md <- getCurrentBreakModule
current_toplevel_decl <- enclosingTickSpan md loc
doContinue (`isSubspanOf` current_toplevel_decl) GHC.SingleStep
stepModuleCmd :: String -> GHCi ()
stepModuleCmd arg = withSandboxOnly ":stepmodule" $ step arg
where
step expr
| not (null expr) = stepCmd expr
| otherwise = do
mb_span <- getCurrentBreakSpan
case mb_span of
Nothing -> stepCmd []
Just pan -> do
let f some_span = srcSpanFileName_maybe pan == srcSpanFileName_maybe some_span
doContinue f GHC.SingleStep
-- | Returns the span of the largest tick containing the srcspan given
enclosingTickSpan :: Module -> SrcSpan -> GHCi SrcSpan
enclosingTickSpan _ (UnhelpfulSpan _) = panic "enclosingTickSpan UnhelpfulSpan"
enclosingTickSpan md (RealSrcSpan src) = do
ticks <- getTickArray md
let line = srcSpanStartLine src
ASSERT(inRange (bounds ticks) line) do
let toRealSrcSpan (UnhelpfulSpan _) = panic "enclosingTickSpan UnhelpfulSpan"
toRealSrcSpan (RealSrcSpan s) = s
enclosing_spans = [ pan | (_,pan) <- ticks ! line
, realSrcSpanEnd (toRealSrcSpan pan) >= realSrcSpanEnd src]
return . head . sortBy leftmost_largest $ enclosing_spans
traceCmd :: String -> GHCi ()
traceCmd arg
= withSandboxOnly ":trace" $ tr arg
where
tr [] = doContinue (const True) GHC.RunAndLogSteps
tr expression = runStmt expression GHC.RunAndLogSteps >> return ()
continueCmd :: String -> GHCi ()
continueCmd = noArgs $ withSandboxOnly ":continue" $ doContinue (const True) GHC.RunToCompletion
-- doContinue :: SingleStep -> GHCi ()
doContinue :: (SrcSpan -> Bool) -> SingleStep -> GHCi ()
doContinue pre step = do
runResult <- resume pre step
_ <- afterRunStmt pre runResult
return ()
abandonCmd :: String -> GHCi ()
abandonCmd = noArgs $ withSandboxOnly ":abandon" $ do
b <- GHC.abandon -- the prompt will change to indicate the new context
when (not b) $ liftIO $ putStrLn "There is no computation running."
deleteCmd :: String -> GHCi ()
deleteCmd argLine = withSandboxOnly ":delete" $ do
deleteSwitch $ words argLine
where
deleteSwitch :: [String] -> GHCi ()
deleteSwitch [] =
liftIO $ putStrLn "The delete command requires at least one argument."
-- delete all break points
deleteSwitch ("*":_rest) = discardActiveBreakPoints
deleteSwitch idents = do
mapM_ deleteOneBreak idents
where
deleteOneBreak :: String -> GHCi ()
deleteOneBreak str
| all isDigit str = deleteBreak (read str)
| otherwise = return ()
historyCmd :: String -> GHCi ()
historyCmd arg
| null arg = history 20
| all isDigit arg = history (read arg)
| otherwise = liftIO $ putStrLn "Syntax: :history [num]"
where
history num = do
resumes <- GHC.getResumeContext
case resumes of
[] -> liftIO $ putStrLn "Not stopped at a breakpoint"
(r:_) -> do
let hist = GHC.resumeHistory r
(took,rest) = splitAt num hist
case hist of
[] -> liftIO $ putStrLn $
"Empty history. Perhaps you forgot to use :trace?"
_ -> do
pans <- mapM GHC.getHistorySpan took
let nums = map (printf "-%-3d:") [(1::Int)..]
names = map GHC.historyEnclosingDecls took
printForUser (vcat(zipWith3
(\x y z -> x <+> y <+> z)
(map text nums)
(map (bold . hcat . punctuate colon . map text) names)
(map (parens . ppr) pans)))
liftIO $ putStrLn $ if null rest then "<end of history>" else "..."
bold :: SDoc -> SDoc
bold c | do_bold = text start_bold <> c <> text end_bold
| otherwise = c
backCmd :: String -> GHCi ()
backCmd = noArgs $ withSandboxOnly ":back" $ do
(names, _, pan) <- GHC.back
printForUser $ ptext (sLit "Logged breakpoint at") <+> ppr pan
printTypeOfNames names
-- run the command set with ":set stop <cmd>"
st <- getGHCiState
enqueueCommands [stop st]
forwardCmd :: String -> GHCi ()
forwardCmd = noArgs $ withSandboxOnly ":forward" $ do
(names, ix, pan) <- GHC.forward
printForUser $ (if (ix == 0)
then ptext (sLit "Stopped at")
else ptext (sLit "Logged breakpoint at")) <+> ppr pan
printTypeOfNames names
-- run the command set with ":set stop <cmd>"
st <- getGHCiState
enqueueCommands [stop st]
-- handle the "break" command
breakCmd :: String -> GHCi ()
breakCmd argLine = withSandboxOnly ":break" $ breakSwitch $ words argLine
breakSwitch :: [String] -> GHCi ()
breakSwitch [] = do
liftIO $ putStrLn "The break command requires at least one argument."
breakSwitch (arg1:rest)
| looksLikeModuleName arg1 && not (null rest) = do
md <- wantInterpretedModule arg1
breakByModule md rest
| all isDigit arg1 = do
imports <- GHC.getContext
case iiModules imports of
(mn : _) -> do
md <- lookupModuleName mn
breakByModuleLine md (read arg1) rest
[] -> do
liftIO $ putStrLn "No modules are loaded with debugging support."
| otherwise = do -- try parsing it as an identifier
wantNameFromInterpretedModule noCanDo arg1 $ \name -> do
let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
case loc of
RealSrcLoc l ->
ASSERT( isExternalName name )
findBreakAndSet (GHC.nameModule name) $
findBreakByCoord (Just (GHC.srcLocFile l))
(GHC.srcLocLine l,
GHC.srcLocCol l)
UnhelpfulLoc _ ->
noCanDo name $ text "can't find its location: " <> ppr loc
where
noCanDo n why = printForUser $
text "cannot set breakpoint on " <> ppr n <> text ": " <> why
breakByModule :: Module -> [String] -> GHCi ()
breakByModule md (arg1:rest)
| all isDigit arg1 = do -- looks like a line number
breakByModuleLine md (read arg1) rest
breakByModule _ _
= breakSyntax
breakByModuleLine :: Module -> Int -> [String] -> GHCi ()
breakByModuleLine md line args
| [] <- args = findBreakAndSet md $ findBreakByLine line
| [col] <- args, all isDigit col =
findBreakAndSet md $ findBreakByCoord Nothing (line, read col)
| otherwise = breakSyntax
breakSyntax :: a
breakSyntax = throwGhcException (CmdLineError "Syntax: :break [<mod>] <line> [<column>]")
findBreakAndSet :: Module -> (TickArray -> Maybe (Int, SrcSpan)) -> GHCi ()
findBreakAndSet md lookupTickTree = do
dflags <- getDynFlags
tickArray <- getTickArray md
(breakArray, _) <- getModBreak md
case lookupTickTree tickArray of
Nothing -> liftIO $ putStrLn $ "No breakpoints found at that location."
Just (tick, pan) -> do
success <- liftIO $ setBreakFlag dflags True breakArray tick
if success
then do
(alreadySet, nm) <-
recordBreak $ BreakLocation
{ breakModule = md
, breakLoc = pan
, breakTick = tick
, onBreakCmd = ""
}
printForUser $
text "Breakpoint " <> ppr nm <>
if alreadySet
then text " was already set at " <> ppr pan
else text " activated at " <> ppr pan
else do
printForUser $ text "Breakpoint could not be activated at"
<+> ppr pan
-- When a line number is specified, the current policy for choosing
-- the best breakpoint is this:
-- - the leftmost complete subexpression on the specified line, or
-- - the leftmost subexpression starting on the specified line, or
-- - the rightmost subexpression enclosing the specified line
--
findBreakByLine :: Int -> TickArray -> Maybe (BreakIndex,SrcSpan)
findBreakByLine line arr
| not (inRange (bounds arr) line) = Nothing
| otherwise =
listToMaybe (sortBy (leftmost_largest `on` snd) comp) `mplus`
listToMaybe (sortBy (leftmost_smallest `on` snd) incomp) `mplus`
listToMaybe (sortBy (rightmost `on` snd) ticks)
where
ticks = arr ! line
starts_here = [ tick | tick@(_,pan) <- ticks,
GHC.srcSpanStartLine (toRealSpan pan) == line ]
(comp, incomp) = partition ends_here starts_here
where ends_here (_,pan) = GHC.srcSpanEndLine (toRealSpan pan) == line
toRealSpan (RealSrcSpan pan) = pan
toRealSpan (UnhelpfulSpan _) = panic "findBreakByLine UnhelpfulSpan"
findBreakByCoord :: Maybe FastString -> (Int,Int) -> TickArray
-> Maybe (BreakIndex,SrcSpan)
findBreakByCoord mb_file (line, col) arr
| not (inRange (bounds arr) line) = Nothing
| otherwise =
listToMaybe (sortBy (rightmost `on` snd) contains ++
sortBy (leftmost_smallest `on` snd) after_here)
where
ticks = arr ! line
-- the ticks that span this coordinate
contains = [ tick | tick@(_,pan) <- ticks, pan `spans` (line,col),
is_correct_file pan ]
is_correct_file pan
| Just f <- mb_file = GHC.srcSpanFile (toRealSpan pan) == f
| otherwise = True
after_here = [ tick | tick@(_,pan) <- ticks,
let pan' = toRealSpan pan,
GHC.srcSpanStartLine pan' == line,
GHC.srcSpanStartCol pan' >= col ]
toRealSpan (RealSrcSpan pan) = pan
toRealSpan (UnhelpfulSpan _) = panic "findBreakByCoord UnhelpfulSpan"
-- For now, use ANSI bold on terminals that we know support it.
-- Otherwise, we add a line of carets under the active expression instead.
-- In particular, on Windows and when running the testsuite (which sets
-- TERM to vt100 for other reasons) we get carets.
-- We really ought to use a proper termcap/terminfo library.
do_bold :: Bool
do_bold = (`isPrefixOf` unsafePerformIO mTerm) `any` ["xterm", "linux"]
where mTerm = System.Environment.getEnv "TERM"
`catchIO` \_ -> return "TERM not set"
start_bold :: String
start_bold = "\ESC[1m"
end_bold :: String
end_bold = "\ESC[0m"
-----------------------------------------------------------------------------
-- :list
listCmd :: String -> InputT GHCi ()
listCmd c = listCmd' c
listCmd' :: String -> InputT GHCi ()
listCmd' "" = do
mb_span <- lift getCurrentBreakSpan
case mb_span of
Nothing ->
printForUser $ text "Not stopped at a breakpoint; nothing to list"
Just (RealSrcSpan pan) ->
listAround pan True
Just pan@(UnhelpfulSpan _) ->
do resumes <- GHC.getResumeContext
case resumes of
[] -> panic "No resumes"
(r:_) ->
do let traceIt = case GHC.resumeHistory r of
[] -> text "rerunning with :trace,"
_ -> empty
doWhat = traceIt <+> text ":back then :list"
printForUser (text "Unable to list source for" <+>
ppr pan
$$ text "Try" <+> doWhat)
listCmd' str = list2 (words str)
list2 :: [String] -> InputT GHCi ()
list2 [arg] | all isDigit arg = do
imports <- GHC.getContext
case iiModules imports of
[] -> liftIO $ putStrLn "No module to list"
(mn : _) -> do
md <- lift $ lookupModuleName mn
listModuleLine md (read arg)
list2 [arg1,arg2] | looksLikeModuleName arg1, all isDigit arg2 = do
md <- wantInterpretedModule arg1
listModuleLine md (read arg2)
list2 [arg] = do
wantNameFromInterpretedModule noCanDo arg $ \name -> do
let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
case loc of
RealSrcLoc l ->
do tickArray <- ASSERT( isExternalName name )
lift $ getTickArray (GHC.nameModule name)
let mb_span = findBreakByCoord (Just (GHC.srcLocFile l))
(GHC.srcLocLine l, GHC.srcLocCol l)
tickArray
case mb_span of
Nothing -> listAround (realSrcLocSpan l) False
Just (_, UnhelpfulSpan _) -> panic "list2 UnhelpfulSpan"
Just (_, RealSrcSpan pan) -> listAround pan False
UnhelpfulLoc _ ->
noCanDo name $ text "can't find its location: " <>
ppr loc
where
noCanDo n why = printForUser $
text "cannot list source code for " <> ppr n <> text ": " <> why
list2 _other =
liftIO $ putStrLn "syntax: :list [<line> | <module> <line> | <identifier>]"
listModuleLine :: Module -> Int -> InputT GHCi ()
listModuleLine modl line = do
graph <- GHC.getModuleGraph
let this = filter ((== modl) . GHC.ms_mod) graph
case this of
[] -> panic "listModuleLine"
summ:_ -> do
let filename = expectJust "listModuleLine" (ml_hs_file (GHC.ms_location summ))
loc = mkRealSrcLoc (mkFastString (filename)) line 0
listAround (realSrcLocSpan loc) False
-- | list a section of a source file around a particular SrcSpan.
-- If the highlight flag is True, also highlight the span using
-- start_bold\/end_bold.
-- GHC files are UTF-8, so we can implement this by:
-- 1) read the file in as a BS and syntax highlight it as before
-- 2) convert the BS to String using utf-string, and write it out.
-- It would be better if we could convert directly between UTF-8 and the
-- console encoding, of course.
listAround :: MonadIO m => RealSrcSpan -> Bool -> InputT m ()
listAround pan do_highlight = do
contents <- liftIO $ BS.readFile (unpackFS file)
-- Drop carriage returns to avoid duplicates, see #9367.
let ls = BS.split '\n' $ BS.filter (/= '\r') contents
ls' = take (line2 - line1 + 1 + pad_before + pad_after) $
drop (line1 - 1 - pad_before) $ ls
fst_line = max 1 (line1 - pad_before)
line_nos = [ fst_line .. ]
highlighted | do_highlight = zipWith highlight line_nos ls'
| otherwise = [\p -> BS.concat[p,l] | l <- ls']
bs_line_nos = [ BS.pack (show l ++ " ") | l <- line_nos ]
prefixed = zipWith ($) highlighted bs_line_nos
output = BS.intercalate (BS.pack "\n") prefixed
utf8Decoded <- liftIO $ BS.useAsCStringLen output
$ \(p,n) -> utf8DecodeString (castPtr p) n
liftIO $ putStrLn utf8Decoded
where
file = GHC.srcSpanFile pan
line1 = GHC.srcSpanStartLine pan
col1 = GHC.srcSpanStartCol pan - 1
line2 = GHC.srcSpanEndLine pan
col2 = GHC.srcSpanEndCol pan - 1
pad_before | line1 == 1 = 0
| otherwise = 1
pad_after = 1
highlight | do_bold = highlight_bold
| otherwise = highlight_carets
highlight_bold no line prefix
| no == line1 && no == line2
= let (a,r) = BS.splitAt col1 line
(b,c) = BS.splitAt (col2-col1) r
in
BS.concat [prefix, a,BS.pack start_bold,b,BS.pack end_bold,c]
| no == line1
= let (a,b) = BS.splitAt col1 line in
BS.concat [prefix, a, BS.pack start_bold, b]
| no == line2
= let (a,b) = BS.splitAt col2 line in
BS.concat [prefix, a, BS.pack end_bold, b]
| otherwise = BS.concat [prefix, line]
highlight_carets no line prefix
| no == line1 && no == line2
= BS.concat [prefix, line, nl, indent, BS.replicate col1 ' ',
BS.replicate (col2-col1) '^']
| no == line1
= BS.concat [indent, BS.replicate (col1 - 2) ' ', BS.pack "vv", nl,
prefix, line]
| no == line2
= BS.concat [prefix, line, nl, indent, BS.replicate col2 ' ',
BS.pack "^^"]
| otherwise = BS.concat [prefix, line]
where
indent = BS.pack (" " ++ replicate (length (show no)) ' ')
nl = BS.singleton '\n'
-- --------------------------------------------------------------------------
-- Tick arrays
getTickArray :: Module -> GHCi TickArray
getTickArray modl = do
st <- getGHCiState
let arrmap = tickarrays st
case lookupModuleEnv arrmap modl of
Just arr -> return arr
Nothing -> do
(_breakArray, ticks) <- getModBreak modl
let arr = mkTickArray (assocs ticks)
setGHCiState st{tickarrays = extendModuleEnv arrmap modl arr}
return arr
discardTickArrays :: GHCi ()
discardTickArrays = do
st <- getGHCiState
setGHCiState st{tickarrays = emptyModuleEnv}
mkTickArray :: [(BreakIndex,SrcSpan)] -> TickArray
mkTickArray ticks
= accumArray (flip (:)) [] (1, max_line)
[ (line, (nm,pan)) | (nm,pan) <- ticks,
let pan' = toRealSpan pan,
line <- srcSpanLines pan' ]
where
max_line = foldr max 0 (map (GHC.srcSpanEndLine . toRealSpan . snd) ticks)
srcSpanLines pan = [ GHC.srcSpanStartLine pan .. GHC.srcSpanEndLine pan ]
toRealSpan (RealSrcSpan pan) = pan
toRealSpan (UnhelpfulSpan _) = panic "mkTickArray UnhelpfulSpan"
-- don't reset the counter back to zero?
discardActiveBreakPoints :: GHCi ()
discardActiveBreakPoints = do
st <- getGHCiState
mapM_ (turnOffBreak.snd) (breaks st)
setGHCiState $ st { breaks = [] }
deleteBreak :: Int -> GHCi ()
deleteBreak identity = do
st <- getGHCiState
let oldLocations = breaks st
(this,rest) = partition (\loc -> fst loc == identity) oldLocations
if null this
then printForUser (text "Breakpoint" <+> ppr identity <+>
text "does not exist")
else do
mapM_ (turnOffBreak.snd) this
setGHCiState $ st { breaks = rest }
turnOffBreak :: BreakLocation -> GHCi Bool
turnOffBreak loc = do
dflags <- getDynFlags
(arr, _) <- getModBreak (breakModule loc)
liftIO $ setBreakFlag dflags False arr (breakTick loc)
getModBreak :: Module -> GHCi (GHC.BreakArray, Array Int SrcSpan)
getModBreak m = do
Just mod_info <- GHC.getModuleInfo m
let modBreaks = GHC.modInfoModBreaks mod_info
let arr = GHC.modBreaks_flags modBreaks
let ticks = GHC.modBreaks_locs modBreaks
return (arr, ticks)
setBreakFlag :: DynFlags -> Bool -> GHC.BreakArray -> Int -> IO Bool
setBreakFlag dflags toggle arr i
| toggle = GHC.setBreakOn dflags arr i
| otherwise = GHC.setBreakOff dflags arr i
-- ---------------------------------------------------------------------------
-- User code exception handling
-- This is the exception handler for exceptions generated by the
-- user's code and exceptions coming from children sessions;
-- it normally just prints out the exception. The
-- handler must be recursive, in case showing the exception causes
-- more exceptions to be raised.
--
-- Bugfix: if the user closed stdout or stderr, the flushing will fail,
-- raising another exception. We therefore don't put the recursive
-- handler arond the flushing operation, so if stderr is closed
-- GHCi will just die gracefully rather than going into an infinite loop.
handler :: SomeException -> GHCi Bool
handler exception = do
flushInterpBuffers
liftIO installSignalHandlers
ghciHandle handler (showException exception >> return False)
showException :: SomeException -> GHCi ()
showException se =
liftIO $ case fromException se of
-- omit the location for CmdLineError:
Just (CmdLineError s) -> putException s
-- ditto:
Just ph@(PhaseFailed {}) -> putException (showGhcException ph "")
Just other_ghc_ex -> putException (show other_ghc_ex)
Nothing ->
case fromException se of
Just UserInterrupt -> putException "Interrupted."
_ -> putException ("*** Exception: " ++ show se)
where
putException = hPutStrLn stderr
-----------------------------------------------------------------------------
-- recursive exception handlers
-- Don't forget to unblock async exceptions in the handler, or if we're
-- in an exception loop (eg. let a = error a in a) the ^C exception
-- may never be delivered. Thanks to Marcin for pointing out the bug.
ghciHandle :: (HasDynFlags m, ExceptionMonad m) => (SomeException -> m a) -> m a -> m a
ghciHandle h m = gmask $ \restore -> do
dflags <- getDynFlags
gcatch (restore (GHC.prettyPrintGhcErrors dflags m)) $ \e -> restore (h e)
ghciTry :: GHCi a -> GHCi (Either SomeException a)
ghciTry (GHCi m) = GHCi $ \s -> gtry (m s)
tryBool :: GHCi a -> GHCi Bool
tryBool m = do
r <- ghciTry m
case r of
Left _ -> return False
Right _ -> return True
-- ----------------------------------------------------------------------------
-- Utils
lookupModule :: GHC.GhcMonad m => String -> m Module
lookupModule mName = lookupModuleName (GHC.mkModuleName mName)
lookupModuleName :: GHC.GhcMonad m => ModuleName -> m Module
lookupModuleName mName = GHC.lookupModule mName Nothing
isHomeModule :: Module -> Bool
isHomeModule m = GHC.modulePackageKey m == mainPackageKey
-- TODO: won't work if home dir is encoded.
-- (changeDirectory may not work either in that case.)
expandPath :: MonadIO m => String -> InputT m String
expandPath = liftIO . expandPathIO
expandPathIO :: String -> IO String
expandPathIO p =
case dropWhile isSpace p of
('~':d) -> do
tilde <- getHomeDirectory -- will fail if HOME not defined
return (tilde ++ '/':d)
other ->
return other
sameFile :: FilePath -> FilePath -> IO Bool
sameFile path1 path2 = do
absPath1 <- canonicalizePath path1
absPath2 <- canonicalizePath path2
return $ absPath1 == absPath2
wantInterpretedModule :: GHC.GhcMonad m => String -> m Module
wantInterpretedModule str = wantInterpretedModuleName (GHC.mkModuleName str)
wantInterpretedModuleName :: GHC.GhcMonad m => ModuleName -> m Module
wantInterpretedModuleName modname = do
modl <- lookupModuleName modname
let str = moduleNameString modname
dflags <- getDynFlags
when (GHC.modulePackageKey modl /= thisPackage dflags) $
throwGhcException (CmdLineError ("module '" ++ str ++ "' is from another package;\nthis command requires an interpreted module"))
is_interpreted <- GHC.moduleIsInterpreted modl
when (not is_interpreted) $
throwGhcException (CmdLineError ("module '" ++ str ++ "' is not interpreted; try \':add *" ++ str ++ "' first"))
return modl
wantNameFromInterpretedModule :: GHC.GhcMonad m
=> (Name -> SDoc -> m ())
-> String
-> (Name -> m ())
-> m ()
wantNameFromInterpretedModule noCanDo str and_then =
handleSourceError GHC.printException $ do
names <- GHC.parseName str
case names of
[] -> return ()
(n:_) -> do
let modl = ASSERT( isExternalName n ) GHC.nameModule n
if not (GHC.isExternalName n)
then noCanDo n $ ppr n <>
text " is not defined in an interpreted module"
else do
is_interpreted <- GHC.moduleIsInterpreted modl
if not is_interpreted
then noCanDo n $ text "module " <> ppr modl <>
text " is not interpreted"
else and_then n
| nathyong/microghc-ghc | ghc/InteractiveUI.hs | bsd-3-clause | 127,497 | 1,946 | 101 | 36,887 | 28,383 | 15,086 | 13,297 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Bead.View.Content.SetUserPassword.Page (
setUserPassword
) where
import Data.String (fromString)
import Text.Blaze.Html5 as H hiding (id)
import qualified Bead.Controller.Pages as Pages
import Bead.Controller.UserStories (isStudentOfMine)
import Bead.View.Content
import qualified Bead.View.Content.Bootstrap as Bootstrap
import qualified Bead.View.ResetPassword as P
import qualified Bead.View.DataBridge as B
setUserPassword = ViewModifyHandler setUserPasswordPage setUsrPwd
setUserPasswordPage :: GETContentHandler
setUserPasswordPage = return setUserPasswordContent
setUsrPwd :: POSTContentHandler
setUsrPwd = do
user <- getParameter usernamePrm
newPwd <- getParameter studentNewPwdPrm
ok <- userStory (isStudentOfMine user)
if ok
then do
msg <- P.setUserPassword user newPwd
return $ StatusMessage msg
else do
let username = usernameCata id user
return . StatusMessage $ msg_SetUserPassword_NonRegisteredUser
"This user is not registered in neither of your courses nor your groups."
setUserPasswordContent :: IHtml
setUserPasswordContent = do
msg <- getI18N
return $ do
Bootstrap.row $ Bootstrap.colMd Bootstrap.colSize4 Bootstrap.colOffset4 $
postForm (routeOf setUserPassword) `withId` (rFormId setStudentPwdForm) $ do
Bootstrap.textInput (B.name usernamePrm) (msg $ msg_SetUserPassword_User "Username: ") ""
Bootstrap.passwordInput (B.name studentNewPwdPrm) (msg $ msg_SetUserPassword_NewPassword "New password: ")
Bootstrap.passwordInput (B.name studentNewPwdAgainPrm) (msg $ msg_SetUserPassword_NewPasswordAgain "New password (again): ")
Bootstrap.submitButton (fieldName changePasswordBtn) (msg $ msg_SetUserPassword_SetButton "Update")
where
setUserPassword = Pages.setUserPassword ()
| andorp/bead | src/Bead/View/Content/SetUserPassword/Page.hs | bsd-3-clause | 1,912 | 0 | 16 | 353 | 424 | 223 | 201 | 38 | 2 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="tr-TR">
<title>SVN Digger Files</title>
<maps>
<homeID>svndigger</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/svndigger/src/main/javahelp/help_tr_TR/helpset_tr_TR.hs | apache-2.0 | 967 | 77 | 66 | 157 | 409 | 207 | 202 | -1 | -1 |
{-# LANGUAGE PartialTypeSignatures #-}
module PartialClassMethodSignature where
class Foo a where
foo :: a -> _
| urbanslug/ghc | testsuite/tests/partial-sigs/should_fail/PartialClassMethodSignature.hs | bsd-3-clause | 116 | 0 | 7 | 20 | 23 | 13 | 10 | 4 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
import SafeLang11_A
import SafeLang11_B
$(mkSimpleClass ''A)
main = do
let b = c :: A
putStrLn $ "I have a value of A :: " ++ show b
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/safeHaskell/safeLanguage/SafeLang11.hs | bsd-3-clause | 196 | 0 | 9 | 47 | 54 | 28 | 26 | 8 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Applicative (pure)
import Control.Monad
import Control.Monad.Loops
import Control.Monad.Trans.Maybe
import Data.Bits hiding (rotate)
import Data.IORef
import Data.Maybe
import Data.Monoid
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Vector as V
import Graphics.GL.Core32
import Graphics.UI.GLFW hiding (Image)
import NanoVG as NVG
import NanoVG.Internal.Text as Internal
import Prelude hiding (init)
import Foreign.C.Types
import Foreign.Ptr
foreign import ccall unsafe "initGlew"
glewInit :: IO CInt
main :: IO ()
main =
do e <- init
when (not e) $ putStrLn "Failed to init GLFW"
windowHint $ WindowHint'ContextVersionMajor 3
windowHint $ WindowHint'ContextVersionMinor 2
windowHint $ WindowHint'OpenGLForwardCompat True
windowHint $ WindowHint'OpenGLProfile OpenGLProfile'Core
windowHint $ WindowHint'OpenGLDebugContext True
win <- createWindow 1000 600 "NanoVG" Nothing Nothing
case win of
Nothing -> putStrLn "Failed to create window" >> terminate
Just w ->
do makeContextCurrent win
glewInit
glGetError
c@(Context c') <- createGL3 (S.fromList [Antialias,StencilStrokes,Debug])
-- error handling? who needs that anyway
Just demoData <- runMaybeT $ loadDemoData c
swapInterval 0
setTime 0
whileM_ (not <$> windowShouldClose w) $
do Just t <- getTime
(mx,my) <- getCursorPos w
(width,height) <- getWindowSize w
(fbWidth,fbHeight) <- getFramebufferSize w
let pxRatio = fromIntegral fbWidth / fromIntegral width
glViewport 0 0 (fromIntegral fbWidth) (fromIntegral fbHeight)
glClearColor 0.3 0.3 0.32 1.0
glClear (GL_COLOR_BUFFER_BIT .|. GL_DEPTH_BUFFER_BIT .|. GL_STENCIL_BUFFER_BIT)
beginFrame c (fromIntegral width) (fromIntegral height) pxRatio
renderDemo c demoData mx my width height t
endFrame c
swapBuffers w
pollEvents
renderDemo :: Context -> DemoData -> Double -> Double -> Int -> Int -> Double -> IO ()
renderDemo c demoData mx my w h t =
do drawEyes c (fromIntegral w - 250) 50 150 100 (realToFrac mx) (realToFrac my) (realToFrac t)
drawParagraph c (fromIntegral w - 450) 50 150 100 (realToFrac mx) (realToFrac my)
drawGraph c 0 (fromIntegral h/2) (fromIntegral w) (fromIntegral h/2) (realToFrac t)
drawColorwheel c (fromIntegral w - 300) (fromIntegral h - 300) 250 250 (realToFrac t)
drawLines c 120 (fromIntegral h - 50) 600 50 (realToFrac t)
drawWidths c 10 50 30
drawCaps c 10 300 30
drawScissor c 50 (fromIntegral h-80) (realToFrac t)
drawComposite c
save c
let popy = 95 + 24
drawThumbnails c 365 popy 160 300 (images demoData) (realToFrac t)
restore c
drawThumbnails :: Context -> CFloat -> CFloat -> CFloat -> CFloat -> V.Vector Image -> CFloat -> IO ()
drawThumbnails vg x y w h images t =
do let cornerRadius = 3
thumb = 60
arry = 30.5
nimages = V.length images
stackh = (fromIntegral nimages/2)*(thumb+10)+10
u = (1+cos (t*0.5))*0.5
u2 = (1-cos (t*0.2))*0.5
dv = 1/(fromIntegral nimages - 1)
save vg
shadowPaint <- boxGradient vg x (y+4) w h (cornerRadius*2) 20 (rgba 0 0 0 128) (rgba 0 0 0 0)
beginPath vg
rect vg (x-10) (y-10) (w+20) (h+30)
roundedRect vg x y w h cornerRadius
pathWinding vg (fromIntegral $ fromEnum Hole)
fillPaint vg shadowPaint
fill vg
beginPath vg
roundedRect vg x y w h cornerRadius
moveTo vg (x-10) (y+arry)
lineTo vg (x+1) (y+arry-11)
lineTo vg (x+1) (y+arry+11)
fillColor vg (rgba 200 200 200 255)
fill vg
save vg
scissor vg x y w h
translate vg 0 (-(stackh-h)*u)
flip V.imapM_ images $ \i image -> do
let tx = x + 10 + fromIntegral (i `mod` 2) * (thumb + 10)
ty = y + 10 + fromIntegral (i `div` 2) * (thumb + 10)
v = fromIntegral i * dv
a = clamp ((u2-v)/dv) 0 1
drawImage iw ih ix iy = do
imgPaint <- imagePattern vg (tx+ix) (ty+iy) iw ih (0/180*pi) image a
beginPath vg
roundedRect vg tx ty thumb thumb 5
fillPaint vg imgPaint
fill vg
(imgw,imgh) <- imageSize vg image
when (a < 1) $ drawSpinner vg (tx + thumb/2) (ty+thumb/2) (thumb*0.25) t
if imgw < imgh
then
let iw = thumb
ih = iw*fromIntegral imgh/fromIntegral imgw
ix = 0
iy = -(ih-thumb)*0.5
in drawImage iw ih ix iy
else
let ih = thumb
iw = ih * fromIntegral imgw/ fromIntegral imgh
ix = -(iw-thumb)*0.5
iy = 0
in drawImage iw ih ix iy
shadowPaint <- boxGradient vg (tx-1) ty (thumb+2) (thumb+2) 5 3 (rgba 0 0 0 128) (rgba 0 0 0 0)
beginPath vg
rect vg (tx-5) (ty-5) (thumb+10) (thumb+10)
roundedRect vg tx ty thumb thumb 6
pathWinding vg (fromIntegral $ fromEnum Hole)
fillPaint vg shadowPaint
fill vg
beginPath vg
roundedRect vg (tx+0.5) (ty+0.5) (thumb-1) (thumb-1) (4-0.5)
strokeWidth vg 1
strokeColor vg (rgba 255 255 255 192)
stroke vg
restore vg
restore vg
drawSpinner :: Context -> CFloat -> CFloat -> CFloat -> CFloat -> IO ()
drawSpinner vg cx cy r t =
do let a0 = 0+t*6
a1 = pi + t*6
r0 = r
r1 = r*0.75
save vg
beginPath vg
arc vg cx cy r0 a0 a1 CW
arc vg cx cy r1 a1 a0 CCW
closePath vg
let ax = cx+cos a0 * (r0+r1)*0.5
ay = cy+sin a0 * (r0+r1)*0.5
bx = cx+cos a1 * (r0+r1)*0.5
by = cy+sin a1 * (r0+r1)*0.5
paint <- linearGradient vg ax ay bx by (rgba 0 0 0 0) (rgba 0 0 0 128)
fillPaint vg paint
fill vg
restore vg
drawEyes :: Context -> CFloat -> CFloat -> CFloat -> CFloat -> CFloat -> CFloat -> CFloat -> IO ()
drawEyes c@(Context c') x y w h mx my t = do
bg <- linearGradient c x (y+h*0.5) (x+w*0.1) (y+h) (rgba 0 0 0 32) (rgba 0 0 0 16)
beginPath c
ellipse c (lx+3) (ly+16) ex ey
ellipse c (rx+3) (ry+16) ex ey
fillPaint c bg
fill c
bg <- linearGradient c x (y+h*0.25) (x+w*0.1) (y+h) (rgba 220 220 220 255) (rgba 128 128 128 255)
beginPath c
ellipse c lx ly ex ey
ellipse c rx ry ex ey
fillPaint c bg
fill c
let dx' = (mx - rx) / (ex * 10)
dy' = (my - ry) / (ey * 10)
d = sqrt (dx'*dx'+dy'*dy')
dx'' = if d > 1 then dx'/d else dx'
dy'' = if d > 1 then dy'/d else dy'
dx = dx'' * ex * 0.4
dy = dy'' * ey * 0.5
beginPath c
ellipse c (lx+dx) (ly+dy+ey*0.25*(1-blink)) br (br*blink)
fillColor c (rgba 32 32 32 255)
fill c
let dx'' = (mx - rx) / (ex * 10)
dy'' = (my - ry) / (ey * 10)
d = sqrt (dx'' * dx'' + dy'' * dy'')
dx' = if d > 1 then dx'' / d else dx''
dy' = if d > 1 then dy'' / d else dy''
dx = dx' * ex * 0.4
dy = dy' * ey * 0.5
beginPath c
ellipse c (rx+dx) (ry+dy+ey*0.25*(1-blink)) br (br*blink)
fillColor c (rgba 32 32 32 255)
fill c
gloss <- radialGradient c (lx-ex*0.25) (ly-ey*0.5) (ex*0.1) (ex*0.75) (rgba 255 255 255 128) (rgba 255 255 255 0)
beginPath c
ellipse c lx ly ex ey
fillPaint c gloss
fill c
gloss <- radialGradient c (rx-ex*0.25) (ry-ey*0.5) (ex*0.1) (ex*0.75) (rgba 255 255 255 128) (rgba 255 255 255 0)
beginPath c
ellipse c rx ry ex ey
fillPaint c gloss
fill c
where ex = w * 0.23
ey = h * 0.5
lx = x + ex
ly = y + ey
rx = x + w - ex
ry = y + ey
br = 0.5 * min ex ey
blink = 1 - ((sin (t*0.5))**200)*0.8
drawParagraph :: Context -> CFloat -> CFloat -> CFloat -> CFloat -> CFloat -> CFloat -> IO ()
drawParagraph c x y w h mx my =
do save c
fontSize c 18
fontFace c "sans"
textAlign c (S.fromList [AlignLeft,AlignTop])
(_,_,lineh) <- textMetrics c
gutter <- newIORef Nothing
yEnd <- newIORef y
NVG.textBreakLines c text w 3 $ \row i -> do
let y' = y + fromIntegral i * lineh
hit = mx > x && mx < (x+w) && my >= y' && my < (y' + lineh)
writeIORef yEnd y'
beginPath c
fillColor c (rgba 255 255 255 (if hit then 64 else 16))
rect c x y' (width row) lineh
fill c
fillColor c (rgba 255 255 255 255)
Internal.text c x y' (start row) (end row)
when hit $ do
let caretxInit = if mx < x+ (width row) / 2 then x else x + width row
ps = x
glyphs <- NVG.textGlyphPositions c x y (start row) (end row) 100
let leftBorders = V.map glyphX glyphs
rightBorders = V.snoc (V.drop 1 leftBorders) (x + width row)
rightPoints = V.zipWith (\x y -> 0.3*x+0.7*y) leftBorders rightBorders
leftPoints = V.cons x (V.take (V.length glyphs - 1) rightPoints)
caretx = maybe caretxInit (glyphX . (glyphs V.!)) $ V.findIndex (\(px,gx) -> mx >= px && mx < gx) $ V.zip leftPoints rightPoints
beginPath c
fillColor c (rgba 255 192 0 255)
rect c caretx y' 1 lineh
fill c
-- realized too late that I probably should have used a fold
writeIORef gutter (Just (i+1,x-10,y'+lineh/2))
gutter' <- readIORef gutter
forM_ gutter' $ \(gutter,gx,gy) -> do
let txt = T.pack $ show gutter
fontSize c 13
textAlign c (S.fromList [AlignRight,AlignMiddle])
(Bounds (V4 b0 b1 b2 b3)) <- textBounds c gx gy txt
beginPath c
fillColor c (rgba 255 192 0 255)
roundedRect c (b0-4) (b1-2) ((b2-b0)+8) ((b3-b1)+4) (((b3-b1)+4)/2-1)
fill c
fillColor c (rgba 32 32 32 255)
NVG.text c gx gy txt
y' <- (\x -> x+20+lineh) <$> readIORef yEnd
fontSize c 13
textAlign c (S.fromList [AlignLeft, AlignTop])
textLineHeight c 1.2
(Bounds (V4 b0 b1 b2 b3)) <- textBoxBounds c x y' 150 helpText
let gx = abs $ (mx - (b0+b2)*0.5) / (b0 - b2)
gy = abs $ (my - (b1+b3)*0.5) / (b1 - b3)
a = (\x -> clamp x 0 1) $ max gx gy - 0.5
globalAlpha c a
beginPath c
fillColor c (rgba 220 220 220 255)
roundedRect c (b0-2) (b1-2) ((b2-b0)+4) ((b3-b1)+4) 3
let px = (b2+b0)/2
moveTo c px (b1-10)
lineTo c (px+7) (b1+1)
lineTo c (px-7) (b1+1)
fill c
fillColor c (rgba 0 0 0 220)
textBox c x y' 150 helpText
restore c
where text = "This is longer chunk of text.\n \n Would have used lorem ipsum but she was busy jumping over the lazy dog with the fox and all the men who came to the aid of the party."
helpText = "Hover your mouse over the text to see calculated caret position."
drawGraph :: Context -> CFloat -> CFloat -> CFloat -> CFloat -> CFloat -> IO ()
drawGraph c x y w h t =
do bg <- linearGradient c x y x (y+h) (rgba 0 16 192 0) (rgba 0 160 192 64)
beginPath c
moveTo c (sx V.! 0) (sy V.! 0)
forM_ [1..5] $ \i ->
bezierTo c (sx V.! (i-1) + dx*0.5) (sy V.! (i-1)) (sx V.! i - dx*0.5) (sy V.! i) (sx V.! i) (sy V.! i)
lineTo c (x+w) (y+h)
lineTo c x (y+h)
fillPaint c bg
fill c
beginPath c
moveTo c (sx V.! 0) (sy V.! 0 + 2)
forM_ [1..5] $ \i ->
bezierTo c (sx V.! (i-1)+dx*0.5) (sy V.! (i-1)+2) (sx V.! i - dx*0.5) (sy V.! i + 2) (sx V.! i) (sy V.! i + 2)
strokeColor c (rgba 0 0 0 32)
strokeWidth c 3
stroke c
beginPath c
moveTo c (sx V.! 0) (sy V.! 0)
forM_ [1..5] $ \i ->
bezierTo c (sx V.! (i-1)+dx*0.5) (sy V.! (i-1)) (sx V.! i - dx*0.5) (sy V.! i) (sx V.! i) (sy V.! i)
strokeColor c (rgba 0 160 192 255)
strokeWidth c 3
stroke c
V.forM_ (V.zip sx sy) $ \(x,y) ->
do bg <- radialGradient c x (y+2) 3 8 (rgba 0 0 0 32) (rgba 0 0 0 0)
beginPath c
rect c (x-10) (y-10+2) 20 20
fillPaint c bg
fill c
beginPath c
V.forM_ (V.zip sx sy) $ \(x,y) -> circle c x y 4
fillColor c (rgba 0 160 192 255)
fill c
beginPath c
V.forM_ (V.zip sx sy) $ \(x,y) -> circle c x y 2
fillColor c (rgba 220 220 220 255)
fill c
strokeWidth c 1
where samples :: V.Vector CFloat
samples =
V.fromList
[(1 + sin (t * 1.2345 + cos (t * 0.33457) * 0.44)) * 0.5
,(1 + sin (t * 0.68363 + cos (t * 1.3) * 1.55)) * 0.5
,(1 + sin (t * 1.1642 + cos (t * 0.33457) * 1.24)) * 0.5
,(1 + sin (t * 0.56345 + cos (t * 1.63) * 0.14)) * 0.5
,(1 + sin (t * 1.6245 + cos (t * 0.254) * 0.3)) * 0.5
,(1 + sin (t * 0.345 + cos (t * 0.03) * 0.6)) * 0.5]
dx = w / 5
sx :: V.Vector CFloat
sx =
V.generate 6
(\i -> x + fromIntegral i * dx)
sy :: V.Vector CFloat
sy = V.map (\s -> y + h * s * 0.8) samples
drawColorwheel :: Context -> CFloat -> CFloat -> CFloat -> CFloat -> CFloat -> IO ()
drawColorwheel c x y w h t =
do save c
forM_ [0..5] $ \i ->
do let a0 = i / 6 * pi * 2 - aeps
a1 = (i+1)/6*pi*2+aeps
beginPath c
arc c cx cy r0 a0 a1 CW
arc c cx cy r1 a1 a0 CCW
closePath c
let ax = cx + cos a0 * (r0+r1)*0.5
ay = cy+sin a0 * (r0+r1)*0.5
bx = cx + cos a1 * (r0+r1) * 0.5
by = cy + sin a1 * (r0 + r1) * 0.5
paint <- linearGradient c ax ay bx by (hsla (a0/(2*pi)) 1 0.55 255) (hsla (a1/(2*pi)) 1 0.55 255)
fillPaint c paint
fill c
beginPath c
circle c cx cy (r0-0.5)
circle c cx cy (r1+0.5)
strokeColor c (rgba 0 0 0 64)
strokeWidth c 1
stroke c
save c
translate c cx cy
rotate c (hue*pi*2)
strokeWidth c 2
beginPath c
rect c (r0-1) (-3) (r1-r0+2) 6
strokeColor c (rgba 255 255 255 192)
stroke c
paint <- boxGradient c (r0-3) (-5) (r1-r0+6) 10 2 4 (rgba 0 0 0 128) (rgba 0 0 0 0)
beginPath c
rect c (r0-2-10) (-4-10) (r1-r0+4+20) (8+20)
rect c (r0-2) (-4) (r1-r0+4) 8
pathWinding c (fromIntegral$fromEnum Hole)
fillPaint c paint
fill c
let r = r0 - 6
ax = cos (120/180*pi) * r
ay = sin(120/180*pi) * r
bx = cos (-120/180*pi) * r
by = sin(-120/180*pi) * r
beginPath c
moveTo c r 0
lineTo c ax ay
lineTo c bx by
closePath c
paint <- linearGradient c r 0 ax ay (hsla hue 1 0.5 255) (rgba 255 255 255 255)
fillPaint c paint
fill c
strokeColor c (rgba 0 0 0 64)
stroke c
let ax = cos (120/180*pi)*r*0.3
ay = sin(120/180*pi)*r*0.4
strokeWidth c 2
beginPath c
circle c ax ay 5
strokeColor c (rgba 255 255 255 192)
stroke c
paint <- radialGradient c ax ay 7 9 (rgba 0 0 0 64) (rgba 0 0 0 0)
beginPath c
rect c (ax-20) (ay-20) 40 40
circle c ax ay 7
pathWinding c (fromIntegral$fromEnum Hole)
fillPaint c paint
fill c
restore c
restore c
where hue = sin (t * 0.12)
cx = x + w*0.5
cy = y+h*0.5
r1 = min w h * 0.5 - 5
r0 = r1 - 20
aeps = 0.5 / r1
drawLines :: Context -> CFloat -> CFloat -> CFloat -> CFloat -> CFloat -> IO ()
drawLines c x y w h t =
do save c
forM_ [0..2] $ \i -> forM_ [0..2] $ \j ->
do let fx = x +s*0.5+(fromIntegral i*3+fromIntegral j)/9*w+pad
fy = y-s*0.5+pad
lineCap c (caps V.! i)
lineJoin c (joins V.! j)
strokeWidth c (s*0.3)
strokeColor c (rgba 0 0 0 160)
beginPath c
moveTo c (fx + pts V.! 0) (fy + pts V.! 1)
moveTo c (fx + pts V.! 2) (fy + pts V.! 3)
moveTo c (fx + pts V.! 4) (fy + pts V.! 5)
moveTo c (fx + pts V.! 6) (fy + pts V.! 7)
stroke c
lineCap c Butt
lineJoin c Bevel
strokeWidth c 1
strokeColor c (rgba 0 192 255 255)
beginPath c
moveTo c (fx + pts V.! 0) (fy + pts V.! 1)
moveTo c (fx + pts V.! 2) (fy + pts V.! 3)
moveTo c (fx + pts V.! 4) (fy + pts V.! 5)
moveTo c (fx + pts V.! 6) (fy + pts V.! 7)
stroke c
restore c
where pad = 0.5
s = w / 9 - pad * 2
joins = V.fromList [Miter,Round,Bevel]
caps = V.fromList [Butt,Round,Square]
pts =
V.fromList
[-s * 0.25 + cos (t * 0.3) * s * 0.5
,sin (t * 0.3) * s * 0.5
,-s * 0.25
,0
,s * 0.25
,0
,s * 0.25 + cos (-t * 0.3) * s * 0.5
,sin (-t * 0.3) * s * 0.5]
drawWidths :: Context -> CFloat -> CFloat -> CFloat -> IO ()
drawWidths c x y width =
do save c
strokeColor c (rgba 0 0 0 255)
forM_ [0..19] $ \i ->
do let w = (i+0.5)*0.1
y' = y + (10*i)
strokeWidth c w
beginPath c
moveTo c x y'
lineTo c (x+width) (y'+width*0.3)
stroke c
restore c
data DemoData =
DemoData {fontNormal :: Font
,fontBold :: Font
,fontIcons :: Font
,images :: V.Vector Image}
loadDemoData :: Context -> MaybeT IO DemoData
loadDemoData c = do icons <- MaybeT $ createFont c "icons" (FileName "nanovg/example/entypo.ttf")
normal <- MaybeT $ createFont c "sans" (FileName "nanovg/example/Roboto-Regular.ttf")
bold <- MaybeT $ createFont c "sans-bold" (FileName "nanovg/example/Roboto-Bold.ttf")
images <- loadImages
pure (DemoData icons normal bold images)
where loadImages :: MaybeT IO (V.Vector Image)
loadImages =
V.generateM 12 $
\i ->
do let file = FileName $
"nanovg/example/images/image" <> T.pack (show (i + 1)) <> ".jpg"
MaybeT $ createImage c file S.empty
drawCaps :: Context -> CFloat -> CFloat -> CFloat -> IO ()
drawCaps c x y width =
do save c
beginPath c
rect c (x-lineWidth/2) y (width+lineWidth) 40
fillColor c (rgba 255 255 255 32)
fill c
beginPath c
rect c x y width 40
fillColor c (rgba 255 255 255 32)
fill c
strokeWidth c lineWidth
forM_ (zip [0..] [Butt,Round,Square]) $ \(i,cap) ->
do lineCap c cap
strokeColor c (rgba 0 0 0 255)
beginPath c
moveTo c x (y+i*10+5)
lineTo c (x+width) (y+i*10+5)
stroke c
restore c
where lineWidth = 8
drawScissor :: Context -> CFloat -> CFloat -> CFloat -> IO ()
drawScissor c x y t =
do save c
translate c x y
rotate c (degToRad 5)
beginPath c
rect c (-20) (-20) 60 40
fillColor c (rgba 255 0 0 255)
fill c
scissor c (-20) (-20) 60 40
translate c 40 0
rotate c t
save c
resetScissor c
beginPath c
rect c (-20) (-10) 60 30
fillColor c (rgba 255 128 0 64)
fill c
restore c
intersectScissor c (-20) (-10) 60 30
beginPath c
rect c (-20) (-10) 60 30
fillColor c (rgba 255 128 0 255)
fill c
restore c
drawComposite :: Context -> IO ()
drawComposite c = do
-- The example in https://github.com/memononen/nanovg/pull/298 implies the
-- need to call beginFrame/endFrame, but it does not seem to be necessary
save c
-- Clears a fragment of the background
globalCompositeOperation c DestinationOut
beginPath c
rect c 50 50 100 100
fillColor c (rgb 0 0 0)
fill c
-- Draws a red circle
globalCompositeOperation c SourceOver
beginPath c
circle c 100 100 30
fillColor c (rgb 255 0 0)
fill c
-- Draws a blue, rounded, rectangle behind the red circle
globalCompositeOperation c DestinationOver
beginPath c
roundedRectVarying c 60 60 80 60 20 10 20 10
fillColor c (rgb 0 0 255)
fill c
restore c
clamp :: Ord a => a -> a -> a -> a
clamp a' low up
| a' < low = low
| a' > up = up
| otherwise = a'
| cocreature/nanovg-hs | example/Example.hs | isc | 20,515 | 25 | 31 | 7,070 | 9,932 | 4,819 | 5,113 | 551 | 5 |
module LilRender.Shader.Library (
GouraudShader, gouraudShader
, PhongShader, phongShader
) where
import LilRender.Color
import qualified LilRender.Color.Named as NC
import LilRender.Math.Geometry
import LilRender.Math.Transform
import LilRender.Math.Vector
import LilRender.Model
import LilRender.Shader
import LilRender.Texture
import Control.Monad.Primitive
import qualified Data.Vector.Mutable as MV
data GouraudShader st = GouraudShader {
_gouraudStateVector :: MV.MVector st Double
, _gouraudLightingDirection :: World (Vector3 Double)
, _gouraudModelToWorldTransform :: Transform (ModelSpace (Vector3 Double)) (World (Vector3 Double))
}
instance Shader GouraudShader where
{-# INLINE vertexShader #-}
vertexShader (GouraudShader state (World lightDirection) modelToWorldTransform) vertex@(Vertex _ _ (Just (VertexNormal modelNormal))) nthVertex = do
let (World worldNormal) = transform modelToWorldTransform modelNormal
MV.write state nthVertex (dotVect worldNormal lightDirection)
return vertex
{-# INLINE fragmentShader #-}
fragmentShader GouraudShader { _gouraudStateVector = state } _ = do
n1 <- MV.read state 0
n2 <- MV.read state 1
n3 <- MV.read state 2
return (\point -> Just $ NC.orange `scaleColor` triangularInterpolate n1 n2 n3 point)
gouraudShader :: (PrimMonad m) => World (Vector3 Double) -> Transform (ModelSpace (Vector3 Double)) (World (Vector3 Double)) -> m (GouraudShader (PrimState m))
gouraudShader dir modelToWorld = do
state <- MV.new 3
return $ GouraudShader state dir modelToWorld
data PhongShader st = PhongShader {
_phongStateVector :: MV.MVector st (Double, Point2 Double)
, _phongLightingDirection :: World (Vector3 Double)
, _phongModelToWorldTransform :: Transform (ModelSpace (Vector3 Double)) (World (Vector3 Double))
}
instance Shader PhongShader where
{-# INLINE vertexShader #-}
vertexShader (PhongShader state (World lightDirection) modelToWorldTransform) vertex@(Vertex _ (Just (TextureCoordinate textureCoord)) (Just (VertexNormal modelNormal))) nthVertex = do
let (World worldNormal) = transform modelToWorldTransform modelNormal
MV.write state nthVertex (dotVect worldNormal lightDirection, textureCoord)
return vertex
{-# INLINE fragmentShader #-}
fragmentShader PhongShader { _phongStateVector = state } texture = do
(n1, Point2 t1x t1y) <- MV.read state 0
(n2, Point2 t2x t2y) <- MV.read state 1
(n3, Point2 t3x t3y) <- MV.read state 2
return (\point -> do
let tx = triangularInterpolate t1x t2x t3x point
let ty = triangularInterpolate t1y t2y t3y point
let color = getColorFromTexture texture (TextureCoordinate (Point2 tx ty))
Just (scaleColor color $ triangularInterpolate n1 n2 n3 point)
)
phongShader :: (PrimMonad m) => World (Vector3 Double) -> Transform (ModelSpace (Vector3 Double)) (World (Vector3 Double)) -> m (PhongShader (PrimState m))
phongShader dir modelToWorld = do
state <- MV.new 3
return $ PhongShader state dir modelToWorld
| SASinestro/lil-render | src/LilRender/Shader/Library.hs | isc | 3,288 | 0 | 20 | 753 | 988 | 498 | 490 | 57 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Snap.Core
import Snap.Http.Server
import Data.Monoid (mempty)
import qualified Data.ByteString.Char8 as B8
import Data.String.Conversions (convertString)
import Control.Monad (liftM)
import Text.Read (readMaybe)
import System.Environment (getArgs)
import Trace
jsResponse :: String -> Snap ()
jsResponse str = do
modifyResponse $ addHeader "Content-Type" "text/plain; charset=UTF-8"
modifyResponse $ addHeader "Access-Control-Allow-Origin" "*"
writeLBS $ convertString str
app = do
code <- (return . maybe "" id . fmap convertString) =<< getQueryParam "code"
let tracedCode = traceJS code
jsResponse tracedCode
runServer :: Int -> IO ()
runServer port = httpServe config app
where config = setPort port
. setAccessLog ConfigNoLog
. setErrorLog (ConfigIoLog B8.putStrLn)
$ mempty
main :: IO ()
main = getArgs >>= runServer . read . head
| heyLu/tracing-js | TraceServer.hs | mit | 965 | 10 | 12 | 204 | 311 | 146 | 165 | 27 | 1 |
module Rebase.Control.Category
(
module Control.Category
)
where
import Control.Category
| nikita-volkov/rebase | library/Rebase/Control/Category.hs | mit | 92 | 0 | 5 | 12 | 20 | 13 | 7 | 4 | 0 |
------------------------- State
type Variable = String
type State = [(Variable,Integer)]
empty :: State
empty = []
get :: State -> Variable -> Integer
get [] _ = 0
get ((x,n):xs) y | x == y = n
| otherwise = get xs y
set :: Variable -> Integer -> State -> State
set x n s = (x,n) : del x s
where
del _ [] = []
del y (x:xs) | fst x == y = xs
| otherwise = x : del y xs
------------------------- Input-Output streams
type Stream = [Integer]
------------------------- Part 2
data Aexp = Num Integer
| Var Variable
| Aexp :+: Aexp
| Aexp :-: Aexp
| Aexp :*: Aexp
| Next
evalA :: Aexp -> State -> Stream -> (Integer,Stream)
evalA (Num n) _ st = (n,st)
evalA (Var v) s st = (get s v,st)
evalA (a :+: b) s st = ((x + y),st2) where (x,st1) = evalA a s st
(y,st2) = evalA b s st1
evalA (a :*: b) s st = ((x * y),st2) where (x,st1) = evalA a s st
(y,st2) = evalA b s st1
evalA (a :-: b) s st = ((x - y),st2) where (x,st1) = evalA a s st
(y,st2) = evalA b s st1
evalA Next _ (a:as) = (a,as)
as::Stream
as = [1,2,3,4,5,6,7,8,9,10]
--a1 :: Aexp
a1 = undefined
--a2 :: Aexp
a2 = undefined
------------------------- Part 3
data Bexp = Boolean Bool
| Aexp :==: Aexp
| Aexp :<=: Aexp
| Neg Bexp
| Bexp :&: Bexp
| Bexp :|: Bexp
| Bexp :&&: Bexp
| Bexp :||: Bexp
evalB :: Bexp -> State -> Stream -> (Bool,Stream)
evalB (Boolean b) _ st = (b,st)
evalB (a :==: b) s st = ((x == y),st2) where (x,st1) = evalA a s st
(y,st2) = evalA b s st1
evalB (a :<=: b) s st = ((x <= y),st2) where (x,st1) = evalA a s st
(y,st2) = evalA b s st1
evalB (Neg b) s st = ((not x),st1) where (x,st1) = evalB b s st
evalB (a :&: b) s st = ((x && y),st2) where (x,st1) = evalB a s st
(y,st2) = evalB b s st1
evalB (a :|: b) s st = ((x || y),st2) where (x,st1) = evalB a s st
(y,st2) = evalB b s st1
evalB (a :&&: b) s st | evalB a s st = evalB b s st
| otherwise = (False,st)
evalB (a :||: b) s st | evalB a s st = (True,st)
| otherwise = evalB b s st
b1 = undefined
b2 = undefined
bs = undefined
------------------------- Part 4
{-
data Comm = Skip
| Variable :=: Aexp
| Comm :>: Comm
| If Bexp Comm Comm
| While Bexp Comm
| Print Aexp
evalC :: Comm -> State -> (State,Stream)
evalC Skip s = (s,[])
evalC (v :=: a) s = (set v x s,[]) where x = evalA a s
evalC (c :>: d) s = (u, xs ++ ys) where (t,xs) = evalC c s
(u,ys) = evalC d t
evalC (If b c d) s | evalB b s = evalC c s
| otherwise = evalC d s
evalC (While b c) s | evalB b s = (u, ys ++ zs)
| otherwise = (s,[]) where (t,ys) = evalC c s
(u,zs) = evalC (While b c) t
evalC (Print a) s = (s, [evalA a s])
{-
factorial :: Comm
factorial = ("x" :=: Next) :>:
("y" :=: Num 1) :>:
While (Num 1 :<=: Var "x") (
("y" :=: (Var "x" :*: Var "y")) :>:
("x" :=: (Var "x" :-: Num 1))
) :>:
Print (Var "y")
runFactorial :: Stream -> Stream
runFactorial a = out
where
(_,out) = evalC factorial empty a
-}
------------------------- Part 1
c1 = (While ((Var "x") :==: (Num 0)) (Print (Num 0)))
c2 = ("x" :=: Num 0) :>:
While (Num 0 :<=: Var "x")
(("x" :=: (Var "x" :+: Num 1)) :>:
Print (Var "x"))
------------------------- Part 5
-- data Chain =
-} | We220/Haskell_Coursework_1 | coursework_1.hs | mit | 3,981 | 31 | 14 | 1,617 | 1,336 | 665 | 671 | 60 | 2 |
module Rebase.Foreign.ForeignPtr.Safe
(
module Foreign.ForeignPtr.Safe
)
where
import Foreign.ForeignPtr.Safe
| nikita-volkov/rebase | library/Rebase/Foreign/ForeignPtr/Safe.hs | mit | 113 | 0 | 5 | 12 | 23 | 16 | 7 | 4 | 0 |
-- file 1.hs
import Control.Exception (evaluate)
import Test.Hspec
-- Problem 1
-- Find the last element of a list.
last' :: [a] -> a
last' [] = error "Please provide a list with at least one element"
last' [x] = x
last' (_:xs) = last' xs
main :: IO()
main = hspec $
describe "99-exercises.1 = Last element of list" $ do
it "returns the last element of a list" $ do
last' [1..20] `shouldBe` (20 :: Int)
last' "hello world" `shouldBe` 'd'
it "throws an exception when the list is empty" $
evaluate (last' []) `shouldThrow` anyException
| baldore/haskell-99-exercises | 1.hs | mit | 586 | 2 | 13 | 149 | 185 | 91 | 94 | 14 | 1 |
module Utils(
fst',
snd',
span',
extract,
lastN,
race,
isValidIdentifier,
Stack,
top,
pop,
push,
singleton,
updateTop,
while,
(<>>),
getString
)where
import Control.Applicative
import Data.Char
-- Apply a function to the fst element of a pair
fst' :: (a -> b) -> (a, c) -> (b, c)
fst' f (a, b) = (f a, b)
-- Apply a function to the snd element of a pair
snd' :: (a -> b) -> (c, a) -> (c, b)
snd' f (a, b) = (a, f b)
-- Similiar to `span`, but put the first unqualified element in the fst position
-- eg. span (/=';') "abc;efg" = ("abc", ";efg")
-- eg. span' (/=';') "abc;efg" = ("abc;", "efg")
span' :: (a -> Bool) -> [a] -> ([a], [a])
span' f [] = ([], [])
span' f (x:xs) = if f x then fst' (x:) $ span' f xs else ([x], xs)
-- Drop the fst and last elements of a list
extract :: [a] -> [a]
extract = tail . init
-- Find the last n elements of a list
lastN :: Int -> [a] -> [a]
lastN n l = reverse $ take n $ reverse l
-- race a b l: if a appears first in l, returns LT; else GT. If neither, returns EQ
race :: Eq a => a -> a -> [a] -> Ordering
race _ _ [] = EQ
race x y (a:as) =
if x == y then EQ
else if x == a then LT
else if y == a then GT
else race x y as
isValidIdentifier :: String -> Bool
isValidIdentifier s@(x:xs) = (isAlpha x || x == '_') && (all (\c -> isAlphaNum c || c == '_') xs)
type Stack = []
top = head
pop = tail
push = (:)
-- null
singleton = pure :: a -> Stack a
updateTop f s = push (f $ top s) $ pop s
while con = until (not . con)
(<>>) :: (Monad f, Applicative f) => f (a -> b) -> a -> f b
f <>> x = f <*> return x
getString :: IO String
getString = do
c <- getChar
if isSpace c then return "" else (c:) <$> getString
| sqd/haskell-C89-interpreter | Utils.hs | mit | 1,681 | 0 | 12 | 408 | 735 | 411 | 324 | 52 | 4 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Utils where
import Control.Monad (when)
import Data.List (isInfixOf)
import qualified System.Directory as D (createDirectoryIfMissing)
import System.Exit (exitFailure)
import System.IO (hPutStrLn, stderr)
import Types
debug :: (MonadReader SparkConfig m, MonadIO m) => String -> m ()
debug str = incase (asks conf_debug) $ liftIO $ putStrLn str
incase :: MonadReader SparkConfig m => (SparkConfig -> Bool) -> m () -> m ()
incase bf func = do
b <- asks bf
when b func
incaseElse :: MonadReader SparkConfig m => (SparkConfig -> Bool) -> m a -> m a -> m a
incaseElse bf funcif funcelse = do
b <- asks bf
if b
then funcif
else funcelse
die :: String -> IO a
die err = hPutStrLn stderr err >> exitFailure
containsNewline :: String -> Bool
containsNewline f = any (\c -> elem c f) ['\n', '\r']
containsMultipleConsequtiveSlashes :: String -> Bool
containsMultipleConsequtiveSlashes = isInfixOf "//"
(&&&) :: (a -> Bool) -> (a -> Bool) -> a -> Bool
(&&&) f g = \a -> f a && g a
(|||) :: (a -> Bool) -> (a -> Bool) -> a -> Bool
(|||) f g = \a -> f a || g a
createDirectoryIfMissing :: FilePath -> IO ()
createDirectoryIfMissing = D.createDirectoryIfMissing True
| badi/super-user-spark | src/Utils.hs | mit | 1,346 | 0 | 9 | 325 | 497 | 261 | 236 | 33 | 2 |
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
module Backend.Language.Haskell where
import Backend.Language.Common
import Data.Default.Class
import Data.Function
import Data.Functor.Foldable
import Data.List (intersperse)
import Data.String
import Data.Text.Prettyprint.Doc
data DestrF a
= VarDF Symbol
| ListDF [a]
| ConDF Symbol [a]
| TupDF [a]
deriving (Functor, Foldable, Traversable)
newtype Destr = Destr (DestrF Destr)
type instance Base Destr = DestrF
instance Recursive Destr where project (Destr a) = a
instance Corecursive Destr where embed = Destr
pattern VarD v = Destr (VarDF v)
pattern ListD l = Destr (ListDF l)
pattern ConD s v = Destr (ConDF s v)
pattern TupD v = Destr (TupDF v)
data ExprF a
= VarEF Symbol
| ApplyEF a a
| LambdaEF (Function a)
| DoEF (GStmt a)
| LetEF Destr a a
| IfEF a a a
| LitEF Lit
deriving (Functor, Traversable, Foldable)
newtype Expr = Expr (ExprF Expr)
type instance Base Expr = ExprF
instance Recursive Expr where project (Expr e) = e
instance Corecursive Expr where embed = Expr
pattern VarE s = Expr (VarEF s)
pattern ApplyE a b = Expr (ApplyEF a b)
pattern LambdaE f = Expr (LambdaEF f)
pattern DoE s = Expr (DoEF s)
pattern LetE d e b = Expr (LetEF d e b)
pattern IfE i t e = Expr (IfEF i t e)
pattern LitE l = Expr (LitEF l)
data Lit
= LitInt Int
| LitStr String
| LitBool Bool
| LitList [Expr]
data StmtF e a
= BindSF Destr e a
| LetSF Destr e a
| RetSF e
deriving (Functor, Foldable, Traversable)
newtype GStmt e = GStmt (StmtF e (GStmt e))
type Stmt = GStmt Expr
instance Functor GStmt where
fmap f = cata $ embed . \case
BindSF d e a -> BindSF d (f e) a
LetSF d e a -> LetSF d (f e) a
RetSF e -> RetSF $ f e
instance Foldable GStmt where
foldMap f = cata $ \case
BindSF _ e a -> f e `mappend` a
LetSF _ e a -> f e `mappend` a
RetSF e -> f e
instance Traversable GStmt where
sequenceA = cata $ fmap embed . \case
BindSF b e a -> BindSF b <$> e <*> a
LetSF b e a -> LetSF b <$> e <*> a
RetSF e -> RetSF <$> e
type instance Base (GStmt e) = StmtF e
instance Recursive (GStmt e) where project (GStmt s) = s
instance Corecursive (GStmt e) where embed = GStmt
pattern BindS d e s = GStmt (BindSF d e s)
pattern LetS d e s = GStmt (LetSF d e s)
pattern RetS e = GStmt (RetSF e)
renderProgram :: Program Expr -> Serialized
renderProgram Program{..} = vsep $ intersperse line
$ map renderNamedFunction functions
++ [renderNamedFunction $ NamedFunction "main" main]
renderNamedFunction :: NamedFunction Expr -> Serialized
renderNamedFunction NamedFunction{functionName = name, namedFunctionFunction = Function{..}} =
vsep
[ hsep $ rname : "::" : intersperse "->" (map (const "Int") parameters ++ ["IO ()"])
, hsep $ rname : rparams ++ ["=", renderExpr functionBody]
]
where
rparams = map pretty parameters
rname = pretty name
mkSig = intersperse "->" . map (const $ "Int")
renderFunction :: Function Expr -> Serialized
renderFunction Function{..} = "\\" <> hsep (map pretty parameters) <+> "->" <+> renderExpr functionBody
renderExpr :: Expr -> Serialized
renderExpr = renderPrec False
where
renderPrec _ (VarE v) = pretty v
renderPrec _ (LitE lit) = renderLit lit
renderPrec p other | p = parens r
| otherwise = r
where
r = case other of
LetE var e b -> "let" <+> renderDestr var <+> "=" <+> renderExpr e <+> "in" <+> renderExpr b
IfE b t e -> "if" <+> renderExpr b <+> "then" <+> renderExpr t <+> "else" <+> renderExpr e
ApplyE fun arg -> renderPrec False fun <+> renderPrec True arg
DoE b -> "do" <> line <> indent 2 (renderStmt b)
LambdaE l -> renderFunction l
renderLit (LitInt i) = pretty $ show i
renderLit (LitStr str) = pretty $ show str
renderLit (LitBool b) = pretty $ show b
renderLit (LitList l) = brackets $ hcat $ intersperse "," $ map renderExpr l
renderStmt (BindS var val cont) = renderDestr var <+> "<-" <+> renderExpr val <> line <> renderStmt cont
renderStmt (RetS e) = renderExpr e
renderStmt (LetS var val cont) = "let" <+> renderDestr var <+> "=" <+> renderExpr val <> line <> renderStmt cont
renderDestr = renderDestrPrec False
renderDestrPrec _ (VarD s) = pretty s
renderDestrPrec _ (ListD l) = brackets $ hcat $ intersperse "," $ map (renderDestrPrec False) l
renderDestrPrec _ (TupD l) = parens $ hcat $ intersperse "," $ map (renderDestrPrec False) l
renderDestrPrec p (ConD con fields) | p = parens r
| otherwise = r
where
r = hsep $ pretty con : map (renderDestrPrec True) fields
| goens/rand-code-graph | src/Backend/Language/Haskell.hs | mit | 5,116 | 0 | 17 | 1,283 | 1,943 | 967 | 976 | 126 | 7 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Concurrent (forkFinally)
import Control.Concurrent.STM
import Control.Exception (bracketOnError)
import Control.Monad
import "monad-logger" Control.Monad.Logger
import Control.Monad.Reader
import Control.Monad.Except
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Version (showVersion)
import Network hiding (socketPort)
import Network.BSD (getProtocolNumber)
import Network.Socket hiding (PortNumber, Type, accept,
sClose)
import Options.Applicative
import PureScript.Ide
import PureScript.Ide.CodecJSON
import PureScript.Ide.Command
import PureScript.Ide.Error
import PureScript.Ide.Types
import PureScript.Ide.Watcher
import System.Directory
import System.Exit
import System.FilePath
import System.IO
import qualified Paths_psc_ide as Paths
-- "Borrowed" from the Idris Compiler
-- Copied from upstream impl of listenOn
-- bound to localhost interface instead of iNADDR_ANY
listenOnLocalhost :: PortID -> IO Socket
listenOnLocalhost (PortNumber port) = do
proto <- getProtocolNumber "tcp"
localhost <- inet_addr "127.0.0.1"
bracketOnError
(socket AF_INET Stream proto)
sClose
(\sock -> do
setSocketOption sock ReuseAddr 1
bindSocket sock (SockAddrInet port localhost)
listen sock maxListenQueue
pure sock)
listenOnLocalhost _ = error "Wrong Porttype"
data Options = Options
{ optionsDirectory :: Maybe FilePath
, optionsOutputPath :: FilePath
, optionsPort :: Int
, optionsDebug :: Bool
}
main :: IO ()
main = do
Options dir outputPath port debug <- execParser opts
maybe (pure ()) setCurrentDirectory dir
serverState <- newTVarIO emptyPscState
cwd <- getCurrentDirectory
_ <- forkFinally (watcher serverState (cwd </> outputPath)) print
let conf =
Configuration
{
confDebug = debug
, confOutputPath = outputPath
}
let env =
PscEnvironment
{
envStateVar = serverState
, envConfiguration = conf
}
startServer (PortNumber (fromIntegral port)) env
where
parser =
Options <$>
optional (strOption (long "directory" <> short 'd')) <*>
strOption (long "output-directory" <> value "output/") <*>
option auto (long "port" <> short 'p' <> value 4242) <*>
switch (long "debug")
opts = info (version <*> parser) mempty
version = abortOption
(InfoMsg (showVersion Paths.version))
(long "version" <> help "Show the version number")
startServer :: PortID -> PscEnvironment -> IO ()
startServer port env = withSocketsDo $ do
sock <- listenOnLocalhost port
runLogger (runReaderT (forever (loop sock)) env)
where
runLogger = runStdoutLoggingT . filterLogger (\_ _ -> confDebug (envConfiguration env))
loop :: (PscIde m, MonadLogger m) => Socket -> m ()
loop sock = do
(cmd,h) <- acceptCommand sock
case decodeT cmd of
Just cmd' -> do
result <- runExceptT (handleCommand cmd')
$(logDebug) ("Answer was: " <> T.pack (show result))
liftIO (hFlush stdout)
case result of
-- What function can I use to clean this up?
Right r -> liftIO $ T.hPutStrLn h (encodeT r)
Left err -> liftIO $ T.hPutStrLn h (encodeT err)
Nothing -> do
$(logDebug) ("Parsing the command failed. Command: " <> cmd)
liftIO $ T.hPutStrLn h (encodeT (GeneralError "Error parsing Command.")) >> hFlush stdout
liftIO (hClose h)
acceptCommand :: (MonadIO m, MonadLogger m) => Socket -> m (T.Text, Handle)
acceptCommand sock = do
h <- acceptConnection
$(logDebug) "Accepted a connection"
cmd <- liftIO (T.hGetLine h)
$(logDebug) cmd
pure (cmd, h)
where
acceptConnection = liftIO $ do
(h,_,_) <- accept sock
hSetEncoding h utf8
hSetBuffering h LineBuffering
pure h
handleCommand :: (PscIde m, MonadLogger m, MonadError PscIdeError m) =>
Command -> m Success
handleCommand (Load modules deps) =
loadModulesAndDeps modules deps
handleCommand (Type search filters) =
findType search filters
handleCommand (Complete filters matcher) =
findCompletions filters matcher
handleCommand (Pursuit query Package) =
findPursuitPackages query
handleCommand (Pursuit query Identifier) =
findPursuitCompletions query
handleCommand (List LoadedModules) =
printModules
handleCommand (List AvailableModules) =
listAvailableModules
handleCommand (List (Imports fp)) =
importsForFile fp
handleCommand (CaseSplit l b e wca t) =
caseSplit l b e wca t
handleCommand (AddClause l wca) =
pure $ addClause l wca
handleCommand Cwd =
TextResult . T.pack <$> liftIO getCurrentDirectory
handleCommand Quit = liftIO exitSuccess
| kRITZCREEK/psc-ide | server/Main.hs | mit | 5,295 | 0 | 20 | 1,455 | 1,451 | 731 | 720 | 132 | 3 |
--------------------------------------------------------------------------------
-- | String-like data structure utilities
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Web.SocketIO.Types.String (
S.IsString(..)
, IsByteString(..)
, IsLazyByteString(..)
, IsText(..)
, IsLazyText(..)
, Serializable(..)
, Text
, StrictText
, ByteString
, LazyByteString
, (<>)
) where
--------------------------------------------------------------------------------
import qualified Data.Aeson as Aeson
import qualified Data.String as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TLE
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BLC
import Data.Monoid ((<>), Monoid)
--------------------------------------------------------------------------------
-- | Lazy Text as default Text
type Text = TL.Text
--------------------------------------------------------------------------------
-- | Type synonym of Strict Text
type StrictText = T.Text
--------------------------------------------------------------------------------
-- | Type synonym of Lazy ByteString
type LazyByteString = BL.ByteString
--------------------------------------------------------------------------------
-- | Class for string-like data structures that can be converted from strict ByteString
class IsByteString a where
fromByteString :: ByteString -> a
-- | to String
instance IsByteString String where
fromByteString = BC.unpack
-- | to strict Text
instance IsByteString T.Text where
fromByteString = TE.decodeUtf8
-- | to lazy Text
instance IsByteString TL.Text where
fromByteString = TLE.decodeUtf8 . BL.fromStrict
-- | to strict ByteString (identity)
instance IsByteString ByteString where
fromByteString = id
-- | to lazy ByteString
instance IsByteString BL.ByteString where
fromByteString = BL.fromStrict
--------------------------------------------------------------------------------
-- | Class for string-like data structures that can be converted from lazy ByteString
class IsLazyByteString a where
fromLazyByteString :: BL.ByteString -> a
-- | to String
instance IsLazyByteString String where
fromLazyByteString = BLC.unpack
-- | to strict Text
instance IsLazyByteString T.Text where
fromLazyByteString = TE.decodeUtf8 . BL.toStrict
-- | to lazy Text
instance IsLazyByteString TL.Text where
fromLazyByteString = TLE.decodeUtf8
-- | to strict ByteString
instance IsLazyByteString ByteString where
fromLazyByteString = BL.toStrict
-- | to lazy ByteString (identity)
instance IsLazyByteString BL.ByteString where
fromLazyByteString = id
--------------------------------------------------------------------------------
-- | Class for string-like data structures that can be converted from strict Text
class IsText a where
fromText :: T.Text -> a
-- | to String
instance IsText String where
fromText = T.unpack
-- | to strict Text (identity)
instance IsText T.Text where
fromText = id
-- | to lazy Text
instance IsText TL.Text where
fromText = TL.fromStrict
-- | to strict ByteString
instance IsText ByteString where
fromText = TE.encodeUtf8
-- | to lazy ByteString
instance IsText BL.ByteString where
fromText = TLE.encodeUtf8 . TL.fromStrict
--------------------------------------------------------------------------------
-- | Class for string-like data structures that can be converted from lazy Text
class IsLazyText a where
fromLazyText :: TL.Text -> a
-- | to String
instance IsLazyText String where
fromLazyText = TL.unpack
-- | to strict Text
instance IsLazyText T.Text where
fromLazyText = TL.toStrict
-- | to lazy Text (identity)
instance IsLazyText TL.Text where
fromLazyText = id
-- | to strict ByteString
instance IsLazyText ByteString where
fromLazyText = TE.encodeUtf8 . TL.toStrict
-- | to lazy ByteString
instance IsLazyText BL.ByteString where
fromLazyText = TLE.encodeUtf8
--------------------------------------------------------------------------------
-- | Class for string-like data structures
class Serializable a where
-- | converts instances to string-like data structures
serialize :: ( Monoid s
, S.IsString s
, IsText s
, IsLazyText s
, IsByteString s
, IsLazyByteString s
, Show a) => a -> s
serialize = S.fromString . show
instance Serializable Aeson.Value where
serialize = fromLazyByteString . Aeson.encode
instance Serializable T.Text where
serialize = fromText
instance Serializable TL.Text where
serialize = fromLazyText
instance Serializable ByteString where
serialize = fromByteString
instance Serializable BL.ByteString where
serialize = fromLazyByteString
instance Serializable Bool
instance Serializable Char
instance Serializable Double
instance Serializable Float
instance Serializable Int
instance Serializable Integer
instance Serializable Ordering
instance Serializable ()
instance Serializable a => Serializable [a]
instance Serializable a => Serializable (Maybe a)
instance (Serializable a, Serializable b) => Serializable (Either a b)
instance (Serializable a, Serializable b, Serializable c) => Serializable (a, b, c)
instance (Serializable a, Serializable b, Serializable c, Serializable d) => Serializable (a, b, c, d)
instance (Serializable a, Serializable b, Serializable c, Serializable d, Serializable e) => Serializable (a, b, c, d, e) | banacorn/socket.io-haskell | Web/SocketIO/Types/String.hs | mit | 6,067 | 0 | 9 | 1,297 | 1,078 | 617 | 461 | 109 | 0 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, GeneralizedNewtypeDeriving, OverloadedStrings, FlexibleContexts #-}
module DigitalOcean where
import qualified API
import Control.Applicative
import Control.Lens
import Control.Lens.TH
import Control.Monad.Reader
import Control.Monad.Trans
import Control.Monad.Trans.Either
import Control.Monad.Trans.Resource
import Data.Aeson
import Data.Aeson.TH
import Data.ByteString.Char8 (ByteString, pack)
import qualified Data.Text as T
import Data.List
import Network.HTTP.Conduit hiding (port)
import URI.TH
import URI.Types
type DropletId = Int
type ImageId = Int
type RegionId = Int
type SizeOptionId = Int
type EventId = Int
type DomainId = Int
type SshKeyId = Int
type RecordId = Int
type IpAddress = T.Text
type NewSshKey = T.Text
type NewDomain = T.Text
data Credentials = Credentials
{ _credentialsClientId :: T.Text
, _credentialsApiKey :: T.Text
} deriving (Read, Show, Eq)
data Droplet = Droplet
{ _dropletBackupsActive :: Maybe Bool
, _dropletId :: DropletId
, _dropletImageId :: ImageId
, _dropletRegionId :: RegionId
, _dropletSizeId :: SizeOptionId
, _dropletStatus :: T.Text
} deriving (Read, Show, Eq)
data NewDropletOptions = NewDropletOptions
{ _newdropletoptionsName :: T.Text
, _newdropletoptionsSizeId :: SizeOptionId
, _newdropletoptionsImageId :: ImageId
, _newdropletoptionsRegionId :: RegionId
, _newdropletoptionsSshKeyIds :: [SshKeyId]
} deriving (Read, Show, Eq)
data NewDroplet = NewDroplet
{ _newdropletId :: DropletId
, _newdropletName :: T.Text
, _newdropletImageId :: ImageId
, _newdropletSizeId :: SizeOptionId
, _newdropletEventId :: EventId
} deriving (Read, Show, Eq)
data Event = Event
{ _eventEventId :: EventId
} deriving (Read, Show, Eq)
data Region = Region
{ _regionId :: RegionId
, _regionName :: T.Text
} deriving (Read, Show, Eq)
data Image = Image
{ _imageId :: ImageId
, _imageName :: T.Text
, _imageDistribution :: T.Text
} deriving (Read, Show, Eq)
data SshKeyInfo = SshKeyInfo
{ _sshkeyinfoId :: SshKeyId
, _sshkeyinfoName :: T.Text
} deriving (Read, Show, Eq)
data SshKey = SshKey
{ _sshkeyId :: SshKeyId
, _sshkeyName :: T.Text
, _sshkeySshPubKey :: T.Text
} deriving (Read, Show, Eq)
data SizeOption = SizeOption
{ _sizeoptionId :: SizeOptionId
, _sizeoptionName :: T.Text
} deriving (Read, Show, Eq)
data Domain = Domain
{ _domainId :: DomainId
, _domainName :: T.Text
, _domainTtl :: Int
, _domainLiveZoneFile :: T.Text
, _domainError :: Maybe T.Text
, _domainZoneFileWithError :: Maybe T.Text
} deriving (Read, Show, Eq)
data DomainRecord = DomainRecord
{ _domainrecordId :: RecordId
, _domainrecordDomainId :: DomainId
, _domainrecordType :: T.Text
, _domainrecordName :: T.Text
, _domainrecordData :: T.Text
, _domainrecordPriority :: Maybe Int
, _domainrecordPort :: Maybe Int
, _domainrecordWeight :: Maybe Int
} deriving (Read, Show, Eq)
data NewRecord = NewRecord
{ _newrecordRecordType :: T.Text
, _newrecordInfo :: T.Text
, _newrecordName :: Maybe T.Text
, _newrecordPriority :: Maybe Int
, _newrecordPort :: Maybe Int
, _newrecordWeight :: Maybe Int
} deriving (Read, Show, Eq)
makeFields ''Credentials
makeFields ''NewDropletOptions
makeFields ''Droplet
makeFields ''NewDroplet
makeFields ''Event
makeFields ''Region
makeFields ''Image
makeFields ''SshKeyInfo
makeFields ''SshKey
makeFields ''SizeOption
makeFields ''Domain
makeFields ''DomainRecord
makeFields ''NewRecord
deriveJSON Prelude.id ''Credentials
deriveJSON Prelude.id ''NewDropletOptions
deriveJSON Prelude.id ''Droplet
deriveJSON Prelude.id ''NewDroplet
deriveJSON Prelude.id ''Event
deriveJSON Prelude.id ''Region
deriveJSON Prelude.id ''Image
deriveJSON Prelude.id ''SshKeyInfo
deriveJSON Prelude.id ''SshKey
deriveJSON Prelude.id ''SizeOption
deriveJSON Prelude.id ''Domain
deriveJSON Prelude.id ''DomainRecord
deriveJSON Prelude.id ''NewRecord
data ImageType = MyImages | Global
instance ToTemplateValue T.Text SingleElement where
toTemplateValue = Single . T.unpack
instance (ToTemplateValue a SingleElement) => ToTemplateValue (Maybe a) SingleElement where
toTemplateValue Nothing = Single ""
toTemplateValue (Just v) = toTemplateValue v
instance ToTemplateValue ImageType SingleElement where
toTemplateValue MyImages = Single "my_images"
toTemplateValue Global = Single "global"
instance ToTemplateValue [SshKeyId] SingleElement where
toTemplateValue ks = Single $ intercalate "," $ map show ks
instance ToTemplateValue Credentials AssociativeListElement where
toTemplateValue x = Associative
[ ("api_key", toTemplateValue $ x ^. apiKey)
, ("client_id", toTemplateValue $ x ^. clientId)
]
instance ToTemplateValue NewDropletOptions AssociativeListElement where
toTemplateValue x = Associative
[ ("name", toTemplateValue $ x ^. name)
, ("size_id", toTemplateValue $ x ^. sizeId)
, ("image_id", toTemplateValue $ x ^. imageId)
, ("region_id", toTemplateValue $ x ^. regionId)
, ("ssh_key_ids", toTemplateValue $ x ^. sshKeyIds)
]
instance ToTemplateValue NewRecord AssociativeListElement where
toTemplateValue x = Associative
[ ("record_type", toTemplateValue $ x ^. recordType)
, ("data", toTemplateValue $ x ^. info)
, ("name", toTemplateValue $ x ^. name)
, ("priority", toTemplateValue $ x ^. priority)
, ("port", toTemplateValue $ x ^. port)
, ("weight", toTemplateValue $ x ^. weight)
]
newtype DigitalOcean a = DigitalOcean { fromDigitalOcean :: ReaderT Credentials API.APIClient a }
deriving (Functor, Applicative, Monad, MonadIO)
runDigitalOcean :: Credentials -> DigitalOcean a -> IO (Either API.APIError a)
runDigitalOcean c m = API.runAPIClient
"https://api.digitalocean.com/"
Prelude.id
(runReaderT (fromDigitalOcean m) c)
get :: FromJSON a => String -> DigitalOcean (Response a)
get = DigitalOcean . lift . API.get . pack
creds :: DigitalOcean Credentials
creds = DigitalOcean ask
-- | /droplets
getDroplets :: DigitalOcean (Response [Droplet])
getDroplets = do
credentials <- creds
get [uri| /droplets{?credentials*} |]
---- | /droplets/new
addDroplet :: NewDropletOptions -> DigitalOcean (Response NewDroplet)
addDroplet newDroplet = do
credentials <- creds
get [uri| /droplets/new{?newDroplet*, credentials*} |]
---- | /droplets/{dropletId}
getDroplet :: DropletId -> DigitalOcean (Response Droplet)
getDroplet dropletId = do
credentials <- creds
get [uri| /droplets/{dropletId}{?credentials*} |]
---- /droplets/{dropletId}/reboot
rebootDroplet :: DropletId -> DigitalOcean (Response Event)
rebootDroplet dropletId = do
credentials <- creds
get [uri| /droplets/{dropletId}/reboot{?credentials*} |]
---- /droplets/{dropletId}/power_cycle
powerCycleDroplet :: DropletId -> DigitalOcean (Response Event)
powerCycleDroplet dropletId = do
credentials <- creds
get [uri| /droplets/{dropletId}/power_cycle{?credentials*} |]
---- /droplets/{dropletId}/shutdown
shutdownDroplet :: DropletId -> DigitalOcean (Response Event)
shutdownDroplet dropletId = do
credentials <- creds
get [uri| /droplets/{dropletId}/shutdown{?credentials*} |]
---- /droplets/{dropletId}/power_off
powerOffDroplet :: DropletId -> DigitalOcean (Response Event)
powerOffDroplet dropletId = do
credentials <- creds
get [uri| /droplets/{dropletId}/power_off{?credentials*} |]
---- /droplets/{dropletId}/power_on
powerOnDroplet :: DropletId -> DigitalOcean (Response Event)
powerOnDroplet dropletId = do
credentials <- creds
get [uri| /droplets/{dropletId}/power_on{?credentials*} |]
---- /droplets/{dropletId}/password_reset
resetRootDropletPassword :: DropletId -> DigitalOcean (Response Event)
resetRootDropletPassword dropletId = do
credentials <- creds
get [uri| /droplets/{dropletId}/password_reset{?credentials*} |]
---- /droplets/{dropletId}/resize
resizeDroplet :: DropletId -> SizeOptionId -> DigitalOcean (Response Event)
resizeDroplet dropletId sizeId = do
credentials <- creds
get [uri| /droplets/{dropletId}/resize{?credentials*} |]
where size_id = sizeId
---- /droplets/{dropletId}/snapshot
takeDropletSnapshot :: DropletId -> Maybe T.Text -> DigitalOcean (Response Event)
takeDropletSnapshot dropletId name = do
credentials <- creds
get [uri| /droplets/{dropletId}/snapshot{?name, credentials*} |]
---- /droplets/{dropletId}/restore
restoreDroplet :: DropletId -> ImageId -> DigitalOcean (Response Event)
restoreDroplet dropletId imageId = do
credentials <- creds
get [uri| /droplets/{dropletId}/restore{?image_id, credentials*} |]
where image_id = imageId
---- /droplets/{dropletId}/rebuild
rebuildDroplet :: DropletId -> ImageId -> DigitalOcean (Response Event)
rebuildDroplet dropletId imageId = do
credentials <- creds
get [uri| /droplets/{dropletId}/rebuild{?image_id, credentials*} |]
where image_id = imageId
---- /droplets/{dropletId}/enable_backups
enableDropletBackups :: DropletId -> DigitalOcean (Response Event)
enableDropletBackups dropletId = do
credentials <- creds
get [uri| /droplets/{dropletId}/enable_backups{?credentials*} |]
---- /droplets/{dropletId}/disable_backups
disableDropletBackups :: DropletId -> DigitalOcean (Response Event)
disableDropletBackups dropletId = do
credentials <- creds
get [uri| /droplets/{dropletId}/disable_backups{?credentials*} |]
---- /droplets/{dropletId}/rename
renameDroplet :: DropletId -> String -> DigitalOcean (Response Event)
renameDroplet dropletId name = do
credentials <- creds
get [uri| /droplets/{dropletId}/rename{?name, credentials*} |]
---- /droplets/{dropletId}/destroy
destroyDroplet :: DropletId -> DigitalOcean (Response Event)
destroyDroplet dropletId = do
credentials <- creds
get [uri| /droplets/{dropletId}/destroy{?credentials*} |]
---- /regions
getRegions :: DigitalOcean (Response [Region])
getRegions = do
credentials <- creds
get [uri| /regions{?credentials*} |]
---- /images
getImages :: Maybe ImageType -> DigitalOcean (Response [Image])
getImages filter = do
credentials <- creds
get [uri| /images{?filter, credentials*} |]
---- /images/{imageId}
getImage :: ImageId -> DigitalOcean (Response Image)
getImage imageId = do
credentials <- creds
get [uri| /images/{imageId}{?credentials*} |]
---- /images/{imageId}/destroy
destroyImage :: ImageId -> DigitalOcean (Response ())
destroyImage imageId = do
credentials <- creds
get [uri| /images/{imageId}/destroy{?credentials*} |]
---- /images/{imageId}/transfer
transferImage :: ImageId -> RegionId -> DigitalOcean (Response Event)
transferImage imageId regionId = do
credentials <- creds
get [uri| /images/{imageId}/transfer{?region_id, credentials*} |]
where region_id = regionId
---- /ssh_keys
getSshKeys :: DigitalOcean (Response [SshKeyInfo])
getSshKeys = do
credentials <- creds
get [uri| /ssh_keys{?credentials*} |]
---- /ssh_keys/new
addSshKey :: String -> String -> DigitalOcean (Response NewSshKey)
addSshKey name sshKeyPub = do
credentials <- creds
get [uri| /ssh_keys/new{?name, ssh_key_pub, credentials*} |]
where ssh_key_pub = sshKeyPub
---- /ssh_key/{sshKeyId}
getSshKey :: SshKeyId -> DigitalOcean (Response SshKey)
getSshKey sshKeyId = do
credentials <- creds
get [uri| /ssh_key/{sshKeyId}{?credentials*} |]
---- /ssh_key/{sshKeyId}/edit
editSshKey :: SshKeyId -> String -> DigitalOcean (Response SshKey)
editSshKey sshKeyId sshKeyPub = do
credentials <- creds
get [uri| /ssh_key/{sshKeyId}/edit{?ssh_key_pub, credentials*} |]
where ssh_key_pub = sshKeyPub
---- /ssh_key/{sshKeyId}/destroy
removeSshKey :: SshKeyId -> DigitalOcean (Response Bool)
removeSshKey sshKeyId = do
credentials <- creds
get [uri| /ssh_key/{sshKeyId}/destroy{?credentials*} |]
---- /sizes
getInstanceSizeOptions :: DigitalOcean (Response [SizeOption])
getInstanceSizeOptions = do
credentials <- creds
get [uri| /sizes{?credentials*} |]
---- /domains
getDomains :: DigitalOcean (Response [Domain])
getDomains = do
credentials <- creds
get [uri| /domains{?credentials*} |]
---- /domains/new
addDomain :: T.Text -> IpAddress -> DigitalOcean (Response NewDomain)
addDomain name ipAddress = do
credentials <- creds
get [uri| /domains/new{?name, ip_address, credentials*} |]
where ip_address = ipAddress
---- /domains/{domainId}
getDomain :: DomainId -> DigitalOcean (Response Domain)
getDomain domainId = do
credentials <- creds
get [uri| /domains/{domainId}{?credentials*} |]
---- /domains/{domainId}/destroy
removeDomain :: DomainId -> DigitalOcean (Response Bool)
removeDomain domainId = do
credentials <- creds
get [uri| /domains/{domainId}/destroy{?credentials*} |]
---- /domains/{domainId}/records
getDomainRecords :: DomainId -> DigitalOcean (Response [DomainRecord])
getDomainRecords domainId = do
credentials <- creds
get [uri| /domains/{domainId}/records{?credentials*} |]
---- /domains/{domainId}/records/new
addDomainRecord :: DomainId -> NewRecord -> DigitalOcean (Response DomainRecord)
addDomainRecord domainId newRecord = do
credentials <- creds
get [uri| /domains/{domainId}/records/new{?newRecord*, credentials*} |]
---- /domains/{domainId}/records/{recordId}
getDomainRecord :: DomainId -> RecordId -> DigitalOcean (Response DomainRecord)
getDomainRecord domainId recordId = do
credentials <- creds
get [uri| /domains/{domainId}/records/{recordId}{?credentials*} |]
---- /domains/{domainId}/records/{recordId}/destroy
removeDomainRecord :: DomainId -> RecordId -> DigitalOcean (Response Bool)
removeDomainRecord domainId recordId = do
credentials <- creds
get [uri| /domains/{domainId}/records/{recordId}/destroy{?credentials*} |]
| iand675/digital-ocean | src/DigitalOcean.hs | mit | 13,738 | 0 | 10 | 1,978 | 3,448 | 1,851 | 1,597 | 324 | 1 |
module Cook.Catalog.Git (
gitClone
) where
import Cook.Recipe
gitClone :: String -> Recipe f ()
gitClone repo = withRecipeName "Git.Clone" $ runProc "git" ["clone", repo]
| jimenezrick/cook.hs | src/Cook/Catalog/Git.hs | mit | 179 | 0 | 7 | 33 | 59 | 32 | 27 | 5 | 1 |
module Magento.Layout.XML (
generateLayout
) where
import Data.Functor ((<$>))
import Data.List (intersect)
import System.FilePath.Posix (makeRelative, pathSeparator)
import System.FilePath.Glob (globDir, compile)
import System.FilePath.Posix (
joinPath,
dropExtension,
splitDirectories)
import Template.Layout (genXml)
import Magento.Controller (parentClassName)
import Magento.Module.Path (
basePath,
jsBasePath,
skinBasePath,
templateBasePath,
blockBasePath,
controllersBasePath)
import Magento.Module (
ModuleInfo,
getName,
getNamespace,
getConfigXml,
getFullName)
import Util (lowercase)
import Util.XML (printXml)
import Util.PHP (
PhpClass,
readClass,
getClassName,
getParentName,
getPublicFunctions)
import Data.String.Utils (join, split, replace)
generateLayout :: ModuleInfo -> String -> IO ()
generateLayout info scope = do
controllers <- collectControllers info scope
stylesheets <- collectStylesheets info scope
skinJavascripts <- collectSkinJavascripts info scope
javascripts <- collectJavascripts info
blocks <- collectBlocks info scope
xml <- genXml controllers stylesheets skinJavascripts javascripts blocks
printXml xml
collectControllers :: ModuleInfo -> String -> IO [String]
collectControllers info scope =
let basePath = controllersBasePath info in do
files <- findPhpFiles basePath
readHandles info scope $ map (\x -> joinPath [basePath, x]) files
collectStylesheets :: ModuleInfo -> String -> IO [FilePath]
collectStylesheets info scope =
findCssFiles (skinBasePath info $ scopeName scope)
collectSkinJavascripts :: ModuleInfo -> String -> IO [FilePath]
collectSkinJavascripts info scope =
findJsFiles (skinBasePath info $ scopeName scope)
collectJavascripts :: ModuleInfo -> IO [FilePath]
collectJavascripts info = findJsFiles (jsBasePath info)
collectBlocks :: ModuleInfo -> String -> IO [(String, String, String)]
collectBlocks info scope = do
blocks <- findPhpFiles (blockBasePath info)
templates <- findPhtmlFiles (templateBasePath info $ scopeName scope)
return $ map blockTuple
(intersectingPaths (prefixModuleName info blocks) templates)
blockTuple :: FilePath -> (String, String, String)
blockTuple path = (blockClassPath path, templatePath path, blockName path)
readHandles :: ModuleInfo -> String -> [FilePath] -> IO [String]
readHandles info scope paths = do
classes <- mapM readClass paths
return $ concat $ map (handles info) (filterByScope scope classes)
handles :: ModuleInfo -> PhpClass -> [String]
handles info cls = map (handle info cls) (getPublicFunctions cls)
handle :: ModuleInfo -> PhpClass -> String -> String
handle info cls fn =
lowercase $ join "_" [
getName info,
replace "Controller" "" $ last $ split "_" $ getClassName cls,
replace "Action()" "" fn
]
filterByScope :: String -> [PhpClass] -> [PhpClass]
filterByScope scope classes =
filter (\x -> getParentName x == parentClassName scope) classes
findJsFiles :: FilePath -> IO [FilePath]
findJsFiles path = findFiles path ["**/*.js"]
findCssFiles :: FilePath -> IO [FilePath]
findCssFiles path = findFiles path ["**/*.css"]
findPhpFiles :: FilePath -> IO [FilePath]
findPhpFiles path = findFiles path ["**/*.php"]
findPhtmlFiles :: FilePath -> IO [FilePath]
findPhtmlFiles path = findFiles path ["**/*.phtml"]
findFiles :: FilePath -> [String] -> IO [FilePath]
findFiles path patterns = do
files <- concat . fst <$> globDir (map compile patterns) path
return $ map (makeRelative path) files
blockName :: String -> String
blockName path = replace [pathSeparator] "_" path
blockClassPath :: FilePath -> String
blockClassPath path =
let xs = splitDirectories path in
(head xs) ++ "/" ++ join "_" (tail xs)
templatePath :: FilePath -> String
templatePath path = (join "/" (splitDirectories path)) ++ ".phtml"
prefixModuleName :: ModuleInfo -> [FilePath] -> [FilePath]
prefixModuleName info paths =
map (\path -> joinPath [getName info, path]) paths
normalizeAndSplit :: FilePath -> [String]
normalizeAndSplit str = splitDirectories $ lowercase $ dropExtension str
intersectingPaths :: [FilePath] -> [FilePath] -> [FilePath]
intersectingPaths paths paths' =
map joinPath $ intersect
(map normalizeAndSplit paths)
(map normalizeAndSplit paths')
scopeName :: String -> String
scopeName "frontend" = "frontend"
scopeName "admin" = "adminhtml"
| prasmussen/magmod | Magento/Layout/XML.hs | mit | 4,498 | 0 | 14 | 806 | 1,419 | 733 | 686 | 112 | 1 |
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Review where
import Assignment
import Control.Exception
import Control.Monad
import Control.Monad.IO.Class (liftIO)
import Data.Random.Extras (sample)
import Data.Random.List (shuffle)
import Data.Random.RVar
import Data.Random.Source.DevRandom
import Data.Typeable
import Database.Persist
import Database.Persist.MySQL
import Database.Persist.TH
import DatabaseAccess
import ReviewRole
data ReviewAssignmentExistsException = ReviewAssignmentExistsException deriving (Show, Typeable)
instance Exception ReviewAssignmentExistsException
data NoSuchReviewAssignmentException = NoSuchReviewAssignmentException deriving (Show, Typeable)
instance Exception NoSuchReviewAssignmentException
share [mkPersist sqlSettings, mkMigrate "migrateReviewAssignments"] [persistLowerCase|
ReviewAssignment
reviewer UserIdentifier maxlen=10
reviewee UserIdentifier maxlen=10
role ReviewRole
assignment Assignment
deriving Show Eq
|]
-- | Database provider for this module.
databaseProviderReviews :: SqlPersistM a -> IO a
databaseProviderReviews action = abstractDatabaseProvider migrateReviewAssignments action
-- | Takes an Assignment, a list of reviewer identifiers and a
-- | list of reviewee identifiers and assigns N reviewees for each
-- | reviewer. It makes sure that a user never reviews themselves.
-- | The reviewer is assigned the reviews with the provided role.
assignNReviews :: Assignment -> [UserIdentifier]
-> [UserIdentifier]
-> Int
-> ReviewRole
-> IO [ReviewAssignment]
assignNReviews _ [] _ _ _ = return []
assignNReviews a (x:xs) ys n r = liftM2 (++) (createReviewList' a x ys n r) (assignNReviews a xs ys n r)
createReviewList' :: Assignment -> UserIdentifier -> [UserIdentifier] -> Int -> ReviewRole -> IO [ReviewAssignment]
createReviewList' a x ys n = createReviewList a x (createRandomList (removeIdList x ys) n) n
-- | Creates list of review assignments for given reviewer and list of reviees.
createReviewList :: Assignment -> UserIdentifier -> RVar [UserIdentifier] -> Int -> ReviewRole -> IO [ReviewAssignment]
createReviewList a x ys n r = do
list <- runRVar ys DevRandom
forM list $ \y -> return (ReviewAssignment x y r a)
-- | Removes given id from list.
removeIdList :: UserIdentifier -> [UserIdentifier] -> [UserIdentifier]
removeIdList x = filter (/= x)
-- | Creates random list of user identifiers. How should we handle
-- | case when n exceeds length of list.
createRandomList :: [UserIdentifier] -> Int -> RVar [UserIdentifier]
createRandomList ids n = sample n ids
shuffleList :: [a] -> IO [a]
shuffleList xs = runRVar (shuffle xs) DevRandom
-- | Takes an assignment, a list of reviewers and reviewees and a
-- | role. Assigns revieews to reviewers pseudorandomly until the
-- | list of revieews is exhausted. For N reviewers and M
-- | reviewees, ensures no reviewer gets less than
-- | floor (M / N) or more than ceil (M / N) reviews.
-- | Should NOT always assign more reviews to users listed
-- | at the beginning of the reviewer list.
assignReviews :: Assignment -> [UserIdentifier]
-> [UserIdentifier]
-> ReviewRole
-> IO [ReviewAssignment]
assignReviews a xs ys r = do
reviewers <- shuffleList xs
reviews <- shuffleList ys
let pairs = zip (cycle reviewers) reviews
unique = filter (uncurry (/=)) pairs
same = map fst $ filter (uncurry (==)) pairs
extra = zip same (tail $ cycle same)
-- | TODO: fix for 1 reviewer [] crash
revs = unique ++ extra
return $ map makeRev revs
where
makeRev t = ReviewAssignment (fst t) (snd t) r a
-- -- | Stores a list of review assignments into a database or
-- -- | file system.
-- storeAssigments :: [ReviewAssignment] -> IO ()
-- storeAssigments xs = forM_ xs $ \x -> databaseProviderReviews $ do
-- existing <- selectList
-- [ReviewAssignmentAssignment ==. reviewAssignmentAssignment x,
-- ReviewAssignmentReviewer ==. reviewAssignmentReviewer x,
-- ReviewAssignmentReviewee ==. reviewAssignmentReviewee x,
-- ReviewAssignmentRole ==. reviewAssignmentRole x] []
-- unless (null existing) $ throw ReviewAssignmentExistsException
-- void (insert x)
-- | Stores a list of review assignments into a database or
-- | file system.
storeAssigments :: [ReviewAssignment] -> IO ()
storeAssigments xs = forM_ xs $ \x -> databaseProviderReviews $ do
exists <- liftIO $ existsReviewAssignment x
unless (not exists) $ throw ReviewAssignmentExistsException
void (insert x)
-- | Function checks if given ReviewAssignment exists.
existsReviewAssignment :: ReviewAssignment -> IO Bool
existsReviewAssignment x = databaseProviderReviews $ do
existing <- selectList
[ReviewAssignmentAssignment ==. reviewAssignmentAssignment x,
ReviewAssignmentReviewer ==. reviewAssignmentReviewer x,
ReviewAssignmentReviewee ==. reviewAssignmentReviewee x,
ReviewAssignmentRole ==. reviewAssignmentRole x] []
return $ not $ null existing
-- | Retrieves all ReviewAssignments for an Assignment from
-- | a database or file system.
assignedReviews :: Assignment -> IO [ReviewAssignment]
assignedReviews a = databaseProviderReviews $ do
reviews <- selectList [ReviewAssignmentAssignment ==. a] []
liftIO $ return $ map unwrapEntity reviews
-- | Retrieves all ReviewAssignments for an Assignment and
-- | a UserIdentifier, i.e. all the reviews for that assigment
-- | the user has to perform.
assignmentsBy :: Assignment -> UserIdentifier -> IO [ReviewAssignment]
assignmentsBy a r = databaseProviderReviews $ do
reviews <- selectList [ReviewAssignmentAssignment ==. a, ReviewAssignmentReviewer ==. r] []
liftIO $ return $ map unwrapEntity reviews
-- | Retrieves all ReviewAssignments for an Assignment and
-- | a UserIdentifier, i.e. all the reviews for that assignment
-- | where the user is a reviewee.
assignmentsFor :: Assignment -> UserIdentifier -> IO [ReviewAssignment]
assignmentsFor a r = databaseProviderReviews $ do
reviews <- selectList [ReviewAssignmentAssignment ==. a, ReviewAssignmentReviewee ==. r] []
liftIO $ return $ map unwrapEntity reviews
-- | Utility function for unwrapping data from Entity context.
unwrapEntity :: Entity a -> a
unwrapEntity (Entity id x) = x
| mratkovic/PUH_project | src/Review.hs | mit | 6,971 | 0 | 13 | 1,511 | 1,266 | 669 | 597 | 92 | 1 |
module SMCDEL.Examples.CoinFlip where
import Data.Map.Strict (fromList)
import Data.List ((\\))
import SMCDEL.Language
import SMCDEL.Symbolic.S5 (boolBddOf)
import SMCDEL.Symbolic.K
coinStart :: BelScene
coinStart = (BlS [P 0] law obs, actual) where
law = boolBddOf (PrpF $ P 0)
obs = fromList [ ("a", allsamebdd [P 0]), ("b", allsamebdd [P 0]) ]
actual = [P 0]
flipRandomAndShowTo :: [Agent] -> Prp -> Agent -> Event
flipRandomAndShowTo everyone p i = (Trf [q] eventlaw changelaw obs, [q]) where
q = freshp [p]
eventlaw = Top
changelaw = fromList [ (p, boolBddOf $ PrpF q) ]
obs = fromList $
(i, allsamebdd [q]) :
[ (j,totalRelBdd) | j <- everyone \\ [i] ]
coinFlip :: Event
coinFlip = flipRandomAndShowTo ["a","b"] (P 0) "b"
coinResult :: BelScene
coinResult = coinStart `update` coinFlip
| jrclogic/SMCDEL | src/SMCDEL/Examples/CoinFlip.hs | gpl-2.0 | 826 | 0 | 12 | 160 | 345 | 196 | 149 | 23 | 1 |
module Bio.Alignment (module Bio.Alignment,
module Bio.Sequence,
module Bio.Alignment.Matrix,
module Bio.Alignment.Pairwise) where
import Tree
import Data.BitVector
import Parameters
import Foreign.Vector
import Bio.Sequence
import Bio.Alignment.Matrix
import Bio.Alignment.Pairwise
-- Alignment -> Int -> EVector Int-> EVector (EVector Int)
builtin builtin_leaf_sequence_counts 3 "leaf_sequence_counts" "Alignment"
branch_hmms (model,_) distances n_branches = listArray' $ map (model distances) [0..n_branches-1]
seqlength as tree node = pairwise_alignment_length1 (as!b) where
b = head $ edgesOutOfNode tree node
minimally_connect_characters a t = mkArray (numNodes t) node_to_bits where
pairs l = [(x,y) | (x:ys) <- tails l, y <- ys]
node_to_bits n = if is_leaf_node t n then
alignment_row_to_bitvector a n
else
foldl1 (.|.) $ [(character_behind_branch_array!b1) .&. (character_behind_branch_array!b2) | (b1,b2) <- pairs $ edgesTowardNode t n]
character_behind_branch b = case edgesBeforeEdge t b of [] -> alignment_row_to_bitvector a (sourceNode t b)
[b1,b2] -> (character_behind_branch_array!b1) .|. (character_behind_branch_array!b2)
character_behind_branch_array = mkArray (2*numBranches t) character_behind_branch
pairwise_alignments_from_matrix a tree = [ pairwise_alignment_from_bits bits1 bits2 | b <- [0..2*numBranches tree-1],
let bits1 = bits ! sourceNode tree b,
let bits2 = bits ! targetNode tree b]
where bits = minimally_connect_characters a tree
data AlignmentOnTree = AlignmentOnTree Tree Int (Array Int Int) (Array Int PairwiseAlignment)
n_sequences (AlignmentOnTree _ n _ _) = n
sequence_lengths (AlignmentOnTree _ _ ls _) = ls
pairwise_alignments (AlignmentOnTree _ _ _ as) = as
-- not using this right now
-- get_sequence_lengths leaf_seqs_array = mkArray (numElements leaf_seqs_array) (\node -> vector_size (leaf_seqs_array!node))
-- This function handles the case where we have only 1 sequence.
compute_sequence_lengths seqs tree as = [ if node < n_leaves then vector_size (seqs!node) else seqlength as tree node | node <- [0..numNodes tree-1] ]
where n_leaves = numElements seqs
-- Current a' is an alignment, but counts and mapping are EVector
builtin builtin_compress_alignment 1 "compress_alignment" "Alignment"
compress_alignment a = (compressed, counts, mapping) where ca = builtin_compress_alignment a
compressed = get_vector_index ca 0
counts = get_vector_index ca 1
mapping = get_vector_index ca 2
alignment_on_tree_length (AlignmentOnTree t _ ls as) = (ls!0) + sumi [numInsert (as!b) | b <- allEdgesFromNode t 0]
builtin builtin_uncompress_alignment 2 "uncompress_alignment" "Alignment"
uncompress_alignment (a, counts, mapping) = builtin_uncompress_alignment a mapping
-- Alignment -> Int -> EVector Int -> [EVector Int]
leaf_sequence_counts a n counts = list_from_vector $ builtin_leaf_sequence_counts a n counts
builtin builtin_ancestral_sequence_alignment 3 "ancestral_sequence_alignment" "Alignment"
ancestral_sequence_alignment a0 states smap = builtin_ancestral_sequence_alignment a0 states smap
builtin builtin_select_alignment_columns 2 "select_alignment_columns" "Alignment"
select_alignment_columns alignment sites = builtin_select_alignment_columns alignment (list_to_vector sites)
builtin builtin_select_alignment_pairs 3 "select_alignment_pairs" "Alignment"
select_alignment_pairs alignment sites doublets = builtin_select_alignment_pairs alignment sites' doublets
where sites' = list_to_vector $ map (\(x,y) -> c_pair x y) sites
| bredelings/BAli-Phy | haskell/Bio/Alignment.hs | gpl-2.0 | 4,100 | 0 | 13 | 1,036 | 971 | 501 | 470 | -1 | -1 |
--
-- Copyright (c) 2013 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
{-# LANGUAGE ScopedTypeVariables, CPP #-}
module DBusArgo (
domainSystemBus
, remoteDomainBus
) where
import qualified Control.Exception as E
import Control.Applicative
import Control.Monad
import Control.Concurrent
import qualified Data.Set as Set
import Data.Maybe
import Data.String
import Network.Socket (SocketType (..))
import System.Posix.Types
import System.Posix.IO
import qualified Data.ByteString as B
import qualified Network.DBus as D
import qualified Network.DBus.Actions as D
import qualified Tools.Argo as A
domainSystemBus :: Int -> IO D.DBusContext
remoteDomainBus :: Int -> Int -> IO D.DBusContext
domainSystemBus domain = remoteDomainBus domain 5555
remoteDomainBus domain argoPort = do
let addr = A.Addr argoPort domain
fd <- connect addr
D.contextNewWith (argoTransport fd)
where
connect addr = A.socket Stream >>= \f ->
-- be careful to close fd on connect error..
( do setFdOption f NonBlockingRead False
A.connect f addr
setFdOption f NonBlockingRead True
return f )
`E.catch` connect_error f
where connect_error f (err::E.SomeException) = A.close f >> E.throw err
argoTransport fd
= D.DBusTransport { D.transportPut = send fd
, D.transportGet = recv fd
, D.transportClose = close fd }
send fd buf = do sent <- A.send fd buf 0
if sent < (B.length buf)
then send fd (B.drop sent buf)
else return ()
-- seems to be needed because stupid dbus bindings do recv 0 and argo blocks on that ?
recv fd 0 = return B.empty
recv fd sz = recv_aux fd (fromIntegral sz)
recv_aux fd sz = do chunk <- A.recv fd (fromIntegral $ sz) 0
case B.length chunk of
0 -> return chunk
l | l >= sz -> return chunk
_ -> B.append chunk <$> recv_aux fd (sz - B.length chunk)
close fd = A.close fd
| OpenXT/manager | xec/DBusArgo.hs | gpl-2.0 | 2,974 | 0 | 17 | 926 | 604 | 320 | 284 | 48 | 5 |
{-# LANGUAGE Arrows #-}
module FRP.Chimera.Agent.Interface
(
AgentId
, AgentData
, DataFilter
, AgentObservable
, Agent
, AgentRandom
, AgentConversationSender
, AgentPureBehaviour
, AgentPureBehaviourReadEnv
, AgentPureBehaviourNoEnv
, AgentDef (..)
, AgentIn (..)
, AgentOut (..)
, agentId
, createAgent
, kill
, isDead
, agentOut
, agentOutObservable
, nextAgentId
, onStart
, onEvent
, dataFlow
, dataFlowTo
, dataFlows
, broadcastDataFlow
, hasDataFlow
, onDataFlow
, onFilterDataFlow
, onDataFlowFrom
, onDataFlowType
, hasConversation
, conversation
, conversationEnd
, agentObservable
, updateAgentObservable
, setAgentObservable
, recInitAllowed
, allowsRecOthers
, recursive
, unrecursive
, isRecursive
, agentRecursions
, agentPure
, agentPureReadEnv
, agentPureIgnoreEnv
, startingAgent
, startingAgentIn
, startingAgentInFromAgentDef
) where
import Data.List
import Data.Maybe
import Control.Concurrent.STM.TVar
import Control.Monad.Random
import Control.Monad.State
import FRP.BearRiver
import FRP.Chimera.Simulation.Internal
type AgentId = Int
type AgentData d = (AgentId, d)
type DataFilter d = AgentData d -> Bool
type AgentObservable o = (AgentId, o)
type Agent m o d e = SF (StateT (AgentOut m o d e) m) (AgentIn o d e, e) e
type AgentRandom o d e g = Agent (Rand g) o d e
{--
type AgentConversationReceiver o d e = (AgentIn o d e
-> e
-> AgentData d
-> Maybe (s, m, e)) -- NOTE: the receiver MUST reply, otherwise we could've used the normal messaging
-}
type AgentConversationSender m o d e = (AgentOut m o d e
-> e
-> Maybe (AgentData d) -- NOTE: this will be Nothing in case the conversation with the target was not established e.g. id not found, target got no receiving handler
-> (AgentOut m o d e, e))
type AgentPureBehaviour m o d e = e -> Double -> AgentIn o d e -> (AgentOut m o d e, e)
type AgentPureBehaviourReadEnv m o d e = e -> Double -> AgentIn o d e -> AgentOut m o d e
type AgentPureBehaviourNoEnv m o d e = Double -> AgentIn o d e -> AgentOut m o d e
data AgentDef m o d e = AgentDef
{ adId :: !AgentId
, adBeh :: Agent m o d e
, adInitData :: ![AgentData d] -- AgentId identifies sender
}
data AgentIn o d e = AgentIn
{ aiId :: !AgentId
, aiData :: ![AgentData d] -- AgentId identifies sender
, aiConversationIncoming :: !(Event (AgentData d))
, aiStart :: !(Event ())
, aiRec :: !(Event [(AgentObservable o, e)])
, aiRecInitAllowed :: !Bool
, aiIdGen :: !(TVar Int)
}
data AgentOut m o d e = AgentOut
{ aoKill :: !(Event ())
, aoCreate :: ![AgentDef m o d e]
, aoData :: ![AgentData d] -- AgentId identifies receiver
, aoConversationRequest :: !(Event (AgentData d, AgentConversationSender m o d e))
, aoConversationReply :: !(Event (AgentData d))
, aoObservable :: !(Maybe o) -- OPTIONAL observable state
, aoRec :: !(Event ())
, aoRecOthersAllowed :: !Bool
}
-------------------------------------------------------------------------------
-- GENERAL
-------------------------------------------------------------------------------
agentId :: AgentIn o d e -> AgentId
agentId = aiId
createAgent :: AgentDef m o d e -> AgentOut m o d e -> AgentOut m o d e
createAgent newDef ao = ao { aoCreate = newDef : aoCreate ao }
agentOut:: AgentOut m o d e
agentOut = agentOutAux Nothing
agentOutObservable :: o -> AgentOut m o d e
agentOutObservable o = agentOutAux (Just o)
nextAgentId :: AgentIn o d e -> AgentId
nextAgentId AgentIn { aiIdGen = idGen } = incrementAtomicallyUnsafe idGen
kill :: AgentOut m o d e -> AgentOut m o d e
kill ao = ao { aoKill = Event () }
isDead :: AgentOut m o d e -> Bool
isDead = isEvent . aoKill
-------------------------------------------------------------------------------
-- EVENTS
-------------------------------------------------------------------------------
onStart :: (AgentOut m o d e -> AgentOut m o d e)
-> AgentIn o d e
-> AgentOut m o d e
-> AgentOut m o d e
onStart evtHdl ai ao = onEvent evtHdl startEvt ao
where
startEvt = aiStart ai
onEvent :: (AgentOut m o d e -> AgentOut m o d e)
-> Event ()
-> AgentOut m o d e
-> AgentOut m o d e
onEvent evtHdl evt ao = event ao (\_ -> evtHdl ao) evt
-------------------------------------------------------------------------------
-- MESSAGING / DATA-FLOW
-------------------------------------------------------------------------------
dataFlow :: AgentData d -> AgentOut m o d e -> AgentOut m o d e
dataFlow d ao = ao { aoData = d : aoData ao }
dataFlowTo :: AgentId -> d -> AgentOut m o d e -> AgentOut m o d e
dataFlowTo aid msg ao = dataFlow (aid, msg) ao
dataFlows :: [AgentData d] -> AgentOut m o d e -> AgentOut m o d e
dataFlows msgs ao = foldr dataFlow ao msgs
broadcastDataFlow :: d -> [AgentId] -> AgentOut m o d e -> AgentOut m o d e
broadcastDataFlow d receiverIds ao = dataFlows datas ao
where
n = length receiverIds
ds = replicate n d
datas = zip receiverIds ds
hasDataFlow :: Eq d => d -> AgentIn o d e -> Bool
hasDataFlow d ai = Data.List.any ((==d) . snd) (aiData ai)
onDataFlow :: (AgentData d -> acc -> acc) -> AgentIn o d e -> acc -> acc
onDataFlow dataHdl ai a = foldr (\d acc'-> dataHdl d acc') a ds
where
ds = aiData ai
onFilterDataFlow :: DataFilter d
-> (AgentData d -> acc -> acc)
-> AgentIn o d e
-> acc
-> acc
onFilterDataFlow dataFilter dataHdl ai acc =
foldr (\d acc'-> dataHdl d acc') acc dsFiltered
where
ds = aiData ai
dsFiltered = filter dataFilter ds
onDataFlowFrom :: AgentId
-> (AgentData d -> acc -> acc)
-> AgentIn o d e
-> acc
-> acc
onDataFlowFrom senderId datHdl ai acc =
onFilterDataFlow filterBySender datHdl ai acc
where
filterBySender = (\(senderId', _) -> senderId == senderId' )
onDataFlowType :: (Eq d)
=> d
-> (AgentData d -> acc -> acc)
-> AgentIn o d e
-> acc
-> acc
onDataFlowType d datHdl ai acc = onFilterDataFlow filterByType datHdl ai acc
where
filterByType = (==d) . snd
-------------------------------------------------------------------------------
-- OBSERVABLE STATE
-------------------------------------------------------------------------------
-- NOTE: assuming that state isJust
agentObservable :: AgentOut m o d e -> o
agentObservable = fromJust . aoObservable
-- NOTE: assuming that state isJust
updateAgentObservable :: (o -> o) -> AgentOut m o d e -> AgentOut m o d e
updateAgentObservable f ao =
ao { aoObservable = Just $ f $ fromJust $ aoObservable ao }
setAgentObservable :: o -> AgentOut m o d e -> AgentOut m o d e
setAgentObservable o ao = updateAgentObservable (const o) ao
-------------------------------------------------------------------------------
-- Conversations
-------------------------------------------------------------------------------
hasConversation :: AgentOut m o d e -> Bool
hasConversation = isEvent . aoConversationRequest
conversation :: AgentData d
-> AgentConversationSender m o d e
-> AgentOut m o d e
-> AgentOut m o d e
conversation msg replyHdl ao = ao { aoConversationRequest = Event (msg, replyHdl)}
conversationEnd :: AgentOut m o d e -> AgentOut m o d e
conversationEnd ao = ao { aoConversationRequest = NoEvent }
-------------------------------------------------------------------------------
-- RECURSION
-------------------------------------------------------------------------------
agentRecursions :: AgentIn o d e -> Event [(AgentObservable o, e)]
agentRecursions = aiRec
recInitAllowed :: AgentIn o d e -> Bool
recInitAllowed = aiRecInitAllowed
allowsRecOthers :: AgentOut m o d e -> Bool
allowsRecOthers = aoRecOthersAllowed
recursive :: Bool -> AgentOut m o d e -> AgentOut m o d e
recursive allowOthers aout =
aout { aoRec = Event (), aoRecOthersAllowed = allowOthers }
unrecursive :: AgentOut m o d e -> AgentOut m o d e
unrecursive aout = aout { aoRec = NoEvent }
isRecursive :: AgentIn o d e -> Bool
isRecursive ain = isEvent $ aiRec ain
-------------------------------------------------------------------------------
-- PURE WRAPPERS
-------------------------------------------------------------------------------
agentPure :: Monad m
=> AgentPureBehaviour m o d e
-> Agent m o d e
agentPure f = proc (ain, e) -> do
t <- time -< ()
let (_ao, e') = f e t ain
-- TODO: put ao using state-monad
returnA -< e'
agentPureReadEnv :: Monad m
=> AgentPureBehaviourReadEnv m o d e
-> Agent m o d e
agentPureReadEnv f = proc (ain, e) -> do
t <- time -< ()
let _ao = f e t ain
-- TODO: put ao using state-monad
returnA -< e
agentPureIgnoreEnv :: Monad m
=> AgentPureBehaviourNoEnv m o d e
-> Agent m o d e
agentPureIgnoreEnv f = proc (ain, e) -> do
t <- time -< ()
let _ao = f t ain
-- TODO: put ao using state-monad
returnA -< e
-------------------------------------------------------------------------------
-- UTILS
-------------------------------------------------------------------------------
startingAgentIn :: [AgentDef m o d e] -> TVar Int -> [AgentIn o d e]
startingAgentIn adefs idGen = map (startingAgentInFromAgentDef idGen) adefs
startingAgent :: [AgentDef m o d e]
-> TVar Int
-> ([Agent m o d e], [AgentIn o d e])
startingAgent adefs idGen = (sfs, ains)
where
ains = startingAgentIn adefs idGen
sfs = map adBeh adefs
startingAgentInFromAgentDef :: TVar Int -> AgentDef m o d e -> AgentIn o d e
startingAgentInFromAgentDef idGen ad =
AgentIn { aiId = adId ad
, aiData = adInitData ad
, aiConversationIncoming = NoEvent
, aiStart = Event ()
, aiRec = NoEvent
, aiRecInitAllowed = True
, aiIdGen = idGen
}
-------------------------------------------------------------------------------
-- PRIVATE
-------------------------------------------------------------------------------
agentOutAux :: Maybe o -> AgentOut m o d e
agentOutAux o =
AgentOut { aoKill = NoEvent
, aoCreate = []
, aoData = []
, aoConversationRequest = NoEvent
, aoConversationReply = NoEvent
, aoObservable = o
, aoRec = NoEvent
, aoRecOthersAllowed = True
} | thalerjonathan/phd | coding/libraries/chimera/src/FRP/Chimera/Agent/Interface.hs | gpl-3.0 | 11,141 | 3 | 14 | 3,035 | 3,095 | 1,651 | 1,444 | 270 | 1 |
module ParserTest where
import Test.HUnit
import SubsParser
introAST :: String
introAST = "Right (Prog [VarDecl \"xs\" (Just (Array [Number 0,Number 1,Number 2,Number 3,Number 4,Number 5,Number 6,Number 7,Number 8,Number 9])),VarDecl \"squares\" (Just (Compr (\"x\",Var \"xs\",Nothing) (Call \"*\" [Var \"x\",Var \"x\"]))),VarDecl \"evens\" (Just (Compr (\"x\",Var \"xs\",Just (ArrayIf (Call \"===\" [Call \"%\" [Var \"x\",Number 2],Number 0]) Nothing)) (Var \"x\"))),VarDecl \"many_a\" (Just (Compr (\"x\",Var \"xs\",Just (ArrayForCompr (\"y\",Var \"xs\",Nothing))) (String \"a\"))),VarDecl \"hundred\" (Just (Compr (\"i\",Array [Number 0],Just (ArrayForCompr (\"x\",Var \"xs\",Just (ArrayForCompr (\"y\",Var \"xs\",Nothing))))) (Assign \"i\" (Call \"+\" [Var \"i\",Number 1]))))])"
funNameAST :: String
funNameAST = "Right (Prog [VarDecl \"k\" (Just (Call \"one.two.three\" [Number 1,Number 2,Number 3]))])"
precedence1AST :: String
precedence1AST = "Right (Prog [ExprAsStm (Call \"+\" [Call \"-\" [Call \"+\" [Number 2,Call \"*\" [Number 3,Number 4]],Number 1],Call \"%\" [Number 2,Number 2]])])"
precedence2AST :: String
precedence2AST = "Right (Prog [ExprAsStm (Call \"===\" [Call \"+\" [Number 7,Number 42],Call \"<\" [Number 12,Number 99]])])"
associativityAST :: String
associativityAST = "Right (Prog [VarDecl \"k\" (Just (Assign \"l\" (Var \"m\")))])"
allowedIdentsAST :: String
allowedIdentsAST = "Right (Prog [VarDecl \"k\" (Just (Var \"_k02__\"))])"
illegalIdents :: String
illegalIdents = "Left \"Parsing error\" (line 1, column 10):\nunexpected \"f\"\nexpecting digit, \"*\", \"%\", \"+\", \"-\", \"<\", \"===\" or \";\""
reservedIdents :: String
reservedIdents = "Left \"Parsing error\" (line 1, column 8):\nunexpected illegal identifier"
dotError :: String
dotError = "Left \"Parsing error\" (line 1, column 15):\nunexpected \" \""
-- Tests
introTest :: Test
introTest = TestCase (do parsedFile <- parseFile "tests/intro.js"
assertEqual "intro test file"
introAST $ show parsedFile)
testSucc1 :: Test
testSucc1 = TestCase (do parsedFile <- parseFile "tests/funName"
assertEqual "funName and array test"
funNameAST $ show parsedFile)
testSucc2 :: Test
testSucc2 = TestCase (do parsedFile <- parseFile "tests/precedence1"
assertEqual "+ / - / * / % precedence test"
precedence1AST $ show parsedFile)
testSucc3 :: Test
testSucc3 = TestCase (do parsedFile <- parseFile "tests/precedence2"
assertEqual "=== / < precedence test"
precedence2AST $ show parsedFile)
testSucc4 :: Test
testSucc4 = TestCase (do parsedFile <- parseFile "tests/associativity"
assertEqual "'=' associativity test"
associativityAST $ show parsedFile)
testSucc5 :: Test
testSucc5 = TestCase (do parsedFile <- parseFile "tests/allowedIdents"
assertEqual "allowed idents (using '_') test"
allowedIdentsAST $ show parsedFile)
testSucc6 :: Test
testSucc6 = TestCase (do parsedFile <- parseFile "tests/illegalIdents"
assertEqual "illegal ident starting with digit"
illegalIdents $ show parsedFile)
testSucc7 :: Test
testSucc7 = TestCase (do parsedFile <- parseFile "tests/reservedIdents"
assertEqual "reserved ident"
reservedIdents $ show parsedFile)
testSucc8 :: Test
testSucc8 = TestCase (do parsedFile <- parseFile "tests/dotError"
assertEqual "spaces after dot error"
dotError $ show parsedFile)
tests:: Test
tests = TestList [TestLabel "intro test file" introTest,
TestLabel "funName test file" testSucc1,
TestLabel "*/%/+/- precedence test file" testSucc2,
TestLabel "=== / < precedence test file" testSucc3,
TestLabel "'=' associativity test file" testSucc4,
TestLabel "allowed Ident test file" testSucc5,
TestLabel "illegal Ident test file" testSucc6,
TestLabel "reserved Ident test file" testSucc7,
TestLabel "spaces after dot error" testSucc8]
| Rathcke/uni | ap/exam/src/subs/ParserTest.hs | gpl-3.0 | 4,466 | 0 | 10 | 1,199 | 557 | 277 | 280 | 67 | 1 |
module Text.Lox.Readers.Document (constituents, parse) where
import Control.Applicative ((<$>), (<*>), (*>), (<*))
import Text.ParserCombinators.Parsec
import Text.Lox.Parsing
constituents :: Char -> GenParser Char st [Either String String]
constituents sep = many1 (try (plain sep) <|> (loxStatement sep)) <* eof
plain :: Char -> GenParser Char st (Either String String)
plain sep = Left <$> (try plainTail <|> try (many1 (noneOf [sep])) <|> unmatched)
where
plainTail =
(sep:) <$> (char sep *> many (noneOf [sep]) <* eof)
unmatched =
(\x -> (sep:x) ++ "\n") <$> (char sep *> many1 (noneOf [sep, '\n']) <* char '\n')
loxStatement :: Char -> GenParser Char st (Either String String)
loxStatement sep = Right <$> (char sep *> many1 (noneOf [sep, '\n']) <* char sep)
| knuton/lox | Text/Lox/Readers/Document.hs | gpl-3.0 | 792 | 0 | 14 | 144 | 353 | 191 | 162 | 14 | 1 |
import Control.Exception
import System.IO
main = do
withFile' "girlfriend.txt" ReadMode (\handle -> do
contents <- hGetContents handle
putStr contents)
withFile' :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
withFile' name mode f = bracket (openFile name mode) (\handle -> hClose handle) (\handle -> f handle)
| medik/lang-hack | Haskell/LearnYouAHaskell/c09/withFileImpl.hs | gpl-3.0 | 401 | 0 | 13 | 136 | 129 | 64 | 65 | 8 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.CreativeGroups.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a list of creative groups, possibly filtered. This method
-- supports paging.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.creativeGroups.list@.
module Network.Google.Resource.DFAReporting.CreativeGroups.List
(
-- * REST Resource
CreativeGroupsListResource
-- * Creating a Request
, creativeGroupsList
, CreativeGroupsList
-- * Request Lenses
, cglSearchString
, cglIds
, cglProFileId
, cglSortOrder
, cglGroupNumber
, cglPageToken
, cglSortField
, cglAdvertiserIds
, cglMaxResults
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.creativeGroups.list@ method which the
-- 'CreativeGroupsList' request conforms to.
type CreativeGroupsListResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"creativeGroups" :>
QueryParam "searchString" Text :>
QueryParams "ids" (Textual Int64) :>
QueryParam "sortOrder" CreativeGroupsListSortOrder :>
QueryParam "groupNumber" (Textual Int32) :>
QueryParam "pageToken" Text :>
QueryParam "sortField" CreativeGroupsListSortField :>
QueryParams "advertiserIds" (Textual Int64) :>
QueryParam "maxResults" (Textual Int32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] CreativeGroupsListResponse
-- | Retrieves a list of creative groups, possibly filtered. This method
-- supports paging.
--
-- /See:/ 'creativeGroupsList' smart constructor.
data CreativeGroupsList = CreativeGroupsList'
{ _cglSearchString :: !(Maybe Text)
, _cglIds :: !(Maybe [Textual Int64])
, _cglProFileId :: !(Textual Int64)
, _cglSortOrder :: !(Maybe CreativeGroupsListSortOrder)
, _cglGroupNumber :: !(Maybe (Textual Int32))
, _cglPageToken :: !(Maybe Text)
, _cglSortField :: !(Maybe CreativeGroupsListSortField)
, _cglAdvertiserIds :: !(Maybe [Textual Int64])
, _cglMaxResults :: !(Maybe (Textual Int32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreativeGroupsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cglSearchString'
--
-- * 'cglIds'
--
-- * 'cglProFileId'
--
-- * 'cglSortOrder'
--
-- * 'cglGroupNumber'
--
-- * 'cglPageToken'
--
-- * 'cglSortField'
--
-- * 'cglAdvertiserIds'
--
-- * 'cglMaxResults'
creativeGroupsList
:: Int64 -- ^ 'cglProFileId'
-> CreativeGroupsList
creativeGroupsList pCglProFileId_ =
CreativeGroupsList'
{ _cglSearchString = Nothing
, _cglIds = Nothing
, _cglProFileId = _Coerce # pCglProFileId_
, _cglSortOrder = Nothing
, _cglGroupNumber = Nothing
, _cglPageToken = Nothing
, _cglSortField = Nothing
, _cglAdvertiserIds = Nothing
, _cglMaxResults = Nothing
}
-- | Allows searching for creative groups by name or ID. Wildcards (*) are
-- allowed. For example, \"creativegroup*2015\" will return creative groups
-- with names like \"creativegroup June 2015\", \"creativegroup April
-- 2015\", or simply \"creativegroup 2015\". Most of the searches also add
-- wild-cards implicitly at the start and the end of the search string. For
-- example, a search string of \"creativegroup\" will match creative groups
-- with the name \"my creativegroup\", \"creativegroup 2015\", or simply
-- \"creativegroup\".
cglSearchString :: Lens' CreativeGroupsList (Maybe Text)
cglSearchString
= lens _cglSearchString
(\ s a -> s{_cglSearchString = a})
-- | Select only creative groups with these IDs.
cglIds :: Lens' CreativeGroupsList [Int64]
cglIds
= lens _cglIds (\ s a -> s{_cglIds = a}) . _Default .
_Coerce
-- | User profile ID associated with this request.
cglProFileId :: Lens' CreativeGroupsList Int64
cglProFileId
= lens _cglProFileId (\ s a -> s{_cglProFileId = a})
. _Coerce
-- | Order of sorted results, default is ASCENDING.
cglSortOrder :: Lens' CreativeGroupsList (Maybe CreativeGroupsListSortOrder)
cglSortOrder
= lens _cglSortOrder (\ s a -> s{_cglSortOrder = a})
-- | Select only creative groups that belong to this subgroup.
cglGroupNumber :: Lens' CreativeGroupsList (Maybe Int32)
cglGroupNumber
= lens _cglGroupNumber
(\ s a -> s{_cglGroupNumber = a})
. mapping _Coerce
-- | Value of the nextPageToken from the previous result page.
cglPageToken :: Lens' CreativeGroupsList (Maybe Text)
cglPageToken
= lens _cglPageToken (\ s a -> s{_cglPageToken = a})
-- | Field by which to sort the list.
cglSortField :: Lens' CreativeGroupsList (Maybe CreativeGroupsListSortField)
cglSortField
= lens _cglSortField (\ s a -> s{_cglSortField = a})
-- | Select only creative groups that belong to these advertisers.
cglAdvertiserIds :: Lens' CreativeGroupsList [Int64]
cglAdvertiserIds
= lens _cglAdvertiserIds
(\ s a -> s{_cglAdvertiserIds = a})
. _Default
. _Coerce
-- | Maximum number of results to return.
cglMaxResults :: Lens' CreativeGroupsList (Maybe Int32)
cglMaxResults
= lens _cglMaxResults
(\ s a -> s{_cglMaxResults = a})
. mapping _Coerce
instance GoogleRequest CreativeGroupsList where
type Rs CreativeGroupsList =
CreativeGroupsListResponse
type Scopes CreativeGroupsList =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient CreativeGroupsList'{..}
= go _cglProFileId _cglSearchString
(_cglIds ^. _Default)
_cglSortOrder
_cglGroupNumber
_cglPageToken
_cglSortField
(_cglAdvertiserIds ^. _Default)
_cglMaxResults
(Just AltJSON)
dFAReportingService
where go
= buildClient
(Proxy :: Proxy CreativeGroupsListResource)
mempty
| rueshyna/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/CreativeGroups/List.hs | mpl-2.0 | 7,042 | 0 | 21 | 1,698 | 1,061 | 609 | 452 | 144 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.Drive
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Manages files in Drive including uploading, downloading, searching,
-- detecting changes, and updating sharing permissions.
--
-- /See:/ <https://developers.google.com/drive/ Drive API Reference>
module Network.Google.Drive
(
-- * Service Configuration
driveService
-- * OAuth Scopes
, driveMetadataReadOnlyScope
, drivePhotosReadOnlyScope
, driveAppDataScope
, driveReadOnlyScope
, driveScope
, driveFileScope
, driveMetadataScope
, driveScriptsScope
-- * API Declaration
, DriveAPI
-- * Resources
-- ** drive.about.get
, module Network.Google.Resource.Drive.About.Get
-- ** drive.changes.getStartPageToken
, module Network.Google.Resource.Drive.Changes.GetStartPageToken
-- ** drive.changes.list
, module Network.Google.Resource.Drive.Changes.List
-- ** drive.changes.watch
, module Network.Google.Resource.Drive.Changes.Watch
-- ** drive.channels.stop
, module Network.Google.Resource.Drive.Channels.Stop
-- ** drive.comments.create
, module Network.Google.Resource.Drive.Comments.Create
-- ** drive.comments.delete
, module Network.Google.Resource.Drive.Comments.Delete
-- ** drive.comments.get
, module Network.Google.Resource.Drive.Comments.Get
-- ** drive.comments.list
, module Network.Google.Resource.Drive.Comments.List
-- ** drive.comments.update
, module Network.Google.Resource.Drive.Comments.Update
-- ** drive.drives.create
, module Network.Google.Resource.Drive.Drives.Create
-- ** drive.drives.delete
, module Network.Google.Resource.Drive.Drives.Delete
-- ** drive.drives.get
, module Network.Google.Resource.Drive.Drives.Get
-- ** drive.drives.hide
, module Network.Google.Resource.Drive.Drives.Hide
-- ** drive.drives.list
, module Network.Google.Resource.Drive.Drives.List
-- ** drive.drives.unhide
, module Network.Google.Resource.Drive.Drives.Unhide
-- ** drive.drives.update
, module Network.Google.Resource.Drive.Drives.Update
-- ** drive.files.copy
, module Network.Google.Resource.Drive.Files.Copy
-- ** drive.files.create
, module Network.Google.Resource.Drive.Files.Create
-- ** drive.files.delete
, module Network.Google.Resource.Drive.Files.Delete
-- ** drive.files.emptyTrash
, module Network.Google.Resource.Drive.Files.EmptyTrash
-- ** drive.files.export
, module Network.Google.Resource.Drive.Files.Export
-- ** drive.files.generateIds
, module Network.Google.Resource.Drive.Files.GenerateIds
-- ** drive.files.get
, module Network.Google.Resource.Drive.Files.Get
-- ** drive.files.list
, module Network.Google.Resource.Drive.Files.List
-- ** drive.files.update
, module Network.Google.Resource.Drive.Files.Update
-- ** drive.files.watch
, module Network.Google.Resource.Drive.Files.Watch
-- ** drive.permissions.create
, module Network.Google.Resource.Drive.Permissions.Create
-- ** drive.permissions.delete
, module Network.Google.Resource.Drive.Permissions.Delete
-- ** drive.permissions.get
, module Network.Google.Resource.Drive.Permissions.Get
-- ** drive.permissions.list
, module Network.Google.Resource.Drive.Permissions.List
-- ** drive.permissions.update
, module Network.Google.Resource.Drive.Permissions.Update
-- ** drive.replies.create
, module Network.Google.Resource.Drive.Replies.Create
-- ** drive.replies.delete
, module Network.Google.Resource.Drive.Replies.Delete
-- ** drive.replies.get
, module Network.Google.Resource.Drive.Replies.Get
-- ** drive.replies.list
, module Network.Google.Resource.Drive.Replies.List
-- ** drive.replies.update
, module Network.Google.Resource.Drive.Replies.Update
-- ** drive.revisions.delete
, module Network.Google.Resource.Drive.Revisions.Delete
-- ** drive.revisions.get
, module Network.Google.Resource.Drive.Revisions.Get
-- ** drive.revisions.list
, module Network.Google.Resource.Drive.Revisions.List
-- ** drive.revisions.update
, module Network.Google.Resource.Drive.Revisions.Update
-- ** drive.teamdrives.create
, module Network.Google.Resource.Drive.Teamdrives.Create
-- ** drive.teamdrives.delete
, module Network.Google.Resource.Drive.Teamdrives.Delete
-- ** drive.teamdrives.get
, module Network.Google.Resource.Drive.Teamdrives.Get
-- ** drive.teamdrives.list
, module Network.Google.Resource.Drive.Teamdrives.List
-- ** drive.teamdrives.update
, module Network.Google.Resource.Drive.Teamdrives.Update
-- * Types
-- ** FileList
, FileList
, fileList
, flNextPageToken
, flIncompleteSearch
, flKind
, flFiles
-- ** FileShortcutDetails
, FileShortcutDetails
, fileShortcutDetails
, fsdTargetId
, fsdTargetResourceKey
, fsdTargetMimeType
-- ** Drive
, Drive
, drive
, dThemeId
, dBackgRoundImageFile
, dColorRgb
, dCreatedTime
, dKind
, dBackgRoundImageLink
, dName
, dRestrictions
, dHidden
, dId
, dCapabilities
-- ** TeamDriveCapabilities
, TeamDriveCapabilities
, teamDriveCapabilities
, tdcCanRename
, tdcCanChangeTeamMembersOnlyRestriction
, tdcCanComment
, tdcCanRenameTeamDrive
, tdcCanChangeTeamDriveBackgRound
, tdcCanDownload
, tdcCanChangeDomainUsersOnlyRestriction
, tdcCanTrashChildren
, tdcCanAddChildren
, tdcCanRemoveChildren
, tdcCanChangeCopyRequiresWriterPermissionRestriction
, tdcCanDeleteTeamDrive
, tdcCanListChildren
, tdcCanEdit
, tdcCanManageMembers
, tdcCanReadRevisions
, tdcCanDeleteChildren
, tdcCanCopy
, tdcCanShare
-- ** PermissionPermissionDetailsItem
, PermissionPermissionDetailsItem
, permissionPermissionDetailsItem
, ppdiInherited
, ppdiPermissionType
, ppdiRole
, ppdiInheritedFrom
-- ** FilesListCorpus
, FilesListCorpus (..)
-- ** CommentQuotedFileContent
, CommentQuotedFileContent
, commentQuotedFileContent
, cqfcValue
, cqfcMimeType
-- ** DriveCapabilities
, DriveCapabilities
, driveCapabilities
, dcCanRename
, dcCanComment
, dcCanChangeDriveBackgRound
, dcCanRenameDrive
, dcCanDownload
, dcCanChangeDomainUsersOnlyRestriction
, dcCanTrashChildren
, dcCanAddChildren
, dcCanChangeCopyRequiresWriterPermissionRestriction
, dcCanChangeDriveMembersOnlyRestriction
, dcCanListChildren
, dcCanEdit
, dcCanManageMembers
, dcCanReadRevisions
, dcCanDeleteChildren
, dcCanCopy
, dcCanDeleteDrive
, dcCanShare
-- ** AboutStorageQuota
, AboutStorageQuota
, aboutStorageQuota
, asqUsageInDriveTrash
, asqLimit
, asqUsage
, asqUsageInDrive
-- ** Reply
, Reply
, reply
, rHTMLContent
, rModifiedTime
, rCreatedTime
, rKind
, rAction
, rContent
, rAuthor
, rId
, rDeleted
-- ** AboutImportFormats
, AboutImportFormats
, aboutImportFormats
, aifAddtional
-- ** FileCapabilities
, FileCapabilities
, fileCapabilities
, fcCanRename
, fcCanComment
, fcCanMoveChildrenWithinDrive
, fcCanMoveChildrenWithinTeamDrive
, fcCanModifyContent
, fcCanDelete
, fcCanMoveItemIntoTeamDrive
, fcCanChangeSecurityUpdateEnabled
, fcCanDownload
, fcCanTrash
, fcCanUntrash
, fcCanTrashChildren
, fcCanMoveItemOutOfDrive
, fcCanAddChildren
, fcCanAddMyDriveParent
, fcCanRemoveChildren
, fcCanMoveTeamDriveItem
, fcCanMoveItemWithinTeamDrive
, fcCanReadTeamDrive
, fcCanReadDrive
, fcCanAddFolderFromAnotherDrive
, fcCanChangeCopyRequiresWriterPermission
, fcCanMoveChildrenOutOfDrive
, fcCanListChildren
, fcCanMoveChildrenOutOfTeamDrive
, fcCanEdit
, fcCanChangeViewersCanCopyContent
, fcCanReadRevisions
, fcCanDeleteChildren
, fcCanMoveItemOutOfTeamDrive
, fcCanRemoveMyDriveParent
, fcCanModifyContentRestriction
, fcCanCopy
, fcCanMoveItemWithinDrive
, fcCanShare
-- ** ReplyList
, ReplyList
, replyList
, rlNextPageToken
, rlKind
, rlReplies
-- ** DriveBackgRoundImageFile
, DriveBackgRoundImageFile
, driveBackgRoundImageFile
, dbrifXCoordinate
, dbrifYCoordinate
, dbrifWidth
, dbrifId
-- ** FileContentHintsThumbnail
, FileContentHintsThumbnail
, fileContentHintsThumbnail
, fchtImage
, fchtMimeType
-- ** TeamDriveList
, TeamDriveList
, teamDriveList
, tdlNextPageToken
, tdlTeamDrives
, tdlKind
-- ** Channel
, Channel
, channel
, cResourceURI
, cResourceId
, cKind
, cExpiration
, cToken
, cAddress
, cPayload
, cParams
, cId
, cType
-- ** AboutTeamDriveThemesItem
, AboutTeamDriveThemesItem
, aboutTeamDriveThemesItem
, atdtiColorRgb
, atdtiBackgRoundImageLink
, atdtiId
-- ** TeamDriveRestrictions
, TeamDriveRestrictions
, teamDriveRestrictions
, tdrTeamMembersOnly
, tdrAdminManagedRestrictions
, tdrCopyRequiresWriterPermission
, tdrDomainUsersOnly
-- ** TeamDriveBackgRoundImageFile
, TeamDriveBackgRoundImageFile
, teamDriveBackgRoundImageFile
, tdbrifXCoordinate
, tdbrifYCoordinate
, tdbrifWidth
, tdbrifId
-- ** FileVideoMediaMetadata
, FileVideoMediaMetadata
, fileVideoMediaMetadata
, fvmmHeight
, fvmmWidth
, fvmmDurationMillis
-- ** FileAppProperties
, FileAppProperties
, fileAppProperties
, fapAddtional
-- ** FileLinkShareMetadata
, FileLinkShareMetadata
, fileLinkShareMetadata
, flsmSecurityUpdateEnabled
, flsmSecurityUpdateEligible
-- ** Change
, Change
, change
, chaDrive
, chaRemoved
, chaTime
, chaKind
, chaTeamDrive
, chaTeamDriveId
, chaType
, chaFileId
, chaFile
, chaChangeType
, chaDriveId
-- ** TeamDrive
, TeamDrive
, teamDrive
, tdThemeId
, tdBackgRoundImageFile
, tdColorRgb
, tdCreatedTime
, tdKind
, tdBackgRoundImageLink
, tdName
, tdRestrictions
, tdId
, tdCapabilities
-- ** AboutExportFormats
, AboutExportFormats
, aboutExportFormats
, aefAddtional
-- ** User
, User
, user
, uPhotoLink
, uMe
, uKind
, uEmailAddress
, uDisplayName
, uPermissionId
-- ** ChangeList
, ChangeList
, changeList
, clNewStartPageToken
, clNextPageToken
, clChanges
, clKind
-- ** RevisionExportLinks
, RevisionExportLinks
, revisionExportLinks
, relAddtional
-- ** FileContentHints
, FileContentHints
, fileContentHints
, fchThumbnail
, fchIndexableText
-- ** ChannelParams
, ChannelParams
, channelParams
, cpAddtional
-- ** FileProperties
, FileProperties
, fileProperties
, fpAddtional
-- ** AboutMaxImportSizes
, AboutMaxImportSizes
, aboutMaxImportSizes
, amisAddtional
-- ** About
, About
, about
, aExportFormats
, aMaxImportSizes
, aCanCreateTeamDrives
, aImportFormats
, aKind
, aDriveThemes
, aAppInstalled
, aUser
, aStorageQuota
, aCanCreateDrives
, aMaxUploadSize
, aTeamDriveThemes
, aFolderColorPalette
-- ** FileImageMediaMetadataLocation
, FileImageMediaMetadataLocation
, fileImageMediaMetadataLocation
, fimmlLatitude
, fimmlAltitude
, fimmlLongitude
-- ** ContentRestriction
, ContentRestriction
, contentRestriction
, crRestrictingUser
, crRestrictionTime
, crReason
, crType
, crReadOnly
-- ** StartPageToken
, StartPageToken
, startPageToken
, sptKind
, sptStartPageToken
-- ** FileImageMediaMetadata
, FileImageMediaMetadata
, fileImageMediaMetadata
, fimmRotation
, fimmHeight
, fimmSubjectDistance
, fimmMaxApertureValue
, fimmIsoSpeed
, fimmTime
, fimmLocation
, fimmAperture
, fimmFocalLength
, fimmCameraMake
, fimmWidth
, fimmExposureTime
, fimmCameraModel
, fimmWhiteBalance
, fimmLens
, fimmFlashUsed
, fimmExposureBias
, fimmMeteringMode
, fimmExposureMode
, fimmSensor
, fimmColorSpace
-- ** Comment
, Comment
, comment
, comHTMLContent
, comModifiedTime
, comCreatedTime
, comKind
, comResolved
, comQuotedFileContent
, comAnchor
, comContent
, comReplies
, comAuthor
, comId
, comDeleted
-- ** Revision
, Revision
, revision
, revModifiedTime
, revSize
, revOriginalFilename
, revKind
, revPublishedLink
, revPublished
, revLastModifyingUser
, revPublishAuto
, revMD5Checksum
, revKeepForever
, revMimeType
, revExportLinks
, revPublishedOutsideDomain
, revId
-- ** Permission
, Permission
, permission
, pPhotoLink
, pTeamDrivePermissionDetails
, pKind
, pDomain
, pRole
, pEmailAddress
, pAllowFileDiscovery
, pDisplayName
, pView
, pId
, pDeleted
, pType
, pExpirationTime
, pPermissionDetails
-- ** DriveRestrictions
, DriveRestrictions
, driveRestrictions
, drAdminManagedRestrictions
, drDriveMembersOnly
, drCopyRequiresWriterPermission
, drDomainUsersOnly
-- ** File
, File
, file
, fOwnedByMe
, fThumbnailLink
, fFullFileExtension
, fModifiedTime
, fModifiedByMeTime
, fFileExtension
, fViewedByMe
, fShortcutDetails
, fOwners
, fViewedByMeTime
, fModifiedByMe
, fSize
, fTrashed
, fResourceKey
, fWebViewLink
, fCreatedTime
, fTrashedTime
, fOriginalFilename
, fKind
, fLastModifyingUser
, fIconLink
, fHasThumbnail
, fThumbnailVersion
, fContentRestrictions
, fImageMediaMetadata
, fExplicitlyTrashed
, fShared
, fMD5Checksum
, fTeamDriveId
, fFolderColorRgb
, fMimeType
, fIsAppAuthorized
, fCopyRequiresWriterPermission
, fName
, fExportLinks
, fParents
, fStarred
, fSpaces
, fVersion
, fHasAugmentedPermissions
, fWritersCanShare
, fTrashingUser
, fId
, fPermissionIds
, fPermissions
, fQuotaBytesUsed
, fLinkShareMetadata
, fAppProperties
, fVideoMediaMetadata
, fSharedWithMeTime
, fHeadRevisionId
, fCapabilities
, fDescription
, fViewersCanCopyContent
, fDriveId
, fSharingUser
, fWebContentLink
, fContentHints
, fProperties
-- ** AboutDriveThemesItem
, AboutDriveThemesItem
, aboutDriveThemesItem
, adtiColorRgb
, adtiBackgRoundImageLink
, adtiId
-- ** PermissionTeamDrivePermissionDetailsItem
, PermissionTeamDrivePermissionDetailsItem
, permissionTeamDrivePermissionDetailsItem
, ptdpdiInherited
, ptdpdiTeamDrivePermissionType
, ptdpdiRole
, ptdpdiInheritedFrom
-- ** DriveList
, DriveList
, driveList
, dlNextPageToken
, dlKind
, dlDrives
-- ** GeneratedIds
, GeneratedIds
, generatedIds
, giSpace
, giKind
, giIds
-- ** FileExportLinks
, FileExportLinks
, fileExportLinks
, felAddtional
-- ** CommentList
, CommentList
, commentList
, cllNextPageToken
, cllKind
, cllComments
-- ** RevisionList
, RevisionList
, revisionList
, rllNextPageToken
, rllKind
, rllRevisions
-- ** PermissionList
, PermissionList
, permissionList
, plNextPageToken
, plKind
, plPermissions
) where
import Network.Google.Prelude
import Network.Google.Drive.Types
import Network.Google.Resource.Drive.About.Get
import Network.Google.Resource.Drive.Changes.GetStartPageToken
import Network.Google.Resource.Drive.Changes.List
import Network.Google.Resource.Drive.Changes.Watch
import Network.Google.Resource.Drive.Channels.Stop
import Network.Google.Resource.Drive.Comments.Create
import Network.Google.Resource.Drive.Comments.Delete
import Network.Google.Resource.Drive.Comments.Get
import Network.Google.Resource.Drive.Comments.List
import Network.Google.Resource.Drive.Comments.Update
import Network.Google.Resource.Drive.Drives.Create
import Network.Google.Resource.Drive.Drives.Delete
import Network.Google.Resource.Drive.Drives.Get
import Network.Google.Resource.Drive.Drives.Hide
import Network.Google.Resource.Drive.Drives.List
import Network.Google.Resource.Drive.Drives.Unhide
import Network.Google.Resource.Drive.Drives.Update
import Network.Google.Resource.Drive.Files.Copy
import Network.Google.Resource.Drive.Files.Create
import Network.Google.Resource.Drive.Files.Delete
import Network.Google.Resource.Drive.Files.EmptyTrash
import Network.Google.Resource.Drive.Files.Export
import Network.Google.Resource.Drive.Files.GenerateIds
import Network.Google.Resource.Drive.Files.Get
import Network.Google.Resource.Drive.Files.List
import Network.Google.Resource.Drive.Files.Update
import Network.Google.Resource.Drive.Files.Watch
import Network.Google.Resource.Drive.Permissions.Create
import Network.Google.Resource.Drive.Permissions.Delete
import Network.Google.Resource.Drive.Permissions.Get
import Network.Google.Resource.Drive.Permissions.List
import Network.Google.Resource.Drive.Permissions.Update
import Network.Google.Resource.Drive.Replies.Create
import Network.Google.Resource.Drive.Replies.Delete
import Network.Google.Resource.Drive.Replies.Get
import Network.Google.Resource.Drive.Replies.List
import Network.Google.Resource.Drive.Replies.Update
import Network.Google.Resource.Drive.Revisions.Delete
import Network.Google.Resource.Drive.Revisions.Get
import Network.Google.Resource.Drive.Revisions.List
import Network.Google.Resource.Drive.Revisions.Update
import Network.Google.Resource.Drive.Teamdrives.Create
import Network.Google.Resource.Drive.Teamdrives.Delete
import Network.Google.Resource.Drive.Teamdrives.Get
import Network.Google.Resource.Drive.Teamdrives.List
import Network.Google.Resource.Drive.Teamdrives.Update
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Drive API service.
type DriveAPI =
TeamdrivesListResource :<|> TeamdrivesGetResource
:<|> TeamdrivesCreateResource
:<|> TeamdrivesDeleteResource
:<|> TeamdrivesUpdateResource
:<|> ChangesListResource
:<|> ChangesGetStartPageTokenResource
:<|> ChangesWatchResource
:<|> ChannelsStopResource
:<|> RepliesListResource
:<|> RepliesGetResource
:<|> RepliesCreateResource
:<|> RepliesDeleteResource
:<|> RepliesUpdateResource
:<|> DrivesListResource
:<|> DrivesHideResource
:<|> DrivesGetResource
:<|> DrivesCreateResource
:<|> DrivesUnhideResource
:<|> DrivesDeleteResource
:<|> DrivesUpdateResource
:<|> AboutGetResource
:<|> FilesExportResource
:<|> FilesListResource
:<|> FilesCopyResource
:<|> FilesGetResource
:<|> FilesEmptyTrashResource
:<|> FilesCreateResource
:<|> FilesGenerateIdsResource
:<|> FilesDeleteResource
:<|> FilesUpdateResource
:<|> FilesWatchResource
:<|> PermissionsListResource
:<|> PermissionsGetResource
:<|> PermissionsCreateResource
:<|> PermissionsDeleteResource
:<|> PermissionsUpdateResource
:<|> CommentsListResource
:<|> CommentsGetResource
:<|> CommentsCreateResource
:<|> CommentsDeleteResource
:<|> CommentsUpdateResource
:<|> RevisionsListResource
:<|> RevisionsGetResource
:<|> RevisionsDeleteResource
:<|> RevisionsUpdateResource
| brendanhay/gogol | gogol-drive/gen/Network/Google/Drive.hs | mpl-2.0 | 20,568 | 0 | 49 | 4,601 | 2,611 | 1,859 | 752 | 615 | 0 |
{-# LANGUAGE TypeOperators, TypeFamilies, ScopedTypeVariables #-}
{-# OPTIONS_GHC -Wall #-}
----------------------------------------------------------------------
-- |
-- Module : Shady.Run
-- Copyright : (c) Conal Elliott 2009
-- License : AGPLv3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Some common functionality for compiling & running shaders
----------------------------------------------------------------------
module Shady.Run
(
runAnim, time, grid, MeshSize
-- , runOnce, install, installGrid
) where
import Control.Applicative ((<$>),liftA2)
import Data.Time (getCurrentTime,utctDayTime)
import qualified TypeUnary.Vec as V
import Shady.MechanicsGL (GlIndex)
import Shady.Language.Exp hiding (indices)
import Shady.Misc (Sink,Action)
-- GLUT Timer callbacks are one-shot, so re-register each time. We can re-register
-- first, so try keeping the display rate constant, or re-register second to keep
-- delay constant. Also, turn off the vsync stuff.
-- | Run an animated shader
runAnim :: Sink Action -> Sink R1 -> IO ()
runAnim start sinkU =
do t0 <- time
start (subtract t0 <$> time >>= sinkU)
-- runAnim sinkU = callback (time >>= sinkU) >> mainLoop
-- Get the time since midnight, in seconds
time :: IO R1
time = (vec1 . fromRational . toRational . utctDayTime) <$> getCurrentTime
-- TODO: can I eliminate vec1? And how about realToFrac? What's the type
-- of utctDayTime?
{--------------------------------------------------------------------
Tessellated grid
--------------------------------------------------------------------}
-- | Indices for a collection of triangles covering a grid with given
-- number of columns and rows (in vertices).
gridIndices :: (Enum n, Num n) => (n, n) -> [n]
gridIndices (cols,rows) =
[ i * rows + j | ll <- lls cols rows , tri <- box ll , (i,j) <- tri ]
-- Lower-lefts
lls :: (Enum a, Num a) => a -> a -> [(a,a)]
lls cols rows = liftA2 (,) [0 .. cols-2] [0 .. rows-2]
-- CCW triangles in box with given lower-left
box :: Num a => (a,a) -> [[(a,a)]]
box (i,j) = [[ll,lr,ul],[ul,lr,ur]]
where
ll = (i ,j )
lr = (i+1,j )
ul = (i ,j+1)
ur = (i+1,j+1)
-- TODO: Switch to a single triangle, with degeneragte triangles.
-- | (columns,rows) of a mesh
type MeshSize = (GlIndex,GlIndex)
gridVertices :: MeshSize -> [R2]
gridVertices (cols,rows) = liftA2 vert [0 .. cols-1] [0 .. rows-1]
where
vert i j = V.vec2 (f i cols) (f j rows)
f l n = -- fromIntegral l / fromIntegral (n-1) - 0.5
2 * fromIntegral l / fromIntegral (n-1) - 1
-- | Grid of given dimension
grid :: (GlIndex,GlIndex) -> ([GlIndex], [R2])
grid = liftA2 (,) gridIndices gridVertices
| conal/shady-render | src/Shady/Run.hs | agpl-3.0 | 2,723 | 0 | 11 | 517 | 699 | 408 | 291 | 36 | 1 |
module GuardDuty where
myAbs :: Integer -> Integer
myAbs x
| x < 0 = (-x)
| otherwise = x
bloodNa :: Integer -> String
bloodNa x
| x < 135 = "too low"
| x > 145 = "too high"
| otherwise = "just right"
avgGrade :: (Fractional a, Ord a) => a -> Char
avgGrade x
| y >= 0.9 = 'A'
| y >= 0.8 = 'B'
| y >= 0.7 = 'C'
| y >= 0.59 = 'D'
| otherwise = 'F'
where y = x / 100
numbers x
| x < 0 = -1
| x == 0 = 0
| x > 0 = 1
| thewoolleyman/haskellbook | 07/05/maor/guardDuty.hs | unlicense | 478 | 0 | 8 | 178 | 241 | 116 | 125 | 22 | 1 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- !! WARNING: SPOILERS AHEAD !! --
-- CIS 194: Homework 5
module Calc where
import Provided.ExprT
import Provided.Parser
import qualified Provided.StackVM as S
import Data.Composition ( (.:) )
import qualified Data.Map as M
-- Expressions
eval :: ExprT -> Integer
eval (Lit n) = n
eval (Add x y) = eval x + eval y
eval (Mul x y) = eval x * eval y
evalStr :: String -> Maybe Integer
evalStr = fmap eval . parseExp Lit Add Mul
class Expr a where
lit :: Integer -> a
add :: a -> a -> a
mul :: a -> a -> a
instance Expr ExprT where
lit = Lit
add = Add
mul = Mul
instance Expr Integer where
lit = id
add = (+)
mul = (*)
instance Expr Bool where
lit = (0<)
add = (||)
mul = (&&)
instance Expr MinMax where
lit = MinMax
add = max
mul = min
instance Expr Mod7 where
lit = Mod7 . (`mod` 7)
add = (`mod` 7) .: (+)
mul = (`mod` 7) .: (*)
newtype MinMax = MinMax Integer deriving (Enum, Eq, Integral, Num, Ord, Real, Show)
newtype Mod7 = Mod7 Integer deriving (Enum, Eq, Integral, Num, Ord, Real, Show)
-- Custom CPU
-- The problem text gets really confusing around here:
-- "Simply create an instance of the Expr type class for Program, so that arithmetic
-- expressions can be interpreted as compiled programs."
-- Pretty sure he meant the other way around.
-- "For any arithmetic expression exp :: Expr a => a it should be the case that
-- stackVM exp == Right [IVal exp]"
-- That's not even possible. stackVM :: [StackExp] -> Either String StackVal,
-- it can't take an arbitrary Expr. What's going on here?
instance Expr S.Program where
lit = (:[]) . S.PushI
add = (++ [S.Add]) .: (++)
mul = (++ [S.Mul]) .: (++)
compile :: String -> Maybe S.Program
compile = parseExp lit add mul
-- Introducing variables
class HasVars a where
var :: String -> a
data VarExprT = VLit Integer
| VAdd VarExprT VarExprT
| VMul VarExprT VarExprT
| Var String
deriving (Show, Eq)
instance Expr VarExprT where
lit = VLit
add = VAdd
mul = VMul
instance HasVars VarExprT where
var = Var
instance Expr (M.Map String Integer -> Maybe Integer) where
lit = const . Just
add = liftA2 . liftA2 $ (+)
mul = liftA2 . liftA2 $ (*)
instance HasVars (M.Map String Integer -> Maybe Integer) where
var = M.lookup
-- Provided in the problem description
withVars :: [(String, Integer)] -> (M.Map String Integer -> Maybe Integer) -> Maybe Integer
withVars vs x = x $ M.fromList vs
| nilthehuman/cis194 | Homework5.hs | unlicense | 2,664 | 0 | 10 | 683 | 791 | 450 | 341 | 68 | 1 |
module Units (tests) where
import Test.HUnit
import Test.Framework
import Test.Framework.Providers.HUnit
import Control.Monad.Trans
import Data.Maybe
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import qualified Data.ByteString as BS
import Haskoin.Script
import Haskoin.Protocol
import Haskoin.Crypto
import Haskoin.Util
tests =
[ testGroup "Canonical Signatures"
[ testCase "Canonical Sig 1" testCanonicalSig1
, testCase "Canonical Sig 2" testCanonicalSig2
, testCase "Canonical Sig 3" testCanonicalSig3
, testCase "Canonical Sig 4" testCanonicalSig4
, testCase "Canonical Sig 5" testCanonicalSig5
, testCase "Not Canonical Sig 1" testNotCanonical1
, testCase "Not Canonical Sig 2" testNotCanonical2
, testCase "Not Canonical Sig 3" testNotCanonical3
, testCase "Not Canonical Sig 4" testNotCanonical4
, testCase "Not Canonical Sig 5" testNotCanonical5
, testCase "Not Canonical Sig 6" testNotCanonical6
, testCase "Not Canonical Sig 7" testNotCanonical7
, testCase "Not Canonical Sig 8" testNotCanonical8
, testCase "Not Canonical Sig 9" testNotCanonical9
, testCase "Not Canonical Sig 10" testNotCanonical10
, testCase "Not Canonical Sig 11" testNotCanonical11
, testCase "Not Canonical Sig 12" testNotCanonical12
, testCase "Not Canonical Sig 13" testNotCanonical13
, testCase "Not Canonical Sig 14" testNotCanonical14
, testCase "Not Canonical Sig 15" testNotCanonical15
]
]
{- Canonical Signatures -}
-- Test vectors from bitcoind
-- http://github.com/bitcoin/bitcoin/blob/master/src/test/data/sig_canonical.json
testCanonicalSig1 = assertBool "Canonical Sig1" $
isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"300602010002010001"
testCanonicalSig2 = assertBool "Canonical Sig2" $
isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"3008020200ff020200ff01"
testCanonicalSig3 = assertBool "Canonical Sig3" $
isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"304402203932c892e2e550f3af8ee4ce9c215a87f9bb831dcac87b2838e2c2eaa891df0c022030b61dd36543125d56b9f9f3a1f9353189e5af33cdda8d77a5209aec03978fa001"
testCanonicalSig4 = assertBool "Canonical Sig4" $
isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"30450220076045be6f9eca28ff1ec606b833d0b87e70b2a630f5e3a496b110967a40f90a0221008fffd599910eefe00bc803c688c2eca1d2ba7f6b180620eaa03488e6585db6ba01"
testCanonicalSig5 = assertBool "Canonical Sig5" $
isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"3046022100876045be6f9eca28ff1ec606b833d0b87e70b2a630f5e3a496b110967a40f90a0221008fffd599910eefe00bc803c688c2eca1d2ba7f6b180620eaa03488e6585db6ba01"
testNotCanonical1 = assertBool "Too short" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"30050201ff020001"
testNotCanonical2 = assertBool "Too long" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"30470221005990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba6105022200002d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01"
testNotCanonical3 = assertBool "Hashtype" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"304402205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed11"
testNotCanonical4 = assertBool "Type" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"314402205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01"
testNotCanonical5 = assertBool "Total length" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"304502205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01"
testNotCanonical6 = assertBool "S length OOB" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"301f01205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb101"
testNotCanonical7 = assertBool "R+S" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"304502205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed0001"
testNotCanonical8 = assertBool "R type" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"304401205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01"
testNotCanonical9 = assertBool "R len = 0" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"3024020002202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01"
testNotCanonical10 = assertBool "R < -" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"304402208990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01"
testNotCanonical11 = assertBool "R padded" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"30450221005990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01"
testNotCanonical12 = assertBool "S type" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"304402205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610501202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01"
testNotCanonical13 = assertBool "S len = 0" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"302402205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba6105020001"
testNotCanonical14 = assertBool "S < 0" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"304402205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba61050220fd5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01"
testNotCanonical15 = assertBool "S padded" $
not $ isCanonicalSig $ fromJust $ hexToBS $ stringToBS
"304502205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba61050221002d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01"
| OttoAllmendinger/haskoin-script | testsuite/Units.hs | unlicense | 6,241 | 0 | 10 | 878 | 858 | 433 | 425 | 96 | 1 |
import Graphics.Rendering.OpenGL
import Graphics
import Data.Char
import Material
import System.Environment
import qualified Data.Map as Map
-- Parses the arguments. Not the most elegant of command line options, but
-- it works and I'm lazy.
--
-- args -> ((pitch, yaw, roll), iterations, init string, color map,
-- material map)
argParse :: [String] -> ((GLfloat, GLfloat, GLfloat), Int, String,
Map.Map Char Material, Map.Map Char String)
argParse args = (
(
read (args!!0) * pi / 180.0,
read (args!!1) * pi / 180.0,
read (args!!2) * pi / 180.0
),
read (args!!3),
args!!4,
readMats (drop 5 args),
readExps (drop 5 args))
-- Reads the expansion rules from the arg strings.
readExps :: [String] -> Map.Map Char String
readExps = Map.fromList . readExps'
where
readExps' [] = []
readExps' (x:xs)
| length x >= 3 && take 2 (tail x) == "->" =
(head x, drop 3 x) : readExps' xs
| otherwise = readExps' xs
-- Reads the color map from the arg strings. Ugly hex stuff.
readMats :: [String] -> Map.Map Char Material
readMats = Map.fromList . readMats'
where
readMats' [] = []
readMats' (x:xs)
| length x == 8 && x!!1 == '#' =
(x!!0, matFromHex (drop 2 x)):readMats' xs
| otherwise = readMats' xs
matFromHex x = fromColor
(fromIntegral (intFromHex $ take 2 x) / 255.0)
(fromIntegral (intFromHex $ take 2 $ drop 2 x) / 255.0)
(fromIntegral (intFromHex $ take 2 $ drop 4 x) / 255.0)
intFromHex [] = 0
intFromHex (x:xs) = hexDigit x * (16 ^ length xs) + intFromHex xs
hexDigit x
| x >= '0' && x <= '9' = ord x - ord '0'
| x >= 'a' && x <= 'f' = ord x - ord 'a' + 10
| x >= 'A' && x <= 'F' = ord x - ord 'A' + 10
| otherwise = error "Expected hex digit."
main :: IO ()
main = do
args <- getArgs
if length args < 5 then
putStrLn help
else
(let (angles, iter, str, cmap, exmap) = argParse args in
initDisplay angles iter str cmap exmap)
return ()
help :: String
help = unlines [
"Usage:",
"",
"./3DLSystems PITCH YAW ROLL ITER INIT COLORS... RULES...",
"",
" PITCH - The angle to be used for pitch rotations (+/-)",
" YAW - The angle to be used for yaw rotations (*//)",
" ROLL - The angle to be used for roll rotations (&/|)",
" ITER - The number of iterations to go through.",
" INIT - The initial string to expand.",
" COLORS - The colors in which edges should be draw for a character.",
" Each color has the form 'C#RRGGBB' where C is the character",
" and RRGGBB is a hex triplet for the color. If no color is",
" specified, the character will be rendered as white.",
" RULES - The expansion rules for the L-system. Each rule has the form",
" C->STRING where C is the character to expand and STRING is ",
" the result of expanding it.",
"",
"All angles are specified in degrees. It's hard to enter pi's as a",
"parameter.",
"",
"The following special characters exist:",
"",
" + - Increases the pitch angle",
" - - Decreases the pitch angle",
" * - Increases the yaw angle",
" / - Decreases the yaw angle",
" & - Increases the roll angle",
" | - Decreases the roll angle",
" [ - Detaches",
" ] - Ends a detaches sequence",
"",
"Any character which isn't one of these characters or a lowercase",
"character will be ignored by the rendering. They can be useful as",
"variables during expansion.",
"",
"While running the following keys can be used to affect the animation:",
"",
" + - Zoom in",
" - - Zoom out",
" Up - Rotate upwards",
" Down - Rotate downwards",
" Left - Rotate left",
" Right - Rotate right",
" > - Speed up rotation",
" < - Slow down rotation"
]
| tkerber/-abandoned-3dlsystem- | 3DLSystem.hs | apache-2.0 | 3,957 | 0 | 14 | 1,165 | 963 | 508 | 455 | 97 | 3 |
module Handler.About where
-- friends
import Foundation
getAboutR :: Handler RepHtml
getAboutR = error "not implemented"
| sseefried/play-space-online | Handler/About.hs | bsd-2-clause | 123 | 0 | 5 | 18 | 26 | 15 | 11 | 4 | 1 |
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-}
module Foreign.Crypt ( newCipher
, closeCipher
, decrypt
, Cipher
) where
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Foreign
import Foreign.C.String
import Foreign.C.Types
data CCipher
type Cipher = Ptr CCipher
foreign import ccall "crypt.h newCipher" c_newCipher :: CString -> CString -> IO Cipher
foreign import ccall "crypt.h closeCipher" c_closeCipher :: Cipher -> IO ()
foreign import ccall "crypt.h decrypt" c_decrypt :: Cipher -> CString -> CInt -> IO ()
newCipher :: ByteString -> ByteString -> IO Cipher
newCipher key iv = BS.useAsCStringLen key $ \(ckey, _) ->
BS.useAsCStringLen iv $ \(civ, _) ->
c_newCipher ckey civ
closeCipher :: Cipher -> IO ()
closeCipher = c_closeCipher
decrypt :: Cipher -> ByteString -> IO ByteString
decrypt c cipher = BS.useAsCStringLen cipher $ \(ccipher, len) -> do
c_decrypt c ccipher (fromIntegral len)
BS.packCStringLen (ccipher, len)
| Xandaros/MinecraftCLI | src/Foreign/Crypt.hs | bsd-2-clause | 1,090 | 0 | 11 | 255 | 305 | 166 | 139 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
module Web.Socdiff.LinkedIn.DataSource where
import Control.Concurrent.Async
import Control.Concurrent.QSem
import Control.Exception
import Control.Monad.IO.Class
import Control.Lens
import Data.Aeson.Lens
import Data.Hashable
import qualified Data.Text as T
import Data.Typeable
import Network.Wreq
import Haxl.Core
data LinkedInReq a where
GetConnections :: T.Text -> LinkedInReq [T.Text]
deriving Typeable
deriving instance Eq (LinkedInReq a)
deriving instance Show (LinkedInReq a)
instance Show1 LinkedInReq where show1 = show
instance Hashable (LinkedInReq a) where
hashWithSalt s (GetConnections username) = hashWithSalt s (1::Int, username)
instance StateKey LinkedInReq where
data State LinkedInReq = LinkedInState { numThreads :: Int
, accessToken :: T.Text
}
instance DataSourceName LinkedInReq where
dataSourceName _ = "LinkedIn"
instance DataSource u LinkedInReq where
fetch = instagramFetch
initGlobalState :: Int -> T.Text -> IO (State LinkedInReq)
initGlobalState threads token = return $ LinkedInState threads token
instagramFetch ::
State LinkedInReq ->
Flags ->
u ->
[BlockedFetch LinkedInReq] ->
PerformFetch
instagramFetch LinkedInState{..} _flags _user bfs =
AsyncFetch $ \inner -> do
sem <- newQSem numThreads
asyncs <- mapM (fetchAsync accessToken sem) bfs
inner
mapM_ wait asyncs
fetchAsync :: T.Text -> QSem -> BlockedFetch LinkedInReq -> IO (Async ())
fetchAsync token sem (BlockedFetch req rvar) =
async $ bracket_ (waitQSem sem) (signalQSem sem) $ do
e <- Control.Exception.try $ liftIO $ fetchReq req token
case e of
Left ex -> putFailure rvar (ex :: SomeException)
Right a -> putSuccess rvar a
-- TODO: Pagination.
fetchReq :: LinkedInReq a -> T.Text -> IO a
fetchReq (GetConnections user) token = do
resp <- get $ "https://api.linkedin.com/v1/people/" ++ T.unpack user ++
"/connections:(formatted-name)?format=json&" ++
"oauth2_access_token=" ++ T.unpack token
let people = resp ^.. responseBody . key "values" . values . key "formattedName" . _String
return people
| relrod/socdiff | src/Web/Socdiff/LinkedIn/DataSource.hs | bsd-2-clause | 2,462 | 1 | 14 | 497 | 659 | 339 | 320 | -1 | -1 |
Subsets and Splits