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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
-- Test that RebindableSyntax and the new MonadFail interact correctly.
--
-- This should print "Just ()"
{-# LANGUAGE RebindableSyntax #-}
import Prelude hiding (fail)
fail :: String -> a
fail _ = error "Failed with error"
f :: Maybe Int -> Maybe ()
f x = do
42 <- x
return ()
{-# NOINLINE f #-}
main = print (f (Just 42))
|
sdiehl/ghc
|
testsuite/tests/rebindable/RebindableFailB.hs
|
bsd-3-clause
| 335
| 0
| 9
| 74
| 95
| 49
| 46
| 10
| 1
|
{-# LANGUAGE GADTs, KindSignatures #-}
-- See #301
-- This particular one doesn't use GADTs per se,
-- but it does use dictionaries in constructors
module Expr1 where
import Data.Kind (Type)
data Expr :: Type -> Type where -- Not a GADT at all
Const :: Show a => a -> Expr a
-- Note the Show constraint here
Var :: Var a -> Expr a
newtype Var a = V String
instance Show (Var a) where show (V s) = s
--------------------------
e1 :: Expr Int
e1 = Const 42
e2 :: Expr Bool
e2 = Const True
e3 :: Expr Integer
e3 = Var (V "mersenne100")
--------------------------
eval :: Expr a -> a
eval (Const c) = c
eval (Var v) = error ("free variable `" ++ shows v "'")
{-
Up to here, everything works nicely:
\begin{verbatim}
*Expr0> eval e1
42
*Expr0> eval e2
True
*Expr1> eval e3
*** Exception: free variable `mersenne100'
\end{verbatim}
But let us now try to define a |shows| function.
In the following, without the type signature we get:
\begin{verbatim}
*Expr1> :t showsExpr
showsExpr :: forall a. (Show a) => Expr a -> String -> String
*Expr1> showsExpr e1 ""
"42"
*Expr1> showsExpr e2 ""
"True"
*Expr1> showsExpr e3 ""
"mersenne100"
\end{verbatim}
However, in the last case, the instance |Show Integer| was not used,
so should not have been required.
Therefore I would expect it to work as it is now, i.e.,
with the type signature:
-}
showsExpr :: Expr a -> ShowS
showsExpr (Const c) = shows c
showsExpr (Var v) = shows v
{-
We used to get a complaint about the |Const| alternative (then line
63) that documents that the constraint in the type of |Const| must
have been ignored:
No instance for (Show a)
arising from use of `shows' at Expr1.lhs:63:22-26
Probable fix: add (Show a) to the type signature(s) for `showsExpr'
In the definition of `showsExpr': showsExpr (Const c) = shows c
-}
|
sdiehl/ghc
|
testsuite/tests/gadt/karl1.hs
|
bsd-3-clause
| 1,947
| 0
| 8
| 490
| 261
| 138
| 123
| -1
| -1
|
{-# LANGUAGE PatternSynonyms #-}
module Foo () where
data A a = A a
pattern Q :: () => (A ~ f) => a -> f a
pattern Q a = A a
|
AlexanderPankiv/ghc
|
testsuite/tests/patsyn/should_fail/T11039.hs
|
bsd-3-clause
| 127
| 0
| 9
| 35
| 61
| 34
| 27
| 5
| 0
|
module WhereIn1 where
fac,fib :: Int -> Int
fac 0 = 1
fac 1 = 1
fac n = n * (fac (n - 1))
fib 0 = 1
fib 1 = 1
fib n = (fib (n - 1)) + (fib (n - 2))
|
mpickering/HaRe
|
old/testing/removeDef/WhereIn1_AstOut.hs
|
bsd-3-clause
| 153
| 0
| 9
| 50
| 110
| 59
| 51
| 8
| 1
|
module F () where
|
ezyang/ghc
|
testsuite/tests/driver/T14075/F.hs
|
bsd-3-clause
| 18
| 0
| 3
| 4
| 7
| 5
| 2
| 1
| 0
|
module ListGists where
import qualified Github.Gists as Github
import Data.List (intercalate)
main = do
possibleGists <- Github.gists "mike-burns"
case possibleGists of
(Left error) -> putStrLn $ "Error: " ++ (show error)
(Right gists) -> putStrLn $ intercalate "\n\n" $ map formatGist gists
formatGist gist =
(Github.gistId gist) ++ "\n" ++
(maybe "indescribable" id $ Github.gistDescription gist) ++ "\n" ++
(Github.gistHtmlUrl gist)
|
bitemyapp/github
|
samples/Gists/ListGists.hs
|
bsd-3-clause
| 462
| 0
| 12
| 87
| 157
| 80
| 77
| 12
| 2
|
import Control.Concurrent
import System.IO
import System.Timeout
main :: IO ()
main = do
forkIO $ do
threadDelay (5 * 1000000)
-- The timeout should terminate before we ever make it here
putStrLn "t=5 seconds: we shouldn't be here"
timeout (1 * 1000000) $ do
hWaitForInput stdin (10 * 1000)
putStrLn "we shouldn't be here"
return ()
|
shlevy/ghc
|
libraries/base/tests/T8684.hs
|
bsd-3-clause
| 388
| 0
| 12
| 111
| 104
| 49
| 55
| 12
| 1
|
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE FlexibleContexts, MultiParamTypeClasses, TypeFamilies #-}
module T4497 where
norm2PropR a = twiddle (norm2 a) a
twiddle :: Normed a => a -> a -> Double
twiddle a b = undefined
norm2 :: e -> RealOf e
norm2 = undefined
class (Num (RealOf t)) => Normed t
type family RealOf x
|
siddhanathan/ghc
|
testsuite/tests/indexed-types/should_compile/T4497.hs
|
bsd-3-clause
| 348
| 0
| 8
| 65
| 100
| 53
| 47
| -1
| -1
|
{-# LANGUAGE GADTs, TypeFamilies #-}
module T8044 where
data X a where
XInt :: X Int
XBool :: X Bool
XChar :: X Char
type family Frob a where
Frob Int = Int
Frob x = Char
frob :: X a -> X (Frob a)
frob XInt = XInt
frob _ = XChar
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/typecheck/should_fail/T8044.hs
|
bsd-3-clause
| 248
| 0
| 8
| 72
| 94
| 51
| 43
| 12
| 1
|
-- Test for trac #314
{-
/*
This
uses
up
some
lines
This
uses
up
some
lines
*/
-}
module ShouldFail where
type_error = "Type error on line 21":"Type error on line 21"
|
urbanslug/ghc
|
testsuite/tests/parser/should_fail/readFail032.hs
|
bsd-3-clause
| 193
| 0
| 5
| 58
| 15
| 10
| 5
| 2
| 1
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
module Server where
import Control.Applicative
import Control.Monad.Base
import Control.Monad.Reader
import Control.Monad.Trans.Control
import qualified Control.Monad.Trans.Reader as RT
import Control.Monad.Logger
import Database.Persist.Sql
import Database.Persist.MySQL
import Network.Wai.Handler.Warp (Port)
import Web.Scotty.Trans
import qualified Data.Text.Lazy as LT
------------------------------------------------------------------------------------
-- Contextはデータベースのコネクションを保持している
data Context = Context { mysqlPool :: ConnectionPool }
-- プールを保持するモナドを定義
newtype ContextM a = ContextM { runContextM :: ReaderT Context IO a }
deriving ( Monad, Functor, Applicative, MonadReader Context, MonadIO, MonadBase IO )
-- IO a とか強制されているところにContextMを適用できるようになる
instance MonadBaseControl IO ContextM where
type StM ContextM a = a
liftBaseWith f = ContextM $ liftBaseWith $ \q -> f (q . runContextM)
restoreM = ContextM . restoreM
instance MonadLogger ContextM where
monadLoggerLog _ _ _ _ = return ()
type CScottyM = ScottyT LT.Text ContextM
type CActionM = ActionT LT.Text ContextM
cscotty :: Port -> Context -> CScottyM () -> IO ()
cscotty port ctx = scottyT port $ \(ContextM r) -> runReaderT r ctx
-- データベース接続情報
connectInfo :: ConnectInfo
connectInfo = ConnectInfo {
connectHost = "localhost",
connectPort = 3306,
connectUser = "hoge",
connectPassword = "hoge",
connectDatabase = "hogeapp",
connectOptions = [],
connectPath = "",
connectSSL = Nothing
}
-- Contextを作成する
newContext :: IO Context
newContext = do
pool <- runStdoutLoggingT $ createMySQLPool connectInfo 4
return Context { mysqlPool = pool }
type DatabaseM = SqlPersistT ContextM
runDB :: ConnectionPool -> DatabaseM a -> ContextM a
runDB pool sql = runSqlPool sql pool
context :: (MonadTrans t) => t ContextM Context
context = lift ask
execDB :: DatabaseM a -> CActionM a
execDB sql = do
pool <- mysqlPool <$> context
lift $ runDB pool sql
|
tagia0212/hs-template
|
src/Server.hs
|
mit
| 2,442
| 0
| 10
| 520
| 555
| 311
| 244
| 52
| 1
|
{-# LANGUAGE CPP, ForeignFunctionInterface #-}
module Network.Wai.Handler.Warp.SendFile (
sendFile
, readSendFile
, packHeader -- for testing
#ifndef WINDOWS
, positionRead
#endif
) where
import qualified Data.ByteString as BS
import Network.Socket (Socket)
#ifdef WINDOWS
import Foreign.ForeignPtr (newForeignPtr_)
import Foreign.Ptr (plusPtr)
import qualified System.IO as IO
#else
import Control.Exception
import Foreign.C.Error (throwErrno)
import Foreign.C.Types
import Foreign.Ptr (Ptr, castPtr, plusPtr)
import Network.Sendfile
import Network.Wai.Handler.Warp.FdCache (openFile, closeFile)
import System.Posix.Types
#endif
import Network.Wai.Handler.Warp.Buffer
import Network.Wai.Handler.Warp.Imports
import Network.Wai.Handler.Warp.Types
----------------------------------------------------------------
-- | Function to send a file based on sendfile() for Linux\/Mac\/FreeBSD.
-- This makes use of the file descriptor cache.
-- For other OSes, this is identical to 'readSendFile'.
--
-- Since: 3.1.0
sendFile :: Socket -> Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile
#ifdef SENDFILEFD
sendFile s _ _ _ fid off len act hdr = case mfid of
-- settingsFdCacheDuration is 0
Nothing -> sendfileWithHeader s path (PartOfFile off len) act hdr
Just fd -> sendfileFdWithHeader s fd (PartOfFile off len) act hdr
where
mfid = fileIdFd fid
path = fileIdPath fid
#else
sendFile _ = readSendFile
#endif
----------------------------------------------------------------
packHeader :: Buffer -> BufSize -> (ByteString -> IO ())
-> IO () -> [ByteString]
-> Int
-> IO Int
packHeader _ _ _ _ [] n = return n
packHeader buf siz send hook (bs:bss) n
| len < room = do
let dst = buf `plusPtr` n
void $ copy dst bs
packHeader buf siz send hook bss (n + len)
| otherwise = do
let dst = buf `plusPtr` n
(bs1, bs2) = BS.splitAt room bs
void $ copy dst bs1
bufferIO buf siz send
hook
packHeader buf siz send hook (bs2:bss) 0
where
len = BS.length bs
room = siz - n
mini :: Int -> Integer -> Int
mini i n
| fromIntegral i < n = i
| otherwise = fromIntegral n
-- | Function to send a file based on pread()\/send() for Unix.
-- This makes use of the file descriptor cache.
-- For Windows, this is emulated by 'Handle'.
--
-- Since: 3.1.0
#ifdef WINDOWS
readSendFile :: Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile
readSendFile buf siz send fid off0 len0 hook headers = do
hn <- packHeader buf siz send hook headers 0
let room = siz - hn
buf' = buf `plusPtr` hn
IO.withBinaryFile path IO.ReadMode $ \h -> do
IO.hSeek h IO.AbsoluteSeek off0
n <- IO.hGetBufSome h buf' (mini room len0)
bufferIO buf (hn + n) send
hook
let n' = fromIntegral n
fptr <- newForeignPtr_ buf
loop h fptr (len0 - n')
where
path = fileIdPath fid
loop h fptr len
| len <= 0 = return ()
| otherwise = do
n <- IO.hGetBufSome h buf (mini siz len)
when (n /= 0) $ do
let bs = PS fptr 0 n
n' = fromIntegral n
send bs
hook
loop h fptr (len - n')
#else
readSendFile :: Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile
readSendFile buf siz send fid off0 len0 hook headers =
bracket setup teardown $ \fd -> do
hn <- packHeader buf siz send hook headers 0
let room = siz - hn
buf' = buf `plusPtr` hn
n <- positionRead fd buf' (mini room len0) off0
bufferIO buf (hn + n) send
hook
let n' = fromIntegral n
loop fd (len0 - n') (off0 + n')
where
path = fileIdPath fid
setup = case fileIdFd fid of
Just fd -> return fd
Nothing -> openFile path
teardown fd = case fileIdFd fid of
Just _ -> return ()
Nothing -> closeFile fd
loop fd len off
| len <= 0 = return ()
| otherwise = do
n <- positionRead fd buf (mini siz len) off
bufferIO buf n send
let n' = fromIntegral n
hook
loop fd (len - n') (off + n')
positionRead :: Fd -> Buffer -> BufSize -> Integer -> IO Int
positionRead fd buf siz off = do
bytes <- fromIntegral <$> c_pread fd (castPtr buf) (fromIntegral siz) (fromIntegral off)
when (bytes < 0) $ throwErrno "positionRead"
return bytes
foreign import ccall unsafe "pread"
c_pread :: Fd -> Ptr CChar -> ByteCount -> FileOffset -> IO CSsize
#endif
|
creichert/wai
|
warp/Network/Wai/Handler/Warp/SendFile.hs
|
mit
| 4,540
| 0
| 16
| 1,223
| 921
| 472
| 449
| 76
| 3
|
module DefaultTypes where
import Type
import TyCon
import DataCon
iBoxT :: TyCon
iBoxT = AlgTyCon {
tyConUnique = 1,
tyConName = "I#",
tyConBinders = [],
tyConTyVars = [],
tyConResKind = tInt,
tyConKind = tInt `TArr` tIntU,
tyConArity = 1,
tcRepName = "Int",
algTcRhs = DataTyCon {data_cons=[iBox]}
}
iBox :: DataCon
iBox = MkData {dcName="I#", dcUnique=0, dcOrigArgTys=[tInt], dcOrigResTy=tIntU}
iBoxV :: Var
iBoxV = mkVar (TyConApp iBoxT [tIntU]) "I#"
|
C-Elegans/linear
|
DefaultTypes.hs
|
mit
| 497
| 0
| 9
| 110
| 165
| 104
| 61
| 19
| 1
|
{-# LANGUAGE DoAndIfThenElse #-}
module StarStats.Log.Log where
import Control.Applicative
import Data.IORef
import System.IO.Unsafe
import System.IO.UTF8
import System.IO (stderr, hFlush)
data LogLevel = None
| Error
| Warning
| Info
| Verbose
| All
deriving (Ord, Eq, Show)
logLevel :: LogLevel
logLevel = All
format :: LogLevel -> String -> String
format l s = concat ["[", shows l, "]: ", s]
where shows All = "ALL"
shows Error = "ERR"
shows Warning = "WAR"
shows Info = "INF"
shows Verbose = "VER"
shows None = "NON"
safeLog :: LogLevel -> String -> IO ()
safeLog l s = do
if l > logLevel
then return ()
else do hPutStrLn stderr (format l s)
hFlush stderr
logAll :: String -> IO ()
logAll s = safeLog All s
logVerbose :: String -> IO ()
logVerbose s = safeLog Verbose s
logInfo :: String -> IO ()
logInfo s = safeLog Info s
logWarning :: String -> IO ()
logWarning s = safeLog Warning s
logError :: String -> IO ()
logError s = safeLog Error s
{-# NOINLINE unsafeLog #-}
unsafeLog :: LogLevel -> String -> a -> a
unsafeLog l s x = unsafePerformIO $ do
safeLog l s
return x
|
deweyvm/starstats
|
src/StarStats/Log/Log.hs
|
mit
| 1,319
| 0
| 12
| 442
| 434
| 224
| 210
| 45
| 6
|
module Y2017.M05.D10.Exercise where
{--
Another Mensa Genius Quiz-a-Day Book challenge from Dr. Abbie F. Salny, et al:
You've bought your weekly egg supply at the local farm store. The first morning
you have company for breakfast and use half the eggs plus one-half an egg. The
next morning you use one-half of what's left plus one-half an egg. The third
morning you use one-half of what's left plus one-half an egg, and on the fourth
morning, you're down to one solitary egg, so you make French toast. In all this
cooking, you've never had one-half an egg to carry over to the next day. How
many eggs did you buy originally?
--}
type Eggs = Int
halfPlusOneHalf :: Eggs -> Eggs
halfPlusOneHalf eggs = undefined
eggsBought :: Eggs
eggsBought = undefined
-- So, how do we reconcile halves 'inside the black box' of the function with
-- the 'integralness' of the egg-count?
|
geophf/1HaskellADay
|
exercises/HAD/Y2017/M05/D10/Exercise.hs
|
mit
| 878
| 0
| 5
| 159
| 44
| 28
| 16
| 6
| 1
|
{-
Copyright (c) 2015 Nils 'bash0r' Jonsson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-}
{- |
Module : $Header$
Description : The EDSL for creating JavaScript DOM elements.
Author : Nils 'bash0r' Jonsson
Copyright : (c) 2015 Nils 'bash0r' Jonsson
License : MIT
Maintainer : aka.bash0r@gmail.com
Stability : unstable
Portability : non-portable (Portability is untested.)
The EDSL for creating JavaScript DOM elements.
-}
module Language.JavaScript
( module Export
) where
import Language.JavaScript.DSL as Export
import Language.JavaScript.Transformation as Export
|
project-horizon/framework
|
src/lib/Language/JavaScript.hs
|
mit
| 1,608
| 0
| 4
| 299
| 30
| 22
| 8
| 4
| 0
|
{-
(**) Extract a slice from a list.
Given two indices, i and k, the slice is the list containing the elements between the i'th and k'th element of the original list (both limits included). Start counting the elements with 1.
Example in Haskell:
*Main> slice ['a','b','c','d','e','f','g','h','i','k'] 3 7
"cdefg"
-}
slice :: [a] -> Int -> Int -> [a]
slice xs i k
| i > 0 && k > i = take (k-i+1) $ drop (i-1) xs
| otherwise = error "Wrong indices"
|
gaoce/haskell_99
|
18.hs
|
mit
| 479
| 0
| 10
| 117
| 97
| 48
| 49
| 4
| 1
|
import Test.Framework (defaultMain, testGroup)
import QueueTest
main = defaultMain [
testGroup "Queue" queueTests
]
|
ornicar/haskant
|
tests/Tests.hs
|
mit
| 160
| 0
| 7
| 58
| 33
| 18
| 15
| 4
| 1
|
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE PatternSynonyms #-}
module Unison.Util.ColorText (
ColorText, Color(..), style, toANSI, toPlain, toHTML, defaultColors,
black, red, green, yellow, blue, purple, cyan, white, hiBlack, hiRed, hiGreen, hiYellow, hiBlue, hiPurple, hiCyan, hiWhite,
bold, underline, invert, background, unstyled,
module Unison.Util.AnnotatedText)
where
import Unison.Prelude
import qualified System.Console.ANSI as ANSI
import Unison.Util.AnnotatedText ( AnnotatedText(..)
, annotate
, Segment(..)
, toPair
)
import qualified Unison.Util.SyntaxText as ST hiding (toPlain)
type ColorText = AnnotatedText Color
data Color
= Black | Red | Green | Yellow | Blue | Purple | Cyan | White
| HiBlack| HiRed | HiGreen | HiYellow | HiBlue | HiPurple | HiCyan | HiWhite
| Bold | Underline | Invert Color | Background Color Color | Default
deriving (Eq, Ord, Show, Read)
black, red, green, yellow, blue, purple, cyan, white, hiBlack, hiRed, hiGreen, hiYellow, hiBlue, hiPurple, hiCyan, hiWhite, bold, underline :: ColorText -> ColorText
black = style Black
red = style Red
green = style Green
yellow = style Yellow
blue = style Blue
purple = style Purple
cyan = style Cyan
white = style White
hiBlack = style HiBlack
hiRed = style HiRed
hiGreen = style HiGreen
hiYellow = style HiYellow
hiBlue = style HiBlue
hiPurple = style HiPurple
hiCyan = style HiCyan
hiWhite = style HiWhite
bold = style Bold
underline = style Underline
unstyled :: ColorText -> ColorText
unstyled = style Default
background :: Color -> ColorText -> ColorText
background c ct = ct <&> Background c
invert :: ColorText -> ColorText
invert ct = ct <&> Invert
style :: Color -> ColorText -> ColorText
style = annotate
toHTML :: String -> ColorText -> String
toHTML cssPrefix (AnnotatedText at) = toList at >>= \case
Segment s color -> wrap color (s >>= newlineToBreak)
where
newlineToBreak '\n' = "<br/>\n"
newlineToBreak ch = [ch]
wrap Nothing s = "<code>" <> s <> "</code>"
wrap (Just c) s =
"<code class=" <> colorName c <> ">" <> s <> "</code>"
colorName c = "\"" <> cssPrefix <> "-" <> show c <> "\""
-- Convert a `ColorText` to a `String`, ignoring colors
toPlain :: ColorText -> String
toPlain (AnnotatedText at) = join (toList $ segment <$> at)
-- Convert a `ColorText` to a `String`, using ANSI codes to produce colors
toANSI :: ColorText -> String
toANSI (AnnotatedText chunks) =
join . toList $ snd (foldl' go (Nothing, mempty) chunks) <> resetANSI
where
go
:: (Maybe Color, Seq String)
-> Segment Color
-> (Maybe Color, Seq String)
go (prev, r) (toPair -> (text, new)) = if prev == new
then (prev, r <> pure text)
else
( new
, case new of
Nothing -> r <> resetANSI <> pure text
Just style -> r <> resetANSI <> toANSI style <> pure text
)
resetANSI = pure . ANSI.setSGRCode $ [ANSI.Reset]
toANSI :: Color -> Seq String
toANSI c = pure $ ANSI.setSGRCode (toANSI' c)
toANSI' :: Color -> [ANSI.SGR]
toANSI' c = case c of
Default -> []
Background c c2 -> (setBg <$> toANSI' c) <> toANSI' c2 where
setBg (ANSI.SetColor ANSI.Foreground intensity color) =
ANSI.SetColor ANSI.Background intensity color
setBg sgr = sgr
Invert c -> [ANSI.SetSwapForegroundBackground True] <> toANSI' c
Black -> [ANSI.SetColor ANSI.Foreground ANSI.Dull ANSI.Black]
Red -> [ANSI.SetColor ANSI.Foreground ANSI.Dull ANSI.Red]
Green -> [ANSI.SetColor ANSI.Foreground ANSI.Dull ANSI.Green]
Yellow -> [ANSI.SetColor ANSI.Foreground ANSI.Dull ANSI.Yellow]
Blue -> [ANSI.SetColor ANSI.Foreground ANSI.Dull ANSI.Blue]
Purple -> [ANSI.SetColor ANSI.Foreground ANSI.Dull ANSI.Magenta]
Cyan -> [ANSI.SetColor ANSI.Foreground ANSI.Dull ANSI.Cyan]
White -> [ANSI.SetColor ANSI.Foreground ANSI.Dull ANSI.White]
HiBlack -> [ANSI.SetColor ANSI.Foreground ANSI.Vivid ANSI.Black]
HiRed -> [ANSI.SetColor ANSI.Foreground ANSI.Vivid ANSI.Red]
HiGreen -> [ANSI.SetColor ANSI.Foreground ANSI.Vivid ANSI.Green]
HiYellow -> [ANSI.SetColor ANSI.Foreground ANSI.Vivid ANSI.Yellow]
HiBlue -> [ANSI.SetColor ANSI.Foreground ANSI.Vivid ANSI.Blue]
HiPurple -> [ANSI.SetColor ANSI.Foreground ANSI.Vivid ANSI.Magenta]
HiCyan -> [ANSI.SetColor ANSI.Foreground ANSI.Vivid ANSI.Cyan]
HiWhite -> [ANSI.SetColor ANSI.Foreground ANSI.Vivid ANSI.White]
Bold -> [ANSI.SetConsoleIntensity ANSI.BoldIntensity]
Underline -> [ANSI.SetUnderlining ANSI.SingleUnderline]
defaultColors :: ST.Element r -> Maybe Color
defaultColors = \case
ST.NumericLiteral -> Nothing
ST.TextLiteral -> Nothing
ST.BytesLiteral -> Just HiBlack
ST.CharLiteral -> Nothing
ST.BooleanLiteral -> Nothing
ST.Blank -> Nothing
ST.Var -> Nothing
ST.Reference _ -> Nothing
ST.Referent _ -> Nothing
ST.Op _ -> Nothing
ST.Unit -> Nothing
ST.AbilityBraces -> Just HiBlack
ST.ControlKeyword -> Just Bold
ST.LinkKeyword -> Just HiBlack
ST.TypeOperator -> Just HiBlack
ST.BindingEquals -> Nothing
ST.TypeAscriptionColon -> Just Blue
ST.DataTypeKeyword -> Nothing
ST.DataTypeParams -> Nothing
ST.DataTypeModifier -> Nothing
ST.UseKeyword -> Just HiBlack
ST.UsePrefix -> Just HiBlack
ST.UseSuffix -> Just HiBlack
ST.HashQualifier _ -> Just HiBlack
ST.DelayForceChar -> Just Yellow
ST.DelimiterChar -> Nothing
ST.Parenthesis -> Nothing
ST.DocDelimiter -> Just Green
ST.DocKeyword -> Just Bold
|
unisonweb/platform
|
parser-typechecker/src/Unison/Util/ColorText.hs
|
mit
| 5,942
| 0
| 15
| 1,512
| 1,849
| 981
| 868
| -1
| -1
|
data WherePenguinsLive =
Galapagos
| Antarctica
| Australia
| SouthAfrica
| SouthAmerica
deriving (Eq, Show)
data Penguin =
Peng WherePenguinsLive
deriving (Eq, Show)
isSouthAfrica :: WherePenguinsLive -> Bool
isSouthAfrica SouthAfrica = True
isSouthAfrica _ = False
gimmeWhereTheyLive :: Penguin -> WherePenguinsLive
gimmeWhereTheyLive (Peng whereItLives) = whereItLives
galapagosPenguin :: Penguin -> Bool
galapagosPenguin (Peng Galapagos) = True
galapagosPenguin _ = False
antarcticPenguin :: Penguin -> Bool
antarcticPenguin (Peng Antarctica) = True
antarcticPenguin _ = False
antarcticOrGalapagos :: Penguin -> Bool
antarcticOrGalapagos p =
(galapagosPenguin p)
|| (antarcticPenguin p)
|
candu/haskellbook
|
ch7/penguin.hs
|
mit
| 762
| 5
| 9
| 158
| 208
| 105
| 103
| 25
| 1
|
-- | Data definitions for canon types
module Canon.Data where
import Music.RealSimpleMusic
-- | Simplest of all Canons. Imitation at unison, all voices
-- playing the same instrument. Parameterized by title,
-- tune, scale, imitative distance, instrument, count of voices,
-- count of repetitions.
data SimpleCanon =
SimpleCanon
{sTitle :: Title
,sKeySignature :: KeySignature
,sTimeSignature :: TimeSignature
,sTempos :: [(Tempo,Rhythm)]
,sIxNotes :: [IndexedNote]
,sScale :: Scale
,sDistance :: Rhythm
,sInstrument :: Instrument
,sCountVoices :: Int
,sRepetitions :: Int
} deriving (Show)
-- | Additionally parameterize by lists of scales and octaves.
data ScalesCanon =
ScalesCanon
{scTitle :: Title
,scKeySignature :: KeySignature
,scTimeSignature :: TimeSignature
,scTempos :: [(Tempo,Rhythm)]
,scIxNotes :: [IndexedNote]
,scScales :: [Scale]
,scDistance :: Rhythm
,scOctaves :: [Octave]
,scInstruments :: [Instrument]
,scRepetitions :: Int
} deriving (Show)
-- | Additionally parameterize by imitative distance.
data Canon =
Canon
{cTitle :: Title
,cKeySignature :: KeySignature
,cTimeSignature :: TimeSignature
,cTempos :: [(Tempo,Rhythm)]
,cIxNotess :: [[IndexedNote]]
,cScales :: [Scale]
,cDistances :: [Rhythm]
,cOctaves :: [Octave]
,cInstruments :: [Instrument]
,cRepetitions :: Int
} deriving (Show)
|
tomtitchener/Canon
|
src/Canon/Data.hs
|
cc0-1.0
| 1,526
| 0
| 10
| 385
| 306
| 201
| 105
| 41
| 0
|
module Control.Time.CGI where
import Control.Time.Typ
import Operate.DateTime
import Gateway.CGI
import Data.Ix
defaults :: IO (Time,Time)
defaults = do
( lo, hi ) <- Operate.DateTime.defaults
return ( read lo, read hi ) -- ARGH
edit :: String -> Maybe Time -> Form IO Time
edit title mt = do
jetzt <- fmap read $ io $ Operate.DateTime.now
let t = case mt of
Just t -> t
Nothing -> jetzt
let def n opts = ( Just $ length $ takeWhile ( \(_,x) -> x /= n ) opts
, opts
)
filled ff cs = drop ( length cs ) ff ++ cs
numbers bnd = do n <- range bnd ; return ( filled "00" $ show n, n )
months = zip [ "Januar", "Februar", "März", "April"
, "Mai", "Juni", "Juli", "August"
, "September", "Oktober", "November", "Dezember"
]
[ 1.. ]
[ y, m, d, h, i, s ] <- selectors title
[ def ( year t ) $ numbers ( 2015, 2025 )
, def ( month t ) $ months
, def ( day t ) $ numbers ( 1, 31 )
, def ( hour t ) $ numbers ( 0, 23 )
, def ( minute t ) $ numbers ( 0, 59 )
, def ( second t ) $ numbers ( 0, 59 )
]
return $ Time
{ year = y, month = m, day = d
, hour = h, minute = i, second = s
}
|
marcellussiegburg/autotool
|
db/src/Control/Time/CGI.hs
|
gpl-2.0
| 1,229
| 28
| 13
| 406
| 553
| 300
| 253
| 33
| 2
|
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, UndecidableInstances, MultiParamTypeClasses, FlexibleContexts, FlexibleInstances #-}
module Machine.Acceptor.Type2 where
-- $Id$
import Language.Sampler
import Autolib.Informed
import Autolib.ToDoc
import Autolib.Reader
import qualified Autolib.Reporter.Checker as C
import Autolib.Reporter hiding ( output )
import Machine.Class
import Inter.Types ( ScoringOrder (..) , OrderScore (..) )
import Data.Typeable
data Acceptor = Acceptor String -- include machine type ??
deriving Typeable
instance OrderScore Acceptor where
scoringOrder _ = Increasing
instance ToDoc Acceptor where
toDoc ( Acceptor kind ) = text $ "Acceptor-" ++ kind
instance Reader Acceptor where
reader = do
my_reserved "Acceptor"
Autolib.Reader.char '-'
cs <- many alphaNum
return $ Acceptor cs
class ( Reader [dat], ToDoc [dat], Reader [prop], ToDoc [prop] )
=> Class dat prop
instance ( Reader [dat], ToDoc [dat], Reader [prop] , ToDoc [prop] )
=> Class dat prop
data Class dat prop => Type m dat prop =
Make { machine_desc :: String
, source :: Sampler
, cut :: Int -- ^ höchstens soviele schritte
, properties :: [ prop ] -- ^ sonstige Bedingungen an Maschine
, start :: m -- ^ damit soll der student anfangen
}
deriving ( Typeable )
$(derives [makeReader, makeToDoc] [''Type])
-- local variables:
-- mode: haskell
-- end:
|
Erdwolf/autotool-bonn
|
src/Machine/Acceptor/Type2.hs
|
gpl-2.0
| 1,478
| 2
| 9
| 330
| 375
| 214
| 161
| -1
| -1
|
{-
Copyright (C) 2006-7 John MacFarlane <jgm@berkeley.edu>
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.Docbook
Copyright : Copyright (C) 2006-7 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to Docbook XML.
-}
module Text.Pandoc.Writers.Docbook ( writeDocbook) where
import Text.Pandoc.Definition
import Text.Pandoc.XML
import Text.Pandoc.Shared
import Text.Pandoc.Templates (renderTemplate)
import Text.Pandoc.Readers.TeXMath
import Data.List ( isPrefixOf, intercalate )
import Data.Char ( toLower )
import Text.PrettyPrint.HughesPJ hiding ( Str )
import Text.Pandoc.Highlighting (languages, languagesByExtension)
-- | Convert list of authors to a docbook <author> section
authorToDocbook :: WriterOptions -> [Inline] -> Doc
authorToDocbook opts name' =
let name = render $ inlinesToDocbook opts name'
in if ',' `elem` name
then -- last name first
let (lastname, rest) = break (==',') name
firstname = removeLeadingSpace rest in
inTagsSimple "firstname" (text $ escapeStringForXML firstname) <>
inTagsSimple "surname" (text $ escapeStringForXML lastname)
else -- last name last
let namewords = words name
lengthname = length namewords
(firstname, lastname) = case lengthname of
0 -> ("","")
1 -> ("", name)
n -> (intercalate " " (take (n-1) namewords), last namewords)
in inTagsSimple "firstname" (text $ escapeStringForXML firstname) $$
inTagsSimple "surname" (text $ escapeStringForXML lastname)
-- | Convert Pandoc document to string in Docbook format.
writeDocbook :: WriterOptions -> Pandoc -> String
writeDocbook opts (Pandoc (Meta tit auths dat) blocks) =
let title = wrap opts tit
authors = map (authorToDocbook opts) auths
date = inlinesToDocbook opts dat
elements = hierarchicalize blocks
main = render $ vcat (map (elementToDocbook opts) elements)
context = writerVariables opts ++
[ ("body", main)
, ("title", render title)
, ("date", render date) ] ++
[ ("author", render a) | a <- authors ]
in if writerStandalone opts
then renderTemplate context $ writerTemplate opts
else main
-- | Convert an Element to Docbook.
elementToDocbook :: WriterOptions -> Element -> Doc
elementToDocbook opts (Blk block) = blockToDocbook opts block
elementToDocbook opts (Sec _ _num id' title elements) =
-- Docbook doesn't allow sections with no content, so insert some if needed
let elements' = if null elements
then [Blk (Para [])]
else elements
in inTags True "section" [("id",id')] $
inTagsSimple "title" (wrap opts title) $$
vcat (map (elementToDocbook opts) elements')
-- | Convert a list of Pandoc blocks to Docbook.
blocksToDocbook :: WriterOptions -> [Block] -> Doc
blocksToDocbook opts = vcat . map (blockToDocbook opts)
-- | Auxiliary function to convert Plain block to Para.
plainToPara :: Block -> Block
plainToPara (Plain x) = Para x
plainToPara x = x
-- | Convert a list of pairs of terms and definitions into a list of
-- Docbook varlistentrys.
deflistItemsToDocbook :: WriterOptions -> [([Inline],[[Block]])] -> Doc
deflistItemsToDocbook opts items =
vcat $ map (\(term, defs) -> deflistItemToDocbook opts term defs) items
-- | Convert a term and a list of blocks into a Docbook varlistentry.
deflistItemToDocbook :: WriterOptions -> [Inline] -> [[Block]] -> Doc
deflistItemToDocbook opts term defs =
let def' = concatMap (map plainToPara) defs
in inTagsIndented "varlistentry" $
inTagsIndented "term" (inlinesToDocbook opts term) $$
inTagsIndented "listitem" (blocksToDocbook opts def')
-- | Convert a list of lists of blocks to a list of Docbook list items.
listItemsToDocbook :: WriterOptions -> [[Block]] -> Doc
listItemsToDocbook opts items = vcat $ map (listItemToDocbook opts) items
-- | Convert a list of blocks into a Docbook list item.
listItemToDocbook :: WriterOptions -> [Block] -> Doc
listItemToDocbook opts item =
inTagsIndented "listitem" $ blocksToDocbook opts $ map plainToPara item
-- | Convert a Pandoc block element to Docbook.
blockToDocbook :: WriterOptions -> Block -> Doc
blockToDocbook _ Null = empty
blockToDocbook _ (Header _ _) = empty -- should not occur after hierarchicalize
blockToDocbook opts (Plain lst) = wrap opts lst
blockToDocbook opts (Para lst) = inTagsIndented "para" $ wrap opts lst
blockToDocbook opts (BlockQuote blocks) =
inTagsIndented "blockquote" $ blocksToDocbook opts blocks
blockToDocbook _ (CodeBlock (_,classes,_) str) =
text ("<screen" ++ lang ++ ">\n") <>
text (escapeStringForXML str) <> text "\n</screen>"
where lang = if null langs
then ""
else " language=\"" ++ escapeStringForXML (head langs) ++
"\""
isLang l = map toLower l `elem` map (map toLower) languages
langsFrom s = if isLang s
then [s]
else languagesByExtension . map toLower $ s
langs = concatMap langsFrom classes
blockToDocbook opts (BulletList lst) =
inTagsIndented "itemizedlist" $ listItemsToDocbook opts lst
blockToDocbook _ (OrderedList _ []) = empty
blockToDocbook opts (OrderedList (start, numstyle, _) (first:rest)) =
let attribs = case numstyle of
DefaultStyle -> []
Decimal -> [("numeration", "arabic")]
UpperAlpha -> [("numeration", "upperalpha")]
LowerAlpha -> [("numeration", "loweralpha")]
UpperRoman -> [("numeration", "upperroman")]
LowerRoman -> [("numeration", "lowerroman")]
items = if start == 1
then listItemsToDocbook opts (first:rest)
else (inTags True "listitem" [("override",show start)]
(blocksToDocbook opts $ map plainToPara first)) $$
listItemsToDocbook opts rest
in inTags True "orderedlist" attribs items
blockToDocbook opts (DefinitionList lst) =
inTagsIndented "variablelist" $ deflistItemsToDocbook opts lst
blockToDocbook _ (RawHtml str) = text str -- raw XML block
blockToDocbook _ HorizontalRule = empty -- not semantic
blockToDocbook opts (Table caption aligns widths headers rows) =
let alignStrings = map alignmentToString aligns
captionDoc = if null caption
then empty
else inTagsIndented "caption"
(inlinesToDocbook opts caption)
tableType = if isEmpty captionDoc then "informaltable" else "table"
percent w = show (truncate (100*w) :: Integer) ++ "%"
coltags = if all (== 0.0) widths
then empty
else vcat $ map (\w ->
selfClosingTag "col" [("width", percent w)]) widths
head' = if all null headers
then empty
else inTagsIndented "thead" $
tableRowToDocbook opts alignStrings "th" headers
body' = inTagsIndented "tbody" $
vcat $ map (tableRowToDocbook opts alignStrings "td") rows
in inTagsIndented tableType $ captionDoc $$ coltags $$ head' $$ body'
alignmentToString :: Alignment -> [Char]
alignmentToString alignment = case alignment of
AlignLeft -> "left"
AlignRight -> "right"
AlignCenter -> "center"
AlignDefault -> "left"
tableRowToDocbook :: WriterOptions
-> [String]
-> String
-> [[Block]]
-> Doc
tableRowToDocbook opts aligns celltype cols =
inTagsIndented "tr" $ vcat $
zipWith (tableItemToDocbook opts celltype) aligns cols
tableItemToDocbook :: WriterOptions
-> [Char]
-> [Char]
-> [Block]
-> Doc
tableItemToDocbook opts tag align item =
let attrib = [("align", align)]
in inTags True tag attrib $ vcat $ map (blockToDocbook opts) item
-- | Take list of inline elements and return wrapped doc.
wrap :: WriterOptions -> [Inline] -> Doc
wrap opts lst = if writerWrapText opts
then fsep $ map (inlinesToDocbook opts) (splitBy Space lst)
else inlinesToDocbook opts lst
-- | Convert a list of inline elements to Docbook.
inlinesToDocbook :: WriterOptions -> [Inline] -> Doc
inlinesToDocbook opts lst = hcat $ map (inlineToDocbook opts) lst
-- | Convert an inline element to Docbook.
inlineToDocbook :: WriterOptions -> Inline -> Doc
inlineToDocbook _ (Str str) = text $ escapeStringForXML str
inlineToDocbook opts (Emph lst) =
inTagsSimple "emphasis" $ inlinesToDocbook opts lst
inlineToDocbook opts (Strong lst) =
inTags False "emphasis" [("role", "strong")] $ inlinesToDocbook opts lst
inlineToDocbook opts (Strikeout lst) =
inTags False "emphasis" [("role", "strikethrough")] $
inlinesToDocbook opts lst
inlineToDocbook opts (Superscript lst) =
inTagsSimple "superscript" $ inlinesToDocbook opts lst
inlineToDocbook opts (Subscript lst) =
inTagsSimple "subscript" $ inlinesToDocbook opts lst
inlineToDocbook opts (SmallCaps lst) =
inTags False "emphasis" [("role", "smallcaps")] $
inlinesToDocbook opts lst
inlineToDocbook opts (Quoted _ lst) =
inTagsSimple "quote" $ inlinesToDocbook opts lst
inlineToDocbook opts (Cite _ lst) =
inlinesToDocbook opts lst
inlineToDocbook _ Apostrophe = char '\''
inlineToDocbook _ Ellipses = text "…"
inlineToDocbook _ EmDash = text "—"
inlineToDocbook _ EnDash = text "–"
inlineToDocbook _ (Code str) =
inTagsSimple "literal" $ text (escapeStringForXML str)
inlineToDocbook opts (Math _ str) = inlinesToDocbook opts $ readTeXMath str
inlineToDocbook _ (TeX _) = empty
inlineToDocbook _ (HtmlInline _) = empty
inlineToDocbook _ LineBreak = text $ "<literallayout></literallayout>"
inlineToDocbook _ Space = char ' '
inlineToDocbook opts (Link txt (src, _)) =
if isPrefixOf "mailto:" src
then let src' = drop 7 src
emailLink = inTagsSimple "email" $ text $
escapeStringForXML $ src'
in if txt == [Code src']
then emailLink
else inlinesToDocbook opts txt <+> char '(' <> emailLink <>
char ')'
else (if isPrefixOf "#" src
then inTags False "link" [("linkend", drop 1 src)]
else inTags False "ulink" [("url", src)]) $
inlinesToDocbook opts txt
inlineToDocbook _ (Image _ (src, tit)) =
let titleDoc = if null tit
then empty
else inTagsIndented "objectinfo" $
inTagsIndented "title" (text $ escapeStringForXML tit)
in inTagsIndented "inlinemediaobject" $ inTagsIndented "imageobject" $
titleDoc $$ selfClosingTag "imagedata" [("fileref", src)]
inlineToDocbook opts (Note contents) =
inTagsIndented "footnote" $ blocksToDocbook opts contents
|
kowey/pandoc-old
|
src/Text/Pandoc/Writers/Docbook.hs
|
gpl-2.0
| 12,175
| 0
| 20
| 3,322
| 3,014
| 1,553
| 1,461
| 209
| 13
|
{-
CC_Clones - Classic games reimplemented
© Callum Lowcay 2006-2011
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/>.
-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
module Common.Counters (
CounterState,
initCounter, updateCounter,
addCounter, subCounter, setCounter, resetCounter,
renderCounter
) where
import Common.AniTimer
import Common.Graphics
import Control.Monad
import Control.Monad.State
import Graphics.UI.SDL
data CounterState = CounterState {
digits :: Sprite,
display :: Int,
target :: Int,
aniTimer :: AniTimer,
framesToAlignment :: Int,
nDigits :: Int,
changedDigits :: [Bool]
} deriving (Show)
-- Initialise a new CounterState
initCounter :: Sprite -> Int -> CounterState
initCounter digits nDigits = CounterState {
digits = digits,
display = 0, target = 0,
aniTimer = resetTimer, framesToAlignment = 0,
nDigits = nDigits,
changedDigits = replicate nDigits False
}
-- The delay for counter frames, in milliseconds
frameDelay :: Double
frameDelay = ((1 :: Double) * 10^3) / (4 * 18)
smartDelay :: Int -> Int -> Double
smartDelay display target = frameDelay `min`
(((2 :: Double) * 10^3) / (fromIntegral (target - display) * 18))
-- Update a counter state based on a time delta
updateCounter :: Int -> CounterState -> CounterState
updateCounter delay (state@CounterState {..}) =
let
(frames, aniTimer') =
runState (advanceFrames delay (smartDelay display target)) aniTimer
offset' = framesToAlignment - frames
framesToAlignment' = if offset' < 0
then offset' `mod` 18 else offset'
advanceDigits = if offset' < 0
then abs offset' `div` 18 + 1 else 0
display' = if target > display
then min target (display + advanceDigits)
else if target < display
then max target (display - advanceDigits)
else display
in state {
framesToAlignment =
if target == display && framesToAlignment == 0
then 0 else framesToAlignment',
aniTimer = aniTimer',
display = display',
changedDigits = if framesToAlignment' > framesToAlignment
then zipWith (/=)
(fixedFieldLeft nDigits 0 $ toDec display)
(fixedFieldLeft nDigits 0 $ toDec display')
else changedDigits
}
-- Add a number to the counter
addCounter :: Int -> CounterState -> CounterState
addCounter n (state@(CounterState {target})) =
state {target = target + n}
-- Subtract a number from the counter
subCounter :: Int -> CounterState -> CounterState
subCounter n (state@(CounterState {target})) =
state {target = target - n}
-- Set the value of the counter
setCounter :: Int -> CounterState -> CounterState
setCounter n state = state {target = n}
-- Set the value of the counter, and do not animate the return
resetCounter :: Int -> CounterState -> CounterState
resetCounter n state = state {
target = n, display = n,
aniTimer = resetTimer, framesToAlignment = 0
}
-- Render the counter
renderCounter :: (Int, Int) -> CounterState -> IO ()
renderCounter (x, y) (state@CounterState {..}) = do
let
ddigits = fixedFieldLeft nDigits 0 $ toDec display
digitOffsets = zip
(reverse [0..(nDigits - 1)])
(map digitOffset (zip changedDigits ddigits))
ddisplay <- getVideoSurface
forM_ digitOffsets $ \(iDigit, offset) ->
renderSpriteLoopV ddisplay 0
(x + (iDigit * 20), y) offset digits
return ()
where
digitOffset (changed, d) =
((d * 18) - (if changed then framesToAlignment else 0)) `mod` 180
-- Pad or crop a list to a certain length
fixedFieldLeft :: Int -> a -> [a] -> [a]
fixedFieldLeft n padding xs = take n (xs ++ repeat padding)
-- Convert an integer to decimal digits, little endian
toDec :: Int -> [Int]
toDec n
| n < 10 = [n]
| otherwise = (n `rem` 10) : toDec (n `div` 10)
|
CLowcay/CC_Clones
|
src/Common/Counters.hs
|
gpl-3.0
| 4,245
| 90
| 15
| 790
| 1,214
| 681
| 533
| 91
| 7
|
-- Author: Viacheslav Lotsmanov
-- License: GPLv3 https://raw.githubusercontent.com/unclechu/xlib-keys-hack/master/LICENSE
module Utils.Sugar
( (&), (<&>), (.&>), (<$.), (.>)
, (?), (|?|) -- condition helpers
, module Data.Maybe.Preserve
, applyIf, applyUnless
, unnoticed, apart
, liftAT2, liftAT3
) where
import "base" Data.Bool (bool)
import qualified "base" Data.Function as Operators ((&))
import qualified "base" Data.Functor as Operators ((<&>))
import "base" Data.Functor (($>))
import "extra" Data.Tuple.Extra (uncurry3)
import "base" Control.Applicative (liftA2, liftA3)
-- local imports
import Data.Maybe.Preserve
( preserve, preserve'
, preserveF, preserveF', lazyPreserveF'
, preserveM, preserveM'
)
(&) :: a -> (a -> b) -> b
(&) = (Operators.&)
{-# INLINE (&) #-}
infixl 1 &
(<&>) :: Functor f => f a -> (a -> b) -> f b
(<&>) = (Operators.<&>)
{-# INLINE (<&>) #-}
infixr 5 <&>
-- Point-free fmap (left-to-right version).
-- Mix of (.>) and (<&>).
(.&>) :: Functor f => (a -> f b) -> (b -> c) -> a -> f c
f .&> g = f .> fmap g
{-# INLINE (.&>) #-}
infixl 9 .&> -- Precedence of (.>)
-- Point-free fmap.
-- Mix of (<$>) and (.).
(<$.) :: Functor f => (b -> c) -> (a -> f b) -> a -> f c
f <$. g = fmap f . g
{-# INLINE (<$.) #-}
infixr 9 <$. -- Precedence of (.)
-- Pipe composition operator.
-- Left-to-right composition instead of right-to-left.
-- Just like bind operator (>>=) for monads but for simple functions.
(.>) :: (a -> b) -> (b -> c) -> a -> c
(.>) = flip (.)
{-# INLINE [0] (.>) #-}
{-# RULES "(.>)/(.)" forall a b. (.>) a b = b . a #-}
infixl 9 .>
-- Makes function from then-else values that takes an expression.
-- Flipped version of `Data.Bool.bool`.
-- Example:
-- let foo = "Yes" |?| "No"
-- in [foo (2+2 == 4), foo (2+2 == 5)] -- returns: ["Yes", "No"]
(|?|) :: a -> a -> (Bool -> a)
a |?| b = bool b a
{-# INLINE [0] (|?|) #-}
{-# RULES "(|?|)/if" forall a b c. (|?|) a b c = if c then a else b #-}
infixl 2 |?|
-- If-then-else chain operator.
-- See more: https://wiki.haskell.org/Case
-- Example:
-- isFoo ? "foo" $
-- isBar ? "bar" $
-- "default"
(?) :: Bool -> a -> a -> a
(?) c x y = if c then x else y
{-# INLINE (?) #-}
infixl 1 ?
applyIf :: (a -> a) -> Bool -> a -> a
applyIf = (|?| id)
{-# INLINE applyIf #-}
applyUnless :: (a -> a) -> Bool -> a -> a
applyUnless = (id |?|)
{-# INLINE applyUnless #-}
-- | A helper to do some stuff with incoming value, just by reading it
-- or looking at it but always returning it back unchanged.
--
-- "unnoticed" means we don't notice if we remove whole call,
-- types won't change and original value will be the same.
--
-- It helps to avoid noisy code patterns like this one:
--
-- @
-- foo >>= \bar -> bar <$ f bar
-- @
--
-- To replace them with:
--
-- @
-- foo >>= unnoticed f
-- @
unnoticed :: Functor f => (a -> f b) -> a -> f a
unnoticed f x = x <$ f x
{-# INLINE unnoticed #-}
-- | Just an alias for the "$>" operator.
--
-- Kinda alternative version of "unnoticed", when we want to do something and
-- return back incoming value unchanged. But also we don't need that incoming
-- value at all in our function, so that function doesn't even care what type
-- of incoming value is and in some sense it lives "apart" from that context.
--
-- Writing it like this is not very readable:
--
-- @
-- foo >>= (($>) $ bar $ baz bzz)
-- @
--
-- This I think is better:
--
-- @
-- foo >>= apart (bar $ baz bzz)
-- @
apart :: Functor f => f a -> b -> f b
apart = ($>)
{-# INLINE apart #-}
liftAT2 :: Applicative f => (f a, f b) -> f (a, b)
liftAT2 = uncurry $ liftA2 (,)
{-# INLINE liftAT2 #-}
liftAT3 :: Applicative f => (f a, f b, f c) -> f (a, b, c)
liftAT3 = uncurry3 $ liftA3 (,,)
{-# INLINE liftAT3 #-}
|
unclechu/xlib-keys-hack
|
src/Utils/Sugar.hs
|
gpl-3.0
| 3,762
| 0
| 10
| 819
| 882
| 542
| 340
| -1
| -1
|
module Chap03.Exercise07 where
import Control.Applicative (liftA2)
import Data.Maybe
import Chap03.Data.Heap (Heap(..), arbHeap)
import Test.QuickCheck (Arbitrary(..), sized)
data ExplicitMin h a = Empty
| H a (h a)
deriving (Show)
instance Heap h => Heap (ExplicitMin h) where
empty = Empty
isEmpty Empty = True
isEmpty _ = False
insert x Empty = H x (insert x empty)
insert x (H y h) = H (min x y) (insert x h)
merge Empty h = h
merge h Empty = h
merge (H x h1) (H y h2) = H (min x y) (merge h1 h2)
findMin Empty = Nothing
findMin (H x _) = Just x
deleteMin Empty = Nothing
deleteMin (H _ h) = Just . fromMaybe Empty $ liftA2 H minh' h'
where
h' = deleteMin h
minh' = h' >>= findMin
instance (Heap h, Ord a, Arbitrary a) => Arbitrary (ExplicitMin h a) where
arbitrary = sized arbHeap
|
stappit/okasaki-pfds
|
src/Chap03/Exercise07.hs
|
gpl-3.0
| 910
| 0
| 8
| 275
| 389
| 203
| 186
| 25
| 0
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module OpenSandbox.Protocol.TypesSpec (main,spec) where
import Control.Monad
import qualified Data.ByteString as B
import Data.Int
import qualified Data.Text as T
import Data.UUID
import qualified Data.Vector as V
import Data.Word
import Generic.Random.Generic
import OpenSandbox
import Test.Hspec
import Test.QuickCheck
import Test.QuickCheck.Test
import OpenSandbox.World.ChunkSpec()
import Common
import Data.NBTSpec()
instance Arbitrary Chat where
arbitrary = genericArbitrary
instance Arbitrary UpdatedColumns where
arbitrary = do
columns <- (arbitrary :: Gen Int8)
if columns > 0
then UpdatedColumns <$> return columns <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
else return NoUpdatedColumns
instance Arbitrary UpdateScoreAction where
arbitrary = genericArbitrary
instance Arbitrary TitleAction where
arbitrary = genericArbitrary
instance Arbitrary TeamMode where
arbitrary = genericArbitrary
instance Arbitrary EntityProperty where
arbitrary = genericArbitrary
instance Arbitrary WorldBorderAction where
arbitrary = genericArbitrary
instance Arbitrary Icon where
arbitrary = genericArbitrary
instance Arbitrary CombatEvent where
arbitrary = genericArbitrary
instance Arbitrary EntityStatus where
arbitrary = genericArbitrary
instance Arbitrary BlockChange where
arbitrary = genericArbitrary
instance Arbitrary GameChangeReason where
arbitrary = do
i <- (choose (0,10) :: Gen Int)
if i /= 9
then return (toEnum i)
else return (toEnum (i - 1))
instance Arbitrary Difficulty where
arbitrary = genericArbitrary
instance Arbitrary GameMode where
arbitrary = genericArbitrary
instance Arbitrary Dimension where
arbitrary = genericArbitrary
instance Arbitrary WorldType where
arbitrary = genericArbitrary
instance Arbitrary Statistic where
arbitrary = genericArbitrary
instance Arbitrary ProtocolState where
arbitrary = genericArbitrary
instance Arbitrary PlayerListEntries where
arbitrary = genericArbitrary
instance Arbitrary PlayerListAdd where
arbitrary = genericArbitrary
instance Arbitrary PlayerListUpdateGameMode where
arbitrary = genericArbitrary
instance Arbitrary PlayerListUpdateLatency where
arbitrary = genericArbitrary
instance Arbitrary PlayerListUpdateDisplayName where
arbitrary = genericArbitrary
instance Arbitrary PlayerListRemovePlayer where
arbitrary = genericArbitrary
instance Arbitrary SlotData where
arbitrary = genericArbitrary
instance Arbitrary PlayerProperty where
arbitrary = genericArbitrary
instance Arbitrary EntityMetadataEntry where
arbitrary = do
k <- arbitrary :: Gen Bool
w <- choose (0,254) :: Gen Word8
if k
then return MetadataEnd
else Entry <$> return w <*> arbitrary <*> arbitrary
instance Arbitrary MetadataType where
arbitrary = genericArbitrary
instance Arbitrary Animation where
arbitrary = genericArbitrary
instance Arbitrary UpdateBlockEntityAction where
arbitrary = genericArbitrary
instance Arbitrary BlockAction where
arbitrary = genericArbitrary
instance Arbitrary InstrumentType where
arbitrary = genericArbitrary
instance Arbitrary NotePitch where
arbitrary = genericArbitrary
instance Arbitrary PistonState where
arbitrary = genericArbitrary
instance Arbitrary PistonDirection where
arbitrary = genericArbitrary
instance Arbitrary BossBarAction where
arbitrary = genericArbitrary
instance Arbitrary Slot where
arbitrary = mkSlot <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
instance Arbitrary UseEntityType where
arbitrary = genericArbitrary
instance Arbitrary EntityHand where
arbitrary = genericArbitrary
instance Arbitrary ScoreboardMode where
arbitrary = genericArbitrary
spec :: Spec
spec = do
describe "Minecraft Protocol Core Types (Serialize)" $ do
context "VarInt:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_CustomSerializeIdentity putVarInt getVarInt :: Int -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "VarLong:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_CustomSerializeIdentity putVarLong getVarLong :: Int64 -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "String:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_CustomSerializeIdentity putText getText :: T.Text -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "EntityMetadata:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_CustomSerializeIdentity putEntityMetadata getEntityMetadata :: EntityMetadata -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "Slot:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: Slot -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "Position:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_CustomSerializeIdentity putPosition getPosition :: Position -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "Angle:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_CustomSerializeIdentity putAngle getAngle :: Angle -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "UUID:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_CustomSerializeIdentity putUUID getUUID :: UUID -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "UUID':" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_CustomSerializeIdentity putUUID' getUUID' :: UUID -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "ByteArray:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_CustomSerializeIdentity putNetcodeByteString getNetcodeByteString :: B.ByteString -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
describe "Minecraft Protocol Custom Records" $ do
context "BlockChange:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: BlockChange -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "Statistic:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: Statistic -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "PlayerProperty:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: PlayerProperty -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "PlayerListEntries:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: PlayerListEntries -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "Icon:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: Icon -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "EntityProperty:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: EntityProperty -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "BlockAction:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: BlockAction -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "BossBar:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: BossBarAction -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "WorldBorderAction:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: WorldBorderAction -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "UpdatedColumns:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: UpdatedColumns -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "CombatEvent:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: CombatEvent -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "ScoreboardMode:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: ScoreboardMode -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "TeamMode:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: TeamMode -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
context "TitleAction:" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: TitleAction -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
main :: IO ()
main = hspec spec
|
oldmanmike/opensandbox
|
test/OpenSandbox/Protocol/TypesSpec.hs
|
gpl-3.0
| 9,989
| 0
| 17
| 2,579
| 2,607
| 1,264
| 1,343
| 287
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Carbon.Website.Item where
import Data.Function (on)
import Data.Monoid (Monoid(..))
import qualified Data.Aeson as Aeson
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import qualified Data.Set as Set
import Carbon.Backend.Item (hToId, idToH)
import Carbon.Website.Common
import qualified Carbon.Backend.Logic as BLogic
import qualified Carbon.Backend.Item as BItem
import qualified Carbon.Data.Logic as Logic
import qualified Carbon.Data.Logic.Evaluation as Evaluation
import qualified Carbon.Data.ResultSet as ResultSet
import qualified Carbon.Website.Session as Session
createItem :: OBW Response
createItem = withItem $ \i -> msum [sane i, setItem i]
-- | FIXME We need to chk if item type is preserved during update
updateItem :: ItemId -> OBW Response
updateItem iid = withItem $ \i -> do
eEO <- liftB $ GetItem iid
case eEO of
(Left e) -> respBadRequest . toResponse $ unlines ["Cannot update requested item, because it cannot be found.", e]
(Right o) -> do
o' <- liftB $ idToH o
let i' = o' `mappend` (i <+ iid)
msum [sane i', okChange o' i', setItem i']
where
okChange :: Item String -> Item String -> OBW Response
okChange old new = do
eEU <- liftB . GetUser $ commitAuthor new
case eEU of
(Left e) -> respBadRequest . toResponse $ unlines ["Cannot find commitAuthor on the server.",e]
(Right u) -> do
let okDisc = (okDDelta u `on` discussion) old new
okResS = (ResultSet.okRDelta u `on` resultSet) old new
when (okDisc && okResS) mzero
let repDisc = okDisc ? (["Changes to the Discussion were accepted."],["Changes on the Discussion were not accepted."])
repResS = okResS ? (["Changes to the ResultSet were accepted."],["Changes on the ResultSet were not accepted."])
liftIO $ (ResultSet.rDeltaTable u `on` resultSet) old new
respBadRequest . toResponse . unlines $ repDisc++repResS
okDDelta :: User -> Maybe (Discussion (Item String)) -> Maybe (Discussion (Item String)) -> Bool
okDDelta _ Nothing _ = True
okDDelta _ (Just _) Nothing = False
{- If the user is an admin, we request that discussionId and evaluation stay the same.
Otherwise deadline must be the same and participants may only differ by the current user. -}
okDDelta u (Just old) (Just new)
| isAdmin u = sameId old new && sameEvaluation old new
| otherwise = and [sameId old new, sameEvaluation old new, sameDeadline old new, saneParticipants u old new]
where
sameId = (==) `on` discussionId
sameEvaluation = (==) `on` evaluation
sameDeadline = (==) `on` deadline
saneParticipants u = (==) `on` (Set.delete (userId u) . participants)
readItem :: ItemId -> OBW Response
readItem iid = do
eEI <- liftB $ GetItem iid
case eEI of
(Right i) -> do
i' <- liftB $ BItem.mapArgs i BLogic.autoCondition
displayItem i'
(Left e) -> respInternalServerError $ toResponse e
deleteItem :: ItemId -> OBW Response
deleteItem iid = do
mE <- liftB $ DeleteItem iid
case mE of
Nothing -> respOk . toResponse $ concat ["Item ", show iid, " deleted."]
(Just e) -> respInternalServerError $ toResponse e
-- Handling items:
withItem :: (Item String -> OBW Response) -> OBW Response
withItem onItem = Session.chkSession' $ \uid -> do
eEItem <- getItem uid
let onError = respBadRequest . toResponse
either onError onItem eEItem
setItem :: Item String -> OBW Response
setItem i = do
liftIO $ putStrLn "Carbon.Website.Item:setItem"
liftIO $ print i
eEI <- liftB $ SetItem =<< BLogic.autoCondition =<< hToId i
let no = respInternalServerError . toResponse
either no displayItem eEI
displayItem :: Item Id -> OBW Response
displayItem i = do
i' <- liftB $ idToH i
respOk $ responseJSON' i'
-- sane :: Item a -> OBW Response
sane :: Item String -> OBW Response
sane i
| itemIsSane i = mzero
| otherwise = do
liftIO $ putStrLn "Insane Item found:" >> sanityTable i
respBadRequest "Sorry, but the given Item is not considered sane by the server."
-- Reading get parameters:
getItem :: UserId -> OBW (Either Error (Item String))
getItem author = do
-- Reading parts:
mDescription <- getFromJSON "description"
mArticle <- getFromJSON "article"
mCondition <- getFromJSON "condition"
mRelation <- getFromJSON "relation"
mDiscussion <- getFromJSON "discussion"
mResultSet <- getFromJSON "resultSet"
plusm (return $ Left "Got no commit Message") $ do
cMsg <- look "commitMessage"
-- Constructing Item:
let i = Item{
itemId = mempty
, description = mDescription
, article = mArticle
, condition = mCondition
, relation = mRelation
, relations = []
, discussion = mDiscussion
, resultSet = mResultSet
, creation = mempty
, deletion = mempty
, parents = mempty
, children = mempty
, commitMessage = cMsg
, commitAuthor = author
}
return $ Right i
where
getFromJSON :: (Aeson.FromJSON a) => String -> OBW (Maybe a)
getFromJSON = plusm (return Nothing) . liftM Aeson.decode . lookBS
fitInstance :: ItemId -> OBW Response
fitInstance iid = Session.chkSession' $ \uid -> do
liftIO $ putStrLn "Carbon.Website.Item:fitInstance"
eEI <- liftB $ GetItem iid
case eEI of
(Left e) -> respBadRequest $ toResponse e
(Right i) -> plusm noDisc $ do
guard $ itemIsDiscussion i
plusm noFile $ do
f <- getFile
let source = "Client upload by user: " ++ show uid
eInstance = Logic.execParser Logic.parseInstance source f
either withError (withInstance uid i) eInstance
where
noDisc = respBadRequest "Item is no discussion."
noFile = respBadRequest "Expected .dl file is missing."
withError :: String -> OBW Response
withError = respBadRequest . toResponse
withInstance :: UserId -> Item Id -> Instance Headline -> OBW Response
withInstance uid item inst = do
eEI <- liftB $ BLogic.fitInstance uid item inst
case eEI of
(Right i) -> respOk $ responseJSON' i
(Left e) -> respInternalServerError $ toResponse e
getFile :: OBW String
getFile = do
(tmpName, _, _) <- lookFile "file"
liftIO $ readFile tmpName
acs :: ItemId -> OBW Response
acs = respOk . responseJSON' <=< liftB . BLogic.diamondInput
{-|
Should be called upon a discussion,
which will then be evaluated.
|-}
evaluate :: ItemId -> OBW Response
evaluate iid = do
liftIO $ putStrLn "Carbon.Website.Item:evaluate"
(input, _) <- liftB $ BLogic.diamondInput iid
config <- gets config
let path = diamondDlDir config ++ show iid ++ ".dl"
results <- liftIO $ Evaluation.run config path input
let rSet = fromResults $ fmap read results
eEI <- liftB $ do
(Right i) <- GetItem iid
SetItem . addVoters $ i <+ rSet
case eEI of
(Right i) -> displayItem i
(Left e) -> respInternalServerError $ toResponse e
where
-- only works when: itemIsDiscussion i, itemIsResult i
addVoters :: Item Id -> Item Id
addVoters i = let ps = participants . Maybe.fromJust $ discussion i
ps' = zip (Set.toList ps) $ repeat False
rs = Maybe.fromJust $ resultSet i
in i <+ rs{voters = ps'}
|
runjak/carbon-adf
|
Carbon/Website/Item.hs
|
gpl-3.0
| 7,521
| 0
| 22
| 1,915
| 2,289
| 1,151
| 1,138
| -1
| -1
|
{---------------------------------------------------------------------}
{- Copyright 2015, 2016 Nathan Bloomfield -}
{- -}
{- This file is part of Carl. -}
{- -}
{- Carl is free software: you can redistribute it and/or modify -}
{- it under the terms of the GNU General Public License version 3, -}
{- as published by the Free Software Foundation. -}
{- -}
{- Carl 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 Carl. If not, see <http://www.gnu.org/licenses/>. -}
{---------------------------------------------------------------------}
{-# OPTIONS_GHC -XMultiParamTypeClasses #-}
module Carl.Struct.Matrix (
Matrix(Null), Dim, Index, mCell,
-- Construct
mRowMajorFromList, mFromRowList, mRowFromList, mColFromList,
mFromMap, mConst, mFromMapM, mToRowList, mRowsOf, mColsOf, toListM,
mListRowOf, mListColOf, mRowOf, mColOf,
mEntryOf, mIsNull, mIsSquare,
mNumRows, mNumCols,
mIsRow, mIsCol,
mTranspose, mHCat, mVCat, mBCat, mHCats, mVCats, mBCats,
mSwapRows, mSwapCols, mDelRow, mDelCol,
mShowStr, tabulateWithM,
mAddRow, mAddCol, mScaleRow, mScaleCol,
mScaleRowT, mScaleColT,
mSeq, mAny, mAll, mCombine, mConvolve,
mEScale, mEAdd, mESwap, mEId,
mEScaleT, mEAddT, mESwapT, mEIdT,
gjPivots, gjREForm, mClearAbovePivot, mClearAbovePivots, gjREFactor,
mGJForm, mGJFactor, mIsGaussJordanForm, mPivotCols, mRank,
mGJFormT, mGJFactorT
) where
{--------------------}
{- Contents -}
{- :General -}
{- :Types -}
{- :Construct -}
{- :Query -}
{- :Structure -}
{- :Monad -}
{- :Mutate -}
{- :Display -}
{- :Arithmetic -}
{- :Algebra -}
{- :Ringoid -}
{- :URingoid -}
{- :GaussJordan -}
{--------------------}
import Carl.Algebra.Ring
import Carl.Monad
import Carl.Write.LaTeX
import GHC.Arr
import Control.Monad.Instances ()
import Data.List (groupBy, findIndex, intercalate, genericLength, isPrefixOf, intersperse)
import Control.Monad (foldM, zipWithM)
import Control.Monad.ListM (foldM1)
{----------}
{- :Types -}
{----------}
type Dim = (Integer, Integer)
type Index = (Integer, Integer)
getColIdx :: Index -> Integer
getColIdx (_,c) = c
data Matrix a
= Matrix (Array Index a) | Null
deriving Eq
{--------------}
{- :Construct -}
{--------------}
-- From Element
mCell :: a -> Matrix a
mCell x = Matrix $ array ((1,1),(1,1)) [((1,1),x)]
-- From List
-- This should be only one of two constructors which call ``array''.
mRowMajorFromList :: Integer -> Integer -> [a] -> Either AlgErr (Matrix a)
mRowMajorFromList _ _ [] = Right Null
mRowMajorFromList r c as
| r <= 0 || c <= 0 = Left (NullMatrix "mRowMajorFromList")
| otherwise = do
if enoughElts (r*c) as
then do
let bds = ((1,1), (fromIntegral r, fromIntegral c))
return $ Matrix $ array bds $ zip (range bds) as
else Left MalformedMatrix
where
enoughElts _ [] = True
enoughElts n (_:xs)
| n <= 0 = True
| otherwise = enoughElts (n-1) xs
mFromRowList :: [[a]] -> Either AlgErr (Matrix a)
mFromRowList [] = return Null
mFromRowList xss
| sameLength xss = do
let r = genericLength xss
let c = genericLength (head xss)
mRowMajorFromList r c (concat xss)
| otherwise = Left MalformedMatrix
sameLength :: [[a]] -> Bool
sameLength [] = True
sameLength xs = (maximum ks) == (minimum ks)
where ks = map length xs
mRowFromList :: [a] -> Either AlgErr (Matrix a)
mRowFromList as = mRowMajorFromList 1 (genericLength as) as
mColFromList :: [a] -> Either AlgErr (Matrix a)
mColFromList as = mRowMajorFromList (genericLength as) 1 as
-- From Map
mFromMap :: Dim -> (Index -> a) -> Either AlgErr (Matrix a)
mFromMap (r,c) f = mRowMajorFromList r c $ map f $ range ((1,1),(r,c))
mConst :: Dim -> a -> Either AlgErr (Matrix a)
mConst d a = mFromMap d (const a)
mFromMapM :: Dim -> (Index -> Either AlgErr a) -> Either AlgErr (Matrix a)
mFromMapM (r,c) f = do
as <- sequence $ map f $ range ((1,1),(r,c))
mRowMajorFromList r c as
{----------}
{- :Query -}
{----------}
mIsNull :: Matrix a -> Either AlgErr Bool
mIsNull (Matrix _) = return False
mIsNull Null = return True
-- Dimension
mDim :: Matrix a -> Either AlgErr Dim
mDim (Matrix m) = Right $ snd $ bounds m
mDim Null = Left (NullMatrix "mDim")
mNumRows :: Matrix a -> Either AlgErr Integer
mNumRows Null = Left (NullMatrix "mNumRows")
mNumRows m = do
(r,_) <- mDim m
return r
mIsRow :: Matrix a -> Either AlgErr Bool
mIsRow m = do
r <- mNumRows m
return (r == 1)
mNumCols :: Matrix a -> Either AlgErr Integer
mNumCols Null = Left (NullMatrix "mNumCols")
mNumCols m = do
(_,c) <- mDim m
return c
mIsCol :: Matrix a -> Either AlgErr Bool
mIsCol m = do
c <- mNumCols m
return (c == 1)
mIsSquare :: Matrix a -> Either AlgErr Bool
mIsSquare Null = return False
mIsSquare m = do
(r,c) <- mDim m
return (r == c)
-- Indices
mIsRowIndexOf :: Integer -> Matrix a -> Either AlgErr Bool
_ `mIsRowIndexOf` Null = return False
i `mIsRowIndexOf` m = do
(r,_) <- mDim m
return $ 0 < i && i <= r
mIsColIndexOf :: Integer -> Matrix a -> Either AlgErr Bool
_ `mIsColIndexOf` Null = return False
j `mIsColIndexOf` m = do
(_,c) <- mDim m
return $ 0 < j && j <= c
mIsIndexOf :: Index -> Matrix a -> Either AlgErr Bool
(i,j) `mIsIndexOf` m = do
p <- i `mIsRowIndexOf` m
q <- j `mIsColIndexOf` m
return (p && q)
-- Entries
mEntryOf :: Index -> Matrix a -> Either AlgErr a
_ `mEntryOf` Null = Left (NullMatrix "mEntryOf")
(i,j) `mEntryOf` m@(Matrix a) = do
p <- (i,j) `mIsIndexOf` m
if p
then Right $ a ! (i,j)
else do
d <- mDim m
Left (InvalidIndex $ show (i,j) ++ show d)
mToRowList :: Matrix a -> [[a]]
mToRowList Null = []
mToRowList (Matrix a) = map (map snd) $ groupBy foo $ assocs a
where foo ((i1,_),_) ((i2,_),_) = i1 == i2
toListM :: Matrix a -> [a]
toListM Null = []
toListM (Matrix m) = map snd $ assocs m
mListRowOf :: Integer -> Matrix a -> Either AlgErr [a]
k `mListRowOf` m = do
p <- k `mIsRowIndexOf` m
(r,c) <- mDim m
if not p
then Left (InvalidRowIndex $ show k ++ show (r,c))
else sequence $ map (\j -> (k,j) `mEntryOf` m) [1..c]
mListColOf :: Integer -> Matrix a -> Either AlgErr [a]
k `mListColOf` m = do
p <- k `mIsColIndexOf` m
(r,c) <- mDim m
if not p
then Left (InvalidColIndex $ show k ++ show (r,c))
else sequence $ map (\i -> (i,k) `mEntryOf` m) [1..r]
-- Entrywise bool
mAll :: (a -> Bool) -> Matrix a -> Bool
mAll p m = all p $ toListM m
mAny :: (a -> Bool) -> Matrix a -> Bool
mAny p m = any p $ toListM m
{--------------}
{- :Structure -}
{--------------}
mRowOf :: Integer -> Matrix a -> Either AlgErr (Matrix a)
i `mRowOf` m = do
p <- i `mIsRowIndexOf` m
(r,c) <- mDim m
if not p
then Left (InvalidRowIndex $ show i ++ show (r,c))
else do
let foo (h,k) = (h+i-1,k) `mEntryOf` m
mFromMapM (1,c) foo
mRowsOf :: Matrix a -> Either AlgErr [Matrix a]
mRowsOf Null = Right []
mRowsOf m = do
r <- mNumRows m
sequence $ map (`mRowOf` m) [1..r]
mColOf :: Integer -> Matrix a -> Either AlgErr (Matrix a)
j `mColOf` m = do
p <- j `mIsColIndexOf` m
(r,c) <- mDim m
if not p
then Left (InvalidColIndex $ show j ++ show (r,c))
else do
let foo (h,k) = (h,k+j-1) `mEntryOf` m
mFromMapM (r,1) foo
mColsOf :: Matrix a -> Either AlgErr [Matrix a]
mColsOf Null = Right []
mColsOf m = do
c <- mNumCols m
sequence $ map (`mColOf` m) [1..c]
mTranspose :: Matrix a -> Either AlgErr (Matrix a)
mTranspose Null = Right Null
mTranspose m = do
(r,c) <- mDim m
let foo (i,j) = (j,i) `mEntryOf` m
(c,r) `mFromMapM` foo
-- Horizontal catenate
mHCat :: Matrix a -> Matrix a -> Either AlgErr (Matrix a)
mHCat a Null = Right a
mHCat Null b = Right b
mHCat a b = do
(ra,ca) <- mDim a
(rb,cb) <- mDim b
if ra /= rb
then Left (DimMismatch $ show (ra,ca) ++ show (rb,cb))
else do
let foo (i,j) = if j <= ca then (i,j) `mEntryOf` a else (i,j-ca) `mEntryOf` b
mFromMapM (ra, ca + cb) foo
-- Vertical catenate
mVCat :: Matrix a -> Matrix a -> Either AlgErr (Matrix a)
mVCat a Null = Right a
mVCat Null b = Right b
mVCat a b = do
(ra,ca) <- mDim a
(rb,cb) <- mDim b
if ca /= cb
then Left (DimMismatch $ show (ra,ca) ++ show (rb,cb))
else do
let foo (i,j) = if i <= ra then (i,j) `mEntryOf` a else (i-ra,j) `mEntryOf` b
mFromMapM (ra + rb, ca) foo
mBCat :: (Ringoid a) => Matrix a -> Matrix a -> Either AlgErr (Matrix a)
mBCat a Null = Right a
mBCat Null b = Right b
mBCat a b = do
(ra,ca) <- mDim a
(rb,cb) <- mDim b
za <- mConst (ra,cb) rZero
wa <- mHCat a za
zb <- mConst (rb,ca) rZero
wb <- mHCat zb b
mVCat wa wb
mHCats, mVCats :: [Matrix a] -> Either AlgErr (Matrix a)
mHCats = foldM mHCat Null
mVCats = foldM mVCat Null
mBCats :: (Ringoid a) => [Matrix a] -> Either AlgErr (Matrix a)
mBCats = foldM mBCat Null
-- Quadrant catenate
mQCat :: ((Matrix a, Matrix a), (Matrix a, Matrix a)) -> Either AlgErr (Matrix a)
mQCat ((a,b),(c,d)) = do
h <- mHCat a b
k <- mHCat c d
mVCat h k
mHSplit :: Matrix a -> Integer -> Either AlgErr (Matrix a, Matrix a)
mHSplit Null _ = Right (Null, Null)
mHSplit m k = do
(r,c) <- mDim m
if k <= 1
then return (Null, m)
else if k >= c+1
then return (m, Null)
else do
a <- mFromMapM (r, k-1) (\(i,j) -> (i,j) `mEntryOf` m)
b <- mFromMapM (r, c-k+1) (\(i,j) -> (i, j+k-1) `mEntryOf` m)
return (a,b)
mVSplit :: Matrix a -> Integer -> Either AlgErr (Matrix a, Matrix a)
mVSplit Null _ = Right (Null, Null)
mVSplit m k = do
(r,c) <- mDim m
if k <= 1
then return (Null, m)
else if k >= r+1
then return (m, Null)
else do
a <- mFromMapM (k-1, c) (\(i,j) -> (i,j) `mEntryOf` m)
b <- mFromMapM (r-k+1, c) (\(i,j) -> (i+k-1, j) `mEntryOf` m)
return (a,b)
mQSplit :: Matrix a -> Index -> Either AlgErr ((Matrix a, Matrix a), (Matrix a, Matrix a))
mQSplit m (i,j) = do
(h,k) <- m `mVSplit` i
(a,b) <- h `mHSplit` j
(c,d) <- k `mHSplit` j
return ((a,b),(c,d))
{----------}
{- :Monad -}
{----------}
instance Functor Matrix where
fmap _ Null = Null
fmap f (Matrix m) = Matrix $ fmap f m
mSeq :: (Monad m) => Matrix (m a) -> m (Matrix a)
mSeq m = do
case mToRowList m of
[] -> return Null
as -> do
rs <- sequence $ map sequence as
case mDim m of
Left _ -> return Null
Right (r,c) -> do
let bds = ((1,1),(r,c))
return $ Matrix $ array bds $ zip (range bds) (concat rs)
{-----------}
{- :Mutate -}
{-----------}
mSwapRows :: Integer -> Integer -> Matrix a -> Either AlgErr (Matrix a)
mSwapRows r1 r2 m = do
(r,c) <- mDim m
let foo (i,j)
| i == r1 = (r2,j) `mEntryOf` m
| i == r2 = (r1,j) `mEntryOf` m
| otherwise = (i,j) `mEntryOf` m
(r,c) `mFromMapM` foo
mSwapCols :: Integer -> Integer -> Matrix a -> Either AlgErr (Matrix a)
mSwapCols c1 c2 m = do
(r,c) <- mDim m
let foo (i,j)
| j == c1 = (i,c2) `mEntryOf` m
| j == c2 = (i,c1) `mEntryOf` m
| otherwise = (i,j) `mEntryOf` m
(r,c) `mFromMapM` foo
mDelRow :: Matrix a -> Integer -> Either AlgErr (Matrix a)
m `mDelRow` t = do
p <- t `mIsRowIndexOf` m
if not p
then return m
else do
(r,c) <- mDim m
let foo (i,j) = if i < t then (i,j) `mEntryOf` m else (i+1,j) `mEntryOf` m
mFromMapM (r-1, c) foo
mDelCol :: Matrix a -> Integer -> Either AlgErr (Matrix a)
m `mDelCol` t = do
p <- t `mIsColIndexOf` m
if not p
then return m
else do
(r,c) <- mDim m
let foo (i,j) = if j < t then (i,j) `mEntryOf` m else (i,j+1) `mEntryOf` m
mFromMapM (r, c-1) foo
{------------}
{- :Display -}
{------------}
mShowStr :: Matrix String -> Either AlgErr String
mShowStr m = do
let
bar [] = "[]"
bar xs = "[" ++ (intercalate ";" xs) ++ "]"
return $ bar $ map bar $ mToRowList m
instance (Show a) => Show (Matrix a) where
show m = case mShowStr $ fmap show m of
Left _ -> "error in matrix"
Right s -> s
tabulateWith :: (a -> String) -> Matrix a -> Either AlgErr String
tabulateWith _ Null = return "[]"
tabulateWith f m = do
let rows = map (map f) $ mToRowList m
let k = maximum $ map length $ concat rows
let g x = reverse $ take k $ (reverse x) ++ (repeat ' ')
let foo xs = "[ " ++ xs ++ " ]"
return $ init $ unlines $ map (foo . unwords . map g) $ rows
tabulateWithS :: (a -> String) -> Matrix a -> String
tabulateWithS f m = case tabulateWith f m of
Left _ -> "error in tabulateWithS"
Right s -> s
tabulateWithM :: (Functor m, Monad m) => (a -> m String) -> Matrix a -> m String
tabulateWithM f m = fmap (tabulateWithS id) $ mSeq $ fmap f m
{---------------}
{- :Arithmetic -}
{---------------}
mCombine :: (a -> b -> c) -> Matrix a -> Matrix b -> Either AlgErr (Matrix c)
mCombine _ Null Null = return Null
mCombine f m n = do
dm <- mDim m
dn <- mDim n
if dm /= dn
then Left (DimMismatch $ show dm ++ show dn)
else do
let foo (i,j) = do
x <- (i,j) `mEntryOf` m
y <- (i,j) `mEntryOf` n
return (f x y)
mFromMapM dm foo
mCombineE :: (a -> b -> Either AlgErr c) -> Matrix a -> Matrix b -> Either AlgErr (Matrix c)
mCombineE _ Null Null = return Null
mCombineE f m n = do
dm <- mDim m
dn <- mDim n
if dm /= dn
then Left (DimMismatch $ show dm ++ show dn)
else do
let foo (i,j) = do
x <- (i,j) `mEntryOf` m
y <- (i,j) `mEntryOf` n
case (f x y) of
Left err -> Left (MatCoefErr $ show err)
Right z -> return z
mFromMapM dm foo
mConvolve
:: (a -> b -> c) -> (c -> c -> c) -> Matrix a -> Matrix b -> Either AlgErr (Matrix c)
mConvolve _ _ Null _ = Right Null
mConvolve _ _ _ Null = Right Null
mConvolve f g m n = do
(rm,cm) <- mDim m
(rn,cn) <- mDim n
if cm /= rn
then Left (DimMismatch $ show (rm,cm) ++ show (rn,cn))
else do
let foo (i,j) = do
as <- i `mListRowOf` m
bs <- j `mListColOf` n
return $ foldl1 g $ zipWith f as bs
mFromMapM (rm,cn) foo
mConvolveE
:: (a -> b -> Either AlgErr c) -> (c -> c -> Either AlgErr c) -> Matrix a -> Matrix b -> Either AlgErr (Matrix c)
mConvolveE _ _ Null _ = Right Null
mConvolveE _ _ _ Null = Right Null
mConvolveE f g m n = do
(rm,cm) <- mDim m
(rn,cn) <- mDim n
if cm /= rn
then Left (DimMismatch $ show (rm,cm) ++ show (rn,cn))
else do
let foo (i,j) = do
as <- i `mListRowOf` m
bs <- j `mListColOf` n
let d = zipWithM f as bs >>= foldM1 g
case d of
Left err -> Left (MatCoefErr $ show err)
Right x -> return x
mFromMapM (rm,cn) foo
{------------}
{- :Ringoid -}
{------------}
instance (Ringoid t) => Ringoid (Matrix t) where
rAdd m1 m2 = case mCombineE rAdd m1 m2 of
Left _ -> error "rAdd Matrix definition"
Right x -> Right x
rMul m1 m2 = case mConvolveE rMul rAdd m1 m2 of
Left _ -> error "rMul Matrix definition"
Right x -> Right x
rNeg m = fmap rNeg m
rZero = Null
rIsZero m = mAll rIsZero m
rNeutOf = mSeq . fmap rNeutOf
rLAnnOf Null = return Null
rLAnnOf m = do
a <- (1,1) `mEntryOf` m
z <- rLAnnOf a
r <- mNumRows m
mConst (r,r) z
rRAnnOf Null = return Null
rRAnnOf m = do
a <- (1,1) `mEntryOf` m
z <- rRAnnOf a
c <- mNumCols m
mConst (c,c) z
mZerosAboveIndex :: (Ringoid a) => Matrix a -> Index -> Either AlgErr Bool
mZerosAboveIndex m (h,k) = do
ts <- sequence $ map (\i -> (i,k) `mEntryOf` m) [1..h-1]
return (and $ map rIsZero ts)
mScaleRow :: (Ringoid a, CRingoid a)
=> a -> Integer -> Matrix a -> Either AlgErr (Matrix a)
mScaleRow _ _ Null = Right Null
mScaleRow c h m = do
dm <- mDim m
let foo (i,j)
| i==h = do
a <- (i,j) `mEntryOf` m
case c `rMul` a of
Left err -> Left (MatCoefErr $ show err)
Right x -> return x
| otherwise = (i,j) `mEntryOf` m
mFromMapM dm foo
mScaleRowT :: (Ringoid a, CRingoid a)
=> a -> a -> Integer -> Matrix a -> Either AlgErr (Matrix a)
mScaleRowT _ = mScaleRow
mScaleCol :: (Ringoid a, CRingoid a)
=> a -> Integer -> Matrix a -> Either AlgErr (Matrix a)
mScaleCol _ _ Null = Right Null
mScaleCol c h m = do
dm <- mDim m
let foo (i,j)
| j==h = do
a <- (i,j) `mEntryOf` m
case c `rMul` a of
Left err -> Left (MatCoefErr $ show err)
Right x -> return x
| otherwise = (i,j) `mEntryOf` m
mFromMapM dm foo
mScaleColT :: (Ringoid a, CRingoid a)
=> a -> a -> Integer -> Matrix a -> Either AlgErr (Matrix a)
mScaleColT _ = mScaleCol
mAddRow :: (Ringoid a, CRingoid a)
=> a -> Integer -> Integer -> Matrix a -> Either AlgErr (Matrix a)
mAddRow _ _ _ Null = Right Null
mAddRow c h1 h2 m = do
dm <- mDim m
let foo (i,j)
| i==h2 = do
a1 <- (h1,j) `mEntryOf` m
a2 <- (h2,j) `mEntryOf` m
case opM2 rAdd (return a2) (rMul c a1) of
Left err -> Left (MatCoefErr $ show err)
Right x -> return x
| otherwise = (i,j) `mEntryOf` m
mFromMapM dm foo
mAddCol :: (Ringoid a, CRingoid a)
=> a -> Integer -> Integer -> Matrix a -> Either AlgErr (Matrix a)
mAddCol _ _ _ Null = Right Null
mAddCol c h1 h2 m = do
dm <- mDim m
let foo (i,j)
| j==h2 = do
a1 <- (i,h1) `mEntryOf` m
a2 <- (i,h2) `mEntryOf` m
case opM2 rAdd (return a2) (rMul c a1) of
Left err -> Left (MatCoefErr $ show err)
Right x -> return x
| otherwise = (i,j) `mEntryOf` m
mFromMapM dm foo
-- Find minimal k such that i,k entry is not zero for some i.
-- I.e. index of the leftmost nonzero column.
mFirstNonZeroColIndex :: (Ringoid a) => Matrix a -> Either AlgErr Integer
mFirstNonZeroColIndex Null = Left (NullMatrix "mFirstNonZeroColIndex")
mFirstNonZeroColIndex m = do
cs <- mColsOf m >>= return . map (rIsZero)
case findIndex (== False) cs of
Nothing -> Left ZeroMatrix
Just k -> Right $ fromIntegral (k+1)
-- Find minimal k such that k,j entry is not zero for some j.
-- I.e. index of the topmost nonzero row
mFirstNonZeroRowIndex :: (Ringoid a) => Matrix a -> Either AlgErr Integer
mFirstNonZeroRowIndex Null = Left (NullMatrix "mFirstNonZeroRowIndex")
mFirstNonZeroRowIndex m = do
cs <- mRowsOf m >>= return . map (rIsZero)
case findIndex (== False) cs of
Nothing -> Left ZeroMatrix
Just k -> Right $ fromIntegral (k+1)
instance (Ringoid t) => DagRingoid (Matrix t) where
rDag m = case mTranspose m of
Right n -> n
_ -> error "DagRingoid Matrix instance"
instance (Ringoid t) => BipRingoid (Matrix t) where
rBipIn x y = case mVCat x y of
Left _ -> error "rBipIn Matrix definition"
Right m -> Right m
rBipOut x y = case mHCat x y of
Left _ -> error "rBipOut Matrix definition"
Right m -> Right m
{-------------}
{- :URingoid -}
{-------------}
mEId :: (Ringoid a, URingoid a) => Integer -> Either AlgErr (Matrix a)
mEId n = do
let foo (i,j) = if i==j then rOne else rZero
(n,n) `mFromMap` foo
mEIdT :: (Ringoid a, URingoid a) => a -> Integer -> Either AlgErr (Matrix a)
mEIdT _ = mEId
-- Swap rows/cols
mESwap :: (Ringoid a, URingoid a)
=> Integer -> Integer -> Integer -> Either AlgErr (Matrix a)
mESwap n h k = do
let foo (i,j)
| (i,j) == (h,k) || (i,j) == (k,h) = rOne
| i == j && i /= h && i /= k = rOne
| otherwise = rZero
(n,n) `mFromMap` foo
mESwapT :: (Ringoid a, URingoid a)
=> a -> Integer -> Integer -> Integer -> Either AlgErr (Matrix a)
mESwapT _ = mESwap
-- Multiply row/col by a scalar
mEScale :: (Ringoid a, URingoid a)
=> Integer -> Integer -> a -> Either AlgErr (Matrix a)
mEScale n k a = do
let foo (i,j)
| i == k && k == j = a
| i == j && i /= k = rOne
| otherwise = rZero
(n,n) `mFromMap` foo
mEScaleT :: (Ringoid a, URingoid a)
=> a -> Integer -> Integer -> a -> Either AlgErr (Matrix a)
mEScaleT _ = mEScale
-- Add scalar multiple of one row/col to another
mEAdd :: (Ringoid a, URingoid a)
=> Integer -> Index -> a -> Either AlgErr (Matrix a)
mEAdd n (h,k) a = do
let foo (i,j)
| (i,j) == (h,k) = a
| i == j = rOne
| otherwise = rZero
(n,n) `mFromMap` foo
mEAddT :: (Ringoid a, URingoid a)
=> a -> Integer -> Integer -> Integer -> a -> Either AlgErr (Matrix a)
mEAddT _ n i j r = mEAdd n (i,j) r
{----------------}
{- :GaussJordan -}
{----------------}
-- Detecting GJ Form
gjLeftmostNonzeroIndices :: (Ringoid a)
=> Matrix a -> Either AlgErr [(Integer, Integer)]
gjLeftmostNonzeroIndices Null = return []
gjLeftmostNonzeroIndices m = do
rs <- mRowsOf m
sequence $ filter isRight $ map sndSeq $ zip [1..] (map mFirstNonZeroColIndex rs)
gjLeftmostNonzeroIndicesAscending :: (Ringoid a)
=> Matrix a -> Either AlgErr Bool
gjLeftmostNonzeroIndicesAscending m = do
ks <- gjLeftmostNonzeroIndices m
let is = map fst ks
let js = map snd ks
let
isAscending [] = True
isAscending [_] = True
isAscending (x:y:xs) = if x >= y then False else isAscending (y:xs)
return $ (is `isPrefixOf` [1..]) && (isAscending js)
gjLeftmostNonzeroEntriesAreOne :: (Ringoid a, URingoid a)
=> Matrix a -> Either AlgErr Bool
gjLeftmostNonzeroEntriesAreOne m = do
ks <- gjLeftmostNonzeroIndices m
ts <- sequence $ map (`mEntryOf` m) ks
return (and $ map rIsOne ts)
gjEntriesAboveLeftmostNonzerosAreZero :: (Ringoid a)
=> Matrix a -> Either AlgErr Bool
gjEntriesAboveLeftmostNonzerosAreZero m = do
ks <- gjLeftmostNonzeroIndices m
ps <- sequence $ map (mZerosAboveIndex m) ks
return (and ps)
mIsGaussJordanForm :: (Ringoid a, URingoid a)
=> Matrix a -> Either AlgErr Bool
mIsGaussJordanForm m = do
p <- gjLeftmostNonzeroIndicesAscending m
q <- gjLeftmostNonzeroEntriesAreOne m
r <- gjEntriesAboveLeftmostNonzerosAreZero m
return (p && q && r)
-- Elementary Row/Column Operations
data ElemOp a
= RowSwap Integer Integer
| RowScale Integer a
| RowAdd Integer Integer a
| ColSwap Integer Integer
| ColScale Integer a
| ColAdd Integer Integer a
| NoOp
deriving (Eq, Show)
ePrependRow :: ElemOp a -> ElemOp a
ePrependRow (RowSwap h k) = RowSwap (h+1) (k+1)
ePrependRow (RowScale h a) = RowScale (h+1) a
ePrependRow (RowAdd h k a) = RowAdd (h+1) (k+1) a
ePrependRow x = x
ePrependRows :: [ElemOp a] -> [ElemOp a]
ePrependRows = map ePrependRow
eOpMatrix :: (Ringoid a, URingoid a)
=> Integer -> ElemOp a -> Either AlgErr (Matrix a)
eOpMatrix n (RowSwap h k ) = mESwap n h k
eOpMatrix n (RowScale k a ) = mEScale n k a
eOpMatrix n (RowAdd h k a) = mEAdd n (k,h) a
eOpMatrix n (ColSwap h k ) = mESwap n h k
eOpMatrix n (ColScale k a ) = mEScale n k a
eOpMatrix n (ColAdd h k a) = mEAdd n (h,k) a
eOpMatrix n NoOp = mEId n
ePerformOp :: (Ringoid a, CRingoid a)
=> Matrix a -> ElemOp a -> Either AlgErr (Matrix a)
ePerformOp m (RowSwap h k) = mSwapRows h k m
ePerformOp m (RowScale h c) = mScaleRow c h m
ePerformOp m (RowAdd h k c) = mAddRow c h k m
ePerformOp m (ColSwap h k) = mSwapCols h k m
ePerformOp m (ColScale h c) = mScaleCol c h m
ePerformOp m (ColAdd h k c) = mAddCol c h k m
ePerformOp m NoOp = return m
ePerformOps :: (Ringoid a, CRingoid a)
=> Matrix a -> [ElemOp a] -> Either AlgErr (Matrix a)
ePerformOps = foldM ePerformOp
-- GJ Factorization
-- m = [z|n] where first column of n is not zero.
gjSplitLeftZero :: (Ringoid a)
=> Matrix a -> Either AlgErr (Matrix a, Matrix a)
gjSplitLeftZero m = do
j <- mFirstNonZeroColIndex m
m `mHSplit` j
-- If m -> (n, ops), then after performing ops on m, we get n, and the (1,1) entry of n is 1.
gjMoveFirstPivot :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Either AlgErr (Matrix a, [ElemOp a])
gjMoveFirstPivot m = do
i <- (1 `mColOf` m) >>= mFirstNonZeroRowIndex
b <- ((i,1) `mEntryOf` m) >>= rInv
let ops = [RowScale i b, RowSwap i 1]
n <- ePerformOps m ops
return (n, ops)
gjClearEntryWithPivot :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Index -> Integer -> Either AlgErr (ElemOp a)
gjClearEntryWithPivot m (i,j) k = do
t <- (k,j) `mEntryOf` m
if rIsZero t
then return NoOp
else do
v <- (i,j) `mEntryOf` m >>= rInv
w <- rMul (rNeg t) v
return (RowAdd i k w)
gjClearFirstColumn :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Either AlgErr (Matrix a, [ElemOp a])
gjClearFirstColumn m = do
cs <- 1 `mListColOf` m
case cs of
[] -> Left (NullMatrix "gjClearFirstColumn")
[_] -> return (m, [])
(_:_) -> do
r <- mNumRows m
ops <- sequence $ map (gjClearEntryWithPivot m (1,1)) [2..r]
n <- ePerformOps m ops
return (n, ops)
-- If rowEchelon m = Right (ops, n, is)
-- then n is (a) row echelon form of m, with pivots is,
-- and is row-equivalent to m via the row operations ops.
gjRowEchelon :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Either AlgErr (Matrix a, [ElemOp a], [Index])
gjRowEchelon Null = Left (NullMatrix "gjRowEchelon")
gjRowEchelon m = do
if rIsZero m
then return (m, [NoOp], [])
else do
q <- mIsRow m
if q
then do
j <- mFirstNonZeroColIndex m
b <- (1,j) `mEntryOf` m >>= rInv
n <- mScaleRow b 1 m
return (n, [RowScale 1 b], [(1,j)])
else do
(z,w1) <- gjSplitLeftZero m
j <- case z of
Null -> return 0
_ -> mNumCols z
(w2, movePivot) <- gjMoveFirstPivot w1
(w3, clearColumn) <- gjClearFirstColumn w2
r <- mIsCol w3
if r
then do
n <- z `mHCat` w3
return (n, movePivot ++ clearColumn, [(1,j+1)])
else do
((t1,t2),(t3,t4)) <- mQSplit w3 (2,2)
(u4, recurse, piv) <- gjRowEchelon t4
w4 <- mQCat ((t1,t2),(t3,u4))
n <- z `mHCat` w4
let shiftPivots = map (\(h,k) -> (h+1,k+j+1)) piv
return (n, movePivot ++ clearColumn ++ ePrependRows recurse, (1,j+1):shiftPivots)
gjREForm :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Either AlgErr (Matrix a)
gjREForm m = do
(n,_,_) <- gjRowEchelon m
return n
gjREFactor :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Either AlgErr (Matrix a)
gjREFactor m = do
r <- mNumRows m
(_,ops,_) <- gjRowEchelon m
ps <- sequence $ map (eOpMatrix r) ops
rProd ps
gjPivots :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Either AlgErr [Index]
gjPivots m = do
(_,_,ps) <- gjRowEchelon m
return ps
mPivotCols :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Either AlgErr [Integer]
mPivotCols m = do
ps <- gjPivots m
return $ map getColIdx ps
mRank :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Either AlgErr Integer
mRank m = do
ps <- gjPivots m
return (sum $ map (const 1) ps)
mClearAbovePivot :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Index -> Either AlgErr (Matrix a, [ElemOp a])
mClearAbovePivot m (i,j) = do
ops <- sequence $ map (gjClearEntryWithPivot m (i,j)) [1..i-1]
n <- ePerformOps m ops
return (n, ops)
mClearAbovePivots :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> [Index] -> Either AlgErr (Matrix a, [ElemOp a])
mClearAbovePivots m [] = return (m,[])
mClearAbovePivots m (p:ps) = do
(n,xs) <- mClearAbovePivot m p
(q,ys) <- mClearAbovePivots n ps
return (q, xs ++ ys)
mGaussJordan :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Either AlgErr (Matrix a, [ElemOp a], [Index])
mGaussJordan m = do
(n, ops, ps) <- gjRowEchelon m
(q, ups) <- mClearAbovePivots n ps
return (q, ops ++ ups, ps)
mGJForm :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Either AlgErr (Matrix a)
mGJForm m = do
(n,_,_) <- mGaussJordan m
return n
mGJFormT :: (Ringoid a, CRingoid a, URingoid a)
=> a -> Matrix a -> Either AlgErr (Matrix a)
mGJFormT _ = mGJForm
mGJFactor :: (Ringoid a, CRingoid a, URingoid a)
=> Matrix a -> Either AlgErr (Matrix a)
mGJFactor m = do
r <- mNumRows m
(_,ops,_) <- mGaussJordan m
ps <- sequence $ map (eOpMatrix r) ops
rProd $ reverse ps
mGJFactorT :: (Ringoid a, CRingoid a, URingoid a)
=> a -> Matrix a -> Either AlgErr (Matrix a)
mGJFactorT _ = mGJFactor
instance (LaTeX a) => LaTeX (Matrix a) where
latex m = "\\begin{bmatrix}\n " ++ foo ++ "\n\\end{bmatrix}"
where
foo = concat $ intersperse " \\\\\n " $ map (concat . intersperse " & " . map latex) $ mToRowList m
|
nbloomf/carl
|
src/Carl/Struct/Matrix.hs
|
gpl-3.0
| 29,447
| 0
| 24
| 8,046
| 13,190
| 6,728
| 6,462
| 755
| 5
|
module Main (main) where
import Parser
import ParserTypes
import System.Glib.UTFString
import Test.Hspec
main :: IO ()
main = hspec $ do
describe "primitive parser" $ do
it "parses the empty string" $ do
parsePrim "" `shouldBe` []
it "parses a normal string" $ do
parsePrim "abcde" `shouldBe` [PrimText "abcde"]
it "recognizes a control sequence" $ do
parsePrim "\x1b[0;m" `shouldBe` [PrimControlSeq "[0;m"]
it "recognizes both together" $ do
parsePrim "abc\x1b[0;m" `shouldBe` [ PrimText "abc"
, PrimControlSeq "[0;m" ]
it "strips cr" $ do
parsePrim "\r\n" `shouldBe` [PrimText "\n"]
it "strips cr with other things" $ do
parsePrim "abc\r\ndef" `shouldBe` [PrimText "abc\ndef"]
-- TODO: OSC tests on processPrim
describe "OSC parser" $ do
it "rejects the empty string" $ do
mkOSCmd "" `shouldBe` []
it "supports code 1" $ do
mkOSCmd "1;hello world" `shouldBe` [WindowTitle "hello world"]
-- it "supports \\a terminator" $ do
-- mkOSCmd "1;hello world;" `shouldBe` [WindowTitle "hello world"]
it "supports code 2" $ do
mkOSCmd "2;hello world" `shouldBe` [IconName "hello world"]
it "supports code 0" $ do
mkOSCmd "0;hi" `shouldBe` [IconName "hi", WindowTitle "hi"]
describe "parser" $ do
it "parses empty" $ do
parse "" `shouldBe` []
it "parses a normal string" $ do
parse "abcde" `shouldBe` [Text "abcde"]
it "recognizes a control sequence" $ do
parse "\x1b[0m" `shouldBe` [SGR [Reset]]
it "recognizes both together" $ do
parse "abc\x1b[0m" `shouldBe` [ Text "abc"
, SGR [Reset] ]
it "recognizes color settings" $ do
parse "\x1b[30;41m" `shouldBe` [SGR [ Set (Black, Foreground)
, Set (Red, Background) ]]
it "recognizes other settings" $ do
parse "\x1b[1J" `shouldBe` [ CSI 'J' ["1"] ]
it "works on real output" $ do
parse "\x1b[0m\x1b[01;34m.git\x1b[0m\r\ndrwxr-xr-x" `shouldBe`
[ SGR [Reset], SGR [Bold, Set (Blue, Foreground) ]
, Text ".git", SGR [Reset], Text "\ndrwxr-xr-x"]
it "strips CR" $ do
parse "\r\n" `shouldBe` [Text "\n"]
it "works on real output with colors" $ do
parse "\x1b[01;34m.\x1b[0m\r\ndrwxr-xr-x" `shouldBe` [
SGR [ Bold
, Set (Blue, Foreground) ]
, Text "."
, SGR [Reset]
, Text "\ndrwxr-xr-x" ]
describe "control seq" $ do
it "makes a CSI" $ do
mkControlSeq 'J' ["1"] `shouldBe` Just (CSI 'J' ["1"])
describe "SGR" $ do
it "makes reset" $ do
mkColorCmd "0" `shouldBe` Just Reset
it "makes bg and fg" $ do
mkColorCmd "30" `shouldBe` Just (Set (Black, Foreground))
it "goes to string property" $ do
colorForGtk Blue `shouldBe` "blue"
|
pscollins/Termonoid
|
test/Main.hs
|
gpl-3.0
| 2,901
| 0
| 19
| 828
| 877
| 425
| 452
| 68
| 1
|
{-
Copyright (C) 2014 Esteban I. Ruiz Moreno (EXio4)
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/>
-}
module Coloring (
Pal,
palette,
dark
) where
import Graphics.UI.SDL
type Pal = [(Int,Color)]
palette :: Pal
palette =
[(1, red)
,(2, blue)
,(3, purple)
,(4, green)
,(5, yellow)]
red :: Color
blue :: Color
purple :: Color
green :: Color
yellow :: Color
red = Color 255 0 0 0
blue = Color 0 0 255 0
purple = Color 255 0 255 0
green = Color 0 255 0 0
yellow = Color 255 255 0 0
dark :: Color -> Color
dark (Color a b c _) = Color (op a) (op b) (op c) 0
where op x = (x `div` 5) * 2
|
EXio4/zyflex
|
src/Coloring.hs
|
gpl-3.0
| 1,250
| 0
| 9
| 325
| 266
| 152
| 114
| 26
| 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.Compute.InterconnectAttachments.AggregatedList
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves an aggregated list of interconnect attachments.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.interconnectAttachments.aggregatedList@.
module Network.Google.Resource.Compute.InterconnectAttachments.AggregatedList
(
-- * REST Resource
InterconnectAttachmentsAggregatedListResource
-- * Creating a Request
, interconnectAttachmentsAggregatedList
, InterconnectAttachmentsAggregatedList
-- * Request Lenses
, iaalIncludeAllScopes
, iaalReturnPartialSuccess
, iaalOrderBy
, iaalProject
, iaalFilter
, iaalPageToken
, iaalMaxResults
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.interconnectAttachments.aggregatedList@ method which the
-- 'InterconnectAttachmentsAggregatedList' request conforms to.
type InterconnectAttachmentsAggregatedListResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"aggregated" :>
"interconnectAttachments" :>
QueryParam "includeAllScopes" Bool :>
QueryParam "returnPartialSuccess" Bool :>
QueryParam "orderBy" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] InterconnectAttachmentAggregatedList
-- | Retrieves an aggregated list of interconnect attachments.
--
-- /See:/ 'interconnectAttachmentsAggregatedList' smart constructor.
data InterconnectAttachmentsAggregatedList =
InterconnectAttachmentsAggregatedList'
{ _iaalIncludeAllScopes :: !(Maybe Bool)
, _iaalReturnPartialSuccess :: !(Maybe Bool)
, _iaalOrderBy :: !(Maybe Text)
, _iaalProject :: !Text
, _iaalFilter :: !(Maybe Text)
, _iaalPageToken :: !(Maybe Text)
, _iaalMaxResults :: !(Textual Word32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InterconnectAttachmentsAggregatedList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'iaalIncludeAllScopes'
--
-- * 'iaalReturnPartialSuccess'
--
-- * 'iaalOrderBy'
--
-- * 'iaalProject'
--
-- * 'iaalFilter'
--
-- * 'iaalPageToken'
--
-- * 'iaalMaxResults'
interconnectAttachmentsAggregatedList
:: Text -- ^ 'iaalProject'
-> InterconnectAttachmentsAggregatedList
interconnectAttachmentsAggregatedList pIaalProject_ =
InterconnectAttachmentsAggregatedList'
{ _iaalIncludeAllScopes = Nothing
, _iaalReturnPartialSuccess = Nothing
, _iaalOrderBy = Nothing
, _iaalProject = pIaalProject_
, _iaalFilter = Nothing
, _iaalPageToken = Nothing
, _iaalMaxResults = 500
}
-- | Indicates whether every visible scope for each scope type (zone, region,
-- global) should be included in the response. For new resource types added
-- after this field, the flag has no effect as new resource types will
-- always include every visible scope for each scope type in response. For
-- resource types which predate this field, if this flag is omitted or
-- false, only scopes of the scope types where the resource type is
-- expected to be found will be included.
iaalIncludeAllScopes :: Lens' InterconnectAttachmentsAggregatedList (Maybe Bool)
iaalIncludeAllScopes
= lens _iaalIncludeAllScopes
(\ s a -> s{_iaalIncludeAllScopes = a})
-- | Opt-in for partial success behavior which provides partial results in
-- case of failure. The default value is false.
iaalReturnPartialSuccess :: Lens' InterconnectAttachmentsAggregatedList (Maybe Bool)
iaalReturnPartialSuccess
= lens _iaalReturnPartialSuccess
(\ s a -> s{_iaalReturnPartialSuccess = a})
-- | Sorts list results by a certain order. By default, results are returned
-- in alphanumerical order based on the resource name. You can also sort
-- results in descending order based on the creation timestamp using
-- \`orderBy=\"creationTimestamp desc\"\`. This sorts results based on the
-- \`creationTimestamp\` field in reverse chronological order (newest
-- result first). Use this to sort resources like operations so that the
-- newest operation is returned first. Currently, only sorting by \`name\`
-- or \`creationTimestamp desc\` is supported.
iaalOrderBy :: Lens' InterconnectAttachmentsAggregatedList (Maybe Text)
iaalOrderBy
= lens _iaalOrderBy (\ s a -> s{_iaalOrderBy = a})
-- | Project ID for this request.
iaalProject :: Lens' InterconnectAttachmentsAggregatedList Text
iaalProject
= lens _iaalProject (\ s a -> s{_iaalProject = a})
-- | A filter expression that filters resources listed in the response. The
-- expression must specify the field name, a comparison operator, and the
-- value that you want to use for filtering. The value must be a string, a
-- number, or a boolean. The comparison operator must be either \`=\`,
-- \`!=\`, \`>\`, or \`\<\`. For example, if you are filtering Compute
-- Engine instances, you can exclude instances named \`example-instance\`
-- by specifying \`name != example-instance\`. You can also filter nested
-- fields. For example, you could specify \`scheduling.automaticRestart =
-- false\` to include instances only if they are not scheduled for
-- automatic restarts. You can use filtering on nested fields to filter
-- based on resource labels. To filter on multiple expressions, provide
-- each separate expression within parentheses. For example: \`\`\`
-- (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\")
-- \`\`\` By default, each expression is an \`AND\` expression. However,
-- you can include \`AND\` and \`OR\` expressions explicitly. For example:
-- \`\`\` (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel
-- Broadwell\") AND (scheduling.automaticRestart = true) \`\`\`
iaalFilter :: Lens' InterconnectAttachmentsAggregatedList (Maybe Text)
iaalFilter
= lens _iaalFilter (\ s a -> s{_iaalFilter = a})
-- | Specifies a page token to use. Set \`pageToken\` to the
-- \`nextPageToken\` returned by a previous list request to get the next
-- page of results.
iaalPageToken :: Lens' InterconnectAttachmentsAggregatedList (Maybe Text)
iaalPageToken
= lens _iaalPageToken
(\ s a -> s{_iaalPageToken = a})
-- | The maximum number of results per page that should be returned. If the
-- number of available results is larger than \`maxResults\`, Compute
-- Engine returns a \`nextPageToken\` that can be used to get the next page
-- of results in subsequent list requests. Acceptable values are \`0\` to
-- \`500\`, inclusive. (Default: \`500\`)
iaalMaxResults :: Lens' InterconnectAttachmentsAggregatedList Word32
iaalMaxResults
= lens _iaalMaxResults
(\ s a -> s{_iaalMaxResults = a})
. _Coerce
instance GoogleRequest
InterconnectAttachmentsAggregatedList
where
type Rs InterconnectAttachmentsAggregatedList =
InterconnectAttachmentAggregatedList
type Scopes InterconnectAttachmentsAggregatedList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient
InterconnectAttachmentsAggregatedList'{..}
= go _iaalProject _iaalIncludeAllScopes
_iaalReturnPartialSuccess
_iaalOrderBy
_iaalFilter
_iaalPageToken
(Just _iaalMaxResults)
(Just AltJSON)
computeService
where go
= buildClient
(Proxy ::
Proxy InterconnectAttachmentsAggregatedListResource)
mempty
|
brendanhay/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/InterconnectAttachments/AggregatedList.hs
|
mpl-2.0
| 8,753
| 0
| 20
| 1,818
| 842
| 503
| 339
| 126
| 1
|
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE CPP #-}
module Gonimo.Server where
import Control.Exception (AsyncException, SomeException,
asyncExceptionFromException,
fromException, throw)
import Control.Monad ((<=<))
import Control.Monad.Except (ExceptT (..))
import Control.Monad.Freer (Eff)
import Control.Monad.Freer.Exception (catchError, throwError)
import Control.Monad.Freer.Reader (runReader)
import Data.Aeson (encode)
import Data.Bifunctor (first)
import Data.Monoid
import qualified Data.Text as T
import Database.Persist (Entity (..), (==.))
import qualified Gonimo.Database.Effects as Db
import Gonimo.Database.Effects.Servant
import Gonimo.Server.Auth
import Gonimo.Server.AuthHandlers
import Gonimo.Server.DbEntities
import Gonimo.Server.Effects hiding (Server)
import Gonimo.Server.Error (ServantException (..), throwServant, ServerError (..))
#ifdef DEVELOPMENT
import Gonimo.Server.Effects.Development
#else
import Gonimo.Server.Effects.Production
#endif
import Gonimo.Server.Handlers
import Gonimo.Server.Types
import Gonimo.WebAPI
import Servant ((:<|>) (..), (:~>) (..),
ServantErr (..), Server, ServerT,
enter, err500)
import Servant.Server (err400, err401)
effServer :: ServerT GonimoAPI ServerEffects
effServer = createClient
:<|> getAuthServer
:<|> createFunnyName
:<|> getCoffee
authServer :: ServerT AuthGonimoAPI AuthServerEffects
authServer = createInvitation
:<|> answerInvitation
:<|> sendInvitation
:<|> putInvitationInfo
:<|> createFamily
:<|> createChannel
:<|> receiveSocket
:<|> putChannel
:<|> receiveChannel
-- Let's serve
getServer :: Config -> Server GonimoAPI
getServer c = enter (effToServant c) effServer
getAuthServer :: Maybe AuthToken -> ServerT AuthGonimoAPI ServerEffects
getAuthServer s = enter (authToEff s) authServer
----------------------- Natural transformations -------------------------
authToEff' :: Maybe AuthToken -> AuthServerEffects a -> ServerEffects a
authToEff' Nothing _ = throwServant err401 { -- Not standard conform, but I don't care for now.
errReasonPhrase = "You need to provide an AuthToken!"
}
authToEff' (Just s) m = do
authData <- runDb $ do
client@(Entity _ Client{..}) <- getByAuthErr $ AuthTokenClient s
account <- getAuthErr clientAccountId
fids <- map (familyAccountFamilyId . entityVal)
<$> Db.selectList [FamilyAccountAccountId ==. clientAccountId] []
return $ AuthData (Entity clientAccountId account) fids client
runReader m authData
where
invalidAuthErr = err400 { errReasonPhrase = "The provided AuthToken is not valid!"
, errBody = encode InvalidAuthToken
}
getByAuthErr = servantErrOnNothing invalidAuthErr <=< Db.getBy
getAuthErr = servantErrOnNothing invalidAuthErr <=< Db.get
authToEff :: Maybe AuthToken -> AuthServerEffects :~> ServerEffects
authToEff token = Nat $ authToEff' token
-------
effToServant' :: Config -> ServerEffects a -> ExceptT ServantErr IO a
effToServant' c = ExceptT . fmap (first exceptionToServantErr) . runExceptionServer c . handleExceptions
effToServant :: Config -> ServerEffects :~> ExceptT ServantErr IO
effToServant c = Nat $ effToServant' c
-------------------------------------------------------------------------
---------------------- Exception handling -------------------------------
handleExceptions :: ServerConstraint r => Eff r a -> Eff r a
handleExceptions action = catchError action $ \e ->
case asyncExceptionFromException e of
-- A more reliable technique for this would be: https://www.schoolofhaskell.com/user/snoyberg/general-haskell/exceptions/catching-all-exceptions .
Just (ae :: AsyncException) -> throw ae -- Async exceptions are bad - just quit.
_ -> do
$(logError) $ "Error: " <> T.pack (show e) -- For now, try to carry on for all other exceptions.
throwError e -- Simply throwing an err500 to the user and log the error.
exceptionToServantErr :: SomeException -> ServantErr
exceptionToServantErr se = case fromException se of
Just (ServantException err) -> err
Nothing -> err500
|
charringer/gonimo-back
|
src/Gonimo/Server.hs
|
agpl-3.0
| 4,855
| 0
| 16
| 1,358
| 956
| 526
| 430
| -1
| -1
|
module ConfigParse where
import qualified Data.ConfigFile as CP
import Data.Either.Utils (forceEither) -- provided by MissingH
data SnapshotLimitConfig = SnapshotLimitConfig
{ yearlyLimit :: !Int
, monthlyLimit :: !Int
, weeklyLimit :: !Int
, dailyLimit :: !Int
, hourlyLimit :: !Int
, quaterHourlyLimit :: !Int
} deriving (Show)
-- TODO get rid of forceEither here
getConfigParser :: String -> IO CP.ConfigParser
getConfigParser filepath = forceEither <$> CP.readfile CP.emptyCP filepath
getTimelineConfig :: CP.ConfigParser -> Either CP.CPError SnapshotLimitConfig
getTimelineConfig cp = do
keep_yearly <- CP.get cp "TIMELINE" "keep_yearly"
keep_monthly <- CP.get cp "TIMELINE" "keep_monthly"
keep_weekly <- CP.get cp "TIMELINE" "keep_weekly"
keep_daily <- CP.get cp "TIMELINE" "keep_daily"
keep_hourly <- CP.get cp "TIMELINE" "keep_hourly"
keep_quater_hourly <- CP.get cp "TIMELINE" "keep_quater_hourly"
return $ SnapshotLimitConfig keep_yearly keep_monthly keep_weekly
keep_daily keep_hourly keep_quater_hourly
|
vimalloc/apfs-auto-snapshot
|
src/ConfigParse.hs
|
agpl-3.0
| 1,184
| 0
| 9
| 292
| 260
| 132
| 128
| 35
| 1
|
{-# LANGUAGE TemplateHaskell #-}
import Data.Vector.DynamicTimeWarping
import Data.Vector.Unboxed (fromList)
import Test.QuickCheck
dist l r = distanceBy (\x y -> (x-y)^2) l r
prop_Reflexivity :: [Float] -> [Float] -> Bool
prop_Reflexivity l r =
let l' = fromList l
r' = fromList r
in abs (dist l' r' - dist r' l') <= 1e-10 ||
(dist l' r' == 1/0 && dist r' l' == 1/0)
prop_NonNegative :: [Float] -> [Float] -> Bool
prop_NonNegative l r =
let l' = fromList l
r' = fromList r
in dist l' r' >= 0
main = $quickCheckAll
|
zombiecalypse/DynamicTimeWarp
|
src/Test.hs
|
lgpl-3.0
| 547
| 0
| 14
| 126
| 244
| 124
| 120
| 17
| 1
|
module Foldr where
import CLaSH.Prelude
topEntity :: Vec 4 (Unsigned 8) -> (Unsigned 8)
topEntity = foldr div 1
testInput :: Signal (Vec 4 (Unsigned 8))
testInput = pure (24 :> 7 :> 4 :> 2 :> Nil)
expectedOutput :: Signal (Unsigned 8) -> Signal Bool
expectedOutput = outputVerifier (8 :> Nil)
|
ggreif/clash-compiler
|
tests/shouldwork/Vector/Foldr.hs
|
bsd-2-clause
| 297
| 0
| 10
| 56
| 130
| 67
| 63
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE LambdaCase #-}
import Control.Applicative ((<$>))
import Control.Monad (unless, forM_)
import System.FilePath (isAbsolute, (</>))
import System.Console.CmdArgs
-- import System.IO (hFlush, stdout)
import qualified Numeric.SGD.Momentum as SGD
import Data.String (fromString)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as L
-- import qualified Data.Text.Lazy.IO as L
import qualified Data.Text.Lazy.Encoding as L
import qualified Data.ByteString.Lazy as BL
import Data.Tagset.Positional (parseTagset)
import qualified Data.Tagset.Positional as P
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import qualified Dhall as Dhall
import qualified Data.DAG as DAG
import qualified Data.CRF.Chain1.Constrained.DAG.Dataset.Codec as CRF.Codec
import qualified Data.CRF.Chain1.Constrained.DAG.Train as CRF.Train
-- import Data.CRF.Chain1.Constrained.DAG.Train (Error(..))
import qualified NLP.Concraft.DAG.Guess as Guess
import qualified NLP.Concraft.DAG.Schema as Schema
-- import qualified NLP.Concraft.DAG.Disamb as Disamb
-- import qualified NLP.Concraft.DAG2 as C
-- import qualified NLP.Concraft.Polish.DAG2 as P
import qualified NLP.Concraft.DAGSeg as C
import qualified NLP.Concraft.DAG.Morphosyntax as X
import qualified NLP.Concraft.DAG.Morphosyntax.Accuracy as Acc
import qualified NLP.Concraft.DAG.Segmentation as Seg
import qualified NLP.Concraft.Polish.DAG.Morphosyntax as PX
import qualified NLP.Concraft.Polish.DAGSeg as Pol
import qualified NLP.Concraft.Polish.DAG.Format.Base as DB
import qualified NLP.Concraft.Polish.DAG.Server as Server
-- import qualified NLP.Concraft.Polish.Request as R
import Paths_concraft_pl (version, getDataFileName)
import Data.Version (showVersion)
---------------------------------------
-- Command line options
---------------------------------------
-- | A description of the Concraft-pl tool.
concraftDesc :: String
concraftDesc = "Concraft-pl " ++ showVersion version
data Concraft
= Train
{ trainPath :: FilePath
, evalPath :: Maybe FilePath
, tagsetPath :: Maybe FilePath
, iterNum :: Double
, batchSize :: Int
, regVar :: Double
, gain0 :: Double
, tau :: Double
, disk :: Bool
, outModel :: FilePath
, guessNum :: Int
, r0 :: Guess.R0T
, zeroProbLabel :: String
, visibleOnly :: Bool
-- , disambTiers :: Pol.DisambTiersCfg
, config :: FilePath
}
| Tag
{ inModel :: FilePath
-- , marginals :: Bool
, inFile :: Maybe FilePath
, outFile :: Maybe FilePath
, blackFile :: Maybe FilePath
, probType :: DB.ProbType
-- , suppressProbs :: Bool
, mayGuessNum :: Maybe Int
, freqPath :: Maybe FilePath
, freqSmoothing :: Double
, shortestPath :: Bool
, longestPath :: Bool
, numericDisamb :: Bool
}
| Server
{ inModel :: FilePath
, blackFile :: Maybe FilePath
, probType :: DB.ProbType
, mayGuessNum :: Maybe Int
, numericDisamb :: Bool
, port :: Int
}
| Client
{ serverAddr :: String
, port :: Int
, inFile :: Maybe FilePath
, outFile :: Maybe FilePath
, batchSize :: Int
}
| Eval
{ justTagsetPath :: FilePath
, goldPath :: FilePath
, taggPath :: FilePath
, onlyOov :: Bool
, onlyAmb :: Bool
, onlyEos :: Bool
, expandTags :: Bool
, ignoreTags :: Bool
, heedEos :: Bool
, weak :: Bool
-- , discardProb0 :: Bool
, verbose :: Bool
}
| Check
{ justTagsetPath :: FilePath
, dagPath :: FilePath
}
| Freqs
{ dagPath :: FilePath
-- , justTagsetPath :: FilePath
-- , outPath :: FilePath
}
| Ambi
{ dagPath :: FilePath
, onlyChosen :: Bool
}
deriving (Data, Typeable, Show)
trainMode :: Concraft
trainMode = Train
{ trainPath = def &= argPos 1 &= typ "TRAIN-FILE"
, evalPath = def &= typFile &= help "Evaluation file"
, tagsetPath = def &= typFile &= help "Tagset definition file"
, config = def &= typFile &= help "Global configuration file"
-- , discardHidden = False &= help "Discard hidden features"
, iterNum = 20 &= help "Number of SGD iterations"
, batchSize = 50 &= help
"Batch size (the number of dataset elements taken in a single SGD update)"
, regVar = 10.0 &=
help "Regularization variance (the higher variance, the higher penalty for large params)"
, gain0 = 0.25 &= help
"Initial gain parameter (gain is used to scale the gradient before parameter update)"
-- The value `0.25` makes sense given that SGD momentum is used
, tau = 5.0 &= help
"Initial tau parameter (after how many passes over the full dataset the gain is halved)"
, disk = False &= help "Store SGD dataset on disk"
, outModel = def &= typFile &= help "Output Model file"
, guessNum = 10 &= help "Number of guessed tags for each unknown word"
, r0 = Guess.OovChosen &= help "R0 construction method"
, zeroProbLabel = "xxx" &= help "Zero probability label"
, visibleOnly = False &= help "Extract only visible features for the guesser"
-- , disambTiers = Pol.TiersDefault &= help "Dismabiguation tiers configuration"
}
tagMode :: Concraft
tagMode = Tag
{ inModel = def &= argPos 0 &= typ "MODEL-FILE"
-- , noAna = False &= help "Do not analyse input text"
-- , marginals = False &= help "Tag with marginal probabilities" }
, inFile = def &= typFile &= help "Input file (stdin by default)"
, outFile = def &= typFile &= help "Output file (stdout by default)"
, blackFile = def &= typFile &= help "File with blacklisted tags, one per line"
, probType = DB.Marginals &= help "Type of probabilities"
-- , suppressProbs = False &= help "Do not show probabilities"
, freqPath = def &= typFile &= help "File with chosen/not-chosen counts"
, freqSmoothing = 1.0 &= help
"Smoothing parameter for frequency-based path selection"
, shortestPath = False &= help
"Select shortest paths prior to parsing (can serve as a segmentation baseline)"
, longestPath = False &= help
"Select longest paths prior to parsing (mutually exclusive with shortestPath)"
, mayGuessNum = def &= help "Number of guessed tags for each unknown word"
, numericDisamb = False &= help
"Print disamb markers as numerical values in the probability column"
}
serverMode :: Concraft
serverMode = Server
{ inModel = def &= argPos 0 &= typ "MODEL-FILE"
, blackFile = def &= typFile &= help "File with blacklisted tags, one per line"
, probType = DB.Marginals &= help "Type of probabilities"
, mayGuessNum = def &= help "Number of guessed tags for each unknown word"
, numericDisamb = False &= help
"Print disamb markers as numerical values in the probability column"
, port = 3000 &= help "Server port"
}
clientMode :: Concraft
clientMode = Client
{ serverAddr = "http://localhost" &= help "Server address"
, port = 3000 &= help "Server port number"
, inFile = def &= typFile &= help "Input file (stdin by default)"
, outFile = def &= typFile &= help "Output file (stdout by default)"
, batchSize = 10 &= help "Sent graphs in batches of the given size"
}
evalMode :: Concraft
evalMode = Eval
{ justTagsetPath = def &= typ "TAGSET-FILE" &= argPos 0
, goldPath = def &= typ "GOLD-FILE" &= argPos 1
, taggPath = def &= typ "TAGGED-FILE" &= argPos 2
, onlyOov = False &= help "Only OOV edges"
, onlyAmb = False &= help "Only segmentation-ambiguous edges"
, onlyEos = False &= help "Only EOS edges"
, expandTags = False &= help "Expand tags"
, ignoreTags = False &= help "Ignore tags (compute segmentation-level accurracy)"
, heedEos = False &= help "Pay attention to EOS markers (ignored by default)"
, weak = False &= help "Compute weak accuracy rather than strong"
-- , discardProb0 = False &= help "Discard sentences with near 0 probability"
, verbose = False &= help "Print information about compared elements"
}
checkMode :: Concraft
checkMode = Check
{ justTagsetPath = def &= typ "TAGSET-FILE" &= argPos 0
, dagPath= def &= typ "DAG-FILE" &= argPos 1
}
freqsMode :: Concraft
freqsMode = Freqs
{ dagPath = def &= typ "DAG-FILE" &= argPos 1
-- , justTagsetPath = def &= typ "TAGSET-FILE" &= argPos 0
-- , outPath = def &= typ "FREQ-FILE" &= help "Output file to store counts"
}
ambiMode :: Concraft
ambiMode = Ambi
{ dagPath = def &= typ "DAG-FILE" &= argPos 1
, onlyChosen = False &= help "Take only the chose tokens into account"
}
argModes :: Mode (CmdArgs Concraft)
argModes = cmdArgsMode $ modes
[ trainMode, tagMode, serverMode, clientMode
, evalMode, checkMode, freqsMode, ambiMode ]
&= summary concraftDesc
&= program "concraft-pl"
---------------------------------------
-- Main
---------------------------------------
main :: IO ()
main = exec =<< cmdArgsRun argModes
exec :: Concraft -> IO ()
exec Train{..} = do
tagsetPath' <- case tagsetPath of
Nothing -> getDataFileName "config/nkjp-tagset.cfg"
Just x -> return x
tagset <- parseTagset tagsetPath' <$> readFile tagsetPath'
-- Dhall configuration
let configPath =
if isAbsolute config
then config
else "./" </> config
dhall <- Dhall.detailed
(Dhall.input Dhall.auto $ fromString configPath)
-- let zeroProbLab = P.parseTag taset zeroProbLabel
let zeroProbLab = PX.Interp
{ PX.base = "none"
, PX.tag = T.pack zeroProbLabel
, PX.commonness = Nothing
, PX.qualifier = Nothing
, PX.metaInfo = Nothing
, PX.eos = False }
train0 = DB.parseData <$> readFileUtf8 trainPath
eval0 = case evalPath of
Nothing -> return []
Just ph -> DB.parseData <$> readFileUtf8 ph
-- putStrLn $ "\nRegularization variance: " ++ show regVar
concraft <- Pol.train (trainConf dhall tagset zeroProbLab) train0 eval0
unless (null outModel) $ do
putStrLn $ "\nSaving model in " ++ outModel ++ "..."
Pol.saveModel outModel concraft
where
sgdArgs = SGD.SgdArgs
{ SGD.batchSize = batchSize
, SGD.regVar = regVar
, SGD.iterNum = iterNum
, SGD.gain0 = gain0
, SGD.tau = tau
}
trainConf dhall tagset zeroLab = Pol.TrainConf
{ tagset = tagset
, sgdArgs = sgdArgs
-- , reana = not noAna
, onDisk = disk
, guessNum = guessNum
, r0 = r0
, zeroProbLabel = zeroLab
, guessOnlyVisible = visibleOnly
-- , disambTiersCfg = disambTiers
, globalConfig = dhall
}
exec Tag{..} = do
-- crf <- Pol.loadModel P.parseTag inModel
crf <- Pol.loadModel Pol.simplify4gsr Pol.complexify4gsr Pol.simplify4dmb inModel
-- inp <- DB.parseData <$> L.getContents
inp <- DB.parseData <$> case inFile of
Nothing -> getContentsUtf8
Just path -> readFileUtf8 path
blackSet <-
case blackFile of
Nothing -> pure S.empty
Just path -> readBlackSet path
pathSelection <-
case (shortestPath, longestPath, freqPath) of
(True, _, _) -> return $ Just Seg.Min
(_, True, _) -> return $ Just Seg.Max
(_, _, Just freqPath') -> do
freqMap <- loadFreqMap freqPath'
let conf = Seg.FreqConf
{ Seg.pickFreqMap = freqMap
, Seg.smoothingParam = freqSmoothing
}
return . Just $ Seg.Freq conf
_ -> return Nothing
let guessNum = case mayGuessNum of
Nothing -> C.guessNum crf
Just k -> k
cfg = Pol.AnnoConf
{ trimParam = guessNum
, pickPath = pathSelection
, blackSet = blackSet
}
out = Pol.annoAll cfg crf <$> inp
showCfg = DB.ShowCfg
-- { suppressProbs = suppressProbs
{ probType = probType
, numericDisamb = numericDisamb }
case outFile of
Nothing -> putStrUtf8 $ DB.showData showCfg out
Just path -> writeFileUtf8 path $ DB.showData showCfg out
exec Server{..} = do
crf <- Pol.loadModel Pol.simplify4gsr Pol.complexify4gsr Pol.simplify4dmb inModel
blackSet <-
case blackFile of
Nothing -> pure S.empty
Just path -> readBlackSet path
let guessNum = case mayGuessNum of
Nothing -> C.guessNum crf
Just k -> k
cfg = Pol.AnnoConf
{ trimParam = guessNum
, pickPath = Nothing
, blackSet = blackSet
}
showCfg = DB.ShowCfg
{ probType = probType
, numericDisamb = numericDisamb
}
serverCfg = Server.ServerCfg
{ concraft = crf
, annoCfg = cfg
, showCfg = showCfg
}
Server.runServer serverCfg port
exec Client{..} = do
-- clear the file, if specified (stdout otherwise)
case outFile of
Nothing -> return ()
Just path -> writeFileUtf8 path ""
inpAll <- case inFile of
Nothing -> getContentsUtf8
Just path -> readFileUtf8 path
let inputs
= map (L.intercalate "\n\n")
. group batchSize
$ filter
(not . L.null)
(L.splitOn "\n\n" inpAll)
forM_ (map L.toStrict inputs) $ \inp -> do
let req = Server.Request {dag = inp}
cfg = Server.ClientCfg {serverAddr=serverAddr, portNumber=port}
Server.sendRequest cfg req >>= \case
Nothing -> putStrLn "<< NO RESPONSE >>"
Just Server.Answer{..} -> case outFile of
Nothing -> putStrUtf8 (L.fromStrict dag)
Just path -> appendFileUtf8 path (L.fromStrict dag)
exec Eval{..} = do
tagset <- parseTagset justTagsetPath <$> readFile justTagsetPath
let simplify = fmap $ \seg ->
let simplify4eval interp =
( P.parseTag tagset $ PX.tag interp
, PX.eos interp && heedEos )
newTags = X.mapWMap simplify4eval (X.tags seg)
in seg {X.tags = newTags}
process = PX.packSent . simplify
fromFile = fmap (map process . DB.parseData) . readFileUtf8
putStrLn $ concat
[ "Note that in this evaluation lemmas "
, "are *not* taken into account."
]
let cfg = Acc.AccCfg
{ Acc.onlyOov = onlyOov
, Acc.onlyAmb = onlyAmb
, Acc.onlyMarkedWith =
if onlyEos
then S.singleton True
else S.empty
, Acc.accTagset = tagset
, Acc.expandTag = expandTags
, Acc.ignoreTag = ignoreTags
, Acc.weakAcc = weak
-- , Acc.discardProb0 = discardProb0
, Acc.verbose = verbose
}
stats <- Acc.collect cfg
<$> fromFile goldPath
<*> fromFile taggPath
putStr "Precision: " >> print (Acc.precision stats)
putStr "Recall: " >> print (Acc.recall stats)
putStr "Accuracy: " >> print (Acc.accuracy stats)
exec Check{..} = do
tagset <- parseTagset justTagsetPath <$> readFile justTagsetPath
dags <- DB.parseData <$> readFileUtf8 dagPath
forM_ dags $ \dag -> do
case verifyDAG tagset dag of
Nothing -> return ()
Just err -> do
putStrLn (show err)
showDAG dag
-- case err of
-- Malformed -> do
-- putStrLn "Incorrectly structured graph:"
-- showDAG dag
-- Cyclic -> do
-- putStrLn "Graph with cycles:"
-- showDAG dag
-- _ -> do
-- -- putStrLn "Another error:"
-- putStrLn (show err)
-- showDAG dag
--
-- if (not $ DAG.isOK dag) then do
-- putStrLn "Incorrectly structured graph:"
-- showDAG dag
-- else if (not $ DAG.isDAG dag) then do
-- putStrLn "Graph with cycles:"
-- showDAG dag
-- else case verifyProb tagset dag of
-- Nothing -> return ()
-- Just p -> do
-- putStr "Probability equal to "
-- putStr (show p)
-- putStrLn ":"
-- showDAG dag
where
showDAG dag =
forM_ (DAG.dagEdges dag) $ \edgeID -> do
let from = DAG.begsWith edgeID dag
to = DAG.endsWith edgeID dag
val = DAG.edgeLabel edgeID dag
putStr (show $ DAG.unNodeID from)
putStr ", "
putStr (show $ DAG.unNodeID to)
putStr " => "
T.putStrLn (PX.orth $ X.word val)
verifyDAG tagset dag =
let schema = Schema.fromConf Schema.nullConf
rawData = Guess.schemed (Pol.simplify4gsr tagset) schema [PX.packSent dag]
[encDag] = CRF.Codec.encodeDataL (CRF.Codec.mkCodec rawData) rawData
in CRF.Train.verifyDAG encDag
-- verifyProb tagset dag =
-- let schema = Schema.fromConf Schema.nullConf
-- rawData = Guess.schemed (Pol.simplify4gsr tagset) schema [PX.packSent dag]
-- [encDag] = CRF.Codec.encodeDataL (CRF.Codec.mkCodec rawData) rawData
-- p = CRF.Train.dagProb encDag
-- eps = 1e-9
-- in if p >= 1 - eps && p <= 1 + eps
-- then Nothing
-- else Just p
exec Freqs{..} = do
-- tagset <- parseTagset justTagsetPath <$> readFile justTagsetPath
dags <- DB.parseData <$> readFileUtf8 dagPath
let freqMap = Seg.computeFreqs $ map PX.packSent dags
printFreqMap freqMap
exec Ambi{..} = do
dags <- DB.parseData <$> readFileUtf8 dagPath
let stats = Seg.computeAmbiStats cfg $ map PX.packSent dags
print stats
where
cfg = Seg.AmbiCfg
{ Seg.onlyChosen = onlyChosen
}
---------------------------------------
-- Frequency map
---------------------------------------
printFreqMap
:: M.Map T.Text (Int, Int)
-> IO ()
printFreqMap freqMap =
forM_ (M.toList freqMap) $ \(orth, (chosen, notChosen)) -> do
T.putStr $ T.replace "\t" " " orth
T.putStr "\t"
putStr $ show chosen
T.putStr "\t"
putStrLn $ show notChosen
loadFreqMap
:: FilePath
-> IO (M.Map T.Text (Int, Int))
loadFreqMap filePath = do
M.fromList . map readPair . T.lines <$> T.readFile filePath
where
readPair line =
case T.splitOn "\t" line of
[orth, chosen, notChosen] ->
(orth, (readInt chosen, readInt notChosen))
_ -> error $ "loadFreqMap: line incorrectly formatted: " ++ T.unpack line
readInt = read . T.unpack
---------------------------------------
-- Blacklist
---------------------------------------
readBlackSet :: FilePath -> IO (S.Set T.Text)
readBlackSet path =
S.fromList . map (L.toStrict . L.strip) . L.lines <$> readFileUtf8 path
---------------------------------------
-- UTF8
---------------------------------------
readFileUtf8 :: FilePath -> IO L.Text
readFileUtf8 path = L.decodeUtf8 <$> BL.readFile path
writeFileUtf8 :: FilePath -> L.Text -> IO ()
writeFileUtf8 path = BL.writeFile path . L.encodeUtf8
appendFileUtf8 :: FilePath -> L.Text -> IO ()
appendFileUtf8 path = BL.appendFile path . L.encodeUtf8
getContentsUtf8 :: IO L.Text
getContentsUtf8 = L.decodeUtf8 <$> BL.getContents
putStrUtf8 :: L.Text -> IO ()
putStrUtf8 = BL.putStr . L.encodeUtf8
---------------------------------------
-- Utils
---------------------------------------
-- | Group the input list into the groups of X.
group :: Int -> [a] -> [[a]]
group n =
doit n []
where
doit k acc (x:xs)
| k > 0 =
doit (k-1) (x:acc) xs
| otherwise =
reverse acc : doit n [] (x:xs)
doit _ acc []
| null acc = []
| otherwise = [reverse acc]
-- ---------------------------------------
-- -- Reading files
-- ---------------------------------------
--
-- -- TODO: make everything work on DAG input/output.
--
-- parseFileO' :: Format -> Maybe FilePath -> IO [X.SentO X.Tag]
-- parseFileO' format path = case path of
-- Nothing -> return []
-- Just pt -> parseFileO format pt
--
--
-- parseFileO :: Format -> FilePath -> IO [X.SentO X.Tag]
-- parseFileO format path = parseParaO format <$> L.readFile path
--
--
-- parseFile :: Format -> FilePath -> IO [X.Sent X.Tag]
-- parseFile format path = parsePara format <$> L.readFile path
--
--
-- ---------------------------------------
-- -- Parsing text
-- ---------------------------------------
--
--
-- -- parseTextO :: Format -> L.Text -> [[X.SentO X.Tag]]
-- -- parseTextO format = map (map X.withOrig) . parseText format
--
--
-- parseParaO :: Format -> L.Text -> [X.SentO X.Tag]
-- parseParaO format = map X.withOrig . parsePara format
--
--
-- ---------------------------------------
-- -- Parsing (format dependent)
-- ---------------------------------------
--
--
-- parseText :: Format -> L.Text -> [[X.Sent X.Tag]]
-- parseText Plain = P.parsePlain
--
--
-- parsePara :: Format -> L.Text -> [X.Sent X.Tag]
-- parsePara Plain = P.parsePara
--
--
-- ---------------------------------------
-- -- Showing (format dependent)
-- ---------------------------------------
--
--
-- data ShowCfg = ShowCfg {
-- -- | The format used.
-- formatCfg :: Format
-- -- | Show weights?
-- , showWsCfg :: Bool }
--
--
-- showData :: ShowCfg -> [[X.Sent X.Tag]] -> L.Text
-- showData ShowCfg{..} = P.showPlain (P.ShowCfg {P.showWsCfg = showWsCfg})
|
kawu/concraft-pl
|
tools/concraft-pl.hs
|
bsd-2-clause
| 21,668
| 117
| 21
| 5,802
| 4,823
| 2,586
| 2,237
| 416
| 19
|
-- | Some auxiliary functions for property inference.
module Database.DSH.Backend.Sql.Opt.Properties.Auxiliary where
import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Set.Monad as S
import Database.Algebra.Table.Lang
(∪) :: Ord a => S.Set a -> S.Set a -> S.Set a
(∪) = S.union
(∩) :: Ord a => S.Set a -> S.Set a -> S.Set a
(∩) = S.intersection
(∖) :: Ord a => S.Set a -> S.Set a -> S.Set a
(∖) = S.difference
(∈) :: Ord a => a -> S.Set a -> Bool
(∈) = S.member
(⊆) :: Ord a => S.Set a -> S.Set a -> Bool
(⊆) = S.isSubsetOf
-- | Singleton set abbreviation
ss :: Ord a => a -> S.Set a
ss = S.singleton
-- | List set abbreviation
ls :: Ord a => [a] -> S.Set a
ls = S.fromList
unionss :: Ord a => S.Set (S.Set a) -> S.Set a
unionss = S.foldr (∪) S.empty
exprCols :: Expr -> S.Set Attr
exprCols (BinAppE _ e1 e2) = exprCols e1 ∪ exprCols e2
exprCols (TernaryAppE _ e1 e2 e3) = exprCols e1 ∪ exprCols e2 ∪ exprCols e3
exprCols (UnAppE _ e) = exprCols e
exprCols (ColE c) = S.singleton c
exprCols (ConstE _) = S.empty
aggrInput :: AggrType -> S.Set Attr
aggrInput (Avg e) = exprCols e
aggrInput (Max e) = exprCols e
aggrInput (Min e) = exprCols e
aggrInput (Sum e) = exprCols e
aggrInput (All e) = exprCols e
aggrInput (Any e) = exprCols e
aggrInput (Count e) = exprCols e
aggrInput (CountDistinct e) = exprCols e
aggrInput CountStar = S.empty
winFunInput :: WinFun -> S.Set Attr
winFunInput (WinAvg e) = exprCols e
winFunInput (WinMax e) = exprCols e
winFunInput (WinMin e) = exprCols e
winFunInput (WinSum e) = exprCols e
winFunInput (WinAll e) = exprCols e
winFunInput (WinAny e) = exprCols e
winFunInput (WinFirstValue e) = exprCols e
winFunInput (WinLastValue e) = exprCols e
winFunInput WinCount = S.empty
mapCol :: Proj -> Maybe (Attr, Attr)
mapCol (a, ColE b) = Just (a, b)
mapCol (a, UnAppE (Cast _) (ColE b)) = Just (a, b)
mapCol _ = Nothing
-- | Build a map from a projection list that maps each attribute to
-- its new names after projection. Only attributes that are simply
-- renamed are considered.
mapColMulti :: [Proj] -> M.Map Attr (S.Set Attr)
mapColMulti = L.foldl' insertMap M.empty
where
insertMap m (a, ColE b) = M.insertWith S.union b (ss a) m
insertMap m (a, UnAppE (Cast _) (ColE b)) = M.insertWith S.union b (ss a) m
insertMap m _ = m
mColE :: Expr -> Maybe Attr
mColE (ColE c) = Just c
mColE _ = Nothing
|
ulricha/dsh-sql
|
src/Database/DSH/Backend/Sql/Opt/Properties/Auxiliary.hs
|
bsd-3-clause
| 2,754
| 0
| 11
| 808
| 1,098
| 562
| 536
| 59
| 3
|
module BowlingKata.Day6 (score) where
score :: [Int] -> Int
score ([]) = 0
score (x:[]) = x
score (x:y:[]) = x + y
score (x:y:z:[]) = x + y + z
score (x:y:z:xs) | x == 10 = 10 + y + z + score (y:z:xs)
| (x + y) == 10 = 10 + z + score (z:xs)
| otherwise = x + y + score (z:xs)
|
Alex-Diez/haskell-tdd-kata
|
old-katas/src/BowlingKata/Day6.hs
|
bsd-3-clause
| 352
| 0
| 10
| 144
| 235
| 121
| 114
| 9
| 1
|
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-}
module Main where
{- external modules -}
import qualified Data.ByteString as BS
import qualified Data.HashMap.Strict as Map
import Control.Applicative
import Control.Monad.Error
import Snap.Core
import Snap.Http.Server
import Snap.Util.FileServe
import System.Console.CmdArgs
import System.Directory
import System.Exit
import System.IO
import GHC.Conc
{- Noelm modules -}
import qualified Noelm.Internal.Name as N
import qualified Noelm.Internal.Version as V
import qualified Noelm.Internal.Paths as Noelm
{- noelm-get modules -}
import qualified Noelm.Get.Utils.Paths as Path
{- internal modules -}
import qualified Noelm.Get.Server.Generate.Docs as Docs
import qualified Noelm.Get.Server.Generate.Html as Html
import qualified Noelm.Get.Server.Routes as Route
data Flags = Flags
{ port :: Int
, regenerate :: Bool
} deriving (Data,Typeable,Show,Eq)
flags :: Flags
flags = Flags
{ port = 8000 &= help "set the port of the server"
, regenerate = False &= help "flag to regenerate all documentation"
}
-- | Set up the server.
main :: IO ()
main = do
setNumCapabilities =<< getNumProcessors
getRuntimeAndDocs
setupLogging
setupSrcHtml
createDirectoryIfMissing True Path.libDir
cargs <- cmdArgs flags
when (regenerate cargs) Docs.regenerate
httpServe (setPort (port cargs) defaultConfig) $
ifTop (serveFile "public/Home.html")
<|> route [ ("catalog" , Route.catalog)
, ("versions" , Route.versions)
, ("register" , Route.register)
, ("metadata" , Route.metadata)
, ("resources", serveDirectoryWith directoryConfig "resources")
]
<|> serveDirectoryWith directoryConfig "public"
<|> do modifyResponse $ setResponseStatus 404 "Not found"
serveFile "public/Error404.html"
getRuntimeAndDocs :: IO ()
getRuntimeAndDocs = do
BS.writeFile "resources/noelm-runtime.js" =<< BS.readFile Noelm.runtime
BS.writeFile "resources/docs.json" =<< BS.readFile Noelm.docs
setupLogging :: IO ()
setupLogging =
do createDirectoryIfMissing True "log"
createIfMissing "log/access.log"
createIfMissing "log/error.log"
where
createIfMissing path = do
exists <- doesFileExist path
when (not exists) $ BS.writeFile path ""
setupSrcHtml :: IO ()
setupSrcHtml =
do createDirectoryIfMissing True "public"
result <- runErrorT generate
case result of
Right _ -> return ()
Left err -> do hPutStrLn stderr err
exitFailure
where
generate = mapM Html.generateSrc $ map (\name -> "src/" ++ name ++ ".noelm") noelms
noelms = ["Error404","Catalog","Home","DesignGuidelines","Documentation"]
directoryConfig :: MonadSnap m => DirectoryConfig m
directoryConfig =
fancyDirectoryConfig
{ indexGenerator = defaultIndexGenerator defaultMimeTypes indexStyle
, mimeTypes = Map.insert ".noelm" "text/plain" $
Map.insert ".ico" "image/x-icon" $ defaultMimeTypes
}
indexStyle :: BS.ByteString
indexStyle =
"body { margin:0; font-family:sans-serif; background:rgb(245,245,245);\
\ font-family: calibri, verdana, helvetica, arial; }\
\div.header { padding: 40px 50px; font-size: 24px; }\
\div.content { padding: 0 40px }\
\div.footer { display:none; }\
\table { width:100%; border-collapse:collapse; }\
\td { padding: 6px 10px; }\
\tr:nth-child(odd) { background:rgb(216,221,225); }\
\td { font-family:monospace }\
\th { background:rgb(90,99,120); color:white; text-align:left;\
\ padding:10px; font-weight:normal; }"
|
timthelion/noelm-get-server
|
src/Noelm/Get/Server/Server.hs
|
bsd-3-clause
| 3,689
| 0
| 15
| 770
| 759
| 411
| 348
| 79
| 2
|
-- Copyright : (C) 2009 Corey O'Connor
-- License : BSD-style (see the file LICENSE)
module Bind.Marshal.StaticProperties.DesAction where
import Bind.Marshal.Prelude
import Bind.Marshal.Action
import Bind.Marshal.DesAction.Static
|
coreyoconnor/bind-marshal
|
src/Bind/Marshal/StaticProperties/DesAction.hs
|
bsd-3-clause
| 242
| 0
| 4
| 36
| 29
| 21
| 8
| 4
| 0
|
import Data.Char (isLower, ord)
lowerToCode :: Char -> Maybe Int
lowerToCode c
| isLower c = Just $ ord c
| otherwise = Nothing
evenDiv2 :: Int -> Maybe Int
evenDiv2 n
| even n = Just $ n `div` 2
| otherwise = Nothing
bindM :: Maybe a -> (a -> Maybe b) -> Maybe b
Just x `bindM` f = f x
Nothing `bindM` _ = Nothing
|
YoshikuniJujo/funpaala
|
samples/33_functor_monad/lowerToCode.hs
|
bsd-3-clause
| 322
| 2
| 9
| 76
| 173
| 84
| 89
| 12
| 1
|
{-# LANGUAGE PackageImports #-}
module Main where
-- ghc --make WASHMain -package text -o WASHMain
import Data.List (isSuffixOf)
import Control.Exception
import System.Directory
import System.Environment
import System.IO
import WASHGenerator
import WASHFlags
main =
do args <- getArgs
runPreprocessor flags0 args
runPreprocessor flags [washfile] =
do fileExists <- doesFileExist washfile
if ".wash" `isSuffixOf` washfile
then
preprocess flags washfile (take (length washfile - 5) washfile ++ ".hs") ""
else if fileExists
then
bracket (openFile washfile ReadMode)
hClose
(\ inhandle -> preprocessPIPE flags washfile inhandle stdout "")
else
preprocess flags
(washfile ++ ".wash")
(washfile ++ ".hs")
""
runPreprocessor flags [washfile, hsfile] =
preprocess flags (washfile) (hsfile) ""
runPreprocessor flags [originalFile, washfile, hsfile] =
preprocess flags (washfile) (hsfile) ""
runPreprocessor flags [] =
preprocessPIPE flags "<stdin>" stdin stdout ""
runPreprocessor flags args =
do progName <- getProgName
hPutStrLn stderr ("Usage: " ++ progName ++ " washfile [hsfile]")
hPutStrLn stderr (" or: " ++ progName ++ " originalFile infile outfile")
hPutStrLn stderr (" or: " ++ progName)
hPutStrLn stderr (" to run as pipe processor")
hPutStrLn stderr ("Actual arguments: " ++ show args)
|
nh2/WashNGo
|
washparser/hs/WASHMain.hs
|
bsd-3-clause
| 1,391
| 22
| 14
| 279
| 407
| 210
| 197
| 37
| 3
|
module Convention
( Signature(..)
, ArgumentType(..)
, printArgumentType
, argumentByteSize
, genSignatureList
) where
import Data.ByteString.Builder
import Test.QuickCheck
-- |Datatype for function arguments: integers and floating points of different sizes and a pointer type
data ArgumentType
= I8
| I16
| I32
| I64
| F32
| F64
| Pointer
deriving (Eq, Enum, Bounded, Ord, Show)
-- |C syntax for data type
printArgumentType :: ArgumentType -> Builder
printArgumentType t = case t of
I8 -> string8 "unsigned char"
I16 -> string8 "unsigned short"
I32 -> string8 "unsigned int"
I64 -> string8 "unsigned long long"
F32 -> string8 "float"
F64 -> string8 "double"
Pointer -> string8 "void *"
-- |Size of data types in bytes
argumentByteSize :: Bool -> ArgumentType -> Int
argumentByteSize p64 t = case t of
I8 -> 1
I16 -> 2
I32 -> 4
I64 -> 8
F32 -> 4
F64 -> 8
Pointer -> if p64 then 8 else 4
-- |A function signature is represented by a list of its argument types
newtype Signature = Signature [ArgumentType] deriving (Eq, Ord, Show)
-- |Random signatures for QuickCheck
instance Arbitrary Signature where
arbitrary = Signature <$> sized arguments
where
arguments :: Int -> Gen [ArgumentType]
arguments n | n > 0 = vectorOf n $ elements [minBound..maxBound]
| otherwise = arguments 1
shrink (Signature args) = Signature <$> shrinkList shrinkNothing args
-- |Generator for a list of expressions. The list has a fixed length `len' and each expression is sized up to `complexity'
genSignatureList :: Int -> Int -> Gen [Signature]
genSignatureList len complexity = vectorOf len $ resize complexity arbitrary
|
m-schmidt/fuzzer
|
src/Convention.hs
|
bsd-3-clause
| 1,759
| 0
| 11
| 424
| 427
| 225
| 202
| 44
| 8
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE JavaScriptFFI #-}
{-# LANGUAGE OverloadedStrings #-}
-- |
module JavaScript.Canvas (
-- * Canvas accessors
Canvas
, runCanvas
, width
, height
, resize
-- * Drawing
, fillRect
, clearRect
, moveTo
, lineTo
, stroke
, strokeStyle
, fill
, fillStyle
, beginPath
, drawLine
, drawprojLine
, lineWidth
, clear
, arc
) where
import Control.Applicative
import Control.Monad.Trans.Reader
import Control.Monad.IO.Class
import qualified Data.Foldable as F
import GHCJS.Types
----------------------------------------------------------------
-- Canvas API
----------------------------------------------------------------
-- | Monad for drawing in canvas
newtype Canvas a = Canvas (ReaderT (JSRef CanvasTag,JSRef Context) IO a)
deriving (Functor,Applicative,Monad,MonadIO)
-- | Run context
runCanvas :: JSString -> Canvas a -> IO a
runCanvas cnvId (Canvas m) = do
cnv <- jscnv_getElementByID cnvId
cxt <- jscnv_getContext cnv
runReaderT m (cnv,cxt)
----------------------------------------------------------------
-- Primitives
----------------------------------------------------------------
fillRect :: Double -> Double -> Double -> Double -> Canvas ()
fillRect x y w h = Canvas $ ReaderT $ \(_,cxt) ->
jscnv_fillRect cxt x y w h
clearRect :: Double -> Double -> Double -> Double -> Canvas ()
clearRect x y w h = Canvas $ ReaderT $ \(_,cxt) ->
jscnv_clearRect cxt x y w h
clear :: Canvas ()
clear = Canvas $ ReaderT $ \(cnv,_) -> jscnv_clear cnv
lineTo :: Double -> Double -> Canvas ()
lineTo x y = Canvas $ ReaderT $ \(_,cxt) -> jscnv_lineTo cxt x y
moveTo :: Double -> Double -> Canvas ()
moveTo x y = Canvas $ ReaderT $ \(_,cxt) -> jscnv_moveTo cxt x y
lineWidth :: Double -> Canvas ()
lineWidth w = Canvas $ ReaderT $ \(_,cxt) -> jscnv_lineWidth cxt w
stroke :: Canvas ()
stroke = Canvas $ ReaderT $ \(_,cxt) -> jscnv_stroke cxt
fill :: Canvas ()
fill = Canvas $ ReaderT $ \(_,cxt) -> jscnv_fill cxt
strokeStyle :: JSString -> Canvas ()
strokeStyle s = Canvas $ ReaderT $ \(_,cxt) -> jscnv_strokeStyle cxt s
fillStyle :: JSString -> Canvas ()
fillStyle s = Canvas $ ReaderT $ \(_,cxt) -> jscnv_fillStyle cxt s
resize :: Int -> Int -> Canvas ()
resize x y = Canvas $ ReaderT $ \(cnv,_) -> jscnv_resize cnv x y
width :: Canvas Int
width = Canvas $ ReaderT $ \(cnv,_) -> jscnv_width cnv
height :: Canvas Int
height = Canvas $ ReaderT $ \(cnv,_) -> jscnv_height cnv
beginPath :: Canvas ()
beginPath = Canvas $ ReaderT $ \(_,cxt) -> jscnv_beginPath cxt
arc :: (Double,Double) -> Double -> (Double,Double) -> Canvas ()
arc (x,y) r (a,b) = Canvas $ ReaderT $ \(_,cxt) ->
jscnv_arc cxt x y r a b
----------------------------------------------------------------
-- Compound functions
----------------------------------------------------------------
drawLine :: F.Foldable f => f (Double,Double) -> Canvas ()
drawLine xs = case F.toList xs of
[] -> return ()
[_] -> return ()
((x,y):ps) -> moveTo x y >> F.forM_ ps (uncurry lineTo)
drawprojLine :: F.Foldable f => (a -> Maybe (Double,Double)) -> f a -> Canvas ()
drawprojLine proj
= mapM_ (\x -> drawLine x) . split . fmap proj . F.toList
where
split [] = []
split xs = case spanJust xs of
(a,rest) -> a : split rest
--
spanJust (Just a:xs) = case spanJust xs of
(as,rest) -> (a:as,rest)
spanJust xs = ([],dropNothing xs)
--
dropNothing (Nothing:xs) = dropNothing xs
dropNothing xs = xs
----------------------------------------------------------------
-- FFI
----------------------------------------------------------------
data Context
data CanvasTag
foreign import javascript safe "document.getElementById($1)"
jscnv_getElementByID :: JSString -> IO (JSRef CanvasTag)
foreign import javascript safe "$1.getContext('2d')"
jscnv_getContext :: JSRef CanvasTag -> IO (JSRef Context)
foreign import javascript safe "$1.fillRect($2,$3,$4,$5)"
jscnv_fillRect :: JSRef Context -> Double -> Double -> Double -> Double -> IO ()
foreign import javascript safe "$1.clearRect($2,$3,$4,$5)"
jscnv_clearRect :: JSRef Context -> Double -> Double -> Double -> Double -> IO ()
foreign import javascript safe "$1.moveTo($2,$3)"
jscnv_moveTo :: JSRef Context -> Double -> Double -> IO ()
foreign import javascript safe "$1.lineTo($2,$3)"
jscnv_lineTo :: JSRef Context -> Double -> Double -> IO ()
foreign import javascript safe "$1.lineWidth = $2"
jscnv_lineWidth :: JSRef Context -> Double -> IO ()
foreign import javascript safe "$1.stroke()"
jscnv_stroke :: JSRef Context -> IO ()
foreign import javascript safe "$1.strokeStyle = $2"
jscnv_strokeStyle :: JSRef Context -> JSString -> IO ()
foreign import javascript safe "$1.fill()"
jscnv_fill :: JSRef Context -> IO ()
foreign import javascript safe "$1.fillStyle = $2"
jscnv_fillStyle :: JSRef Context -> JSString -> IO ()
foreign import javascript safe "$1.width = $1.width"
jscnv_clear :: JSRef CanvasTag -> IO ()
foreign import javascript safe "$1.width"
jscnv_width :: JSRef CanvasTag -> IO Int
foreign import javascript safe "$1.height"
jscnv_height :: JSRef CanvasTag -> IO Int
foreign import javascript safe "{$1.width = $2; $1.height = $3;}"
jscnv_resize :: JSRef CanvasTag -> Int -> Int -> IO ()
foreign import javascript safe "$1.beginPath()"
jscnv_beginPath :: JSRef Context -> IO ()
foreign import javascript safe "$1.arc($2,$3,$4,$5,$6)"
jscnv_arc :: JSRef Context -> Double -> Double -> Double -> Double -> Double -> IO ()
|
Shimuuar/web-planetarium
|
JavaScript/Canvas.hs
|
bsd-3-clause
| 5,623
| 58
| 12
| 1,070
| 1,866
| 984
| 882
| -1
| -1
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Matterhorn.Command
( commandList
, dispatchCommand
, printArgSpec
, toggleMessagePreview
)
where
import Prelude ()
import Matterhorn.Prelude
import Brick.Main ( invalidateCache )
import qualified Control.Exception as Exn
import qualified Data.Char as Char
import qualified Data.Text as T
import Lens.Micro.Platform ( (%=) )
import qualified Network.Mattermost.Endpoints as MM
import qualified Network.Mattermost.Exceptions as MM
import qualified Network.Mattermost.Types as MM
import Matterhorn.State.Attachments
import Matterhorn.Connection ( connectWebsockets )
import Matterhorn.Constants ( normalChannelSigil )
import Matterhorn.HelpTopics
import Matterhorn.Scripts
import Matterhorn.State.Help
import Matterhorn.State.Editing
import Matterhorn.State.ChannelList
import Matterhorn.State.Channels
import Matterhorn.State.ChannelTopicWindow
import Matterhorn.State.ChannelSelect
import Matterhorn.State.Logging
import Matterhorn.State.PostListOverlay
import Matterhorn.State.UserListOverlay
import Matterhorn.State.ChannelListOverlay
import Matterhorn.State.ThemeListOverlay
import Matterhorn.State.Messages
import Matterhorn.State.NotifyPrefs
import Matterhorn.State.Common ( postInfoMessage )
import Matterhorn.State.Teams
import Matterhorn.State.Users
import Matterhorn.Themes ( attrForUsername )
import Matterhorn.Types
-- | This function skips any initial whitespace and returns the first
-- 'token' (i.e. any sequence of non-whitespace characters) as well as
-- the trailing rest of the string, after any whitespace. This is used
-- for tokenizing the first bits of command input while leaving the
-- subsequent chunks unchanged, preserving newlines and other
-- important formatting.
unwordHead :: Text -> Maybe (Text, Text)
unwordHead t =
let t' = T.dropWhile Char.isSpace t
(w, rs) = T.break Char.isSpace t'
in if T.null w
then Nothing
else Just (w, T.dropWhile Char.isSpace rs)
printArgSpec :: CmdArgs a -> Text
printArgSpec NoArg = ""
printArgSpec (LineArg ts) = "<" <> ts <> ">"
printArgSpec (TokenArg t NoArg) = "<" <> t <> ">"
printArgSpec (UserArg rs) = "<" <> addUserSigil "user" <> ">" <> addSpace (printArgSpec rs)
printArgSpec (ChannelArg rs) = "<" <> normalChannelSigil <> "channel>" <> addSpace (printArgSpec rs)
printArgSpec (TokenArg t rs) = "<" <> t <> ">" <> addSpace (printArgSpec rs)
addSpace :: Text -> Text
addSpace "" = ""
addSpace t = " " <> t
matchArgs :: CmdArgs a -> Text -> Either Text a
matchArgs NoArg t = case unwordHead t of
Nothing -> return ()
Just (a, as)
| not (T.all Char.isSpace as) -> Left ("Unexpected arguments '" <> t <> "'")
| otherwise -> Left ("Unexpected argument '" <> a <> "'")
matchArgs (LineArg _) t = return t
matchArgs spec@(UserArg rs) t = case unwordHead t of
Nothing -> case rs of
NoArg -> Left ("Missing argument: " <> printArgSpec spec)
_ -> Left ("Missing arguments: " <> printArgSpec spec)
Just (a, as) -> (,) <$> pure a <*> matchArgs rs as
matchArgs spec@(ChannelArg rs) t = case unwordHead t of
Nothing -> case rs of
NoArg -> Left ("Missing argument: " <> printArgSpec spec)
_ -> Left ("Missing arguments: " <> printArgSpec spec)
Just (a, as) -> (,) <$> pure a <*> matchArgs rs as
matchArgs spec@(TokenArg _ rs) t = case unwordHead t of
Nothing -> case rs of
NoArg -> Left ("Missing argument: " <> printArgSpec spec)
_ -> Left ("Missing arguments: " <> printArgSpec spec)
Just (a, as) -> (,) <$> pure a <*> matchArgs rs as
commandList :: [Cmd]
commandList =
[ Cmd "quit" "Exit Matterhorn" NoArg $ \ () -> requestQuit
, Cmd "right" "Focus on the next channel" NoArg $ \ () ->
nextChannel
, Cmd "left" "Focus on the previous channel" NoArg $ \ () ->
prevChannel
, Cmd "create-channel" "Create a new public channel"
(LineArg "channel name") $ \ name ->
createOrdinaryChannel True name
, Cmd "create-private-channel" "Create a new private channel"
(LineArg "channel name") $ \ name ->
createOrdinaryChannel False name
, Cmd "delete-channel" "Delete the current channel"
NoArg $ \ () ->
beginCurrentChannelDeleteConfirm
, Cmd "hide" "Hide the current DM or group channel from the channel list"
NoArg $ \ () -> do
tId <- use csCurrentTeamId
hideDMChannel =<< use (csCurrentChannelId tId)
, Cmd "reconnect" "Force a reconnection attempt to the server"
NoArg $ \ () ->
connectWebsockets
, Cmd "members" "Show the current channel's members"
NoArg $ \ () ->
enterChannelMembersUserList
, Cmd "leave" "Leave a normal channel or hide a DM channel" NoArg $ \ () ->
startLeaveCurrentChannel
, Cmd "join" "Find a channel to join" NoArg $ \ () ->
enterChannelListOverlayMode
, Cmd "join" "Join the specified channel" (ChannelArg NoArg) $ \(n, ()) ->
joinChannelByName n
, Cmd "theme" "List the available themes" NoArg $ \ () ->
enterThemeListMode
, Cmd "theme" "Set the color theme"
(TokenArg "theme" NoArg) $ \ (themeName, ()) ->
setTheme themeName
, Cmd "topic" "Set the current channel's topic (header) interactively"
NoArg $ \ () ->
openChannelTopicWindow
, Cmd "topic" "Set the current channel's topic (header)"
(LineArg "topic") $ \ p ->
if not (T.null p) then setChannelTopic p else return ()
, Cmd "add-user" "Search for a user to add to the current channel"
NoArg $ \ () ->
enterChannelInviteUserList
, Cmd "msg" "Search for a user to enter a private chat"
NoArg $ \ () ->
enterDMSearchUserList
, Cmd "msg" "Chat with the specified user"
(UserArg NoArg) $ \ (name, ()) ->
changeChannelByName name
, Cmd "username-attribute" "Display the attribute used to color the specified username"
(UserArg NoArg) $ \ (name, ()) ->
displayUsernameAttribute name
, Cmd "msg" "Go to a user's channel and send the specified message or command"
(UserArg $ LineArg "message or command") $ \ (name, msg) -> do
withFetchedUserMaybe (UserFetchByUsername name) $ \foundUser -> do
case foundUser of
Just user -> createOrFocusDMChannel user $ Just $ \cId -> do
tId <- use csCurrentTeamId
handleInputSubmission tId cId msg
Nothing -> mhError $ NoSuchUser name
, Cmd "log-start" "Begin logging debug information to the specified path"
(TokenArg "path" NoArg) $ \ (path, ()) ->
startLogging $ T.unpack path
, Cmd "log-snapshot" "Dump the current debug log buffer to the specified path"
(TokenArg "path" NoArg) $ \ (path, ()) ->
logSnapshot $ T.unpack path
, Cmd "log-stop" "Stop logging"
NoArg $ \ () ->
stopLogging
, Cmd "log-mark" "Add a custom marker message to the Matterhorn debug log"
(LineArg "message") $ \ markMsg ->
mhLog LogUserMark markMsg
, Cmd "log-status" "Show current debug logging status"
NoArg $ \ () ->
getLogDestination
, Cmd "add-user" "Add a user to the current channel"
(UserArg NoArg) $ \ (uname, ()) ->
addUserByNameToCurrentChannel uname
, Cmd "remove" "Remove a user from the current channel"
(UserArg NoArg) $ \ (uname, ()) ->
removeUserFromCurrentChannel uname
, Cmd "user" "Show users to initiate a private DM chat channel"
-- n.b. this is identical to "msg", but is provided as an
-- alternative mental model for useability.
NoArg $ \ () ->
enterDMSearchUserList
, Cmd "message-preview" "Toggle preview of the current message" NoArg $ \_ ->
toggleMessagePreview
, Cmd "toggle-truncate-verbatim-blocks" "Toggle truncation of verbatim and code blocks" NoArg $ \_ ->
toggleVerbatimBlockTruncation
, Cmd "toggle-channel-list" "Toggle channel list visibility" NoArg $ \_ ->
toggleChannelListVisibility
, Cmd "toggle-message-timestamps" "Toggle message timestamps" NoArg $ \_ ->
toggleMessageTimestamps
, Cmd "toggle-expanded-topics" "Toggle expanded channel topics" NoArg $ \_ ->
toggleExpandedChannelTopics
, Cmd "focus" "Focus on a channel or user"
(ChannelArg NoArg) $ \ (name, ()) ->
changeChannelByName name
, Cmd "focus" "Select from available channels" NoArg $ \ () ->
beginChannelSelect
, Cmd "help" "Show the main help screen" NoArg $ \ _ ->
showHelpScreen mainHelpTopic
, Cmd "shortcuts" "Show keyboard shortcuts" NoArg $ \ _ ->
showHelpScreen mainHelpTopic
, Cmd "help" "Show help about a particular topic"
(TokenArg "topic" NoArg) $ \ (topicName, ()) ->
case lookupHelpTopic topicName of
Nothing -> mhError $ NoSuchHelpTopic topicName
Just topic -> showHelpScreen topic
, Cmd "sh" "List the available shell scripts" NoArg $ \ () ->
listScripts
, Cmd "group-create" "Create a group chat"
(LineArg (addUserSigil "user" <> " [" <> addUserSigil "user" <> " ...]"))
createGroupChannel
, Cmd "sh" "Run a prewritten shell script"
(TokenArg "script" (LineArg "message")) $ \ (script, text) -> do
tId <- use csCurrentTeamId
cId <- use (csCurrentChannelId tId)
findAndRunScript cId script text
, Cmd "flags" "Open a window of your flagged posts" NoArg $ \ () ->
enterFlaggedPostListMode
, Cmd "pinned-posts" "Open a window of this channel's pinned posts" NoArg $ \ () ->
enterPinnedPostListMode
, Cmd "search" "Search for posts with given terms" (LineArg "terms") $
enterSearchResultPostListMode
, Cmd "notify-prefs" "Edit the current channel's notification preferences" NoArg $ \_ ->
enterEditNotifyPrefsMode
, Cmd "rename-channel-url" "Rename the current channel's URL name" (TokenArg "channel name" NoArg) $ \ (name, _) ->
renameChannelUrl name
, Cmd "move-team-left" "Move the currently-selected team to the left in the team list" NoArg $ \_ ->
moveCurrentTeamLeft
, Cmd "move-team-right" "Move the currently-selected team to the right in the team list" NoArg $ \_ ->
moveCurrentTeamRight
, Cmd "attach" "Attach a given file without browsing" (LineArg "path") $
attachFileByPath
, Cmd "toggle-favorite" "Toggle the favorite status of the current channel" NoArg $ \_ ->
toggleChannelFavoriteStatus
]
displayUsernameAttribute :: Text -> MH ()
displayUsernameAttribute name = do
let an = attrForUsername trimmed
trimmed = trimUserSigil name
postInfoMessage $ "The attribute used for " <> addUserSigil trimmed <>
" is " <> (attrNameToConfig an)
execMMCommand :: Text -> Text -> MH ()
execMMCommand name rest = do
tId <- use csCurrentTeamId
cId <- use (csCurrentChannelId tId)
session <- getSession
em <- use (csCurrentTeam.tsEditState.cedEditMode)
let mc = MM.MinCommand
{ MM.minComChannelId = cId
, MM.minComCommand = "/" <> name <> " " <> rest
, MM.minComParentId = case em of
Replying _ p -> Just $ MM.getId p
Editing p _ -> MM.postRootId p
_ -> Nothing
, MM.minComRootId = case em of
Replying _ p -> MM.postRootId p <|> (Just $ MM.postId p)
Editing p _ -> MM.postRootId p
_ -> Nothing
, MM.minComTeamId = tId
}
runCmd = liftIO $ do
void $ MM.mmExecuteCommand mc session
handleHTTP (MM.HTTPResponseException err) =
return (Just (T.pack err))
-- XXX: this might be a bit brittle in the future, because it
-- assumes the shape of an error message. We might want to
-- think about a better way of discovering this error and
-- reporting it accordingly?
handleCmdErr (MM.MattermostServerError err) =
let (_, msg) = T.breakOn ": " err in
return (Just (T.drop 2 msg))
handleMMErr (MM.MattermostError
{ MM.mattermostErrorMessage = msg }) =
return (Just msg)
errMsg <- liftIO $ (runCmd >> return Nothing) `Exn.catch` handleHTTP
`Exn.catch` handleCmdErr
`Exn.catch` handleMMErr
case errMsg of
Nothing -> return ()
Just err ->
mhError $ GenericError ("Error running command: " <> err)
dispatchCommand :: Text -> MH ()
dispatchCommand cmd =
case unwordHead cmd of
Just (x, xs)
| matchingCmds <- [ c
| c@(Cmd name _ _ _) <- commandList
, name == x
] -> go [] matchingCmds
where go [] [] = do
execMMCommand x xs
go errs [] = do
let msg = ("error running command /" <> x <> ":\n" <>
mconcat [ " " <> e | e <- errs ])
mhError $ GenericError msg
go errs (Cmd _ _ spec exe : cs) =
case matchArgs spec xs of
Left e -> go (e:errs) cs
Right args -> exe args
_ -> return ()
toggleMessagePreview :: MH ()
toggleMessagePreview = do
mh invalidateCache
csResources.crConfiguration.configShowMessagePreviewL %= not
|
matterhorn-chat/matterhorn
|
src/Matterhorn/Command.hs
|
bsd-3-clause
| 13,655
| 0
| 22
| 3,748
| 3,423
| 1,763
| 1,660
| -1
| -1
|
#!/usr/bin/env runhaskell
import Data.List
import Data.IORef
import System.Exit
import System.Process
import System.Environment
import System.Posix.Unistd
import Control.Concurrent
polltime = 10 -- in seconds
main =
do args <- getArgs
-- A flag for completion:
ref <- newIORef False
case args of
time:rest ->
let timeout = read time
cmd = concat $ intersperse " " rest
in
do putStrLn$ "++ Running command with timeout = "++ show timeout ++" seconds:\n " ++ cmd
pid <- runCommand cmd
sync <- newEmptyMVar
let loop acc =
if acc > (timeout :: Int)
then do putStrLn$ "\nERROR: TIMED OUT!"
putMVar sync (ExitFailure 88)
--exitWith (ExitFailure 88)
else do sleep polltime
x <- getProcessExitCode pid
case x of
Nothing -> do putStrLn$ "++ Polling, approximately "++
show (acc+polltime) ++" seconds have elapsed..."
loop (acc+polltime)
Just code -> putMVar sync code
let poll_thread = loop 0
let wait_thread =
do code <- waitForProcess pid
writeIORef ref True
putStrLn$ "++ Command completed without timing out, exit code: "++ show code
putMVar sync code
forkIO wait_thread
forkIO poll_thread
final <- readMVar sync
exitWith final
|
rrnewton/Haskell-CnC
|
timeout.hs
|
bsd-3-clause
| 1,463
| 39
| 19
| 516
| 378
| 190
| 188
| 39
| 3
|
{-# OPTIONS -fno-warn-unused-imports #-}
{-# LANGUAGE ForeignFunctionInterface #-}
#include "HsConfigure.h"
-- #hide
module Data.Time.LocalTime.TimeZone
(
-- * Time zones
TimeZone(..),timeZoneOffsetString,timeZoneOffsetString',minutesToTimeZone,hoursToTimeZone,utc,
-- getting the locale time zone
getTimeZone,getCurrentTimeZone
) where
--import System.Time.Calendar.Format
import Data.Time.Calendar.Private
import Data.Time.Clock
import Data.Time.Clock.POSIX
import Foreign
import Foreign.C
import Control.DeepSeq
import Data.Typeable
#if LANGUAGE_Rank2Types
import Data.Data
#endif
-- | A TimeZone is a whole number of minutes offset from UTC, together with a name and a \"just for summer\" flag.
data TimeZone = TimeZone {
-- | The number of minutes offset from UTC. Positive means local time will be later in the day than UTC.
timeZoneMinutes :: Int,
-- | Is this time zone just persisting for the summer?
timeZoneSummerOnly :: Bool,
-- | The name of the zone, typically a three- or four-letter acronym.
timeZoneName :: String
} deriving (Eq,Ord
#if LANGUAGE_DeriveDataTypeable
#if LANGUAGE_Rank2Types
,Data
#endif
#endif
)
instance NFData TimeZone where
rnf (TimeZone m so n) = m `deepseq` so `deepseq` n `deepseq` ()
instance Typeable TimeZone where
typeOf _ = mkTyConApp (mkTyCon "Data.Time.LocalTime.TimeZone.TimeZone") []
-- | Create a nameless non-summer timezone for this number of minutes
minutesToTimeZone :: Int -> TimeZone
minutesToTimeZone m = TimeZone m False ""
-- | Create a nameless non-summer timezone for this number of hours
hoursToTimeZone :: Int -> TimeZone
hoursToTimeZone i = minutesToTimeZone (60 * i)
showT :: NumericPadOption -> Int -> String
showT opt t = show4 opt ((div t 60) * 100 + (mod t 60))
-- | Text representing the offset of this timezone, such as \"-0800\" or \"+0400\" (like %z in formatTime), with arbitrary padding
timeZoneOffsetString' :: NumericPadOption -> TimeZone -> String
timeZoneOffsetString' opt (TimeZone t _ _) | t < 0 = '-':(showT opt (negate t))
timeZoneOffsetString' opt (TimeZone t _ _) = '+':(showT opt t)
-- | Text representing the offset of this timezone, such as \"-0800\" or \"+0400\" (like %z in formatTime)
timeZoneOffsetString :: TimeZone -> String
timeZoneOffsetString = timeZoneOffsetString' (Just '0')
instance Show TimeZone where
show zone@(TimeZone _ _ "") = timeZoneOffsetString zone
show (TimeZone _ _ name) = name
-- | The UTC time zone
utc :: TimeZone
utc = TimeZone 0 False "UTC"
{-# CFILES cbits/HsTime.c #-}
foreign import ccall unsafe "HsTime.h get_current_timezone_seconds" get_current_timezone_seconds :: CTime -> Ptr CInt -> Ptr CString -> IO CLong
posixToCTime :: POSIXTime -> CTime
posixToCTime = fromInteger . floor
-- | Get the local time-zone for a given time (varying as per summertime adjustments)
getTimeZone :: UTCTime -> IO TimeZone
getTimeZone time = with 0 (\pdst -> with nullPtr (\pcname -> do
secs <- get_current_timezone_seconds (posixToCTime (utcTimeToPOSIXSeconds time)) pdst pcname
case secs of
0x80000000 -> fail "localtime_r failed"
_ -> do
dst <- peek pdst
cname <- peek pcname
name <- peekCString cname
return (TimeZone (div (fromIntegral secs) 60) (dst == 1) name)
))
-- | Get the current time-zone
getCurrentTimeZone :: IO TimeZone
getCurrentTimeZone = getCurrentTime >>= getTimeZone
|
takano-akio/time
|
Data/Time/LocalTime/TimeZone.hs
|
bsd-3-clause
| 3,352
| 10
| 24
| 538
| 753
| 407
| 346
| 53
| 2
|
{-# LANGUAGE ScopedTypeVariables #-}
module Data.Obfus.ByteString where
import Pipes
import qualified Data.ByteString as B
import Data.Bits (xor)
import Data.SecureMem
import Crypto.Cipher.Types
import Crypto.Cipher.RC4 (RC4)
xorStream :: Monad m => B.ByteString -> Pipe B.ByteString B.ByteString m ()
xorStream key
| B.length key == 0 = error "xorStream: empty key"
| otherwise = goPipe 0
where
goPipe keyOffset = do
bs <- await
let (newKeyOffset, bs') = goXor keyOffset bs
yield bs'
goPipe newKeyOffset
goXor i bs =
let i' = (i + B.length bs) `rem` B.length key
bs' = B.pack $ zipWith xor (B.unpack bs) (drop i infKey)
in (i', bs')
infKey = cycle $ B.unpack key
rc4Stream :: Monad m => B.ByteString -> Pipe B.ByteString B.ByteString m ()
rc4Stream key
| B.length key == 0 = error "xorStream: empty key"
| otherwise = goPipe initRc4
where
Right (initRc4 :: RC4) = fmap cipherInit $ makeKey key
goPipe :: Monad m => RC4 -> Pipe B.ByteString B.ByteString m ()
goPipe ctx = do
bs <- await
let (bs', newCtx) = streamCombine ctx bs
yield bs'
goPipe newCtx
|
overminder/simple-obfus
|
src/Data/Obfus/ByteString.hs
|
bsd-3-clause
| 1,129
| 0
| 15
| 253
| 448
| 219
| 229
| 33
| 1
|
module Outdated where
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Maybe (listToMaybe)
import Data.Version
import System.Directory (getAppUserDataDirectory)
import System.FilePath
import Distribution.ParseUtils
import Distribution.InstalledPackageInfo (InstalledPackageInfo(..))
import Distribution.Simple.PackageIndex (allPackages)
import Distribution.Package(PackageIdentifier(..), PackageName(..))
import Config
import CabalVersions (loadLatestVersions)
import InstalledPackages (getUserPackages)
main :: Config -> [String] -> IO ()
main config _ = do
userPackages <- getUserPackages config
latest <- loadLatestVersions =<< determineRepoCachePath
mapM_ (check config latest) (allPackages userPackages)
check :: Config -> Map String Version -> InstalledPackageInfo -> IO ()
check config latest pkg =
let pkgId = sourcePackageId pkg
name = unPackageName (pkgName pkgId)
currentVersion = pkgVersion pkgId
in
case Map.lookup name latest of
Just cabalVersion
| cabalVersion > currentVersion ->
let output
| quiet config = name
| otherwise = name ++ " current: " ++ showVersion currentVersion
++ " latest: " ++ showVersion cabalVersion
in putStrLn output
_ -> return ()
--
-- Look up cabal's repository cache
--
determineRepoCachePath :: IO FilePath
determineRepoCachePath =
do cabalConfig <- loadCabalConfig
case lookupField "remote-repo-cache" cabalConfig of
Nothing -> fail "No remote-repo-cache field in cabal configuration"
Just dir -> return (dir </> "hackage.haskell.org" </> "00-index.tar.gz")
-- | Default cabal configuration directory as defined in
-- Distribution.Client.Config
defaultCabalDir :: IO FilePath
defaultCabalDir = getAppUserDataDirectory "cabal"
-- | Default cabal configuration file as defined in
-- Distribution.Client.Config
defaultCabalConfigFile :: IO FilePath
defaultCabalConfigFile =
do dir <- defaultCabalDir
return (dir </> "config")
loadCabalConfig :: IO [Field]
loadCabalConfig =
do cabalFileName <- defaultCabalConfigFile
contents <- readFile cabalFileName
case readFields contents of
ParseFailed perror -> fail ("Unable to parse cabal configuration: " ++ show perror)
ParseOk _warnings fields -> return fields
lookupField :: String -> [Field] -> Maybe String
lookupField k fields = listToMaybe [ v | F _ k' v <- fields, k == k' ]
|
glguy/GhcPkgUtils
|
Outdated.hs
|
bsd-3-clause
| 2,479
| 0
| 19
| 485
| 623
| 316
| 307
| 54
| 2
|
{-# LANGUAGE TemplateHaskell #-}
module Code.Move_To_Front.Data where
import Code.Type ( BitSize (..) )
import Autolib.Reader
import Autolib.ToDoc
import Autolib.Size
import Data.Typeable
data Move_To_Front = Move_To_Front deriving ( Eq, Ord, Typeable )
$(derives [makeReader, makeToDoc] [''Move_To_Front])
data Coding a = Coding { queue :: a
, output :: [ Int ]
}
deriving ( Eq, Ord, Typeable )
$(derives [makeReader, makeToDoc] [''Coding])
instance Size (Coding a) where
size = length . output
instance BitSize (Coding a) where
bitSize = fromIntegral . size
-- Local variables:
-- mode: haskell
-- End:
|
florianpilz/autotool
|
src/Code/Move_To_Front/Data.hs
|
gpl-2.0
| 662
| 2
| 9
| 146
| 201
| 115
| 86
| 17
| 0
|
module MalTypes where
import Data.List (intercalate)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import MalPrinter
data Form = FList List
| FVector List
| FHashMap HashMap
| FAtom Atom
| FQuote Form
| FQuasiquote Form
| FUnquote Form
| FSpliceUnquote Form
| FKeyword String
| FMeta (List, HashMap)
| FDeref Atom
deriving (Eq, Show)
newtype List = List [Form] deriving (Eq, Show)
newtype HashMap = HashMap (Map Key Form) deriving (Eq, Show)
data Key = StringKey MalString | KeywordKey String deriving (Eq, Ord, Show)
instance Printable Key where
malPrint (StringKey s) = malPrint s
malPrint (KeywordKey k) = ":" ++ k
data Atom = NumberAtom Integer
| StringAtom MalString
| SymbolAtom String
deriving (Eq, Show)
newtype MalString = MalString String deriving (Eq, Ord, Show)
instance Printable Form where
malPrint (FList l) = "(" ++ malPrint l ++ ")"
malPrint (FVector l) = "[" ++ malPrint l ++ "]"
malPrint (FHashMap m) = "{" ++ malPrint m ++ "}"
malPrint (FAtom a) = malPrint a
malPrint (FQuote q) = "(quote " ++ malPrint q ++ ")"
malPrint (FQuasiquote q) = "(quasiquote " ++ malPrint q ++ ")"
malPrint (FUnquote q) = "(unquote " ++ malPrint q ++ ")"
malPrint (FSpliceUnquote q) = "(splice-unquote " ++ malPrint q ++ ")"
malPrint (FKeyword s) = ":" ++ s
malPrint (FMeta (l, m)) = "(with-meta " ++ malPrint (FVector l) ++ " " ++
malPrint (FHashMap m) ++ ")"
malPrint (FDeref r) = "(deref " ++ malPrint r ++ ")"
instance Printable List where
malPrint (List fs) = intercalate " " $ map malPrint fs
instance Printable HashMap where
malPrint (HashMap m) = intercalate " " $ map pkv $ M.toList m
where pkv (k, v) = malPrint k ++ " " ++ malPrint v
instance Printable Atom where
malPrint (NumberAtom n) = show n
malPrint (StringAtom s) = malPrint s
malPrint (SymbolAtom s) = s
instance Printable MalString where
malPrint (MalString s) = show s
|
joncol/mal
|
haskell/step2/src/MalTypes.hs
|
mpl-2.0
| 2,182
| 0
| 12
| 647
| 770
| 398
| 372
| 52
| 0
|
{-# OPTIONS_GHC -fglasgow-exts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Morphism.Exo
-- Copyright : (C) 2008 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable (rank-2 polymorphism)
--
-- Martin Erwig's exomorphism
----------------------------------------------------------------------------
module Control.Morphism.Exo
( exo
) where
import Control.Functor.Algebra
import Control.Morphism.Hylo
-- | Martin Erwig's exomorphism from d to d'
exo :: Functor h => Bialgebra m n b -> (h b -> m b) -> (h a -> h (g a)) -> Trialgebra f g h a -> g a -> b
exo d' f g d = hylo (fst d' . f) id (g . snd d)
|
urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav
|
Control/Morphism/Exo.hs
|
apache-2.0
| 802
| 4
| 13
| 143
| 166
| 91
| 75
| 7
| 1
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="az-AZ">
<title>Tips and Tricks | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>İndeks</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Axtar</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/tips/src/main/javahelp/org/zaproxy/zap/extension/tips/resources/help_az_AZ/helpset_az_AZ.hs
|
apache-2.0
| 978
| 92
| 29
| 161
| 404
| 214
| 190
| -1
| -1
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE RecordWildCards #-}
module HEP.Kinematics.Variable.MT2 (mT2) where
import HEP.Kinematics hiding (invariantMassSq)
import HEP.Kinematics.Vector.LorentzVector (invariantMassSq)
import Control.Lens ((^.))
import Control.Monad.Trans.Class (MonadTrans (..))
import Control.Monad.Trans.Reader
import Control.Monad.Trans.State.Strict
import Linear.Matrix (M33, det33)
import Linear.V3
data Input = Input { visible1 :: !FourMomentum
, visible2 :: !FourMomentum
, missing :: !TransverseMomentum
, mInvisible1 :: !Mass
, mInvisible2 :: !Mass
, precision :: !Double
, useDeciSections :: !Bool }
-- | calculates MT2.
--
-- This uses the algorithm in <http://arxiv.org/abs/1411.4312 arXiv:1411.4312>
-- by C.G. Lester and B. Nachman.
mT2 :: FourMomentum -> FourMomentum -> TransverseMomentum -> Mass -> Mass
-> Double -> Bool -> Mass
mT2 vis1 vis2 miss mInv1 mInv2 pre sec =
let mVis1 = mass vis1
mVis2 = mass vis2
getScale v = let !ptv = pt v in ptv * ptv
!s = sqrt $ (getScale vis1 + getScale vis2 + getScale miss
+ mVis1 * mVis1 + mInv1 * mInv1
+ mVis2 * mVis2 + mInv2 * mInv2) / 8.0
m1Min = mVis1 + mInv1
m2Min = mVis2 + mInv2
in if m2Min > m1Min
then mT2' m2Min s (Input vis1 vis2 miss mInv1 mInv2 pre sec)
else mT2' m1Min s (Input vis2 vis1 miss mInv2 mInv1 pre sec)
mT2' :: Mass -> Double -> Input -> Mass
mT2' mMin scale input@Input {..} =
let mLower = mMin
mUpper = runReader (growUpper (mMin + scale)) input
in case mUpper of
Nothing -> -1
Just m -> runReader (evalStateT (bisect useDeciSections) (mLower, m))
input
growUpper :: Mass -> Reader Input (Maybe Mass)
growUpper mUpper = do
Input {..} <- ask
let side1 = mkEllipse mUpper mInvisible1 (-visible1) zero
side2 = mkEllipse mUpper mInvisible2 visible2 missing
case ellipsesAreDisjoint side1 side2 of
Nothing -> return Nothing
Just False -> return (Just mUpper)
Just _ -> growUpper $! mUpper * 2
bisect :: Bool -> StateT (Mass, Mass) (Reader Input) Mass
bisect sec = do
(mLower, mUpper) <- get
Input {..} <- lift ask
if mUpper - mLower <= precision
then return $! (mLower + mUpper) * 0.5
else do let trialM = if sec
then (mLower * 15 + mUpper) / 16
else (mLower + mUpper) * 0.5
if trialM <= mLower || trialM >= mUpper
then return trialM
else do
let side1 = mkEllipse trialM mInvisible1 (-visible1) zero
side2 = mkEllipse trialM mInvisible2 visible2 missing
case ellipsesAreDisjoint side1 side2 of
Nothing -> return mLower
Just False -> put (mLower, trialM) >> bisect sec
Just _ -> put (trialM, mUpper) >> bisect False
type CoeffMatrix = M33 Double
mkEllipse :: Mass -- ^ The test parent mass
-> Mass -- ^ The mass of the inivisible particle
-> FourMomentum -> TransverseMomentum -> Maybe CoeffMatrix
mkEllipse m mInv vis inv =
let mVisSq = invariantMassSq vis
mInvSq = mInv * mInv
mSq = m * m
!(px', py') = pxpy vis
!(kx', ky') = pxpy inv
!axx = 4 * (mVisSq + py' * py')
!ayy = 4 * (mVisSq + px' * px')
!axy = - 4 * px' * py'
!ax = - 4 * mVisSq * kx' - 2 * mInvSq * px' + 2 * mSq * px'
- 2 * mVisSq * px' + 4 * ky' * px' * py' - 4 * kx' * py' * py'
!ay = - 4 * mVisSq * ky' - 4 * ky' * px' * px' - 2 * mInvSq * py'
+ 2 * mSq * py' - 2 * mVisSq * py' + 4 * kx' * px' * py'
!az = - mInvSq * mInvSq + 2 * mInvSq * mSq
- mSq * mSq + 2 * mInvSq * mVisSq
+ 2 * mSq * mVisSq - mVisSq * mVisSq
- 4 * mSq * (kx' * px' + ky' * py')
+ 4 * mVisSq * (kx' * kx' + ky' * ky' + kx' * px' + ky' * py')
+ 4 * mInvSq * (px' * px' + py' * py' + kx' * px' + ky' * py')
+ 4 * (ky' * ky' * px' * px' + kx' * kx' * py' * py')
- 8 * kx' * ky' * px' * py'
in mkCoeffMatrix axx ayy axy ax ay az
mkCoeffMatrix :: Double -> Double -> Double -> Double -> Double -> Double
-> Maybe CoeffMatrix
mkCoeffMatrix axx ayy axy ax ay az | axx < 0 || ayy < 0 = Nothing
| otherwise = do
let row1 = V3 axx axy ax
row2 = V3 axy ayy ay
row3 = V3 ax ay az
return (V3 row1 row2 row3)
cxx, cxy, cx, cyy, cy, cz :: CoeffMatrix -> Double
cxx = (^._x._x)
cxy = (^._x._y)
cx = (^._x._z)
cyy = (^._y._y)
cy = (^._y._z)
cz = (^._z._z)
coeffLamPow :: CoeffMatrix -> CoeffMatrix -> [Double]
coeffLamPow m1 m2 =
let coeffLamPow3 = det33 m1
coeffLamPow2 = coeff12 m1 m2
coeffLamPow1 = coeff12 m2 m1
coeffLamPow0 = det33 m2
coeffLamPow' = [coeffLamPow3, coeffLamPow2, coeffLamPow1, coeffLamPow0]
in if abs coeffLamPow3 >= abs coeffLamPow0
then coeffLamPow'
else reverse coeffLamPow'
where
coeff12 m1' m2' = let axx = cxx m1'; axy = cxy m1'; ayy = cyy m1'
ax = cx m1'; ay = cy m1'; a = cz m1'
bxx = cxx m2'; bxy = cxy m2'; byy = cyy m2'
bx = cx m2'; by = cy m2'; b = cz m2'
in axx * ayy * b + 2.0 * axy * ay * bx - 2 * ax * ayy * bx
+ a * ayy * bxx - 2 * a * axy * bxy + 2 * ax * ay * bxy
+ 2 * ax * axy * by - 2 * axx * ay * by + a * axx * byy
- byy * ax * ax - b * axy * axy - bxx * ay * ay
ellipsesAreDisjoint :: Maybe CoeffMatrix -> Maybe CoeffMatrix -> Maybe Bool
ellipsesAreDisjoint Nothing _ = Nothing
ellipsesAreDisjoint _ Nothing = Nothing
ellipsesAreDisjoint (Just m1) (Just m2)
| m1 == m2 = return False
| otherwise = do
let [c3, c2, c1, c0] = coeffLamPow m1 m2
case c3 of
0 -> Nothing
_ -> do let [a, b, c] = map (/ c3) [c2, c1, c0]
s2 = - 3 * b + a * a
s4 = - 27 * c * c + 18 * c * a * b + a * a * b * b
- 4 * c * a ** 3 - 4 * b ** 3
return $ not (s2 <= 0 || s4 <= 0)
&& (a < 0 || 3 * a * c + b * a * a - 4 * b * b < 0)
|
cbpark/hep-kinematics
|
src/HEP/Kinematics/Variable/MT2.hs
|
bsd-3-clause
| 6,934
| 0
| 49
| 2,796
| 2,482
| 1,276
| 1,206
| 155
| 6
|
{-# LANGUAGE CPP, MagicHash, NondecreasingIndentation, UnboxedTuples,
RecordWildCards, BangPatterns #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2005-2007
--
-- Running statements interactively
--
-- -----------------------------------------------------------------------------
module InteractiveEval (
Resume(..), History(..),
execStmt, ExecOptions(..), execOptions, ExecResult(..), resumeExec,
runDecls, runDeclsWithLocation,
isStmt, hasImport, isImport, isDecl,
parseImportDecl, SingleStep(..),
abandon, abandonAll,
getResumeContext,
getHistorySpan,
getModBreaks,
getHistoryModule,
back, forward,
setContext, getContext,
availsToGlobalRdrEnv,
getNamesInScope,
getRdrNamesInScope,
moduleIsInterpreted,
getInfo,
exprType,
typeKind,
parseName,
showModule,
moduleIsBootOrNotObjectLinkable,
parseExpr, compileParsedExpr,
compileExpr, dynCompileExpr,
compileExprRemote, compileParsedExprRemote,
Term(..), obtainTermFromId, obtainTermFromVal, reconstructType
) where
#include "HsVersions.h"
import GhcPrelude
import InteractiveEvalTypes
import GHCi
import GHCi.Message
import GHCi.RemoteTypes
import GhcMonad
import HscMain
import HsSyn
import HscTypes
import InstEnv
import IfaceEnv ( newInteractiveBinder )
import FamInstEnv ( FamInst )
import CoreFVs ( orphNamesOfFamInst )
import TyCon
import Type hiding( typeKind )
import RepType
import TcType hiding( typeKind )
import Var
import Id
import Name hiding ( varName )
import NameSet
import Avail
import RdrName
import VarEnv
import ByteCodeTypes
import Linker
import DynFlags
import Unique
import UniqSupply
import MonadUtils
import Module
import PrelNames ( toDynName, pretendNameIsInScope )
import Panic
import Maybes
import ErrUtils
import SrcLoc
import RtClosureInspect
import Outputable
import FastString
import Bag
import Util
import qualified Lexer (P (..), ParseResult(..), unP, mkPState)
import qualified Parser (parseStmt, parseModule, parseDeclaration, parseImport)
import System.Directory
import Data.Dynamic
import Data.Either
import qualified Data.IntMap as IntMap
import Data.List (find,intercalate)
import StringBuffer (stringToStringBuffer)
import Control.Monad
import GHC.Exts
import Data.Array
import Exception
-- -----------------------------------------------------------------------------
-- running a statement interactively
getResumeContext :: GhcMonad m => m [Resume]
getResumeContext = withSession (return . ic_resume . hsc_IC)
mkHistory :: HscEnv -> ForeignHValue -> BreakInfo -> History
mkHistory hsc_env hval bi = History hval bi (findEnclosingDecls hsc_env bi)
getHistoryModule :: History -> Module
getHistoryModule = breakInfo_module . historyBreakInfo
getHistorySpan :: HscEnv -> History -> SrcSpan
getHistorySpan hsc_env History{..} =
let BreakInfo{..} = historyBreakInfo in
case lookupHpt (hsc_HPT hsc_env) (moduleName breakInfo_module) of
Just hmi -> modBreaks_locs (getModBreaks hmi) ! breakInfo_number
_ -> panic "getHistorySpan"
getModBreaks :: HomeModInfo -> ModBreaks
getModBreaks hmi
| Just linkable <- hm_linkable hmi,
[BCOs cbc _] <- linkableUnlinked linkable
= fromMaybe emptyModBreaks (bc_breaks cbc)
| otherwise
= emptyModBreaks -- probably object code
{- | Finds the enclosing top level function name -}
-- ToDo: a better way to do this would be to keep hold of the decl_path computed
-- by the coverage pass, which gives the list of lexically-enclosing bindings
-- for each tick.
findEnclosingDecls :: HscEnv -> BreakInfo -> [String]
findEnclosingDecls hsc_env (BreakInfo modl ix) =
let hmi = expectJust "findEnclosingDecls" $
lookupHpt (hsc_HPT hsc_env) (moduleName modl)
mb = getModBreaks hmi
in modBreaks_decls mb ! ix
-- | Update fixity environment in the current interactive context.
updateFixityEnv :: GhcMonad m => FixityEnv -> m ()
updateFixityEnv fix_env = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
setSession $ hsc_env { hsc_IC = ic { ic_fix_env = fix_env } }
-- -----------------------------------------------------------------------------
-- execStmt
-- | default ExecOptions
execOptions :: ExecOptions
execOptions = ExecOptions
{ execSingleStep = RunToCompletion
, execSourceFile = "<interactive>"
, execLineNumber = 1
, execWrap = EvalThis -- just run the statement, don't wrap it in anything
}
-- | Run a statement in the current interactive context.
execStmt
:: GhcMonad m
=> String -- ^ a statement (bind or expression)
-> ExecOptions
-> m ExecResult
execStmt stmt ExecOptions{..} = do
hsc_env <- getSession
-- Turn off -fwarn-unused-local-binds when running a statement, to hide
-- warnings about the implicit bindings we introduce.
let ic = hsc_IC hsc_env -- use the interactive dflags
idflags' = ic_dflags ic `wopt_unset` Opt_WarnUnusedLocalBinds
hsc_env' = hsc_env{ hsc_IC = ic{ ic_dflags = idflags' } }
-- compile to value (IO [HValue]), don't run
r <- liftIO $ hscStmtWithLocation hsc_env' stmt
execSourceFile execLineNumber
case r of
-- empty statement / comment
Nothing -> return (ExecComplete (Right []) 0)
Just (ids, hval, fix_env) -> do
updateFixityEnv fix_env
status <-
withVirtualCWD $
liftIO $
evalStmt hsc_env' (isStep execSingleStep) (execWrap hval)
let ic = hsc_IC hsc_env
bindings = (ic_tythings ic, ic_rn_gbl_env ic)
size = ghciHistSize idflags'
handleRunStatus execSingleStep stmt bindings ids
status (emptyHistory size)
runDecls :: GhcMonad m => String -> m [Name]
runDecls = runDeclsWithLocation "<interactive>" 1
-- | Run some declarations and return any user-visible names that were brought
-- into scope.
runDeclsWithLocation :: GhcMonad m => String -> Int -> String -> m [Name]
runDeclsWithLocation source linenumber expr =
do
hsc_env <- getSession
(tyThings, ic) <- liftIO $ hscDeclsWithLocation hsc_env expr source linenumber
setSession $ hsc_env { hsc_IC = ic }
hsc_env <- getSession
hsc_env' <- liftIO $ rttiEnvironment hsc_env
setSession hsc_env'
return $ filter (not . isDerivedOccName . nameOccName)
-- For this filter, see Note [What to show to users]
$ map getName tyThings
{- Note [What to show to users]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't want to display internally-generated bindings to users.
Things like the coercion axiom for newtypes. These bindings all get
OccNames that users can't write, to avoid the possiblity of name
clashes (in linker symbols). That gives a convenient way to suppress
them. The relevant predicate is OccName.isDerivedOccName.
See Trac #11051 for more background and examples.
-}
withVirtualCWD :: GhcMonad m => m a -> m a
withVirtualCWD m = do
hsc_env <- getSession
-- a virtual CWD is only necessary when we're running interpreted code in
-- the same process as the compiler.
if gopt Opt_ExternalInterpreter (hsc_dflags hsc_env) then m else do
let ic = hsc_IC hsc_env
let set_cwd = do
dir <- liftIO $ getCurrentDirectory
case ic_cwd ic of
Just dir -> liftIO $ setCurrentDirectory dir
Nothing -> return ()
return dir
reset_cwd orig_dir = do
virt_dir <- liftIO $ getCurrentDirectory
hsc_env <- getSession
let old_IC = hsc_IC hsc_env
setSession hsc_env{ hsc_IC = old_IC{ ic_cwd = Just virt_dir } }
liftIO $ setCurrentDirectory orig_dir
gbracket set_cwd reset_cwd $ \_ -> m
parseImportDecl :: GhcMonad m => String -> m (ImportDecl GhcPs)
parseImportDecl expr = withSession $ \hsc_env -> liftIO $ hscImport hsc_env expr
emptyHistory :: Int -> BoundedList History
emptyHistory size = nilBL size
handleRunStatus :: GhcMonad m
=> SingleStep -> String-> ([TyThing],GlobalRdrEnv) -> [Id]
-> EvalStatus_ [ForeignHValue] [HValueRef]
-> BoundedList History
-> m ExecResult
handleRunStatus step expr bindings final_ids status history
| RunAndLogSteps <- step = tracing
| otherwise = not_tracing
where
tracing
| EvalBreak is_exception apStack_ref ix mod_uniq resume_ctxt _ccs <- status
, not is_exception
= do
hsc_env <- getSession
let hmi = expectJust "handleRunStatus" $
lookupHptDirectly (hsc_HPT hsc_env)
(mkUniqueGrimily mod_uniq)
modl = mi_module (hm_iface hmi)
breaks = getModBreaks hmi
b <- liftIO $
breakpointStatus hsc_env (modBreaks_flags breaks) ix
if b
then not_tracing
-- This breakpoint is explicitly enabled; we want to stop
-- instead of just logging it.
else do
apStack_fhv <- liftIO $ mkFinalizedHValue hsc_env apStack_ref
let bi = BreakInfo modl ix
!history' = mkHistory hsc_env apStack_fhv bi `consBL` history
-- history is strict, otherwise our BoundedList is pointless.
fhv <- liftIO $ mkFinalizedHValue hsc_env resume_ctxt
status <- liftIO $ GHCi.resumeStmt hsc_env True fhv
handleRunStatus RunAndLogSteps expr bindings final_ids
status history'
| otherwise
= not_tracing
not_tracing
-- Hit a breakpoint
| EvalBreak is_exception apStack_ref ix mod_uniq resume_ctxt ccs <- status
= do
hsc_env <- getSession
resume_ctxt_fhv <- liftIO $ mkFinalizedHValue hsc_env resume_ctxt
apStack_fhv <- liftIO $ mkFinalizedHValue hsc_env apStack_ref
let hmi = expectJust "handleRunStatus" $
lookupHptDirectly (hsc_HPT hsc_env)
(mkUniqueGrimily mod_uniq)
modl = mi_module (hm_iface hmi)
bp | is_exception = Nothing
| otherwise = Just (BreakInfo modl ix)
(hsc_env1, names, span, decl) <- liftIO $
bindLocalsAtBreakpoint hsc_env apStack_fhv bp
let
resume = Resume
{ resumeStmt = expr, resumeContext = resume_ctxt_fhv
, resumeBindings = bindings, resumeFinalIds = final_ids
, resumeApStack = apStack_fhv
, resumeBreakInfo = bp
, resumeSpan = span, resumeHistory = toListBL history
, resumeDecl = decl
, resumeCCS = ccs
, resumeHistoryIx = 0 }
hsc_env2 = pushResume hsc_env1 resume
setSession hsc_env2
return (ExecBreak names bp)
-- Completed successfully
| EvalComplete allocs (EvalSuccess hvals) <- status
= do hsc_env <- getSession
let final_ic = extendInteractiveContextWithIds (hsc_IC hsc_env) final_ids
final_names = map getName final_ids
liftIO $ Linker.extendLinkEnv (zip final_names hvals)
hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic}
setSession hsc_env'
return (ExecComplete (Right final_names) allocs)
-- Completed with an exception
| EvalComplete alloc (EvalException e) <- status
= return (ExecComplete (Left (fromSerializableException e)) alloc)
| otherwise
= panic "not_tracing" -- actually exhaustive, but GHC can't tell
resumeExec :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m ExecResult
resumeExec canLogSpan step
= do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> liftIO $
throwGhcExceptionIO (ProgramError "not stopped at a breakpoint")
(r:rs) -> do
-- unbind the temporary locals by restoring the TypeEnv from
-- before the breakpoint, and drop this Resume from the
-- InteractiveContext.
let (resume_tmp_te,resume_rdr_env) = resumeBindings r
ic' = ic { ic_tythings = resume_tmp_te,
ic_rn_gbl_env = resume_rdr_env,
ic_resume = rs }
setSession hsc_env{ hsc_IC = ic' }
-- remove any bindings created since the breakpoint from the
-- linker's environment
let old_names = map getName resume_tmp_te
new_names = [ n | thing <- ic_tythings ic
, let n = getName thing
, not (n `elem` old_names) ]
liftIO $ Linker.deleteFromLinkEnv new_names
case r of
Resume { resumeStmt = expr, resumeContext = fhv
, resumeBindings = bindings, resumeFinalIds = final_ids
, resumeApStack = apStack, resumeBreakInfo = mb_brkpt
, resumeSpan = span
, resumeHistory = hist } -> do
withVirtualCWD $ do
status <- liftIO $ GHCi.resumeStmt hsc_env (isStep step) fhv
let prevHistoryLst = fromListBL 50 hist
hist' = case mb_brkpt of
Nothing -> prevHistoryLst
Just bi
| not $canLogSpan span -> prevHistoryLst
| otherwise -> mkHistory hsc_env apStack bi `consBL`
fromListBL 50 hist
handleRunStatus step expr bindings final_ids status hist'
back :: GhcMonad m => Int -> m ([Name], Int, SrcSpan, String)
back n = moveHist (+n)
forward :: GhcMonad m => Int -> m ([Name], Int, SrcSpan, String)
forward n = moveHist (subtract n)
moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan, String)
moveHist fn = do
hsc_env <- getSession
case ic_resume (hsc_IC hsc_env) of
[] -> liftIO $
throwGhcExceptionIO (ProgramError "not stopped at a breakpoint")
(r:rs) -> do
let ix = resumeHistoryIx r
history = resumeHistory r
new_ix = fn ix
--
when (history `lengthLessThan` new_ix) $ liftIO $
throwGhcExceptionIO (ProgramError "no more logged breakpoints")
when (new_ix < 0) $ liftIO $
throwGhcExceptionIO (ProgramError "already at the beginning of the history")
let
update_ic apStack mb_info = do
(hsc_env1, names, span, decl) <-
liftIO $ bindLocalsAtBreakpoint hsc_env apStack mb_info
let ic = hsc_IC hsc_env1
r' = r { resumeHistoryIx = new_ix }
ic' = ic { ic_resume = r':rs }
setSession hsc_env1{ hsc_IC = ic' }
return (names, new_ix, span, decl)
-- careful: we want apStack to be the AP_STACK itself, not a thunk
-- around it, hence the cases are carefully constructed below to
-- make this the case. ToDo: this is v. fragile, do something better.
if new_ix == 0
then case r of
Resume { resumeApStack = apStack,
resumeBreakInfo = mb_brkpt } ->
update_ic apStack mb_brkpt
else case history !! (new_ix - 1) of
History{..} ->
update_ic historyApStack (Just historyBreakInfo)
-- -----------------------------------------------------------------------------
-- After stopping at a breakpoint, add free variables to the environment
result_fs :: FastString
result_fs = fsLit "_result"
bindLocalsAtBreakpoint
:: HscEnv
-> ForeignHValue
-> Maybe BreakInfo
-> IO (HscEnv, [Name], SrcSpan, String)
-- Nothing case: we stopped when an exception was raised, not at a
-- breakpoint. We have no location information or local variables to
-- bind, all we can do is bind a local variable to the exception
-- value.
bindLocalsAtBreakpoint hsc_env apStack Nothing = do
let exn_occ = mkVarOccFS (fsLit "_exception")
span = mkGeneralSrcSpan (fsLit "<unknown>")
exn_name <- newInteractiveBinder hsc_env exn_occ span
let e_fs = fsLit "e"
e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
e_tyvar = mkRuntimeUnkTyVar e_name liftedTypeKind
exn_id = Id.mkVanillaGlobal exn_name (mkTyVarTy e_tyvar)
ictxt0 = hsc_IC hsc_env
ictxt1 = extendInteractiveContextWithIds ictxt0 [exn_id]
--
Linker.extendLinkEnv [(exn_name, apStack)]
return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span, "<exception thrown>")
-- Just case: we stopped at a breakpoint, we have information about the location
-- of the breakpoint and the free variables of the expression.
bindLocalsAtBreakpoint hsc_env apStack_fhv (Just BreakInfo{..}) = do
let
hmi = expectJust "bindLocalsAtBreakpoint" $
lookupHpt (hsc_HPT hsc_env) (moduleName breakInfo_module)
breaks = getModBreaks hmi
info = expectJust "bindLocalsAtBreakpoint2" $
IntMap.lookup breakInfo_number (modBreaks_breakInfo breaks)
vars = cgb_vars info
result_ty = cgb_resty info
occs = modBreaks_vars breaks ! breakInfo_number
span = modBreaks_locs breaks ! breakInfo_number
decl = intercalate "." $ modBreaks_decls breaks ! breakInfo_number
-- Filter out any unboxed ids;
-- we can't bind these at the prompt
pointers = filter (\(id,_) -> isPointer id) vars
isPointer id | [rep] <- typePrimRep (idType id)
, isGcPtrRep rep = True
| otherwise = False
(ids, offsets) = unzip pointers
free_tvs = tyCoVarsOfTypesList (result_ty:map idType ids)
-- It might be that getIdValFromApStack fails, because the AP_STACK
-- has been accidentally evaluated, or something else has gone wrong.
-- So that we don't fall over in a heap when this happens, just don't
-- bind any free variables instead, and we emit a warning.
mb_hValues <-
mapM (getBreakpointVar hsc_env apStack_fhv . fromIntegral) offsets
when (any isNothing mb_hValues) $
debugTraceMsg (hsc_dflags hsc_env) 1 $
text "Warning: _result has been evaluated, some bindings have been lost"
us <- mkSplitUniqSupply 'I' -- Dodgy; will give the same uniques every time
let tv_subst = newTyVars us free_tvs
filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
(_,tidy_tys) = tidyOpenTypes emptyTidyEnv $
map (substTy tv_subst . idType) filtered_ids
new_ids <- zipWith3M mkNewId occs tidy_tys filtered_ids
result_name <- newInteractiveBinder hsc_env (mkVarOccFS result_fs) span
let result_id = Id.mkVanillaGlobal result_name
(substTy tv_subst result_ty)
result_ok = isPointer result_id
final_ids | result_ok = result_id : new_ids
| otherwise = new_ids
ictxt0 = hsc_IC hsc_env
ictxt1 = extendInteractiveContextWithIds ictxt0 final_ids
names = map idName new_ids
let fhvs = catMaybes mb_hValues
Linker.extendLinkEnv (zip names fhvs)
when result_ok $ Linker.extendLinkEnv [(result_name, apStack_fhv)]
hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
return (hsc_env1, if result_ok then result_name:names else names, span, decl)
where
-- We need a fresh Unique for each Id we bind, because the linker
-- state is single-threaded and otherwise we'd spam old bindings
-- whenever we stop at a breakpoint. The InteractveContext is properly
-- saved/restored, but not the linker state. See #1743, test break026.
mkNewId :: OccName -> Type -> Id -> IO Id
mkNewId occ ty old_id
= do { name <- newInteractiveBinder hsc_env occ (getSrcSpan old_id)
; return (Id.mkVanillaGlobalWithInfo name ty (idInfo old_id)) }
newTyVars :: UniqSupply -> [TcTyVar] -> TCvSubst
-- Similarly, clone the type variables mentioned in the types
-- we have here, *and* make them all RuntimeUnk tyvars
newTyVars us tvs
= mkTvSubstPrs [ (tv, mkTyVarTy (mkRuntimeUnkTyVar name (tyVarKind tv)))
| (tv, uniq) <- tvs `zip` uniqsFromSupply us
, let name = setNameUnique (tyVarName tv) uniq ]
rttiEnvironment :: HscEnv -> IO HscEnv
rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
let tmp_ids = [id | AnId id <- ic_tythings ic]
incompletelyTypedIds =
[id | id <- tmp_ids
, not $ noSkolems id
, (occNameFS.nameOccName.idName) id /= result_fs]
hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds)
return hsc_env'
where
noSkolems = noFreeVarsOfType . idType
improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do
let tmp_ids = [id | AnId id <- ic_tythings ic]
Just id = find (\i -> idName i == name) tmp_ids
if noSkolems id
then return hsc_env
else do
mb_new_ty <- reconstructType hsc_env 10 id
let old_ty = idType id
case mb_new_ty of
Nothing -> return hsc_env
Just new_ty -> do
case improveRTTIType hsc_env old_ty new_ty of
Nothing -> return $
WARN(True, text (":print failed to calculate the "
++ "improvement for a type")) hsc_env
Just subst -> do
let dflags = hsc_dflags hsc_env
when (dopt Opt_D_dump_rtti dflags) $
printInfoForUser dflags alwaysQualify $
fsep [text "RTTI Improvement for", ppr id, equals, ppr subst]
let ic' = substInteractiveContext ic subst
return hsc_env{hsc_IC=ic'}
pushResume :: HscEnv -> Resume -> HscEnv
pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
where
ictxt0 = hsc_IC hsc_env
ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
-- -----------------------------------------------------------------------------
-- Abandoning a resume context
abandon :: GhcMonad m => m Bool
abandon = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> return False
r:rs -> do
setSession hsc_env{ hsc_IC = ic { ic_resume = rs } }
liftIO $ abandonStmt hsc_env (resumeContext r)
return True
abandonAll :: GhcMonad m => m Bool
abandonAll = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> return False
rs -> do
setSession hsc_env{ hsc_IC = ic { ic_resume = [] } }
liftIO $ mapM_ (abandonStmt hsc_env. resumeContext) rs
return True
-- -----------------------------------------------------------------------------
-- Bounded list, optimised for repeated cons
data BoundedList a = BL
{-# UNPACK #-} !Int -- length
{-# UNPACK #-} !Int -- bound
[a] -- left
[a] -- right, list is (left ++ reverse right)
nilBL :: Int -> BoundedList a
nilBL bound = BL 0 bound [] []
consBL :: a -> BoundedList a -> BoundedList a
consBL a (BL len bound left right)
| len < bound = BL (len+1) bound (a:left) right
| null right = BL len bound [a] $! tail (reverse left)
| otherwise = BL len bound (a:left) $! tail right
toListBL :: BoundedList a -> [a]
toListBL (BL _ _ left right) = left ++ reverse right
fromListBL :: Int -> [a] -> BoundedList a
fromListBL bound l = BL (length l) bound l []
-- lenBL (BL len _ _ _) = len
-- -----------------------------------------------------------------------------
-- | Set the interactive evaluation context.
--
-- (setContext imports) sets the ic_imports field (which in turn
-- determines what is in scope at the prompt) to 'imports', and
-- constructs the ic_rn_glb_env environment to reflect it.
--
-- We retain in scope all the things defined at the prompt, and kept
-- in ic_tythings. (Indeed, they shadow stuff from ic_imports.)
setContext :: GhcMonad m => [InteractiveImport] -> m ()
setContext imports
= do { hsc_env <- getSession
; let dflags = hsc_dflags hsc_env
; all_env_err <- liftIO $ findGlobalRdrEnv hsc_env imports
; case all_env_err of
Left (mod, err) ->
liftIO $ throwGhcExceptionIO (formatError dflags mod err)
Right all_env -> do {
; let old_ic = hsc_IC hsc_env
!final_rdr_env = all_env `icExtendGblRdrEnv` ic_tythings old_ic
; setSession
hsc_env{ hsc_IC = old_ic { ic_imports = imports
, ic_rn_gbl_env = final_rdr_env }}}}
where
formatError dflags mod err = ProgramError . showSDoc dflags $
text "Cannot add module" <+> ppr mod <+>
text "to context:" <+> text err
findGlobalRdrEnv :: HscEnv -> [InteractiveImport]
-> IO (Either (ModuleName, String) GlobalRdrEnv)
-- Compute the GlobalRdrEnv for the interactive context
findGlobalRdrEnv hsc_env imports
= do { idecls_env <- hscRnImportDecls hsc_env idecls
-- This call also loads any orphan modules
; return $ case partitionEithers (map mkEnv imods) of
([], imods_env) -> Right (foldr plusGlobalRdrEnv idecls_env imods_env)
(err : _, _) -> Left err }
where
idecls :: [LImportDecl GhcPs]
idecls = [noLoc d | IIDecl d <- imports]
imods :: [ModuleName]
imods = [m | IIModule m <- imports]
mkEnv mod = case mkTopLevEnv (hsc_HPT hsc_env) mod of
Left err -> Left (mod, err)
Right env -> Right env
availsToGlobalRdrEnv :: ModuleName -> [AvailInfo] -> GlobalRdrEnv
availsToGlobalRdrEnv mod_name avails
= mkGlobalRdrEnv (gresFromAvails (Just imp_spec) avails)
where
-- We're building a GlobalRdrEnv as if the user imported
-- all the specified modules into the global interactive module
imp_spec = ImpSpec { is_decl = decl, is_item = ImpAll}
decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
is_qual = False,
is_dloc = srcLocSpan interactiveSrcLoc }
mkTopLevEnv :: HomePackageTable -> ModuleName -> Either String GlobalRdrEnv
mkTopLevEnv hpt modl
= case lookupHpt hpt modl of
Nothing -> Left "not a home module"
Just details ->
case mi_globals (hm_iface details) of
Nothing -> Left "not interpreted"
Just env -> Right env
-- | Get the interactive evaluation context, consisting of a pair of the
-- set of modules from which we take the full top-level scope, and the set
-- of modules from which we take just the exports respectively.
getContext :: GhcMonad m => m [InteractiveImport]
getContext = withSession $ \HscEnv{ hsc_IC=ic } ->
return (ic_imports ic)
-- | Returns @True@ if the specified module is interpreted, and hence has
-- its full top-level scope available.
moduleIsInterpreted :: GhcMonad m => Module -> m Bool
moduleIsInterpreted modl = withSession $ \h ->
if moduleUnitId modl /= thisPackage (hsc_dflags h)
then return False
else case lookupHpt (hsc_HPT h) (moduleName modl) of
Just details -> return (isJust (mi_globals (hm_iface details)))
_not_a_home_module -> return False
-- | Looks up an identifier in the current interactive context (for :info)
-- Filter the instances by the ones whose tycons (or clases resp)
-- are in scope (qualified or otherwise). Otherwise we list a whole lot too many!
-- The exact choice of which ones to show, and which to hide, is a judgement call.
-- (see Trac #1581)
getInfo :: GhcMonad m => Bool -> Name
-> m (Maybe (TyThing,Fixity,[ClsInst],[FamInst], SDoc))
getInfo allInfo name
= withSession $ \hsc_env ->
do mb_stuff <- liftIO $ hscTcRnGetInfo hsc_env name
case mb_stuff of
Nothing -> return Nothing
Just (thing, fixity, cls_insts, fam_insts, docs) -> do
let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
-- Filter the instances based on whether the constituent names of their
-- instance heads are all in scope.
let cls_insts' = filter (plausible rdr_env . orphNamesOfClsInst) cls_insts
fam_insts' = filter (plausible rdr_env . orphNamesOfFamInst) fam_insts
return (Just (thing, fixity, cls_insts', fam_insts', docs))
where
plausible rdr_env names
-- Dfun involving only names that are in ic_rn_glb_env
= allInfo
|| nameSetAll ok names
where -- A name is ok if it's in the rdr_env,
-- whether qualified or not
ok n | n == name = True
-- The one we looked for in the first place!
| pretendNameIsInScope n = True
| isBuiltInSyntax n = True
| isExternalName n = isJust (lookupGRE_Name rdr_env n)
| otherwise = True
-- | Returns all names in scope in the current interactive context
getNamesInScope :: GhcMonad m => m [Name]
getNamesInScope = withSession $ \hsc_env -> do
return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
-- | Returns all 'RdrName's in scope in the current interactive
-- context, excluding any that are internally-generated.
getRdrNamesInScope :: GhcMonad m => m [RdrName]
getRdrNamesInScope = withSession $ \hsc_env -> do
let
ic = hsc_IC hsc_env
gbl_rdrenv = ic_rn_gbl_env ic
gbl_names = concatMap greRdrNames $ globalRdrEnvElts gbl_rdrenv
-- Exclude internally generated names; see e.g. Trac #11328
return (filter (not . isDerivedOccName . rdrNameOcc) gbl_names)
-- | Parses a string as an identifier, and returns the list of 'Name's that
-- the identifier can refer to in the current interactive context.
parseName :: GhcMonad m => String -> m [Name]
parseName str = withSession $ \hsc_env -> liftIO $
do { lrdr_name <- hscParseIdentifier hsc_env str
; hscTcRnLookupRdrName hsc_env lrdr_name }
-- | Returns @True@ if passed string is a statement.
isStmt :: DynFlags -> String -> Bool
isStmt dflags stmt =
case parseThing Parser.parseStmt dflags stmt of
Lexer.POk _ _ -> True
Lexer.PFailed _ _ _ -> False
-- | Returns @True@ if passed string has an import declaration.
hasImport :: DynFlags -> String -> Bool
hasImport dflags stmt =
case parseThing Parser.parseModule dflags stmt of
Lexer.POk _ thing -> hasImports thing
Lexer.PFailed _ _ _ -> False
where
hasImports = not . null . hsmodImports . unLoc
-- | Returns @True@ if passed string is an import declaration.
isImport :: DynFlags -> String -> Bool
isImport dflags stmt =
case parseThing Parser.parseImport dflags stmt of
Lexer.POk _ _ -> True
Lexer.PFailed _ _ _ -> False
-- | Returns @True@ if passed string is a declaration but __/not a splice/__.
isDecl :: DynFlags -> String -> Bool
isDecl dflags stmt = do
case parseThing Parser.parseDeclaration dflags stmt of
Lexer.POk _ thing ->
case unLoc thing of
SpliceD _ -> False
_ -> True
Lexer.PFailed _ _ _ -> False
parseThing :: Lexer.P thing -> DynFlags -> String -> Lexer.ParseResult thing
parseThing parser dflags stmt = do
let buf = stringToStringBuffer stmt
loc = mkRealSrcLoc (fsLit "<interactive>") 1 1
Lexer.unP parser (Lexer.mkPState dflags buf loc)
-- -----------------------------------------------------------------------------
-- Getting the type of an expression
-- | Get the type of an expression
-- Returns the type as described by 'TcRnExprMode'
exprType :: GhcMonad m => TcRnExprMode -> String -> m Type
exprType mode expr = withSession $ \hsc_env -> do
ty <- liftIO $ hscTcExpr hsc_env mode expr
return $ tidyType emptyTidyEnv ty
-- -----------------------------------------------------------------------------
-- Getting the kind of a type
-- | Get the kind of a type
typeKind :: GhcMonad m => Bool -> String -> m (Type, Kind)
typeKind normalise str = withSession $ \hsc_env -> do
liftIO $ hscKcType hsc_env normalise str
-----------------------------------------------------------------------------
-- Compile an expression, run it, and deliver the result
-- | Parse an expression, the parsed expression can be further processed and
-- passed to compileParsedExpr.
parseExpr :: GhcMonad m => String -> m (LHsExpr GhcPs)
parseExpr expr = withSession $ \hsc_env -> do
liftIO $ runInteractiveHsc hsc_env $ hscParseExpr expr
-- | Compile an expression, run it, and deliver the resulting HValue.
compileExpr :: GhcMonad m => String -> m HValue
compileExpr expr = do
parsed_expr <- parseExpr expr
compileParsedExpr parsed_expr
-- | Compile an expression, run it, and deliver the resulting HValue.
compileExprRemote :: GhcMonad m => String -> m ForeignHValue
compileExprRemote expr = do
parsed_expr <- parseExpr expr
compileParsedExprRemote parsed_expr
-- | Compile a parsed expression (before renaming), run it, and deliver
-- the resulting HValue.
compileParsedExprRemote :: GhcMonad m => LHsExpr GhcPs -> m ForeignHValue
compileParsedExprRemote expr@(L loc _) = withSession $ \hsc_env -> do
-- > let _compileParsedExpr = expr
-- Create let stmt from expr to make hscParsedStmt happy.
-- We will ignore the returned [Id], namely [expr_id], and not really
-- create a new binding.
let expr_fs = fsLit "_compileParsedExpr"
expr_name = mkInternalName (getUnique expr_fs) (mkTyVarOccFS expr_fs) loc
let_stmt = L loc . LetStmt . L loc . HsValBinds $
ValBindsIn (unitBag $ mkHsVarBind loc (getRdrName expr_name) expr) []
Just ([_id], hvals_io, fix_env) <- liftIO $ hscParsedStmt hsc_env let_stmt
updateFixityEnv fix_env
status <- liftIO $ evalStmt hsc_env False (EvalThis hvals_io)
case status of
EvalComplete _ (EvalSuccess [hval]) -> return hval
EvalComplete _ (EvalException e) ->
liftIO $ throwIO (fromSerializableException e)
_ -> panic "compileParsedExpr"
compileParsedExpr :: GhcMonad m => LHsExpr GhcPs -> m HValue
compileParsedExpr expr = do
fhv <- compileParsedExprRemote expr
dflags <- getDynFlags
liftIO $ wormhole dflags fhv
-- | Compile an expression, run it and return the result as a Dynamic.
dynCompileExpr :: GhcMonad m => String -> m Dynamic
dynCompileExpr expr = do
parsed_expr <- parseExpr expr
-- > Data.Dynamic.toDyn expr
let loc = getLoc parsed_expr
to_dyn_expr = mkHsApp (L loc . HsVar . L loc $ getRdrName toDynName)
parsed_expr
hval <- compileParsedExpr to_dyn_expr
return (unsafeCoerce# hval :: Dynamic)
-----------------------------------------------------------------------------
-- show a module and it's source/object filenames
showModule :: GhcMonad m => ModSummary -> m String
showModule mod_summary =
withSession $ \hsc_env -> do
interpreted <- moduleIsBootOrNotObjectLinkable mod_summary
let dflags = hsc_dflags hsc_env
return (showModMsg dflags (hscTarget dflags) interpreted mod_summary)
moduleIsBootOrNotObjectLinkable :: GhcMonad m => ModSummary -> m Bool
moduleIsBootOrNotObjectLinkable mod_summary = withSession $ \hsc_env ->
case lookupHpt (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
Nothing -> panic "missing linkable"
Just mod_info -> return $ case hm_linkable mod_info of
Nothing -> True
Just linkable -> not (isObjectLinkable linkable)
----------------------------------------------------------------------------
-- RTTI primitives
obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term
obtainTermFromVal hsc_env bound force ty x =
cvObtainTerm hsc_env bound force ty (unsafeCoerce# x)
obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term
obtainTermFromId hsc_env bound force id = do
let dflags = hsc_dflags hsc_env
hv <- Linker.getHValue hsc_env (varName id) >>= wormhole dflags
cvObtainTerm hsc_env bound force (idType id) hv
-- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
reconstructType hsc_env bound id = do
let dflags = hsc_dflags hsc_env
hv <- Linker.getHValue hsc_env (varName id) >>= wormhole dflags
cvReconstructType hsc_env bound (idType id) hv
mkRuntimeUnkTyVar :: Name -> Kind -> TyVar
mkRuntimeUnkTyVar name kind = mkTcTyVar name kind RuntimeUnk
|
shlevy/ghc
|
compiler/main/InteractiveEval.hs
|
bsd-3-clause
| 36,775
| 13
| 30
| 9,690
| 8,387
| 4,270
| 4,117
| 657
| 4
|
{-# LANGUAGE CPP, ScopedTypeVariables, OverloadedStrings, PatternGuards #-}
-- |
-- Module : Language.Haskell.BuildWrapper.API
-- Copyright : (c) JP Moresmau 2011
-- License : BSD3
--
-- Maintainer : jpmoresmau@gmail.com
-- Stability : beta
-- Portability : portable
--
-- API entry point, with all exposed methods
module Language.Haskell.BuildWrapper.API where
import Language.Haskell.BuildWrapper.Base
import Language.Haskell.BuildWrapper.Cabal
import qualified Language.Haskell.BuildWrapper.GHC as BwGHC
import Language.Haskell.BuildWrapper.GHCStorage
import Language.Haskell.BuildWrapper.Src
import qualified Data.Text as T
import qualified Data.HashMap.Lazy as HM
import qualified Data.Map as DM
import Data.List (sortBy)
import Prelude hiding (readFile, writeFile)
import qualified Data.Vector as V
import Control.Monad.State
import Language.Haskell.Exts.Annotated hiding (String)
import Language.Preprocessor.Cpphs
import Data.Maybe
import System.Directory
import System.FilePath
import GHC (TypecheckedSource, TypecheckedModule(..), Ghc, ms_mod, pm_mod_summary, moduleName, getSessionDynFlags, getSession)
import Data.Aeson
import Outputable (ppr)
import Data.Foldable (foldrM)
import qualified MonadUtils as GMU (liftIO)
import Control.Arrow (first)
-- | copy all files from the project to the temporary folder
synchronize :: Bool -- ^ if true copy all files, if false only copy files newer than their corresponding temp files
-> BuildWrapper(OpResult ([FilePath],[FilePath])) -- ^ return the list of files copied, the list of files deleted
synchronize force =do
cf<-gets cabalFile
(fileList,ns)<-getFilesToCopy
let fullFileList=takeFileName cf :
"Setup.hs":
"Setup.lhs":
fileList
m1<-mapM (copyFromMain force) fullFileList
del<-deleteGhosts fullFileList
return ((catMaybes m1,del), ns)
-- | synchronize one file only
synchronize1 :: Bool -- ^ always copy the file, if false only copy the file if it is newer than its corresponding temp file
-> FilePath -- ^ the source file in the project folder
-> BuildWrapper(Maybe FilePath) -- ^ return Nothing if no copy or Just file if copied
synchronize1 force fp = do
m1<-mapM (copyFromMain force) [fp]
return $ head m1
-- | write contents to temporary file
write :: FilePath -- ^ the source file in the project folder
-> String -- ^ the contents
-> BuildWrapper()
write fp s= do
real<-getTargetPath fp
--liftIO $ putStrLn ("contents:"++s)
liftIO $ writeFile real s
-- | run cabal configure
configure :: WhichCabal -- ^ use the source or temp cabal
-> BuildWrapper (OpResult Bool) -- ^ True if configure succeeded
configure which= do
(mlbi,msgs)<-cabalConfigure which
return (isJust mlbi,msgs)
-- | run cabal build
build :: Bool -- ^ do we want output (True) or just compilation without linking?
-> WhichCabal -- ^ use original cabal or temp cabal file
-> BuildWrapper (OpResult BuildResult)
build = cabalBuild
-- | generate usage information files
generateUsage :: Bool -- ^ should we return all files or only the changed ones?
-> String -- ^ the cabal component name
-> BuildWrapper(OpResult (Maybe [FilePath]))
generateUsage returnAll ccn=
withCabal Source (\lbi -> do
cbis<-getAllFiles lbi
cf<-gets cabalFile
temp<-getFullTempDir
let dir=takeDirectory cf
pkg<-liftM T.pack getPackageName
allMps<-mapM (\cbi->do
let
mps1=map (\(m,f)->(f,moduleToString $ fromJust m)) $ filter (isJust . fst) $ cbiModulePaths cbi
mps<-filterM (\(f,_)->do
fullSrc<-getFullSrc f
fullTgt<-getTargetPath f
let fullUsage=getUsageFile fullTgt
liftIO $ isSourceMoreRecent fullSrc fullUsage
) $ filter (\(f,_)->fitForUsage f
)
mps1
opts<-fileGhcOptions cbi
modules<-liftIO $ do
cd<-getCurrentDirectory
setCurrentDirectory dir
(mods,notes)<-BwGHC.withASTNotes (getModule pkg) (temp </>) dir (MultipleFile mps) opts
print notes
setCurrentDirectory cd
return mods
mapM_ (generate pkg) modules
return $ if returnAll then mps1 else mps
) $ filter (\cbi->cabalComponentName (cbiComponent cbi) == ccn) cbis
return $ map fst $ concat allMps
)
where
-- | fitForUsage
fitForUsage :: FilePath -> Bool
fitForUsage f
| takeDirectory f == "." && takeBaseName f == "Setup"=False -- exclude Setup
| otherwise=let ext=takeExtension f
in ext `elem` [".hs",".lhs"] -- only keep haskell files
-- | get module name and import/export usage information
getModule :: T.Text -- ^ the current package name
-> FilePath -- ^ the file to process
-> TypecheckedModule -- ^ the GHC typechecked module
-> Ghc(FilePath,T.Text,Value,[Usage])
getModule pkg f tm=do
let (hsg,imps,mexps,_)=fromJust $ tm_renamed_source tm
(ius,aliasMap)<-foldrM (BwGHC.ghcImportToUsage pkg) ([],DM.empty) imps
-- GMU.liftIO $ Prelude.print $ showSDoc $ ppr aliasMap
df <- getSessionDynFlags
env <- getSession
let modu=T.pack $ showSD True df $ ppr $ moduleName $ ms_mod $ pm_mod_summary $ tm_parsed_module tm
eus<-mapM (BwGHC.ghcExportToUsage df pkg modu aliasMap) (fromMaybe [] mexps)
--ms_mod $ pm_mod_summary $ tm_parsed_module tm
js<-GMU.liftIO $ dataToJSON df env tm hsg
return (f,modu,js,ius ++ concat eus)
-- | generate all usage information and stores it to file
generate :: T.Text -- ^ the current package name
-> (FilePath,T.Text,Value,[Usage]) -> BuildWrapper()
generate pkg (fp,modu,v,ius)
| modu=="Main" && ccn=="" = return () -- Main inside a library: do nothing
| otherwise = do
-- liftIO $ Prelude.putStrLn (show modu ++ ":" ++ show ccn)
tgt<-getTargetPath fp
--mv<-liftIO $ readGHCInfo tgt
-- let v = dataToJSON hsg
-- liftIO $ Prelude.putStrLn tgt
-- liftIO $ Prelude.putStrLn $ formatJSON $ BSC.unpack $ encode v
--case mv of
-- Just v->do
let vals=extractUsages v
--liftIO $ mapM_ (Prelude.putStrLn . formatJSON . BSC.unpack . encode) vals
(mast,_)<-getAST fp (Just ccn)
case mast of
Just (ParseOk ast)->do
let ods=getHSEOutline ast
--liftIO $ Prelude.print ods
let val=reconcile pkg vals ods ius
let (es,is)=getHSEImportExport ast
let modLoc=maybe Null toJSON (getModuleLocation ast)
let valWithModule=Array $ V.fromList [toJSON pkg,toJSON modu,modLoc,val,toJSON $ OutlineResult ods es is]
liftIO $ setUsageInfo tgt valWithModule
return ()
_ -> return ()
return ()
-- | reconcile AST, usage information and outline into one final usage object
reconcile :: T.Text -- ^ the current package name
-> [Value] -> [OutlineDef] -> [Usage] -> Value
reconcile pkg vals ods ius=let
mapOds=foldr mapOutline DM.empty ods
in foldr usageToJSON (object [])
(ius ++ concatMap (ghcValToUsage pkg mapOds) vals)
-- | store outline def by line
mapOutline :: OutlineDef -> DM.Map Int [OutlineDef] -> DM.Map Int [OutlineDef]
mapOutline od m=let
ifs=odLoc od
lins=[(iflLine $ ifsStart ifs) .. (iflLine $ ifsEnd ifs)]
m2=foldr (addOutline od) m lins
in foldr mapOutline m2 (odChildren od)
-- | add one outline def by line
addOutline :: OutlineDef -> Int -> DM.Map Int [OutlineDef] -> DM.Map Int [OutlineDef]
addOutline od l m=let
mods=DM.lookup l m
newOds=case mods of
Just ods->od:ods
Nothing->[od]
in DM.insert l newOds m
-- | translate Usage structure to JSON
usageToJSON :: Usage -> Value -> Value
usageToJSON u v@(Object pkgs) | Just pkg<-usagePackage u v=
let
(Object mods) = HM.lookupDefault (object []) pkg pkgs
(Object types)= HM.lookupDefault (object []) (usModule u) mods
typeKey=if usType u
then "types"
else "vars"
(Object names)= HM.lookupDefault (object []) typeKey types
nameKey=usName u
-- , ",", (usType u)
(Array lins)= HM.lookupDefault (Array V.empty) nameKey names
lineV= usLoc u -- Number $ I $ usLine u
objectV=object ["s" .= usSection u, "d" .= usDef u, "l" .= lineV]
lins2=if objectV `V.elem` lins
then lins
else V.cons objectV lins
names2=HM.insert nameKey (Array lins2) names
types2=HM.insert typeKey (Object names2) types
mods2=HM.insert (usModule u) (Object types2) mods
in Object $ HM.insert pkg (Object mods2) pkgs
usageToJSON _ a=a
-- | get the package for a given usage module
usagePackage :: Usage -> Value -> Maybe T.Text
usagePackage u (Object pkgs)=case usPackage u of
Just p->Just p
Nothing->let
modu=usModule u
matchingpkgs=HM.foldrWithKey (listPkgs modu) [] pkgs
in listToMaybe matchingpkgs
usagePackage _ _=Nothing
-- | list packages possible for module
listPkgs :: T.Text -> T.Text -> Value -> [T.Text] -> [T.Text]
listPkgs modu k (Object mods) l=if HM.member modu mods then k : l else l
listPkgs _ _ _ l=l
-- | translate GHC AST to Usages
ghcValToUsage :: T.Text -> DM.Map Int [OutlineDef] -> Value -> [Usage]
ghcValToUsage pkg mapOds (Object m) |
Just (String s)<-HM.lookup "Name" m,
Just (String mo)<-HM.lookup "Module" m,
not $ T.null mo, -- ignore local objects
Just (String p)<-HM.lookup "Package" m,
Just (String ht)<-HM.lookup "HType" m,
Just arr<-HM.lookup "Pos" m,
Success ifs <- fromJSON arr= let
mods=DM.lookup (iflLine $ ifsStart ifs) mapOds
(section,def)=getSection mods s ifs
in [Usage (Just (if p=="main" then pkg else p)) mo s section (ht=="t") arr def]
ghcValToUsage _ _ _=[]
-- | retrieve section name for given location, and whether what we reference is actually a reference, and in that case the comment
getSection :: Maybe [OutlineDef] -> T.Text -> InFileSpan -> (T.Text,Bool)
getSection (Just ods) objName ifs =let
matchods=filter (\od-> ifsOverlap (odLoc od) ifs) ods
-- most precise outline def
bestods=sortBy (\od1 od2->let
l1=iflLine $ ifsStart $ odLoc od1
l2=iflLine $ ifsStart $ odLoc od2
in case compare l2 l1 of
EQ -> let
c1=iflColumn $ ifsStart $ odLoc od1
c2=iflColumn $ ifsStart $ odLoc od2
in compare c2 c1
a-> a
) matchods
-- widest outline def (function type...)
widestods=sortBy (\od1 od2->let
l1=iflLine $ ifsStart $ odLoc od1
l2=iflLine $ ifsStart $ odLoc od2
in case compare l1 l2 of
EQ -> let
c1=iflColumn $ ifsStart $ odLoc od1
c2=iflColumn $ ifsStart $ odLoc od2
in compare c1 c2
a-> a
) matchods
in case bestods of
(x:_)->let
def=odName x == objName &&
((iflColumn (ifsStart $ odLoc x) == iflColumn (ifsStart ifs))
|| (
(Data `elem` odType x)
&& (iflColumn (ifsStart $ odLoc x) + 5==iflColumn (ifsStart ifs))
)
|| (
(Type `elem` odType x)
&& (iflColumn (ifsStart $ odLoc x) + 5 == iflColumn (ifsStart ifs))
))
in (odName $ head widestods,def)
_->("",False)
getSection _ _ _=("",False)
-- importToUsage :: ImportDef -> [Usage]
-- importToUsage imd=[Usage (i_package imd) (i_module imd) "" False (toJSON $ i_loc imd)]
-- | build one source file in GHC
build1 :: FilePath -- ^ the source file
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> BuildWrapper (OpResult (Maybe [NameDef])) -- ^ Just names in scope if build is successful
build1 fp mccn=withGHCAST' fp mccn BwGHC.getGhcNameDefsInScope
-- | build one source file in GHC
build1LongRunning :: FilePath -- ^ the source file
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> BuildWrapper (OpResult (Maybe ())) -- ^ True if build is successful
build1LongRunning fp mccn=withGHCAST fp mccn BwGHC.getGhcNameDefsInScopeLongRunning
-- | preprocess a file
preproc :: BuildFlags -- ^ the build flags
-> FilePath -- ^ the file to preprocess
-> IO String -- ^ the resulting code
preproc bf tgt= do
inputOrig<-readFile tgt
let epo=parseOptions $ bfPreproc bf
case epo of
Right opts2->runCpphs opts2 tgt inputOrig
Left _->return inputOrig
-- | get the build flags for a source file
getBuildFlags :: FilePath -- ^ the source file
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> BuildWrapper (OpResult BuildFlags)
getBuildFlags fp mccn=do
tgt<-getTargetPath fp
src<-getCabalFile Source
ex <- liftIO $ doesFileExist src
if ex
then do
modSrc<-liftIO $ getModificationTime src
mbf<-liftIO $ readBuildFlagsInfo tgt modSrc
case filterBuildFlags mbf of
Just bf-> return bf
Nothing -> do
(mcbi,bwns)<-getBuildInfo fp mccn
--liftIO $ print mcbi
ret<-case mcbi of
Just cbi->do
opts2<-fileGhcOptions $ snd cbi
-- liftIO $ Prelude.print fp
-- liftIO $ Prelude.print $ cbiModulePaths $ snd cbi
-- liftIO $ Prelude.print opts2
let
fullFp=takeDirectory src </> fp
modName=listToMaybe $ mapMaybe fst (filter (\ (_, f) -> f == fullFp) $ cbiModulePaths $ snd cbi)
-- (modName,_)=cabalExtensions $ snd cbi
cppo=fileCppOptions (snd cbi) ++ unlitF
modS=fmap moduleToString modName
-- liftIO $ Prelude.print opts
-- ghcOptions is sufficient, contains extensions and such
-- opts ++
return (BuildFlags opts2 cppo modS (Just $ cabalComponentName $ cbiComponent $ snd cbi),bwns)
Nothing -> return (BuildFlags [] unlitF Nothing Nothing,[])
liftIO $ storeBuildFlagsInfo tgt ret
return ret
else return (BuildFlags [] unlitF Nothing Nothing,[])
where
unlitF=let
lit=".lhs" == takeExtension fp
in ("-D__GLASGOW_HASKELL__=" ++ show (__GLASGOW_HASKELL__ :: Int)) : ["--unlit" | lit]
filterBuildFlags :: Maybe (BuildFlags,[BWNote]) -> Maybe (BuildFlags,[BWNote])
filterBuildFlags (Just (bf,_)) | mccn /= bfComponent bf=Nothing
filterBuildFlags mbf=mbf
-- | get haskell-src-exts commented AST for source file
getAST :: FilePath -- ^ the source file
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> BuildWrapper (OpResult (Maybe (ParseResult (Module SrcSpanInfo, [Comment]))))
getAST fp mccn=do
(bf,ns)<-getBuildFlags fp mccn
tgt<-getTargetPath fp
input<-liftIO $ preproc bf tgt
let pr= getHSEAST input (bfAst bf)
-- liftIO $ print pr
return (Just pr,ns)
-- | get GHC typechecked AST for source file
getGHCAST :: FilePath -- ^ the source file
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> BuildWrapper (OpResult (Maybe TypecheckedSource))
getGHCAST fp mccn = withGHCAST' fp mccn BwGHC.getAST
-- | perform an action on the GHC AST
withGHCAST :: FilePath -- ^ the source file
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> (FilePath -- ^ the source file
-> FilePath -- ^ the base directory
-> String -- ^ the module name
-> [String] -- ^ the GHC options
-> IO a)
-> BuildWrapper (OpResult (Maybe a))
withGHCAST fp mccn f=withGHCAST' fp mccn (\a b c d->do
r<- f a b c d
return (Just r,[]))
-- | perform an action on the GHC AST, returning notes alonside with the result
withGHCAST' :: FilePath -- ^ the source file
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> (FilePath -- ^ the source file
-> FilePath -- ^ the base directory
-> String -- ^ the module name
-> [String] -- ^ the GHC options
-> IO (OpResult (Maybe a))) -> BuildWrapper (OpResult (Maybe a))
withGHCAST' fp mccn f= do
(bf,ns)<-getBuildFlags fp mccn
-- liftIO $ print bf
case bf of
(BuildFlags opts _ (Just modS) _)-> do
tgt<-getTargetPath fp
temp<-getFullTempDir
liftIO $ do
cd<-getCurrentDirectory
setCurrentDirectory temp
(pr,bwns2)<- f tgt temp modS opts
setCurrentDirectory cd
return (pr,ns ++ bwns2)
_ -> return (Nothing,ns)
-- | get outline for source file
getOutline :: FilePath -- ^ source file
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> BuildWrapper (OpResult OutlineResult)
getOutline fp mccn=do
tgt<-getTargetPath fp
let usageFile=getUsageFile tgt
usageStale<-liftIO $ isSourceMoreRecent tgt usageFile
mods<-if not usageStale
then do
mv<-liftIO $ getUsageInfo tgt
return $ case mv of
Array arr | V.length arr==5->let
(Success r)= fromJSON (arr V.! 4)
in Just r
_->Nothing
else return Nothing
case mods of
Just ods-> return (ods,[])
_ -> do
(mast,bwns)<-getAST fp mccn
case mast of
Just (ParseOk ast)->do
-- liftIO $ Prelude.print $ snd ast
let ods=getHSEOutline ast
let (es,is)=getHSEImportExport ast
return (OutlineResult ods es is,bwns)
Just (ParseFailed failLoc err)->return (OutlineResult [] [] [],BWNote BWError err (mkEmptySpan fp (srcLine failLoc) (srcColumn failLoc)) :bwns)
_ -> return (OutlineResult [] [] [],bwns)
-- | get lexer token types for source file
getTokenTypes :: FilePath -- ^ the source file
-> BuildWrapper (OpResult [TokenDef])
getTokenTypes fp=do
tgt<-getTargetPath fp
ett<-liftIO $ do
input<-readFile tgt
BwGHC.tokenTypesArbitrary tgt input (".lhs" == takeExtension fp) knownExtensionNames
case ett of
Right tt->return (tt,[])
Left bw -> return ([],[bw])
-- | get all occurrences of a token in the file
getOccurrences :: FilePath -- ^ the source file
-> String -- ^ the token to search for
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> BuildWrapper (OpResult [TokenDef])
getOccurrences fp query mccn=do
(BuildFlags opts _ _ _, _)<-getBuildFlags fp mccn
tgt<-getTargetPath fp
input<-liftIO $ readFile tgt
ett<-liftIO $ BwGHC.occurrences tgt input (T.pack query) (".lhs" == takeExtension fp) opts
case ett of
Right tt->return (tt,[])
Left bw -> return ([],[bw])
-- | get thing at point
getThingAtPoint :: FilePath -- ^ the source file
-> Int -- ^ the line
-> Int -- ^ the column
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-- -> Bool -- ^ do we want the result qualified?
-- -> Bool -- ^ do we want the result typed?
-> BuildWrapper (OpResult (Maybe ThingAtPoint))
getThingAtPoint fp line col mccn=
liftM (first (fromMaybe Nothing)) $ withGHCAST fp mccn $ BwGHC.getThingAtPointJSON line col
-- | get locals identifiers
getLocals :: FilePath -- ^ the source file
-> Int -- ^ the start line
-> Int -- ^ the start column
-> Int -- ^ the end line
-> Int -- ^ the end column
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> BuildWrapper (OpResult [ThingAtPoint])
getLocals fp sline scol eline ecol mccn=
liftM (first (fromMaybe [])) $ withGHCAST fp mccn $ BwGHC.getLocalsJSON sline scol eline ecol
-- | evaluate an expression
evalExpression :: FilePath -- ^ the source file
-> String -- ^ expression
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> BuildWrapper (OpResult [EvalResult])
evalExpression fp expression mccn=
liftM (first (fromMaybe [])) $ withGHCAST fp mccn $ BwGHC.eval expression
-- | get all names in scope (GHC API)
getNamesInScope :: FilePath
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> BuildWrapper (OpResult (Maybe [String]))
getNamesInScope fp mccn=withGHCAST fp mccn BwGHC.getGhcNamesInScope
-- | get cabal dependencies
getCabalDependencies :: FilePath -> BuildWrapper (OpResult [(FilePath,[CabalPackage])])
getCabalDependencies fp=do
msd<-case fp of
""-> return Nothing
_-> liftM Just $ getFullSrc fp
cabalDependencies msd
-- | get cabal components
getCabalComponents :: BuildWrapper (OpResult [CabalComponent])
getCabalComponents = cabalComponents
-- | clean imports in a source file
cleanImports :: FilePath -- ^ the source file
-> Bool -- ^ format?
-> Maybe String -- ^ the cabal component to use, or Nothing if not specified
-> BuildWrapper (OpResult [ImportClean])
cleanImports fp doFormat mccn=do
(bf,ns)<-getBuildFlags fp mccn
case bf of
(BuildFlags opts _ (Just modS) _)-> do
tgt<-getTargetPath fp
temp<-getFullTempDir
liftIO $ do
cd<-getCurrentDirectory
setCurrentDirectory temp
(m,bwns2)<-BwGHC.ghcCleanImports tgt temp modS opts doFormat
setCurrentDirectory cd
return (m,ns ++ bwns2)
_ -> return ([],ns)
-- | clean generated and copied files
clean :: Bool -- ^ everything?
-> BuildWrapper Bool
clean everything=do
if everything
then deleteTemp
else deleteGenerated
return everything
|
achirkin/BuildWrapper
|
src/Language/Haskell/BuildWrapper/API.hs
|
bsd-3-clause
| 28,740
| 0
| 32
| 12,620
| 6,185
| 3,124
| 3,061
| 429
| 17
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE PostfixOperators #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
--------------------------------------------------------------------------------
-- Call from a periodic thread.
--
-- (c) 2015 Galois, Inc.
--
--------------------------------------------------------------------------------
module Main where
import Ivory.Tower
import Ivory.Language
import Tower.AADL
test0 :: Tower e ()
test0 = do
towerModule towerDepModule
towerDepends towerDepModule
(cin, _) <- channel
per <- period (100`ms`)
monitor "sender" $ do
handler per "tick" $ do
e <- emitter cin 1
callback $ \msg -> do
m <- deref msg
call_ printf "Sender ping received %llu. Writing to receiver.\n" m
emitV e (m+1)
--------------------------------------------------------------------------------
-- Compiler
main :: IO ()
main =
runCompileAADL
initialOpts { genDirOpts = Just "test_per"
}
test0
--------------------------------------------------------------------------------
-- Helpers
printf :: Def('[IString, ITime] :-> ())
printf = importProc "printf" "stdio.h"
towerDepModule :: Module
towerDepModule = package "towerDeps" (incl printf)
|
GaloisInc/tower
|
tower-aadl/test/TestPerSender.hs
|
bsd-3-clause
| 1,459
| 0
| 19
| 250
| 265
| 142
| 123
| 36
| 1
|
-- (c) The University of Glasgow 2006
{-# LANGUAGE CPP #-}
-- | Highly random utility functions
--
module ETA.Utils.Util (
-- * Flags dependent on the compiler build
ghciSupported, debugIsOn, ncgDebugIsOn,
ghciTablesNextToCode,
isWindowsHost, isDarwinHost,
-- * General list processing
expectHead,
zipEqual, zipWithEqual, zipWith3Equal, zipWith4Equal,
zipLazy, stretchZipWith, zipWithAndUnzip,
filterByList,
unzipWith,
mapFst, mapSnd, chkAppend,
mapAndUnzip, mapAndUnzip3, mapAccumL2,
nOfThem, filterOut, partitionWith, splitEithers,
dropWhileEndLE,
foldl1', foldl2, count, all2,
lengthExceeds, lengthIs, lengthAtLeast,
listLengthCmp, atLength,
equalLength, compareLength, leLength,
isSingleton, only, singleton,
notNull, snocView,
isIn, isn'tIn,
-- * Tuples
fstOf3, sndOf3, thirdOf3,
firstM, first3M,
third3,
uncurry3,
-- * List operations controlled by another list
takeList, dropList, splitAtList, split,
dropTail,
-- * For loop
nTimes,
-- * Sorting
sortWith, minWith, nubSort,
-- * Comparisons
isEqual, eqListBy, eqMaybeBy,
thenCmp, cmpList,
removeSpaces,
(<&&>), (<||>),
-- * Edit distance
fuzzyMatch, fuzzyLookup,
-- * Transitive closures
transitiveClosure,
-- * Strictness
seqList,
-- * Module names
looksLikeModuleName,
-- * Argument processing
getCmd, toCmdArgs, toArgs,
-- * Floating point
readRational,
-- * read helpers
maybeRead, maybeReadFuzzy,
-- * IO-ish utilities
doesDirNameExist,
getModificationUTCTime,
modificationTimeIfExists,
hSetTranslit,
global, consIORef, globalM,
-- * Filenames and paths
Suffix,
splitLongestPrefix,
escapeSpaces,
Direction(..), reslash,
makeRelativeTo,
-- * Utils for defining Data instances
abstractConstr, abstractDataType, mkNoRepType,
-- * Utils for printing C code
charToC,
-- * Hashing
hashString,
) where
#include "HsVersions.h"
import ETA.Utils.Exception
import ETA.Utils.Panic
import Data.Data
import Data.IORef ( IORef, newIORef, atomicModifyIORef )
import System.IO.Unsafe ( unsafePerformIO )
import Data.List hiding (group)
#ifdef DEBUG
import ETA.Utils.FastTypes
#endif
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative (Applicative)
#endif
import Control.Applicative ( liftA2 )
import Control.Monad ( liftM )
import GHC.IO.Encoding (mkTextEncoding, textEncodingName)
import System.IO (Handle, hGetEncoding, hSetEncoding)
import System.IO.Error as IO ( isDoesNotExistError )
import System.Directory ( doesDirectoryExist, getModificationTime )
import System.FilePath
import Data.Char ( isUpper, isAlphaNum, isSpace, chr, ord, isDigit )
import Data.Int
import Data.Ratio ( (%) )
import Data.Ord ( comparing )
import Data.Bits
import Data.Word
import qualified Data.IntMap as IM
import qualified Data.Set as Set
import Data.Time
infixr 9 `thenCmp`
{-
************************************************************************
* *
\subsection{Is DEBUG on, are we on Windows, etc?}
* *
************************************************************************
These booleans are global constants, set by CPP flags. They allow us to
recompile a single module (this one) to change whether or not debug output
appears. They sometimes let us avoid even running CPP elsewhere.
It's important that the flags are literal constants (True/False). Then,
with -0, tests of the flags in other modules will simplify to the correct
branch of the conditional, thereby dropping debug code altogether when
the flags are off.
-}
ghciSupported :: Bool
#ifdef GHCI
ghciSupported = True
#else
ghciSupported = False
#endif
debugIsOn :: Bool
#ifdef DEBUG
debugIsOn = True
#else
debugIsOn = False
#endif
ncgDebugIsOn :: Bool
#ifdef NCG_DEBUG
ncgDebugIsOn = True
#else
ncgDebugIsOn = False
#endif
ghciTablesNextToCode :: Bool
#ifdef GHCI_TABLES_NEXT_TO_CODE
ghciTablesNextToCode = True
#else
ghciTablesNextToCode = False
#endif
isWindowsHost :: Bool
#ifdef mingw32_HOST_OS
isWindowsHost = True
#else
isWindowsHost = False
#endif
isDarwinHost :: Bool
#ifdef darwin_HOST_OS
isDarwinHost = True
#else
isDarwinHost = False
#endif
{-
************************************************************************
* *
\subsection{A for loop}
* *
************************************************************************
-}
-- | Compose a function with itself n times. (nth rather than twice)
nTimes :: Int -> (a -> a) -> (a -> a)
nTimes 0 _ = id
nTimes 1 f = f
nTimes n f = f . nTimes (n-1) f
fstOf3 :: (a,b,c) -> a
sndOf3 :: (a,b,c) -> b
thirdOf3 :: (a,b,c) -> c
fstOf3 (a,_,_) = a
sndOf3 (_,b,_) = b
thirdOf3 (_,_,c) = c
third3 :: (c -> d) -> (a, b, c) -> (a, b, d)
third3 f (a, b, c) = (a, b, f c)
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 f (a, b, c) = f a b c
firstM :: Monad m => (a -> m c) -> (a, b) -> m (c, b)
firstM f (x, y) = liftM (\x' -> (x', y)) (f x)
first3M :: Monad m => (a -> m d) -> (a, b, c) -> m (d, b, c)
first3M f (x, y, z) = liftM (\x' -> (x', y, z)) (f x)
{-
************************************************************************
* *
\subsection[Utils-lists]{General list processing}
* *
************************************************************************
-}
expectHead :: String -> [a] -> a
expectHead _ (x:_) = x
expectHead err _ = error ("expectHead " ++ err)
filterOut :: (a->Bool) -> [a] -> [a]
-- ^ Like filter, only it reverses the sense of the test
filterOut _ [] = []
filterOut p (x:xs) | p x = filterOut p xs
| otherwise = x : filterOut p xs
partitionWith :: (a -> Either b c) -> [a] -> ([b], [c])
-- ^ Uses a function to determine which of two output lists an input element should join
partitionWith _ [] = ([],[])
partitionWith f (x:xs) = case f x of
Left b -> (b:bs, cs)
Right c -> (bs, c:cs)
where (bs,cs) = partitionWith f xs
splitEithers :: [Either a b] -> ([a], [b])
-- ^ Teases a list of 'Either's apart into two lists
splitEithers [] = ([],[])
splitEithers (e : es) = case e of
Left x -> (x:xs, ys)
Right y -> (xs, y:ys)
where (xs,ys) = splitEithers es
chkAppend :: [a] -> [a] -> [a]
-- Checks for the second arguemnt being empty
-- Used in situations where that situation is common
chkAppend xs ys
| null ys = xs
| otherwise = xs ++ ys
{-
A paranoid @zip@ (and some @zipWith@ friends) that checks the lists
are of equal length. Alastair Reid thinks this should only happen if
DEBUGging on; hey, why not?
-}
zipEqual :: String -> [a] -> [b] -> [(a,b)]
zipWithEqual :: String -> (a->b->c) -> [a]->[b]->[c]
zipWith3Equal :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
zipWith4Equal :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
#ifndef DEBUG
zipEqual _ = zip
zipWithEqual _ = zipWith
zipWith3Equal _ = zipWith3
zipWith4Equal _ = zipWith4
#else
zipEqual _ [] [] = []
zipEqual msg (a:as) (b:bs) = (a,b) : zipEqual msg as bs
zipEqual msg _ _ = panic ("zipEqual: unequal lists:"++msg)
zipWithEqual msg z (a:as) (b:bs)= z a b : zipWithEqual msg z as bs
zipWithEqual _ _ [] [] = []
zipWithEqual msg _ _ _ = panic ("zipWithEqual: unequal lists:"++msg)
zipWith3Equal msg z (a:as) (b:bs) (c:cs)
= z a b c : zipWith3Equal msg z as bs cs
zipWith3Equal _ _ [] [] [] = []
zipWith3Equal msg _ _ _ _ = panic ("zipWith3Equal: unequal lists:"++msg)
zipWith4Equal msg z (a:as) (b:bs) (c:cs) (d:ds)
= z a b c d : zipWith4Equal msg z as bs cs ds
zipWith4Equal _ _ [] [] [] [] = []
zipWith4Equal msg _ _ _ _ _ = panic ("zipWith4Equal: unequal lists:"++msg)
#endif
-- | 'zipLazy' is a kind of 'zip' that is lazy in the second list (observe the ~)
zipLazy :: [a] -> [b] -> [(a,b)]
zipLazy [] _ = []
zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
-- | 'filterByList' takes a list of Bools and a list of some elements and
-- filters out these elements for which the corresponding value in the list of
-- Bools is False. This function does not check whether the lists have equal
-- length.
filterByList :: [Bool] -> [a] -> [a]
filterByList (True:bs) (x:xs) = x : filterByList bs xs
filterByList (False:bs) (_:xs) = filterByList bs xs
filterByList _ _ = []
stretchZipWith :: (a -> Bool) -> b -> (a->b->c) -> [a] -> [b] -> [c]
-- ^ @stretchZipWith p z f xs ys@ stretches @ys@ by inserting @z@ in
-- the places where @p@ returns @True@
stretchZipWith _ _ _ [] _ = []
stretchZipWith p z f (x:xs) ys
| p x = f x z : stretchZipWith p z f xs ys
| otherwise = case ys of
[] -> []
(y:ys) -> f x y : stretchZipWith p z f xs ys
mapFst :: (a->c) -> [(a,b)] -> [(c,b)]
mapSnd :: (b->c) -> [(a,b)] -> [(a,c)]
mapFst f xys = [(f x, y) | (x,y) <- xys]
mapSnd f xys = [(x, f y) | (x,y) <- xys]
mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
mapAndUnzip _ [] = ([], [])
mapAndUnzip f (x:xs)
= let (r1, r2) = f x
(rs1, rs2) = mapAndUnzip f xs
in
(r1:rs1, r2:rs2)
mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
mapAndUnzip3 _ [] = ([], [], [])
mapAndUnzip3 f (x:xs)
= let (r1, r2, r3) = f x
(rs1, rs2, rs3) = mapAndUnzip3 f xs
in
(r1:rs1, r2:rs2, r3:rs3)
zipWithAndUnzip :: (a -> b -> (c,d)) -> [a] -> [b] -> ([c],[d])
zipWithAndUnzip f (a:as) (b:bs)
= let (r1, r2) = f a b
(rs1, rs2) = zipWithAndUnzip f as bs
in
(r1:rs1, r2:rs2)
zipWithAndUnzip _ _ _ = ([],[])
mapAccumL2 :: (s1 -> s2 -> a -> (s1, s2, b)) -> s1 -> s2 -> [a] -> (s1, s2, [b])
mapAccumL2 f s1 s2 xs = (s1', s2', ys)
where ((s1', s2'), ys) = mapAccumL (\(s1, s2) x -> case f s1 s2 x of
(s1', s2', y) -> ((s1', s2'), y))
(s1, s2) xs
nOfThem :: Int -> a -> [a]
nOfThem n thing = replicate n thing
-- | @atLength atLen atEnd ls n@ unravels list @ls@ to position @n@. Precisely:
--
-- @
-- atLength atLenPred atEndPred ls n
-- | n < 0 = atLenPred n
-- | length ls < n = atEndPred (n - length ls)
-- | otherwise = atLenPred (drop n ls)
-- @
atLength :: ([a] -> b)
-> (Int -> b)
-> [a]
-> Int
-> b
atLength atLenPred atEndPred ls n
| n < 0 = atEndPred n
| otherwise = go n ls
where
go n [] = atEndPred n
go 0 ls = atLenPred ls
go n (_:xs) = go (n-1) xs
-- Some special cases of atLength:
lengthExceeds :: [a] -> Int -> Bool
-- ^ > (lengthExceeds xs n) = (length xs > n)
lengthExceeds = atLength notNull (const False)
lengthAtLeast :: [a] -> Int -> Bool
lengthAtLeast = atLength notNull (== 0)
lengthIs :: [a] -> Int -> Bool
lengthIs = atLength null (==0)
listLengthCmp :: [a] -> Int -> Ordering
listLengthCmp = atLength atLen atEnd
where
atEnd 0 = EQ
atEnd x
| x > 0 = LT -- not yet seen 'n' elts, so list length is < n.
| otherwise = GT
atLen [] = EQ
atLen _ = GT
equalLength :: [a] -> [b] -> Bool
equalLength [] [] = True
equalLength (_:xs) (_:ys) = equalLength xs ys
equalLength _ _ = False
compareLength :: [a] -> [b] -> Ordering
compareLength [] [] = EQ
compareLength (_:xs) (_:ys) = compareLength xs ys
compareLength [] _ = LT
compareLength _ [] = GT
leLength :: [a] -> [b] -> Bool
-- ^ True if length xs <= length ys
leLength xs ys = case compareLength xs ys of
LT -> True
EQ -> True
GT -> False
----------------------------
singleton :: a -> [a]
singleton x = [x]
isSingleton :: [a] -> Bool
isSingleton [_] = True
isSingleton _ = False
notNull :: [a] -> Bool
notNull [] = False
notNull _ = True
only :: [a] -> a
#ifdef DEBUG
only [a] = a
#else
only (a:_) = a
#endif
only _ = panic "Util: only"
-- Debugging/specialising versions of \tr{elem} and \tr{notElem}
isIn, isn'tIn :: Eq a => String -> a -> [a] -> Bool
# ifndef DEBUG
isIn _msg x ys = x `elem` ys
isn'tIn _msg x ys = x `notElem` ys
# else /* DEBUG */
isIn msg x ys
= elem100 (_ILIT(0)) x ys
where
elem100 _ _ [] = False
elem100 i x (y:ys)
| i ># _ILIT(100) = trace ("Over-long elem in " ++ msg)
(x `elem` (y:ys))
| otherwise = x == y || elem100 (i +# _ILIT(1)) x ys
isn'tIn msg x ys
= notElem100 (_ILIT(0)) x ys
where
notElem100 _ _ [] = True
notElem100 i x (y:ys)
| i ># _ILIT(100) = trace ("Over-long notElem in " ++ msg)
(x `notElem` (y:ys))
| otherwise = x /= y && notElem100 (i +# _ILIT(1)) x ys
# endif /* DEBUG */
{-
************************************************************************
* *
\subsubsection{Sort utils}
* *
************************************************************************
-}
sortWith :: Ord b => (a->b) -> [a] -> [a]
sortWith get_key xs = sortBy (comparing get_key) xs
minWith :: Ord b => (a -> b) -> [a] -> a
minWith get_key xs = ASSERT( not (null xs) )
head (sortWith get_key xs)
nubSort :: Ord a => [a] -> [a]
nubSort = Set.toAscList . Set.fromList
{-
************************************************************************
* *
\subsection[Utils-transitive-closure]{Transitive closure}
* *
************************************************************************
This algorithm for transitive closure is straightforward, albeit quadratic.
-}
transitiveClosure :: (a -> [a]) -- Successor function
-> (a -> a -> Bool) -- Equality predicate
-> [a]
-> [a] -- The transitive closure
transitiveClosure succ eq xs
= go [] xs
where
go done [] = done
go done (x:xs) | x `is_in` done = go done xs
| otherwise = go (x:done) (succ x ++ xs)
_ `is_in` [] = False
x `is_in` (y:ys) | eq x y = True
| otherwise = x `is_in` ys
{-
************************************************************************
* *
\subsection[Utils-accum]{Accumulating}
* *
************************************************************************
A combination of foldl with zip. It works with equal length lists.
-}
foldl2 :: (acc -> a -> b -> acc) -> acc -> [a] -> [b] -> acc
foldl2 _ z [] [] = z
foldl2 k z (a:as) (b:bs) = foldl2 k (k z a b) as bs
foldl2 _ _ _ _ = panic "Util: foldl2"
all2 :: (a -> b -> Bool) -> [a] -> [b] -> Bool
-- True if the lists are the same length, and
-- all corresponding elements satisfy the predicate
all2 _ [] [] = True
all2 p (x:xs) (y:ys) = p x y && all2 p xs ys
all2 _ _ _ = False
-- Count the number of times a predicate is true
count :: (a -> Bool) -> [a] -> Int
count _ [] = 0
count p (x:xs) | p x = 1 + count p xs
| otherwise = count p xs
{-
@splitAt@, @take@, and @drop@ but with length of another
list giving the break-off point:
-}
takeList :: [b] -> [a] -> [a]
takeList [] _ = []
takeList (_:xs) ls =
case ls of
[] -> []
(y:ys) -> y : takeList xs ys
dropList :: [b] -> [a] -> [a]
dropList [] xs = xs
dropList _ xs@[] = xs
dropList (_:xs) (_:ys) = dropList xs ys
splitAtList :: [b] -> [a] -> ([a], [a])
splitAtList [] xs = ([], xs)
splitAtList _ xs@[] = (xs, xs)
splitAtList (_:xs) (y:ys) = (y:ys', ys'')
where
(ys', ys'') = splitAtList xs ys
-- drop from the end of a list
dropTail :: Int -> [a] -> [a]
-- Specification: dropTail n = reverse . drop n . reverse
-- Better implemention due to Joachim Breitner
-- http://www.joachim-breitner.de/blog/archives/600-On-taking-the-last-n-elements-of-a-list.html
dropTail n xs
= go (drop n xs) xs
where
go (_:ys) (x:xs) = x : go ys xs
go _ _ = [] -- Stop when ys runs out
-- It'll always run out before xs does
-- dropWhile from the end of a list. This is similar to Data.List.dropWhileEnd,
-- but is lazy in the elements and strict in the spine. For reasonably short lists,
-- such as path names and typical lines of text, dropWhileEndLE is generally
-- faster than dropWhileEnd. Its advantage is magnified when the predicate is
-- expensive--using dropWhileEndLE isSpace to strip the space off a line of text
-- is generally much faster than using dropWhileEnd isSpace for that purpose.
-- Specification: dropWhileEndLE p = reverse . dropWhile p . reverse
-- Pay attention to the short-circuit (&&)! The order of its arguments is the only
-- difference between dropWhileEnd and dropWhileEndLE.
dropWhileEndLE :: (a -> Bool) -> [a] -> [a]
dropWhileEndLE p = foldr (\x r -> if null r && p x then [] else x:r) []
snocView :: [a] -> Maybe ([a],a)
-- Split off the last element
snocView [] = Nothing
snocView xs = go [] xs
where
-- Invariant: second arg is non-empty
go acc [x] = Just (reverse acc, x)
go acc (x:xs) = go (x:acc) xs
go _ [] = panic "Util: snocView"
split :: Char -> String -> [String]
split c s = case rest of
[] -> [chunk]
_:rest -> chunk : split c rest
where (chunk, rest) = break (==c) s
{-
************************************************************************
* *
\subsection[Utils-comparison]{Comparisons}
* *
************************************************************************
-}
isEqual :: Ordering -> Bool
-- Often used in (isEqual (a `compare` b))
isEqual GT = False
isEqual EQ = True
isEqual LT = False
thenCmp :: Ordering -> Ordering -> Ordering
{-# INLINE thenCmp #-}
thenCmp EQ ordering = ordering
thenCmp ordering _ = ordering
eqListBy :: (a->a->Bool) -> [a] -> [a] -> Bool
eqListBy _ [] [] = True
eqListBy eq (x:xs) (y:ys) = eq x y && eqListBy eq xs ys
eqListBy _ _ _ = False
eqMaybeBy :: (a ->a->Bool) -> Maybe a -> Maybe a -> Bool
eqMaybeBy _ Nothing Nothing = True
eqMaybeBy eq (Just x) (Just y) = eq x y
eqMaybeBy _ _ _ = False
cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
-- `cmpList' uses a user-specified comparer
cmpList _ [] [] = EQ
cmpList _ [] _ = LT
cmpList _ _ [] = GT
cmpList cmp (a:as) (b:bs)
= case cmp a b of { EQ -> cmpList cmp as bs; xxx -> xxx }
removeSpaces :: String -> String
removeSpaces = dropWhileEndLE isSpace . dropWhile isSpace
-- Boolean operators lifted to Applicative
(<&&>) :: Applicative f => f Bool -> f Bool -> f Bool
(<&&>) = liftA2 (&&)
infixr 3 <&&> -- same as (&&)
(<||>) :: Applicative f => f Bool -> f Bool -> f Bool
(<||>) = liftA2 (||)
infixr 2 <||> -- same as (||)
{-
************************************************************************
* *
\subsection{Edit distance}
* *
************************************************************************
-}
-- | Find the "restricted" Damerau-Levenshtein edit distance between two strings.
-- See: <http://en.wikipedia.org/wiki/Damerau-Levenshtein_distance>.
-- Based on the algorithm presented in "A Bit-Vector Algorithm for Computing
-- Levenshtein and Damerau Edit Distances" in PSC'02 (Heikki Hyyro).
-- See http://www.cs.uta.fi/~helmu/pubs/psc02.pdf and
-- http://www.cs.uta.fi/~helmu/pubs/PSCerr.html for an explanation
restrictedDamerauLevenshteinDistance :: String -> String -> Int
restrictedDamerauLevenshteinDistance str1 str2
= restrictedDamerauLevenshteinDistanceWithLengths m n str1 str2
where
m = length str1
n = length str2
restrictedDamerauLevenshteinDistanceWithLengths
:: Int -> Int -> String -> String -> Int
restrictedDamerauLevenshteinDistanceWithLengths m n str1 str2
| m <= n
= if n <= 32 -- n must be larger so this check is sufficient
then restrictedDamerauLevenshteinDistance' (undefined :: Word32) m n str1 str2
else restrictedDamerauLevenshteinDistance' (undefined :: Integer) m n str1 str2
| otherwise
= if m <= 32 -- m must be larger so this check is sufficient
then restrictedDamerauLevenshteinDistance' (undefined :: Word32) n m str2 str1
else restrictedDamerauLevenshteinDistance' (undefined :: Integer) n m str2 str1
restrictedDamerauLevenshteinDistance'
:: (Bits bv, Num bv) => bv -> Int -> Int -> String -> String -> Int
restrictedDamerauLevenshteinDistance' _bv_dummy m n str1 str2
| [] <- str1 = n
| otherwise = extractAnswer $
foldl' (restrictedDamerauLevenshteinDistanceWorker
(matchVectors str1) top_bit_mask vector_mask)
(0, 0, m_ones, 0, m) str2
where
m_ones@vector_mask = (2 ^ m) - 1
top_bit_mask = (1 `shiftL` (m - 1)) `asTypeOf` _bv_dummy
extractAnswer (_, _, _, _, distance) = distance
restrictedDamerauLevenshteinDistanceWorker
:: (Bits bv, Num bv) => IM.IntMap bv -> bv -> bv
-> (bv, bv, bv, bv, Int) -> Char -> (bv, bv, bv, bv, Int)
restrictedDamerauLevenshteinDistanceWorker str1_mvs top_bit_mask vector_mask
(pm, d0, vp, vn, distance) char2
= seq str1_mvs $ seq top_bit_mask $ seq vector_mask $
seq pm' $ seq d0' $ seq vp' $ seq vn' $
seq distance'' $ seq char2 $
(pm', d0', vp', vn', distance'')
where
pm' = IM.findWithDefault 0 (ord char2) str1_mvs
d0' = ((((sizedComplement vector_mask d0) .&. pm') `shiftL` 1) .&. pm)
.|. ((((pm' .&. vp) + vp) .&. vector_mask) `xor` vp) .|. pm' .|. vn
-- No need to mask the shiftL because of the restricted range of pm
hp' = vn .|. sizedComplement vector_mask (d0' .|. vp)
hn' = d0' .&. vp
hp'_shift = ((hp' `shiftL` 1) .|. 1) .&. vector_mask
hn'_shift = (hn' `shiftL` 1) .&. vector_mask
vp' = hn'_shift .|. sizedComplement vector_mask (d0' .|. hp'_shift)
vn' = d0' .&. hp'_shift
distance' = if hp' .&. top_bit_mask /= 0 then distance + 1 else distance
distance'' = if hn' .&. top_bit_mask /= 0 then distance' - 1 else distance'
sizedComplement :: Bits bv => bv -> bv -> bv
sizedComplement vector_mask vect = vector_mask `xor` vect
matchVectors :: (Bits bv, Num bv) => String -> IM.IntMap bv
matchVectors = snd . foldl' go (0 :: Int, IM.empty)
where
go (ix, im) char = let ix' = ix + 1
im' = IM.insertWith (.|.) (ord char) (2 ^ ix) im
in seq ix' $ seq im' $ (ix', im')
{-# SPECIALIZE INLINE restrictedDamerauLevenshteinDistance'
:: Word32 -> Int -> Int -> String -> String -> Int #-}
{-# SPECIALIZE INLINE restrictedDamerauLevenshteinDistance'
:: Integer -> Int -> Int -> String -> String -> Int #-}
{-# SPECIALIZE restrictedDamerauLevenshteinDistanceWorker
:: IM.IntMap Word32 -> Word32 -> Word32
-> (Word32, Word32, Word32, Word32, Int)
-> Char -> (Word32, Word32, Word32, Word32, Int) #-}
{-# SPECIALIZE restrictedDamerauLevenshteinDistanceWorker
:: IM.IntMap Integer -> Integer -> Integer
-> (Integer, Integer, Integer, Integer, Int)
-> Char -> (Integer, Integer, Integer, Integer, Int) #-}
{-# SPECIALIZE INLINE sizedComplement :: Word32 -> Word32 -> Word32 #-}
{-# SPECIALIZE INLINE sizedComplement :: Integer -> Integer -> Integer #-}
{-# SPECIALIZE matchVectors :: String -> IM.IntMap Word32 #-}
{-# SPECIALIZE matchVectors :: String -> IM.IntMap Integer #-}
fuzzyMatch :: String -> [String] -> [String]
fuzzyMatch key vals = fuzzyLookup key [(v,v) | v <- vals]
-- | Search for possible matches to the users input in the given list,
-- returning a small number of ranked results
fuzzyLookup :: String -> [(String,a)] -> [a]
fuzzyLookup user_entered possibilites
= map fst $ take mAX_RESULTS $ sortBy (comparing snd)
[ (poss_val, distance) | (poss_str, poss_val) <- possibilites
, let distance = restrictedDamerauLevenshteinDistance
poss_str user_entered
, distance <= fuzzy_threshold ]
where
-- Work out an approriate match threshold:
-- We report a candidate if its edit distance is <= the threshold,
-- The threshhold is set to about a quarter of the # of characters the user entered
-- Length Threshold
-- 1 0 -- Don't suggest *any* candidates
-- 2 1 -- for single-char identifiers
-- 3 1
-- 4 1
-- 5 1
-- 6 2
--
fuzzy_threshold = truncate $ fromIntegral (length user_entered + 2) / (4 :: Rational)
mAX_RESULTS = 3
{-
************************************************************************
* *
\subsection[Utils-pairs]{Pairs}
* *
************************************************************************
-}
unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
seqList :: [a] -> b -> b
seqList [] b = b
seqList (x:xs) b = x `seq` seqList xs b
-- Global variables:
global :: a -> IORef a
global a = unsafePerformIO (newIORef a)
consIORef :: IORef [a] -> a -> IO ()
consIORef var x = do
atomicModifyIORef var (\xs -> (x:xs,()))
globalM :: IO a -> IORef a
globalM ma = unsafePerformIO (ma >>= newIORef)
-- Module names:
looksLikeModuleName :: String -> Bool
looksLikeModuleName [] = False
looksLikeModuleName (c:cs) = isUpper c && go cs
where go [] = True
go ('.':cs) = looksLikeModuleName cs
go (c:cs) = (isAlphaNum c || c == '_' || c == '\'') && go cs
{-
Akin to @Prelude.words@, but acts like the Bourne shell, treating
quoted strings as Haskell Strings, and also parses Haskell [String]
syntax.
-}
getCmd :: String -> Either String -- Error
(String, String) -- (Cmd, Rest)
getCmd s = case break isSpace $ dropWhile isSpace s of
([], _) -> Left ("Couldn't find command in " ++ show s)
res -> Right res
toCmdArgs :: String -> Either String -- Error
(String, [String]) -- (Cmd, Args)
toCmdArgs s = case getCmd s of
Left err -> Left err
Right (cmd, s') -> case toArgs s' of
Left err -> Left err
Right args -> Right (cmd, args)
toArgs :: String -> Either String -- Error
[String] -- Args
toArgs str
= case dropWhile isSpace str of
s@('[':_) -> case reads s of
[(args, spaces)]
| all isSpace spaces ->
Right args
_ ->
Left ("Couldn't read " ++ show str ++ "as [String]")
s -> toArgs' s
where
toArgs' s = case dropWhile isSpace s of
[] -> Right []
('"' : _) -> case reads s of
[(arg, rest)]
-- rest must either be [] or start with a space
| all isSpace (take 1 rest) ->
case toArgs' rest of
Left err -> Left err
Right args -> Right (arg : args)
_ ->
Left ("Couldn't read " ++ show s ++ "as String")
s' -> case break isSpace s' of
(arg, s'') -> case toArgs' s'' of
Left err -> Left err
Right args -> Right (arg : args)
{-
-- -----------------------------------------------------------------------------
-- Floats
-}
readRational__ :: ReadS Rational -- NB: doesn't handle leading "-"
readRational__ r = do
(n,d,s) <- readFix r
(k,t) <- readExp s
return ((n%1)*10^^(k-d), t)
where
readFix r = do
(ds,s) <- lexDecDigits r
(ds',t) <- lexDotDigits s
return (read (ds++ds'), length ds', t)
readExp (e:s) | e `elem` "eE" = readExp' s
readExp s = return (0,s)
readExp' ('+':s) = readDec s
readExp' ('-':s) = do (k,t) <- readDec s
return (-k,t)
readExp' s = readDec s
readDec s = do
(ds,r) <- nonnull isDigit s
return (foldl1 (\n d -> n * 10 + d) [ ord d - ord '0' | d <- ds ],
r)
lexDecDigits = nonnull isDigit
lexDotDigits ('.':s) = return (span isDigit s)
lexDotDigits s = return ("",s)
nonnull p s = do (cs@(_:_),t) <- return (span p s)
return (cs,t)
readRational :: String -> Rational -- NB: *does* handle a leading "-"
readRational top_s
= case top_s of
'-' : xs -> - (read_me xs)
xs -> read_me xs
where
read_me s
= case (do { (x,"") <- readRational__ s ; return x }) of
[x] -> x
[] -> error ("readRational: no parse:" ++ top_s)
_ -> error ("readRational: ambiguous parse:" ++ top_s)
-----------------------------------------------------------------------------
-- read helpers
maybeRead :: Read a => String -> Maybe a
maybeRead str = case reads str of
[(x, "")] -> Just x
_ -> Nothing
maybeReadFuzzy :: Read a => String -> Maybe a
maybeReadFuzzy str = case reads str of
[(x, s)]
| all isSpace s ->
Just x
_ ->
Nothing
-----------------------------------------------------------------------------
-- Verify that the 'dirname' portion of a FilePath exists.
--
doesDirNameExist :: FilePath -> IO Bool
doesDirNameExist fpath = doesDirectoryExist (takeDirectory fpath)
-----------------------------------------------------------------------------
-- Backwards compatibility definition of getModificationTime
getModificationUTCTime :: FilePath -> IO UTCTime
getModificationUTCTime = getModificationTime
-- --------------------------------------------------------------
-- check existence & modification time at the same time
modificationTimeIfExists :: FilePath -> IO (Maybe UTCTime)
modificationTimeIfExists f = do
(do t <- getModificationUTCTime f; return (Just t))
`catchIO` \e -> if isDoesNotExistError e
then return Nothing
else ioError e
-- --------------------------------------------------------------
-- Change the character encoding of the given Handle to transliterate
-- on unsupported characters instead of throwing an exception
hSetTranslit :: Handle -> IO ()
hSetTranslit h = do
menc <- hGetEncoding h
case fmap textEncodingName menc of
Just name | '/' `notElem` name -> do
enc' <- mkTextEncoding $ name ++ "//TRANSLIT"
hSetEncoding h enc'
_ -> return ()
-- split a string at the last character where 'pred' is True,
-- returning a pair of strings. The first component holds the string
-- up (but not including) the last character for which 'pred' returned
-- True, the second whatever comes after (but also not including the
-- last character).
--
-- If 'pred' returns False for all characters in the string, the original
-- string is returned in the first component (and the second one is just
-- empty).
splitLongestPrefix :: String -> (Char -> Bool) -> (String,String)
splitLongestPrefix str pred
| null r_pre = (str, [])
| otherwise = (reverse (tail r_pre), reverse r_suf)
-- 'tail' drops the char satisfying 'pred'
where (r_suf, r_pre) = break pred (reverse str)
escapeSpaces :: String -> String
escapeSpaces = foldr (\c s -> if isSpace c then '\\':c:s else c:s) ""
type Suffix = String
--------------------------------------------------------------
-- * Search path
--------------------------------------------------------------
data Direction = Forwards | Backwards
reslash :: Direction -> FilePath -> FilePath
reslash d = f
where f ('/' : xs) = slash : f xs
f ('\\' : xs) = slash : f xs
f (x : xs) = x : f xs
f "" = ""
slash = case d of
Forwards -> '/'
Backwards -> '\\'
makeRelativeTo :: FilePath -> FilePath -> FilePath
this `makeRelativeTo` that = directory </> thisFilename
where (thisDirectory, thisFilename) = splitFileName this
thatDirectory = dropFileName that
directory = joinPath $ f (splitPath thisDirectory)
(splitPath thatDirectory)
f (x : xs) (y : ys)
| x == y = f xs ys
f xs ys = replicate (length ys) ".." ++ xs
{-
************************************************************************
* *
\subsection[Utils-Data]{Utils for defining Data instances}
* *
************************************************************************
These functions helps us to define Data instances for abstract types.
-}
abstractConstr :: String -> Constr
abstractConstr n = mkConstr (abstractDataType n) ("{abstract:"++n++"}") [] Prefix
abstractDataType :: String -> DataType
abstractDataType n = mkDataType n [abstractConstr n]
{-
************************************************************************
* *
\subsection[Utils-C]{Utils for printing C code}
* *
************************************************************************
-}
charToC :: Word8 -> String
charToC w =
case chr (fromIntegral w) of
'\"' -> "\\\""
'\'' -> "\\\'"
'\\' -> "\\\\"
c | c >= ' ' && c <= '~' -> [c]
| otherwise -> ['\\',
chr (ord '0' + ord c `div` 64),
chr (ord '0' + ord c `div` 8 `mod` 8),
chr (ord '0' + ord c `mod` 8)]
{-
************************************************************************
* *
\subsection[Utils-Hashing]{Utils for hashing}
* *
************************************************************************
-}
-- | A sample hash function for Strings. We keep multiplying by the
-- golden ratio and adding. The implementation is:
--
-- > hashString = foldl' f golden
-- > where f m c = fromIntegral (ord c) * magic + hashInt32 m
-- > magic = 0xdeadbeef
--
-- Where hashInt32 works just as hashInt shown above.
--
-- Knuth argues that repeated multiplication by the golden ratio
-- will minimize gaps in the hash space, and thus it's a good choice
-- for combining together multiple keys to form one.
--
-- Here we know that individual characters c are often small, and this
-- produces frequent collisions if we use ord c alone. A
-- particular problem are the shorter low ASCII and ISO-8859-1
-- character strings. We pre-multiply by a magic twiddle factor to
-- obtain a good distribution. In fact, given the following test:
--
-- > testp :: Int32 -> Int
-- > testp k = (n - ) . length . group . sort . map hs . take n $ ls
-- > where ls = [] : [c : l | l <- ls, c <- ['\0'..'\xff']]
-- > hs = foldl' f golden
-- > f m c = fromIntegral (ord c) * k + hashInt32 m
-- > n = 100000
--
-- We discover that testp magic = 0.
hashString :: String -> Int32
hashString = foldl' f golden
where f m c = fromIntegral (ord c) * magic + hashInt32 m
magic = fromIntegral (0xdeadbeef :: Word32)
golden :: Int32
golden = 1013904242 -- = round ((sqrt 5 - 1) * 2^32) :: Int32
-- was -1640531527 = round ((sqrt 5 - 1) * 2^31) :: Int32
-- but that has bad mulHi properties (even adding 2^32 to get its inverse)
-- Whereas the above works well and contains no hash duplications for
-- [-32767..65536]
-- | A sample (and useful) hash function for Int32,
-- implemented by extracting the uppermost 32 bits of the 64-bit
-- result of multiplying by a 33-bit constant. The constant is from
-- Knuth, derived from the golden ratio:
--
-- > golden = round ((sqrt 5 - 1) * 2^32)
--
-- We get good key uniqueness on small inputs
-- (a problem with previous versions):
-- (length $ group $ sort $ map hashInt32 [-32767..65536]) == 65536 + 32768
--
hashInt32 :: Int32 -> Int32
hashInt32 x = mulHi x golden + x
-- hi 32 bits of a x-bit * 32 bit -> 64-bit multiply
mulHi :: Int32 -> Int32 -> Int32
mulHi a b = fromIntegral (r `shiftR` 32)
where r :: Int64
r = fromIntegral a * fromIntegral b
|
pparkkin/eta
|
compiler/ETA/Utils/Util.hs
|
bsd-3-clause
| 38,411
| 0
| 19
| 11,754
| 9,887
| 5,387
| 4,500
| 581
| 8
|
len [a] - Int
len lst = sum[1 x - lst]
main = do
inputdata - getContents
putStrLn $ show $ len $ map (read String - Int) $ lines inputdata
|
zeyuanxy/hacker-rank
|
practice/fp/intro/fp-list-length/fp-list-length.hs
|
mit
| 146
| 0
| 12
| 38
| 82
| 38
| 44
| -1
| -1
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program.Hpc
-- Copyright : Thomas Tuegel 2011
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This module provides an library interface to the @hpc@ program.
module Distribution.Simple.Program.Hpc
( markup
, union
) where
import Distribution.ModuleName ( ModuleName )
import Distribution.Simple.Program.Run
( ProgramInvocation, programInvocation, runProgramInvocation )
import Distribution.Simple.Program.Types ( ConfiguredProgram(..) )
import Distribution.Text ( display )
import Distribution.Simple.Utils ( warn )
import Distribution.Verbosity ( Verbosity )
import Distribution.Version ( Version(..), orLaterVersion, withinRange )
-- | Invoke hpc with the given parameters.
--
-- Prior to HPC version 0.7 (packaged with GHC 7.8), hpc did not handle
-- multiple .mix paths correctly, so we print a warning, and only pass it the
-- first path in the list. This means that e.g. test suites that import their
-- library as a dependency can still work, but those that include the library
-- modules directly (in other-modules) don't.
markup :: ConfiguredProgram
-> Version
-> Verbosity
-> FilePath -- ^ Path to .tix file
-> [FilePath] -- ^ Paths to .mix file directories
-> FilePath -- ^ Path where html output should be located
-> [ModuleName] -- ^ List of modules to exclude from report
-> IO ()
markup hpc hpcVer verbosity tixFile hpcDirs destDir excluded = do
hpcDirs' <- if withinRange hpcVer (orLaterVersion version07)
then return hpcDirs
else do
warn verbosity $ "Your version of HPC (" ++ display hpcVer
++ ") does not properly handle multiple search paths. "
++ "Coverage report generation may fail unexpectedly. These "
++ "issues are addressed in version 0.7 or later (GHC 7.8 or "
++ "later)."
++ if null droppedDirs
then ""
else " The following search paths have been abandoned: "
++ show droppedDirs
return passedDirs
runProgramInvocation verbosity
(markupInvocation hpc tixFile hpcDirs' destDir excluded)
where
version07 = Version { versionBranch = [0, 7], versionTags = [] }
(passedDirs, droppedDirs) = splitAt 1 hpcDirs
markupInvocation :: ConfiguredProgram
-> FilePath -- ^ Path to .tix file
-> [FilePath] -- ^ Paths to .mix file directories
-> FilePath -- ^ Path where html output should be
-- located
-> [ModuleName] -- ^ List of modules to exclude from
-- report
-> ProgramInvocation
markupInvocation hpc tixFile hpcDirs destDir excluded =
let args = [ "markup", tixFile
, "--destdir=" ++ destDir
]
++ map ("--hpcdir=" ++) hpcDirs
++ ["--exclude=" ++ display moduleName
| moduleName <- excluded ]
in programInvocation hpc args
union :: ConfiguredProgram
-> Verbosity
-> [FilePath] -- ^ Paths to .tix files
-> FilePath -- ^ Path to resultant .tix file
-> [ModuleName] -- ^ List of modules to exclude from union
-> IO ()
union hpc verbosity tixFiles outFile excluded =
runProgramInvocation verbosity
(unionInvocation hpc tixFiles outFile excluded)
unionInvocation :: ConfiguredProgram
-> [FilePath] -- ^ Paths to .tix files
-> FilePath -- ^ Path to resultant .tix file
-> [ModuleName] -- ^ List of modules to exclude from union
-> ProgramInvocation
unionInvocation hpc tixFiles outFile excluded =
programInvocation hpc $ concat
[ ["sum", "--union"]
, tixFiles
, ["--output=" ++ outFile]
, ["--exclude=" ++ display moduleName
| moduleName <- excluded ]
]
|
jwiegley/ghc-release
|
libraries/Cabal/cabal/Distribution/Simple/Program/Hpc.hs
|
gpl-3.0
| 4,227
| 0
| 18
| 1,329
| 639
| 360
| 279
| 71
| 3
|
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module GHC.Stack (module M) where
import "base" GHC.Stack as M
|
Ye-Yong-Chi/codeworld
|
codeworld-base/src/GHC/Stack.hs
|
apache-2.0
| 733
| 0
| 4
| 136
| 23
| 17
| 6
| 4
| 0
|
{-# LANGUAGE BangPatterns, CPP, NondecreasingIndentation, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
-- NB: we specifically ignore deprecations. GHC 7.6 marks the .QSem module as
-- deprecated, although it became un-deprecated later. As a result, using 7.6
-- as your bootstrap compiler throws annoying warnings.
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2011
--
-- This module implements multi-module compilation, and is used
-- by --make and GHCi.
--
-- -----------------------------------------------------------------------------
module Compiler.GhcMake(
depanal,
load, LoadHowMuch(..),
topSortModuleGraph,
noModError, cyclicModuleErr
) where
-- #include "HsVersions.h"
-- #ifdef GHCI
-- import qualified Linker ( unload )
-- #endif
import DriverPhases
import Compiler.DriverPipeline
import DynFlags hiding (isObjectTarget)
import ErrUtils
import Finder
import GhcMonad
import HeaderInfo
import HsSyn
import HscTypes
import Module
import RdrName ( RdrName )
import TcIface ( typecheckIface )
import TcRnMonad ( initIfaceCheck )
import Bag ( listToBag )
import BasicTypes
import Digraph
import Exception ( tryIO, gbracket, gfinally )
import FastString
import Maybes ( expectJust )
import MonadUtils ( allM, MonadIO )
import Outputable
import Panic
import SrcLoc
import StringBuffer
import SysTools
import UniqFM
import Util
import Data.Either ( rights, partitionEithers )
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import qualified FiniteMap as Map ( insertListWith )
import Control.Concurrent ( forkIOWithUnmask, killThread )
import qualified GHC.Conc as CC
import Control.Concurrent.MVar
import Control.Concurrent.QSem
import Control.Exception
import Control.Monad
import Data.IORef
import Data.List
import qualified Data.List as List
import Data.Maybe
import Data.Ord ( comparing )
import Data.Time
import System.Directory
import System.FilePath
import System.IO ( fixIO )
import System.IO.Error ( isDoesNotExistError )
import GHC.Conc ( getNumProcessors, getNumCapabilities, setNumCapabilities )
isObjectTarget _ = True
label_self :: String -> IO ()
label_self thread_name = do
self_tid <- CC.myThreadId
CC.labelThread self_tid thread_name
-- -----------------------------------------------------------------------------
-- Loading the program
-- | Perform a dependency analysis starting from the current targets
-- and update the session with the new module graph.
--
-- Dependency analysis entails parsing the @import@ directives and may
-- therefore require running certain preprocessors.
--
-- Note that each 'ModSummary' in the module graph caches its 'DynFlags'.
-- These 'DynFlags' are determined by the /current/ session 'DynFlags' and the
-- @OPTIONS@ and @LANGUAGE@ pragmas of the parsed module. Thus if you want to
-- changes to the 'DynFlags' to take effect you need to call this function
-- again.
--
depanal :: GhcMonad m =>
[ModuleName] -- ^ excluded modules
-> Bool -- ^ allow duplicate roots
-> m ModuleGraph
depanal excluded_mods allow_dup_roots = do
hsc_env <- getSession
let
dflags = hsc_dflags hsc_env
targets = hsc_targets hsc_env
old_graph = hsc_mod_graph hsc_env
liftIO $ showPass dflags "Chasing dependencies"
liftIO $ debugTraceMsg dflags 2 (hcat [
text "Chasing modules from: ",
hcat (punctuate comma (map pprTarget targets))])
mod_graphE <- liftIO $ downsweep hsc_env old_graph excluded_mods allow_dup_roots
mod_graph <- reportImportErrors mod_graphE
modifySession $ \_ -> hsc_env { hsc_mod_graph = mod_graph }
return mod_graph
-- | Describes which modules of the module graph need to be loaded.
data LoadHowMuch
= LoadAllTargets
-- ^ Load all targets and its dependencies.
| LoadUpTo ModuleName
-- ^ Load only the given module and its dependencies.
| LoadDependenciesOf ModuleName
-- ^ Load only the dependencies of the given module, but not the module
-- itself.
-- | Try to load the program. See 'LoadHowMuch' for the different modes.
--
-- This function implements the core of GHC's @--make@ mode. It preprocesses,
-- compiles and loads the specified modules, avoiding re-compilation wherever
-- possible. Depending on the target (see 'DynFlags.hscTarget') compilating
-- and loading may result in files being created on disk.
--
-- Calls the 'reportModuleCompilationResult' callback after each compiling
-- each module, whether successful or not.
--
-- Throw a 'SourceError' if errors are encountered before the actual
-- compilation starts (e.g., during dependency analysis). All other errors
-- are reported using the callback.
--
load :: GhcMonad m => LoadHowMuch -> m SuccessFlag
load how_much = do
mod_graph <- depanal [] False
guessOutputFile
hsc_env <- getSession
let hpt1 = hsc_HPT hsc_env
let dflags = hsc_dflags hsc_env
-- The "bad" boot modules are the ones for which we have
-- B.hs-boot in the module graph, but no B.hs
-- The downsweep should have ensured this does not happen
-- (see msDeps)
let all_home_mods = [ms_mod_name s
| s <- mod_graph, not (isBootSummary s)]
bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
not (ms_mod_name s `elem` all_home_mods)]
-- ASSERT( null bad_boot_mods ) return ()
-- check that the module given in HowMuch actually exists, otherwise
-- topSortModuleGraph will bomb later.
let checkHowMuch (LoadUpTo m) = checkMod m
checkHowMuch (LoadDependenciesOf m) = checkMod m
checkHowMuch _ = id
checkMod m and_then
| m `elem` all_home_mods = and_then
| otherwise = do
liftIO $ errorMsg dflags (text "no such module:" <+>
quotes (ppr m))
return Failed
checkHowMuch how_much $ do
-- mg2_with_srcimps drops the hi-boot nodes, returning a
-- graph with cycles. Among other things, it is used for
-- backing out partially complete cycles following a failed
-- upsweep, and for removing from hpt all the modules
-- not in strict downwards closure, during calls to compile.
let mg2_with_srcimps :: [SCC ModSummary]
mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
-- If we can determine that any of the {-# SOURCE #-} imports
-- are definitely unnecessary, then emit a warning.
warnUnnecessarySourceImports mg2_with_srcimps
let
-- check the stability property for each module.
stable_mods@(stable_obj,stable_bco)
= checkStability hpt1 mg2_with_srcimps all_home_mods
-- prune bits of the HPT which are definitely redundant now,
-- to save space.
pruned_hpt = pruneHomePackageTable hpt1
(flattenSCCs mg2_with_srcimps)
stable_mods
_ <- liftIO $ evaluate pruned_hpt
-- before we unload anything, make sure we don't leave an old
-- interactive context around pointing to dead bindings. Also,
-- write the pruned HPT to allow the old HPT to be GC'd.
modifySession $ \_ -> discardIC $ hsc_env { hsc_HPT = pruned_hpt }
liftIO $ debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
text "Stable BCO:" <+> ppr stable_bco)
-- Unload any modules which are going to be re-linked this time around.
let stable_linkables = [ linkable
| m <- stable_obj++stable_bco,
Just hmi <- [lookupUFM pruned_hpt m],
Just linkable <- [hm_linkable hmi] ]
liftIO $ unload hsc_env stable_linkables
-- We could at this point detect cycles which aren't broken by
-- a source-import, and complain immediately, but it seems better
-- to let upsweep_mods do this, so at least some useful work gets
-- done before the upsweep is abandoned.
--hPutStrLn stderr "after tsort:\n"
--hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
-- Now do the upsweep, calling compile for each module in
-- turn. Final result is version 3 of everything.
-- Topologically sort the module graph, this time including hi-boot
-- nodes, and possibly just including the portion of the graph
-- reachable from the module specified in the 2nd argument to load.
-- This graph should be cycle-free.
-- If we're restricting the upsweep to a portion of the graph, we
-- also want to retain everything that is still stable.
let full_mg :: [SCC ModSummary]
full_mg = topSortModuleGraph False mod_graph Nothing
maybe_top_mod = case how_much of
LoadUpTo m -> Just m
LoadDependenciesOf m -> Just m
_ -> Nothing
partial_mg0 :: [SCC ModSummary]
partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
-- LoadDependenciesOf m: we want the upsweep to stop just
-- short of the specified module (unless the specified module
-- is stable).
partial_mg
| LoadDependenciesOf _mod <- how_much
= {- ASSERT( case last partial_mg0 of
AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False ) -}
List.init partial_mg0
| otherwise
= partial_mg0
stable_mg =
[ AcyclicSCC ms
| AcyclicSCC ms <- full_mg,
ms_mod_name ms `elem` stable_obj++stable_bco ]
-- the modules from partial_mg that are not also stable
-- NB. also keep cycles, we need to emit an error message later
unstable_mg = filter not_stable partial_mg
where not_stable (CyclicSCC _) = True
not_stable (AcyclicSCC ms)
= ms_mod_name ms `notElem` stable_obj++stable_bco
-- Load all the stable modules first, before attempting to load
-- an unstable module (#7231).
mg = stable_mg ++ unstable_mg
-- clean up between compilations
let cleanup hsc_env = intermediateCleanTempFiles (hsc_dflags hsc_env)
(flattenSCCs mg2_with_srcimps)
hsc_env
liftIO $ debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
2 (ppr mg))
n_jobs <- case parMakeCount dflags of
Nothing -> liftIO getNumProcessors
Just n -> return n
let upsweep_fn | n_jobs > 1 = parUpsweep n_jobs
| otherwise = upsweep
setSession hsc_env{ hsc_HPT = emptyHomePackageTable }
(upsweep_ok, modsUpswept)
<- upsweep_fn pruned_hpt stable_mods cleanup mg
-- Make modsDone be the summaries for each home module now
-- available; this should equal the domain of hpt3.
-- Get in in a roughly top .. bottom order (hence reverse).
let modsDone = reverse modsUpswept
-- Try and do linking in some form, depending on whether the
-- upsweep was completely or only partially successful.
if succeeded upsweep_ok
then
-- Easy; just relink it all.
do liftIO $ debugTraceMsg dflags 2 (text "Upsweep completely successful.")
-- Clean up after ourselves
hsc_env1 <- getSession
liftIO $ intermediateCleanTempFiles dflags modsDone hsc_env1
-- Issue a warning for the confusing case where the user
-- said '-o foo' but we're not going to do any linking.
-- We attempt linking if either (a) one of the modules is
-- called Main, or (b) the user said -no-hs-main, indicating
-- that main() is going to come from somewhere else.
--
let ofile = outputFile dflags
let no_hs_main = gopt Opt_NoHsMain dflags
let
main_mod = mainModIs dflags
a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
do_linking = a_root_is_Main || no_hs_main || ghcLink dflags == LinkDynLib || ghcLink dflags == LinkStaticLib
when (ghcLink dflags == LinkBinary
&& isJust ofile && not do_linking) $
liftIO $ debugTraceMsg dflags 1 $
text ("Warning: output was redirected with -o, " ++
"but no output will be generated\n" ++
"because there is no " ++
moduleNameString (moduleName main_mod) ++ " module.")
-- link everything together
linkresult <- liftIO $ link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
loadFinish Succeeded linkresult
else
-- Tricky. We need to back out the effects of compiling any
-- half-done cycles, both so as to clean up the top level envs
-- and to avoid telling the interactive linker to link them.
do liftIO $ debugTraceMsg dflags 2 (text "Upsweep partially successful.")
let modsDone_names
= map ms_mod modsDone
let mods_to_zap_names
= findPartiallyCompletedCycles modsDone_names
mg2_with_srcimps
let mods_to_keep
= filter ((`notElem` mods_to_zap_names).ms_mod)
modsDone
hsc_env1 <- getSession
let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
(hsc_HPT hsc_env1)
-- Clean up after ourselves
liftIO $ intermediateCleanTempFiles dflags mods_to_keep hsc_env1
-- there should be no Nothings where linkables should be, now
-- ASSERT(all (isJust.hm_linkable) (eltsUFM (hsc_HPT hsc_env))) do
-- Link everything together
linkresult <- liftIO $ link (ghcLink dflags) dflags False hpt4
modifySession $ \hsc_env -> hsc_env{ hsc_HPT = hpt4 }
loadFinish Failed linkresult
-- | Finish up after a load.
loadFinish :: GhcMonad m => SuccessFlag -> SuccessFlag -> m SuccessFlag
-- If the link failed, unload everything and return.
loadFinish _all_ok Failed
= do hsc_env <- getSession
liftIO $ unload hsc_env []
modifySession discardProg
return Failed
-- Empty the interactive context and set the module context to the topmost
-- newly loaded module, or the Prelude if none were loaded.
loadFinish all_ok Succeeded
= do modifySession discardIC
return all_ok
-- | Forget the current program, but retain the persistent info in HscEnv
discardProg :: HscEnv -> HscEnv
discardProg hsc_env
= discardIC $ hsc_env { hsc_mod_graph = emptyMG
, hsc_HPT = emptyHomePackageTable }
-- | Discard the contents of the InteractiveContext, but keep the DynFlags
discardIC :: HscEnv -> HscEnv
discardIC hsc_env
= hsc_env { hsc_IC = emptyInteractiveContext (ic_dflags (hsc_IC hsc_env)) }
intermediateCleanTempFiles :: DynFlags -> [ModSummary] -> HscEnv -> IO ()
intermediateCleanTempFiles dflags summaries hsc_env
= do notIntermediate <- readIORef (filesToNotIntermediateClean dflags)
cleanTempFilesExcept dflags (notIntermediate ++ except)
where
except =
-- Save preprocessed files. The preprocessed file *might* be
-- the same as the source file, but that doesn't do any
-- harm.
map ms_hspp_file summaries ++
-- Save object files for loaded modules. The point of this
-- is that we might have generated and compiled a stub C
-- file, and in the case of GHCi the object file will be a
-- temporary file which we must not remove because we need
-- to load/link it later.
hptObjs (hsc_HPT hsc_env)
-- | If there is no -o option, guess the name of target executable
-- by using top-level source file name as a base.
guessOutputFile :: GhcMonad m => m ()
guessOutputFile = modifySession $ \env ->
let dflags = hsc_dflags env
mod_graph = hsc_mod_graph env
mainModuleSrcPath :: Maybe String
mainModuleSrcPath = do
let isMain = (== mainModIs dflags) . ms_mod
[ms] <- return (filter isMain mod_graph)
ml_hs_file (ms_location ms)
name = fmap dropExtension mainModuleSrcPath
name_exe = do
#if defined(mingw32_HOST_OS)
-- we must add the .exe extention unconditionally here, otherwise
-- when name has an extension of its own, the .exe extension will
-- not be added by DriverPipeline.exeFileName. See #2248
name' <- fmap (<.> "exe") name
#else
name' <- name
#endif
mainModuleSrcPath' <- mainModuleSrcPath
-- #9930: don't clobber input files (unless they ask for it)
if name' == mainModuleSrcPath'
then throwGhcException . UsageError $
"default output name would overwrite the input file; " ++
"must specify -o explicitly"
else Just name'
in
case outputFile dflags of
Just _ -> env
Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
-- -----------------------------------------------------------------------------
--
-- | Prune the HomePackageTable
--
-- Before doing an upsweep, we can throw away:
--
-- - For non-stable modules:
-- - all ModDetails, all linked code
-- - all unlinked code that is out of date with respect to
-- the source file
--
-- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
-- space at the end of the upsweep, because the topmost ModDetails of the
-- old HPT holds on to the entire type environment from the previous
-- compilation.
pruneHomePackageTable :: HomePackageTable
-> [ModSummary]
-> ([ModuleName],[ModuleName])
-> HomePackageTable
pruneHomePackageTable hpt summ (stable_obj, stable_bco)
= mapUFM prune hpt
where prune hmi
| is_stable modl = hmi'
| otherwise = hmi'{ hm_details = emptyModDetails }
where
modl = moduleName (mi_module (hm_iface hmi))
hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
= hmi{ hm_linkable = Nothing }
| otherwise
= hmi
where ms = expectJust "prune" (lookupUFM ms_map modl)
ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
is_stable m = m `elem` stable_obj || m `elem` stable_bco
-- -----------------------------------------------------------------------------
--
-- | Return (names of) all those in modsDone who are part of a cycle as defined
-- by theGraph.
findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
findPartiallyCompletedCycles modsDone theGraph
= chew theGraph
where
chew [] = []
chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
chew ((CyclicSCC vs):rest)
= let names_in_this_cycle = nub (map ms_mod vs)
mods_in_this_cycle
= nub ([done | done <- modsDone,
done `elem` names_in_this_cycle])
chewed_rest = chew rest
in
if notNull mods_in_this_cycle
&& length mods_in_this_cycle < length names_in_this_cycle
then mods_in_this_cycle ++ chewed_rest
else chewed_rest
-- ---------------------------------------------------------------------------
--
-- | Unloading
unload :: HscEnv -> [Linkable] -> IO ()
unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
= return ()
{-
case ghcLink (hsc_dflags hsc_env) of
#ifdef GHCI
LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
#else
LinkInMemory -> panic "unload: no interpreter"
-- urgh. avoid warnings:
hsc_env stable_linkables
#endif
_other -> return ()
-}
-- -----------------------------------------------------------------------------
{- |
Stability tells us which modules definitely do not need to be recompiled.
There are two main reasons for having stability:
- avoid doing a complete upsweep of the module graph in GHCi when
modules near the bottom of the tree have not changed.
- to tell GHCi when it can load object code: we can only load object code
for a module when we also load object code fo all of the imports of the
module. So we need to know that we will definitely not be recompiling
any of these modules, and we can use the object code.
The stability check is as follows. Both stableObject and
stableBCO are used during the upsweep phase later.
@
stable m = stableObject m || stableBCO m
stableObject m =
all stableObject (imports m)
&& old linkable does not exist, or is == on-disk .o
&& date(on-disk .o) > date(.hs)
stableBCO m =
all stable (imports m)
&& date(BCO) > date(.hs)
@
These properties embody the following ideas:
- if a module is stable, then:
- if it has been compiled in a previous pass (present in HPT)
then it does not need to be compiled or re-linked.
- if it has not been compiled in a previous pass,
then we only need to read its .hi file from disk and
link it to produce a 'ModDetails'.
- if a modules is not stable, we will definitely be at least
re-linking, and possibly re-compiling it during the 'upsweep'.
All non-stable modules can (and should) therefore be unlinked
before the 'upsweep'.
- Note that objects are only considered stable if they only depend
on other objects. We can't link object code against byte code.
-}
checkStability
:: HomePackageTable -- HPT from last compilation
-> [SCC ModSummary] -- current module graph (cyclic)
-> [ModuleName] -- all home modules
-> ([ModuleName], -- stableObject
[ModuleName]) -- stableBCO
checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
where
checkSCC (stable_obj, stable_bco) scc0
| stableObjects = (scc_mods ++ stable_obj, stable_bco)
| stableBCOs = (stable_obj, scc_mods ++ stable_bco)
| otherwise = (stable_obj, stable_bco)
where
scc = flattenSCC scc0
scc_mods = map ms_mod_name scc
home_module m = m `elem` all_home_mods && m `notElem` scc_mods
scc_allimps = nub (filter home_module (concatMap ms_home_allimps scc))
-- all imports outside the current SCC, but in the home pkg
stable_obj_imps = map (`elem` stable_obj) scc_allimps
stable_bco_imps = map (`elem` stable_bco) scc_allimps
stableObjects =
and stable_obj_imps
&& all object_ok scc
stableBCOs =
and (zipWith (||) stable_obj_imps stable_bco_imps)
&& all bco_ok scc
object_ok ms
| gopt Opt_ForceRecomp (ms_hspp_opts ms) = False
| Just t <- ms_obj_date ms = t >= ms_hs_date ms
&& same_as_prev t
| otherwise = False
where
same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
Just hmi | Just l <- hm_linkable hmi
-> isObjectLinkable l && t == linkableTime l
_other -> True
-- why '>=' rather than '>' above? If the filesystem stores
-- times to the nearset second, we may occasionally find that
-- the object & source have the same modification time,
-- especially if the source was automatically generated
-- and compiled. Using >= is slightly unsafe, but it matches
-- make's behaviour.
--
-- But see #5527, where someone ran into this and it caused
-- a problem.
bco_ok ms
| gopt Opt_ForceRecomp (ms_hspp_opts ms) = False
| otherwise = case lookupUFM hpt (ms_mod_name ms) of
Just hmi | Just l <- hm_linkable hmi ->
not (isObjectLinkable l) &&
linkableTime l >= ms_hs_date ms
_other -> False
{- Parallel Upsweep
-
- The parallel upsweep attempts to concurrently compile the modules in the
- compilation graph using multiple Haskell threads.
-
- The Algorithm
-
- A Haskell thread is spawned for each module in the module graph, waiting for
- its direct dependencies to finish building before it itself begins to build.
-
- Each module is associated with an initially empty MVar that stores the
- result of that particular module's compile. If the compile succeeded, then
- the HscEnv (synchronized by an MVar) is updated with the fresh HMI of that
- module, and the module's HMI is deleted from the old HPT (synchronized by an
- IORef) to save space.
-
- Instead of immediately outputting messages to the standard handles, all
- compilation output is deferred to a per-module TQueue. A QSem is used to
- limit the number of workers that are compiling simultaneously.
-
- Meanwhile, the main thread sequentially loops over all the modules in the
- module graph, outputting the messages stored in each module's TQueue.
-}
-- | Each module is given a unique 'LogQueue' to redirect compilation messages
-- to. A 'Nothing' value contains the result of compilation, and denotes the
-- end of the message queue.
data LogQueue = LogQueue !(IORef [Maybe (Severity, SrcSpan, PprStyle, MsgDoc)])
!(MVar ())
-- | The graph of modules to compile and their corresponding result 'MVar' and
-- 'LogQueue'.
type CompilationGraph = [(ModSummary, MVar SuccessFlag, LogQueue)]
-- | Build a 'CompilationGraph' out of a list of strongly-connected modules,
-- also returning the first, if any, encountered module cycle.
buildCompGraph :: [SCC ModSummary] -> IO (CompilationGraph, Maybe [ModSummary])
buildCompGraph [] = return ([], Nothing)
buildCompGraph (scc:sccs) = case scc of
AcyclicSCC ms -> do
mvar <- newEmptyMVar
log_queue <- do
ref <- newIORef []
sem <- newEmptyMVar
return (LogQueue ref sem)
(rest,cycle) <- buildCompGraph sccs
return ((ms,mvar,log_queue):rest, cycle)
CyclicSCC mss -> return ([], Just mss)
-- A Module and whether it is a boot module.
type BuildModule = (Module, IsBoot)
-- | 'Bool' indicating if a module is a boot module or not. We need to treat
-- boot modules specially when building compilation graphs, since they break
-- cycles. Regular source files and signature files are treated equivalently.
data IsBoot = IsBoot | NotBoot
deriving (Ord, Eq, Show, Read)
-- | Tests if an 'HscSource' is a boot file, primarily for constructing
-- elements of 'BuildModule'.
hscSourceToIsBoot :: HscSource -> IsBoot
hscSourceToIsBoot HsBootFile = IsBoot
hscSourceToIsBoot _ = NotBoot
mkBuildModule :: ModSummary -> BuildModule
mkBuildModule ms = (ms_mod ms, if isBootSummary ms then IsBoot else NotBoot)
-- | The entry point to the parallel upsweep.
--
-- See also the simpler, sequential 'upsweep'.
parUpsweep
:: GhcMonad m
=> Int
-- ^ The number of workers we wish to run in parallel
-> HomePackageTable
-> ([ModuleName],[ModuleName])
-> (HscEnv -> IO ())
-> [SCC ModSummary]
-> m (SuccessFlag,
[ModSummary])
parUpsweep n_jobs old_hpt stable_mods cleanup sccs = do
hsc_env <- getSession
let dflags = hsc_dflags hsc_env
-- The bits of shared state we'll be using:
-- The global HscEnv is updated with the module's HMI when a module
-- successfully compiles.
hsc_env_var <- liftIO $ newMVar hsc_env
-- The old HPT is used for recompilation checking in upsweep_mod. When a
-- module sucessfully gets compiled, its HMI is pruned from the old HPT.
old_hpt_var <- liftIO $ newIORef old_hpt
-- What we use to limit parallelism with.
par_sem <- liftIO $ newQSem n_jobs
let updNumCapabilities = liftIO $ do
n_capabilities <- getNumCapabilities
unless (n_capabilities /= 1) $ setNumCapabilities n_jobs
return n_capabilities
-- Reset the number of capabilities once the upsweep ends.
let resetNumCapabilities orig_n = liftIO $ setNumCapabilities orig_n
gbracket updNumCapabilities resetNumCapabilities $ \_ -> do
-- Sync the global session with the latest HscEnv once the upsweep ends.
let finallySyncSession io = io `gfinally` do
hsc_env <- liftIO $ readMVar hsc_env_var
setSession hsc_env
finallySyncSession $ do
-- Build the compilation graph out of the list of SCCs. Module cycles are
-- handled at the very end, after some useful work gets done. Note that
-- this list is topologically sorted (by virtue of 'sccs' being sorted so).
(comp_graph,cycle) <- liftIO $ buildCompGraph sccs
let comp_graph_w_idx = zip comp_graph [1..]
-- The list of all loops in the compilation graph.
-- NB: For convenience, the last module of each loop (aka the module that
-- finishes the loop) is prepended to the beginning of the loop.
let comp_graph_loops = go (map fstOf3 (reverse comp_graph))
where
go [] = []
go (ms:mss) | Just loop <- getModLoop ms (ms:mss)
= map mkBuildModule (ms:loop) : go mss
| otherwise
= go mss
-- Build a Map out of the compilation graph with which we can efficiently
-- look up the result MVar associated with a particular home module.
let home_mod_map :: Map BuildModule (MVar SuccessFlag, Int)
home_mod_map =
Map.fromList [ (mkBuildModule ms, (mvar, idx))
| ((ms,mvar,_),idx) <- comp_graph_w_idx ]
liftIO $ label_self "main --make thread"
-- For each module in the module graph, spawn a worker thread that will
-- compile this module.
let { spawnWorkers = forM comp_graph_w_idx $ \((mod,!mvar,!log_queue),!mod_idx) ->
forkIOWithUnmask $ \unmask -> do
liftIO $ label_self $ unwords
[ "worker --make thread"
, "for module"
, show (moduleNameString (ms_mod_name mod))
, "number"
, show mod_idx
]
-- Replace the default log_action with one that writes each
-- message to the module's log_queue. The main thread will
-- deal with synchronously printing these messages.
--
-- Use a local filesToClean var so that we can clean up
-- intermediate files in a timely fashion (as soon as
-- compilation for that module is finished) without having to
-- worry about accidentally deleting a simultaneous compile's
-- important files.
lcl_files_to_clean <- newIORef []
let lcl_dflags = dflags { log_action = parLogAction log_queue
, filesToClean = lcl_files_to_clean }
-- Unmask asynchronous exceptions and perform the thread-local
-- work to compile the module (see parUpsweep_one).
m_res <- try $ unmask $ prettyPrintGhcErrors lcl_dflags $
parUpsweep_one mod home_mod_map comp_graph_loops
lcl_dflags cleanup
par_sem hsc_env_var old_hpt_var
stable_mods mod_idx (length sccs)
res <- case m_res of
Right flag -> return flag
Left exc -> do
-- Don't print ThreadKilled exceptions: they are used
-- to kill the worker thread in the event of a user
-- interrupt, and the user doesn't have to be informed
-- about that.
when (fromException exc /= Just ThreadKilled)
(errorMsg lcl_dflags (text (show exc)))
return Failed
-- Populate the result MVar.
putMVar mvar res
-- Write the end marker to the message queue, telling the main
-- thread that it can stop waiting for messages from this
-- particular compile.
writeLogQueue log_queue Nothing
-- Add the remaining files that weren't cleaned up to the
-- global filesToClean ref, for cleanup later.
files_kept <- readIORef (filesToClean lcl_dflags)
addFilesToClean dflags files_kept
-- Kill all the workers, masking interrupts (since killThread is
-- interruptible). XXX: This is not ideal.
; killWorkers = uninterruptibleMask_ . mapM_ killThread }
-- Spawn the workers, making sure to kill them later. Collect the results
-- of each compile.
results <- liftIO $ bracket spawnWorkers killWorkers $ \_ ->
-- Loop over each module in the compilation graph in order, printing
-- each message from its log_queue.
forM comp_graph $ \(mod,mvar,log_queue) -> do
printLogs dflags log_queue
result <- readMVar mvar
if succeeded result then return (Just mod) else return Nothing
-- Collect and return the ModSummaries of all the successful compiles.
-- NB: Reverse this list to maintain output parity with the sequential upsweep.
let ok_results = reverse (catMaybes results)
-- Handle any cycle in the original compilation graph and return the result
-- of the upsweep.
case cycle of
Just mss -> do
liftIO $ fatalErrorMsg dflags (cyclicModuleErr mss)
return (Failed,ok_results)
Nothing -> do
let success_flag = successIf (all isJust results)
return (success_flag,ok_results)
where
writeLogQueue :: LogQueue -> Maybe (Severity,SrcSpan,PprStyle,MsgDoc) -> IO ()
writeLogQueue (LogQueue ref sem) msg = do
atomicModifyIORef ref $ \msgs -> (msg:msgs,())
_ <- tryPutMVar sem ()
return ()
-- The log_action callback that is used to synchronize messages from a
-- worker thread.
parLogAction :: LogQueue -> LogAction
parLogAction log_queue _dflags !severity !srcSpan !style !msg = do
writeLogQueue log_queue (Just (severity,srcSpan,style,msg))
-- Print each message from the log_queue using the log_action from the
-- session's DynFlags.
printLogs :: DynFlags -> LogQueue -> IO ()
printLogs !dflags (LogQueue ref sem) = read_msgs
where read_msgs = do
takeMVar sem
msgs <- atomicModifyIORef ref $ \xs -> ([], reverse xs)
print_loop msgs
print_loop [] = read_msgs
print_loop (x:xs) = case x of
Just (severity,srcSpan,style,msg) -> do
log_action dflags dflags severity srcSpan style msg
print_loop xs
-- Exit the loop once we encounter the end marker.
Nothing -> return ()
-- The interruptible subset of the worker threads' work.
parUpsweep_one
:: ModSummary
-- ^ The module we wish to compile
-> Map BuildModule (MVar SuccessFlag, Int)
-- ^ The map of home modules and their result MVar
-> [[BuildModule]]
-- ^ The list of all module loops within the compilation graph.
-> DynFlags
-- ^ The thread-local DynFlags
-> (HscEnv -> IO ())
-- ^ The callback for cleaning up intermediate files
-> QSem
-- ^ The semaphore for limiting the number of simultaneous compiles
-> MVar HscEnv
-- ^ The MVar that synchronizes updates to the global HscEnv
-> IORef HomePackageTable
-- ^ The old HPT
-> ([ModuleName],[ModuleName])
-- ^ Lists of stable objects and BCOs
-> Int
-- ^ The index of this module
-> Int
-- ^ The total number of modules
-> IO SuccessFlag
-- ^ The result of this compile
parUpsweep_one mod home_mod_map comp_graph_loops lcl_dflags cleanup par_sem
hsc_env_var old_hpt_var stable_mods mod_index num_mods = do
let this_build_mod = mkBuildModule mod
let home_imps = map unLoc $ ms_home_imps mod
let home_src_imps = map unLoc $ ms_home_srcimps mod
-- All the textual imports of this module.
let textual_deps = Set.fromList $ mapFst (mkModule (thisPackage lcl_dflags)) $
zip home_imps (repeat NotBoot) ++
zip home_src_imps (repeat IsBoot)
-- Dealing with module loops
-- ~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- Not only do we have to deal with explicit textual dependencies, we also
-- have to deal with implicit dependencies introduced by import cycles that
-- are broken by an hs-boot file. We have to ensure that:
--
-- 1. A module that breaks a loop must depend on all the modules in the
-- loop (transitively or otherwise). This is normally always fulfilled
-- by the module's textual dependencies except in degenerate loops,
-- e.g.:
--
-- A.hs imports B.hs-boot
-- B.hs doesn't import A.hs
-- C.hs imports A.hs, B.hs
--
-- In this scenario, getModLoop will detect the module loop [A,B] but
-- the loop finisher B doesn't depend on A. So we have to explicitly add
-- A in as a dependency of B when we are compiling B.
--
-- 2. A module that depends on a module in an external loop can't proceed
-- until the entire loop is re-typechecked.
--
-- These two invariants have to be maintained to correctly build a
-- compilation graph with one or more loops.
-- The loop that this module will finish. After this module successfully
-- compiles, this loop is going to get re-typechecked.
let finish_loop = listToMaybe
[ tail loop | loop <- comp_graph_loops
, head loop == this_build_mod ]
-- If this module finishes a loop then it must depend on all the other
-- modules in that loop because the entire module loop is going to be
-- re-typechecked once this module gets compiled. These extra dependencies
-- are this module's "internal" loop dependencies, because this module is
-- inside the loop in question.
let int_loop_deps = Set.fromList $
case finish_loop of
Nothing -> []
Just loop -> filter (/= this_build_mod) loop
-- If this module depends on a module within a loop then it must wait for
-- that loop to get re-typechecked, i.e. it must wait on the module that
-- finishes that loop. These extra dependencies are this module's
-- "external" loop dependencies, because this module is outside of the
-- loop(s) in question.
let ext_loop_deps = Set.fromList
[ head loop | loop <- comp_graph_loops
, any (`Set.member` textual_deps) loop
, this_build_mod `notElem` loop ]
let all_deps = foldl1 Set.union [textual_deps, int_loop_deps, ext_loop_deps]
-- All of the module's home-module dependencies.
let home_deps_with_idx =
[ home_dep | dep <- Set.toList all_deps
, Just home_dep <- [Map.lookup dep home_mod_map] ]
-- Sort the list of dependencies in reverse-topological order. This way, by
-- the time we get woken up by the result of an earlier dependency,
-- subsequent dependencies are more likely to have finished. This step
-- effectively reduces the number of MVars that each thread blocks on.
let home_deps = map fst $ sortBy (flip (comparing snd)) home_deps_with_idx
-- Wait for the all the module's dependencies to finish building.
deps_ok <- allM (fmap succeeded . readMVar) home_deps
-- We can't build this module if any of its dependencies failed to build.
if not deps_ok
then return Failed
else do
-- Any hsc_env at this point is OK to use since we only really require
-- that the HPT contains the HMIs of our dependencies.
hsc_env <- readMVar hsc_env_var
old_hpt <- readIORef old_hpt_var
let logger err = printBagOfErrors lcl_dflags (srcErrorMessages err)
-- Limit the number of parallel compiles.
let withSem sem = bracket_ (waitQSem sem) (signalQSem sem)
mb_mod_info <- withSem par_sem $
handleSourceError (\err -> do logger err; return Nothing) $ do
-- Have the ModSummary and HscEnv point to our local log_action
-- and filesToClean var.
let lcl_mod = localize_mod mod
let lcl_hsc_env = localize_hsc_env hsc_env
-- Compile the module.
mod_info <- upsweep_mod lcl_hsc_env old_hpt stable_mods lcl_mod
mod_index num_mods
return (Just mod_info)
case mb_mod_info of
Nothing -> return Failed
Just mod_info -> do
let this_mod = ms_mod_name mod
-- Prune the old HPT unless this is an hs-boot module.
unless (isBootSummary mod) $
atomicModifyIORef old_hpt_var $ \old_hpt ->
(delFromUFM old_hpt this_mod, ())
-- Update and fetch the global HscEnv.
lcl_hsc_env' <- modifyMVar hsc_env_var $ \hsc_env -> do
let hsc_env' = hsc_env { hsc_HPT = addToUFM (hsc_HPT hsc_env)
this_mod mod_info }
-- If this module is a loop finisher, now is the time to
-- re-typecheck the loop.
hsc_env'' <- case finish_loop of
Nothing -> return hsc_env'
Just loop -> typecheckLoop lcl_dflags hsc_env' $
map (moduleName . fst) loop
return (hsc_env'', localize_hsc_env hsc_env'')
-- Clean up any intermediate files.
cleanup lcl_hsc_env'
return Succeeded
where
localize_mod mod
= mod { ms_hspp_opts = (ms_hspp_opts mod)
{ log_action = log_action lcl_dflags
, filesToClean = filesToClean lcl_dflags } }
localize_hsc_env hsc_env
= hsc_env { hsc_dflags = (hsc_dflags hsc_env)
{ log_action = log_action lcl_dflags
, filesToClean = filesToClean lcl_dflags } }
-- -----------------------------------------------------------------------------
--
-- | The upsweep
--
-- This is where we compile each module in the module graph, in a pass
-- from the bottom to the top of the graph.
--
-- There better had not be any cyclic groups here -- we check for them.
upsweep
:: GhcMonad m
=> HomePackageTable -- ^ HPT from last time round (pruned)
-> ([ModuleName],[ModuleName]) -- ^ stable modules (see checkStability)
-> (HscEnv -> IO ()) -- ^ How to clean up unwanted tmp files
-> [SCC ModSummary] -- ^ Mods to do (the worklist)
-> m (SuccessFlag,
[ModSummary])
-- ^ Returns:
--
-- 1. A flag whether the complete upsweep was successful.
-- 2. The 'HscEnv' in the monad has an updated HPT
-- 3. A list of modules which succeeded loading.
upsweep old_hpt stable_mods cleanup sccs = do
(res, done) <- upsweep' old_hpt [] sccs 1 (length sccs)
return (res, reverse done)
where
upsweep' _old_hpt done
[] _ _
= return (Succeeded, done)
upsweep' _old_hpt done
(CyclicSCC ms:_) _ _
= do dflags <- getSessionDynFlags
liftIO $ fatalErrorMsg dflags (cyclicModuleErr ms)
return (Failed, done)
upsweep' old_hpt done
(AcyclicSCC mod:mods) mod_index nmods
= do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
-- show (map (moduleUserString.moduleName.mi_module.hm_iface)
-- (moduleEnvElts (hsc_HPT hsc_env)))
let logger _mod = defaultWarnErrLogger
hsc_env <- getSession
-- Remove unwanted tmp files between compilations
liftIO (cleanup hsc_env)
mb_mod_info
<- handleSourceError
(\err -> do logger mod (Just err); return Nothing) $ do
mod_info <- liftIO $ upsweep_mod hsc_env old_hpt stable_mods
mod mod_index nmods
logger mod Nothing -- log warnings
return (Just mod_info)
case mb_mod_info of
Nothing -> return (Failed, done)
Just mod_info -> do
let this_mod = ms_mod_name mod
-- Add new info to hsc_env
hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
hsc_env1 = hsc_env { hsc_HPT = hpt1 }
-- Space-saving: delete the old HPT entry
-- for mod BUT if mod is a hs-boot
-- node, don't delete it. For the
-- interface, the HPT entry is probaby for the
-- main Haskell source file. Deleting it
-- would force the real module to be recompiled
-- every time.
old_hpt1 | isBootSummary mod = old_hpt
| otherwise = delFromUFM old_hpt this_mod
done' = mod:done
-- fixup our HomePackageTable after we've finished compiling
-- a mutually-recursive loop. See reTypecheckLoop, below.
hsc_env2 <- liftIO $ reTypecheckLoop hsc_env1 mod done'
setSession hsc_env2
upsweep' old_hpt1 done' mods (mod_index+1) nmods
maybeGetIfaceDate :: DynFlags -> ModLocation -> IO (Maybe UTCTime)
maybeGetIfaceDate dflags location
| writeInterfaceOnlyMode dflags
-- Minor optimization: it should be harmless to check the hi file location
-- always, but it's better to avoid hitting the filesystem if possible.
= modificationTimeIfExists (ml_hi_file location)
| otherwise
= return Nothing
-- | Compile a single module. Always produce a Linkable for it if
-- successful. If no compilation happened, return the old Linkable.
upsweep_mod :: HscEnv
-> HomePackageTable
-> ([ModuleName],[ModuleName])
-> ModSummary
-> Int -- index of module
-> Int -- total number of modules
-> IO HomeModInfo
upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
= let
this_mod_name = ms_mod_name summary
this_mod = ms_mod summary
mb_obj_date = ms_obj_date summary
mb_if_date = ms_iface_date summary
obj_fn = ml_obj_file (ms_location summary)
hs_date = ms_hs_date summary
is_stable_obj = this_mod_name `elem` stable_obj
is_stable_bco = this_mod_name `elem` stable_bco
old_hmi = lookupUFM old_hpt this_mod_name
-- We're using the dflags for this module now, obtained by
-- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
dflags = ms_hspp_opts summary
prevailing_target = hscTarget (hsc_dflags hsc_env)
local_target = hscTarget dflags
-- If OPTIONS_GHC contains -fasm or -fllvm, be careful that
-- we don't do anything dodgy: these should only work to change
-- from -fllvm to -fasm and vice-versa, otherwise we could
-- end up trying to link object code to byte code.
target = if prevailing_target /= local_target
&& (not (isObjectTarget prevailing_target)
|| not (isObjectTarget local_target))
then prevailing_target
else local_target
-- store the corrected hscTarget into the summary
summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
-- The old interface is ok if
-- a) we're compiling a source file, and the old HPT
-- entry is for a source file
-- b) we're compiling a hs-boot file
-- Case (b) allows an hs-boot file to get the interface of its
-- real source file on the second iteration of the compilation
-- manager, but that does no harm. Otherwise the hs-boot file
-- will always be recompiled
mb_old_iface
= case old_hmi of
Nothing -> Nothing
Just hm_info | isBootSummary summary -> Just iface
| not (mi_boot iface) -> Just iface
| otherwise -> Nothing
where
iface = hm_iface hm_info
compile_it :: Maybe Linkable -> SourceModified -> IO HomeModInfo
compile_it mb_linkable src_modified =
compileOne hsc_env summary' mod_index nmods
mb_old_iface mb_linkable src_modified
compile_it_discard_iface :: Maybe Linkable -> SourceModified
-> IO HomeModInfo
compile_it_discard_iface mb_linkable src_modified =
compileOne hsc_env summary' mod_index nmods
Nothing mb_linkable src_modified
-- With the HscNothing target we create empty linkables to avoid
-- recompilation. We have to detect these to recompile anyway if
-- the target changed since the last compile.
is_fake_linkable
| Just hmi <- old_hmi, Just l <- hm_linkable hmi =
null (linkableUnlinked l)
| otherwise =
-- we have no linkable, so it cannot be fake
False
implies False _ = True
implies True x = x
in
case () of
_
-- Regardless of whether we're generating object code or
-- byte code, we can always use an existing object file
-- if it is *stable* (see checkStability).
| is_stable_obj, Just hmi <- old_hmi -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "skipping stable obj mod:" <+> ppr this_mod_name)
return hmi
-- object is stable, and we have an entry in the
-- old HPT: nothing to do
| is_stable_obj, isNothing old_hmi -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "compiling stable on-disk mod:" <+> ppr this_mod_name)
linkable <- liftIO $ findObjectLinkable this_mod obj_fn
(expectJust "upsweep1" mb_obj_date)
compile_it (Just linkable) SourceUnmodifiedAndStable
-- object is stable, but we need to load the interface
-- off disk to make a HMI.
| not (isObjectTarget target), is_stable_bco,
(target /= HscNothing) `implies` not is_fake_linkable ->
-- ASSERT(isJust old_hmi) -- must be in the old_hpt
let Just hmi = old_hmi in do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "skipping stable BCO mod:" <+> ppr this_mod_name)
return hmi
-- BCO is stable: nothing to do
| not (isObjectTarget target),
Just hmi <- old_hmi,
Just l <- hm_linkable hmi,
not (isObjectLinkable l),
(target /= HscNothing) `implies` not is_fake_linkable,
linkableTime l >= ms_hs_date summary -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "compiling non-stable BCO mod:" <+> ppr this_mod_name)
compile_it (Just l) SourceUnmodified
-- we have an old BCO that is up to date with respect
-- to the source: do a recompilation check as normal.
-- When generating object code, if there's an up-to-date
-- object file on the disk, then we can use it.
-- However, if the object file is new (compared to any
-- linkable we had from a previous compilation), then we
-- must discard any in-memory interface, because this
-- means the user has compiled the source file
-- separately and generated a new interface, that we must
-- read from the disk.
--
| isObjectTarget target,
Just obj_date <- mb_obj_date,
obj_date >= hs_date -> do
case old_hmi of
Just hmi
| Just l <- hm_linkable hmi,
isObjectLinkable l && linkableTime l == obj_date -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "compiling mod with new on-disk obj:" <+> ppr this_mod_name)
compile_it (Just l) SourceUnmodified
_otherwise -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "compiling mod with new on-disk obj2:" <+> ppr this_mod_name)
linkable <- liftIO $ findObjectLinkable this_mod obj_fn obj_date
compile_it_discard_iface (Just linkable) SourceUnmodified
-- See Note [Recompilation checking when typechecking only]
| writeInterfaceOnlyMode dflags,
Just if_date <- mb_if_date,
if_date >= hs_date -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "skipping tc'd mod:" <+> ppr this_mod_name)
compile_it Nothing SourceUnmodified
_otherwise -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "compiling mod:" <+> ppr this_mod_name)
compile_it Nothing SourceModified
-- Note [Recompilation checking when typechecking only]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- If we are compiling with -fno-code -fwrite-interface, there won't
-- be any object code that we can compare against, nor should there
-- be: we're *just* generating interface files. In this case, we
-- want to check if the interface file is new, in lieu of the object
-- file. See also Trac #9243.
-- Filter modules in the HPT
retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
retainInTopLevelEnvs keep_these hpt
= listToUFM [ (mod, expectJust "retain" mb_mod_info)
| mod <- keep_these
, let mb_mod_info = lookupUFM hpt mod
, isJust mb_mod_info ]
-- ---------------------------------------------------------------------------
-- Typecheck module loops
{-
See bug #930. This code fixes a long-standing bug in --make. The
problem is that when compiling the modules *inside* a loop, a data
type that is only defined at the top of the loop looks opaque; but
after the loop is done, the structure of the data type becomes
apparent.
The difficulty is then that two different bits of code have
different notions of what the data type looks like.
The idea is that after we compile a module which also has an .hs-boot
file, we re-generate the ModDetails for each of the modules that
depends on the .hs-boot file, so that everyone points to the proper
TyCons, Ids etc. defined by the real module, not the boot module.
Fortunately re-generating a ModDetails from a ModIface is easy: the
function TcIface.typecheckIface does exactly that.
Picking the modules to re-typecheck is slightly tricky. Starting from
the module graph consisting of the modules that have already been
compiled, we reverse the edges (so they point from the imported module
to the importing module), and depth-first-search from the .hs-boot
node. This gives us all the modules that depend transitively on the
.hs-boot module, and those are exactly the modules that we need to
re-typecheck.
Following this fix, GHC can compile itself with --make -O2.
-}
reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
reTypecheckLoop hsc_env ms graph
| Just loop <- getModLoop ms graph
, let non_boot = filter (not.isBootSummary) loop
= typecheckLoop (hsc_dflags hsc_env) hsc_env (map ms_mod_name non_boot)
| otherwise
= return hsc_env
getModLoop :: ModSummary -> ModuleGraph -> Maybe [ModSummary]
getModLoop ms graph
| not (isBootSummary ms)
, any (\m -> ms_mod m == this_mod && isBootSummary m) graph
, let mss = reachableBackwards (ms_mod_name ms) graph
= Just mss
| otherwise
= Nothing
where
this_mod = ms_mod ms
typecheckLoop :: DynFlags -> HscEnv -> [ModuleName] -> IO HscEnv
typecheckLoop dflags hsc_env mods = do
debugTraceMsg dflags 2 $
text "Re-typechecking loop: " <> ppr mods
new_hpt <-
fixIO $ \new_hpt -> do
let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
mds <- initIfaceCheck new_hsc_env $
mapM (typecheckIface . hm_iface) hmis
let new_hpt = addListToUFM old_hpt
(zip mods [ hmi{ hm_details = details }
| (hmi,details) <- zip hmis mds ])
return new_hpt
return hsc_env{ hsc_HPT = new_hpt }
where
old_hpt = hsc_HPT hsc_env
hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
reachableBackwards mod summaries
= [ ms | (ms,_,_) <- reachableG (transposeG graph) root ]
where -- the rest just sets up the graph:
(graph, lookup_node) = moduleGraphNodes False summaries
root = expectJust "reachableBackwards" (lookup_node HsBootFile mod)
-- ---------------------------------------------------------------------------
--
-- | Topological sort of the module graph
topSortModuleGraph
:: Bool
-- ^ Drop hi-boot nodes? (see below)
-> [ModSummary]
-> Maybe ModuleName
-- ^ Root module name. If @Nothing@, use the full graph.
-> [SCC ModSummary]
-- ^ Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
-- The resulting list of strongly-connected-components is in topologically
-- sorted order, starting with the module(s) at the bottom of the
-- dependency graph (ie compile them first) and ending with the ones at
-- the top.
--
-- Drop hi-boot nodes (first boolean arg)?
--
-- - @False@: treat the hi-boot summaries as nodes of the graph,
-- so the graph must be acyclic
--
-- - @True@: eliminate the hi-boot nodes, and instead pretend
-- the a source-import of Foo is an import of Foo
-- The resulting graph has no hi-boot nodes, but can be cyclic
topSortModuleGraph drop_hs_boot_nodes summaries mb_root_mod
= map (fmap summaryNodeSummary) $ stronglyConnCompG initial_graph
where
(graph, lookup_node) = moduleGraphNodes drop_hs_boot_nodes summaries
initial_graph = case mb_root_mod of
Nothing -> graph
Just root_mod ->
-- restrict the graph to just those modules reachable from
-- the specified module. We do this by building a graph with
-- the full set of nodes, and determining the reachable set from
-- the specified node.
let root | Just node <- lookup_node HsSrcFile root_mod, graph `hasVertexG` node = node
| otherwise = throwGhcException (ProgramError "module does not exist")
in graphFromEdgedVertices (seq root (reachableG graph root))
type SummaryNode = (ModSummary, Int, [Int])
summaryNodeKey :: SummaryNode -> Int
summaryNodeKey (_, k, _) = k
summaryNodeSummary :: SummaryNode -> ModSummary
summaryNodeSummary (s, _, _) = s
moduleGraphNodes :: Bool -> [ModSummary]
-> (Graph SummaryNode, HscSource -> ModuleName -> Maybe SummaryNode)
moduleGraphNodes drop_hs_boot_nodes summaries = (graphFromEdgedVertices nodes, lookup_node)
where
numbered_summaries = zip summaries [1..]
lookup_node :: HscSource -> ModuleName -> Maybe SummaryNode
lookup_node hs_src mod = Map.lookup (mod, hscSourceToIsBoot hs_src) node_map
lookup_key :: HscSource -> ModuleName -> Maybe Int
lookup_key hs_src mod = fmap summaryNodeKey (lookup_node hs_src mod)
node_map :: NodeMap SummaryNode
node_map = Map.fromList [ ((moduleName (ms_mod s),
hscSourceToIsBoot (ms_hsc_src s)), node)
| node@(s, _, _) <- nodes ]
-- We use integers as the keys for the SCC algorithm
nodes :: [SummaryNode]
nodes = [ (s, key, out_keys)
| (s, key) <- numbered_summaries
-- Drop the hi-boot ones if told to do so
, not (isBootSummary s && drop_hs_boot_nodes)
, let out_keys = out_edge_keys hs_boot_key (map unLoc (ms_home_srcimps s)) ++
out_edge_keys HsSrcFile (map unLoc (ms_home_imps s)) ++
(-- see [boot-edges] below
if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
then []
else case lookup_key HsBootFile (ms_mod_name s) of
Nothing -> []
Just k -> [k]) ]
-- [boot-edges] if this is a .hs and there is an equivalent
-- .hs-boot, add a link from the former to the latter. This
-- has the effect of detecting bogus cases where the .hs-boot
-- depends on the .hs, by introducing a cycle. Additionally,
-- it ensures that we will always process the .hs-boot before
-- the .hs, and so the HomePackageTable will always have the
-- most up to date information.
-- Drop hs-boot nodes by using HsSrcFile as the key
hs_boot_key | drop_hs_boot_nodes = HsSrcFile
| otherwise = HsBootFile
out_edge_keys :: HscSource -> [ModuleName] -> [Int]
out_edge_keys hi_boot ms = mapMaybe (lookup_key hi_boot) ms
-- If we want keep_hi_boot_nodes, then we do lookup_key with
-- IsBoot; else NotBoot
-- The nodes of the graph are keyed by (mod, is boot?) pairs
-- NB: hsig files show up as *normal* nodes (not boot!), since they don't
-- participate in cycles (for now)
type NodeKey = (ModuleName, IsBoot)
type NodeMap a = Map.Map NodeKey a
msKey :: ModSummary -> NodeKey
msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot })
= (moduleName mod, hscSourceToIsBoot boot)
mkNodeMap :: [ModSummary] -> NodeMap ModSummary
mkNodeMap summaries = Map.fromList [ (msKey s, s) | s <- summaries]
nodeMapElts :: NodeMap a -> [a]
nodeMapElts = Map.elems
-- | If there are {-# SOURCE #-} imports between strongly connected
-- components in the topological sort, then those imports can
-- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
-- were necessary, then the edge would be part of a cycle.
warnUnnecessarySourceImports :: GhcMonad m => [SCC ModSummary] -> m ()
warnUnnecessarySourceImports sccs = do
dflags <- getDynFlags
logWarnings (listToBag (concatMap (check dflags . flattenSCC) sccs))
where check dflags ms =
let mods_in_this_cycle = map ms_mod_name ms in
[ warn dflags i | m <- ms, i <- ms_home_srcimps m,
unLoc i `notElem` mods_in_this_cycle ]
warn :: DynFlags -> Located ModuleName -> WarnMsg
warn dflags (L loc mod) =
mkPlainErrMsg dflags loc
(ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
<+> quotes (ppr mod))
reportImportErrors :: MonadIO m => [Either ErrMsg b] -> m [b]
reportImportErrors xs | null errs = return oks
| otherwise = throwManyErrors errs
where (errs, oks) = partitionEithers xs
throwManyErrors :: MonadIO m => [ErrMsg] -> m ab
throwManyErrors errs = liftIO $ throwIO $ mkSrcErr $ listToBag errs
-----------------------------------------------------------------------------
--
-- | Downsweep (dependency analysis)
--
-- Chase downwards from the specified root set, returning summaries
-- for all home modules encountered. Only follow source-import
-- links.
--
-- We pass in the previous collection of summaries, which is used as a
-- cache to avoid recalculating a module summary if the source is
-- unchanged.
--
-- The returned list of [ModSummary] nodes has one node for each home-package
-- module, plus one for any hs-boot files. The imports of these nodes
-- are all there, including the imports of non-home-package modules.
downsweep :: HscEnv
-> [ModSummary] -- Old summaries
-> [ModuleName] -- Ignore dependencies on these; treat
-- them as if they were package modules
-> Bool -- True <=> allow multiple targets to have
-- the same module name; this is
-- very useful for ghc -M
-> IO [Either ErrMsg ModSummary]
-- The elts of [ModSummary] all have distinct
-- (Modules, IsBoot) identifiers, unless the Bool is true
-- in which case there can be repeats
downsweep hsc_env old_summaries excl_mods allow_dup_roots
= do
rootSummaries <- mapM getRootSummary roots
rootSummariesOk <- reportImportErrors rootSummaries
let root_map = mkRootMap rootSummariesOk
checkDuplicates root_map
summs <- loop (concatMap calcDeps rootSummariesOk) root_map
return summs
where
-- When we're compiling a signature file, we have an implicit
-- dependency on what-ever the signature's implementation is.
-- (But not when we're type checking!)
calcDeps summ
| HsigFile <- ms_hsc_src summ
, Just m <- getSigOf (hsc_dflags hsc_env) (moduleName (ms_mod summ))
, modulePackageKey m == thisPackage (hsc_dflags hsc_env)
= (noLoc (moduleName m), NotBoot) : msDeps summ
| otherwise = msDeps summ
dflags = hsc_dflags hsc_env
roots = hsc_targets hsc_env
old_summary_map :: NodeMap ModSummary
old_summary_map = mkNodeMap old_summaries
getRootSummary :: Target -> IO (Either ErrMsg ModSummary)
getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf)
= do exists <- liftIO $ doesFileExist file
if exists
then Right `fmap` summariseFile hsc_env old_summaries file mb_phase
obj_allowed maybe_buf
else return $ Left $ mkPlainErrMsg dflags noSrcSpan $
text "can't find file:" <+> text file
getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf)
= do maybe_summary <- summariseModule hsc_env old_summary_map NotBoot
(L rootLoc modl) obj_allowed
maybe_buf excl_mods
case maybe_summary of
Nothing -> return $ Left $ packageModErr dflags modl
Just s -> return s
rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
-- In a root module, the filename is allowed to diverge from the module
-- name, so we have to check that there aren't multiple root files
-- defining the same module (otherwise the duplicates will be silently
-- ignored, leading to confusing behaviour).
checkDuplicates :: NodeMap [Either ErrMsg ModSummary] -> IO ()
checkDuplicates root_map
| allow_dup_roots = return ()
| null dup_roots = return ()
| otherwise = liftIO $ multiRootsErr dflags (head dup_roots)
where
dup_roots :: [[ModSummary]] -- Each at least of length 2
dup_roots = filterOut isSingleton $ map rights $ nodeMapElts root_map
loop :: [(Located ModuleName,IsBoot)]
-- Work list: process these modules
-> NodeMap [Either ErrMsg ModSummary]
-- Visited set; the range is a list because
-- the roots can have the same module names
-- if allow_dup_roots is True
-> IO [Either ErrMsg ModSummary]
-- The result includes the worklist, except
-- for those mentioned in the visited set
loop [] done = return (concat (nodeMapElts done))
loop ((wanted_mod, is_boot) : ss) done
| Just summs <- Map.lookup key done
= if isSingleton summs then
loop ss done
else
do { multiRootsErr dflags (rights summs); return [] }
| otherwise
= do mb_s <- summariseModule hsc_env old_summary_map
is_boot wanted_mod True
Nothing excl_mods
case mb_s of
Nothing -> loop ss done
Just (Left e) -> loop ss (Map.insert key [Left e] done)
Just (Right s)-> loop (calcDeps s ++ ss)
(Map.insert key [Right s] done)
where
key = (unLoc wanted_mod, is_boot)
mkRootMap :: [ModSummary] -> NodeMap [Either ErrMsg ModSummary]
mkRootMap summaries = Map.insertListWith (flip (++))
[ (msKey s, [Right s]) | s <- summaries ]
Map.empty
-- | Returns the dependencies of the ModSummary s.
-- A wrinkle is that for a {-# SOURCE #-} import we return
-- *both* the hs-boot file
-- *and* the source file
-- as "dependencies". That ensures that the list of all relevant
-- modules always contains B.hs if it contains B.hs-boot.
-- Remember, this pass isn't doing the topological sort. It's
-- just gathering the list of all relevant ModSummaries
msDeps :: ModSummary -> [(Located ModuleName, IsBoot)]
msDeps s =
concat [ [(m,IsBoot), (m,NotBoot)] | m <- ms_home_srcimps s ]
++ [ (m,NotBoot) | m <- ms_home_imps s ]
home_imps :: [Located (ImportDecl RdrName)] -> [Located ModuleName]
home_imps imps = [ ideclName i | L _ i <- imps, isLocal (ideclPkgQual i) ]
where isLocal Nothing = True
isLocal (Just pkg) | pkg == fsLit "this" = True -- "this" is special
isLocal _ = False
ms_home_allimps :: ModSummary -> [ModuleName]
ms_home_allimps ms = map unLoc (ms_home_srcimps ms ++ ms_home_imps ms)
ms_home_srcimps :: ModSummary -> [Located ModuleName]
ms_home_srcimps = home_imps . ms_srcimps
ms_home_imps :: ModSummary -> [Located ModuleName]
ms_home_imps = home_imps . ms_imps
-----------------------------------------------------------------------------
-- Summarising modules
-- We have two types of summarisation:
--
-- * Summarise a file. This is used for the root module(s) passed to
-- cmLoadModules. The file is read, and used to determine the root
-- module name. The module name may differ from the filename.
--
-- * Summarise a module. We are given a module name, and must provide
-- a summary. The finder is used to locate the file in which the module
-- resides.
summariseFile
:: HscEnv
-> [ModSummary] -- old summaries
-> FilePath -- source file name
-> Maybe Phase -- start phase
-> Bool -- object code allowed?
-> Maybe (StringBuffer,UTCTime)
-> IO ModSummary
summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf
-- we can use a cached summary if one is available and the
-- source file hasn't changed, But we have to look up the summary
-- by source file, rather than module name as we do in summarise.
| Just old_summary <- findSummaryBySourceFile old_summaries file
= do
let location = ms_location old_summary
dflags = hsc_dflags hsc_env
src_timestamp <- get_src_timestamp
-- The file exists; we checked in getRootSummary above.
-- If it gets removed subsequently, then this
-- getModificationUTCTime may fail, but that's the right
-- behaviour.
-- return the cached summary if the source didn't change
if ms_hs_date old_summary == src_timestamp &&
not (gopt Opt_ForceRecomp (hsc_dflags hsc_env))
then do -- update the object-file timestamp
obj_timestamp <-
if isObjectTarget (hscTarget (hsc_dflags hsc_env))
|| obj_allowed -- bug #1205
then liftIO $ getObjTimestamp location NotBoot
else return Nothing
hi_timestamp <- maybeGetIfaceDate dflags location
return old_summary{ ms_obj_date = obj_timestamp
, ms_iface_date = hi_timestamp }
else
new_summary src_timestamp
| otherwise
= do src_timestamp <- get_src_timestamp
new_summary src_timestamp
where
get_src_timestamp = case maybe_buf of
Just (_,t) -> return t
Nothing -> liftIO $ getModificationUTCTime file
-- getMofificationUTCTime may fail
new_summary src_timestamp = do
let dflags = hsc_dflags hsc_env
let hsc_src = if isHaskellSigFilename file then HsigFile else HsSrcFile
(dflags', hspp_fn, buf)
<- preprocessFile hsc_env file mb_phase maybe_buf
(srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
-- Make a ModLocation for this file
location <- liftIO $ mkHomeModLocation dflags mod_name file
-- Tell the Finder cache where it is, so that subsequent calls
-- to findModule will find it, even if it's not on any search path
mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location
-- when the user asks to load a source file by name, we only
-- use an object file if -fobject-code is on. See #1205.
obj_timestamp <-
if isObjectTarget (hscTarget (hsc_dflags hsc_env))
|| obj_allowed -- bug #1205
then liftIO $ modificationTimeIfExists (ml_obj_file location)
else return Nothing
hi_timestamp <- maybeGetIfaceDate dflags location
return (ModSummary { ms_mod = mod, ms_hsc_src = hsc_src,
ms_location = location,
ms_hspp_file = hspp_fn,
ms_hspp_opts = dflags',
ms_hspp_buf = Just buf,
ms_srcimps = srcimps, ms_textual_imps = the_imps,
ms_hs_date = src_timestamp,
ms_iface_date = hi_timestamp,
ms_obj_date = obj_timestamp })
findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
findSummaryBySourceFile summaries file
= case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
[] -> Nothing
(x:_) -> Just x
-- Summarise a module, and pick up source and timestamp.
summariseModule
:: HscEnv
-> NodeMap ModSummary -- Map of old summaries
-> IsBoot -- IsBoot <=> a {-# SOURCE #-} import
-> Located ModuleName -- Imported module to be summarised
-> Bool -- object code allowed?
-> Maybe (StringBuffer, UTCTime)
-> [ModuleName] -- Modules to exclude
-> IO (Maybe (Either ErrMsg ModSummary)) -- Its new summary
summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod)
obj_allowed maybe_buf excl_mods
| wanted_mod `elem` excl_mods
= return Nothing
| Just old_summary <- Map.lookup (wanted_mod, is_boot) old_summary_map
= do -- Find its new timestamp; all the
-- ModSummaries in the old map have valid ml_hs_files
let location = ms_location old_summary
src_fn = expectJust "summariseModule" (ml_hs_file location)
-- check the modification time on the source file, and
-- return the cached summary if it hasn't changed. If the
-- file has disappeared, we need to call the Finder again.
case maybe_buf of
Just (_,t) -> check_timestamp old_summary location src_fn t
Nothing -> do
m <- tryIO (getModificationUTCTime src_fn)
case m of
Right t -> check_timestamp old_summary location src_fn t
Left e | isDoesNotExistError e -> find_it
| otherwise -> ioError e
| otherwise = find_it
where
dflags = hsc_dflags hsc_env
check_timestamp old_summary location src_fn src_timestamp
| ms_hs_date old_summary == src_timestamp &&
not (gopt Opt_ForceRecomp dflags) = do
-- update the object-file timestamp
obj_timestamp <-
if isObjectTarget (hscTarget (hsc_dflags hsc_env))
|| obj_allowed -- bug #1205
then getObjTimestamp location is_boot
else return Nothing
hi_timestamp <- maybeGetIfaceDate dflags location
return (Just (Right old_summary{ ms_obj_date = obj_timestamp
, ms_iface_date = hi_timestamp}))
| otherwise =
-- source changed: re-summarise.
new_summary location (ms_mod old_summary) src_fn src_timestamp
find_it = do
-- Don't use the Finder's cache this time. If the module was
-- previously a package module, it may have now appeared on the
-- search path, so we want to consider it to be a home module. If
-- the module was previously a home module, it may have moved.
uncacheModule hsc_env wanted_mod
found <- findImportedModule hsc_env wanted_mod Nothing
case found of
Found location mod
| isJust (ml_hs_file location) ->
-- Home package
just_found location mod
| otherwise ->
-- Drop external-pkg
-- ASSERT(modulePackageKey mod /= thisPackage dflags)
return Nothing
err -> return $ Just $ Left $ noModError dflags loc wanted_mod err
-- Not found
just_found location mod = do
-- Adjust location to point to the hs-boot source file,
-- hi file, object file, when is_boot says so
let location' | IsBoot <- is_boot = addBootSuffixLocn location
| otherwise = location
src_fn = expectJust "summarise2" (ml_hs_file location')
-- Check that it exists
-- It might have been deleted since the Finder last found it
maybe_t <- modificationTimeIfExists src_fn
case maybe_t of
Nothing -> return $ Just $ Left $ noHsFileErr dflags loc src_fn
Just t -> new_summary location' mod src_fn t
new_summary location mod src_fn src_timestamp
= do
-- Preprocess the source file and get its imports
-- The dflags' contains the OPTIONS pragmas
(dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
(srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
-- NB: Despite the fact that is_boot is a top-level parameter, we
-- don't actually know coming into this function what the HscSource
-- of the module in question is. This is because we may be processing
-- this module because another module in the graph imported it: in this
-- case, we know if it's a boot or not because of the {-# SOURCE #-}
-- annotation, but we don't know if it's a signature or a regular
-- module until we actually look it up on the filesystem.
let hsc_src = case is_boot of
IsBoot -> HsBootFile
_ | isHaskellSigFilename src_fn -> HsigFile
| otherwise -> HsSrcFile
when (mod_name /= wanted_mod) $
throwOneError $ mkPlainErrMsg dflags' mod_loc $
text "File name does not match module name:"
$$ text "Saw:" <+> quotes (ppr mod_name)
$$ text "Expected:" <+> quotes (ppr wanted_mod)
-- Find the object timestamp, and return the summary
obj_timestamp <-
if isObjectTarget (hscTarget (hsc_dflags hsc_env))
|| obj_allowed -- bug #1205
then getObjTimestamp location is_boot
else return Nothing
hi_timestamp <- maybeGetIfaceDate dflags location
return (Just (Right (ModSummary { ms_mod = mod,
ms_hsc_src = hsc_src,
ms_location = location,
ms_hspp_file = hspp_fn,
ms_hspp_opts = dflags',
ms_hspp_buf = Just buf,
ms_srcimps = srcimps,
ms_textual_imps = the_imps,
ms_hs_date = src_timestamp,
ms_iface_date = hi_timestamp,
ms_obj_date = obj_timestamp })))
getObjTimestamp :: ModLocation -> IsBoot -> IO (Maybe UTCTime)
getObjTimestamp location is_boot
= if is_boot == IsBoot then return Nothing
else modificationTimeIfExists (ml_obj_file location)
preprocessFile :: HscEnv
-> FilePath
-> Maybe Phase -- ^ Starting phase
-> Maybe (StringBuffer,UTCTime)
-> IO (DynFlags, FilePath, StringBuffer)
preprocessFile hsc_env src_fn mb_phase Nothing
= do
(dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
buf <- hGetStringBuffer hspp_fn
return (dflags', hspp_fn, buf)
preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
= do
let dflags = hsc_dflags hsc_env
let local_opts = getOptions dflags buf src_fn
(dflags', leftovers, warns)
<- parseDynamicFilePragma dflags local_opts
checkProcessArgsResult dflags leftovers
handleFlagWarnings dflags' warns
let needs_preprocessing
| Just (Unlit _) <- mb_phase = True
| Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
-- note: local_opts is only required if there's no Unlit phase
| xopt Opt_Cpp dflags' = True
| gopt Opt_Pp dflags' = True
| otherwise = False
when needs_preprocessing $
throwGhcExceptionIO (ProgramError "buffer needs preprocesing; interactive check disabled")
return (dflags', src_fn, buf)
-----------------------------------------------------------------------------
-- Error messages
-----------------------------------------------------------------------------
noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> ErrMsg
-- ToDo: we don't have a proper line number for this error
noModError dflags loc wanted_mod err
= mkPlainErrMsg dflags loc $ cannotFindModule dflags wanted_mod err
noHsFileErr :: DynFlags -> SrcSpan -> String -> ErrMsg
noHsFileErr dflags loc path
= mkPlainErrMsg dflags loc $ text "Can't find" <+> text path
packageModErr :: DynFlags -> ModuleName -> ErrMsg
packageModErr dflags mod
= mkPlainErrMsg dflags noSrcSpan $
text "module" <+> quotes (ppr mod) <+> text "is a package module"
multiRootsErr :: DynFlags -> [ModSummary] -> IO ()
multiRootsErr _ [] = panic "multiRootsErr"
multiRootsErr dflags summs@(summ1:_)
= throwOneError $ mkPlainErrMsg dflags noSrcSpan $
text "module" <+> quotes (ppr mod) <+>
text "is defined in multiple files:" <+>
sep (map text files)
where
mod = ms_mod summ1
files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
cyclicModuleErr :: [ModSummary] -> SDoc
-- From a strongly connected component we find
-- a single cycle to report
cyclicModuleErr mss
= -- ASSERT( not (null mss) )
case findCycle graph of
Nothing -> ptext (sLit "Unexpected non-cycle") <+> ppr mss
Just path -> vcat [ ptext (sLit "Module imports form a cycle:")
, nest 2 (show_path path) ]
where
graph :: [Node NodeKey ModSummary]
graph = [(ms, msKey ms, get_deps ms) | ms <- mss]
get_deps :: ModSummary -> [NodeKey]
get_deps ms = ([ (unLoc m, IsBoot) | m <- ms_home_srcimps ms ] ++
[ (unLoc m, NotBoot) | m <- ms_home_imps ms ])
show_path [] = panic "show_path"
show_path [m] = ptext (sLit "module") <+> ppr_ms m
<+> ptext (sLit "imports itself")
show_path (m1:m2:ms) = vcat ( nest 7 (ptext (sLit "module") <+> ppr_ms m1)
: nest 6 (ptext (sLit "imports") <+> ppr_ms m2)
: go ms )
where
go [] = [ptext (sLit "which imports") <+> ppr_ms m1]
go (m:ms) = (ptext (sLit "which imports") <+> ppr_ms m) : go ms
ppr_ms :: ModSummary -> SDoc
ppr_ms ms = quotes (ppr (moduleName (ms_mod ms))) <+>
(parens (text (msHsFilePath ms)))
|
seereason/ghcjs
|
src/Compiler/GhcMake.hs
|
mit
| 87,322
| 0
| 35
| 27,685
| 14,338
| 7,328
| 7,010
| 1,089
| 8
|
module ExprEnumFrom where
f = [ "aap" .. ]
|
roberth/uu-helium
|
test/typeerrors/Examples/ExprEnumFrom.hs
|
gpl-3.0
| 44
| 0
| 5
| 10
| 13
| 9
| 4
| 2
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Web.Twitter.Conduit
import Web.Twitter.Types.Lens
import Control.Lens
import Control.Monad.IO.Class
import Control.Monad.Trans.Control
import Control.Monad.Trans.Resource
import qualified Data.ByteString.Char8 as B8
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import Data.Default
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.HTTP.Conduit
import System.IO (hFlush, stdout)
import Web.Authenticate.OAuth (OAuth(..), Credential(..))
import qualified Web.Authenticate.OAuth as OA
tokens :: OAuth
tokens = twitterOAuth
{ oauthConsumerKey = error "You MUST specify oauthConsumerKey parameter."
, oauthConsumerSecret = error "You MUST specify oauthConsumerSecret parameter."
}
authorize :: (MonadBaseControl IO m, MonadResource m)
=> OAuth -- ^ OAuth Consumer key and secret
-> (String -> m String) -- ^ PIN prompt
-> Manager
-> m Credential
authorize oauth getPIN mgr = do
cred <- OA.getTemporaryCredential oauth mgr
let url = OA.authorizeUrl oauth cred
pin <- getPIN url
OA.getAccessToken oauth (OA.insert "oauth_verifier" (B8.pack pin) cred) mgr
getTWInfo :: IO TWInfo
getTWInfo = do
cred <- withManager $ \mgr -> authorize tokens getPIN mgr
return $ setCredential tokens cred def
where
getPIN url = liftIO $ do
putStrLn $ "browse URL: " ++ url
putStr "> what was the PIN twitter provided you with? "
hFlush stdout
getLine
main :: IO ()
main = do
twInfo <- getTWInfo
putStrLn $ "# your home timeline (up to 100 tweets):"
withManager $ \mgr -> do
sourceWithMaxId twInfo mgr homeTimeline
C.$= CL.isolate 100
C.$$ CL.mapM_ $ \status -> liftIO $ do
T.putStrLn $ T.concat [ T.pack . show $ status ^. statusId
, ": "
, status ^. statusUser . userScreenName
, ": "
, status ^. statusText
]
|
AndrewRademacher/twitter-conduit
|
sample/simple.hs
|
bsd-2-clause
| 2,213
| 0
| 22
| 639
| 534
| 293
| 241
| -1
| -1
|
import Control.Concurrent
import Control.Monad
import Data.Time
import Hypervisor.Console
import System.CPUTime
import System.Environment
import System.Locale
main :: IO ()
main = do
con <- initXenConsole
args <- getArgs
let count = case args of
[arg] | take 6 arg == "count=" -> read $ drop 6 arg
_ -> 100
replicateM_ count $ do
utc_time <- getZonedTime
cputime <- getCPUTime
writeConsole con $ formatTime defaultTimeLocale "%c%n" utc_time
writeConsole con $ show cputime ++ "\n"
threadDelay (1 * 1000 * 1000)
|
thumphries/HaLVM
|
examples/Core/Time/Time.hs
|
bsd-3-clause
| 600
| 0
| 17
| 168
| 192
| 91
| 101
| 20
| 2
|
module TreeIn2 where
data Tree a = Leaf a | Branch (Tree a) (Tree a)
fringe :: (Tree a) -> [a]
fringe (Leaf x) = [x]
fringe (Branch left right)
= case right of
right@(Leaf b_1) -> (fringe left) ++ (fringe right)
right@(Branch b_1 b_2)
-> (fringe left) ++ (fringe right)
fringe (Branch left right)
= (fringe left) ++ (fringe right)
|
kmate/HaRe
|
old/testing/introCase/TreeIn2AST.hs
|
bsd-3-clause
| 386
| 0
| 10
| 116
| 184
| 97
| 87
| 11
| 2
|
-- | A description of the platform we're compiling for.
--
module Platform (
Platform(..),
Arch(..),
OS(..),
ArmISA(..),
ArmISAExt(..),
ArmABI(..),
target32Bit,
isARM,
osElfTarget,
osMachOTarget,
platformUsesFrameworks,
platformBinariesAreStaticLibs,
)
where
-- | Contains enough information for the native code generator to emit
-- code for this platform.
data Platform
= Platform {
platformArch :: Arch,
platformOS :: OS,
-- Word size in bytes (i.e. normally 4 or 8,
-- for 32bit and 64bit platforms respectively)
platformWordSize :: {-# UNPACK #-} !Int,
platformUnregisterised :: Bool,
platformHasGnuNonexecStack :: Bool,
platformHasIdentDirective :: Bool,
platformHasSubsectionsViaSymbols :: Bool
}
deriving (Read, Show, Eq)
-- | Architectures that the native code generator knows about.
-- TODO: It might be nice to extend these constructors with information
-- about what instruction set extensions an architecture might support.
--
data Arch
= ArchUnknown
| ArchX86
| ArchX86_64
| ArchPPC
| ArchPPC_64
| ArchSPARC
| ArchARM
{ armISA :: ArmISA
, armISAExt :: [ArmISAExt]
, armABI :: ArmABI
}
| ArchARM64
| ArchAlpha
| ArchMipseb
| ArchMipsel
| ArchJavaScript
deriving (Read, Show, Eq)
isARM :: Arch -> Bool
isARM (ArchARM {}) = True
isARM _ = False
-- | Operating systems that the native code generator knows about.
-- Having OSUnknown should produce a sensible default, but no promises.
data OS
= OSUnknown
| OSLinux
| OSDarwin
| OSiOS
| OSSolaris2
| OSMinGW32
| OSFreeBSD
| OSDragonFly
| OSOpenBSD
| OSNetBSD
| OSKFreeBSD
| OSHaiku
| OSOsf3
| OSQNXNTO
| OSAndroid
deriving (Read, Show, Eq)
-- | ARM Instruction Set Architecture, Extensions and ABI
--
data ArmISA
= ARMv5
| ARMv6
| ARMv7
deriving (Read, Show, Eq)
data ArmISAExt
= VFPv2
| VFPv3
| VFPv3D16
| NEON
| IWMMX2
deriving (Read, Show, Eq)
data ArmABI
= SOFT
| SOFTFP
| HARD
deriving (Read, Show, Eq)
target32Bit :: Platform -> Bool
target32Bit p = platformWordSize p == 4
-- | This predicates tells us whether the OS supports ELF-like shared libraries.
osElfTarget :: OS -> Bool
osElfTarget OSLinux = True
osElfTarget OSFreeBSD = True
osElfTarget OSDragonFly = True
osElfTarget OSOpenBSD = True
osElfTarget OSNetBSD = True
osElfTarget OSSolaris2 = True
osElfTarget OSDarwin = False
osElfTarget OSiOS = False
osElfTarget OSMinGW32 = False
osElfTarget OSKFreeBSD = True
osElfTarget OSHaiku = True
osElfTarget OSOsf3 = False -- I don't know if this is right, but as
-- per comment below it's safe
osElfTarget OSQNXNTO = False
osElfTarget OSAndroid = True
osElfTarget OSUnknown = False
-- Defaulting to False is safe; it means don't rely on any
-- ELF-specific functionality. It is important to have a default for
-- portability, otherwise we have to answer this question for every
-- new platform we compile on (even unreg).
-- | This predicate tells us whether the OS support Mach-O shared libraries.
osMachOTarget :: OS -> Bool
osMachOTarget OSDarwin = True
osMachOTarget _ = False
osUsesFrameworks :: OS -> Bool
osUsesFrameworks OSDarwin = True
osUsesFrameworks OSiOS = True
osUsesFrameworks _ = False
platformUsesFrameworks :: Platform -> Bool
platformUsesFrameworks = osUsesFrameworks . platformOS
osBinariesAreStaticLibs :: OS -> Bool
osBinariesAreStaticLibs OSiOS = True
osBinariesAreStaticLibs _ = False
platformBinariesAreStaticLibs :: Platform -> Bool
platformBinariesAreStaticLibs = osBinariesAreStaticLibs . platformOS
|
tibbe/ghc
|
compiler/utils/Platform.hs
|
bsd-3-clause
| 4,187
| 0
| 9
| 1,310
| 693
| 409
| 284
| 109
| 1
|
-- Note: this file derives from old-locale:System.Locale.hs, which is copyright (c) The University of Glasgow 2001
module Data.Time.Format.Locale (
TimeLocale(..)
, defaultTimeLocale
, iso8601DateFormat
, rfc822DateFormat
)
where
import Data.Time.LocalTime
data TimeLocale = TimeLocale {
-- |full and abbreviated week days, starting with Sunday
wDays :: [(String, String)],
-- |full and abbreviated months
months :: [(String, String)],
-- |AM\/PM symbols
amPm :: (String, String),
-- |formatting strings
dateTimeFmt, dateFmt,
timeFmt, time12Fmt :: String,
-- |time zones known by name
knownTimeZones :: [TimeZone]
} deriving (Eq, Ord, Show)
-- | Locale representing American usage.
--
-- 'knownTimeZones' contains only the ten time-zones mentioned in RFC 822 sec. 5:
-- \"UT\", \"GMT\", \"EST\", \"EDT\", \"CST\", \"CDT\", \"MST\", \"MDT\", \"PST\", \"PDT\".
-- Note that the parsing functions will regardless parse single-letter military time-zones and +HHMM format.
defaultTimeLocale :: TimeLocale
defaultTimeLocale = TimeLocale {
wDays = [("Sunday", "Sun"), ("Monday", "Mon"),
("Tuesday", "Tue"), ("Wednesday", "Wed"),
("Thursday", "Thu"), ("Friday", "Fri"),
("Saturday", "Sat")],
months = [("January", "Jan"), ("February", "Feb"),
("March", "Mar"), ("April", "Apr"),
("May", "May"), ("June", "Jun"),
("July", "Jul"), ("August", "Aug"),
("September", "Sep"), ("October", "Oct"),
("November", "Nov"), ("December", "Dec")],
amPm = ("AM", "PM"),
dateTimeFmt = "%a %b %e %H:%M:%S %Z %Y",
dateFmt = "%m/%d/%y",
timeFmt = "%H:%M:%S",
time12Fmt = "%I:%M:%S %p",
knownTimeZones =
[
TimeZone 0 False "UT",
TimeZone 0 False "GMT",
TimeZone (-5 * 60) False "EST",
TimeZone (-4 * 60) True "EDT",
TimeZone (-6 * 60) False "CST",
TimeZone (-5 * 60) True "CDT",
TimeZone (-7 * 60) False "MST",
TimeZone (-6 * 60) True "MDT",
TimeZone (-8 * 60) False "PST",
TimeZone (-7 * 60) True "PDT"
]
}
{- | Construct format string according to <http://en.wikipedia.org/wiki/ISO_8601 ISO-8601>.
The @Maybe String@ argument allows to supply an optional time specification. E.g.:
@
'iso8601DateFormat' Nothing == "%Y-%m-%d" -- i.e. @/YYYY-MM-DD/@
'iso8601DateFormat' (Just "%H:%M:%S") == "%Y-%m-%dT%H:%M:%S" -- i.e. @/YYYY-MM-DD/T/HH:MM:SS/@
@
-}
iso8601DateFormat :: Maybe String -> String
iso8601DateFormat mTimeFmt =
"%Y-%m-%d" ++ case mTimeFmt of
Nothing -> ""
Just fmt -> 'T' : fmt
-- | Format string according to <http://tools.ietf.org/html/rfc822#section-5 RFC822>.
rfc822DateFormat :: String
rfc822DateFormat = "%a, %_d %b %Y %H:%M:%S %Z"
|
jtojnar/haste-compiler
|
libraries/time/lib/Data/Time/Format/Locale.hs
|
bsd-3-clause
| 3,116
| 0
| 11
| 941
| 598
| 368
| 230
| 50
| 2
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude
, BangPatterns
, NondecreasingIndentation
#-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.Encoding.Latin1
-- Copyright : (c) The University of Glasgow, 2009
-- License : see libraries/base/LICENSE
--
-- Maintainer : libraries@haskell.org
-- Stability : internal
-- Portability : non-portable
--
-- Single-byte encodings that map directly to Unicode code points.
--
-- Portions Copyright : (c) Tom Harper 2008-2009,
-- (c) Bryan O'Sullivan 2009,
-- (c) Duncan Coutts 2009
--
-----------------------------------------------------------------------------
module GHC.IO.Encoding.Latin1 (
latin1, mkLatin1,
latin1_checked, mkLatin1_checked,
ascii, mkAscii,
latin1_decode,
ascii_decode,
latin1_encode,
latin1_checked_encode,
ascii_encode,
) where
import GHC.Base
import GHC.Real
import GHC.Num
-- import GHC.IO
import GHC.IO.Buffer
import GHC.IO.Encoding.Failure
import GHC.IO.Encoding.Types
-- -----------------------------------------------------------------------------
-- Latin1
latin1 :: TextEncoding
latin1 = mkLatin1 ErrorOnCodingFailure
-- | @since 4.4.0.0
mkLatin1 :: CodingFailureMode -> TextEncoding
mkLatin1 cfm = TextEncoding { textEncodingName = "ISO8859-1",
mkTextDecoder = latin1_DF cfm,
mkTextEncoder = latin1_EF cfm }
latin1_DF :: CodingFailureMode -> IO (TextDecoder ())
latin1_DF cfm =
return (BufferCodec {
encode = latin1_decode,
recover = recoverDecode cfm,
close = return (),
getState = return (),
setState = const $ return ()
})
latin1_EF :: CodingFailureMode -> IO (TextEncoder ())
latin1_EF cfm =
return (BufferCodec {
encode = latin1_encode,
recover = recoverEncode cfm,
close = return (),
getState = return (),
setState = const $ return ()
})
latin1_checked :: TextEncoding
latin1_checked = mkLatin1_checked ErrorOnCodingFailure
-- | @since 4.4.0.0
mkLatin1_checked :: CodingFailureMode -> TextEncoding
mkLatin1_checked cfm = TextEncoding { textEncodingName = "ISO8859-1(checked)",
mkTextDecoder = latin1_DF cfm,
mkTextEncoder = latin1_checked_EF cfm }
latin1_checked_EF :: CodingFailureMode -> IO (TextEncoder ())
latin1_checked_EF cfm =
return (BufferCodec {
encode = latin1_checked_encode,
recover = recoverEncode cfm,
close = return (),
getState = return (),
setState = const $ return ()
})
-- -----------------------------------------------------------------------------
-- ASCII
-- | @since 4.8.2.0
ascii :: TextEncoding
ascii = mkAscii ErrorOnCodingFailure
-- | @since 4.8.2.0
mkAscii :: CodingFailureMode -> TextEncoding
mkAscii cfm = TextEncoding { textEncodingName = "ASCII",
mkTextDecoder = ascii_DF cfm,
mkTextEncoder = ascii_EF cfm }
ascii_DF :: CodingFailureMode -> IO (TextDecoder ())
ascii_DF cfm =
return (BufferCodec {
encode = ascii_decode,
recover = recoverDecode cfm,
close = return (),
getState = return (),
setState = const $ return ()
})
ascii_EF :: CodingFailureMode -> IO (TextEncoder ())
ascii_EF cfm =
return (BufferCodec {
encode = ascii_encode,
recover = recoverEncode cfm,
close = return (),
getState = return (),
setState = const $ return ()
})
-- -----------------------------------------------------------------------------
-- The actual decoders and encoders
-- TODO: Eliminate code duplication between the checked and unchecked
-- versions of the decoder or encoder (but don't change the Core!)
latin1_decode :: DecodeBuffer
latin1_decode
input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ }
output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os }
= let
loop !ir !ow
| ow >= os = done OutputUnderflow ir ow
| ir >= iw = done InputUnderflow ir ow
| otherwise = do
c0 <- readWord8Buf iraw ir
ow' <- writeCharBuf oraw ow (unsafeChr (fromIntegral c0))
loop (ir+1) ow'
-- lambda-lifted, to avoid thunks being built in the inner-loop:
done why !ir !ow = return (why,
if ir == iw then input{ bufL=0, bufR=0 }
else input{ bufL=ir },
output{ bufR=ow })
in
loop ir0 ow0
ascii_decode :: DecodeBuffer
ascii_decode
input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ }
output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os }
= let
loop !ir !ow
| ow >= os = done OutputUnderflow ir ow
| ir >= iw = done InputUnderflow ir ow
| otherwise = do
c0 <- readWord8Buf iraw ir
if c0 > 0x7f then invalid else do
ow' <- writeCharBuf oraw ow (unsafeChr (fromIntegral c0))
loop (ir+1) ow'
where
invalid = done InvalidSequence ir ow
-- lambda-lifted, to avoid thunks being built in the inner-loop:
done why !ir !ow = return (why,
if ir == iw then input{ bufL=0, bufR=0 }
else input{ bufL=ir },
output{ bufR=ow })
in
loop ir0 ow0
latin1_encode :: EncodeBuffer
latin1_encode
input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ }
output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os }
= let
done why !ir !ow = return (why,
if ir == iw then input{ bufL=0, bufR=0 }
else input{ bufL=ir },
output{ bufR=ow })
loop !ir !ow
| ow >= os = done OutputUnderflow ir ow
| ir >= iw = done InputUnderflow ir ow
| otherwise = do
(c,ir') <- readCharBuf iraw ir
writeWord8Buf oraw ow (fromIntegral (ord c))
loop ir' (ow+1)
in
loop ir0 ow0
latin1_checked_encode :: EncodeBuffer
latin1_checked_encode input output
= single_byte_checked_encode 0xff input output
ascii_encode :: EncodeBuffer
ascii_encode input output
= single_byte_checked_encode 0x7f input output
single_byte_checked_encode :: Int -> EncodeBuffer
single_byte_checked_encode max_legal_char
input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ }
output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os }
= let
done why !ir !ow = return (why,
if ir == iw then input{ bufL=0, bufR=0 }
else input{ bufL=ir },
output{ bufR=ow })
loop !ir !ow
| ow >= os = done OutputUnderflow ir ow
| ir >= iw = done InputUnderflow ir ow
| otherwise = do
(c,ir') <- readCharBuf iraw ir
if ord c > max_legal_char then invalid else do
writeWord8Buf oraw ow (fromIntegral (ord c))
loop ir' (ow+1)
where
invalid = done InvalidSequence ir ow
in
loop ir0 ow0
{-# INLINE single_byte_checked_encode #-}
|
ghc-android/ghc
|
libraries/base/GHC/IO/Encoding/Latin1.hs
|
bsd-3-clause
| 7,692
| 0
| 20
| 2,506
| 1,898
| 1,029
| 869
| 157
| 3
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Compact.Serialized
-- Copyright : (c) The University of Glasgow 2001-2009
-- (c) Giovanni Campagna <gcampagn@cs.stanford.edu> 2015
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : unstable
-- Portability : non-portable (GHC Extensions)
--
-- This module contains support for serializing a Compact for network
-- transmission and on-disk storage.
--
-- /Since: 1.0.0/
module GHC.Compact.Serialized(
SerializedCompact(..),
withSerializedCompact,
importCompact,
importCompactByteStrings,
) where
import GHC.Prim
import GHC.Types
import GHC.Word (Word8)
import GHC.Ptr (Ptr(..), plusPtr)
import Control.Concurrent
import qualified Data.ByteString as ByteString
import Data.ByteString.Internal(toForeignPtr)
import Data.IORef(newIORef, readIORef, writeIORef)
import Foreign.ForeignPtr(withForeignPtr)
import Foreign.Marshal.Utils(copyBytes)
import GHC.Compact
-- | A serialized version of the 'Compact' metadata (each block with
-- address and size and the address of the root). This structure is
-- meant to be sent alongside the actual 'Compact' data. It can be
-- sent out of band in advance if the data is to be sent over RDMA
-- (which requires both sender and receiver to have pinned buffers).
data SerializedCompact a = SerializedCompact
{ serializedCompactBlockList :: [(Ptr a, Word)]
, serializedCompactRoot :: Ptr a
}
addrIsNull :: Addr# -> Bool
addrIsNull addr = isTrue# (nullAddr# `eqAddr#` addr)
compactGetFirstBlock :: Compact# -> IO (Ptr a, Word)
compactGetFirstBlock buffer =
IO (\s -> case compactGetFirstBlock# buffer s of
(# s', addr, size #) -> (# s', (Ptr addr, W# size) #) )
compactGetNextBlock :: Compact# -> Addr# -> IO (Ptr a, Word)
compactGetNextBlock buffer block =
IO (\s -> case compactGetNextBlock# buffer block s of
(# s', addr, size #) -> (# s', (Ptr addr, W# size) #) )
mkBlockList :: Compact# -> IO [(Ptr a, Word)]
mkBlockList buffer = compactGetFirstBlock buffer >>= go
where
go :: (Ptr a, Word) -> IO [(Ptr a, Word)]
go (Ptr block, _) | addrIsNull block = return []
go item@(Ptr block, _) = do
next <- compactGetNextBlock buffer block
rest <- go next
return $ item : rest
-- We MUST mark withSerializedCompact as NOINLINE
-- Otherwise the compiler will eliminate the call to touch#
-- causing the Compact# to be potentially GCed too eagerly,
-- before func had a chance to copy everything into its own
-- buffers/sockets/whatever
-- | Serialize the 'Compact', and call the provided function with
-- with the 'Compact' serialized representation. It is not safe
-- to return the pointer from the action and use it after
-- the action completes: all uses must be inside this bracket,
-- since we cannot guarantee that the compact region will stay
-- live from the 'Ptr' object. For example, it would be
-- unsound to use 'unsafeInterleaveIO' to lazily construct
-- a lazy bytestring from the 'Ptr'.
--
{-# NOINLINE withSerializedCompact #-}
withSerializedCompact :: Compact a ->
(SerializedCompact a -> IO c) -> IO c
withSerializedCompact (Compact buffer root lock) func = withMVar lock $ \_ -> do
rootPtr <- IO (\s -> case anyToAddr# root s of
(# s', rootAddr #) -> (# s', Ptr rootAddr #) )
blockList <- mkBlockList buffer
let serialized = SerializedCompact blockList rootPtr
r <- func serialized
IO (\s -> case touch# buffer s of
s' -> (# s', r #) )
fixupPointers :: Addr# -> Addr# -> State# RealWorld ->
(# State# RealWorld, Maybe (Compact a) #)
fixupPointers firstBlock rootAddr s =
case compactFixupPointers# firstBlock rootAddr s of
(# s', buffer, adjustedRoot #) ->
if addrIsNull adjustedRoot then (# s', Nothing #)
else case addrToAny# adjustedRoot of
(# root #) -> case mkCompact buffer root s' of
(# s'', c #) -> (# s'', Just c #)
-- | Deserialize a 'SerializedCompact' into a in-memory 'Compact'. The
-- provided function will be called with the address and size of each
-- newly allocated block in succession, and should fill the memory
-- from the external source (eg. by reading from a socket or from disk)
-- 'importCompact' can return Nothing if the 'Compact' was corrupt
-- or it had pointers that could not be adjusted.
importCompact :: SerializedCompact a -> (Ptr b -> Word -> IO ()) ->
IO (Maybe (Compact a))
-- what we would like is
{-
importCompactPtrs ((firstAddr, firstSize):rest) = do
(firstBlock, compact) <- compactAllocateAt firstAddr firstSize
#nullAddr
fillBlock firstBlock firstAddr firstSize
let go prev [] = return ()
go prev ((addr, size):rest) = do
(block, _) <- compactAllocateAt addr size prev
fillBlock block addr size
go block rest
go firstBlock rest
if isTrue# (compactFixupPointers compact) then
return $ Just compact
else
return Nothing
But we can't do that because IO Addr# is not valid (kind mismatch)
This check exists to prevent a polymorphic data constructor from using
an unlifted type (which would break GC) - it would not a problem for IO
because IO stores a function, not a value, but the kind check is there
anyway.
Note that by the reasoning, we cannot do IO (# Addr#, Word# #), nor
we can do IO (Addr#, Word#) (that would break the GC for real!)
And therefore we need to do everything with State# explicitly.
-}
-- just do shut up GHC
importCompact (SerializedCompact [] _) _ = return Nothing
importCompact (SerializedCompact blocks root) filler = do
-- I'm not sure why we need a bang pattern here, given that
-- these are obviously strict lets, but ghc complains otherwise
let !((_, W# firstSize):otherBlocks) = blocks
let !(Ptr rootAddr) = root
IO $ \s0 ->
case compactAllocateBlock# firstSize nullAddr# s0 of {
(# s1, firstBlock #) ->
case fillBlock firstBlock firstSize s1 of { s2 ->
case go firstBlock otherBlocks s2 of { s3 ->
fixupPointers firstBlock rootAddr s3
}}}
where
-- note that the case statements above are strict even though
-- they don't seem to inspect their argument because State#
-- is an unlifted type
fillBlock :: Addr# -> Word# -> State# RealWorld -> State# RealWorld
fillBlock addr size s = case filler (Ptr addr) (W# size) of
IO action -> case action s of
(# s', _ #) -> s'
go :: Addr# -> [(Ptr a, Word)] -> State# RealWorld -> State# RealWorld
go _ [] s = s
go previous ((_, W# size):rest) s =
case compactAllocateBlock# size previous s of
(# s', block #) -> case fillBlock block size s' of
s'' -> go block rest s''
sanityCheckByteStrings :: SerializedCompact a -> [ByteString.ByteString] -> Bool
sanityCheckByteStrings (SerializedCompact scl _) bsl = go scl bsl
where
go [] [] = True
go (_:_) [] = False
go [] (_:_) = False
go ((_, size):scs) (bs:bss) =
fromIntegral size == ByteString.length bs && go scs bss
-- | Convenience function for importing a compact region that is represented
-- by a list of strict 'ByteString's.
--
importCompactByteStrings :: SerializedCompact a -> [ByteString.ByteString] ->
IO (Maybe (Compact a))
importCompactByteStrings serialized stringList =
-- sanity check stringList first - if we throw an exception later we leak
-- memory!
if not (sanityCheckByteStrings serialized stringList) then
return Nothing
else do
state <- newIORef stringList
let filler :: Ptr Word8 -> Word -> IO ()
filler to size = do
-- this pattern match will never fail
(next:rest) <- readIORef state
let (fp, off, _) = toForeignPtr next
withForeignPtr fp $ \from -> do
copyBytes to (from `plusPtr` off) (fromIntegral size)
writeIORef state rest
importCompact serialized filler
|
shlevy/ghc
|
libraries/ghc-compact/GHC/Compact/Serialized.hs
|
bsd-3-clause
| 8,135
| 0
| 19
| 1,802
| 1,674
| 883
| 791
| 105
| 4
|
{-# LANGUAGE OverloadedStrings, LambdaCase, TemplateHaskell #-}
module Web.Slack.Types.File where
import Data.Aeson
import Data.Aeson.Types
import Control.Applicative
import Data.Text (Text)
import qualified Data.Text as T
import Data.Maybe
import Control.Lens.TH
import Web.Slack.Types.Id
import Web.Slack.Types.Comment
import Web.Slack.Types.Time
import Web.Slack.Types.Base
import Prelude
data File = File { _fileId :: FileId
, _fileTimestamp :: Time
, _fileName :: Maybe Text
, _fileTitle :: Text
, _fileMime :: Text
, _filetype :: Text
, _filePrettyType :: Text
, _fileUser :: UserId
, _fileMode :: Mode
, _fileEditable :: Bool
, _fileIsExternal :: Bool
, _fileExternalType :: Text
, _fileSize :: Int
, _fileUrl :: FileUrl
, _fileThumbs :: Thumbnail
, _filePermalink :: URL
, _fileEditLink :: Maybe URL
, _filePreview :: Maybe Preview
, _filePublic :: Bool
, _filePublicShared :: Bool
, _fileChannels :: [ChannelId]
, _fileGroups :: [ChannelId]
, _fileInitialComment :: Maybe Comment
, _fileStars :: Int
, _fileComments :: Int } deriving Show
data Mode = Hosted | External | Snippet | Post deriving Show
instance FromJSON File where
parseJSON = withObject "File" (\o ->
File <$> o .: "id" <*> o .: "timestamp" <*> o .: "name" <*> o .: "title"
<*> o .: "mimetype" <*> o .: "filetype" <*> o .: "pretty_type" <*> o .: "user"
<*> o .: "mode" <*> o .: "editable" <*> o .: "is_external" <*> o .: "external_type"
<*> o .: "size" <*> (parseJSON (Object o) :: Parser FileUrl)
<*> (parseJSON (Object o) :: Parser Thumbnail) <*> o .: "permalink" <*> o .:? "edit_link"
<*> (pure $ parseMaybe parseJSON (Object o) :: Parser (Maybe Preview))
<*> o .: "is_public" <*> o .: "public_url_shared"
<*> o .: "channels" <*> o .: "groups" <*> o .:? "initial_comment"
<*> fmap (fromMaybe 0) (o .:? "num_stars") <*> o .: "comments_count" )
instance FromJSON FileUrl where
parseJSON = withObject "FileURL" (\o -> URL <$> o .: "url_private" <*> o .: "url_private_download")
instance FromJSON Thumbnail where
parseJSON = withObject "Thumbnail" (\o -> Thumbnail <$> o .:? "thumb_64" <*> o .:? "thumb_80" <*> o .:? "thumb_360" <*> o .:? "thumb_360_gif" <*> o .:? "thumb_360_w" <*> o .:? "thumb_360_h")
instance FromJSON Preview where
parseJSON = withObject "preview" (\o -> Preview <$> o .: "preview" <*> o .: "preview_highlight"
<*> o .: "lines" <*> o .: "lines_more")
data Preview = Preview { _previewText :: Text, _previewHighlight :: Text, _lines :: Int, _linesMore :: Int } deriving Show
data FileUrl = URL { _private :: Text, _privateDownload :: Text } deriving Show
data Thumbnail = Thumbnail { _w64 :: Maybe URL, _w80 :: Maybe URL, _w360 :: Maybe URL, _w360gif :: Maybe URL, _width :: Maybe Int, _height :: Maybe Int} deriving Show
makeLenses ''File
makeLenses ''FileUrl
makeLenses ''Thumbnail
makeLenses ''Preview
instance FromJSON Mode where
parseJSON = withText "mode"
(\case
"hosted" -> pure Hosted
"external" -> pure External
"snippet" -> pure Snippet
"post" -> pure Post
s -> fail $ "Unrecognised mode: " ++ T.unpack s)
|
madjar/slack-api
|
src/Web/Slack/Types/File.hs
|
mit
| 3,932
| 0
| 54
| 1,400
| 988
| 547
| 441
| 73
| 0
|
module Workplaces.WeaponMaking where
import Rules
import TestFramework
import TestHelpers
import Test.Tasty.QuickCheck
import Test.Tasty
import Test.QuickCheck.Monadic
weaponMakingTests :: TestTree
weaponMakingTests = localOption (QuickCheckMaxRatio 500) $ testGroup "Weapon making tests" $ [
testProperty "Can arm worker after starting working and worker is unarmed" $ movingWorkerProperty $ do
(plId, workerId, _) <- startWorkingInWeaponMaking
canArm <- getsUniverse isArmingWorker <*> pure plId
checkWorkerIsUnarmed workerId
assert $ canArm,
testProperty "Can go on adventure after starting working and arming" $ movingWorkerProperty $ do
(plId, workerId, _) <- startWorkingInWeaponMaking
checkWorkerIsUnarmed workerId
applyToUniverse $ armWorker plId 1
canAdventure <- getsUniverse canGoOnAdventure <*> pure plId
assert $ canAdventure,
testProperty "Can arm worker after starting working and worker is unarmed" $ movingWorkerProperty $ do
(plId, workerId, _) <- startWorkingInWeaponMaking
canArm <- getsUniverse isArmingWorker <*> pure plId
checkWorkerIsUnarmed workerId
assert $ canArm,
testProperty "Next player's turn after arming and adventuring" $ movingWorkerProperty $ do
(plId, workerId, _) <- startWorkingInWeaponMaking
checkWorkerIsUnarmed workerId
checkPlayerHasValidOccupants plId
applyToUniverse $ armWorker plId 1
applyToUniverse $ adventure plId WoodReward
validateNextPlayer plId,
testProperty "Next player's turn after adventuring" $ movingWorkerProperty $ do
(plId, workerId, _) <- startWorkingInWeaponMaking
checkWorkerIsArmed workerId
checkPlayerHasValidOccupants plId
applyToUniverse $ adventure plId WoodReward
validateNextPlayer plId,
testProperty "Next player's turn after adventuring and building" $ movingWorkerProperty $ do
(plId, workerId, _) <- startWorkingInWeaponMaking
checkWorkerIsArmed workerId
checkPlayerHasValidOccupants plId
(pos, dir) <- pickSpecificPosition availableSingleForestPositions plId
applyToUniverse $ adventure plId GrassReward
applyToUniverse $ buildBuildings plId pos dir $ SingleSmallBuildingDesc Grass
validateNextPlayer plId
]
startWorkingInWeaponMaking :: UniversePropertyMonad (PlayerId, WorkerId, WorkplaceId)
startWorkingInWeaponMaking = do
universe <- getUniverse
(plId, workerId, workplaceId) <- startWorkingInWorkplaceType WeaponMaking
let iron = getIronAmount $ getPlayerResources universe plId
let workerStrength = getWorkerStrength universe workerId
pre $ workerStrength > 0 || iron > 0
return (plId, workerId, workplaceId)
checkWorkerIsUnarmed :: WorkerId -> UniversePropertyMonad ()
checkWorkerIsUnarmed workerId = do
workerStrength <- getsUniverse getWorkerStrength <*> pure workerId
pre $ workerStrength == 0
checkWorkerIsArmed :: WorkerId -> UniversePropertyMonad ()
checkWorkerIsArmed workerId = do
workerStrength <- getsUniverse getWorkerStrength <*> pure workerId
pre $ workerStrength > 0
|
martin-kolinek/some-board-game-rules
|
test/Workplaces/WeaponMaking.hs
|
mit
| 3,131
| 0
| 12
| 586
| 699
| 332
| 367
| 62
| 1
|
{-# LANGUAGE BangPatterns #-}
{--
http://www.freetype.org/freetype2/docs/tutorial/step1.html
--}
module Main where
import Prelude hiding (lookup)
import Control.Monad
import Control.Applicative
import System.FilePath
import Data.Char
import Data.Map (toList, lookup, size)
import Graphics.Font
import Codec.Picture
{--
" !\"#$%&'()*+,-./0123456789:;<=>?"
"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
"`abcdefghijklmnopqrstuvwxyz{|}~"
--}
fontPath :: FilePath
fontPath = "font" </> "SourceCodePro-Regular.otf"
charFolder :: FilePath
charFolder = "chars"
main :: IO ()
main = withNewLibrary $ \lib -> do
let descr = FontDescriptor
{ charSize = (0, 16*64)
, deviceRes = (600, 600)
}
font <- loadFont lib fontPath descr
imgs <- generateAllCharImgs font Monochrome
print $ "_loaded chars: " ++ show (size imgs)
forM_ (toList imgs) $ \(!c, !img) -> do
print c
print $ glyphMetrics <$> lookup c (charMap font)
writePng (charFolder </> "char" ++ show (ord c) ++ ".png") img
|
MaxDaten/typography-ft2
|
examples/LibTest.hs
|
mit
| 1,046
| 0
| 19
| 215
| 284
| 151
| 133
| 26
| 1
|
module Phb.Main where
import BasePrelude
import Prelude ()
import qualified Data.ByteString.Lazy as LBS
import Database.Persist.Sql (toSqlKey)
import Text.Blaze.Html.Renderer.Utf8 (renderHtml)
import Phb.Db.Heartbeat (loadHeartbeat)
import Phb.Db.Setup (setup)
import Phb.Output.Email (heartbeatHtml)
printHtml :: IO ()
printHtml = do
--setup
hMay <- loadHeartbeat (toSqlKey 1)
traverse_ (LBS.writeFile "heartbeat.html" . renderHtml . heartbeatHtml) hMay
|
benkolera/phb
|
hs/Phb/Main.hs
|
mit
| 511
| 0
| 12
| 105
| 137
| 81
| 56
| 13
| 1
|
module Y2016.M08.D30.Exercise where
-- below imports available on 1HaskellADay git repository
import Control.Scan.CSV
import Data.Monetary.BitCoin
import Data.Monetary.USD
{--
Okay, last week we started looking at the bitcoin value-proposition a little
bit, comparing it to itself and then bitcoin against gold.
But how do you get bitcoins? One way is to buy them, which is a perfectly
viable option (which we will explore further), another way is to earn them,
by exchanging work for bitcoin (you know, like, money, and stuff), and another
way is to mine them.
Bitcoin mining is a whole, rich topic into itself, including how mining evolved
to the point now where mining uses specialized hardware with chips designed
with that sole-purpose. The internet is available for you to explore this
topic further.
So, let's pretend we know all about mining. Just go with me on this one for now.
Okay, as a miner, you ... can use your computer, and that worked in the early
days of mining, but now: not so much. Let's buy some mining hardware and then
start to mine.
But which mining hardware? Going to
https://www.bitcoinmining.com/bitcoin-mining-hardware/
three options are recommended, so let's look at those.
--}
data PowerEfficiency = SomeMeasureOfEfficiency
deriving (Eq, Ord, Show)
data BitCoinMiner =
BTCMiner { model :: String,
cost :: USD,
efficiency :: PowerEfficiency,
approxBTCperMonth :: BitCoin }
deriving (Eq, Ord, Show)
readBitCoinMiners :: FilePath -> IO [BitCoinMiner]
readBitCoinMiners = undefined
-- read in the models provided from bitcoin_miners.csv in this directory, url:
-- https://raw.githubusercontent.com/geophf/1HaskellADay/master/exercises/HAD/Y2016/M08/D30/bitcoin_miners.csv
-- Hint: perhaps Control.Scan.CSV.csv will help?
-- Now that you have those data. What is the best machine to do bitcoin
-- mining? Why? Come up with a set of measures that compare cost, efficiency
-- and approximate bitcoins mined to determine what's the 'best' machine
data CostEfficiencyBTCMeasure = MeasureYouDetermine
bestBitCoinMiner :: [BitCoinMiner] -> (BitCoinMiner, CostEfficiencyBTCMeasure)
bestBitCoinMiner = undefined
-- Show your justification for the 'best' bitcoin miner
|
geophf/1HaskellADay
|
exercises/HAD/Y2016/M08/D30/Exercise.hs
|
mit
| 2,260
| 0
| 8
| 388
| 155
| 97
| 58
| 17
| 1
|
module Distribution.App
(App(..),
addAppHooks,
ibtoolProgram
)
where
import Data.Maybe
import Distribution.Compat.Filesystem
import Distribution.Compat.ReadP
import Distribution.PackageDescription
import Distribution.ParseUtils
import Distribution.ReadE
import Distribution.Simple
import Distribution.Simple.Build
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Program
import Distribution.Simple.Setup
import Distribution.Simple.Utils
import Distribution.System
import Distribution.Verbosity
import System.Directory
import System.FilePath (replaceExtension)
data App = App {
appCHeaders :: [FilePath],
appCSources :: [FilePath],
appName :: String,
appInfoPlist :: FilePath,
appResourceDirectory :: Maybe FilePath,
appXIBs :: [FilePath],
appOtherResources :: [FilePath]
}
deriving (Show)
addAppHooks :: UserHooks -> UserHooks
addAppHooks userHooks =
let oldHookedPrograms = hookedPrograms userHooks
oldBuildHook = buildHook userHooks
in userHooks {
hookedPrograms = [touchProgram, ibtoolProgram] ++ oldHookedPrograms,
buildHook = appBuildHook oldBuildHook
}
touchProgram :: Program
touchProgram = simpleProgram "touch"
ibtoolProgram :: Program
ibtoolProgram = simpleProgram "ibtool"
appBuildHook :: (PackageDescription
-> LocalBuildInfo
-> UserHooks
-> BuildFlags
-> IO ())
-> PackageDescription
-> LocalBuildInfo
-> UserHooks
-> BuildFlags
-> IO ()
appBuildHook oldBuildHook
packageDescription
localBuildInfo
userHooks
buildFlags = do
oldBuildHook packageDescription localBuildInfo userHooks buildFlags
if buildOS == OSX
then withExeLBI packageDescription
localBuildInfo
(\executable componentLocalBuildInfo -> do
maybeApp <- getApp buildFlags executable
case maybeApp of
Nothing -> return ()
Just app -> buildApp buildFlags
localBuildInfo
executable
app)
else return ()
getApp :: BuildFlags -> Executable -> IO (Maybe App)
getApp buildFlags executable = do
let verbosity = fromFlagOrDefault normal $ buildVerbosity buildFlags
fields = customFieldsBI $ buildInfo executable
getParse fieldName parser = do
case lookup fieldName fields of
Nothing -> return Nothing
Just string -> do
case [x | (x, "") <- readP_to_S parser string] of
[result] -> return $ Just result
[] -> fail $ "No parse of " ++ fieldName ++ "."
_ -> fail $ "Ambiguous parse of " ++ fieldName ++ "."
getListParse fieldName parser = do
result <- getParse fieldName $ parseCommaList parser
case result of
Nothing -> return []
Just items -> return items
maybeAppInfoPlist <- getParse "x-app-info-plist" parseFilePathQ
case maybeAppInfoPlist of
Nothing -> return Nothing
Just appInfoPlist -> do
appCHeaders <- getListParse "x-app-c-headers" parseFilePathQ
appCSources <- getListParse "x-app-c-sources" parseFilePathQ
let appName = exeName executable
appResourceDirectory <-
getParse "x-app-resource-dir" parseFilePathQ
>>= return . fmap pathCoerceToDirectory
appXIBs <- getListParse "x-app-xibs" parseFilePathQ
appOtherResources <- getListParse "x-app-other-resources" parseFilePathQ
return $ Just App {
appCHeaders = appCHeaders,
appCSources = appCSources,
appName = appName,
appInfoPlist = appInfoPlist,
appResourceDirectory = appResourceDirectory,
appXIBs = appXIBs,
appOtherResources = appOtherResources
}
buildApp :: BuildFlags -> LocalBuildInfo -> Executable -> App -> IO ()
buildApp buildFlags localBuildInfo executable app = do
let distPref = fromFlagOrDefault defaultDistPref $ buildDistPref buildFlags
verbosity = fromFlagOrDefault normal $ buildVerbosity buildFlags
appPath = distPref </> "build" </> (appName app ++ ".app")
contentsPath = appPath </> "Contents"
executableDirectoryPath = contentsPath </> "MacOS"
resourcesPath = contentsPath </> "Resources"
(touchConfiguredProgram, _) <-
requireProgram verbosity touchProgram $ withPrograms localBuildInfo
(ibtoolConfiguredProgram, _) <-
requireProgram verbosity ibtoolProgram $ withPrograms localBuildInfo
info verbosity $ "Building " ++ appName app ++ ".app bundle..."
removeDirectoryRecursiveSilently appPath
createDirectoryIfMissing False appPath
writeFileAtomic (appPath </> "PkgInfo") "APPL????"
createDirectoryIfMissing False contentsPath
let infoPlistSource = appInfoPlist app
infoPlistDestination = contentsPath </> "Info.plist"
installOrdinaryFile verbosity infoPlistSource infoPlistDestination
createDirectoryIfMissing False executableDirectoryPath
let executableSource =
buildDir localBuildInfo </> exeName executable </> exeName executable
executableDestination =
executableDirectoryPath </> appName app
installExecutableFile verbosity executableSource executableDestination
createDirectoryIfMissing False resourcesPath
let sourceResourcePath relativePath =
case appResourceDirectory app of
Nothing -> relativePath
Just resourceDirectory -> resourceDirectory </> relativePath
mapM_ (\xib -> do
let xibPath = sourceResourcePath xib
nibPath = resourcesPath </> replaceExtension xib ".nib"
runProgram verbosity
ibtoolConfiguredProgram
["--warnings",
"--errors",
"--output-format=human-readable-text",
"--compile",
nibPath,
xibPath])
$ appXIBs app
mapM_ (\resource -> do
let resourceSource = sourceResourcePath resource
resourceDestination = resourcesPath </> resource
installOrdinaryFile verbosity resourceSource resourceDestination)
$ appOtherResources app
runProgram verbosity touchConfiguredProgram [appPath]
|
IreneKnapp/cabal-app
|
Distribution/App.hs
|
mit
| 6,722
| 0
| 22
| 2,039
| 1,367
| 682
| 685
| 154
| 6
|
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Unison.HashQualified where
import Unison.Prelude hiding (fromString)
import qualified Data.Text as Text
import Prelude hiding ( take )
import Unison.Name ( Name, Convert, Parse )
import qualified Unison.Name as Name
import Unison.Reference ( Reference )
import qualified Unison.Reference as Reference
import Unison.Referent ( Referent )
import qualified Unison.Referent as Referent
import Unison.ShortHash ( ShortHash )
import qualified Unison.ShortHash as SH
import Unison.Var ( Var )
import qualified Unison.Var as Var
data HashQualified n
= NameOnly n | HashOnly ShortHash | HashQualified n ShortHash
deriving (Eq, Foldable, Traversable, Functor, Show, Generic)
stripNamespace :: Text -> HashQualified Name -> HashQualified Name
stripNamespace namespace hq = case hq of
NameOnly name -> NameOnly $ strip name
HashQualified name sh -> HashQualified (strip name) sh
ho -> ho
where
strip name =
fromMaybe name $ Name.stripNamePrefix (Name.unsafeFromText namespace) name
toName :: HashQualified n -> Maybe n
toName = \case
NameOnly name -> Just name
HashQualified name _ -> Just name
HashOnly _ -> Nothing
-- Sort the list of names by length of segments: smaller number of
-- segments is listed first. NameOnly < Hash qualified < Hash only
--
-- Examples:
-- [foo.bar.baz, bar.baz] -> [bar.baz, foo.bar.baz]
-- [#a29dj2k91, foo.bar.baz] -> [foo.bar.baz, #a29dj2k91]
-- [foo.bar#abc, foo.bar] -> [foo.bar, foo.bar#abc]
-- [.foo.bar, foo.bar] -> [foo.bar, .foo.bar]
sortByLength :: [HashQualified Name] -> [HashQualified Name]
sortByLength hs = sortOn f hs where
f (NameOnly n) = (countDots n, 0, Left n)
f (HashQualified n _h) = (countDots n, 1, Left n)
f (HashOnly h) = (maxBound, 0, Right h)
countDots n = Text.count "." (Text.dropEnd 1 (Name.toText n))
hasName, hasHash :: HashQualified Name -> Bool
hasName = isJust . toName
hasHash = isJust . toHash
toHash :: HashQualified n -> Maybe ShortHash
toHash = \case
NameOnly _ -> Nothing
HashQualified _ sh -> Just sh
HashOnly sh -> Just sh
-- partial: assumes either a name or hash is provided (or both)
fromNameHash :: Maybe Name -> Maybe ShortHash -> HashQualified Name
fromNameHash n h = case n of
Just name -> case h of
Just hash -> HashQualified name hash
Nothing -> NameOnly name
Nothing -> case h of
Just hash -> HashOnly hash
Nothing -> error "bad HQ construction"
take :: Int -> HashQualified n -> HashQualified n
take i = \case
n@(NameOnly _) -> n
HashOnly s -> HashOnly (SH.take i s)
HashQualified n s -> if i == 0 then NameOnly n else HashQualified n (SH.take i s)
toString :: Show n => HashQualified n -> String
toString = Text.unpack . toText
fromString :: String -> Maybe (HashQualified Name)
fromString = fromText . Text.pack
unsafeFromString :: String -> HashQualified Name
unsafeFromString s = fromMaybe msg . fromString $ s where
msg = error $ "HashQualified.unsafeFromString " <> show s
-- Parses possibly-hash-qualified into structured type.
-- Doesn't validate against base58 or the codebase.
fromText :: Text -> Maybe (HashQualified Name)
fromText t = case Text.breakOn "#" t of -- breakOn leaves the '#' on the RHS
(name, "" ) -> Just $ NameOnly (Name.unsafeFromText name) -- safe bc breakOn #
("" , hash) -> HashOnly <$> SH.fromText hash
(name, hash) -> HashQualified (Name.unsafeFromText name) <$> SH.fromText hash
-- Won't crash as long as SH.unsafeFromText doesn't crash on any input that
-- starts with '#', which is true as of the time of this writing, but not great.
unsafeFromText :: Text -> HashQualified Name
unsafeFromText txt = fromMaybe msg . fromText $ txt where
msg = error $ "HashQualified.unsafeFromText " <> show txt
toText :: Show n => HashQualified n -> Text
toText = \case
NameOnly name -> Text.pack (show name)
HashQualified name hash -> Text.pack (show name) <> SH.toText hash
HashOnly hash -> SH.toText hash
-- Returns the full referent in the hash. Use HQ.take to just get a prefix
fromNamedReferent :: n -> Referent -> HashQualified n
fromNamedReferent n r = HashQualified n (Referent.toShortHash r)
-- Returns the full reference in the hash. Use HQ.take to just get a prefix
fromNamedReference :: n -> Reference -> HashQualified n
fromNamedReference n r = HashQualified n (Reference.toShortHash r)
fromReferent :: Referent -> HashQualified Name
fromReferent = HashOnly . Referent.toShortHash
fromReference :: Reference -> HashQualified Name
fromReference = HashOnly . Reference.toShortHash
fromPattern :: Reference -> Int -> HashQualified Name
fromPattern r cid = HashOnly $ Referent.patternShortHash r cid
fromName :: n -> HashQualified n
fromName = NameOnly
unsafeFromVar :: Var v => v -> HashQualified Name
unsafeFromVar = unsafeFromText . Var.name
fromVar :: Var v => v -> Maybe (HashQualified Name)
fromVar = fromText . Var.name
toVar :: Var v => HashQualified Name -> v
toVar = Var.named . toText
-- todo: find this logic elsewhere and replace with call to this
matchesNamedReferent :: Name -> Referent -> HashQualified Name -> Bool
matchesNamedReferent n r = \case
NameOnly n' -> n' == n
HashOnly sh -> sh `SH.isPrefixOf` Referent.toShortHash r
HashQualified n' sh -> n' == n && sh `SH.isPrefixOf` Referent.toShortHash r
matchesNamedReference :: Name -> Reference -> HashQualified Name -> Bool
matchesNamedReference n r = \case
NameOnly n' -> n' == n
HashOnly sh -> sh `SH.isPrefixOf` Reference.toShortHash r
HashQualified n' sh -> n' == n && sh `SH.isPrefixOf` Reference.toShortHash r
-- Use `requalify hq . Referent.Ref` if you want to pass in a `Reference`.
requalify :: HashQualified Name -> Referent -> HashQualified Name
requalify hq r = case hq of
NameOnly n -> fromNamedReferent n r
HashQualified n _ -> fromNamedReferent n r
HashOnly _ -> fromReferent r
-- Ordered alphabetically, based on the name. Hashes come last.
instance (Eq n, Name.Alphabetical n) => Ord (HashQualified n) where
compare a b = case (toName a, toName b) of
(Just n , Just n2) -> Name.compareAlphabetical n n2
(Nothing, Just _) -> GT
(Just _ , Nothing) -> LT
(Nothing, Nothing) -> EQ
<>
case (toHash a, toHash b) of
(Nothing, Nothing) -> EQ
(Nothing, Just _) -> LT -- prefer NameOnly to HashQualified
(Just _, Nothing) -> GT
(Just sh, Just sh2) -> compare sh sh2
instance Convert n n2 => Convert (HashQualified n) (HashQualified n2) where
convert = fmap Name.convert
instance Convert n (HashQualified n) where
convert = NameOnly
instance Parse Text (HashQualified Name) where
parse = fromText
--instance Show n => Show (HashQualified n) where
-- show = Text.unpack . toText
|
unisonweb/platform
|
unison-core/src/Unison/HashQualified.hs
|
mit
| 7,163
| 0
| 12
| 1,620
| 2,030
| 1,038
| 992
| -1
| -1
|
import Data.List
lowest :: Int -> [(Int, Int)] -> Int
lowest candidate [] = candidate
lowest candidate ((lo, hi):xs) =
if lo > candidate then candidate
else lowest (max candidate (hi + 1)) xs
total :: Int -> [(Int, Int)] -> Int
total candidate [] = 4294967295 - candidate + 1
total candidate ((lo, hi):xs) =
if lo > candidate then lo - candidate + total (hi + 1) xs
else total (max candidate (hi + 1)) xs
parse :: String -> (Int, Int)
parse line =
let [(lo, '-':hi)] = reads line
in (lo, read hi)
part1 :: String -> Int
part1 = lowest 0 . sort . map parse . lines
part2 :: String -> Int
part2 = total 0 . sort . map parse . lines
|
seishun/aoc2016
|
day20.hs
|
mit
| 647
| 0
| 11
| 146
| 336
| 179
| 157
| 19
| 2
|
{-# LANGUAGE DoAndIfThenElse #-}
import Control.Monad (liftM)
import Control.Monad.State.Strict (lift)
import Data.Char (toLower)
import Data.List (isPrefixOf)
import System.Console.Haskeline (Completion, InputT, Settings, completeWordWithPrev, defaultSettings, getInputLine, runInputT, setComplete, simpleCompletion)
import System.Directory (getDirectoryContents, getCurrentDirectory)
import System.FilePath ()
import qualified Data.Map as M
import Functions (getProjectAttributes, IDEState)
import IDECommands (ideCommand, ideCommands)
import Print (setRed, printPrompt)
-- TODO: use aeson and json for .project file
-- TODO: autocomplete "init" on language names
-------------------------------------------------------------------------------
-- Main loop
-------------------------------------------------------------------------------
main :: IO ()
main = do
firstState <- getProjectAttributes
let loop :: IDEState -> InputT IO ()
loop state = do
lift setRed
lift $ printPrompt state
minput <- getInputLine ""
case liftM commandSubstitute minput of
Nothing -> return ()
Just "exit" -> return ()
Just input -> do
newState <- lift (ideCommand (words input) state)
loop newState
runInputT ideSettings $ loop firstState
-------------------------------------------------------------------------------
-- Command line
-------------------------------------------------------------------------------
-- The settings to use for the shell
ideSettings :: Settings IO
ideSettings = setComplete (completeWordWithPrev Nothing " \t" findCompletion)
defaultSettings
-- Complete command line commands
findCompletion :: String -> String -> IO [Completion]
-- TODO: list all possible languages
-- match "init "
findCompletion " tini" s = return $ map simpleCompletion $ filter (s `isPrefixOf`) ["haskell", "python"]
-- TODO: only look for tracked files and maybe all source files in directory
-- tree
-- match "edit "
findCompletion " tide" s = do
dir <- getDirectoryContents =<< getCurrentDirectory
return $ map simpleCompletion $ filter (s `isPrefixOf`) dir
-- match on commands
findCompletion _ s = return $ map simpleCompletion $ filter (s `isPrefixOf`)
(M.keys ideCommands)
-- substitute an equivalent command string using the default command name
commandSubstitute :: String -> String
commandSubstitute s = result
where
wList = words s
result
| null wList = s
| map toLower (head wList) `elem` exitCommands = "exit"
| otherwise = unwords
(wordSubstitute (map toLower $ head wList) : tail wList)
-- substitute an equivalent command name with the default name
wordSubstitute :: String -> String
wordSubstitute "ls" = "list"
wordSubstitute "e" = "edit"
wordSubstitute s = s
-- the list of exist commands
exitCommands :: [String]
exitCommands = ["exit", ":q", "quit", ":quit"]
|
jonathanmcelroy/commandLineIDE
|
main.hs
|
mit
| 3,091
| 0
| 22
| 680
| 659
| 353
| 306
| 51
| 3
|
module GHCJS.DOM.WebGLContextAttributes (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/WebGLContextAttributes.hs
|
mit
| 52
| 0
| 3
| 7
| 10
| 7
| 3
| 1
| 0
|
import Test.Framework (defaultMain)
import qualified Tests.Parser.BuildConfig
import qualified Tests.Parser.Properties
import qualified Tests.Parser.PluginDesc
main :: IO ()
main = defaultMain [ Tests.Parser.BuildConfig.tests
, Tests.Parser.Properties.tests
, Tests.Parser.PluginDesc.tests
]
|
mbezjak/grailsproject
|
test/run.hs
|
mit
| 351
| 0
| 7
| 85
| 71
| 45
| 26
| 8
| 1
|
module Language.Binal.Generator.Simple(generateString) where
import Control.Applicative
import Control.Monad.State
import qualified Data.Aeson as Aeson
import qualified Data.Maybe as Maybe
import qualified Data.HashMap.Strict as HashMap
import qualified Data.ByteString.Lazy.UTF8 as BS
import Language.Binal.Types
import Language.Binal.Generator.Types
import qualified Language.Binal.Util as Util
import qualified Language.Binal.Generator.Util as GUtil
humanReadable :: JSAST -> JSAST
humanReadable (ExprStmtJSAST (AssignJSAST name (CondJSAST x y z))) = humanReadable (IfJSAST (humanReadable x) (humanReadable (ExprStmtJSAST (AssignJSAST name y))) (humanReadable (ExprStmtJSAST (AssignJSAST name z))))
humanReadable x@(ExprStmtJSAST (AssignJSAST _ (SeqJSAST []))) = x
humanReadable (ExprStmtJSAST (AssignJSAST x (SeqJSAST xs))) = humanReadable (BlockJSAST (map ExprStmtJSAST (init xs) ++ [ExprStmtJSAST (AssignJSAST x (last xs))]))
humanReadable (ExprStmtJSAST (AssignJSAST x y))
| x == y = BlockJSAST []
| otherwise = ExprStmtJSAST (AssignJSAST (humanReadable x) (humanReadable y))
humanReadable (ExprStmtJSAST (SeqJSAST ys)) = BlockJSAST (map (humanReadable . ExprStmtJSAST) ys)
humanReadable (ExprStmtJSAST (CondJSAST x y z)) = IfJSAST (humanReadable x) (humanReadable (ExprStmtJSAST y)) (humanReadable (ExprStmtJSAST z))
humanReadable (RetJSAST (SeqJSAST xs)) = BlockJSAST ((map (humanReadable . ExprStmtJSAST) (init xs)) ++ [humanReadable (RetJSAST (last xs))])
humanReadable (RetJSAST (CondJSAST x y z)) = IfJSAST (humanReadable x) (humanReadable (RetJSAST y)) (humanReadable (RetJSAST z))
humanReadable (RetJSAST (AssignJSAST name x)) = humanReadable (BlockJSAST [ExprStmtJSAST (AssignJSAST name x), RetJSAST (IdentJSAST "undefined")])
humanReadable (RetJSAST (StmtExprJSAST (ThrowJSAST x)))= humanReadable (ThrowJSAST x)
humanReadable (RetJSAST (StmtExprJSAST (RetJSAST x)))= humanReadable (RetJSAST x)
humanReadable (BlockJSAST xs) = BlockJSAST (map humanReadable xs)
humanReadable (IfJSAST x (BlockJSAST []) (BlockJSAST [])) = humanReadable (ExprStmtJSAST x)
humanReadable (IfJSAST x (BlockJSAST []) z) = humanReadable (IfJSAST (UnaryJSAST "!" x) z (BlockJSAST []))
humanReadable x@(DefVarsJSAST _) = x
humanReadable (AssignJSAST x y) = AssignJSAST (humanReadable x) (humanReadable y)
humanReadable (MemberJSAST x y) = MemberJSAST (humanReadable x) y
humanReadable (ComputedMemberJSAST x y) = ComputedMemberJSAST (humanReadable x) (humanReadable y)
humanReadable (ObjLitJSAST x) = ObjLitJSAST (HashMap.map humanReadable x)
humanReadable (ArrLitJSAST x) = ArrLitJSAST (map humanReadable x)
humanReadable (FuncLitJSAST x y) = FuncLitJSAST (map humanReadable x) (humanReadable y)
humanReadable x@(IdentJSAST _) = x
humanReadable x@(StrLitJSAST _) = x
humanReadable x@(NumLitJSAST _) = x
humanReadable (CallJSAST x y) = CallJSAST (humanReadable x) (map humanReadable y)
humanReadable (RetJSAST x) = RetJSAST (humanReadable x)
humanReadable (ExprStmtJSAST x) = ExprStmtJSAST (humanReadable x)
humanReadable (StmtExprJSAST x) = StmtExprJSAST (humanReadable x)
humanReadable (ProgramJSAST xs) = ProgramJSAST (map humanReadable xs)
humanReadable (CondJSAST x y z) = CondJSAST (humanReadable x) (humanReadable y) (humanReadable z)
humanReadable (IfJSAST x y z) = IfJSAST (humanReadable x) (humanReadable y) (humanReadable z)
humanReadable (BinaryJSAST x y z) = BinaryJSAST x (humanReadable y) (humanReadable z)
humanReadable (UnaryJSAST x y) = UnaryJSAST x (humanReadable y)
humanReadable (SeqJSAST xs) = SeqJSAST (map humanReadable xs)
humanReadable (ThrowJSAST x) = ThrowJSAST (humanReadable x)
humanReadable (NewJSAST x y) = NewJSAST (humanReadable x) (map humanReadable y)
humanReadable (WhileJSAST x y) = WhileJSAST (humanReadable x) (humanReadable y)
generateDeclare :: TypedAST -> JSAST
generateDeclare = DefVarsJSAST . map GUtil.toJSSafeSymbol . Util.flatSymbolsT
generateParams1 :: TypedAST -> Int -> JSAST
generateParams1 (TyLit (SymLit s) _ _) _ = IdentJSAST (GUtil.toJSSafeSymbol s)
generateParams1 _ i = IdentJSAST ("_" ++ show i)
generateParams :: TypedAST -> [JSAST]
generateParams (TyLit (SymLit s) _ _) = [IdentJSAST (GUtil.toJSSafeSymbol s)]
generateParams (TyLit _ _ _) = []
generateParams (TyList xs _ _) = map (uncurry generateParams1) (zip xs [0..])
assignValues :: TypedAST -> JSAST -> JSAST
assignValues (TyLit (SymLit s) _ _) tmp = ExprStmtJSAST (AssignJSAST (IdentJSAST (GUtil.toJSSafeSymbol s)) tmp)
assignValues (TyLit (StrLit _) _ _) _ = BlockJSAST []
assignValues (TyLit (NumLit _) _ _) _ = BlockJSAST []
assignValues (TyLit (BoolLit _) _ _) _ = BlockJSAST []
assignValues (TyList xs _ _) tmp
= BlockJSAST
(map (\(x,i) ->
assignValues x
(ComputedMemberJSAST tmp (NumLitJSAST (realToFrac i)))) (zip xs ([0..] :: [Int])))
generateString :: TypedAST -> String
generateString = BS.toString . Aeson.encode . Aeson.toJSON . flatJSAST . humanReadable . flatJSAST . generateProgram
generateProgram :: TypedAST -> JSAST
generateProgram tast = do
let x = evalState (generateStmt tast) [0..]
ProgramJSAST [
ExprStmtJSAST (StmtExprJSAST (
BlockJSAST [
ExprStmtJSAST (StrLitJSAST "use strict"),
DefVarsJSAST ["Binal"],
ExprStmtJSAST (AssignJSAST (IdentJSAST "Binal") (CallJSAST (IdentJSAST "require") [StrLitJSAST "binal-runtime"])),
x]))]
generateFuncBody :: TypedAST -> JSAST
generateFuncBody tast = do
let (result, varList) = runState (generateStmt tast) [0..]
let declareList = map (\i -> "_tmp" ++ show i) [0..(head varList - 1)]
let tmpDeclare = case declareList of
[] -> BlockJSAST []
_ -> DefVarsJSAST declareList
case result of
BlockJSAST [] -> BlockJSAST []
BlockJSAST xs ->
case last xs of
ExprStmtJSAST x -> BlockJSAST (tmpDeclare : (init xs ++ [RetJSAST x]))
_ -> BlockJSAST (tmpDeclare:xs)
ExprStmtJSAST x -> BlockJSAST [tmpDeclare,RetJSAST x]
x -> BlockJSAST [tmpDeclare, x]
gensym :: State [Int] Int
gensym = do
varList <- get
modify tail
return (head varList)
generateStmt :: TypedAST -> State [Int] JSAST
generateStmt (TyList (TyLit (SymLit "seq") _ _:xs) _ _) = do
BlockJSAST <$> mapM generateStmt xs
generateStmt (TyList (TyLit (SymLit "let") _ _:pattern:value:[]) _ _) = do
let declare = generateDeclare pattern
value' <- generateExpr value
case pattern of
(TyLit (SymLit s) _ _) -> do
let assign = ExprStmtJSAST (AssignJSAST (IdentJSAST (GUtil.toJSSafeSymbol s)) value')
return (BlockJSAST [declare, assign])
_ -> do
i <- gensym
let tmp = IdentJSAST ("_tmp" ++ show i)
let tmpAssign = ExprStmtJSAST (AssignJSAST tmp value')
let assign = assignValues pattern tmp
return (BlockJSAST [declare, tmpAssign, assign])
generateStmt (TyList (TyLit (SymLit "letrec") _ _:pattern:value:[]) _ _) = do
let declare = generateDeclare pattern
value' <- generateExpr value
case pattern of
(TyLit (SymLit s) _ _) -> do
let assign = ExprStmtJSAST (AssignJSAST (IdentJSAST (GUtil.toJSSafeSymbol s)) value')
return (BlockJSAST [declare, assign])
_ -> do
i <- gensym
let tmp = IdentJSAST ("_tmp" ++ show i)
let tmpAssign = ExprStmtJSAST (AssignJSAST tmp value')
let assign = assignValues pattern tmp
return (BlockJSAST [declare, tmpAssign, assign])
generateStmt (TyList (TyLit (SymLit "assume") _ _:_:[]) _ _) = do
return (BlockJSAST [])
generateStmt x = ExprStmtJSAST <$> generateExpr x
unRet :: JSAST -> JSAST
unRet (IfJSAST x y z) = IfJSAST x (unRet y) (unRet z)
unRet (BlockJSAST xs) = BlockJSAST (map unRet xs)
unRet (RetJSAST x) = ExprStmtJSAST x
unRet x = x
generateTailRecur :: TypedAST -> TypedAST -> State [Int] JSAST
generateTailRecur params body = do
let params' = generateParams params
let body' = generateFuncBody body
recurParamsS <- mapM (\_ -> (\i -> ("_tmp" ++ show i)) <$> gensym) params'
let recurParams = map IdentJSAST recurParamsS
let declare = DefVarsJSAST (["recur", "terminate", "_tmp_ret", "_tmp_is_recur"] ++ recurParamsS)
let recur = FuncLitJSAST recurParams (BlockJSAST (map (\(p1,p2) -> ExprStmtJSAST (AssignJSAST p1 p2)) (zip params' recurParams)))
let isRecur = IdentJSAST "true"
let sliceCall = CallJSAST (MemberJSAST (MemberJSAST (MemberJSAST (IdentJSAST "Array") "prototype") "slice") "call") [IdentJSAST "arguments", NumLitJSAST 0]
let lastCheck = CondJSAST (BinaryJSAST "===" (MemberJSAST (IdentJSAST "arguments") "length") (NumLitJSAST 1)) (IdentJSAST "ret") (NewJSAST (MemberJSAST (IdentJSAST "Binal") "Tuple") [sliceCall])
let terminateBody = BlockJSAST [
ExprStmtJSAST (AssignJSAST (IdentJSAST "_tmp_ret") (IdentJSAST "ret"))]
let terminate = FuncLitJSAST [IdentJSAST "ret"]
(BlockJSAST
[ ExprStmtJSAST
(AssignJSAST (IdentJSAST "_tmp_is_recur") (IdentJSAST "false")),
ExprStmtJSAST
(AssignJSAST (IdentJSAST "ret") lastCheck),
terminateBody])
return
(BlockJSAST
[ declare,
ExprStmtJSAST (AssignJSAST (IdentJSAST "recur") recur),
ExprStmtJSAST (AssignJSAST (IdentJSAST "terminate") terminate),
ExprStmtJSAST (AssignJSAST (IdentJSAST "_tmp_ret") (IdentJSAST "undefined")),
ExprStmtJSAST (AssignJSAST (IdentJSAST "_tmp_is_recur") isRecur),
WhileJSAST
(IdentJSAST "_tmp_is_recur")
(unRet body'),
RetJSAST (IdentJSAST "_tmp_ret")
])
generateExpr :: TypedAST -> State [Int] JSAST
generateExpr (TyLit (SymLit s) _ _) = case s of
"num.add" ->
return (FuncLitJSAST [IdentJSAST "x", IdentJSAST "y"] (BlockJSAST [RetJSAST (BinaryJSAST "+" (IdentJSAST "x") (IdentJSAST "y"))]))
"str.add" ->
return (FuncLitJSAST [IdentJSAST "x", IdentJSAST "y"] (BlockJSAST [RetJSAST (BinaryJSAST "+" (IdentJSAST "x") (IdentJSAST "y"))]))
_ -> return (IdentJSAST (GUtil.toJSSafeSymbol s))
generateExpr (TyLit (StrLit s) _ _) = return (StrLitJSAST s)
generateExpr (TyLit (NumLit i) _ _) = return (NumLitJSAST i)
generateExpr (TyLit (BoolLit True) _ _) = return (IdentJSAST "true")
generateExpr (TyLit (BoolLit False) _ _) = return (IdentJSAST "false")
generateExpr (TyList (TyLit (SymLit "^") _ _:params:body:[]) _ _) = do
let params' = generateParams params
body' <- case body of
(TyList (TyLit (SymLit "loop") _ _:body1:[]) _ _)
-> generateTailRecur params body1
_ -> return (generateFuncBody body)
case params' of
[] -> return (FuncLitJSAST [] body')
_ -> do
let isVarArgs (RecTy _ _) = True
isVarArgs (VarTy _) = True
isVarArgs (EitherTy tys) = any isVarArgs tys
isVarArgs (ListTy []) = False
isVarArgs (ListTy tys) = isVarArgs (last tys)
isVarArgs _ = False
let lastParamTyAST = case params of
TyList xs _ _ -> last xs
x -> x
if isVarArgs (Util.typeof lastParamTyAST)
then do
let initParams = init params'
let lastParam = last params'
let sliceCall = CallJSAST (MemberJSAST (MemberJSAST (MemberJSAST (IdentJSAST "Array") "prototype") "slice") "call") [IdentJSAST "arguments", NumLitJSAST (realToFrac (length initParams))]
let lastCheck = CondJSAST (BinaryJSAST "===" (MemberJSAST (IdentJSAST "arguments") "length") (NumLitJSAST (realToFrac (length params')))) lastParam (NewJSAST (MemberJSAST (IdentJSAST "Binal") "Tuple") [sliceCall])
return (FuncLitJSAST params' (BlockJSAST [ExprStmtJSAST (AssignJSAST lastParam lastCheck), body']))
else do
return (FuncLitJSAST params' body')
generateExpr x@(TyList (TyLit (SymLit "seq") _ _:_) _ _) = do
StmtExprJSAST <$> generateStmt x
generateExpr x@(TyList (TyLit (SymLit "let") _ _:_) _ _) = do
StmtExprJSAST <$> generateStmt x
generateExpr x@(TyList (TyLit (SymLit "letrec") _ _:_) _ _) = do
StmtExprJSAST <$> generateStmt x
generateExpr (TyList (TyLit (SymLit "object") _ _:xs) _ _) = do
let symbols = Maybe.catMaybes (map (\(x,i) -> if even i then Just x else Nothing) (zip xs ([0..] :: [Int])))
let exprs = Maybe.catMaybes (map (\(x,i) -> if odd i then Just x else Nothing) (zip xs ([0..] :: [Int])))
let propertyNames = Maybe.catMaybes (map (\x -> case x of
TyLit (SymLit s) _ _ -> Just s
_ -> Nothing) symbols)
zs <- mapM generateExpr exprs
return (ObjLitJSAST (HashMap.fromList (zip propertyNames zs)))
generateExpr (TyList (TyLit (SymLit ".") _ _:obj:TyLit (SymLit s) _ _:[]) _ _) = do
obj' <- generateExpr obj
return (MemberJSAST obj' s)
generateExpr (TyList (TyLit (SymLit ":=") _ _:x:y:[]) _ _) = do
x' <- generateExpr x
y' <- generateExpr y
return (AssignJSAST x' y')
generateExpr x@(TyList (TyLit (SymLit "assume") _ _:_:[]) _ _) = do
StmtExprJSAST <$> generateStmt x
generateExpr (TyList (TyLit (SymLit "match") ty1 pos:x:xs) _ _) = do
value <- generateExpr x
(isTmpAssign, sym, tmp) <-
case value of
IdentJSAST s -> return (False, s, value)
_ -> do
i <- gensym
let s = "_tmp" ++ show i
return (True, s, IdentJSAST s)
let tmpAssign = AssignJSAST tmp value
zs <- mapM (\y -> generateExpr (TyList [y, TyLit (SymLit sym) (case Util.typeof y of
ArrTy s _ -> s
_ -> Util.typeof x) (Util.whereIs x)] ty1 pos)) xs
let exprAndTypes = zip zs (map Util.typeof xs)
let fs = map (\(expr, ty) -> case ty of
ArrTy ty' _ -> CondJSAST (generateMatching ty' tmp) expr
_ -> CondJSAST (UnaryJSAST "void" (NumLitJSAST 1)) expr) exprAndTypes
let y = foldr id (StmtExprJSAST (ThrowJSAST (NewJSAST (MemberJSAST (IdentJSAST "Binal") "NonExhaustivePatterns") [StrLitJSAST "Non-exhaustive patterns in match"]))) fs
if isTmpAssign
then return (SeqJSAST [tmpAssign, y])
else return y
generateExpr (TyList (TyLit (SymLit "cond") _ _:xs) _ _) = do
values <- mapM generateExpr xs
let conds = Maybe.catMaybes (map (\(x,i) -> if even i then Just x else Nothing) (zip (init values) ([0..] :: [Int])))
let thenClauses = Maybe.catMaybes (map (\(x,i) -> if odd i then Just x else Nothing) (zip values ([0..] :: [Int])))
let elseClause = last values
return (foldr id elseClause (map (uncurry CondJSAST) (zip conds thenClauses)))
generateExpr (TyList (TyLit (SymLit "num.add") _ _:x:y:[]) _ _) = do
BinaryJSAST "+" <$> generateExpr x <*> generateExpr y
generateExpr (TyList (TyLit (SymLit "str.add") _ _:x:y:[]) _ _) = do
BinaryJSAST "+" <$> generateExpr x <*> generateExpr y
generateExpr (TyList (TyLit (SymLit "mutable") _ _:x:[]) _ _) = do
generateExpr x
generateExpr (TyList (TyLit (SymLit "unmutable") _ _:x:[]) _ _) = do
generateExpr x
generateExpr (TyList (f@(TyLit (SymLit "recur") _ _):args) _ _) = do
f' <- generateExpr f
args' <- mapM generateExpr args
return (CallJSAST f' args')
generateExpr (TyList (f:args) _ _) = do
let isVarArgs (RecTy _ _) = True
isVarArgs (VarTy _) = True
isVarArgs (EitherTy tys) = any isVarArgs tys
isVarArgs (ListTy []) = False
isVarArgs (ListTy tys) = isVarArgs (last tys)
isVarArgs _ = False
let godFunction1 this f' initArgs' lastArg' = do
(isTmpAssignF, tmpF) <-
case f' of
IdentJSAST _ -> return (False, f')
MemberJSAST _ _ -> return (False, f')
ComputedMemberJSAST _ _ -> return (False, f')
_ -> do
i <- gensym
return (True, IdentJSAST ("_tmp" ++ show i))
(isTmpAssign, tmp) <-
case lastArg' of
IdentJSAST _ -> return (False ,lastArg')
MemberJSAST _ _ -> return (False, lastArg')
ComputedMemberJSAST _ _ -> return (False, lastArg')
_ -> do
i <- gensym
return (True, IdentJSAST ("_tmp" ++ show i))
let tmpAssignF = AssignJSAST tmpF f'
let tmpAssign = AssignJSAST tmp lastArg'
let normalCall = CallJSAST tmpF (initArgs' ++ [tmp])
let noName = case initArgs' of
[] -> MemberJSAST tmp "xs"
_ -> CallJSAST (MemberJSAST (ArrLitJSAST initArgs') "concat") [MemberJSAST tmp "xs"]
let alternateCall = CallJSAST (MemberJSAST tmpF "apply") ([this] ++ [noName])
let callTest = CondJSAST (BinaryJSAST "instanceof" tmp (MemberJSAST (IdentJSAST "Binal") "Tuple"))
let call = callTest alternateCall normalCall
if isTmpAssignF
then
if isTmpAssign
then return (SeqJSAST [tmpAssignF, tmpAssign, call])
else return (SeqJSAST [tmpAssignF, call])
else
if isTmpAssign
then return (SeqJSAST [tmpAssign, call])
else return call
let godFunction this f' initArgs' lastArg' = do
case Util.typeof (last args) of
ListTy [] -> do
return (CallJSAST f' (initArgs' ++ [lastArg']))
ListTy tys -> do
(isTmpAssign, tmp) <-
case lastArg' of
IdentJSAST _ -> return (False, lastArg')
MemberJSAST _ _ -> return (False, lastArg')
ComputedMemberJSAST _ _ -> return (False, lastArg')
_ -> do
i <- gensym
return (True, IdentJSAST ("_tmp" ++ show i))
let lastAs = map (\i -> ComputedMemberJSAST (MemberJSAST tmp "xs") (NumLitJSAST (realToFrac i))) [0..(length tys - 1)]
if isVarArgs (last tys)
then do
let sliceCall = CallJSAST (MemberJSAST (MemberJSAST tmp "xs") "slice") [NumLitJSAST (realToFrac (length tys - 1))]
let lastGet = ComputedMemberJSAST (MemberJSAST tmp "xs") (NumLitJSAST (realToFrac (length tys - 1)))
let lastCheck = CondJSAST (BinaryJSAST "===" (MemberJSAST (MemberJSAST tmp "xs") "length") (NumLitJSAST (realToFrac (length tys))))
(CallJSAST f' ((initArgs' ++ init lastAs) ++ [lastGet]))
(CallJSAST (MemberJSAST f' "apply") [this, CallJSAST (MemberJSAST (ArrLitJSAST (initArgs' ++ init lastAs)) "concat") [sliceCall]])
if isTmpAssign
then do
let assign = ExprStmtJSAST (AssignJSAST tmp lastArg')
return
(StmtExprJSAST
(BlockJSAST
[
assign,
(ExprStmtJSAST lastCheck)
]))
else do
return lastCheck
else do
if isTmpAssign
then do
let assign = ExprStmtJSAST (AssignJSAST tmp lastArg')
return
(StmtExprJSAST
(BlockJSAST
[
assign,
(ExprStmtJSAST (CallJSAST f' (initArgs' ++ lastAs)))
]))
else do
return (CallJSAST f' (initArgs' ++ lastAs))
_ -> do
if isVarArgs (Util.typeof (last args))
then godFunction1 this f' initArgs' lastArg'
else return (CallJSAST f' (initArgs' ++ [lastArg']))
f' <- generateExpr f
case args of
[] -> return (CallJSAST f' [])
_ -> do
let lastArg = last args
initArgs' <- mapM generateExpr (init args)
lastArg' <- generateExpr lastArg
case f' of
MemberJSAST this name -> do
(isTmpAssignThis, tmpThis) <-
case this of
IdentJSAST _ -> return (False, this)
_ -> do
i <- gensym
return (True, IdentJSAST ("_tmp" ++ show i))
let tmpAssignThis = AssignJSAST tmpThis this
if isTmpAssignThis
then do
x <- godFunction tmpThis (MemberJSAST tmpThis name) initArgs' lastArg'
case x of
SeqJSAST xs -> return (SeqJSAST (tmpAssignThis:xs))
_ -> return (SeqJSAST [tmpAssignThis, x])
else do
godFunction tmpThis f' initArgs' lastArg'
_ -> do
godFunction (IdentJSAST "this") f' initArgs' lastArg'
generateExpr (TyList [] _ _) = undefined
generateMatching :: TyKind -> JSAST -> JSAST
generateMatching StrTy jast = BinaryJSAST "===" (UnaryJSAST "typeof" jast) (StrLitJSAST "string")
generateMatching NumTy jast = BinaryJSAST "===" (UnaryJSAST "typeof" jast) (StrLitJSAST "number")
generateMatching BoolTy jast = BinaryJSAST "===" (UnaryJSAST "typeof" jast) (StrLitJSAST "boolean")
generateMatching (ListTy []) jast = jast
generateMatching (ListTy xs) jast = do
let conds = map (\(x, i) ->
generateMatching x (ComputedMemberJSAST (MemberJSAST jast "xs") (NumLitJSAST (realToFrac i))))
(zip (init xs) ([0..] :: [Int]))
let lastGet = ComputedMemberJSAST (MemberJSAST jast "xs") (NumLitJSAST (realToFrac (length xs - 1)))
let lastCheck = CondJSAST (BinaryJSAST "===" (MemberJSAST (MemberJSAST jast "xs") "length") (NumLitJSAST (realToFrac (length xs)))) lastGet (IdentJSAST "true")
let cond1 = generateMatching (last xs) lastCheck
BinaryJSAST "&&" (BinaryJSAST "instanceof" jast (MemberJSAST (IdentJSAST "Binal") "Tuple")) (foldr (BinaryJSAST "&&") cond1 conds)
generateMatching (VarTy _) jast = jast
generateMatching (RecTy _ _) _ = IdentJSAST "true"
generateMatching (EitherTy xs) jast = do
let isVar (VarTy _) = True
isVar _ = False
if any isVar xs
then jast
else do
let conds = map (\x -> generateMatching x jast) xs
foldr1 (BinaryJSAST "||") conds
generateMatching (ObjectTy _ m) jast
| HashMap.null m = jast
| otherwise = do
let matchers = map (\(key,val) -> (generateMatching val (MemberJSAST jast key))) (HashMap.toList m)
foldr1 (BinaryJSAST "&&") matchers
generateMatching _ _ = ThrowJSAST (NewJSAST (MemberJSAST (IdentJSAST "Binal") "NonExhaustivePatterns") [StrLitJSAST "Non-exhaustive patterns"])
|
pasberth/binal1
|
Language/Binal/Generator/Simple.hs
|
mit
| 22,497
| 0
| 34
| 5,742
| 8,666
| 4,260
| 4,406
| 414
| 50
|
module Y2020.M08.D28.Solution where
{--
Clean words. Today let's make those words clean. What words, you ask? Welp,
one answer is: "alles o' dems wordz!" so, ... yeah: that.
Yesterday, we found we have some weird words in a document we were scanning,
and, also, we found the weird characters in those weird words.
So.
Let's remove the weird characters FROM the document, THEN rescan the document.
Voila, and I hope, we will have a scanned document of clean words.
If only it were that simple (play weird, moody, and forboding music here).
--}
import Control.Monad ((>=>))
import Data.Char (toLower)
import Data.List (sortOn)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Ord
import Data.Set (Set)
import qualified Data.Set as Set
import Y2020.M08.D25.Solution (gutenbergIndex, workingDir, gutenbergTop100Index)
import Y2020.M08.D26.Solution (importBook, Text)
import qualified Data.Bag as Bag
-- a helpful function to import a document to analyze:
study :: FilePath -> IO Text
study = gutenbergIndex >=> importBook . head . Map.toList
encleanifyDoc :: Set Char -> Text -> Text
encleanifyDoc = unfiltered . flip Set.member
where unfiltered f = filter (not . f)
{--
`encleanifyDoc` takes a set of weird characters and removes those weird
characters from a document. N.B.: not all weird characters are weird characters.
What?
From yesterday, we saw that the weird characters for a specific doc were:
{"!\"#$%'()*,-./0123456789:;?@[]\182\187\191"}
But we know that '-' is a word-connector, ... for example: "word-connector"
is a word that has '-' as one of its characters.
[... ya see wha' I dun did wid dat? lol ...]
Are there any other characters that you know and love and want to deweirdify?
Also, the word "don't" but not the words "'A" and "Proposal,'" in the phrase:
"'A Modest Proposal,'" ... so ... simple? easy? straightforward?
Hmmmm.
--}
deweirdify :: Set Char -> Set Char -> Set Char
deweirdify = Set.difference
{--
>>> let weirdos = Set.fromList "!\"#$%'()*,-./0123456789:;?@[]\182\187\191"
>>> deweirdify weirdos (Set.fromList "-'")
fromList "!\"#$%()*,./0123456789:;?@[]\182\187\191"
After you magically encleanify the document, let's encleanify EACH WORD!
*EEK*!
--}
encleanifyWord :: Set Char -> String -> String
-- I ... think (?) if we remove weird characters at the bookends of the word,
-- it's encleanified? Let's give that a try
encleanifyWord weirdos word =
let starting = rmFront weirdos word
tailing = rmFront weirdos(reverse starting)
newWord = reverse tailing
in newWord
rmFront :: Set Char -> String -> String
rmFront = dropWhile . flip Set.member
{--
>>> rmFront weirdos "'A"
"A"
>>> rmFront weirdos "joe"
"joe"
>>> encleanifyWord weirdos "'asffag;;;."
"asffag"
>>> encleanifyWord weirdos "don't"
"don't"
Woot!
After you've encleanified the document and the words of the document, you
can now create a word-count (there's that pesky '-', again, and "there's" has
that pesky inlined '\'' in it, too! ... IT'S TURTLES ALL THE WAY DOWN, I TELL
YA!).
We'll look at the problem of 'stop-words' (often called "STOPWORDS" (caps
intentional)), ... but not today.
--}
cleanDoc :: Set Char -> Text -> [String]
cleanDoc weirds book =
let subweirds = deweirdify weirds (Set.fromList "-'")
cleenBook = encleanifyDoc subweirds book
lowercaseBook = map toLower cleenBook
in map (encleanifyWord weirds) (words lowercaseBook)
{--
>>> let bookwords = cleanDoc weirdos <$> bookus
>>> length <$> bookwords
31530
--}
wordFreq :: [String] -> Map String Int
wordFreq = Bag.asMap . Bag.fromList
-- I mean: you can wordFreq a weirded-out doc, but why?
-- Also ... it ... 'MIGHT'(?) be nice to have all the words be of uniform case?
-- ... but then ... proper nouns? Or is that an issue for Named Entity
-- recognizers to deal with?
{--
>>> let wordus = wordFreq <$> bookwords
>>> take 5 . sortOn (Down . snd) . Map.toList <$> wordus
[("the",1742),("and",1118),("of",778),("a",761),("to",738)]
--}
{-- BONUS -------------------------------------------------------
Thought-experiment:
So, I'm thinking about weirdos being (Char -> Bool) as opposed to Set Char.
There are trade-offs to either approach. What are they? Redeclare the above
functions to use weirdo as one type or the other. What impact does that have
on your approaches and implementations to the problem solution?
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2020/M08/D28/Solution.hs
|
mit
| 4,400
| 0
| 12
| 764
| 462
| 257
| 205
| -1
| -1
|
--dando la altura dar los nodos de esa altura
nivel :: Int -> Arbol a -> [a]
nivel n AV = []
nivel 1 (AB r _ _) = [r]
nivel n (AB r i d)) = (nivel (n-1) i) ++ (nivel (n-1) d)
|
josegury/HaskellFuntions
|
Arboles/ListNodos-NodosAltura.hs
|
mit
| 175
| 1
| 9
| 44
| 112
| 58
| 54
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
module Y2017.M11.D21.Exercise where
{--
Okey-dokey. From yesterday's exercise, we're returning full articles with
key-phrases and ranked and everything!
Boss-man: I don't need full article text, just a summary of the first 140
characters. And remove the special characters. And drop the key-phrases: we
don't need that in the front-end.
Okay, then! Let's do that!
From yesterday's results, do the above. Capice?
--}
import Data.Aeson hiding (Value)
import Data.Aeson.Encode.Pretty
import Data.Time
-- below imports available 1HaskellADay git repository
import Y2017.M11.D01.Exercise -- for special character filtration
import Y2017.M11.D03.Exercise -- for Strength
import Y2017.M11.D06.Exercise hiding (title) -- for Value
import Y2017.M11.D07.Exercise -- for Recommendation
import Y2017.M11.D20.Exercise -- for article sets filtered by keyword search
data Brief =
Summarized { briefIdx :: Integer, date :: Maybe Day,
title, summary :: String,
rank :: Value Strength }
deriving (Eq, Show)
rec2brief :: Recommendation -> Brief
rec2brief rec = undefined
-- also: WATCH OUT for special characters in the title
summarize :: SpecialCharTable -> String -> String
summarize special text = undefined
-- summarize truncates the full text to the first 140 characters, because we're
-- HALF of a tweet. ... yup.
{--
JSON structure is:
article_id
article_date
article_title
article_summary
article_rank
article_view_count
--}
instance ToJSON Brief where
toJSON brief = undefined
{-- BONUS -----------------------------------------------------------------
Write an app that does just like yesterday's app does: returns a set of articles
from a set of keyword filters, but this time returns briefs-as-JSON
--}
main' :: [String] -> IO ()
main' keywords = undefined
|
geophf/1HaskellADay
|
exercises/HAD/Y2017/M11/D21/Exercise.hs
|
mit
| 1,850
| 0
| 9
| 314
| 218
| 136
| 82
| 23
| 1
|
module Test.Smoke
( module Test.Smoke.Assert,
module Test.Smoke.Bless,
module Test.Smoke.Discovery,
module Test.Smoke.Execution,
module Test.Smoke.Plan,
module Test.Smoke.Summary,
module Test.Smoke.Types,
)
where
import Test.Smoke.Assert
import Test.Smoke.Bless
import Test.Smoke.Discovery
import Test.Smoke.Execution
import Test.Smoke.Plan
import Test.Smoke.Summary
import Test.Smoke.Types
|
SamirTalwar/Smoke
|
src/lib/Test/Smoke.hs
|
mit
| 420
| 0
| 5
| 62
| 100
| 69
| 31
| 15
| 0
|
import Data.Char(toUpper)
main =
do
inpStr <- readFile "input.txt"
writeFile "output.txt" (map toUpper inpStr)
|
zhangjiji/real-world-haskell
|
ch7/to-upper-lazy3.hs
|
mit
| 122
| 0
| 9
| 25
| 42
| 20
| 22
| 5
| 1
|
{-# LANGUAGE LambdaCase #-}
module Dama.Fixity.Resolve (resolveFixity) where
import Data.Set (Set)
import qualified Data.Set as S
import Dama.Error
import qualified Dama.Fixity.IR as IR
import Dama.Location
import Dama.Parser.AST (AltList((:+), (:+:)))
import qualified Dama.Parser.AST as AST
resolveFixity :: AST.Program -> Either Error IR.Program
resolveFixity = traverse resolveDecl
resolveDecl :: AST.Decl -> Either Error IR.Decl
resolveDecl (AST.PDecl a b) = IR.PDecl <$> resolveExprR a <*> resolveExpr b
resolveDecl (AST.FDecl f as b) = IR.FDecl (resolveIdent f)
<$> traverse resolveExprR as <*> resolveExpr b
resolveExprR :: AST.ExprR -> Either Error IR.ExprR
resolveExprR (AST.ExprRVar i) = Right . IR.ExprRVar $ resolveIdent i
resolveExprR (AST.ExprRC a) = uncurry IR.ExprRCons <$> resolveExprRC a
resolveExprRC :: AST.ExprRC -> Either Error (IR.Ident, [IR.ExprR])
resolveExprRC (AST.ExprRCons i) = Right (resolveIdent i, [])
resolveExprRC (AST.AppR a b) = (\(i, cs) d -> (i, cs ++ [d])) <$> resolveExprRC a <*> resolveExprR b
resolveExprRC (AST.ChainR c) = resolveChainR c
resolveChainR :: AltList AST.ExprR AST.Ident AST.ExprR -> Either Error (IR.Ident, [IR.ExprR])
resolveChainR = \case
a :+ o :+: b -> resolveExprRC $ convert a o b
a :+ o :+ b :+ cs -> resolveChainR $ AST.ExprRC (convert a o b) :+ cs
where
convert a o = AST.AppR $ AST.AppR (AST.ExprRCons o) a
resolveExpr :: AST.Expr -> Either Error IR.Expr
resolveExpr (AST.ExprIdent i) = Right . IR.ExprIdent $ resolveIdent i
resolveExpr (AST.App a b) = IR.App <$> resolveExpr a <*> resolveExpr b
resolveExpr (AST.Chain c) = resolveChain c
resolveExpr (AST.LeftSection c) = IR.Lam (IR.Ident location varName)
<$> resolveChain (appendEI c)
where
appendEI :: AltList AST.Expr AST.Ident AST.Ident -> AltList AST.Expr AST.Ident AST.Expr
appendEI (a :+: b@(AST.Ident l _)) = a :+ b :+: AST.ExprIdent (AST.Ident l varName)
appendEI (a :+ bs) = a :+ appendII bs
appendII :: AltList AST.Ident AST.Expr AST.Ident -> AltList AST.Ident AST.Expr AST.Expr
appendII (a :+ bs) = a :+ appendEI bs
location = case c of
a :+: _ -> exprLocation a
a :+ _ -> exprLocation a
varName = freshVar $ chainEIVars c
resolveExpr (AST.RightSection c) = IR.Lam (IR.Ident location varName)
<$> resolveChain (AST.ExprIdent (AST.Ident location varName) :+ c)
where
location = case c of
AST.Ident l _ :+: _ -> l
AST.Ident l _ :+ _ -> l
varName = freshVar $ chainIEVars c
resolveChain :: AltList AST.Expr AST.Ident AST.Expr -> Either Error IR.Expr
resolveChain = \case
a :+ o :+: b -> resolveExpr $ convert a o b
a :+ o :+ b :+ cs -> resolveChain $ convert a o b :+ cs
where
convert a o = AST.App $ AST.App (AST.ExprIdent o) a
resolveIdent :: AST.Ident -> IR.Ident
resolveIdent (AST.Ident l s) = IR.Ident l s
exprLocation :: AST.Expr -> Location
exprLocation (AST.ExprIdent (AST.Ident l _)) = l
exprLocation (AST.App a _) = exprLocation a
exprLocation (AST.Chain (a :+ _)) = exprLocation a
exprLocation (AST.LeftSection (a :+ _)) = exprLocation a
exprLocation (AST.LeftSection (a :+: _)) = exprLocation a
exprLocation (AST.RightSection (AST.Ident l _ :+ _)) = l
exprLocation (AST.RightSection (AST.Ident l _ :+: _)) = l
freshVar :: Set String -> String
freshVar vs = head . dropWhile (`S.member` vs) $ ('v' :) . show <$> [0 :: Integer ..]
exprVars :: AST.Expr -> Set String
exprVars (AST.ExprIdent (AST.Ident _ s)) = S.singleton s
exprVars (AST.App a b) = S.union (exprVars a) (exprVars b)
exprVars (AST.Chain c) = chainEEVars c
exprVars (AST.LeftSection c) = chainEIVars c
exprVars (AST.RightSection c) = chainIEVars c
chainEEVars :: AltList AST.Expr AST.Ident AST.Expr -> Set String
chainEEVars (a :+ as) = S.union (exprVars a) (chainIEVars as)
chainEIVars :: AltList AST.Expr AST.Ident AST.Ident -> Set String
chainEIVars (a :+: AST.Ident _ s) = S.insert s $ exprVars a
chainEIVars (a :+ as) = S.union (exprVars a) (chainIIVars as)
chainIEVars :: AltList AST.Ident AST.Expr AST.Expr -> Set String
chainIEVars (AST.Ident _ s :+: a) = S.insert s $ exprVars a
chainIEVars (AST.Ident _ s :+ as) = S.insert s $ chainEEVars as
chainIIVars :: AltList AST.Ident AST.Expr AST.Ident -> Set String
chainIIVars (AST.Ident _ s :+ as) = S.insert s $ chainEIVars as
|
tysonzero/dama
|
src/Dama/Fixity/Resolve.hs
|
mit
| 4,323
| 0
| 13
| 803
| 1,902
| 956
| 946
| 81
| 4
|
{-|
Module : Language.GoLite.Syntax.Typecheck
Description : GoLite syntax definitions with type and source annotations
Copyright : (c) Jacob Errington and Frederic Lafrance, 2016
License : MIT
Maintainer : goto@mail.jerrington.me
Stability : experimental
Defines type synonyms for typechecked syntax trees.
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ViewPatterns #-}
module Language.GoLite.Syntax.Typecheck where
import Language.GoLite.Pretty
import Language.GoLite.Syntax.Precedence
import Language.GoLite.Syntax.SrcAnn
import Language.GoLite.Syntax.Types as Ty
import Language.GoLite.Types
import Control.Applicative ( Const(..) )
import Data.Functor.Foldable
-- | An annotation that consists of both type and source position information.
type TySrcSpan = (Type, SrcSpan)
-- | A type and source position annotated functor value.
type TySrcAnn f a = Ann TySrcSpan f a
-- | A fixed point of a type and source position annotated functor.
type TySrcAnnFix f = Fix (Ann TySrcSpan f)
-- | 'Package' with type and source position annotations.
type TySrcAnnPackage
= Package SrcAnnIdent TySrcAnnTopLevelDecl
-- | 'TopLevelDecl' with type and source position annotations.
type TySrcAnnTopLevelDecl
= TopLevelDecl TySrcAnnDeclaration TySrcAnnFunDecl
-- | 'VarDecl' with type and source position annotations.
type TySrcAnnVarDecl
= VarDecl GlobalId TySrcAnnType TySrcAnnExpr
-- | 'FunDecl' with type and source position annotations.
type TySrcAnnFunDecl
= FunDecl GlobalId TySrcAnnType (Maybe TySrcAnnType) TySrcAnnStatement
type TySrcAnnTypeF
= SrcAnnTypeF
-- | A fixed point of 'SrcAnnTypeF' with type and source position annotations.
type TySrcAnnType
= TySrcAnnFix SrcAnnTypeF
-- | 'StatementF' with type and source position annotations.
type TySrcAnnStatementF
= StatementF
TySrcAnnDeclaration
TySrcAnnExpr
GlobalId
SrcAnnAssignOp
TySrcAnnCaseHead
-- | The fixed point of 'TySrcAnnStatementF' with type and source position
-- annotations.
type TySrcAnnStatement
= SrcAnnFix TySrcAnnStatementF
-- | 'CaseHead' with type and source position annotations.
type TySrcAnnCaseHead
= CaseHead TySrcAnnExpr
-- | 'Declaration' with type and source position annotations.
type TySrcAnnDeclaration
= Declaration TySrcAnnTypeDecl TySrcAnnVarDecl
-- | 'TypeDecl' with type and source position annotations.
type TySrcAnnTypeDecl
= TypeDecl SrcAnnIdent TySrcAnnType
-- | 'ExprF' with type and source position annotations.
type TySrcAnnExprF
= ExprF SrcAnnIdent GlobalId SrcAnnBinaryOp SrcAnnUnaryOp TySrcAnnLiteral TySrcAnnType
-- | The fixed point of 'TySrcAnnExprF' with type and source position
-- annotations.
type TySrcAnnExpr
= TySrcAnnFix TySrcAnnExprF
-- | 'Literal' with type and source position annotations.
type TySrcAnnLiteral
= TySrcAnn Literal ()
-- | '' with type and source position annotations.
type TySrcAnnGoInt
= TySrcAnn (Const GoInt) ()
-- | 'GoFloat' with type and source position annotations.
type TySrcAnnGoFloat
= TySrcAnn (Const GoFloat) ()
-- | 'GoRune' with type and source position annotations.
type TySrcAnnGoRune
= TySrcAnn (Const GoRune) ()
-- | 'GoString' with type and source position annotations.
type TySrcAnnGoString
= TySrcAnn (Const GoString) ()
instance Pretty TySrcAnnType where
pretty = annCata phi where
phi :: (Type, SrcSpan) -> SrcAnnTypeF Doc -> Doc
phi (t, _) e = case e of
SliceType d -> text "[]" <> d <+> pretty (Comment t)
ArrayType n d -> prettyBrackets True (pretty n) <> d <+> pretty (Comment t)
NamedType (bare -> name) -> pretty name <+> pretty (Comment t)
StructType fields ->
text "struct {" $+$ nest indentLevel (
vcat (map (\(bare -> i, d) -> pretty i <+> d) fields)
) $+$
text "}" <+> pretty (Comment t)
instance Pretty TySrcAnnLiteral where
pretty (Ann (ty, _) lit) = case lit of
IntLit x -> pretty x <+> pretty (Comment ty)
FloatLit x -> pretty x <+> pretty (Comment ty)
RuneLit x -> pretty (text $ show x) <+> pretty (Comment ty)
StringLit x -> doubleQuotes (text $ show x) <+> pretty (Comment ty)
instance Pretty TySrcAnnExpr where
pretty = snd . cata f where
f ::
( Pretty selId
, Pretty id
, Pretty bin
, Pretty un
, Pretty lit
, Pretty ty
, HasPrecedence bin
, HasPrecedence un
)
=> TySrcAnn (ExprF selId id bin un lit ty) (Int, Doc)
-> (Int, Doc)
f (Ann (ty, _) e) = case e of
BinaryOp op (dl, l) (dr, r) -> (precedence op,) $
prettyParens (dl <= precedence op) l
<+>
pretty op
<+>
pretty (Comment ty)
<+>
prettyParens (dr <= precedence op) r
UnaryOp op (dp, p) -> (precedence op,) $
pretty op
<>
prettyParens (dp <= precedence op) p
<+>
pretty (Comment ty)
Literal l -> (6,) $ pretty l
Variable x -> (6,) $ pretty x <+> pretty (Comment ty)
Ty.Slice (ep, ex) lo hi up ->
let p q = case q of
Nothing -> empty
Just (_, q') -> q'
in (6,) $
prettyParens (ep <= 6) ex <+>
prettyBrackets True (
p lo <> text ":" <> p hi <> case up of
Nothing -> empty
Just (_, u) ->
text ":" <> u
) <+>
pretty (Comment ty)
Conversion t (_, e') -> (6,) $
pretty t <> prettyParens True e' <+> pretty (Comment ty)
Selector (ps, e') name -> (6,) $
prettyParens (ps <= 6) e' <+> text "." <+> pretty name <+>
pretty (Comment ty)
Index (di, ei) (_, ej) -> (6,) $
prettyParens (di <= 6) ei <+> prettyBrackets True ej <+> pretty (Comment ty)
TypeAssertion (dex, ex) ty' -> (6,) $ cat
[ prettyParens (dex <= 6) ex
, text "."
, prettyParens True (pretty ty')
] <+>
pretty (Comment ty)
Call (fp, fb) mty args -> (6,) $
prettyParens (fp <= 6) (prettyPrec 6 fb) <>
prettyParens True (
case args of
[] -> pretty ty
s -> case mty of
Nothing ->
sep $
punctuate comma $
map (pretty . snd) s
Just t ->
sep $
punctuate comma $
pretty t : map (pretty . snd) s
)
|
djeik/goto
|
libgoto/Language/GoLite/Syntax/Typecheck.hs
|
mit
| 7,289
| 0
| 23
| 2,521
| 1,689
| 880
| 809
| 145
| 0
|
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE CPP #-}
module IHaskell.Test.Eval (testEval) where
import Prelude
import Data.List (stripPrefix)
import Control.Monad (when, forM_)
import Data.IORef (newIORef, modifyIORef, readIORef)
import System.Directory (getTemporaryDirectory, setCurrentDirectory)
import Data.String.Here (hereLit)
import qualified GHC.Paths
import Test.Hspec
import IHaskell.Test.Util (strip)
import IHaskell.Eval.Evaluate (interpret, evaluate)
import IHaskell.Types (EvaluationResult(..), defaultKernelState, KernelState(..),
LintStatus(..), Display(..), extractPlain)
eval :: String -> IO ([Display], String)
eval string = do
outputAccum <- newIORef []
pagerAccum <- newIORef []
let publish evalResult _ =
case evalResult of
IntermediateResult{} -> return ()
FinalResult outs page _ -> do
modifyIORef outputAccum (outs :)
modifyIORef pagerAccum (page :)
noWidgetHandling s _ = return s
getTemporaryDirectory >>= setCurrentDirectory
let state = defaultKernelState { getLintStatus = LintOff }
_ <- interpret GHC.Paths.libdir False False $ const $
IHaskell.Eval.Evaluate.evaluate state string publish noWidgetHandling
out <- readIORef outputAccum
pagerout <- readIORef pagerAccum
return (reverse out, unlines . map extractPlain . reverse $ pagerout)
becomes :: String -> [String] -> IO ()
becomes string expected = evaluationComparing comparison string
where
comparison :: ([Display], String) -> IO ()
comparison (results, _pageOut) = do
when (length results /= length expected) $
expectationFailure $ "Expected result to have " ++ show (length expected)
++ " results. Got " ++ show results
forM_ (zip results expected) $ \(ManyDisplay [Display result], expect) -> case extractPlain result of
"" -> expectationFailure $ "No plain-text output in " ++ show result ++ "\nExpected: " ++ expect
str -> str `shouldBe` expect
evaluationComparing :: (([Display], String) -> IO b) -> String -> IO b
evaluationComparing comparison string = do
let indent (' ':x) = 1 + indent x
indent _ = 0
empty = null . strip
stringLines = filter (not . empty) $ lines string
minIndent = minimum (map indent stringLines)
newString = unlines $ map (drop minIndent) stringLines
eval newString >>= comparison
pages :: String -> [String] -> IO ()
pages string expected = evaluationComparing comparison string
where
comparison (_results, pageOut) =
strip (stripHtml pageOut) `shouldBe` strip (fixQuotes $ unlines expected)
-- A very, very hacky method for removing HTML
stripHtml str = go str
where
go ('<':xs) =
case stripPrefix "script" xs of
Nothing -> go' str
Just s -> dropScriptTag s
go (x:xs) = x : go xs
go [] = []
go' ('>':xs) = go xs
go' (_:xs) = go' xs
go' [] = error $ "Unending bracket html tag in string " ++ str
dropScriptTag str1 =
case stripPrefix "</script>" str1 of
Just s -> go s
Nothing -> dropScriptTag $ tail str
fixQuotes :: String -> String
fixQuotes = id
testEval :: Spec
testEval =
describe "Code Evaluation" $ do
it "gets rid of the test failure with Nix" $
let
throwAway string _ =
evaluationComparing (const $ shouldBe True True) string
in throwAway "True" ["True"]
it "evaluates expressions" $ do
"3" `becomes` ["3"]
"3+5" `becomes` ["8"]
"print 3" `becomes` ["3"]
[hereLit|
let x = 11
z = 10 in
x+z
|] `becomes` ["21"]
it "evaluates flags" $ do
":set -package hello" `becomes` ["Warning: -package not supported yet"]
":set -XNoImplicitPrelude" `becomes` []
it "evaluates multiline expressions" $ do
[hereLit|
import Control.Monad
forM_ [1, 2, 3] $ \x ->
print x
|] `becomes` ["1\n2\n3"]
it "evaluates function declarations silently" $ do
[hereLit|
fun :: [Int] -> Int
fun [] = 3
fun (x:xs) = 10
fun [1, 2]
|] `becomes` ["10"]
it "evaluates data declarations" $ do
[hereLit|
data X = Y Int
| Z String
deriving (Show, Eq)
print [Y 3, Z "No"]
print (Y 3 == Z "No")
|] `becomes` ["[Y 3,Z \"No\"]", "False"]
it "evaluates do blocks in expressions" $ do
[hereLit|
show (show (do
Just 10
Nothing
Just 100))
|] `becomes` ["\"\\\"Nothing\\\"\""]
it "is silent for imports" $ do
"import Control.Monad" `becomes` []
"import qualified Control.Monad" `becomes` []
"import qualified Control.Monad as CM" `becomes` []
"import Control.Monad (when)" `becomes` []
it "prints Unicode characters correctly" $ do
"putStrLn \"Héllö, Üñiço∂e!\"" `becomes` ["Héllö, Üñiço∂e!"]
"putStrLn \"Привет!\"" `becomes` ["Привет!"]
it "prints multiline output correctly" $ do
":! printf \"hello\\nworld\"" `becomes` ["hello\nworld"]
it "evaluates directives" $ do
#if MIN_VERSION_ghc(9,2,0)
-- It's `a` instead of `p`
":typ 3" `becomes` ["3 :: forall {a}. Num a => a"]
#elif MIN_VERSION_ghc(9,0,0)
-- brackets around the type variable
":typ 3" `becomes` ["3 :: forall {p}. Num p => p"]
#elif MIN_VERSION_ghc(8,2,0)
-- It's `p` instead of `t` for some reason
":typ 3" `becomes` ["3 :: forall p. Num p => p"]
#else
":typ 3" `becomes` ["3 :: forall t. Num t => t"]
#endif
":k Maybe" `becomes` ["Maybe :: * -> *"]
#if MIN_VERSION_ghc(8,10,0)
":in String" `pages` ["type String :: *\ntype String = [Char]\n \t-- Defined in \8216GHC.Base\8217"]
#else
":in String" `pages` ["type String = [Char] \t-- Defined in \8216GHC.Base\8217"]
#endif
it "captures stderr" $ do
[hereLit|
import Debug.Trace
trace "test" 5
|] `becomes` ["test\n5"]
it "immediately applies language extensions" $ do
[hereLit|
{-# LANGUAGE RankNTypes #-}
identity :: forall a. a -> a
identity a = a
|] `becomes` []
|
gibiansky/IHaskell
|
src/tests/IHaskell/Test/Eval.hs
|
mit
| 6,460
| 0
| 17
| 1,896
| 1,536
| 807
| 729
| 121
| 7
|
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
module Stratosphere.Values
( Val (..)
, sub
, ValList (..)
, ToRef (..)
) where
import Data.Aeson
import Data.HashMap.Strict (HashMap)
import Data.String (IsString (..))
import Data.Text (Text)
import GHC.Exts (IsList(..))
-- GADTs are cool, but I couldn't get this to work with FromJSON. Now that we
-- don't have FromJSON though, we can revisit this.
-- data Val a where
-- Literal :: a -> Val a
-- Ref :: Text -> Val a
-- If :: Text -> Val a -> Val a -> Val a
-- And :: Val Bool -> Val Bool -> Val Bool
-- Equals :: (Show a, ToJSON a) => Val a -> Val a -> Val Bool
-- Or :: Val Bool -> Val Bool -> Val Bool
-- | This type is a wrapper around any values in a template. A value can be a
-- 'Literal', a 'Ref', or an intrinsic function. See:
-- http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html
data Val a
= Literal a
| Ref Text
| If Text (Val a) (Val a)
| And (Val Bool) (Val Bool)
| Equals (Val a) (Val a)
| Or (Val Bool) (Val Bool)
| GetAtt Text Text
| Base64 (Val Text)
| Join Text (ValList Text)
| Select Integer (ValList a)
| FindInMap (Val a) (Val a) (Val a) -- ^ Map name, top level key, and second level key
| ImportValue Text -- ^ The account-and-region-unique exported name of the value to import
| Sub Text (Maybe (HashMap Text (Val Text))) -- ^ Substitution string and optional map of values
deriving instance (Show a) => Show (Val a)
deriving instance (Eq a) => Eq (Val a)
deriving instance Functor Val
instance (IsString a) => IsString (Val a) where
fromString s = Literal (fromString s)
instance (ToJSON a) => ToJSON (Val a) where
toJSON (Literal v) = toJSON v
toJSON (Ref r) = refToJSON r
toJSON (If i x y) = mkFunc "Fn::If" [toJSON i, toJSON x, toJSON y]
toJSON (And x y) = mkFunc "Fn::And" [toJSON x, toJSON y]
toJSON (Equals x y) = mkFunc "Fn::Equals" [toJSON x, toJSON y]
toJSON (Or x y) = mkFunc "Fn::Or" [toJSON x, toJSON y]
toJSON (GetAtt x y) = mkFunc "Fn::GetAtt" [toJSON x, toJSON y]
toJSON (Base64 v) = object [("Fn::Base64", toJSON v)]
toJSON (Join d vs) = mkFunc "Fn::Join" [toJSON d, toJSON vs]
toJSON (Select i vs) = mkFunc "Fn::Select" [toJSON i, toJSON vs]
toJSON (FindInMap mapName topKey secondKey) =
object [("Fn::FindInMap", toJSON [toJSON mapName, toJSON topKey, toJSON secondKey])]
toJSON (ImportValue t) = importValueToJSON t
toJSON (Sub s Nothing) = object [("Fn::Sub", toJSON s)]
toJSON (Sub s (Just vals)) = mkFunc "Fn::Sub" [toJSON s, Object (toJSON <$> vals)]
-- | Simple version of 'Sub' without a map of values.
sub :: Text -> Val Text
sub s = Sub s Nothing
refToJSON :: Text -> Value
refToJSON ref = object [("Ref", toJSON ref)]
importValueToJSON :: Text -> Value
importValueToJSON ref = object [("Fn::ImportValue", toJSON ref)]
mkFunc :: Text -> [Value] -> Value
mkFunc name args = object [(name, Array $ fromList args)]
-- | 'ValList' is like 'Val', except it is used in place of lists of Vals in
-- templates. For example, if you have a parameter called @SubnetIds@ of type
-- @List<AWS::EC2::Subnet::Id>@ then, you can use @RefList "SubnetIds"@ to
-- reference it.
data ValList a
= ValList [Val a]
| RefList Text
| ImportValueList Text
| Split Text (Val a)
| GetAZs (Val Text)
deriving (Show, Eq)
deriving instance Functor ValList
instance IsList (ValList a) where
type Item (ValList a) = Val a
fromList = ValList
toList (ValList xs) = xs
-- This is obviously not meaningful, but the IsList instance is so useful
-- that I decided to allow it.
toList (RefList _) = []
toList (ImportValueList _) = []
toList (Split _ _) = []
toList (GetAZs _) = []
instance (ToJSON a) => ToJSON (ValList a) where
toJSON (ValList vals) = toJSON vals
toJSON (RefList ref) = refToJSON ref
toJSON (ImportValueList ref) = importValueToJSON ref
toJSON (Split d s) = mkFunc "Fn::Split" [toJSON d, toJSON s]
toJSON (GetAZs r) = object [("Fn::GetAZs", toJSON r)]
-- | Class used to create a 'Ref' from another type.
class ToRef a b where
toRef :: a -> Val b
|
frontrowed/stratosphere
|
library/Stratosphere/Values.hs
|
mit
| 4,297
| 0
| 12
| 862
| 1,355
| 716
| 639
| 84
| 1
|
module Darcs.Util.Download.Request
( UrlRequest(..)
, Cachable(..)
, UrlState(..)
, Q(..)
, readQ
, insertQ
, pushQ
, addUsingPriority
, deleteQ
, elemQ
, emptyQ
, nullQ
, Priority(..)
, ConnectionError(..)
) where
import Data.List ( delete )
import Data.Map ( Map )
import Foreign.C.Types ( CInt )
data Priority = High
| Low
deriving Eq
data Cachable = Cachable
| Uncachable
| MaxAge !CInt
deriving (Show, Eq)
-- | A UrlRequest object contains a url to get, the file into which the
-- contents at the given url should be written, the cachability of this request
-- and the request's priority.
data UrlRequest = UrlRequest
{ url :: String
, file :: FilePath
, cachable :: Cachable
, priority :: Priority
}
type InProgressStatus = ( FilePath -- FilePath to write url contents into
, [FilePath] -- Extra paths to copy complete file into
, Cachable -- Cachable status
)
-- | A UrlState object contains a map of url -> InProgressStatus, a Q of urls
-- waiting to be started, the current pipe length and the unique junk to
-- create unique filenames.
data UrlState = UrlState
{ inProgress :: Map String InProgressStatus
, waitToStart :: Q String
, pipeLength :: Int
, randomJunk :: String
}
-- |Q represents a prioritised queue, with two-tier priority. The left list
-- contains higher priority items than the right list.
data Q a = Q [a] [a]
-- |'readQ' will try and take an element from the Q, preferring elements from
-- the high priority list.
readQ :: Q a -> Maybe (a, Q a)
readQ (Q (x : xs) ys) = return (x, Q xs ys)
readQ (Q [] ys) = do
x : xs <- return $ reverse ys
return (x, Q xs [])
-- | Return a function for adding an element based on the priority.
addUsingPriority :: Priority -> a -> Q a -> Q a
addUsingPriority High = pushQ
addUsingPriority Low = insertQ
-- |'insertQ' inserts a low priority item into a Q.
insertQ :: a -> Q a -> Q a
insertQ y (Q xs ys) = Q xs (y:ys)
-- |'pushQ' inserts a high priority item into a Q.
pushQ :: a -> Q a -> Q a
pushQ x (Q xs ys) = Q (x:xs) ys
-- |'deleteQ' removes any instances of a given element from the Q.
deleteQ :: Eq a => a -> Q a -> Q a
deleteQ x (Q xs ys) = Q (delete x xs) (delete x ys)
-- |'deleteQ' checks for membership in a Q.
elemQ :: Eq a => a -> Q a -> Bool
elemQ x (Q xs ys) = x `elem` xs || x `elem` ys
-- |'emptyQ' is an empty Q.
emptyQ :: Q a
emptyQ = Q [] []
-- |'nullQ' checks if the Q contains no items.
nullQ :: Q a -> Bool
nullQ (Q [] []) = True
nullQ _ = False
-- | Data type to represent a connection error.
-- The following are the codes from libcurl
-- which map to each of the constructors:
-- * 6 -> CouldNotResolveHost : The remote host was not resolved.
-- * 7 -> CouldNotConnectToServer : Failed to connect() to host or proxy.
-- * 28 -> OperationTimeout: the specified time-out period was reached.
data ConnectionError = CouldNotResolveHost
| CouldNotConnectToServer
| OperationTimeout
deriving (Eq, Read, Show)
|
DavidAlphaFox/darcs
|
src/Darcs/Util/Download/Request.hs
|
gpl-2.0
| 3,231
| 0
| 10
| 904
| 748
| 421
| 327
| 66
| 1
|
mytake :: Int -> [a] -> [a]
mytake _ [] = []
mytake n _
| n <= 0 = []
mytake n (x:xs) = x : mytake (n-1) xs
main = do
let list = mytake 3 [3, 1, 3, 4]
print list
|
demo-code/hs
|
mytake.hs
|
gpl-2.0
| 169
| 0
| 11
| 51
| 126
| 64
| 62
| 8
| 1
|
-- Non-deterministically generate a new bit when asked to.
module T where
import Tests.KesterelBasis
bitP, nextBitP :: ProbeID
bitP = "bit"
nextBitP = "next bit"
input_process (bit, nextBit) =
-- loopE (((sustainE bit `nondetE` haltE) `weak_abortE` nextBit) >>> pauseE)
loopE ((r True `nondetE` r False) >>> pauseE)
where
r s = loopE_ $ \e ->
(if s then emitE bit else nothingE)
>>> presentE nextBit (throwE e) nothingE
>>> pauseE
top = signalE $ \s@(bit, nextBit) -> probeSigE bitP bit >>> probeSigE nextBitP nextBit >>>
( loopE ((nothingE `nondetE` emitE nextBit) >>> pauseE)
||||
input_process s )
system = unitA >>> runE top
Just (m, (_, ())) = isConstructive system
ctlM = mkCTLModel m
-- The input process behaves.
test_input_process_new = isOK (mc ctlM (ag (probe nextBitP --> (ex (probe bitP) /\ ex (neg (probe bitP))))))
test_input_process_hold = isOK (mc ctlM (ag (neg (probe nextBitP) --> (probe bitP <-> ax (probe bitP)))))
-- ce = showCounterExample ctlM (ag (probe nextBitP --> (ex (probe bitP) /\ ex (neg (probe bitP)))))
-- The sender always eventually asks (and not) for more bits.
test_input_process_live_more = isOK (mc ctlM (ag (ef (probe nextBitP))))
test_input_process_live_stop = isOK (mc ctlM (ag (ef (neg (probe nextBitP)))))
|
peteg/ADHOC
|
Tests/08_Kesterel/140_nondet_bits.hs
|
gpl-2.0
| 1,302
| 0
| 18
| 250
| 437
| 230
| 207
| 22
| 2
|
import Control.Monad
import Language.Haskell.Exts hiding (Type(..), Lambda, Case)
import qualified Language.Haskell.Exts as E
import System.Environment
data Term = Function String Expression deriving (Eq, Show)
data Expression = Variable_e String
| Lambda String Expression
| Expression :$ Expression
| Case Expression [(Pattern, Expression)]
| Constant Int
| Str String
| Boolean Bool
| Expression Operator Expression Expression
deriving (Eq, Show)
data Pattern = Constructor String [String]
| Variable_p String
| WildCard
deriving (Eq, Show)
data Operator = Add
| Subtract
| Multiply
| Divide
deriving (Eq, Show)
data Type = A Atomic | Type :-> Type
data Atomic = BoolTy | IntTy | ListTy Atomic
transform :: Module -> Maybe [Term]
transform (Module _ _ _ _ _ _ ds) = (flip3 foldM) ds [] $ \a d -> do
t <- transformDeclaration d
return (t:a)
transformDeclaration :: Decl -> Maybe Term
transformDeclaration (FunBind [(Match _ (Ident i) vs _ (UnGuardedRhs b) _)]) = do
b' <- transformExpression b
(v':vs') <- (flip3 foldM) vs [] $ \a v -> case v of
(PVar (Ident i)) -> return (i:a)
_ -> Nothing
return (Function i (foldr (\v a -> Lambda v a) (Lambda v' b') (reverse vs')))
transformDeclaration (PatBind _ (PVar (Ident i)) (UnGuardedRhs b) _) = do
b' <- transformExpression b
return (Function i b')
transformDeclaration _ = Nothing
transformExpression :: Exp -> Maybe Expression
transformExpression (App p q) = do
p' <- transformExpression p
q' <- transformExpression q
return (p' :$ q')
transformExpression (E.Case e ps) = do
e' <- transformExpression e
ps' <- (flip3 foldM) ps [] $ \a (Alt _ p b _) -> do
b' <- case b of
(UnGuardedRhs b') -> transformExpression b'
p' <- transformPattern p
return ((p', b'):a)
return (Case e' ps')
transformExpression (Con (UnQual (Ident i))) = return (Variable_e i)
transformExpression (InfixApp p (QVarOp (UnQual (Symbol o))) q) = do
p' <- transformExpression p
q' <- transformExpression q
o' <- case o of
"+" -> return Add
"-" -> return Subtract
"*" -> return Multiply
"/" -> return Divide
_ -> Nothing
return (Expression o' p' q')
transformExpression (E.Lambda _ vs b) = do
b' <- transformExpression b
(v':vs') <- (flip3 foldM) vs [] $ \a v -> case v of
(PVar (Ident i)) -> return (i:a)
_ -> Nothing
return (foldr (\v a -> Lambda v a) (Lambda v' b') (reverse vs'))
transformExpression (Lit (Int i)) = return (Constant (fromIntegral i))
transformExpression (Lit (String s)) = return (Str s)
transformExpression (Paren e) = do
e' <- transformExpression e
return e'
transformExpression (Var (UnQual (Ident i))) = return (Variable_e i)
transformExpression _ = Nothing
transformPattern :: Pat -> Maybe Pattern
transformPattern (PVar (Ident i)) = return (Variable_p i)
transformPattern (PApp (UnQual (Ident i)) as) = do
as' <- (flip3 foldM) as [] $ \a p -> case p of
(PVar (Ident i)) -> return (i:a)
_ -> Nothing
return (Constructor i as')
transformPattern (PParen p) = transformPattern p
transformPattern PWildCard = return WildCard
transformPattern _ = Nothing
flip3 f a b c = f c b a
|
orchid-hybrid/lotus
|
Lotus.hs
|
gpl-2.0
| 3,478
| 0
| 17
| 964
| 1,441
| 717
| 724
| 88
| 6
|
module CountEntries where
import System.Directory(doesDirectoryExist, getDirectoryContents)
import System.FilePath((</>))
import Control.Monad (forM, liftM)
notDots :: FilePath -> Bool
notDots = \s -> s /="." && s /= ".."
listDirectory :: FilePath -> IO [String]
listDirectory = liftM (filter notDots) . getDirectoryContents
listDirectoryAlt :: FilePath -> IO [String]
listDirectoryAlt = \m -> let d = getDirectoryContents m in
d >>= \s -> return (filter notDots s)
listDirectoryAlt2 :: FilePath -> IO [String]
listDirectoryAlt2 = \fp -> (filter notDots) `liftM` (getDirectoryContents fp)
|
dservgun/haskell_test_code
|
src/CountEntries.hs
|
gpl-2.0
| 677
| 0
| 12
| 167
| 208
| 115
| 93
| 13
| 1
|
{- findAll searchWord readfileString rowList wordList
PURPOSE:
PRE: True ?
POST:
VARIANT: Length of readfileString
EXAMPLES:
-}
findAll :: [Char] -> [String] -> [String] -> [String] -> [String]
findAll word [] _ wList | wList == [] = ["No match found"]
| wList /= [] = reverse (wList)
findAll word [string] rList wList | word == string = reverse (("On Row "++(show ((length rList)+1))):wList)
| word /= string && wList /= [] = reverse (wList)
| word /= string && wList == [] = ["No match found"]
findAll word (string:xs) rList wList
| word == string = findAll word xs rList (("On Row "++(show ((length rList)+1))):wList)
| word /= string && string == "\n" = findAll word xs ("\n":rList) wList
| word /= string && string /= "\n" = findAll word xs rList wList
{- findFirst searchWord readfileString rowList
PURPOSE:
PRE: True ?
POST:
VARIANT: Length of readfileString
EXAMPLES:
-}
findFirst :: [Char] -> [String] -> [String] -> [Char]
findFirst word [] _ = "No match found"
findFirst word [string] rList | word == string = "On Row "++(show ((length rList)+1)
| word /= string = "No match found"
findFirst word (string:xs) rList | word == string = "On Row "++(show ((length rList)+1))
| word /= string && string == "\n" = findFirst word xs ("\n":rList)
| word /= string && string /= "\n" = findFirst word xs rList
{- findX searchWord number readfileString rowList wordList
PURPOSE:
PRE: Number may not be negative
POST:
VARIANT: Length of readfileString
EXAMPLES:
-}
findX :: [Char] -> Integer -> [String] -> [String] -> [String] -> [String]
findX word _ [] _ wList | wList == [] = ["No match found"]
| wList /= [] = wList
findX word x [string] rList wList
| word == string && x > 0 = (reverse ("On Row "++(show ((length rList)+1))):wList)
| word == string && x == 0 = reverse (wList)
| word /= string && wList /= [] = reverse (wList)
| word /= string && wList == [] = ["No match found"]
findX word x (string:xs) rList wList
| word == string && x > 0 = findX word (x-1) xs rList (("On Row "++(show ((length rList)+1))):wList)
| word == string && x == 0 = reverse (wList)
| word /= string && x == 0 = reverse (wList)
| word /= string && string == "\n" = findX word x xs ("\n":rList) wList
| word /= string && string /= "\n" = findX word x xs rList wList
|
Notogora/magictext
|
find.hs
|
gpl-2.0
| 2,450
| 34
| 16
| 615
| 985
| 522
| 463
| -1
| -1
|
-- mt - Prints a multiplication table.
-- Written by Colin Woodbury <colingw@gmail.com>
-- Usage: mt <number>
import System.Environment (getArgs)
import Text.Printf (printf)
import Data.Char (isDigit)
main :: IO ()
main = do
args <- getArgs
let lim = processArgs args
putStrLn $ makeTable lim
-- A default value of `10` is given for improper input.
processArgs :: [String] -> Int
processArgs [] = 10
processArgs (n:_) | and $ map isDigit n = read n
| otherwise = 10
makeTable :: Int -> String
makeTable lim = topRow ++ "\n" ++ border ++ "\n" ++ table
where topRow = renderRow "" 1 lim
border = replicate (read pad + 2 + (lim * (read pad + 1))) '-'
table = concat $ map (\m -> renderRow (show m) m lim ++ "\n") [1..lim]
pad = getPad lim
renderRow :: String -> Int -> Int -> String
renderRow label mult lim = printf ("%" ++ pad ++ "s |%s") label renderedRow
where renderedRow = concat $ map renderNum [1..lim]
renderNum n = printf (" %" ++ pad ++ "d") (n * mult) :: String
pad = getPad lim
getPad :: Int -> String
getPad lim = show . length . show $ lim * lim
|
fosskers/mt
|
mt.hs
|
gpl-3.0
| 1,148
| 13
| 13
| 295
| 430
| 219
| 211
| 25
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.