code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
{-# LANGUAGE FlexibleInstances #-}
{- |
Module : Language.Egison.EvalState
Licence : MIT
This module defines the state during the evaluation.
-}
module Language.Egison.EvalState
( EvalState(..)
, initialEvalState
, MonadEval(..)
, mLabelFuncName
) where
import Control.Monad.Except
import Control.Monad.Trans.State.Strict
import Language.Egison.IExpr
newtype EvalState = EvalState
-- Names of called functions for improved error message
{ funcNameStack :: [Var]
}
initialEvalState :: EvalState
initialEvalState = EvalState { funcNameStack = [] }
class (Applicative m, Monad m) => MonadEval m where
pushFuncName :: Var -> m ()
topFuncName :: m Var
popFuncName :: m ()
getFuncNameStack :: m [Var]
instance Monad m => MonadEval (StateT EvalState m) where
pushFuncName name = do
st <- get
put $ st { funcNameStack = name : funcNameStack st }
return ()
topFuncName = head . funcNameStack <$> get
popFuncName = do
st <- get
put $ st { funcNameStack = tail $ funcNameStack st }
return ()
getFuncNameStack = funcNameStack <$> get
instance (MonadEval m) => MonadEval (ExceptT e m) where
pushFuncName name = lift $ pushFuncName name
topFuncName = lift topFuncName
popFuncName = lift popFuncName
getFuncNameStack = lift getFuncNameStack
mLabelFuncName :: MonadEval m => Maybe Var -> m a -> m a
mLabelFuncName Nothing m = m
mLabelFuncName (Just name) m = do
pushFuncName name
v <- m
popFuncName
return v
|
egison/egison
|
hs-src/Language/Egison/EvalState.hs
|
Haskell
|
mit
| 1,515
|
{-# LANGUAGE CPP #-}
module GHCJS.DOM.Element (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.Element
#else
module Graphics.UI.Gtk.WebKit.DOM.Element
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.Element
#else
import Graphics.UI.Gtk.WebKit.DOM.Element
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/Element.hs
|
Haskell
|
mit
| 420
|
module GHCJS.Utils where
import GHCJS.Foreign
import GHCJS.Types
foreign import javascript unsafe
"console.log($1)" consoleLog :: JSRef a -> IO ()
foreign import javascript unsafe
"(function() { return this; })()" this :: IO (JSRef a)
|
CRogers/stack-ide-atom
|
haskell/src/GHCJS/Utils.hs
|
Haskell
|
mit
| 242
|
module Main where
import Data.Monoid
import Language.LambdaCalculus
maybeFromEither :: Either x y -> Maybe y
maybeFromEither (Left _) = Nothing
maybeFromEither (Right x) = Just x
-- | Read a lambda calclus example from file
--
openExample :: String -> IO (Maybe Term)
openExample ex = do
contents <- readFile $ "samples/" ++ ex ++ ".lc"
return $ maybeFromEither $ parseTerm contents
|
owainlewis/lambda-calculus
|
src/Main.hs
|
Haskell
|
mit
| 413
|
{-# LANGUAGE MultiParamTypeClasses, DataKinds, KindSignatures, TypeOperators, FlexibleInstances, OverlappingInstances, TypeSynonymInstances, IncoherentInstances #-}
module Math.Matrix where
import Math.Vec hiding (r,g,b,a,x,y,z,w)
import qualified Math.Vec as V (r,g,b,a,x,y,z,w)
import GHC.TypeLits
type Matrix n m a = Vec n (Vec m a)
-- composition
consx :: Vec n a -> Matrix n m a -> Matrix n (m+1) a
consx v m = vmap (uncurry $ cons) $ vzip v m
snocx :: Matrix n m a -> Vec n a -> Matrix n (m+1) a
snocx m v = vmap (uncurry $ snoc) $ vzip m v
-- indexing
-- shorthand
infixr 5 |->
(|->) :: Matrix m n a -> (Int, Int) -> a
(|->) m (r,c) = (m ! r) ! c
-- row vector
row :: Matrix m n a -> Int -> Vec n a
row mat r = mat ! r
infixr 5 <->
(<->) :: Matrix m n a -> Int -> Vec n a
(<->) = row
-- col vector
col :: Matrix m n a -> Int -> Vec m a
col mat c = vmap (!c) mat
infixr 5 <|>
(<|>) :: Matrix m n a -> Int -> Vec m a
(<|>) = col
dimy :: Matrix m n a -> Int
dimy = dim
dimx :: Matrix m n a -> Int
dimx mat = dim $ mat <-> 0
-- commonly used matrix types
type Mat3 = Matrix 3 3 Double
mat3 :: Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Mat3
mat3 a b c d e f g h i
= (a & b & c & nil)
& (d & e & f & nil)
& (g & h & i & nil)
& nil
type Mat4 = Matrix 4 4 Double
mat4 :: Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Mat4
mat4 a b c d e f g h i j k l m n o p
= (a & b & c & d & nil)
& (e & f & g & h & nil)
& (i & j & k & l & nil)
& (m & n & o & p & nil)
& nil
type Mat3f = Matrix 3 3 Float
mat3f :: Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Mat3f
mat3f a b c d e f g h i
= (a & b & c & nil)
& (d & e & f & nil)
& (g & h & i & nil)
& nil
type Mat4f = Matrix 4 4 Float
mat4f :: Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Mat4f
mat4f a b c d e f g h i j k l m n o p
= (a & b & c & d & nil)
& (e & f & g & h & nil)
& (i & j & k & l & nil)
& (m & n & o & p & nil)
& nil
class HomogeneousMatAccessors (n::Nat) where
tx :: Matrix n n a -> a
ty :: Matrix n n a -> a
tz :: Matrix n n a -> a
sx :: Matrix n n a -> a
sy :: Matrix n n a -> a
sz :: Matrix n n a -> a
instance HomogeneousMatAccessors 3 where
tx mat = mat |-> (0,2)
ty mat = mat |-> (1,2)
tz = error "tz undefined for Mat33!"
sx mat = mat |-> (0,0)
sy mat = mat |-> (1,1)
sz = error "scale z undefined for Mat33!"
instance HomogeneousMatAccessors 4 where
tx mat = mat |-> (0,3)
ty mat = mat |-> (1,3)
tz mat = mat |-> (2,3)
sx mat = mat |-> (0,0)
sy mat = mat |-> (1,1)
sz mat = mat |-> (2,2)
instance Num a => ScalarOps (Matrix n m a) a where
s *** m = vmap (s ***) m
instance Fractional a => ScalarFracOps (Matrix n m a) a where
m /// s = vmap (/// s) m
-- common operations
matmul :: Num a => Matrix n m a -> Matrix m p a -> Matrix n p a
matmul a b = vector $ map rowc [0..(dimy a - 1)] where
rowc r = vector $ map (\c -> dot ar (b <|> c)) [0..(dimx b - 1)] where
ar = a <-> r
vecmat :: Num a => Vec n a -> Matrix n m a -> Vec m a
vecmat v m = vector $ map (\c -> dot v (m <|> c)) [0..(dimx m - 1)]
matvec :: Num a => Matrix n m a -> Vec m a -> Vec n a
matvec m v = vector $ map (\r -> dot (m <-> r) v) [0..(dimy m - 1)]
identity :: Num a => Int -> Matrix n n a
identity n = vector $ map row' [0..(n-1)] where
row' i = vector $ replicate i 0 ++ 1:replicate (n-i-1) 0
tensor :: Num a => Vec n a -> Matrix n n a
tensor v = vector $ map row' [0..(dim v - 1)] where
row' i = vmap (* (v ! i)) v
-- typesafe id constructors
identity4 :: Num a => Matrix 4 4 a
identity4 = identity 4
identity3 :: Num a => Matrix 3 3 a
identity3 = identity 3
transpose :: Matrix n m a -> Matrix m n a
transpose m = vector $ map (m <|>) [0..(dimx m - 1)]
-- Doolittle LU decomposition
lu :: Fractional a => Matrix n n a -> (Matrix n n a, Matrix n n a) -- first is L, second is U
lu m = if dim m == dimy m then doolittle (identity $ dim m) m 0 else error "matrix not square" where
mdim = dim m
doolittle l a n
| n == mdim-1 = (l,a)
| otherwise = doolittle l' a' (n+1) where
l' = matmul l ln' -- ln' is inverse of ln
a' = matmul ln a
ln = vector (map id' [0..n] ++ map lr' [(n+1)..(mdim-1)]) where
lr' i = vector $ replicate n 0 ++ [-(ai' i)] ++ replicate (i-n-1) 0 ++ 1:replicate (mdim-i-1) 0
ln' = vector (map id' [0..n] ++ map lr' [(n+1)..(mdim-1)]) where
lr' i = vector $ replicate n 0 ++ [ai' i] ++ replicate (i-n-1) 0 ++ 1:replicate (mdim-i-1) 0
id' i = vector $ replicate i 0 ++ 1:replicate (mdim-i-1) 0
ai' i = (a |-> (i,n)) / (a |-> (n,n))
det :: Fractional a => Matrix n n a -> a
det m
| dim m == 1 = m |-> (0,0)
| dim m == 2 = let a = m |-> (0,0)
b = m |-> (0,1)
c = m |-> (1,0)
d = m |-> (1,1)
in a*d - b*c
| dim m == 3 = let a = m |-> (0,0)
b = m |-> (0,1)
c = m |-> (0,2)
d = m |-> (1,0)
e = m |-> (1,1)
f = m |-> (1,2)
g = m |-> (2,0)
h = m |-> (2,1)
i = m |-> (2,2)
in a*e*i + b*f*g + c*d*h - c*e*g - b*d*i - a*f*h
| otherwise = tridet u where
(_,u) = lu m
tridet mat = foldl (*) 1 $ map (\i -> mat |-> (i,i)) [0..(dim mat - 1)]
-- solve Ax = B for x using forward substitution, where A is an nxn matrix, B is a 1xn vector, and return value x is a 1xn vector
-- assumes A is a lower triangular matrix
forwardsub :: Fractional a => Matrix n n a -> Vec n a -> Vec n a
forwardsub a b = fs a b 0 where
fs m v n
| n == dim v = v
| otherwise = fs m v' (n+1) where
v' = v // [(n, ((v ! n) - fsum) / m_nn)] where
fsum = sum $ map (\i -> (m |-> (n,i)) * (v ! i)) [0..(n - 1)] -- m_n0 * v_0 + m_n1 * v_1 ... + m_nn-1 * v_n-1
m_nn = m |-> (n,n)
-- solve Ax = B for x using backward substitution, where A is an nxn matrix, B is a 1xn vector, and return value x is a 1xn vector
-- assumes A is an upper triangular matrix
backsub :: Fractional a => Matrix n n a -> Vec n a -> Vec n a
backsub a b = bs a b (dim b - 1) where
bs m v n
| n == -1 = v
| otherwise = bs m v' (n-1) where
v' = v // [(n, ((v ! n) - fsum) / m_nn)] where
fsum = sum $ map (\i -> (m |-> (n,i)) * (v ! i)) [(n + 1)..(dim v - 1)]
m_nn = m |-> (n,n)
-- returns the trace of a matrix
tr :: Num a => Matrix n n a -> a
tr m
| dimx m /= dimy m = error "matrix not square"
| otherwise = sum $ map (\i -> m |-> (i,i)) [0..(dim m - 1)]
inv :: Fractional a => Matrix n n a -> Matrix n n a
inv m
| dimx m /= dimy m = error "matrix not square"
| dim m == 2 = let d = det m
t = tr m
in (1/d) *** (t *** identity 2 - m)
| dim m == 3 = let d = det m
t = tr m
t' = tr (matmul m m)
mm = matmul m m
in (1/d) *** ((0.5 * (t*t - t')) *** identity 3 - t *** m + mm)
| dim m == 4 = let d = det m
t = tr m
m2 = matmul m m
m3 = matmul m m2
t2 = tr m2
t3 = tr m3
a = (1/6) * ((t*t*t) - (3*t*t2) + (2*t3))
b = (1/2) * ((t*t) - t2)
in (1/d) *** (a *** identity 4 - b *** m + t *** m2 - m3)
| otherwise = transpose $ vector $ map col' [0..(dim m - 1)] where
col' i = backsub u $ forwardsub l (idm <|> i) where
(l,u) = lu m
idm = identity $ dim m
-- graphics utilities
xaxis = vec3 1 0 0
yaxis = vec3 0 1 0
zaxis = vec3 0 0 1
rotationmat :: Vec3 -> Double -> Mat4
rotationmat axis angle = make44 $ cos r *** identity3 + sin r *** crossmat + (1 - cos r) *** tensor axis
where r = angle * pi / 180
crossmat = mat3 0 (-z) y
z 0 (-x)
(-y) x 0
where
x = V.x axis
y = V.y axis
z = V.z axis
make44 m = snocx (snoc m (vec3 0 0 0)) (vec4 0 0 0 1)
scalemat :: Double -> Double -> Double -> Mat4
scalemat x y z = mat4 x 0 0 0
0 y 0 0
0 0 z 0
0 0 0 1
translationmat :: Vec3 -> Mat4
translationmat v = mat4 1 0 0 (V.x v)
0 1 0 (V.y v)
0 0 1 (V.z v)
0 0 0 1
-- debugging helpers
instance (Show a) => Show (Matrix n m a) where
show m = concatMap showRow [0..(dimy m - 1)] where
showRow r = concatMap formatRowValueAtColumn [0..(dimx m - 1)] where
formatRowValueAtColumn c
| c == dimx m - 1 && r == dimy m - 1 = show (m |-> (r,c))
| c == dimx m - 1 = show (m |-> (r,c)) ++ "\n"
| otherwise = show (m |-> (r,c)) ++ "\t"
|
davidyu/Slowpoke
|
hs/src/Math/matrix.hs
|
Haskell
|
mit
| 9,345
|
{-# LANGUAGE LambdaCase #-}
import Brainhack.Evaluator (emptyMachine, eval, runBrainState)
import Brainhack.Parser (parse)
import Control.Exception.Safe (SomeException)
import Control.Monad (forM)
import Data.Bifunctor (second)
import Data.List (nub)
import Data.Tuple.Extra ((&&&))
import NicoLang.Parser.Items (NicoToken(NicoToken))
import System.EasyFile (getDirectoryContents)
import System.IO.Silently (capture_)
import Test.Tasty (TestTree)
import Test.Tasty.HUnit ((@?=))
import Text.Printf (printf)
import qualified Data.Text as T
import qualified NicoLangTest.ParserTest as PT
import qualified Test.Tasty as Test (defaultMain, testGroup)
import qualified Test.Tasty.HUnit as Test (testCase, assertFailure)
main :: IO ()
main = do
inOutTests <- getInOutTests
Test.defaultMain $
Test.testGroup "nico-lang test" $
[ PT.test
, inOutTests
]
getInOutTests :: IO TestTree
getInOutTests = do
inOutPairs <- map inOutFiles . testNames . filter (`notElem` [".", ".."]) <$> getDirectoryContents "test/in-out"
inOutPairs' <- sequence . map (twiceMapM readFile) $ inOutPairs
-- `init` removes the line break of the tail
let inOutPairs'' = map (second init) inOutPairs'
resultPairs <- forM inOutPairs'' $ firstMapM $ \source -> do
case parse . NicoToken . T.pack $ source of
Left e -> return . Left $ "Parse error: " ++ show (e :: SomeException)
Right a -> return . Right =<< (capture_ . flip runBrainState emptyMachine $ eval a)
return $ Test.testGroup "in-out matching test" $
flip map resultPairs $ \case
(Left e, outData) -> Test.testCase (show outData) $ Test.assertFailure e
(Right inData, outData) -> Test.testCase (show outData) $ inData @?= outData
where
testNames :: [FilePath] -> [FilePath]
testNames = nub . map (takeWhile (/='.'))
inOutFiles :: FilePath -> (FilePath, FilePath)
inOutFiles = (printf "test/in-out/%s.nico") &&& (printf "test/in-out/%s.out")
twiceMapM :: Monad m => (a -> m b) -> (a, a) -> m (b, b)
twiceMapM f (x, y) = do
x' <- f x
y' <- f y
return (x', y')
firstMapM :: Monad m => (a -> m b) -> (a, x) -> m (b, x)
firstMapM f (x, y) = do
x' <- f x
return (x', y)
|
aiya000/nico-lang
|
test/Spec.hs
|
Haskell
|
mit
| 2,199
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE TypeApplications #-}
{-# OPTIONS_GHC -O0 #-}
{-# OPTIONS_GHC -fomit-interface-pragmas #-}
module ZoomHub.Storage.PostgreSQL.GetRecent
( getRecent,
)
where
import Data.Binary (Word64)
import Squeal.PostgreSQL
( MonadPQ,
Only (Only),
SortExpression (Desc),
getRows,
limit,
orderBy,
param,
runQueryParams,
where_,
(!),
(&),
(./=),
)
import UnliftIO (MonadUnliftIO)
import ZoomHub.Storage.PostgreSQL.Internal
( contentImageRowToContent,
selectContentBy,
)
import ZoomHub.Storage.PostgreSQL.Schema (Schemas)
import ZoomHub.Types.Content (Content (..))
import ZoomHub.Types.ContentState (ContentState (Active))
getRecent :: (MonadUnliftIO m, MonadPQ Schemas m) => Word64 -> m [Content]
getRecent numItems = do
result <-
runQueryParams
( selectContentBy
( \table ->
table
& where_ ((#content ! #state) ./= param @1) -- TODO: Remove dummy clause
& orderBy [#content ! #initialized_at & Desc]
& limit numItems
)
)
(Only Active)
contentRows <- getRows result
return $ contentImageRowToContent <$> contentRows
|
zoomhub/zoomhub
|
src/ZoomHub/Storage/PostgreSQL/GetRecent.hs
|
Haskell
|
mit
| 1,281
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SQLResultSetRowList
(js_item, item, js_getLength, getLength, SQLResultSetRowList,
castToSQLResultSetRowList, gTypeSQLResultSetRowList)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"item\"]($2)" js_item ::
SQLResultSetRowList -> Word -> IO JSVal
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLResultSetRowList.item Mozilla SQLResultSetRowList.item documentation>
item :: (MonadIO m) => SQLResultSetRowList -> Word -> m JSVal
item self index = liftIO (js_item (self) index)
foreign import javascript unsafe "$1[\"length\"]" js_getLength ::
SQLResultSetRowList -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLResultSetRowList.length Mozilla SQLResultSetRowList.length documentation>
getLength :: (MonadIO m) => SQLResultSetRowList -> m Word
getLength self = liftIO (js_getLength (self))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SQLResultSetRowList.hs
|
Haskell
|
mit
| 1,715
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
import Prelude hiding (Functor, fmap, id)
class (Category c, Category d) => Functor c d t where
fmap :: c a b -> d (t a) (t b)
type Hask = (->)
instance Category Hask where
id x = x
(f . g) x = f (g x)
instance Functor Hask Hask [] where
fmap f [] = []
fmap f (x:xs) = f x : (fmap f xs)
|
riwsky/wiwinwlh
|
src/functors.hs
|
Haskell
|
mit
| 379
|
module TemplateGen.TemplateContext (
TemplateContext(..)
, mkTemplateContext
) where
import qualified TemplateGen.Master as M
import qualified TemplateGen.PageContext as PC
import qualified TemplateGen.Settings as S
import qualified TemplateGen.Url as U
data TemplateContext = TemplateContext {
pageTitle :: PC.PageContext -> String,
pc :: PC.PageContext,
currentRoute :: Maybe U.Url,
appSettings :: M.Master -> S.Settings,
appCopyrightYear :: S.Settings -> String,
appCopyright :: S.Settings -> String,
appAnalytics :: S.Settings -> Maybe String,
master :: M.Master
}
mkTemplateContext :: S.Settings -> PC.PageContext -> TemplateContext
mkTemplateContext s pc = TemplateContext
PC.title -- pageTitle
pc
Nothing -- currentRoute
(\(M.Master s) -> s) -- appSettings
S.copyrightYear -- appCopyrightYear
S.copyright -- appCopyright
S.analytics -- appAnalytics
(M.Master s) -- master
|
seahug/seattlehaskell-org-static
|
src/lib/TemplateGen/TemplateContext.hs
|
Haskell
|
mit
| 952
|
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Consensus.Log
-- Copyright : (c) Phil Hargett 2014
-- License : MIT (see LICENSE file)
--
-- Maintainer : phil@haphazardhouse.net
-- Stability : experimental
-- Portability : portable
--
-- General 'Log' and 'State' typeclasses. Collectively, these implement a state machine, and the
-- Raft algorithm essential is one application of the
-- <https://www.cs.cornell.edu/fbs/publications/SMSurvey.pdf replicated state machine model>
-- for implementing a distributed system.
--
-----------------------------------------------------------------------------
module Data.Log (
Index,
Log(..),
defaultCommitEntries,
fetchLatestEntries,
State(..)
) where
-- local imports
-- external imports
import Prelude hiding (log)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
{-|
A 'Log' of type @l@ is a sequence of entries of type @e@ such that
entries can be appended to the log starting at a particular 'Index' (and potentially
overwrite entries previously appended at the same index), fetched
from a particular 'Index', or committed up to a certain 'Index'. Once committed,
it is undefined whether attempting to fetch entries with an 'Index' < 'lastCommitted'
will succeed or throw an error, as some log implementations may throw away some
committed entries.
Each entry in the 'Log' defines an action that transforms a supplied initial 'State'
into a new 'State'. Commiting a 'Log', given some initial 'State', applies the action contained in
each entry in sequence (starting at a specified 'Index') to some state of type @s@,
producing a new 'State' after committing as many entries as possible.
Each log implementation may choose the monad @m@ in which they operate. Consumers of logs
should always use logs in a functional style: that is, after 'appendEntries' or 'commitEntries',
if the log returned from those functions is not fed into later functions, then results
may be unexpected. While the underlying log implementation may itself be pure, log
methods are wrapped in a monad to support those implementations that may not be--such
as a log whose entries are read from disk.
Implementing 'commitEntries' is optional, as a default implementation is supplied
that will invoke 'commitEntry' and 'applyEntry' as needed. Implementations that wish
to optimize commiting batches of entires may choose to override this method.
-}
class (Monad m,State s m e) => Log l m e s | l -> e,l -> s,l -> m where
{-|
'Index' of last committed entry in the 'Log'.
-}
lastCommitted :: l -> Index
{-|
'Index' of last appended entry (e.g., the end of the 'Log').
-}
lastAppended :: l -> Index
{-|
Append new log entries into the 'Log' after truncating the log
to remove all entries whose 'Index' is greater than or equal
to the specified 'Index', although no entries will be overwritten
if they are already committed.
-}
appendEntries :: l -> Index -> [e] -> m l
{-|
Retrieve a number of entries starting at the specified 'Index'
-}
fetchEntries :: l -> Index -> Int -> m [e]
{-|
For each uncommitted entry whose 'Index' is less than or equal to the
specified index, apply the entry to the supplied 'State' using 'applyEntry',
then mark the entry as committed in the 'Log'. Note that implementers are
free to commit no entries, some entries, or all entries as needed to handle
errors. However, the implementation should eventually commit all entries
if the calling application is well-behaved.
-}
commitEntries :: l -> Index -> s -> m (l,s)
commitEntries = defaultCommitEntries
{-|
Records a single entry in the log as committed; note that
this does not involve any external 'State' to which the entry
must be applied, as that is a separate operation.
-}
commitEntry :: l -> Index -> e -> m l
{-|
Snapshot the current `Log` and `State` to persistant storage
such that in the event of failure, both will be recovered from
this point.
-}
checkpoint :: l -> s -> m (l, s)
{-|
'Log's operate on 'State': that is, when committing, the log applies each
entry to the current 'State', and produces a new 'State'. Application of each
entry operates within a chosen 'Monad', so implementers are free to implement
'State' as needed (e.g., use 'IO', 'STM', etc.).
-}
class (Monad m) => State s m e where
canApplyEntry :: s -> e -> m Bool
applyEntry :: s -> e -> m s
{-|
An 'Index' is a logical offset into a 'Log'.
While the exact interpretation of the 'Index' is up to the 'Log'
implementation, by convention the first 'Index' in a log is @0@.
-}
type Index = Int
{-|
Default implementation of `commitEntries`, which fetches all uncommitted entries
with `fetchEntries`, then commits them one by one with `commitEntry` until either the
result of `canApplyEntry` is false, or all entries are committed.
-}
defaultCommitEntries :: (Monad m,State s m e, Log l m e s) => l -> Index -> s -> m (l,s)
defaultCommitEntries initialLog index initialState = do
let committed = lastCommitted initialLog
count = index - committed
if count > 0
then do
let nextCommitted = committed + 1
uncommitted <- fetchEntries initialLog nextCommitted count
commit initialLog initialState nextCommitted uncommitted
else return (initialLog,initialState)
where
commit oldLog oldState _ [] = do
return (oldLog,oldState)
commit oldLog oldState commitIndex (entry:rest) = do
can <- canApplyEntry oldState entry
if can
then do
newLog <- commitEntry oldLog commitIndex entry
newState <- applyEntry oldState entry
commit newLog newState (commitIndex + 1) rest
else return (oldLog,oldState)
{-|
Return all entries from the 'Log''s 'lastCommitted' time up to and
including the 'lastAppended' time.
-}
fetchLatestEntries :: (Monad m, Log l m e s) => l -> m (Index,[e])
fetchLatestEntries log = do
let commitTime = lastCommitted log
startTime = commitTime + 1
count = lastAppended log - lastCommitted log
entries <- fetchEntries log startTime count
return (commitTime,entries)
|
hargettp/raft
|
src/Data/Log.hs
|
Haskell
|
mit
| 6,658
|
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
import System.Environment (getArgs)
import Data.Ord
import Data.List
import Data.Maybe
import Data.Ratio
type Level = Int
type Elfishness = Rational
type Problem = Elfishness
type Result = Maybe Level
maxLevel :: Level
maxLevel = 40
main :: IO ()
main = do
[file] <- getArgs
ip <- readFile file
writeFile ((takeWhile (/= '.') file) ++ ".out" ) (processInput ip)
writeOutput :: [(Int, Result)] -> [String]
writeOutput = map (\(i, r) -> ("Case #" ++ (show i) ++ ": " ++ (writeResult r)))
processInput :: String -> String
processInput = unlines . writeOutput . zip [1..] . map (solveProblem maxLevel). parseProblem . tail . lines
writeResult :: Result -> String
writeResult Nothing = "impossible"
writeResult (Just x) = show x
parseProblem :: [String] -> [Problem]
parseProblem [] = []
parseProblem (s:ss) = (n%d) : parseProblem ss
where n = read . takeWhile (/= '/') $ s
d = read . tail . dropWhile (/= '/') $ s
validElfness :: Elfishness -> Bool
validElfness elf =
let nume = numerator elf
deno = denominator elf
denomax = (2 ^ maxLevel)
in if denomax `mod` deno == 0 then True else False
solveProblem :: Level -> Problem -> Result
solveProblem lvl elf =
let nume = numerator elf
deno = denominator elf
newElf = (2 * nume) % deno
in if validElfness elf == False
then Nothing
else if lvl <= 0
then Nothing
else if nume * 2 >= deno
then Just (maxLevel - lvl + 1 )
else solveProblem (lvl - 1) newElf
|
cbrghostrider/Hacking
|
codeJam/2014/elf/greedyElf.hs
|
Haskell
|
mit
| 1,999
|
{-# LANGUAGE NoMonomorphismRestriction #-}
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
c1 = circle 0.5 # lw none # showOrigin
c2 = circle 1 # fc orange
c3 = circle 0.5 # fc steelblue # showOrigin
diagram :: Diagram B
diagram = (c1 ||| c2) === c3
main = mainWith $ frame 0.1 diagram
|
jeffreyrosenbluth/NYC-meetup
|
meetup/Atop5.hs
|
Haskell
|
mit
| 304
|
{-# LANGUAGE TypeOperators #-}
module Language.LSP.Server
( module Language.LSP.Server.Control
, VFSData(..)
, ServerDefinition(..)
-- * Handlers
, Handlers(..)
, Handler
, transmuteHandlers
, mapHandlers
, notificationHandler
, requestHandler
, ClientMessageHandler(..)
, Options(..)
, defaultOptions
-- * LspT and LspM
, LspT(..)
, LspM
, MonadLsp(..)
, runLspT
, LanguageContextEnv(..)
, type (<~>)(..)
, getClientCapabilities
, getConfig
, getRootPath
, getWorkspaceFolders
, sendRequest
, sendNotification
-- * VFS
, getVirtualFile
, getVirtualFiles
, persistVirtualFile
, getVersionedTextDoc
, reverseFileMap
-- * Diagnostics
, publishDiagnostics
, flushDiagnosticsBySource
-- * Progress
, withProgress
, withIndefiniteProgress
, ProgressAmount(..)
, ProgressCancellable(..)
, ProgressCancelledException
-- * Dynamic registration
, registerCapability
, unregisterCapability
, RegistrationToken
, setupLogger
, reverseSortEdit
) where
import Language.LSP.Server.Control
import Language.LSP.Server.Core
|
alanz/haskell-lsp
|
lsp/src/Language/LSP/Server.hs
|
Haskell
|
mit
| 1,114
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Hecate.Backend.JSON
( JSON
, run
, initialize
, finalize
, AppState
) where
import Control.Monad (when)
import Control.Monad.Catch (MonadThrow (..))
import qualified Control.Monad.Except as Except
import Control.Monad.IO.Class (MonadIO (..))
import Control.Monad.Reader (MonadReader, ReaderT, ask, runReaderT)
import Control.Monad.State (MonadState, StateT, gets, modify, runStateT)
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Encode.Pretty as AesonPretty
import qualified Data.List as List
import Hecate.Backend.JSON.AppState (AppState, appStateDirty)
import qualified Hecate.Backend.JSON.AppState as AppState
import Hecate.Data (Config, configDataDirectory, configDataFile, entryKeyOrder)
import Hecate.Interfaces
-- * JSON
newtype JSON a = JSON { unJSON :: ReaderT Config (StateT AppState IO) a }
deriving ( Functor
, Applicative
, Monad
, MonadIO
, MonadReader Config
, MonadState AppState
, MonadEncrypt
, MonadInteraction
, MonadAppError
)
instance MonadThrow JSON where
throwM = liftIO . throwM
runJSON :: JSON a -> AppState -> Config -> IO (a, AppState)
runJSON m state cfg = runStateT (runReaderT (unJSON m) cfg) state
writeState :: (MonadAppError m, MonadInteraction m) => AppState -> Config -> m ()
writeState state cfg = when (appStateDirty state) $ do
let dataFile = configDataFile cfg
entries = AppState.selectAll state
aesonCfg = AesonPretty.defConfig{AesonPretty.confCompare = AesonPretty.keyOrder entryKeyOrder}
dataBS = AesonPretty.encodePretty' aesonCfg (List.sort entries)
writeFileFromLazyByteString dataFile dataBS
run :: JSON a -> AppState -> Config -> IO a
run m state cfg = do
(res, state') <- runJSON m state cfg
writeState state' cfg
return res
createState :: (MonadAppError m, MonadInteraction m) => Config -> m AppState
createState cfg = do
let dataDir = configDataDirectory cfg
dataFile = configDataFile cfg
dataDirExists <- doesDirectoryExist dataDir
Except.unless dataDirExists (createDirectory dataDir)
dataBS <- readFileAsLazyByteString dataFile
maybe (aesonError "could not decode") (pure . AppState.mkAppState) (Aeson.decode dataBS)
initialize :: (MonadAppError m, MonadInteraction m) => Config -> m (Config, AppState)
initialize cfg = do
state <- createState cfg
return (cfg, state)
finalize :: (MonadAppError m, MonadInteraction m) => (Config, AppState) -> m ()
finalize _ = pure ()
-- * Instances
instance MonadConfigReader JSON where
askConfig = ask
instance MonadStore JSON where
put e = modify $ AppState.put e
delete e = modify $ AppState.delete e
query q = gets (AppState.query q)
selectAll = gets AppState.selectAll
getCount = gets AppState.getCount
getCountOfKeyId kid = gets (AppState.getCountOfKeyId kid)
createTable = undefined
migrate _ _ = undefined
currentSchemaVersion = undefined
|
henrytill/hecate
|
src/Hecate/Backend/JSON.hs
|
Haskell
|
apache-2.0
| 3,297
|
{-# LANGUAGE OverloadedStrings #-}
module IFind.UI (
runUI
) where
import Control.Applicative
import Data.Either
import Data.IORef
import Graphics.Vty hiding (pad)
import Graphics.Vty.Widgets.All
import System.Exit (exitSuccess)
import Text.Printf
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Text.Regex.PCRE as RE
import qualified Text.Regex.PCRE.String as RES
import IFind.Config
import IFind.FS
import IFind.Opts
import Util.List
-- This type isn't pretty, but we have to specify the type of the
-- complete interface. Initially you can let the compiler tell you
-- what it is.
type T = (Box (Box (HFixed FormattedText) (VFixed Edit))
(List T.Text FormattedText))
data SearchApp =
SearchApp { -- widgets
uiWidget :: Widget T
, statusWidget :: Widget FormattedText
, editSearchWidget :: Widget Edit
, searchResultsWidget :: Widget (List T.Text FormattedText)
, activateHandlers :: Handlers SearchApp
-- search state
, matchingFilePaths:: IORef [TextFilePath]
, allFilePaths:: [TextFilePath]
, ignoreCase:: IORef Bool
}
focusedItemAttr:: IFindConfig -> Attr
focusedItemAttr conf = fgc `on` bgc
where
bgc = focusedItemBackgroundColor . uiColors $ conf
fgc = focusedItemForegroundColor . uiColors $ conf
searchCountAttr:: IFindConfig -> Attr
searchCountAttr conf = fgc `on` bgc
where
bgc = searchCountBackgroundColor . uiColors $ conf
fgc = searchCountForegroundColor . uiColors $ conf
-- | runs UI, returns matching file paths
runUI :: IFindOpts -> IFindConfig -> IO [TextFilePath]
runUI opts conf = do
(ui, fg) <- newSearchApp opts conf
c <- newCollection
_ <- addToCollection c (uiWidget ui) fg
runUi c $ defaultContext { focusAttr = focusedItemAttr conf }
readIORef $ matchingFilePaths ui
newSearchApp :: IFindOpts -> IFindConfig -> IO (SearchApp, Widget FocusGroup)
newSearchApp opts conf = do
editSearchWidget' <- editWidget
searchResultsWidget' <- newTextList [] 1
statusWidget' <- plainText "*>" >>= withNormalAttribute (searchCountAttr conf)
activateHandlers' <- newHandlers
_ <- setEditText editSearchWidget' $ T.pack (searchRe opts)
uiWidget' <- ( (hFixed 8 statusWidget') <++> (vFixed 1 editSearchWidget') )
<-->
(return searchResultsWidget')
allFilePaths' <- findAllFilePaths opts conf
matchingFilePathsRef <- newIORef allFilePaths'
ignoreCaseRef <- newIORef $ caseInsensitive opts
let sApp = SearchApp { uiWidget = uiWidget'
, statusWidget = statusWidget'
, editSearchWidget = editSearchWidget'
, searchResultsWidget = searchResultsWidget'
, activateHandlers = activateHandlers'
, matchingFilePaths = matchingFilePathsRef
, allFilePaths = allFilePaths'
, ignoreCase = ignoreCaseRef
}
editSearchWidget' `onActivate` \_ -> do
shutdownUi
editSearchWidget' `onChange` \_ -> do
updateSearchResults sApp
return ()
editSearchWidget' `onKeyPressed` \_ key mods -> do
case (key, mods) of
(KChar 'u', [MCtrl]) -> do
ic <- readIORef ignoreCaseRef
writeIORef ignoreCaseRef (not ic)
updateSearchResults sApp
return True
(_, _) ->
return False
searchResultsWidget' `onKeyPressed` \w key mods ->
case (key, mods) of
(KChar 'p', [MCtrl]) -> scrollUp w >> return True
(KChar 'n', [MCtrl]) -> scrollDown w >> return True
(KChar 'k', []) -> scrollUp w >> return True
(KChar 'j', []) -> scrollDown w >> return True
(_, _) -> return False
searchResultsWidget' `onItemActivated` \_ -> do
selectedItem <- getSelected searchResultsWidget'
case selectedItem of
Just (_, (t, _)) -> do
writeIORef matchingFilePathsRef [t]
shutdownUi
Nothing ->
return ()
fg <- newFocusGroup
fg `onKeyPressed` \_ key _ -> do
case key of
KEsc -> do
shutdownUi
exitSuccess
_ -> return False
_ <- addToFocusGroup fg editSearchWidget'
_ <- addToFocusGroup fg searchResultsWidget'
_ <- updateSearchResults sApp
return (sApp, fg)
updateSearchResults:: SearchApp -> IO ()
updateSearchResults sApp = do
clearList $ searchResultsWidget sApp
searchEditTxt <- getEditText $ editSearchWidget sApp
ignoreCase' <- readIORef $ ignoreCase sApp
stfp <- searchTxtToFilterPredicate ignoreCase' searchEditTxt
case stfp of
Left es -> do
writeIORef (matchingFilePaths sApp) []
addToResultsList sApp $ fmap (T.pack) es
Right filterPredicate -> do
let matchingFps = filter (filterPredicate) $ allFilePaths sApp
writeIORef (matchingFilePaths sApp) matchingFps
addToResultsList sApp $ take 64 matchingFps
updateStatusText sApp
addToResultsList:: SearchApp -> [T.Text] -> IO ()
addToResultsList sApp xs =
mapM_ (\x -> do
xw <- textWidget nullFormatter x
addToList (searchResultsWidget sApp) x xw) xs
updateStatusText:: SearchApp -> IO ()
updateStatusText sApp = do
matchingFps <- readIORef (matchingFilePaths sApp)
let numResults = length matchingFps
searchEditTxt <- getEditText $ editSearchWidget sApp
ignoreCase' <- readIORef $ ignoreCase sApp
let statusChr = if ignoreCase' then '*' else ']'
if T.null searchEditTxt
then setText (statusWidget sApp) $ T.pack $ "Search: "
else setText (statusWidget sApp) $ T.pack $ printf "[%5d%c " numResults statusChr
-- | searchTxt can be of the form "foo!bar!baz",
-- this behaves similar to 'grep foo | grep -v bar | grep -v baz'
-- Return either Left regex compilation errors or Right file path testing predicate
searchTxtToFilterPredicate:: Bool -> T.Text -> IO (Either [String] (TextFilePath -> Bool))
searchTxtToFilterPredicate reIgnoreCase searchEditTxt =
if T.null searchEditTxt
then return $ Right (\_ -> True)
else compileRegex
where
compileRegex = do cRes <- compileRes
case partitionEithers cRes
of ([], (includeRe:excludeRes)) ->
return $ Right $ \fp ->
let bsFp = TE.encodeUtf8 fp
in (RE.matchTest includeRe bsFp) &&
(not . anyOf (fmap (RE.matchTest) excludeRes) $ bsFp)
(errs, _) -> return $ Left $ map (snd) errs
mkRe:: T.Text -> IO (Either (RES.MatchOffset, String) RES.Regex)
mkRe t = RES.compile reCompOpt reExecOpt (T.unpack t)
reCompOpt =(if (reIgnoreCase) then RES.compCaseless else RES.compBlank)
reExecOpt = RES.execBlank
compileRes:: IO [Either (RES.MatchOffset, String) RE.Regex]
compileRes = mapM (mkRe) $ T.splitOn "!" searchEditTxt
|
andreyk0/ifind
|
IFind/UI.hs
|
Haskell
|
apache-2.0
| 6,997
|
module Checker where
import Data.Maybe
import EdictDB
type Conjugation = String
conjugate :: Word -> Conjugation -> Maybe Word
conjugate _ [] = Nothing
conjugate ([],_) _ = Nothing
conjugate w c
| not (validC c) = Just w
| c == "Te" = teForm $ Just w
| c == "Imperitive" = imperitive $ Just w
| c == "TeIru" = teIru $ Just w
| c == "Past" = pastTense $ Just w
| c == "Tai" = taiForm $ Just w
| c == "Negative" = negative $ Just w
| c == "NegTai" = negative . taiForm $ Just w
| c == "NegPastTai" = pastTense . negative . taiForm $ Just w
| c == "Causitive" = causitive $ Just w
| c == "CausPass" = passive . causitive $ Just w
| c == "Passive" = passive $ Just w
| c == "Polite" = polite w
| c == "PoliteNeg" = politeNeg w
| c == "PolitePast" = politePast w
| c == "PNegPast" = politeNegPast w
| c == "PoVo" = politeVolitional w
| c == "Stem" = stem $ Just w
| otherwise = Nothing
teForm :: Maybe Word -> Maybe Word
teForm Nothing = Nothing
teForm x
| hasIorERu x = Just (init y ++ "て", 'e') --This needs to check for preceding い or え
| last y == 'く' = Just (init y ++ "いて", 'e')
| last y == 'ぐ' = Just (init y ++ "いで", 'e')
| last y == 'う' = Just (init y ++ "って", 'e')
| last y == 'つ' = Just (init y ++ "って", 'e')
| last y == 'る' = Just (init y ++ "って", 'e')
| last y == 'ぬ' = Just (init y ++ "んで", 'e')
| last y == 'む' = Just (init y ++ "んで", 'e')
| last y == 'ぶ' = Just (init y ++ "んで", 'e')
| last y == 'す' = Just (init y ++ "して", 'e')
| otherwise = Nothing
where z = fromJust x
y = fst z
hasIorERu :: Maybe Word -> Bool
hasIorERu Nothing = False
hasIorERu x = beginsWith x 'i' && beginsWith x 'e' && snd y == 'r'
where y = fromJust x
beginsWith :: Maybe Word -> Char -> Bool --probably a bad name for this function, rename later
beginsWith Nothing _ = False
beginsWith x y
| y == 'a' = beginsWithA z
| y == 'i' = beginsWithI z
| y == 'u' = beginsWithU z
| y == 'e' = beginsWithE z
| y == 'o' = beginsWithO z
| otherwise = False --maybe not the best solution, possibly throw an error here
where z = fromJust x
beginsWithA :: Word -> Bool
beginsWithA x
| z == 'あ' = True
| z == 'か' = True
| z == 'が' = True
| z == 'さ' = True
| z == 'ざ' = True
| z == 'た' = True
| z == 'だ' = True
| z == 'な' = True
| z == 'は' = True
| z == 'ば' = True
| z == 'ぱ' = True
| z == 'ま' = True
| z == 'ら' = True
| z == 'わ' = True
| z == 'や' = True
| otherwise = False
where y = take 2 $ reverse . fst $ x
z = y !! 2
beginsWithI :: Word -> Bool
beginsWithI x
| z == 'い' = True
| z == 'き' = True
| z == 'ぎ' = True
| z == 'し' = True
| z == 'じ' = True
| z == 'ち' = True
| z == 'ぢ' = True
| z == 'に' = True
| z == 'ひ' = True
| z == 'び' = True
| z == 'ぴ' = True
| z == 'み' = True
| z == 'り' = True
| otherwise = False
where y = take 2 $ reverse . fst $ x
z = y !! 2
beginsWithU :: Word -> Bool
beginsWithU x
| z == 'う' = True
| z == 'く' = True
| z == 'ぐ' = True
| z == 'す' = True
| z == 'ず' = True
| z == 'つ' = True
| z == 'づ' = True
| z == 'ぬ' = True
| z == 'ふ' = True
| z == 'ぶ' = True
| z == 'ぷ' = True
| z == 'む' = True
| z == 'る' = True
| z == 'ゆ' = True
| otherwise = False
where y = take 2 $ reverse . fst $ x
z = y !! 2
beginsWithE :: Word -> Bool
beginsWithE x
| z == 'え' = True
| z == 'け' = True
| z == 'げ' = True
| z == 'せ' = True
| z == 'ぜ' = True
| z == 'て' = True
| z == 'で' = True
| z == 'ね' = True
| z == 'へ' = True
| z == 'べ' = True
| z == 'ぺ' = True
| z == 'め' = True
| z == 'れ' = True
| otherwise = False
where y = take 2 $ reverse . fst $ x
z = y !! 2
beginsWithO :: Word -> Bool
beginsWithO x
| z == 'お' = True
| z == 'こ' = True
| z == 'ご' = True
| z == 'そ' = True
| z == 'ぞ' = True
| z == 'と' = True
| z == 'ど' = True
| z == 'の' = True
| z == 'ほ' = True
| z == 'ぼ' = True
| z == 'ぽ' = True
| z == 'も' = True
| z == 'ろ' = True
| z == 'よ' = True
| otherwise = False
where y = take 2 $ reverse . fst $ x
z = y !! 2
teIru :: Maybe Word -> Maybe Word
teIru Nothing = Nothing
teIru x
| isNothing (teForm x) = Nothing
| otherwise = Just (y ++ "いる", 'r')
where y = fst . fromJust . teForm $ x
pastTense :: Maybe Word -> Maybe Word
pastTense Nothing = Nothing
pastTense x
| snd z == 'r' = Just (init (fst z) ++ "た", 'r')
| snd z == 'u' && last y == 'て' = Just (init y ++ "た", 'u')
| snd z == 'u' && last y == 'で' = Just (init y ++ "だ", 'u')
| snd z == 'i' = Just (init (fst z) ++ "かった", 'i')
| snd z == 'd' = Just (init (fst z) ++ "だった", 'd')
| otherwise = Nothing
where z = fromJust x
y = fst . fromJust . teForm $ x
taiForm :: Maybe Word -> Maybe Word
taiForm Nothing = Nothing
taiForm x
| snd z == 'r' = Just (init (fst z) ++ "たい", 'i')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "いたい", 'i')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "きたい", 'i')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "ぎたい", 'i')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "したい", 'i')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "ちたい", 'i')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "にたい", 'i')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "みたい", 'i')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "びたい", 'i')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "りたい", 'i')
| snd z == 'n' = Just (init (fst z) ++ "したい", 'i')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
negative :: Maybe Word -> Maybe Word
negative Nothing = Nothing
negative x
| snd z == 'i' = Just (init (fst z) ++ "くない", 'i')
| snd z == 'r' = Just (init (fst z) ++ "ない", 'i')
| snd z == 'd' = Just (init (fst z) ++ "じゃない", 'i')
| snd z == 'n' = Just (init (fst z) ++ "しない", 'i')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "わない", 'i')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "かない", 'i')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "がない", 'i')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "さない", 'i')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "たない", 'i')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "なない", 'i')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "まない", 'i')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "ばない", 'i')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "らない", 'i')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
imperitive :: Maybe Word -> Maybe Word
imperitive Nothing = Nothing
imperitive x
| snd z == 'n' = Just (fst z ++ "しろ", 'r')
| snd z == 'r' = Just (init (fst z) ++ "れ",'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "え", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "け", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "げ", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "せ", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "て", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "ね", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "め", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "べ", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "れ", 'u')
where z = fromJust x
y = last (fst z)
negativeImperitive :: Maybe Word -> Maybe Word
negativeImperitive Nothing = Nothing
negativeImperitive x
| snd z == 'n' = Just (fst z ++ "するな", 'n')
| snd z == 'r' || snd z == 'u' = Just (fst z ++ "な", 'n')
| otherwise = Nothing
where z = fromJust x
volitional :: Maybe Word -> Maybe Word
volitional Nothing = Nothing
volitional x
| snd z == 'n' = Just (fst z ++ "しよう", 'u')
| snd z == 'r' = Just (init (fst z) ++ "よう",'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "おう", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "こう", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "ごう", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "そう", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "とう", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "のう", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "もう", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "ぼう", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "ろう", 'u')
| snd z == 'i' = Just (init (fst z) ++ "かろう", 'u')
| snd z == 'a' = Just (init (fst z) ++ "だろう", 'u')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
potential :: Maybe Word -> Maybe Word
potential Nothing = Nothing
potential x
| snd z == 'd' = Just (fst z ++ "できる", 'r')
| snd z == 'r' = Just (init (fst z) ++ "られる",'r')
| snd z == 'n' = Just (init (fst z) ++ "せられる",'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "える", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "ける", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "げる", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "せる", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "てる", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "ねる", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "める", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "べる", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "れる", 'u')
| snd z == 'i' = Just (init (fst z) ++ "あり得る", 'u')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
conditional :: Maybe Word -> Maybe Word
conditional Nothing = Nothing
conditional x = Just (fst z ++ "ら", snd y)
where z = fromJust . pastTense $ x
y = fromJust x
passive :: Maybe Word -> Maybe Word
passive Nothing = Nothing
passive x
| snd z == 'n' = Just (fst z ++ "される", 'r')
| snd z == 'r' = Just (init (fst z) ++ "られる",'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "われる", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "かれる", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "がれる", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "される", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "たれる", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "なれる", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "まれる", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "ばれる", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "られる", 'u')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
causitive :: Maybe Word -> Maybe Word
causitive Nothing = Nothing
causitive x
| snd z == 'n' = Just (fst z ++ "させる", 'r')
| snd z == 'r' = Just (init (fst z) ++ "させる",'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "わせる", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "かせる", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "がせる", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "させる", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "たせる", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "なせる", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "ませる", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "ばせる", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "らせる", 'u')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
causitivePassive :: Maybe Word -> Maybe Word
causitivePassive Nothing = Nothing
causitivePassive x = passive . causitive $ x
provisionalConditional :: Maybe Word -> Maybe Word
provisionalConditional Nothing = Nothing
provisionalConditional x
| snd z == 'n' = Just (fst z ++ "すれば", 'u')
| snd z == 'r' = Just (init (fst z) ++ "れば",'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "えば", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "けば", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "げば", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "せば", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "てば", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "ねば", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "めば", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "べば", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "れば", 'u')
| snd z == 'i' = Just (init (fst z) ++ "ければ", 'u')
| snd z == 'a' = Just (init (fst z) ++ "であれば", 'u')
where z = fromJust x
y = last (fst z)
stem :: Maybe Word -> Maybe Word
stem Nothing = Nothing
stem x
| snd z == 'r' = Just (init (fst z), 'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "い", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "き", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "ぎ", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "し", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "ち", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "に", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "み", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "び", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "り", 'u')
| fst z == "する" = Just ("し", 's')
| fst z == "くる" = Just ("き", 'k')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
polite :: Word -> Maybe Word
polite x
| snd x == 'n' = Just (fst x ++ "します", 'e')
| snd x == 'r' = Just (init (fst x) ++ "ます", 'e')
| snd x == 'u' && y == 'う' = Just (init (fst x) ++ "います", 'e')
| snd x == 'u' && y == 'く' = Just (init (fst x) ++ "きます", 'e')
| snd x == 'u' && y == 'ぐ' = Just (init (fst x) ++ "ぎます", 'e')
| snd x == 'u' && y == 'す' = Just (init (fst x) ++ "します", 'e')
| snd x == 'u' && y == 'つ' = Just (init (fst x) ++ "ちます", 'e')
| snd x == 'u' && y == 'ぬ' = Just (init (fst x) ++ "にます", 'e')
| snd x == 'u' && y == 'む' = Just (init (fst x) ++ "みます", 'e')
| snd x == 'u' && y == 'ぶ' = Just (init (fst x) ++ "びます", 'e')
| snd x == 'u' && y == 'る' = Just (init (fst x) ++ "ります", 'e')
| otherwise = Nothing
where y = last (fst x)
politeNeg :: Word -> Maybe Word
politeNeg x
| isNothing (polite x) = Nothing
| otherwise = Just (init y ++ "せん", 'e')
where y = fst . fromJust . polite $ x
politeNegPast :: Word -> Maybe Word
politeNegPast x
| isNothing (politeNeg x) = Nothing
| otherwise = Just (y ++ "でした", 'e')
where y = fst . fromJust . politeNeg $ x
politePast :: Word -> Maybe Word
politePast x
| isNothing (polite x) = Nothing
| otherwise = Just (y ++ "した", 'e')
where y = fst . fromJust . polite $ x
politeVolitional :: Word -> Maybe Word
politeVolitional x
| isNothing (polite x) = Nothing
| otherwise = Just (init y ++ "しょう", 'e')
where y = fst . fromJust . polite $ x
validC :: Conjugation -> Bool
validC [] = False
validC x
| x == "Te" = True
| x == "Imperitive" = True
| x == "Past" = True
| x == "TeIru" = True
| x == "Negative" = True
| x == "Tai" = True
| x == "NegTai" = True
| x == "NegPastTai" = True
| x == "Potential" = True
| x == "Causitive" = True
| x == "Passive" = True
| x == "CausPass" = True
| x == "Polite" = True
| x == "PoliteNeg" = True
| x == "PolitePast" = True
| x == "PNegPast" = True
| x == "PoVo" = True
| x == "Stem" = True
| otherwise = False
addType :: String -> Maybe Word
addType x
| take 2 (reverse x) == "する" = Just (init (init x),'n')
| last x == 'う' = Just (x,'u')
| last x == 'く' = Just (x,'u')
| last x == 'ぐ' = Just (x,'u')
| last x == 'す' = Just (x,'u')
| last x == 'つ' = Just (x,'u')
| last x == 'づ' = Just (x,'u')
| last x == 'ぬ' = Just (x,'u')
| last x == 'ぶ' = Just (x,'u')
| last x == 'む' = Just (x,'u')
| last x == 'だ' = Just (x, 'd')
| otherwise = dbLookup x
|
MarkMcCaskey/Refcon
|
Checker.hs
|
Haskell
|
apache-2.0
| 17,577
|
{-# LANGUAGE OverloadedStrings #-}
import Text.HTML.SanitizeXSS
import Text.HTML.SanitizeXSS.Css
import Data.Text (Text)
import Data.Text as T
import Test.Hspec.Monadic
import Test.Hspec.HUnit ()
import Test.HUnit (assert, (@?=), Assertion)
test :: (Text -> Text) -> Text -> Text -> Assertion
test f actual expected = do
let result = f actual
result @?= expected
sanitized = test sanitize
main = hspecX $ do
describe "html sanitizing" $ do
it "big test" $ do
let testHTML = " <a href='http://safe.com'>safe</a><a href='unsafe://hack.com'>anchor</a> <img src='evil://evil.com' /> <unsafe></foo> <bar /> <br></br> <b>Unbalanced</div><img src='http://safe.com'>"
test sanitizeBalance testHTML " <a href=\"http://safe.com\">safe</a><a>anchor</a> <img /> <br /> <b>Unbalanced<div></div><img src=\"http://safe.com\"></b>"
sanitized testHTML " <a href=\"http://safe.com\">safe</a><a>anchor</a> <img /> <br /> <b>Unbalanced</div><img src=\"http://safe.com\">"
it "relativeURI" $ do
let testRelativeURI = "<a href=\"foo\">bar</a>"
sanitized testRelativeURI testRelativeURI
it "protocol hack" $
sanitized "<script src=//ha.ckers.org/.j></script>" ""
it "object hack" $
sanitized "<object classid=clsid:ae24fdae-03c6-11d1-8b76-0080c744f389><param name=url value=javascript:alert('XSS')></object>" ""
it "embed hack" $
sanitized "<embed src=\"data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==\" type=\"image/svg+xml\" AllowScriptAccess=\"always\"></embed>" ""
it "ucase image hack" $
sanitized "<IMG src=javascript:alert('XSS') />" "<img />"
describe "allowedCssAttributeValue" $ do
it "allows hex" $ do
assert $ allowedCssAttributeValue "#abc"
assert $ allowedCssAttributeValue "#123"
assert $ not $ allowedCssAttributeValue "abc"
assert $ not $ allowedCssAttributeValue "123abc"
it "allows rgb" $ do
assert $ allowedCssAttributeValue "rgb(1,3,3)"
assert $ not $ allowedCssAttributeValue "rgb()"
it "allows units" $ do
assert $ allowedCssAttributeValue "10 px"
assert $ not $ allowedCssAttributeValue "10 abc"
describe "css sanitizing" $ do
it "removes style when empty" $
sanitized "<p style=''></p>" "<p></p>"
it "allows any non-url value for white-listed properties" $ do
let whiteCss = "<p style=\"letter-spacing:foo-bar;text-align:10million\"></p>"
sanitized whiteCss whiteCss
it "rejects any url value" $ do
let whiteCss = "<p style=\"letter-spacing:foo url();text-align:url(http://example.com)\"></p>"
sanitized whiteCss "<p style=\"letter-spacing:foo \"></p>"
it "rejects properties not on the white list" $ do
let blackCss = "<p style=\"anything:foo-bar;other-stuff:10million\"></p>"
sanitized blackCss "<p></p>"
it "rejects invalid units for grey-listed css" $ do
let greyCss = "<p style=\"background:foo-bar;border:10million\"></p>"
sanitized greyCss "<p></p>"
it "allows valid units for grey-listed css" $ do
let grey2Css = "<p style=\"background:1;border-foo:10px\"></p>"
sanitized grey2Css grey2Css
|
silkapp/haskell-xss-sanitize
|
test/main.hs
|
Haskell
|
bsd-2-clause
| 3,468
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QHttp_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:31
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Network.QHttp_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Network_h
import Qtc.ClassTypes.Network
import Foreign.Marshal.Array
instance QunSetUserMethod (QHttp ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHttp_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QHttp_unSetUserMethod" qtc_QHttp_unSetUserMethod :: Ptr (TQHttp a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QHttpSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHttp_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QHttp ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHttp_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QHttpSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHttp_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QHttp ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHttp_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QHttpSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHttp_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QHttp ()) (QHttp x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QHttp setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QHttp_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QHttp_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHttp_setUserMethod" qtc_QHttp_setUserMethod :: Ptr (TQHttp a) -> CInt -> Ptr (Ptr (TQHttp x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QHttp :: (Ptr (TQHttp x0) -> IO ()) -> IO (FunPtr (Ptr (TQHttp x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QHttp_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QHttpSc a) (QHttp x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QHttp setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QHttp_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QHttp_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QHttp ()) (QHttp x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QHttp setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QHttp_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QHttp_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHttp_setUserMethodVariant" qtc_QHttp_setUserMethodVariant :: Ptr (TQHttp a) -> CInt -> Ptr (Ptr (TQHttp x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QHttp :: (Ptr (TQHttp x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQHttp x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QHttp_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QHttpSc a) (QHttp x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QHttp setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QHttp_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QHttp_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QHttp ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QHttp_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QHttp_unSetHandler" qtc_QHttp_unSetHandler :: Ptr (TQHttp a) -> CWString -> IO (CBool)
instance QunSetHandler (QHttpSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QHttp_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QHttp ()) (QHttp x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHttp1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHttp1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHttp_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qHttpFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHttp_setHandler1" qtc_QHttp_setHandler1 :: Ptr (TQHttp a) -> CWString -> Ptr (Ptr (TQHttp x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHttp1 :: (Ptr (TQHttp x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQHttp x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QHttp1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHttpSc a) (QHttp x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHttp1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHttp1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHttp_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qHttpFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QHttp ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHttp_event cobj_x0 cobj_x1
foreign import ccall "qtc_QHttp_event" qtc_QHttp_event :: Ptr (TQHttp a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QHttpSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHttp_event cobj_x0 cobj_x1
instance QsetHandler (QHttp ()) (QHttp x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHttp2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHttp2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHttp_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qHttpFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHttp_setHandler2" qtc_QHttp_setHandler2 :: Ptr (TQHttp a) -> CWString -> Ptr (Ptr (TQHttp x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHttp2 :: (Ptr (TQHttp x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQHttp x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QHttp2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHttpSc a) (QHttp x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHttp2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHttp2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHttp_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qHttpFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QHttp ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHttp_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QHttp_eventFilter" qtc_QHttp_eventFilter :: Ptr (TQHttp a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QHttpSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHttp_eventFilter cobj_x0 cobj_x1 cobj_x2
|
keera-studios/hsQt
|
Qtc/Network/QHttp_h.hs
|
Haskell
|
bsd-2-clause
| 16,093
|
{-# LANGUAGE CPP #-}
module CLaSH.GHC.Compat.Outputable
( showPpr, showSDoc, showPprDebug )
where
#if __GLASGOW_HASKELL__ >= 707
import qualified DynFlags (unsafeGlobalDynFlags)
#elif __GLASGOW_HASKELL__ >= 706
import qualified DynFlags (tracingDynFlags)
#endif
import qualified Outputable (Outputable (..), SDoc, showPpr, showSDoc, showSDocDebug)
showSDoc :: Outputable.SDoc -> String
#if __GLASGOW_HASKELL__ >= 707
showSDoc = Outputable.showSDoc DynFlags.unsafeGlobalDynFlags
#endif
showPprDebug :: Outputable.Outputable a => a -> String
showPprDebug = Outputable.showSDocDebug DynFlags.unsafeGlobalDynFlags . Outputable.ppr
showPpr :: (Outputable.Outputable a) => a -> String
#if __GLASGOW_HASKELL__ >= 707
showPpr = Outputable.showPpr DynFlags.unsafeGlobalDynFlags
#elif __GLASGOW_HASKELL__ >= 706
showPpr = Outputable.showPpr DynFlags.tracingDynFlags
#else
showPpr = Outputable.showPpr
#endif
|
christiaanb/clash-compiler
|
clash-ghc/src-ghc/CLaSH/GHC/Compat/Outputable.hs
|
Haskell
|
bsd-2-clause
| 908
|
import Intel.ArBB
import Intel.ArBB.Util.Image
import qualified Intel.ArbbVM as VM
import qualified Data.Vector.Storable as V
import qualified Prelude as P
import Prelude as P hiding (map,zipWith)
import Data.Word
import System.IO
import System.Time
import Text.Printf
import System.Environment
import Foreign hiding (new)
{-
| -1 0 1 |
Gx = | -2 0 2 |
| -1 0 1 |
| -1 -2 -1 |
Gy = | 0 0 0 |
| 1 2 1 |
-}
-- Haskell lists and list comprehensions used as a tool
s1, s2 :: [(Exp ISize,Exp ISize)]
s1 = [(1,1),(0,1),(-1,1),(1,-1),(0,-1),(-1,-1)]
s2 = [(1,1),(1,0),(1,-1),(-1,1),(-1,0),(-1,-1)]
coeffs :: [Exp Float]
coeffs = [-1,-2,-1,1,2,1]
gx' :: Exp Float -> Exp Float
gx' x = foldl (+) 0
$ P.zipWith (*) [getNeighbor2D x a b
| (a,b) <- s1] coeffs
gy' :: Exp Float -> Exp Float
gy' x = foldl (+) 0
$ P.zipWith (*) [getNeighbor2D x a b
| (a,b) <- s2] coeffs
gx :: Exp (DVector Dim2 Float) -> Exp (DVector Dim2 Float)
gx = mapStencil (Stencil [-1,0,1
,-2,0,2
,-1,0,1] (Z:.3:.3))
gy :: Exp (DVector Dim2 Float) -> Exp (DVector Dim2 Float)
gy = mapStencil (Stencil [ 1, 2, 1
, 0, 0, 0
,-1,-2,-1] (Z:.3:.3))
test :: Exp (DVector Dim2 Float) ->
(Exp (DVector Dim2 Float), Exp (DVector Dim2 Float))
test v = (gx v,gy v)
--convertToWord8 :: Exp Float -> Exp Word8
--convertToWord8 x = toWord8 $ (clamp x) * 255
--clamp :: Exp Float -> Exp Float
-- Should be clamp, right ?
--clamp x = max 0 (min x 1)
-- 8 bit per pixel greyscale image will be processed.
--kernel :: Exp Word8 -> Exp Word8
--kernel x = convertToWord8 $ body x
-- where
-- body x = sqrt (x' * x' + y' * y')
-- where
-- x' = gx x
-- y' = gy x
magnitude :: Exp Float -> Exp Float -> Exp Float
magnitude x y = sqrt (x * x + y * y)
runMag :: Exp (DVector Dim2 Float) -> Exp (DVector Dim2 Float) ->
Exp (DVector Dim2 Float)
runMag v1 v2 = zipWith magnitude v1 v2
--sobel :: Exp (DVector Dim2 Word8)
-- -> Exp (DVector Dim2 Word8)
--sobel image = map kernel image
testSobel nIters infile outfile =
withArBB $
do
-- f <- capture sobel
test <- capture test
runMag <- capture runMag
convertGray <- capture toGray
convertF <- capture grayToFloat
convertG <- capture floatToGray
img <- liftIO$ loadBMP_RGB infile
let (Dim [3,r,c]) = toDim$ dVectorShape img
imgColor <- copyIn img
imgGray <- new (Z:.c:.r) 0
imgFloat <- new (Z:.c:.r) 0
imgF1 <- new (Z:.c:.r) 0
imgF2 <- new (Z:.c:.r) 0
execute convertGray imgColor imgGray
execute convertF imgGray imgFloat
-- warmup
execute test imgFloat (imgF1 :- imgF2)
finish
t1 <- liftIO getClockTime
execute test imgFloat (imgF1 :- imgF2)
finish
t2 <- liftIO getClockTime
-- Warmup
--execute runMag (imgF1 :- imgF2) (imgFloat)
--finish
--t1 <- liftIO getClockTime
--loop nIters $
-- do
execute runMag (imgF1 :- imgF2) (imgFloat)
-- finish
--t2 <- liftIO getClockTime
execute convertG imgFloat imgGray
finish
r <- copyOut imgGray
liftIO $ saveBMP_Gray outfile r
liftIO $ printf "%f\n" (diffms (diffClockTimes t2 t1))
mb a = 1024*1024*a
main =
do
VM.setHeapSize (mb 1024) (mb (8192*2))
args <- getArgs
case args of
[a,b] ->
let iters = read a :: Int
in
do
-- putStrLn $ "running " ++ show iters ++ " times"
testSobel iters b "sobout.bmp"
_ -> error "incorrects args"
loop 0 action = return ()
loop n action =
do
action
loop (n-1) action
diffms :: TimeDiff -> Float
diffms diff | tdYear diff == 0 &&
tdMonth diff == 0 &&
tdDay diff == 0 &&
tdMin diff == 0 &&
tdHour diff == 0 = (fromIntegral ps) * 1E-9 +
(fromIntegral sec) * 1000
where
ps = tdPicosec diff
sec = tdSec diff
|
svenssonjoel/EmbArBB
|
Samples/Bench/sobel.hs
|
Haskell
|
bsd-3-clause
| 4,578
|
module Text.Highlighter.Lexers.Vim (lexer) where
import Text.Regex.PCRE.Light
import Text.Highlighter.Types
lexer :: Lexer
lexer = Lexer
{ lName = "VimL"
, lAliases = ["vim"]
, lExtensions = [".vim", ".vimrc"]
, lMimetypes = ["text/x-vim"]
, lStart = root'
, lFlags = [multiline]
}
root' :: TokenMatcher
root' =
[ tok "^\\s*\".*" (Arbitrary "Comment")
, tok "(?<=\\s)\"[^\\-:.%#=*].*" (Arbitrary "Comment")
, tok "[ \\t]+" (Arbitrary "Text")
, tok "/(\\\\\\\\|\\\\/|[^\\n/])*/" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Regex")
, tok "\"(\\\\\\\\|\\\\\"|[^\\n\"])*\"" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Double")
, tok "'(\\\\\\\\|\\\\'|[^\\n'])*'" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Single")
, tok "-?\\d+" (Arbitrary "Literal" :. Arbitrary "Number")
, tok "#[0-9a-f]{6}" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Hex")
, tok "^:" (Arbitrary "Punctuation")
, tok "[()<>+=!|,\126-]" (Arbitrary "Punctuation")
, tok "\\b(let|if|else|endif|elseif|fun|function|endfunction)\\b" (Arbitrary "Keyword")
, tok "\\b(NONE|bold|italic|underline|dark|light)\\b" (Arbitrary "Name" :. Arbitrary "Builtin")
, tok "\\b\\w+\\b" (Arbitrary "Name" :. Arbitrary "Other")
, tok "." (Arbitrary "Text")
]
|
chemist/highlighter
|
src/Text/Highlighter/Lexers/Vim.hs
|
Haskell
|
bsd-3-clause
| 1,348
|
module NumberKata where
import DeleteNth
import HappyNumbers
import LastDigitOfLargeNumber
import PascalsTriangle
import PerimeterOfSquaresInRectangle
import ProductOfConsecutiveFibs
import WeightForWeight
testKata :: IO ()
testKata = print "Hey! Another super-useless function!"
|
Eugleo/Code-Wars
|
src/NumberKata.hs
|
Haskell
|
bsd-3-clause
| 282
|
{-# LANGUAGE TemplateHaskell #-}
module Item
( Item(..)
, itemSymbol
, itemDescription
) where
import Control.Lens
import Misc
data Item = Item
{ _itemSymbol :: Symbol
, _itemDescription :: String
} deriving (Read, Show, Eq)
makeLenses ''Item
|
dagit/7drl2017
|
src/Item.hs
|
Haskell
|
bsd-3-clause
| 258
|
module Graphics.Vty.Widgets.Builder.Handlers.DirBrowser
( handlers
)
where
import Control.Applicative
import Graphics.Vty.Widgets.Builder.Types
import Graphics.Vty.Widgets.Builder.GenLib
import qualified Graphics.Vty.Widgets.Builder.Validation as V
import qualified Graphics.Vty.Widgets.Builder.SrcHelpers as S
handlers :: [WidgetElementHandler]
handlers = [handleDirBrowser]
handleDirBrowser :: WidgetElementHandler
handleDirBrowser =
WidgetElementHandler genSrc doValidation "dirBrowser"
where
doValidation s = V.optional s "skin"
genSrc nam skin = do
let Just skinName = skin <|> Just "defaultBrowserSkin"
browserName <- newEntry "browser"
fgName <- newEntry "focusGroup"
bData <- newEntry "browserData"
append $ S.bind bData "newDirBrowser" [S.expr $ S.mkName skinName]
append $ S.mkLet [ (nam, S.call "dirBrowserWidget" [S.expr browserName])
, (browserName, S.call "fst" [S.expr bData])
, (fgName, S.call "snd" [S.expr bData])
]
mergeFocus nam fgName
return $ declareWidget nam (S.mkTyp "DirBrowserWidgetType" [])
`withField` (browserName, S.parseType "DirBrowser")
|
jtdaugherty/vty-ui-builder
|
src/Graphics/Vty/Widgets/Builder/Handlers/DirBrowser.hs
|
Haskell
|
bsd-3-clause
| 1,325
|
{-# LANGUAGE OverloadedStrings #-}
module Spell.LazyText
where
import qualified Data.Text.Lazy as TL
import Data.Text.Lazy (Text)
import Data.Monoid
import Data.List.Ordered (nubSort)
import Data.Ord
import Data.List
import Control.Monad
type Dict = ( TL.Text -> Bool, TL.Text -> Int )
singles :: [ TL.Text ]
singles = map TL.singleton ['a'..'z']
edits :: TL.Text -> [ TL.Text ]
edits w = deletes <> nubSort (transposes <> replaces) <> inserts
where
splits = zip (TL.inits w) (TL.tails w)
deletes = [ a <> (TL.drop 1 b) | (a,b) <- splits, TL.length b > 0 ]
transposes = [ a <> c <> (TL.drop 2 b) | (a,b) <- splits, TL.length b > 1,
let c = TL.pack [ TL.index b 1, TL.index b 0 ] ]
replaces = [ a <> c <> (TL.drop 1 b) | (a,b) <- splits, TL.length b > 1,
c <- singles ]
inserts = [ a <> c <> b | (a,b) <- splits, c <- singles ]
orElse :: [a] -> [a] -> [a]
orElse [] bs = bs
orElse as _ = as
-- | Correct a word. 'isMember' and 'frequency' are functions to
-- determine if a word is in the dictionary and to lookup its
-- frequency, respectively.
correct :: Dict -> TL.Text -> TL.Text
correct (isMember,frequency) w0 =
let ed0 = [ w0 ]
ed1 = edits w0
ed2 = [ e2 | e1 <- ed1, e2 <- edits e1 ]
kn0 = filter isMember ed0
kn1 = filter isMember ed1
kn2 = filter isMember ed2
candidates = kn0 `orElse` (kn1 `orElse` (kn2 `orElse` [w0]))
in maximumBy (comparing frequency) candidates
-- helper function to ensure that ghc doesn't optimize calls
-- to 'correct'
foo n w0 | n > 0 = w0 <> ""
| otherwise = w0
-- test correcting a word multiple times (for timing)
testRep :: Dict -> Int -> TL.Text -> IO ()
testRep dictfns n w0 = do
replicateM_ n $ do
print $ correct dictfns (foo n w0)
|
erantapaa/test-spelling
|
src/Spell/LazyText.hs
|
Haskell
|
bsd-3-clause
| 1,820
|
{-# LANGUAGE RankNTypes, ScopedTypeVariables #-}
module Network.LambdaBridge.Bridge where
import Data.Word as W
import System.Random
import Data.Default
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Concurrent.Chan
import Numeric
import Data.Word
import Data.Binary
import Data.Binary.Get as Get
import Data.Binary.Put as Put
import qualified Data.ByteString.Lazy as LBS
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Time.Clock
import Control.Exception as Exc
import Control.Monad
import Control.Concurrent.Chan
import Control.Concurrent.STM
import Control.Concurrent.STM.TVar
import System.IO.Unsafe (unsafeInterleaveIO)
-- | A 'Bridge' is a bidirectional connection to a specific remote API.
-- There are many different types of Bridges in the lambda-bridge API.
data Bridge msg = Bridge
{ toBridge :: msg -> IO () -- ^ write to a bridge; may block; called many times.
, fromBridge :: IO msg -- ^ read from a bridge; may block, called many times.
-- The expectation is that *eventually* after some
-- time and/or computation
-- someone will read from the bridge, and the
-- reading does not depend on any external interaction or events.
}
--------------------------------------------------------------------------
-- | A 'Bridge (of) Byte' is for talking one byte at a time, where the
-- byte may or may not get there, and may get garbled.
--
-- An example of a 'Bridge (of) Byte' is a RS-232 link.
newtype Byte = Byte W.Word8 deriving (Eq,Ord)
instance Show Byte where
show (Byte w) = "0x" ++ showHex w ""
--------------------------------------------------------------------------
-- | A 'Bridge (of) Bytes' is for talking one byte at a time, where the
-- byte may or may not get there, and may get garbled. The Bytes are
-- sent in order. We provide Bytes because the underlying transportation
-- mechansim *may* choose to send many bytes at the same time.
-- Sending a empty sequence Bytes returns without communications,
-- and it is not possible to receive a empty sequence of bytes.
--
-- An example of a 'Bridge (of) Bytes' is a RS-232 link.
newtype Bytes = Bytes BS.ByteString deriving (Eq,Ord)
instance Show Bytes where
show (Bytes ws) = "Bytes " ++ show [Byte w | w <- BS.unpack ws ]
--------------------------------------------------------------------------
-- | A 'Bridge (of) Frame' is small set of bytes, where a Frame may
-- or may not get to the destination, but if received, will
-- not be garbled or fragmented (via CRC or equiv).
-- There is typically an implementation specific maximum size of a Frame.
-- An example of a 'Bridge (of) Frame' is UDP.
newtype Frame = Frame BS.ByteString
instance Show Frame where
show (Frame wds) = "Frame " ++ show [ Byte w | w <- BS.unpack wds ]
instance Binary Frame where
put (Frame bs) = put bs
get = liftM Frame get
-- | A way of turning a Frame into its contents, using the 'Binary' class.
-- This may throw an async exception.
fromFrame :: (Binary a) => Frame -> a
fromFrame (Frame fs) = decode (LBS.fromChunks [fs])
-- | A way of turning something into a Frame, using the 'Binary' class.
toFrame :: (Binary a) => a -> Frame
toFrame a = Frame $ BS.concat $ LBS.toChunks $ encode a
--------------------------------------------------------------------------
-- | 'debugBridge' outputs to the stderr debugging messages
-- about what datum is getting send where.
debugBridge :: (Show msg) => String -> Bridge msg -> IO (Bridge msg)
debugBridge name bridge = do
sendCounter <- newMVar 0
recvCounter <- newMVar 0
return $ Bridge
{ toBridge = \ a -> do
count <- takeMVar sendCounter
putMVar sendCounter (succ count)
putStrLn $ name ++ ":toBridge<" ++ show count ++ "> (" ++ show a ++ ")"
() <- toBridge bridge a
putStrLn $ name ++ ":toBridge<" ++ show count ++ "> success"
, fromBridge = do
count <- takeMVar recvCounter
putMVar recvCounter (succ count)
putStrLn $ name ++ ":fromBridge<" ++ show count ++ ">"
a <- fromBridge bridge `Exc.catch` \ (e :: SomeException) -> do { print e ; throw e }
putStrLn $ name ++ ":fromBridge<" ++ show count ++ "> (" ++ show a ++ ")"
return a
}
-- | ''Realistic'' is the configuration for ''realisticBridge''.
data Realistic a = Realistic
{ loseU :: Float -- ^ lose an 'a'
, dupU :: Float -- ^ dup an 'a'
, execptionU :: Float -- ^ throw exception instead
, pauseU :: Float -- ^ what is the pause between things
, mangleU :: Float -- ^ mangle an 'a'
, mangler :: Float -> a -> a -- ^ how to mangle, based on a number between 0 and 1
}
-- | default instance of 'realistic', which is completely reliable.
instance Default (Realistic a) where
def = Realistic 0 0 0 0 0 (\ g a -> a)
connectBridges :: (Show msg) => Bridge msg -> Realistic msg -> Realistic msg -> Bridge msg -> IO ()
connectBridges lhs lhsOut rhsOut rhs = do
let you :: Float -> IO Bool
you f = do
r <- randomIO
return $ f > r
let optMangle f mangle a = do
b <- you f
if b then do
r <- randomIO
return $ mangle r a
else return a
let unrely :: MVar UTCTime -> Realistic msg -> msg -> (msg -> IO ()) -> IO ()
unrely tmVar opts a k = do
tm0 <- takeMVar tmVar -- old char time
tm1 <- getCurrentTime -- current time
let pause = pauseU opts - realToFrac (tm1 `diffUTCTime` tm0)
if pause <= 0 then return () else do
threadDelay (floor (pause * 1000 * 1000))
return ()
b <- you (loseU opts)
if b then return () else do -- ignore if you "lose" the message.
a <- optMangle (mangleU opts) (mangler opts) a
b <- you (dupU opts)
if b then do -- send twice, please
k a
k a
else do
k a
tm <- getCurrentTime
putMVar tmVar tm
return ()
tm <- getCurrentTime
tmVar1 <- newMVar tm
tmVar2 <- newMVar tm
forkIO $ forever $ do
msg <- fromBridge lhs
unrely tmVar1 lhsOut msg $ toBridge rhs
forever $ do
msg <- fromBridge rhs
unrely tmVar2 rhsOut msg $ toBridge lhs
|
andygill/lambda-bridge
|
Network/LambdaBridge/Bridge.hs
|
Haskell
|
bsd-3-clause
| 6,133
|
import qualified Network.HTTP.Types as HTTP
import qualified Network.HTTP.Conduit as HTTP
import Aws
import qualified Aws.S3 as S3
import qualified Aws.SimpleDb as Sdb
import qualified Aws.Sqs as Sqs
import qualified Aws.Ses as Ses
|
jgm/aws
|
ghci.hs
|
Haskell
|
bsd-3-clause
| 292
|
------------------------------------------------------------------------
-- |
-- Module : ALife.Creatur.Wain.UIVector.Cluster.GeneratePopulation
-- Copyright : (c) Amy de Buitléir 2012-2016
-- License : BSD-style
-- Maintainer : amy@nualeargais.ie
-- Stability : experimental
-- Portability : portable
--
-- ???
--
------------------------------------------------------------------------
{-# LANGUAGE TypeFamilies #-}
import ALife.Creatur (agentId)
import ALife.Creatur.Wain.UIVector.Cluster.Experiment (PatternWain,
randomPatternWain, printStats)
import ALife.Creatur.Wain (adjustEnergy)
import ALife.Creatur.Wain.Pretty (pretty)
import ALife.Creatur.Wain.PersistentStatistics (clearStats)
import ALife.Creatur.Wain.Statistics (Statistic, stats, summarise)
import ALife.Creatur.Wain.UIVector.Cluster.Universe (Universe(..),
writeToLog, store, loadUniverse, uClassifierSizeRange,
uInitialPopulationSize, uStatsFile)
import Control.Lens
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Random (evalRandIO)
import Control.Monad.Random.Class (getRandomR)
import Control.Monad.State.Lazy (StateT, evalStateT, get)
introduceRandomAgent
:: String -> StateT (Universe PatternWain) IO [Statistic]
introduceRandomAgent name = do
u <- get
classifierSize
<- liftIO . evalRandIO . getRandomR . view uClassifierSizeRange $ u
agent
<- liftIO . evalRandIO $
randomPatternWain name u classifierSize
-- Make the first generation a little hungry so they start learning
-- immediately.
-- TODO: Make the amount configurable.
let (agent', _) = adjustEnergy 0.8 agent
writeToLog $ "GeneratePopulation: Created " ++ agentId agent'
writeToLog $ "GeneratePopulation: Stats " ++ pretty (stats agent')
store agent'
return (stats agent')
introduceRandomAgents
:: [String] -> StateT (Universe PatternWain) IO ()
introduceRandomAgents ns = do
xs <- mapM introduceRandomAgent ns
let yss = summarise xs
printStats yss
statsFile <- use uStatsFile
clearStats statsFile
main :: IO ()
main = do
u <- loadUniverse
let ns = map (("Founder" ++) . show) [1..(view uInitialPopulationSize u)]
print ns
evalStateT (introduceRandomAgents ns) u
|
mhwombat/exp-uivector-cluster-wains
|
src/ALife/Creatur/Wain/UIVector/Cluster/GeneratePopulation.hs
|
Haskell
|
bsd-3-clause
| 2,203
|
{-# LANGUAGE QuasiQuotes #-}
module Cauterize.GHC7.Generate.GenStack
( generateOutput
) where
import Cauterize.GHC7.Options
import Cauterize.GHC7.Generate.Utils
import qualified Cauterize.Specification as Spec
import System.FilePath.Posix
import Data.String.Interpolate.Util
import Data.String.Interpolate.IsString
generateOutput :: Spec.Specification -> CautGHC7Opts -> IO ()
generateOutput _ opts = do
stackDir <- createPath [out]
let stackPath = stackDir `combine` "stack.yaml"
let stackData = stackYamlTempl
writeFile stackPath stackData
where
out = outputDirectory opts
stackYamlTempl :: String
stackYamlTempl = unindent [i|
flags: {}
packages:
- '.'
- location:
git: https://github.com/cauterize-tools/cauterize.git
commit: cff794399744a4038c0f2b2dfbc4c43593d2bcbd
- location:
git: https://github.com/aisamanra/s-cargot.git
commit: 1628a7c2913fc5e72ab6ea9a813762bf86d47d49
- location:
git: https://github.com/cauterize-tools/crucible.git
commit: 7f8147e0fbfe210df9e6c83f4c0d48c3de4ed9f7
- location:
git: https://github.com/cauterize-tools/caut-ghc7-ref.git
commit: 36f28786cd97cf9e810649d75270b2ac0cb8d1a5
extra-deps:
- cereal-plus-0.4.0
resolver: lts-2.21|]
|
cauterize-tools/caut-ghc7-ref
|
src/Cauterize/GHC7/Generate/GenStack.hs
|
Haskell
|
bsd-3-clause
| 1,274
|
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Singletons.BoxUnBox where
import Data.Singletons.TH
import Data.Singletons.SuppressUnusedWarnings
$(singletons [d|
data Box a = FBox a
unBox :: Box a -> a
unBox (FBox a) = a
|])
|
int-index/singletons
|
tests/compile-and-dump/Singletons/BoxUnBox.hs
|
Haskell
|
bsd-3-clause
| 240
|
-- © 2001, 2002 Peter Thiemann
module Main where
import WASH.CGI.CGI hiding (head, map, span, div)
main =
run $
standardQuery "Upload File" $
do text "Enter file to upload "
fileH <- checkedFileInputField refuseUnnamed empty
submit fileH display (fieldVALUE "UPLOAD")
refuseUnnamed mf =
do FileReference {fileReferenceExternalName=frn} <- mf
if null frn then fail "" else mf
display :: InputField FileReference VALID -> CGI ()
display fileH =
let fileRef = value fileH in
standardQuery "Upload Successful" $
do p (text (show fileRef))
p (do text "Check file contents "
submit0 (tell fileRef) (fieldVALUE "Show contents"))
|
nh2/WashNGo
|
Examples/old/Upload.hs
|
Haskell
|
bsd-3-clause
| 667
|
module IptAdmin.Config where
import Control.Monad.Error
import Data.ConfigFile
import IptAdmin.Types
import System.FilePath.Posix
cONFpATHd :: String
cONFpATHd = "/etc/iptadmin"
cONFIGURATIONf :: String
cONFIGURATIONf = "iptadmin.conf"
getConfig :: ErrorT String IO IptAdminConfig
getConfig = do
configE <- liftIO $ runErrorT $ do
cp <- join $ liftIO $ readfile emptyCP (cONFpATHd </> cONFIGURATIONf)
saveCommand <- get cp "DEFAULT" "save command"
port <- get cp "DEFAULT" "port"
pamName <- get cp "DEFAULT" "pam name"
sslEnabled <- get cp "DEFAULT" "ssl"
if sslEnabled then do
createPair <- get cp "SSL" "create pair if does not exist"
crtPath <- get cp "SSL" "crt path"
keyPath <- get cp "SSL" "key path"
return $ IptAdminConfig saveCommand
port
pamName
$ Just $ SSLConfig createPair
crtPath
keyPath
else
return $ IptAdminConfig saveCommand
port
pamName
Nothing
case configE of
Left (_, err) -> throwError ("Error on reading " ++ cONFpATHd </> cONFIGURATIONf ++ "\n" ++ err)
Right config -> return config
|
etarasov/iptadmin
|
src/IptAdmin/Config.hs
|
Haskell
|
bsd-3-clause
| 1,482
|
{-# LANGUAGE CPP, FlexibleInstances, OverloadedStrings, Rank2Types #-}
#ifdef GENERICS
{-# LANGUAGE DefaultSignatures, TypeOperators, KindSignatures, FlexibleContexts,
MultiParamTypeClasses, UndecidableInstances, ScopedTypeVariables #-}
#endif
module Data.Csv.Conversion
(
-- * Type conversion
Only(..)
, FromRecord(..)
, FromNamedRecord(..)
, ToNamedRecord(..)
, FromField(..)
, ToRecord(..)
, ToField(..)
-- * Parser
, Result(..)
, Parser
, parse
-- * Accessors
, (.!)
, (.:)
, (.=)
, record
, namedRecord
-- * Util
, lengthMismatch
) where
import Control.Applicative
import Control.Monad
import Data.Attoparsec.Char8 (double, number, parseOnly)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy as L
import qualified Data.HashMap.Lazy as HM
import Data.Int
import qualified Data.Map as M
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.Encoding as LT
import Data.Traversable
import Data.Vector (Vector, (!))
import qualified Data.Vector as V
import Data.Word
import GHC.Float (double2Float)
import Prelude hiding (takeWhile)
import Data.Csv.Conversion.Internal
import Data.Csv.Types
#ifdef GENERICS
import GHC.Generics
import qualified Data.IntMap as IM
#endif
------------------------------------------------------------------------
-- Type conversion
------------------------------------------------------------------------
-- Index-based conversion
-- | A type that can be converted from a single CSV record, with the
-- possibility of failure.
--
-- When writing an instance, use 'empty', 'mzero', or 'fail' to make a
-- conversion fail, e.g. if a 'Record' has the wrong number of
-- columns.
--
-- Given this example data:
--
-- > John,56
-- > Jane,55
--
-- here's an example type and instance:
--
-- @data Person = Person { name :: Text, age :: Int }
--
-- instance FromRecord Person where
-- parseRecord v
-- | 'V.length' v == 2 = Person '<$>'
-- v '.!' 0 '<*>'
-- v '.!' 1
-- | otherwise = mzero
-- @
class FromRecord a where
parseRecord :: Record -> Parser a
#ifdef GENERICS
default parseRecord :: (Generic a, GFromRecord (Rep a)) => Record -> Parser a
parseRecord r = to <$> gparseRecord r
#endif
-- | Haskell lacks a single-element tuple type, so if you CSV data
-- with just one column you can use the 'Only' type to represent a
-- single-column result.
newtype Only a = Only {
fromOnly :: a
} deriving (Eq, Ord, Read, Show)
-- | A type that can be converted to a single CSV record.
--
-- An example type and instance:
--
-- @data Person = Person { name :: Text, age :: Int }
--
-- instance ToRecord Person where
-- toRecord (Person name age) = 'record' [
-- 'toField' name, 'toField' age]
-- @
--
-- Outputs data on this form:
--
-- > John,56
-- > Jane,55
class ToRecord a where
toRecord :: a -> Record
#ifdef GENERICS
default toRecord :: (Generic a, GToRecord (Rep a) Field) => a -> Record
toRecord = V.fromList . gtoRecord . from
#endif
instance FromField a => FromRecord (Only a) where
parseRecord v
| n == 1 = Only <$> parseField (V.unsafeIndex v 0)
| otherwise = lengthMismatch 1 v
where
n = V.length v
-- TODO: Check if we want all toRecord conversions to be stricter.
instance ToField a => ToRecord (Only a) where
toRecord = V.singleton . toField . fromOnly
instance (FromField a, FromField b) => FromRecord (a, b) where
parseRecord v
| n == 2 = (,) <$> parseField (V.unsafeIndex v 0)
<*> parseField (V.unsafeIndex v 1)
| otherwise = lengthMismatch 2 v
where
n = V.length v
instance (ToField a, ToField b) => ToRecord (a, b) where
toRecord (a, b) = V.fromList [toField a, toField b]
instance (FromField a, FromField b, FromField c) => FromRecord (a, b, c) where
parseRecord v
| n == 3 = (,,) <$> parseField (V.unsafeIndex v 0)
<*> parseField (V.unsafeIndex v 1)
<*> parseField (V.unsafeIndex v 2)
| otherwise = lengthMismatch 3 v
where
n = V.length v
instance (ToField a, ToField b, ToField c) =>
ToRecord (a, b, c) where
toRecord (a, b, c) = V.fromList [toField a, toField b, toField c]
instance (FromField a, FromField b, FromField c, FromField d) =>
FromRecord (a, b, c, d) where
parseRecord v
| n == 4 = (,,,) <$> parseField (V.unsafeIndex v 0)
<*> parseField (V.unsafeIndex v 1)
<*> parseField (V.unsafeIndex v 2)
<*> parseField (V.unsafeIndex v 3)
| otherwise = lengthMismatch 4 v
where
n = V.length v
instance (ToField a, ToField b, ToField c, ToField d) =>
ToRecord (a, b, c, d) where
toRecord (a, b, c, d) = V.fromList [
toField a, toField b, toField c, toField d]
instance (FromField a, FromField b, FromField c, FromField d, FromField e) =>
FromRecord (a, b, c, d, e) where
parseRecord v
| n == 5 = (,,,,) <$> parseField (V.unsafeIndex v 0)
<*> parseField (V.unsafeIndex v 1)
<*> parseField (V.unsafeIndex v 2)
<*> parseField (V.unsafeIndex v 3)
<*> parseField (V.unsafeIndex v 4)
| otherwise = lengthMismatch 5 v
where
n = V.length v
instance (ToField a, ToField b, ToField c, ToField d, ToField e) =>
ToRecord (a, b, c, d, e) where
toRecord (a, b, c, d, e) = V.fromList [
toField a, toField b, toField c, toField d, toField e]
instance (FromField a, FromField b, FromField c, FromField d, FromField e,
FromField f) =>
FromRecord (a, b, c, d, e, f) where
parseRecord v
| n == 6 = (,,,,,) <$> parseField (V.unsafeIndex v 0)
<*> parseField (V.unsafeIndex v 1)
<*> parseField (V.unsafeIndex v 2)
<*> parseField (V.unsafeIndex v 3)
<*> parseField (V.unsafeIndex v 4)
<*> parseField (V.unsafeIndex v 5)
| otherwise = lengthMismatch 6 v
where
n = V.length v
instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f) =>
ToRecord (a, b, c, d, e, f) where
toRecord (a, b, c, d, e, f) = V.fromList [
toField a, toField b, toField c, toField d, toField e, toField f]
instance (FromField a, FromField b, FromField c, FromField d, FromField e,
FromField f, FromField g) =>
FromRecord (a, b, c, d, e, f, g) where
parseRecord v
| n == 7 = (,,,,,,) <$> parseField (V.unsafeIndex v 0)
<*> parseField (V.unsafeIndex v 1)
<*> parseField (V.unsafeIndex v 2)
<*> parseField (V.unsafeIndex v 3)
<*> parseField (V.unsafeIndex v 4)
<*> parseField (V.unsafeIndex v 5)
<*> parseField (V.unsafeIndex v 6)
| otherwise = lengthMismatch 7 v
where
n = V.length v
instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f,
ToField g) =>
ToRecord (a, b, c, d, e, f, g) where
toRecord (a, b, c, d, e, f, g) = V.fromList [
toField a, toField b, toField c, toField d, toField e, toField f,
toField g]
lengthMismatch :: Int -> Record -> Parser a
lengthMismatch expected v =
fail $ "cannot unpack array of length " ++
show n ++ " into a " ++ desired ++ ". Input record: " ++
show v
where
n = V.length v
desired | expected == 1 = "Only"
| expected == 2 = "pair"
| otherwise = show expected ++ "-tuple"
instance FromField a => FromRecord [a] where
parseRecord = traverse parseField . V.toList
instance ToField a => ToRecord [a] where
toRecord = V.fromList . map toField
instance FromField a => FromRecord (V.Vector a) where
parseRecord = traverse parseField
instance ToField a => ToRecord (Vector a) where
toRecord = V.map toField
------------------------------------------------------------------------
-- Name-based conversion
-- | A type that can be converted from a single CSV record, with the
-- possibility of failure.
--
-- When writing an instance, use 'empty', 'mzero', or 'fail' to make a
-- conversion fail, e.g. if a 'Record' has the wrong number of
-- columns.
--
-- Given this example data:
--
-- > name,age
-- > John,56
-- > Jane,55
--
-- here's an example type and instance:
--
-- @{-\# LANGUAGE OverloadedStrings \#-}
--
-- data Person = Person { name :: Text, age :: Int }
--
-- instance FromRecord Person where
-- parseNamedRecord m = Person '<$>'
-- m '.:' \"name\" '<*>'
-- m '.:' \"age\"
-- @
--
-- Note the use of the @OverloadedStrings@ language extension which
-- enables 'B8.ByteString' values to be written as string literals.
class FromNamedRecord a where
parseNamedRecord :: NamedRecord -> Parser a
#ifdef GENERICS
default parseNamedRecord :: (Generic a, GFromNamedRecord (Rep a)) => NamedRecord -> Parser a
parseNamedRecord r = to <$> gparseNamedRecord r
#endif
-- | A type that can be converted to a single CSV record.
--
-- An example type and instance:
--
-- @data Person = Person { name :: Text, age :: Int }
--
-- instance ToRecord Person where
-- toNamedRecord (Person name age) = 'namedRecord' [
-- \"name\" '.=' name, \"age\" '.=' age]
-- @
class ToNamedRecord a where
toNamedRecord :: a -> NamedRecord
#ifdef GENERICS
default toNamedRecord :: (Generic a, GToRecord (Rep a) (B.ByteString, B.ByteString)) => a -> NamedRecord
toNamedRecord = namedRecord . gtoRecord . from
#endif
instance FromField a => FromNamedRecord (M.Map B.ByteString a) where
parseNamedRecord m = M.fromList <$>
(traverse parseSnd $ HM.toList m)
where parseSnd (name, s) = (,) <$> pure name <*> parseField s
instance ToField a => ToNamedRecord (M.Map B.ByteString a) where
toNamedRecord = HM.fromList . map (\ (k, v) -> (k, toField v)) . M.toList
instance FromField a => FromNamedRecord (HM.HashMap B.ByteString a) where
parseNamedRecord m = traverse (\ s -> parseField s) m
instance ToField a => ToNamedRecord (HM.HashMap B.ByteString a) where
toNamedRecord = HM.map toField
------------------------------------------------------------------------
-- Individual field conversion
-- | A type that can be converted from a single CSV field, with the
-- possibility of failure.
--
-- When writing an instance, use 'empty', 'mzero', or 'fail' to make a
-- conversion fail, e.g. if a 'Field' can't be converted to the given
-- type.
--
-- Example type and instance:
--
-- @{-\# LANGUAGE OverloadedStrings \#-}
--
-- data Color = Red | Green | Blue
--
-- instance FromField Color where
-- parseField s
-- | s == \"R\" = pure Red
-- | s == \"G\" = pure Green
-- | s == \"B\" = pure Blue
-- | otherwise = mzero
-- @
class FromField a where
parseField :: Field -> Parser a
-- | A type that can be converted to a single CSV field.
--
-- Example type and instance:
--
-- @{-\# LANGUAGE OverloadedStrings \#-}
--
-- data Color = Red | Green | Blue
--
-- instance ToField Color where
-- toField Red = \"R\"
-- toField Green = \"G\"
-- toField Blue = \"B\"
-- @
class ToField a where
toField :: a -> Field
instance FromField Char where
parseField s
| T.compareLength t 1 == EQ = pure (T.head t)
| otherwise = typeError "Char" s Nothing
where t = T.decodeUtf8 s
{-# INLINE parseField #-}
instance ToField Char where
toField = toField . T.encodeUtf8 . T.singleton
{-# INLINE toField #-}
instance FromField Double where
parseField = parseDouble
{-# INLINE parseField #-}
instance ToField Double where
toField = realFloat
{-# INLINE toField #-}
instance FromField Float where
parseField s = double2Float <$> parseDouble s
{-# INLINE parseField #-}
instance ToField Float where
toField = realFloat
{-# INLINE toField #-}
parseDouble :: B.ByteString -> Parser Double
parseDouble s = case parseOnly double s of
Left err -> typeError "Double" s (Just err)
Right n -> pure n
{-# INLINE parseDouble #-}
instance FromField Int where
parseField = parseIntegral "Int"
{-# INLINE parseField #-}
instance ToField Int where
toField = decimal
{-# INLINE toField #-}
instance FromField Integer where
parseField = parseIntegral "Integer"
{-# INLINE parseField #-}
instance ToField Integer where
toField = decimal
{-# INLINE toField #-}
instance FromField Int8 where
parseField = parseIntegral "Int8"
{-# INLINE parseField #-}
instance ToField Int8 where
toField = decimal
{-# INLINE toField #-}
instance FromField Int16 where
parseField = parseIntegral "Int16"
{-# INLINE parseField #-}
instance ToField Int16 where
toField = decimal
{-# INLINE toField #-}
instance FromField Int32 where
parseField = parseIntegral "Int32"
{-# INLINE parseField #-}
instance ToField Int32 where
toField = decimal
{-# INLINE toField #-}
instance FromField Int64 where
parseField = parseIntegral "Int64"
{-# INLINE parseField #-}
instance ToField Int64 where
toField = decimal
{-# INLINE toField #-}
instance FromField Word where
parseField = parseIntegral "Word"
{-# INLINE parseField #-}
instance ToField Word where
toField = decimal
{-# INLINE toField #-}
instance FromField Word8 where
parseField = parseIntegral "Word8"
{-# INLINE parseField #-}
instance ToField Word8 where
toField = decimal
{-# INLINE toField #-}
instance FromField Word16 where
parseField = parseIntegral "Word16"
{-# INLINE parseField #-}
instance ToField Word16 where
toField = decimal
{-# INLINE toField #-}
instance FromField Word32 where
parseField = parseIntegral "Word32"
{-# INLINE parseField #-}
instance ToField Word32 where
toField = decimal
{-# INLINE toField #-}
instance FromField Word64 where
parseField = parseIntegral "Word64"
{-# INLINE parseField #-}
instance ToField Word64 where
toField = decimal
{-# INLINE toField #-}
-- TODO: Optimize
escape :: B.ByteString -> B.ByteString
escape s
| B.find (\ b -> b == dquote || b == comma || b == nl || b == cr ||
b == sp) s == Nothing = s
| otherwise =
B.concat ["\"",
B.concatMap
(\ b -> if b == dquote then "\"\"" else B.singleton b) s,
"\""]
where
dquote = 34
comma = 44
nl = 10
cr = 13
sp = 32
instance FromField B.ByteString where
parseField = pure
{-# INLINE parseField #-}
instance ToField B.ByteString where
toField = escape
{-# INLINE toField #-}
instance FromField L.ByteString where
parseField s = pure (L.fromChunks [s])
{-# INLINE parseField #-}
instance ToField L.ByteString where
toField = toField . B.concat . L.toChunks
{-# INLINE toField #-}
-- | Assumes UTF-8 encoding.
instance FromField T.Text where
parseField = pure . T.decodeUtf8
{-# INLINE parseField #-}
-- | Uses UTF-8 encoding.
instance ToField T.Text where
toField = toField . T.encodeUtf8
{-# INLINE toField #-}
-- | Assumes UTF-8 encoding.
instance FromField LT.Text where
parseField s = pure (LT.fromChunks [T.decodeUtf8 s])
{-# INLINE parseField #-}
-- | Uses UTF-8 encoding.
instance ToField LT.Text where
toField = toField . B.concat . L.toChunks . LT.encodeUtf8
{-# INLINE toField #-}
-- | Assumes UTF-8 encoding.
instance FromField [Char] where
parseField = fmap T.unpack . parseField
{-# INLINE parseField #-}
-- | Uses UTF-8 encoding.
instance ToField [Char] where
toField = toField . T.pack
{-# INLINE toField #-}
parseIntegral :: Integral a => String -> B.ByteString -> Parser a
parseIntegral typ s = case parseOnly number s of
Left err -> typeError typ s (Just err)
Right n -> pure (floor n)
{-# INLINE parseIntegral #-}
typeError :: String -> B.ByteString -> Maybe String -> Parser a
typeError typ s mmsg =
fail $ "expected " ++ typ ++ ", got " ++ show (B8.unpack s) ++ cause
where
cause = case mmsg of
Just msg -> " (" ++ msg ++ ")"
Nothing -> ""
------------------------------------------------------------------------
-- Constructors and accessors
-- | Retrieve the /n/th field in the given record. The result is
-- 'empty' if the value cannot be converted to the desired type.
-- Raises an exception if the index is out of bounds.
(.!) :: FromField a => Record -> Int -> Parser a
v .! idx = parseField (v ! idx)
{-# INLINE (.!) #-}
-- | Retrieve a field in the given record by name. The result is
-- 'empty' if the field is missing or if the value cannot be converted
-- to the desired type.
(.:) :: FromField a => NamedRecord -> B.ByteString -> Parser a
m .: name = maybe (fail err) parseField $ HM.lookup name m
where err = "no field named " ++ show (B8.unpack name)
{-# INLINE (.:) #-}
-- | Construct a pair from a name and a value. For use with
-- 'namedRecord'.
(.=) :: ToField a => B.ByteString -> a -> (B.ByteString, B.ByteString)
name .= val = (name, toField val)
{-# INLINE (.=) #-}
-- | Construct a record from a list of 'B.ByteString's. Use 'toField'
-- to convert values to 'B.ByteString's for use with 'record'.
record :: [B.ByteString] -> Record
record = V.fromList
-- | Construct a named record from a list of name-value 'B.ByteString'
-- pairs. Use '.=' to construct such a pair from a name and a value.
namedRecord :: [(B.ByteString, B.ByteString)] -> NamedRecord
namedRecord = HM.fromList
------------------------------------------------------------------------
-- Parser for converting records to data types
-- | The result of running a 'Parser'.
data Result a = Error String
| Success a
deriving (Eq, Show)
instance Functor Result where
fmap f (Success a) = Success (f a)
fmap _ (Error err) = Error err
{-# INLINE fmap #-}
instance Monad Result where
return = Success
{-# INLINE return #-}
Success a >>= k = k a
Error err >>= _ = Error err
{-# INLINE (>>=) #-}
instance Applicative Result where
pure = return
{-# INLINE pure #-}
(<*>) = ap
{-# INLINE (<*>) #-}
instance MonadPlus Result where
mzero = fail "mzero"
{-# INLINE mzero #-}
mplus a@(Success _) _ = a
mplus _ b = b
{-# INLINE mplus #-}
instance Alternative Result where
empty = mzero
{-# INLINE empty #-}
(<|>) = mplus
{-# INLINE (<|>) #-}
instance Monoid (Result a) where
mempty = fail "mempty"
{-# INLINE mempty #-}
mappend = mplus
{-# INLINE mappend #-}
-- | Failure continuation.
type Failure f r = String -> f r
-- | Success continuation.
type Success a f r = a -> f r
-- | Conversion of a field to a value might fail e.g. if the field is
-- malformed. This possibility is captured by the 'Parser' type, which
-- lets you compose several field conversions together in such a way
-- that if any of them fail, the whole record conversion fails.
newtype Parser a = Parser {
runParser :: forall f r.
Failure f r
-> Success a f r
-> f r
}
instance Monad Parser where
m >>= g = Parser $ \kf ks -> let ks' a = runParser (g a) kf ks
in runParser m kf ks'
{-# INLINE (>>=) #-}
return a = Parser $ \_kf ks -> ks a
{-# INLINE return #-}
fail msg = Parser $ \kf _ks -> kf msg
{-# INLINE fail #-}
instance Functor Parser where
fmap f m = Parser $ \kf ks -> let ks' a = ks (f a)
in runParser m kf ks'
{-# INLINE fmap #-}
instance Applicative Parser where
pure = return
{-# INLINE pure #-}
(<*>) = apP
{-# INLINE (<*>) #-}
instance Alternative Parser where
empty = fail "empty"
{-# INLINE empty #-}
(<|>) = mplus
{-# INLINE (<|>) #-}
instance MonadPlus Parser where
mzero = fail "mzero"
{-# INLINE mzero #-}
mplus a b = Parser $ \kf ks -> let kf' _ = runParser b kf ks
in runParser a kf' ks
{-# INLINE mplus #-}
instance Monoid (Parser a) where
mempty = fail "mempty"
{-# INLINE mempty #-}
mappend = mplus
{-# INLINE mappend #-}
apP :: Parser (a -> b) -> Parser a -> Parser b
apP d e = do
b <- d
a <- e
return (b a)
{-# INLINE apP #-}
-- | Run a 'Parser'.
parse :: Parser a -> Result a
parse p = runParser p Error Success
{-# INLINE parse #-}
#ifdef GENERICS
class GFromRecord f where
gparseRecord :: Record -> Parser (f p)
instance GFromRecordSum f Record => GFromRecord (M1 i n f) where
gparseRecord v =
case (IM.lookup n gparseRecordSum) of
Nothing -> lengthMismatch n v
Just p -> M1 <$> p v
where
n = V.length v
class GFromNamedRecord f where
gparseNamedRecord :: NamedRecord -> Parser (f p)
instance GFromRecordSum f NamedRecord => GFromNamedRecord (M1 i n f) where
gparseNamedRecord v =
foldr (\f p -> p <|> M1 <$> f v) empty (IM.elems gparseRecordSum)
class GFromRecordSum f r where
gparseRecordSum :: IM.IntMap (r -> Parser (f p))
instance (GFromRecordSum a r, GFromRecordSum b r) => GFromRecordSum (a :+: b) r where
gparseRecordSum =
IM.unionWith (\a b r -> a r <|> b r)
(fmap (L1 <$>) <$> gparseRecordSum)
(fmap (R1 <$>) <$> gparseRecordSum)
instance GFromRecordProd f r => GFromRecordSum (M1 i n f) r where
gparseRecordSum = IM.singleton n (fmap (M1 <$>) f)
where
(n, f) = gparseRecordProd 0
class GFromRecordProd f r where
gparseRecordProd :: Int -> (Int, r -> Parser (f p))
instance GFromRecordProd U1 r where
gparseRecordProd n = (n, const (pure U1))
instance (GFromRecordProd a r, GFromRecordProd b r) => GFromRecordProd (a :*: b) r where
gparseRecordProd n0 = (n2, f)
where
f r = (:*:) <$> fa r <*> fb r
(n1, fa) = gparseRecordProd n0
(n2, fb) = gparseRecordProd n1
instance GFromRecordProd f Record => GFromRecordProd (M1 i n f) Record where
gparseRecordProd n = fmap (M1 <$>) <$> gparseRecordProd n
instance FromField a => GFromRecordProd (K1 i a) Record where
gparseRecordProd n = (n + 1, \v -> K1 <$> parseField (V.unsafeIndex v n))
data Proxy s (f :: * -> *) a = Proxy
instance (FromField a, Selector s) => GFromRecordProd (M1 S s (K1 i a)) NamedRecord where
gparseRecordProd n = (n + 1, \v -> (M1 . K1) <$> v .: name)
where
name = T.encodeUtf8 (T.pack (selName (Proxy :: Proxy s f a)))
class GToRecord a f where
gtoRecord :: a p -> [f]
instance GToRecord U1 f where
gtoRecord U1 = []
instance (GToRecord a f, GToRecord b f) => GToRecord (a :*: b) f where
gtoRecord (a :*: b) = gtoRecord a ++ gtoRecord b
instance (GToRecord a f, GToRecord b f) => GToRecord (a :+: b) f where
gtoRecord (L1 a) = gtoRecord a
gtoRecord (R1 b) = gtoRecord b
instance GToRecord a f => GToRecord (M1 D c a) f where
gtoRecord (M1 a) = gtoRecord a
instance GToRecord a f => GToRecord (M1 C c a) f where
gtoRecord (M1 a) = gtoRecord a
instance GToRecord a Field => GToRecord (M1 S c a) Field where
gtoRecord (M1 a) = gtoRecord a
instance ToField a => GToRecord (K1 i a) Field where
gtoRecord (K1 a) = [toField a]
instance (ToField a, Selector s) => GToRecord (M1 S s (K1 i a)) (B.ByteString, B.ByteString) where
gtoRecord m@(M1 (K1 a)) = [T.encodeUtf8 (T.pack (selName m)) .= toField a]
#endif
|
sjoerdvisscher/cassava
|
Data/Csv/Conversion.hs
|
Haskell
|
bsd-3-clause
| 24,266
|
{-# OPTIONS_GHC -F -pgmF htfpp #-}
module Ebitor.Rope.CursorTest (htf_thisModulesTests) where
import Data.List (intercalate)
import Data.Maybe (fromJust)
import Test.Framework
import Ebitor.Rope (Rope)
import Ebitor.Rope.Cursor
import Ebitor.RopeUtils
import qualified Ebitor.Rope as R
madWorld = "it's a mad mad mad mad world"
patchOfOldSnow = packRope $ intercalate "\n" [
"\tA Patch of Old Snow" -- 20
, "" -- 0
, "There's a patch of old snow in a corner" -- 39
, "That I should have guessed" -- 26
, "Was a blow-away paper the rain" -- 30
, "Had brought to rest." -- 20
, "" -- 0
, "It is speckled with grime as if" -- 31
, "Small print overspread it," -- 26
, "The news of a day I've forgotten--" -- 34
, "If I ever read it." -- 18
, "" -- 0
, "- Robert Frost" -- 14
]
test_positionForCursorLF =
assertEqual (27, Cursor (3, 6))
(R.positionForCursor patchOfOldSnow (Cursor (3, 6)))
test_positionForIndexLF =
assertEqual (27, Cursor (3, 6))
(R.positionForIndex patchOfOldSnow 27)
test_positionForCursorPastEOL =
assertEqual (61, Cursor (3, 40))
(R.positionForCursor patchOfOldSnow (Cursor (3, 100)))
test_positionForCursorAtEOL =
assertEqual (61, Cursor (3, 40))
(R.positionForCursor patchOfOldSnow (Cursor (3, 40)))
test_positionForCursorBeforeLine1 =
assertEqual (0, Cursor (1, 1))
(R.positionForCursor patchOfOldSnow (Cursor (1, 0)))
test_positionForCursorBeforeLine2 =
assertEqual (21, Cursor (2, 1))
(R.positionForCursor patchOfOldSnow (Cursor (2, -1000)))
test_positionForCursorInTab =
assertEqual (1, Cursor (1, 9))
(R.positionForCursor patchOfOldSnow (Cursor (1, 4)))
test_positionForCursorBeforeDocument =
assertEqual (0, Cursor (1, 1))
(R.positionForCursor patchOfOldSnow (Cursor (0, 4)))
test_positionForIndexBeforeDocument =
assertEqual (0, Cursor (1, 1))
(R.positionForIndex patchOfOldSnow (-10))
test_positionForCursorPastDocument =
assertEqual (R.length patchOfOldSnow, Cursor (13, 15))
(R.positionForCursor patchOfOldSnow (Cursor (1000, 1)))
test_positionForIndexPastDocument =
assertEqual (R.length patchOfOldSnow, Cursor (13, 15))
(R.positionForIndex patchOfOldSnow (R.length patchOfOldSnow + 50))
|
benekastah/ebitor
|
test/Ebitor/Rope/CursorTest.hs
|
Haskell
|
bsd-3-clause
| 2,415
|
{-# LANGUAGE OverloadedStrings #-}
module Themes
( InternalTheme(..)
, defaultTheme
, internalThemes
, lookupTheme
, themeDocs
-- * Attribute names
, timeAttr
, channelHeaderAttr
, channelListHeaderAttr
, currentChannelNameAttr
, unreadChannelAttr
, mentionsChannelAttr
, urlAttr
, codeAttr
, emailAttr
, emojiAttr
, channelNameAttr
, clientMessageAttr
, clientHeaderAttr
, clientEmphAttr
, clientStrongAttr
, dateTransitionAttr
, newMessageTransitionAttr
, gapMessageAttr
, errorMessageAttr
, helpAttr
, helpEmphAttr
, channelSelectPromptAttr
, channelSelectMatchAttr
, completionAlternativeListAttr
, completionAlternativeCurrentAttr
, dialogAttr
, dialogEmphAttr
, recentMarkerAttr
, replyParentAttr
, loadMoreAttr
, urlListSelectedAttr
, messageSelectAttr
, messageSelectStatusAttr
, misspellingAttr
, editedMarkingAttr
, editedRecentlyMarkingAttr
-- * Username formatting
, colorUsername
)
where
import Prelude ()
import Prelude.MH
import Brick
import Brick.Themes
import Brick.Widgets.List
import Brick.Widgets.Skylighting ( attrNameForTokenType
, attrMappingsForStyle
, highlightedCodeBlockAttr
)
import Data.Hashable ( hash )
import qualified Data.Map as M
import qualified Data.Text as T
import Graphics.Vty
import qualified Skylighting.Styles as Sky
import Skylighting.Types ( TokenType(..) )
helpAttr :: AttrName
helpAttr = "help"
helpEmphAttr :: AttrName
helpEmphAttr = "helpEmphasis"
recentMarkerAttr :: AttrName
recentMarkerAttr = "recentChannelMarker"
replyParentAttr :: AttrName
replyParentAttr = "replyParentPreview"
loadMoreAttr :: AttrName
loadMoreAttr = "loadMoreMessages"
urlListSelectedAttr :: AttrName
urlListSelectedAttr = "urlListCursor"
messageSelectAttr :: AttrName
messageSelectAttr = "messageSelectCursor"
editedMarkingAttr :: AttrName
editedMarkingAttr = "editedMarking"
editedRecentlyMarkingAttr :: AttrName
editedRecentlyMarkingAttr = "editedRecentlyMarking"
dialogAttr :: AttrName
dialogAttr = "dialog"
dialogEmphAttr :: AttrName
dialogEmphAttr = "dialogEmphasis"
channelSelectMatchAttr :: AttrName
channelSelectMatchAttr = "channelSelectMatch"
channelSelectPromptAttr :: AttrName
channelSelectPromptAttr = "channelSelectPrompt"
completionAlternativeListAttr :: AttrName
completionAlternativeListAttr = "tabCompletionAlternative"
completionAlternativeCurrentAttr :: AttrName
completionAlternativeCurrentAttr = "tabCompletionCursor"
timeAttr :: AttrName
timeAttr = "time"
channelHeaderAttr :: AttrName
channelHeaderAttr = "channelHeader"
channelListHeaderAttr :: AttrName
channelListHeaderAttr = "channelListSectionHeader"
currentChannelNameAttr :: AttrName
currentChannelNameAttr = "currentChannelName"
channelNameAttr :: AttrName
channelNameAttr = "channelName"
unreadChannelAttr :: AttrName
unreadChannelAttr = "unreadChannel"
mentionsChannelAttr :: AttrName
mentionsChannelAttr = "channelWithMentions"
dateTransitionAttr :: AttrName
dateTransitionAttr = "dateTransition"
newMessageTransitionAttr :: AttrName
newMessageTransitionAttr = "newMessageTransition"
urlAttr :: AttrName
urlAttr = "url"
codeAttr :: AttrName
codeAttr = "codeBlock"
emailAttr :: AttrName
emailAttr = "email"
emojiAttr :: AttrName
emojiAttr = "emoji"
clientMessageAttr :: AttrName
clientMessageAttr = "clientMessage"
clientHeaderAttr :: AttrName
clientHeaderAttr = "markdownHeader"
clientEmphAttr :: AttrName
clientEmphAttr = "markdownEmph"
clientStrongAttr :: AttrName
clientStrongAttr = "markdownStrong"
errorMessageAttr :: AttrName
errorMessageAttr = "errorMessage"
gapMessageAttr :: AttrName
gapMessageAttr = "gapMessage"
misspellingAttr :: AttrName
misspellingAttr = "misspelling"
messageSelectStatusAttr :: AttrName
messageSelectStatusAttr = "messageSelectStatus"
data InternalTheme =
InternalTheme { internalThemeName :: Text
, internalTheme :: Theme
}
lookupTheme :: Text -> Maybe InternalTheme
lookupTheme n = find ((== n) . internalThemeName) internalThemes
internalThemes :: [InternalTheme]
internalThemes = validateInternalTheme <$>
[ darkColorTheme
, lightColorTheme
]
validateInternalTheme :: InternalTheme -> InternalTheme
validateInternalTheme it =
let un = undocumentedAttrNames (internalTheme it)
in if not $ null un
then error $ "Internal theme " <> show (T.unpack (internalThemeName it)) <>
" references undocumented attribute names: " <> show un
else it
undocumentedAttrNames :: Theme -> [AttrName]
undocumentedAttrNames t =
let noDocs k = isNothing $ attrNameDescription themeDocs k
in filter noDocs (M.keys $ themeDefaultMapping t)
defaultTheme :: InternalTheme
defaultTheme = darkColorTheme
lightColorTheme :: InternalTheme
lightColorTheme = InternalTheme name theme
where
theme = newTheme def lightAttrs
name = "builtin:light"
def = black `on` white
lightAttrs :: [(AttrName, Attr)]
lightAttrs =
let sty = Sky.kate
in [ (timeAttr, fg black)
, (channelHeaderAttr, fg black `withStyle` underline)
, (channelListHeaderAttr, fg cyan)
, (currentChannelNameAttr, black `on` yellow `withStyle` bold)
, (unreadChannelAttr, black `on` cyan `withStyle` bold)
, (mentionsChannelAttr, black `on` red `withStyle` bold)
, (urlAttr, fg brightYellow)
, (emailAttr, fg yellow)
, (codeAttr, fg magenta)
, (emojiAttr, fg yellow)
, (channelNameAttr, fg blue)
, (clientMessageAttr, fg black)
, (clientEmphAttr, fg black `withStyle` bold)
, (clientStrongAttr, fg black `withStyle` bold `withStyle` underline)
, (clientHeaderAttr, fg red `withStyle` bold)
, (dateTransitionAttr, fg green)
, (newMessageTransitionAttr, black `on` yellow)
, (errorMessageAttr, fg red)
, (gapMessageAttr, fg red)
, (helpAttr, black `on` cyan)
, (helpEmphAttr, fg white)
, (channelSelectMatchAttr, black `on` magenta)
, (channelSelectPromptAttr, fg black)
, (completionAlternativeListAttr, white `on` blue)
, (completionAlternativeCurrentAttr, black `on` yellow)
, (dialogAttr, black `on` cyan)
, (dialogEmphAttr, fg white)
, (listSelectedFocusedAttr, black `on` yellow)
, (recentMarkerAttr, fg black `withStyle` bold)
, (loadMoreAttr, black `on` cyan)
, (urlListSelectedAttr, black `on` yellow)
, (messageSelectAttr, black `on` yellow)
, (messageSelectStatusAttr, fg black)
, (misspellingAttr, fg red `withStyle` underline)
, (editedMarkingAttr, fg yellow)
, (editedRecentlyMarkingAttr, black `on` yellow)
] <>
((\(i, a) -> (usernameAttr i, a)) <$> zip [0..] usernameColors) <>
(filter skipBaseCodeblockAttr $ attrMappingsForStyle sty)
darkAttrs :: [(AttrName, Attr)]
darkAttrs =
let sty = Sky.espresso
in [ (timeAttr, fg white)
, (channelHeaderAttr, fg white `withStyle` underline)
, (channelListHeaderAttr, fg cyan)
, (currentChannelNameAttr, black `on` yellow `withStyle` bold)
, (unreadChannelAttr, black `on` cyan `withStyle` bold)
, (mentionsChannelAttr, black `on` brightMagenta `withStyle` bold)
, (urlAttr, fg yellow)
, (emailAttr, fg yellow)
, (codeAttr, fg magenta)
, (emojiAttr, fg yellow)
, (channelNameAttr, fg cyan)
, (clientMessageAttr, fg white)
, (clientEmphAttr, fg white `withStyle` bold)
, (clientStrongAttr, fg white `withStyle` bold `withStyle` underline)
, (clientHeaderAttr, fg red `withStyle` bold)
, (dateTransitionAttr, fg green)
, (newMessageTransitionAttr, fg yellow `withStyle` bold)
, (errorMessageAttr, fg red)
, (gapMessageAttr, black `on` yellow)
, (helpAttr, black `on` cyan)
, (helpEmphAttr, fg white)
, (channelSelectMatchAttr, black `on` magenta)
, (channelSelectPromptAttr, fg white)
, (completionAlternativeListAttr, white `on` blue)
, (completionAlternativeCurrentAttr, black `on` yellow)
, (dialogAttr, black `on` cyan)
, (dialogEmphAttr, fg white)
, (listSelectedFocusedAttr, black `on` yellow)
, (recentMarkerAttr, fg yellow `withStyle` bold)
, (loadMoreAttr, black `on` cyan)
, (urlListSelectedAttr, black `on` yellow)
, (messageSelectAttr, black `on` yellow)
, (messageSelectStatusAttr, fg white)
, (misspellingAttr, fg red `withStyle` underline)
, (editedMarkingAttr, fg yellow)
, (editedRecentlyMarkingAttr, black `on` yellow)
] <>
((\(i, a) -> (usernameAttr i, a)) <$> zip [0..] usernameColors) <>
(filter skipBaseCodeblockAttr $ attrMappingsForStyle sty)
skipBaseCodeblockAttr :: (AttrName, Attr) -> Bool
skipBaseCodeblockAttr = ((/= highlightedCodeBlockAttr) . fst)
darkColorTheme :: InternalTheme
darkColorTheme = InternalTheme name theme
where
theme = newTheme def darkAttrs
name = "builtin:dark"
def = defAttr
usernameAttr :: Int -> AttrName
usernameAttr i = "username" <> (attrName $ show i)
colorUsername :: Text -> Text -> Widget a
colorUsername username display =
withDefAttr (usernameAttr h) $ txt (display)
where h = hash username `mod` length usernameColors
usernameColors :: [Attr]
usernameColors =
[ fg red
, fg green
, fg yellow
, fg blue
, fg magenta
, fg cyan
, fg brightRed
, fg brightGreen
, fg brightYellow
, fg brightBlue
, fg brightMagenta
, fg brightCyan
]
-- Functions for dealing with Skylighting styles
attrNameDescription :: ThemeDocumentation -> AttrName -> Maybe Text
attrNameDescription td an = M.lookup an (themeDescriptions td)
themeDocs :: ThemeDocumentation
themeDocs = ThemeDocumentation $ M.fromList $
[ ( timeAttr
, "Timestamps on chat messages"
)
, ( channelHeaderAttr
, "Channel headers displayed above chat message lists"
)
, ( channelListHeaderAttr
, "The heading of the channel list sections"
)
, ( currentChannelNameAttr
, "The currently selected channel in the channel list"
)
, ( unreadChannelAttr
, "A channel in the channel list with unread messages"
)
, ( mentionsChannelAttr
, "A channel in the channel list with unread mentions"
)
, ( urlAttr
, "A URL in a chat message"
)
, ( codeAttr
, "A code block in a chat message with no language indication"
)
, ( emailAttr
, "An e-mail address in a chat message"
)
, ( emojiAttr
, "A text emoji indication in a chat message"
)
, ( channelNameAttr
, "A channel name in a chat message"
)
, ( clientMessageAttr
, "A Matterhorn diagnostic or informative message"
)
, ( clientHeaderAttr
, "Markdown heading"
)
, ( clientEmphAttr
, "Markdown 'emphasized' text"
)
, ( clientStrongAttr
, "Markdown 'strong' text"
)
, ( dateTransitionAttr
, "Date transition lines between chat messages on different days"
)
, ( newMessageTransitionAttr
, "The 'New Messages' line that appears above unread messages"
)
, ( errorMessageAttr
, "Matterhorn error messages"
)
, ( gapMessageAttr
, "Matterhorn message gap information"
)
, ( helpAttr
, "The help screen text"
)
, ( helpEmphAttr
, "The help screen's emphasized text"
)
, ( channelSelectPromptAttr
, "Channel selection: prompt"
)
, ( channelSelectMatchAttr
, "Channel selection: the portion of a channel name that matches"
)
, ( completionAlternativeListAttr
, "Tab completion alternatives"
)
, ( completionAlternativeCurrentAttr
, "The currently-selected tab completion alternative"
)
, ( dialogAttr
, "Dialog box text"
)
, ( dialogEmphAttr
, "Dialog box emphasized text"
)
, ( recentMarkerAttr
, "The marker indicating the channel last visited"
)
, ( replyParentAttr
, "The first line of parent messages appearing above reply messages"
)
, ( loadMoreAttr
, "The 'Load More' line that appears at the top of a chat message list"
)
, ( urlListSelectedAttr
, "URL list: the selected URL"
)
, ( messageSelectAttr
, "Message selection: the currently-selected message"
)
, ( messageSelectStatusAttr
, "Message selection: the message selection actions"
)
, ( misspellingAttr
, "A misspelled word in the chat message editor"
)
, ( editedMarkingAttr
, "The 'edited' marking that appears on edited messages"
)
, ( editedRecentlyMarkingAttr
, "The 'edited' marking that appears on newly-edited messages"
)
, ( highlightedCodeBlockAttr
, "The base attribute for syntax-highlighted code blocks"
)
, ( attrNameForTokenType KeywordTok
, "Syntax highlighting: Keyword"
)
, ( attrNameForTokenType DataTypeTok
, "Syntax highlighting: DataType"
)
, ( attrNameForTokenType DecValTok
, "Syntax highlighting: Declaration"
)
, ( attrNameForTokenType BaseNTok
, "Syntax highlighting: BaseN"
)
, ( attrNameForTokenType FloatTok
, "Syntax highlighting: Float"
)
, ( attrNameForTokenType ConstantTok
, "Syntax highlighting: Constant"
)
, ( attrNameForTokenType CharTok
, "Syntax highlighting: Char"
)
, ( attrNameForTokenType SpecialCharTok
, "Syntax highlighting: Special Char"
)
, ( attrNameForTokenType StringTok
, "Syntax highlighting: String"
)
, ( attrNameForTokenType VerbatimStringTok
, "Syntax highlighting: Verbatim String"
)
, ( attrNameForTokenType SpecialStringTok
, "Syntax highlighting: Special String"
)
, ( attrNameForTokenType ImportTok
, "Syntax highlighting: Import"
)
, ( attrNameForTokenType CommentTok
, "Syntax highlighting: Comment"
)
, ( attrNameForTokenType DocumentationTok
, "Syntax highlighting: Documentation"
)
, ( attrNameForTokenType AnnotationTok
, "Syntax highlighting: Annotation"
)
, ( attrNameForTokenType CommentVarTok
, "Syntax highlighting: Comment"
)
, ( attrNameForTokenType OtherTok
, "Syntax highlighting: Other"
)
, ( attrNameForTokenType FunctionTok
, "Syntax highlighting: Function"
)
, ( attrNameForTokenType VariableTok
, "Syntax highlighting: Variable"
)
, ( attrNameForTokenType ControlFlowTok
, "Syntax highlighting: Control Flow"
)
, ( attrNameForTokenType OperatorTok
, "Syntax highlighting: Operator"
)
, ( attrNameForTokenType BuiltInTok
, "Syntax highlighting: Built-In"
)
, ( attrNameForTokenType ExtensionTok
, "Syntax highlighting: Extension"
)
, ( attrNameForTokenType PreprocessorTok
, "Syntax highlighting: Preprocessor"
)
, ( attrNameForTokenType AttributeTok
, "Syntax highlighting: Attribute"
)
, ( attrNameForTokenType RegionMarkerTok
, "Syntax highlighting: Region Marker"
)
, ( attrNameForTokenType InformationTok
, "Syntax highlighting: Information"
)
, ( attrNameForTokenType WarningTok
, "Syntax highlighting: Warning"
)
, ( attrNameForTokenType AlertTok
, "Syntax highlighting: Alert"
)
, ( attrNameForTokenType ErrorTok
, "Syntax highlighting: Error"
)
, ( attrNameForTokenType NormalTok
, "Syntax highlighting: Normal text"
)
, ( listSelectedFocusedAttr
, "The selected channel"
)
] <> [ (usernameAttr i, T.pack $ "Username color " <> show i)
| i <- [0..(length usernameColors)-1]
]
|
aisamanra/matterhorn
|
src/Themes.hs
|
Haskell
|
bsd-3-clause
| 17,282
|
module Opaleye.Internal.NEList where
data NEList a = NEList a [a] deriving Show
singleton :: a -> NEList a
singleton = flip NEList []
toList :: NEList a -> [a]
toList (NEList a as) = a:as
neCat :: NEList a -> NEList a -> NEList a
neCat (NEList a as) bs = NEList a (as ++ toList bs)
instance Functor NEList where
fmap f (NEList a as) = NEList (f a) (fmap f as)
instance Monad NEList where
return = flip NEList []
NEList a as >>= f = NEList b (bs ++ (as >>= (toList . f)))
where NEList b bs = f a
|
k0001/haskell-opaleye
|
Opaleye/Internal/NEList.hs
|
Haskell
|
bsd-3-clause
| 511
|
import Control.Monad
import Codec.Compression.GZip
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy as L
import System.FilePath
import System.FilePath.Find
import System.FilePath.Glob
import System.FilePath.Manip
import Text.Regex.Posix ((=~))
-- Get a list of all symlinks.
getDanglingLinks :: FilePath -> IO [FilePath]
getDanglingLinks = find always (fileType ==? SymbolicLink &&?
followStatus ==? Nothing)
-- Rename all ".cpp" files to ".C".
renameCppToC :: FilePath -> IO ()
renameCppToC path = find always (extension ==? ".cpp") path >>=
mapM_ (renameWith (replaceExtension ".C"))
-- A recursion control predicate that will avoid recursing into
-- directories commonly used by revision control tools.
noRCS :: RecursionPredicate
noRCS = (`notElem` ["_darcs","SCCS","CVS",".svn",".hg",".git"]) `liftM` fileName
cSources :: FilePath -> IO [FilePath]
cSources = find noRCS (extension ==? ".c" ||? extension ==? ".h")
-- Replace all uses of "monkey" with "simian", saving the original copy
-- of the file with a ".bak" extension:
monkeyAround :: FilePath -> IO ()
monkeyAround = modifyWithBackup (<.> "bak") (unwords . map reMonkey . words)
where reMonkey x = if x == "monkey" then "simian" else x
-- Given a simple grep, it's easy to construct a recursive grep.
grep :: (Int -> S.ByteString -> a) -> String -> S.ByteString -> [a]
grep f pat s = consider 0 (S.lines s)
where consider _ [] = []
consider n (l:ls) | S.null l = consider (n+1) ls
consider n (l:ls) | l =~ pat = (f n l):ls'
| otherwise = ls'
where ls' = consider (n+1) ls
grepFile :: (Int -> S.ByteString -> a) -> String -> FilePath -> IO [a]
grepFile f pat name = grep f pat `liftM` S.readFile name
recGrep :: String -> FilePath -> IO [(FilePath, Int, S.ByteString)]
recGrep pat top = find always (fileType ==? RegularFile) top >>=
mapM ((,,) >>= flip grepFile pat) >>=
return . concat
-- Decompress all gzip files matching a fixed glob pattern, and return
-- the results as a single huge lazy ByteString.
decomp :: IO L.ByteString
decomp = namesMatching "*/*.gz" >>=
fmap L.concat . mapM (fmap decompress . L.readFile)
|
bos/filemanip
|
examples/Simple.hs
|
Haskell
|
bsd-3-clause
| 2,319
|
module Avg where
{-@ measure sumD :: [Double] -> Double
sumD([]) = 0.0
sumD(x:xs) = x + (sumD xs)
@-}
{-@ measure lenD :: [Double] -> Double
lenD([]) = 0.0
lenD(x:xs) = (1.0) + (lenD xs)
@-}
{-@ expression Avg Xs = ((sumD Xs) / (lenD Xs)) @-}
{-@ meansD :: xs:{v:[Double] | ((lenD v) > 0.0)}
-> {v:Double | v = Avg xs} @-}
meansD :: [Double] -> Double
meansD xs = sumD xs / lenD xs
{-@ lenD :: xs:[Double] -> {v:Double | v = (lenD xs)} @-}
lenD :: [Double] -> Double
lenD [] = 0.0
lenD (x:xs) = 1.0 + lenD xs
{-@ sumD :: xs:[Double] -> {v:Double | v = (sumD xs)} @-}
sumD :: [Double] -> Double
sumD [] = 0.0
sumD (x:xs) = x + sumD xs
|
ssaavedra/liquidhaskell
|
tests/pos/Avg.hs
|
Haskell
|
bsd-3-clause
| 673
|
{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fcontext-stack42 #-}
module Games.Chaos2010.Database.Database_constraints where
import Games.Chaos2010.Database.Fields
import Database.HaskellDB.DBLayout
type Database_constraints =
Record
(HCons (LVPair Constraint_name (Expr String))
(HCons (LVPair Expression (Expr String)) HNil))
database_constraints :: Table Database_constraints
database_constraints = baseTable "database_constraints"
|
JakeWheat/Chaos-2010
|
Games/Chaos2010/Database/Database_constraints.hs
|
Haskell
|
bsd-3-clause
| 487
|
module MapDeclM where
import Recursive
import IdM
{-+
A class to apply a monadic function to all declarations in a
structure. The type of the structure is #s#, the type of the declarations
is #d#. The functional dependency ensures that we can determine the
type of declarations from the type of the structure.
-}
class MapDeclM s d | s -> d where
mapDeclM :: (Functor m, Monad m) => (d -> m d) -> s -> m s
instance MapDeclM s ds => MapDeclM [s] ds where
mapDeclM = mapM . mapDeclM
{- A convinient function, when the definition is in terms of
the underlying structure. -}
std_mapDeclM f = fmap r . mapDeclM f . struct
mapDecls f m = removeId $ mapDeclM (return.map f) m
|
forste/haReFork
|
tools/base/transforms/MapDeclM.hs
|
Haskell
|
bsd-3-clause
| 686
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP, DeriveDataTypeable #-}
-- |
-- #name_types#
-- GHC uses several kinds of name internally:
--
-- * 'OccName.OccName': see "OccName#name_types"
--
-- * 'RdrName.RdrName' is the type of names that come directly from the parser. They
-- have not yet had their scoping and binding resolved by the renamer and can be
-- thought of to a first approximation as an 'OccName.OccName' with an optional module
-- qualifier
--
-- * 'Name.Name': see "Name#name_types"
--
-- * 'Id.Id': see "Id#name_types"
--
-- * 'Var.Var': see "Var#name_types"
module RdrName (
-- * The main type
RdrName(..), -- Constructors exported only to BinIface
-- ** Construction
mkRdrUnqual, mkRdrQual,
mkUnqual, mkVarUnqual, mkQual, mkOrig,
nameRdrName, getRdrName,
-- ** Destruction
rdrNameOcc, rdrNameSpace, setRdrNameSpace, demoteRdrName,
isRdrDataCon, isRdrTyVar, isRdrTc, isQual, isQual_maybe, isUnqual,
isOrig, isOrig_maybe, isExact, isExact_maybe, isSrcRdrName,
-- * Local mapping of 'RdrName' to 'Name.Name'
LocalRdrEnv, emptyLocalRdrEnv, extendLocalRdrEnv, extendLocalRdrEnvList,
lookupLocalRdrEnv, lookupLocalRdrOcc,
elemLocalRdrEnv, inLocalRdrEnvScope,
localRdrEnvElts, delLocalRdrEnvList,
-- * Global mapping of 'RdrName' to 'GlobalRdrElt's
GlobalRdrEnv, emptyGlobalRdrEnv, mkGlobalRdrEnv, plusGlobalRdrEnv,
lookupGlobalRdrEnv, extendGlobalRdrEnv,
pprGlobalRdrEnv, globalRdrEnvElts,
lookupGRE_RdrName, lookupGRE_Name, getGRE_NameQualifier_maybes,
transformGREs, findLocalDupsRdrEnv, pickGREs,
-- * GlobalRdrElts
gresFromAvails, gresFromAvail,
-- ** Global 'RdrName' mapping elements: 'GlobalRdrElt', 'Provenance', 'ImportSpec'
GlobalRdrElt(..), isLocalGRE, unQualOK, qualSpecOK, unQualSpecOK,
Provenance(..), pprNameProvenance,
Parent(..),
ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
importSpecLoc, importSpecModule, isExplicitItem
) where
#include "HsVersions.h"
import Module
import Name
import Avail
import NameSet
import Maybes
import SrcLoc
import FastString
import Outputable
import Unique
import Util
import StaticFlags( opt_PprStyle_Debug )
import Data.Data
{-
************************************************************************
* *
\subsection{The main data type}
* *
************************************************************************
-}
-- | Do not use the data constructors of RdrName directly: prefer the family
-- of functions that creates them, such as 'mkRdrUnqual'
--
-- - Note: A Located RdrName will only have API Annotations if it is a
-- compound one,
-- e.g.
--
-- > `bar`
-- > ( ~ )
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
-- 'ApiAnnotation.AnnOpen' @'('@ or @'['@ or @'[:'@,
-- 'ApiAnnotation.AnnClose' @')'@ or @']'@ or @':]'@,,
-- 'ApiAnnotation.AnnBackquote' @'`'@,
-- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnTildehsh',
-- 'ApiAnnotation.AnnTilde',
data RdrName
= Unqual OccName
-- ^ Used for ordinary, unqualified occurrences, e.g. @x@, @y@ or @Foo@.
-- Create such a 'RdrName' with 'mkRdrUnqual'
| Qual ModuleName OccName
-- ^ A qualified name written by the user in
-- /source/ code. The module isn't necessarily
-- the module where the thing is defined;
-- just the one from which it is imported.
-- Examples are @Bar.x@, @Bar.y@ or @Bar.Foo@.
-- Create such a 'RdrName' with 'mkRdrQual'
| Orig Module OccName
-- ^ An original name; the module is the /defining/ module.
-- This is used when GHC generates code that will be fed
-- into the renamer (e.g. from deriving clauses), but where
-- we want to say \"Use Prelude.map dammit\". One of these
-- can be created with 'mkOrig'
| Exact Name
-- ^ We know exactly the 'Name'. This is used:
--
-- (1) When the parser parses built-in syntax like @[]@
-- and @(,)@, but wants a 'RdrName' from it
--
-- (2) By Template Haskell, when TH has generated a unique name
--
-- Such a 'RdrName' can be created by using 'getRdrName' on a 'Name'
deriving (Data, Typeable)
{-
************************************************************************
* *
\subsection{Simple functions}
* *
************************************************************************
-}
instance HasOccName RdrName where
occName = rdrNameOcc
rdrNameOcc :: RdrName -> OccName
rdrNameOcc (Qual _ occ) = occ
rdrNameOcc (Unqual occ) = occ
rdrNameOcc (Orig _ occ) = occ
rdrNameOcc (Exact name) = nameOccName name
rdrNameSpace :: RdrName -> NameSpace
rdrNameSpace = occNameSpace . rdrNameOcc
setRdrNameSpace :: RdrName -> NameSpace -> RdrName
-- ^ This rather gruesome function is used mainly by the parser.
-- When parsing:
--
-- > data T a = T | T1 Int
--
-- we parse the data constructors as /types/ because of parser ambiguities,
-- so then we need to change the /type constr/ to a /data constr/
--
-- The exact-name case /can/ occur when parsing:
--
-- > data [] a = [] | a : [a]
--
-- For the exact-name case we return an original name.
setRdrNameSpace (Unqual occ) ns = Unqual (setOccNameSpace ns occ)
setRdrNameSpace (Qual m occ) ns = Qual m (setOccNameSpace ns occ)
setRdrNameSpace (Orig m occ) ns = Orig m (setOccNameSpace ns occ)
setRdrNameSpace (Exact n) ns
| isExternalName n
= Orig (nameModule n) occ
| otherwise -- This can happen when quoting and then splicing a fixity
-- declaration for a type
= Exact $ mkSystemNameAt (nameUnique n) occ (nameSrcSpan n)
where
occ = setOccNameSpace ns (nameOccName n)
-- demoteRdrName lowers the NameSpace of RdrName.
-- see Note [Demotion] in OccName
demoteRdrName :: RdrName -> Maybe RdrName
demoteRdrName (Unqual occ) = fmap Unqual (demoteOccName occ)
demoteRdrName (Qual m occ) = fmap (Qual m) (demoteOccName occ)
demoteRdrName (Orig _ _) = panic "demoteRdrName"
demoteRdrName (Exact _) = panic "demoteRdrName"
-- These two are the basic constructors
mkRdrUnqual :: OccName -> RdrName
mkRdrUnqual occ = Unqual occ
mkRdrQual :: ModuleName -> OccName -> RdrName
mkRdrQual mod occ = Qual mod occ
mkOrig :: Module -> OccName -> RdrName
mkOrig mod occ = Orig mod occ
---------------
-- These two are used when parsing source files
-- They do encode the module and occurrence names
mkUnqual :: NameSpace -> FastString -> RdrName
mkUnqual sp n = Unqual (mkOccNameFS sp n)
mkVarUnqual :: FastString -> RdrName
mkVarUnqual n = Unqual (mkVarOccFS n)
-- | Make a qualified 'RdrName' in the given namespace and where the 'ModuleName' and
-- the 'OccName' are taken from the first and second elements of the tuple respectively
mkQual :: NameSpace -> (FastString, FastString) -> RdrName
mkQual sp (m, n) = Qual (mkModuleNameFS m) (mkOccNameFS sp n)
getRdrName :: NamedThing thing => thing -> RdrName
getRdrName name = nameRdrName (getName name)
nameRdrName :: Name -> RdrName
nameRdrName name = Exact name
-- Keep the Name even for Internal names, so that the
-- unique is still there for debug printing, particularly
-- of Types (which are converted to IfaceTypes before printing)
nukeExact :: Name -> RdrName
nukeExact n
| isExternalName n = Orig (nameModule n) (nameOccName n)
| otherwise = Unqual (nameOccName n)
isRdrDataCon :: RdrName -> Bool
isRdrTyVar :: RdrName -> Bool
isRdrTc :: RdrName -> Bool
isRdrDataCon rn = isDataOcc (rdrNameOcc rn)
isRdrTyVar rn = isTvOcc (rdrNameOcc rn)
isRdrTc rn = isTcOcc (rdrNameOcc rn)
isSrcRdrName :: RdrName -> Bool
isSrcRdrName (Unqual _) = True
isSrcRdrName (Qual _ _) = True
isSrcRdrName _ = False
isUnqual :: RdrName -> Bool
isUnqual (Unqual _) = True
isUnqual _ = False
isQual :: RdrName -> Bool
isQual (Qual _ _) = True
isQual _ = False
isQual_maybe :: RdrName -> Maybe (ModuleName, OccName)
isQual_maybe (Qual m n) = Just (m,n)
isQual_maybe _ = Nothing
isOrig :: RdrName -> Bool
isOrig (Orig _ _) = True
isOrig _ = False
isOrig_maybe :: RdrName -> Maybe (Module, OccName)
isOrig_maybe (Orig m n) = Just (m,n)
isOrig_maybe _ = Nothing
isExact :: RdrName -> Bool
isExact (Exact _) = True
isExact _ = False
isExact_maybe :: RdrName -> Maybe Name
isExact_maybe (Exact n) = Just n
isExact_maybe _ = Nothing
{-
************************************************************************
* *
\subsection{Instances}
* *
************************************************************************
-}
instance Outputable RdrName where
ppr (Exact name) = ppr name
ppr (Unqual occ) = ppr occ
ppr (Qual mod occ) = ppr mod <> dot <> ppr occ
ppr (Orig mod occ) = getPprStyle (\sty -> pprModulePrefix sty mod occ <> ppr occ)
instance OutputableBndr RdrName where
pprBndr _ n
| isTvOcc (rdrNameOcc n) = char '@' <+> ppr n
| otherwise = ppr n
pprInfixOcc rdr = pprInfixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr)
pprPrefixOcc rdr
| Just name <- isExact_maybe rdr = pprPrefixName name
-- pprPrefixName has some special cases, so
-- we delegate to them rather than reproduce them
| otherwise = pprPrefixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr)
instance Eq RdrName where
(Exact n1) == (Exact n2) = n1==n2
-- Convert exact to orig
(Exact n1) == r2@(Orig _ _) = nukeExact n1 == r2
r1@(Orig _ _) == (Exact n2) = r1 == nukeExact n2
(Orig m1 o1) == (Orig m2 o2) = m1==m2 && o1==o2
(Qual m1 o1) == (Qual m2 o2) = m1==m2 && o1==o2
(Unqual o1) == (Unqual o2) = o1==o2
_ == _ = False
instance Ord RdrName where
a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False }
a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False }
a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True }
a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True }
-- Exact < Unqual < Qual < Orig
-- [Note: Apr 2004] We used to use nukeExact to convert Exact to Orig
-- before comparing so that Prelude.map == the exact Prelude.map, but
-- that meant that we reported duplicates when renaming bindings
-- generated by Template Haskell; e.g
-- do { n1 <- newName "foo"; n2 <- newName "foo";
-- <decl involving n1,n2> }
-- I think we can do without this conversion
compare (Exact n1) (Exact n2) = n1 `compare` n2
compare (Exact _) _ = LT
compare (Unqual _) (Exact _) = GT
compare (Unqual o1) (Unqual o2) = o1 `compare` o2
compare (Unqual _) _ = LT
compare (Qual _ _) (Exact _) = GT
compare (Qual _ _) (Unqual _) = GT
compare (Qual m1 o1) (Qual m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2)
compare (Qual _ _) (Orig _ _) = LT
compare (Orig m1 o1) (Orig m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2)
compare (Orig _ _) _ = GT
{-
************************************************************************
* *
LocalRdrEnv
* *
************************************************************************
-}
-- | This environment is used to store local bindings (@let@, @where@, lambda, @case@).
-- It is keyed by OccName, because we never use it for qualified names
-- We keep the current mapping, *and* the set of all Names in scope
-- Reason: see Note [Splicing Exact Names] in RnEnv
data LocalRdrEnv = LRE { lre_env :: OccEnv Name
, lre_in_scope :: NameSet }
instance Outputable LocalRdrEnv where
ppr (LRE {lre_env = env, lre_in_scope = ns})
= hang (ptext (sLit "LocalRdrEnv {"))
2 (vcat [ ptext (sLit "env =") <+> pprOccEnv ppr_elt env
, ptext (sLit "in_scope =") <+> braces (pprWithCommas ppr (nameSetElems ns))
] <+> char '}')
where
ppr_elt name = parens (ppr (getUnique (nameOccName name))) <+> ppr name
-- So we can see if the keys line up correctly
emptyLocalRdrEnv :: LocalRdrEnv
emptyLocalRdrEnv = LRE { lre_env = emptyOccEnv, lre_in_scope = emptyNameSet }
extendLocalRdrEnv :: LocalRdrEnv -> Name -> LocalRdrEnv
-- The Name should be a non-top-level thing
extendLocalRdrEnv (LRE { lre_env = env, lre_in_scope = ns }) name
= WARN( isExternalName name, ppr name )
LRE { lre_env = extendOccEnv env (nameOccName name) name
, lre_in_scope = extendNameSet ns name }
extendLocalRdrEnvList :: LocalRdrEnv -> [Name] -> LocalRdrEnv
extendLocalRdrEnvList (LRE { lre_env = env, lre_in_scope = ns }) names
= WARN( any isExternalName names, ppr names )
LRE { lre_env = extendOccEnvList env [(nameOccName n, n) | n <- names]
, lre_in_scope = extendNameSetList ns names }
lookupLocalRdrEnv :: LocalRdrEnv -> RdrName -> Maybe Name
lookupLocalRdrEnv (LRE { lre_env = env }) (Unqual occ) = lookupOccEnv env occ
lookupLocalRdrEnv _ _ = Nothing
lookupLocalRdrOcc :: LocalRdrEnv -> OccName -> Maybe Name
lookupLocalRdrOcc (LRE { lre_env = env }) occ = lookupOccEnv env occ
elemLocalRdrEnv :: RdrName -> LocalRdrEnv -> Bool
elemLocalRdrEnv rdr_name (LRE { lre_env = env, lre_in_scope = ns })
= case rdr_name of
Unqual occ -> occ `elemOccEnv` env
Exact name -> name `elemNameSet` ns -- See Note [Local bindings with Exact Names]
Qual {} -> False
Orig {} -> False
localRdrEnvElts :: LocalRdrEnv -> [Name]
localRdrEnvElts (LRE { lre_env = env }) = occEnvElts env
inLocalRdrEnvScope :: Name -> LocalRdrEnv -> Bool
-- This is the point of the NameSet
inLocalRdrEnvScope name (LRE { lre_in_scope = ns }) = name `elemNameSet` ns
delLocalRdrEnvList :: LocalRdrEnv -> [OccName] -> LocalRdrEnv
delLocalRdrEnvList (LRE { lre_env = env, lre_in_scope = ns }) occs
= LRE { lre_env = delListFromOccEnv env occs
, lre_in_scope = ns }
{-
Note [Local bindings with Exact Names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With Template Haskell we can make local bindings that have Exact Names.
Computing shadowing etc may use elemLocalRdrEnv (at least it certainly
does so in RnTpes.bindHsTyVars), so for an Exact Name we must consult
the in-scope-name-set.
************************************************************************
* *
GlobalRdrEnv
* *
************************************************************************
-}
type GlobalRdrEnv = OccEnv [GlobalRdrElt]
-- ^ Keyed by 'OccName'; when looking up a qualified name
-- we look up the 'OccName' part, and then check the 'Provenance'
-- to see if the appropriate qualification is valid. This
-- saves routinely doubling the size of the env by adding both
-- qualified and unqualified names to the domain.
--
-- The list in the codomain is required because there may be name clashes
-- These only get reported on lookup, not on construction
--
-- INVARIANT: All the members of the list have distinct
-- 'gre_name' fields; that is, no duplicate Names
--
-- INVARIANT: Imported provenance => Name is an ExternalName
-- However LocalDefs can have an InternalName. This
-- happens only when type-checking a [d| ... |] Template
-- Haskell quotation; see this note in RnNames
-- Note [Top-level Names in Template Haskell decl quotes]
-- | An element of the 'GlobalRdrEnv'
data GlobalRdrElt
= GRE { gre_name :: Name,
gre_par :: Parent,
gre_prov :: Provenance -- ^ Why it's in scope
}
-- | The children of a Name are the things that are abbreviated by the ".."
-- notation in export lists. See Note [Parents]
data Parent = NoParent | ParentIs Name
deriving (Eq)
instance Outputable Parent where
ppr NoParent = empty
ppr (ParentIs n) = ptext (sLit "parent:") <> ppr n
plusParent :: Parent -> Parent -> Parent
-- See Note [Combining parents]
plusParent (ParentIs n) p2 = hasParent n p2
plusParent p1 (ParentIs n) = hasParent n p1
plusParent _ _ = NoParent
hasParent :: Name -> Parent -> Parent
#ifdef DEBUG
hasParent n (ParentIs n')
| n /= n' = pprPanic "hasParent" (ppr n <+> ppr n') -- Parents should agree
#endif
hasParent n _ = ParentIs n
{-
Note [Parents]
~~~~~~~~~~~~~~~~~
Parent Children
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
data T Data constructors
Record-field ids
data family T Data constructors and record-field ids
of all visible data instances of T
class C Class operations
Associated type constructors
Note [Combining parents]
~~~~~~~~~~~~~~~~~~~~~~~~
With an associated type we might have
module M where
class C a where
data T a
op :: T a -> a
instance C Int where
data T Int = TInt
instance C Bool where
data T Bool = TBool
Then: C is the parent of T
T is the parent of TInt and TBool
So: in an export list
C(..) is short for C( op, T )
T(..) is short for T( TInt, TBool )
Module M exports everything, so its exports will be
AvailTC C [C,T,op]
AvailTC T [T,TInt,TBool]
On import we convert to GlobalRdrElt and the combine
those. For T that will mean we have
one GRE with Parent C
one GRE with NoParent
That's why plusParent picks the "best" case.
-}
-- | make a 'GlobalRdrEnv' where all the elements point to the same
-- Provenance (useful for "hiding" imports, or imports with
-- no details).
gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt]
gresFromAvails prov avails
= concatMap (gresFromAvail (const prov)) avails
gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt]
gresFromAvail prov_fn avail
= [ GRE {gre_name = n,
gre_par = mkParent n avail,
gre_prov = prov_fn n}
| n <- availNames avail ]
where
mkParent :: Name -> AvailInfo -> Parent
mkParent _ (Avail _) = NoParent
mkParent n (AvailTC m _) | n == m = NoParent
| otherwise = ParentIs m
emptyGlobalRdrEnv :: GlobalRdrEnv
emptyGlobalRdrEnv = emptyOccEnv
globalRdrEnvElts :: GlobalRdrEnv -> [GlobalRdrElt]
globalRdrEnvElts env = foldOccEnv (++) [] env
instance Outputable GlobalRdrElt where
ppr gre = hang (ppr (gre_name gre) <+> ppr (gre_par gre))
2 (pprNameProvenance gre)
pprGlobalRdrEnv :: Bool -> GlobalRdrEnv -> SDoc
pprGlobalRdrEnv locals_only env
= vcat [ ptext (sLit "GlobalRdrEnv") <+> ppWhen locals_only (ptext (sLit "(locals only)"))
<+> lbrace
, nest 2 (vcat [ pp (remove_locals gre_list) | gre_list <- occEnvElts env ]
<+> rbrace) ]
where
remove_locals gres | locals_only = filter isLocalGRE gres
| otherwise = gres
pp [] = empty
pp gres = hang (ppr occ
<+> parens (ptext (sLit "unique") <+> ppr (getUnique occ))
<> colon)
2 (vcat (map ppr gres))
where
occ = nameOccName (gre_name (head gres))
lookupGlobalRdrEnv :: GlobalRdrEnv -> OccName -> [GlobalRdrElt]
lookupGlobalRdrEnv env occ_name = case lookupOccEnv env occ_name of
Nothing -> []
Just gres -> gres
lookupGRE_RdrName :: RdrName -> GlobalRdrEnv -> [GlobalRdrElt]
lookupGRE_RdrName rdr_name env
= case lookupOccEnv env (rdrNameOcc rdr_name) of
Nothing -> []
Just gres -> pickGREs rdr_name gres
lookupGRE_Name :: GlobalRdrEnv -> Name -> [GlobalRdrElt]
lookupGRE_Name env name
= [ gre | gre <- lookupGlobalRdrEnv env (nameOccName name),
gre_name gre == name ]
getGRE_NameQualifier_maybes :: GlobalRdrEnv -> Name -> [Maybe [ModuleName]]
-- Returns all the qualifiers by which 'x' is in scope
-- Nothing means "the unqualified version is in scope"
-- [] means the thing is not in scope at all
getGRE_NameQualifier_maybes env
= map (qualifier_maybe . gre_prov) . lookupGRE_Name env
where
qualifier_maybe LocalDef = Nothing
qualifier_maybe (Imported iss) = Just $ map (is_as . is_decl) iss
isLocalGRE :: GlobalRdrElt -> Bool
isLocalGRE (GRE {gre_prov = LocalDef}) = True
isLocalGRE _ = False
unQualOK :: GlobalRdrElt -> Bool
-- ^ Test if an unqualifed version of this thing would be in scope
unQualOK (GRE {gre_prov = LocalDef}) = True
unQualOK (GRE {gre_prov = Imported is}) = any unQualSpecOK is
pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt]
-- ^ Take a list of GREs which have the right OccName
-- Pick those GREs that are suitable for this RdrName
-- And for those, keep only only the Provenances that are suitable
-- Only used for Qual and Unqual, not Orig or Exact
--
-- Consider:
--
-- @
-- module A ( f ) where
-- import qualified Foo( f )
-- import Baz( f )
-- f = undefined
-- @
--
-- Let's suppose that @Foo.f@ and @Baz.f@ are the same entity really.
-- The export of @f@ is ambiguous because it's in scope from the local def
-- and the import. The lookup of @Unqual f@ should return a GRE for
-- the locally-defined @f@, and a GRE for the imported @f@, with a /single/
-- provenance, namely the one for @Baz(f)@.
pickGREs rdr_name gres
| (_ : _ : _) <- candidates -- This is usually false, so we don't have to
-- even look at internal_candidates
, (gre : _) <- internal_candidates
= [gre] -- For this internal_candidate stuff,
-- see Note [Template Haskell binders in the GlobalRdrEnv]
-- If there are multiple Internal candidates, pick the
-- first one (ie with the (innermost binding)
| otherwise
= ASSERT2( isSrcRdrName rdr_name, ppr rdr_name )
candidates
where
candidates = mapMaybe pick gres
internal_candidates = filter (isInternalName . gre_name) candidates
rdr_is_unqual = isUnqual rdr_name
rdr_is_qual = isQual_maybe rdr_name
pick :: GlobalRdrElt -> Maybe GlobalRdrElt
pick gre@(GRE {gre_prov = LocalDef, gre_name = n}) -- Local def
| rdr_is_unqual = Just gre
| Just (mod,_) <- rdr_is_qual -- Qualified name
, Just n_mod <- nameModule_maybe n -- Binder is External
, mod == moduleName n_mod = Just gre
| otherwise = Nothing
pick gre@(GRE {gre_prov = Imported [is]}) -- Single import (efficiency)
| rdr_is_unqual,
not (is_qual (is_decl is)) = Just gre
| Just (mod,_) <- rdr_is_qual,
mod == is_as (is_decl is) = Just gre
| otherwise = Nothing
pick gre@(GRE {gre_prov = Imported is}) -- Multiple import
| null filtered_is = Nothing
| otherwise = Just (gre {gre_prov = Imported filtered_is})
where
filtered_is | rdr_is_unqual
= filter (not . is_qual . is_decl) is
| Just (mod,_) <- rdr_is_qual
= filter ((== mod) . is_as . is_decl) is
| otherwise
= []
-- Building GlobalRdrEnvs
plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
plusGlobalRdrEnv env1 env2 = plusOccEnv_C (foldr insertGRE) env1 env2
mkGlobalRdrEnv :: [GlobalRdrElt] -> GlobalRdrEnv
mkGlobalRdrEnv gres
= foldr add emptyGlobalRdrEnv gres
where
add gre env = extendOccEnv_Acc insertGRE singleton env
(nameOccName (gre_name gre))
gre
insertGRE :: GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt]
insertGRE new_g [] = [new_g]
insertGRE new_g (old_g : old_gs)
| gre_name new_g == gre_name old_g
= new_g `plusGRE` old_g : old_gs
| otherwise
= old_g : insertGRE new_g old_gs
plusGRE :: GlobalRdrElt -> GlobalRdrElt -> GlobalRdrElt
-- Used when the gre_name fields match
plusGRE g1 g2
= GRE { gre_name = gre_name g1,
gre_prov = gre_prov g1 `plusProv` gre_prov g2,
gre_par = gre_par g1 `plusParent` gre_par g2 }
transformGREs :: (GlobalRdrElt -> GlobalRdrElt)
-> [OccName]
-> GlobalRdrEnv -> GlobalRdrEnv
-- ^ Apply a transformation function to the GREs for these OccNames
transformGREs trans_gre occs rdr_env
= foldr trans rdr_env occs
where
trans occ env
= case lookupOccEnv env occ of
Just gres -> extendOccEnv env occ (map trans_gre gres)
Nothing -> env
extendGlobalRdrEnv :: Bool -> GlobalRdrEnv -> [AvailInfo] -> GlobalRdrEnv
-- Extend with new LocalDef GREs from the AvailInfos.
--
-- If do_shadowing is True, first remove name clashes between the new
-- AvailInfos and the existing GlobalRdrEnv.
-- This is used by the GHCi top-level
--
-- E.g. Adding a LocalDef "x" when there is an existing GRE for Q.x
-- should remove any unqualified import of Q.x,
-- leaving only the qualified one
--
-- However do *not* remove name clashes between the AvailInfos themselves,
-- so that (say) data T = A | A
-- will still give a duplicate-binding error.
-- Same thing if there are multiple AvailInfos (don't remove clashes),
-- though I'm not sure this ever happens with do_shadowing=True
extendGlobalRdrEnv do_shadowing env avails
= foldl add_avail env1 avails
where
names = concatMap availNames avails
env1 | do_shadowing = foldl shadow_name env names
| otherwise = env
-- By doing the removal first, we ensure that the new AvailInfos
-- don't shadow each other; that would conceal genuine errors
-- E.g. in GHCi data T = A | A
add_avail env avail = foldl (add_name avail) env (availNames avail)
add_name avail env name
= extendOccEnv_Acc (:) singleton env occ gre
where
occ = nameOccName name
gre = GRE { gre_name = name
, gre_par = mkParent name avail
, gre_prov = LocalDef }
shadow_name :: GlobalRdrEnv -> Name -> GlobalRdrEnv
shadow_name env name
= alterOccEnv (fmap alter_fn) env (nameOccName name)
where
alter_fn :: [GlobalRdrElt] -> [GlobalRdrElt]
alter_fn gres = mapMaybe (shadow_with name) gres
shadow_with :: Name -> GlobalRdrElt -> Maybe GlobalRdrElt
shadow_with new_name old_gre@(GRE { gre_name = old_name, gre_prov = LocalDef })
= case (nameModule_maybe old_name, nameModule_maybe new_name) of
(Nothing, _) -> Nothing
(Just old_mod, Just new_mod) | new_mod == old_mod -> Nothing
(Just old_mod, _) -> Just (old_gre { gre_prov = Imported [fake_imp_spec] })
where
fake_imp_spec = ImpSpec id_spec ImpAll -- Urgh!
old_mod_name = moduleName old_mod
id_spec = ImpDeclSpec { is_mod = old_mod_name
, is_as = old_mod_name
, is_qual = True
, is_dloc = nameSrcSpan old_name }
shadow_with new_name old_gre@(GRE { gre_prov = Imported imp_specs })
| null imp_specs' = Nothing
| otherwise = Just (old_gre { gre_prov = Imported imp_specs' })
where
imp_specs' = mapMaybe (shadow_is new_name) imp_specs
shadow_is :: Name -> ImportSpec -> Maybe ImportSpec
shadow_is new_name is@(ImpSpec { is_decl = id_spec })
| Just new_mod <- nameModule_maybe new_name
, is_as id_spec == moduleName new_mod
= Nothing -- Shadow both qualified and unqualified
| otherwise -- Shadow unqualified only
= Just (is { is_decl = id_spec { is_qual = True } })
{-
Note [Template Haskell binders in the GlobalRdrEnv]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For reasons described in Note [Top-level Names in Template Haskell decl quotes]
in RnNames, a GRE with an Internal gre_name (i.e. one generated by a TH decl
quote) should *shadow* a GRE with an External gre_name. Hence some faffing
around in pickGREs and findLocalDupsRdrEnv
-}
findLocalDupsRdrEnv :: GlobalRdrEnv -> [Name] -> [[GlobalRdrElt]]
-- ^ For each 'OccName', see if there are multiple local definitions
-- for it; return a list of all such
-- and return a list of the duplicate bindings
findLocalDupsRdrEnv rdr_env occs
= go rdr_env [] occs
where
go _ dups [] = dups
go rdr_env dups (name:names)
= case filter (pick name) gres of
[] -> go rdr_env dups names
[_] -> go rdr_env dups names -- The common case
dup_gres -> go rdr_env' (dup_gres : dups) names
where
occ = nameOccName name
gres = lookupOccEnv rdr_env occ `orElse` []
rdr_env' = delFromOccEnv rdr_env occ
-- The delFromOccEnv avoids repeating the same
-- complaint twice, when names itself has a duplicate
-- which is a common case
-- See Note [Template Haskell binders in the GlobalRdrEnv]
pick name (GRE { gre_name = n, gre_prov = LocalDef })
| isInternalName name = isInternalName n
| otherwise = True
pick _ _ = False
{-
************************************************************************
* *
Provenance
* *
************************************************************************
-}
-- | The 'Provenance' of something says how it came to be in scope.
-- It's quite elaborate so that we can give accurate unused-name warnings.
data Provenance
= LocalDef -- ^ The thing was defined locally
| Imported
[ImportSpec] -- ^ The thing was imported.
--
-- INVARIANT: the list of 'ImportSpec' is non-empty
data ImportSpec = ImpSpec { is_decl :: ImpDeclSpec,
is_item :: ImpItemSpec }
deriving( Eq, Ord )
-- | Describes a particular import declaration and is
-- shared among all the 'Provenance's for that decl
data ImpDeclSpec
= ImpDeclSpec {
is_mod :: ModuleName, -- ^ Module imported, e.g. @import Muggle@
-- Note the @Muggle@ may well not be
-- the defining module for this thing!
-- TODO: either should be Module, or there
-- should be a Maybe PackageKey here too.
is_as :: ModuleName, -- ^ Import alias, e.g. from @as M@ (or @Muggle@ if there is no @as@ clause)
is_qual :: Bool, -- ^ Was this import qualified?
is_dloc :: SrcSpan -- ^ The location of the entire import declaration
}
-- | Describes import info a particular Name
data ImpItemSpec
= ImpAll -- ^ The import had no import list,
-- or had a hiding list
| ImpSome {
is_explicit :: Bool,
is_iloc :: SrcSpan -- Location of the import item
} -- ^ The import had an import list.
-- The 'is_explicit' field is @True@ iff the thing was named
-- /explicitly/ in the import specs rather
-- than being imported as part of a "..." group. Consider:
--
-- > import C( T(..) )
--
-- Here the constructors of @T@ are not named explicitly;
-- only @T@ is named explicitly.
unQualSpecOK :: ImportSpec -> Bool
-- ^ Is in scope unqualified?
unQualSpecOK is = not (is_qual (is_decl is))
qualSpecOK :: ModuleName -> ImportSpec -> Bool
-- ^ Is in scope qualified with the given module?
qualSpecOK mod is = mod == is_as (is_decl is)
importSpecLoc :: ImportSpec -> SrcSpan
importSpecLoc (ImpSpec decl ImpAll) = is_dloc decl
importSpecLoc (ImpSpec _ item) = is_iloc item
importSpecModule :: ImportSpec -> ModuleName
importSpecModule is = is_mod (is_decl is)
isExplicitItem :: ImpItemSpec -> Bool
isExplicitItem ImpAll = False
isExplicitItem (ImpSome {is_explicit = exp}) = exp
-- Note [Comparing provenance]
-- Comparison of provenance is just used for grouping
-- error messages (in RnEnv.warnUnusedBinds)
instance Eq Provenance where
p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
instance Eq ImpDeclSpec where
p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
instance Eq ImpItemSpec where
p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
instance Ord Provenance where
compare LocalDef LocalDef = EQ
compare LocalDef (Imported _) = LT
compare (Imported _ ) LocalDef = GT
compare (Imported is1) (Imported is2) = compare (head is1)
{- See Note [Comparing provenance] -} (head is2)
instance Ord ImpDeclSpec where
compare is1 is2 = (is_mod is1 `compare` is_mod is2) `thenCmp`
(is_dloc is1 `compare` is_dloc is2)
instance Ord ImpItemSpec where
compare is1 is2 = is_iloc is1 `compare` is_iloc is2
plusProv :: Provenance -> Provenance -> Provenance
-- Choose LocalDef over Imported
-- There is an obscure bug lurking here; in the presence
-- of recursive modules, something can be imported *and* locally
-- defined, and one might refer to it with a qualified name from
-- the import -- but I'm going to ignore that because it makes
-- the isLocalGRE predicate so much nicer this way
plusProv LocalDef LocalDef = panic "plusProv"
plusProv LocalDef _ = LocalDef
plusProv _ LocalDef = LocalDef
plusProv (Imported is1) (Imported is2) = Imported (is1++is2)
pprNameProvenance :: GlobalRdrElt -> SDoc
-- ^ Print out the place where the name was imported
pprNameProvenance (GRE {gre_name = name, gre_prov = LocalDef})
= ptext (sLit "defined at") <+> ppr (nameSrcLoc name)
pprNameProvenance (GRE {gre_name = name, gre_prov = Imported whys})
= case whys of
(why:_) | opt_PprStyle_Debug -> vcat (map pp_why whys)
| otherwise -> pp_why why
[] -> panic "pprNameProvenance"
where
pp_why why = sep [ppr why, ppr_defn_site why name]
-- If we know the exact definition point (which we may do with GHCi)
-- then show that too. But not if it's just "imported from X".
ppr_defn_site :: ImportSpec -> Name -> SDoc
ppr_defn_site imp_spec name
| same_module && not (isGoodSrcSpan loc)
= empty -- Nothing interesting to say
| otherwise
= parens $ hang (ptext (sLit "and originally defined") <+> pp_mod)
2 (pprLoc loc)
where
loc = nameSrcSpan name
defining_mod = nameModule name
same_module = importSpecModule imp_spec == moduleName defining_mod
pp_mod | same_module = empty
| otherwise = ptext (sLit "in") <+> quotes (ppr defining_mod)
instance Outputable ImportSpec where
ppr imp_spec
= ptext (sLit "imported") <+> qual
<+> ptext (sLit "from") <+> quotes (ppr (importSpecModule imp_spec))
<+> pprLoc (importSpecLoc imp_spec)
where
qual | is_qual (is_decl imp_spec) = ptext (sLit "qualified")
| otherwise = empty
pprLoc :: SrcSpan -> SDoc
pprLoc (RealSrcSpan s) = ptext (sLit "at") <+> ppr s
pprLoc (UnhelpfulSpan {}) = empty
|
green-haskell/ghc
|
compiler/basicTypes/RdrName.hs
|
Haskell
|
bsd-3-clause
| 36,400
|
module Board
( Board (..)
, mkBoard
, isEmptyCell
, isValidUnit
, lockUnit
, clearFullRows
) where
import Control.Arrow ((&&&))
import Data.Ix (inRange,range)
import Data.List (foldl')
import Data.Set (Set(..))
import qualified Data.Set as Set
import Cell
import Unit
import Types
data Board = Board { cols :: Number, rows :: Number, fulls :: Set Cell } deriving (Show,Eq)
mkBoard :: Number -> Number -> [Cell] -> Board
mkBoard width height cs = Board { cols = width, rows = height, fulls = Set.fromList cs }
isEmptyCell :: Board -> Cell -> Bool
isEmptyCell b c = c `Set.notMember` fulls b
isValidUnit :: Board -> Unit -> Bool
isValidUnit b u
= notBatting && withinRange
where
notBatting = Set.null $ fs `Set.intersection` cs
withinRange = all (inRange (cell (0,0), cell (cols b -1, rows b -1))) (Set.toList cs)
fs = fulls b
cs = members u
lockUnit :: Board -> Unit -> Board
lockUnit b u = b { fulls = fulls b `Set.union` members u }
findFullRows :: Board -> [Number]
findFullRows b = filter fullRow [0 .. h-1]
where
w = cols b
h = rows b
fs = fulls b
-- fullRow r = Set.size (Set.filter ((r==) . y) fs) == w
fullRow r = b1 && b2 && Set.size fs2 == w-2
where
(_,b1,fs1) = Set.splitMember (Cell 0 r) fs
(fs2,b2,_) = Set.splitMember (Cell (w-1) r) fs1
clearFullRows :: Board -> (Int, Board)
clearFullRows b = (length &&& foldl' clearRow b) cleared
where
cleared = findFullRows b
clearRow :: Board -> Number -> Board
clearRow b r = case Set.split (Cell { x = 0, y = r }) fs of
(ps,qs) -> b { fulls = Set.mapMonotonic (\ c -> c { y = y c + 1 }) ps `Set.union` qs }
where
fs = Set.filter ((r /=) . y) (fulls b)
--
sampleBoard :: Board
sampleBoard = Board { cols = 5, rows = 10
, fulls = Set.fromList (range (cell (1,0), cell (3,4)))
`Set.union`
Set.fromList (range (cell (0,1),cell (4,3))) }
|
msakai/icfpc2015
|
src/Board.hs
|
Haskell
|
bsd-3-clause
| 1,995
|
{-# LANGUAGE DoAndIfThenElse #-}
module Term(Term(..), TermClass(..), Substitution(..), parse, act, makeUniqueVars, betaReduction) where
import Text.Parsec hiding (parse)
import qualified Text.Parsec as Parsec
import Control.Applicative hiding ((<|>))
import Control.Monad
import Data.List
import VarEnvironment
data Substitution a = AssignTo String a
deriving Show
instance Functor Substitution where
fmap f (x `AssignTo` t) = x `AssignTo` f t
class TermClass t where
freeVars :: t -> [String]
substitute :: Substitution t -> t -> t
substituteAll :: (Eq t) => [Substitution t] -> t -> t
substituteAll subs t =
if t == t' then t else substituteAll subs t'
where t' = foldr substitute t subs
data Term = Lambda String Term
| App Term Term
| Var String
instance Eq Term where
(Var x) == (Var y) = x == y
(App n1 m1) == (App n2 m2) = n1 == n2 && m1 == m2
(Lambda x n) == (Lambda y m)
| x == y = n == m
| otherwise = n == substitute (y `AssignTo` Var x) m
_ == _ = False
instance TermClass Term where
freeVars (Lambda x t) = filter (/= x) $ freeVars t
freeVars (App x y) = nub $ freeVars x ++ freeVars y
freeVars (Var x) = [x]
substitute (v `AssignTo` t) (Var x)
| v == x = t
| otherwise = Var x
substitute (v `AssignTo` t) (App x y) = App (substitute (v `AssignTo` t) x) (substitute (v `AssignTo` t) y)
substitute (v `AssignTo` t) (Lambda x y)
| v == x = Lambda x y
| otherwise = Lambda x (substitute (v `AssignTo` t) y)
act :: Term -> [String]
act (Var _) = []
act (Lambda x m) = x : act m
act (App m _)
| null (act m) = []
| otherwise = tail (act m)
betaReduction :: Term -> Term
betaReduction t = evalInEnvironment (freeVars t) (betaReduction' <$> makeUniqueVars t)
where betaReduction' (Lambda x n `App` m) = betaReduction' $ substitute (x `AssignTo` m) n
betaReduction' (Var x) = Var x
betaReduction' (Lambda x n) = Lambda x $ betaReduction' n
betaReduction' (App n m) =
let n' = betaReduction' n
in if n == n' then App n $ betaReduction' m
else betaReduction' (App n' m)
makeUniqueVars :: Term -> Environment Term
makeUniqueVars t = do
mapM_ addToEnvironment $ freeVars t
go t
where go (Var x) = return $ Var x
go (App m n) = App <$> go m <*> go n
go (Lambda x m) = do
(x', m') <- renameVariable x m
addToEnvironment x'
Lambda x' <$> go m'
renameVariable x m = do
inEnv <- inEnvironment x
if inEnv then do
y <- newVar "var"
return (y, substitute (x `AssignTo` Var y) m)
else return (x, m)
------ Printing ------
brackets :: Int -> String -> String
brackets p str = if p > 0 then "(" ++ str ++ ")" else str
lambdaSymb :: String
lambdaSymb = "λ"
--lambdaSymb = "\\"
showTerm :: Int -> Term -> String
showTerm _ (Var x) = x
showTerm prec (App t1 t2) = brackets (prec - 1) (showTerm 1 t1 ++ " " ++ showTerm 2 t2)
showTerm prec t@(Lambda _ _) =
brackets prec $ lambdaSymb ++ showLambda t
where showLambda (Lambda x n@(Lambda _ _)) = x ++ " " ++ showLambda n
showLambda (Lambda x n) = x ++ ". " ++ showTerm 0 n
showLambda _ = error "showLambda: Argument is not Lambda. Couldn't happen."
instance Show Term where
show = showTerm 0
------ Parsing ------
type Parser = Parsec String ()
varname :: Parser String
varname = many1 (alphaNum <|> oneOf "_")
bracketExpr :: Parser Term -> Parser Term
bracketExpr = between (char '(' *> spaces) (spaces *> char ')')
lambdaExpr :: Parser Term
lambdaExpr = do
void $ char '\\' <|> char 'λ'
spaces
vs <- many1 (varname <* spaces)
void $ char '.'
spaces
t <- termExpr
return $ foldr Lambda t vs
termExpr :: Parser Term
termExpr = try appExpr <|> noAppTermExpr
noAppTermExpr :: Parser Term
noAppTermExpr = choice
[ lambdaExpr -- Precedes variable parser because λ is a proper variable name
, Var <$> varname
, bracketExpr termExpr
]
appExpr :: Parser Term
appExpr = do
t1 <- noAppTermExpr
ts <- many1 (spaces *> noAppTermExpr)
return $ foldl App t1 ts
fullExpr :: Parser Term
fullExpr = spaces *> termExpr <* spaces <* eof
parse :: String -> Either ParseError Term
parse = Parsec.parse fullExpr ""
|
projedi/type-inference-rank2
|
src/Term.hs
|
Haskell
|
bsd-3-clause
| 4,308
|
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
module FreeAgentSpec (main, spec) where
import FreeAgent.AgentPrelude
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "FreeAgent" $ do
it "goes out in the world and does a thing" $
True `shouldBe` True
|
jeremyjh/free-agent
|
core/test/FreeAgentSpec.hs
|
Haskell
|
bsd-3-clause
| 334
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.UI.GLUT.Callbacks
-- Copyright : (c) Sven Panne 2002-2005
-- License : BSD-style (see the file libraries/GLUT/LICENSE)
--
-- Maintainer : sven.panne@aedion.de
-- Stability : stable
-- Portability : portable
--
--
-- GLUT supports a number of callbacks to respond to events. There are three
-- types of callbacks: window, menu, and global. Window callbacks indicate when
-- to redisplay or reshape a window, when the visibility of the window changes,
-- and when input is available for the window. Menu callbacks are described in
-- "Graphics.UI.GLUT.Menu". The global callbacks manage the passing of time and
-- menu usage. The calling order of callbacks between different windows is
-- undefined.
--
-- Callbacks for input events should be delivered to the window the event occurs
-- in. Events should not propagate to parent windows.
--
-- A callback of type @Foo@ can registered by setting @fooCallback@ to 'Just'
-- the callback. Almost all callbacks can be de-registered by setting
-- the corresponding @fooCallback@ to 'Nothing', the only exceptions being
-- 'Graphics.UI.GLUT.Callbacks.Window.DisplayCallback' (can only be
-- re-registered) and 'Graphics.UI.GLUT.Callbacks.Global.TimerCallback' (can\'t
-- be unregistered).
--
-- /X Implementation Notes:/ The X GLUT implementation uses the X Input
-- extension to support sophisticated input devices: Spaceball, dial & button
-- box, and digitizing tablet. Because the X Input extension does not mandate
-- how particular types of devices are advertised through the extension, it is
-- possible GLUT for X may not correctly support input devices that would
-- otherwise be of the correct type. The X GLUT implementation will support the
-- Silicon Graphics Spaceball, dial & button box, and digitizing tablet as
-- advertised through the X Input extension.
--
--------------------------------------------------------------------------------
module Graphics.UI.GLUT.Callbacks (
module Graphics.UI.GLUT.Callbacks.Window,
module Graphics.UI.GLUT.Callbacks.Global
) where
import Graphics.UI.GLUT.Callbacks.Window
import Graphics.UI.GLUT.Callbacks.Global
|
FranklinChen/hugs98-plus-Sep2006
|
packages/GLUT/Graphics/UI/GLUT/Callbacks.hs
|
Haskell
|
bsd-3-clause
| 2,245
|
{-# LANGUAGE OverloadedStrings #-}
-- | XSD @dateTime@ data structure <http://www.w3.org/TR/xmlschema-2/#dateTime>
module Text.XML.XSD.DateTime
( DateTime(..)
, isZoned
, isUnzoned
, dateTime'
, dateTime
, toText
, fromZonedTime
, toUTCTime
, fromUTCTime
, toLocalTime
, fromLocalTime
, utcTime'
, utcTime
, localTime'
, localTime
) where
import Control.Applicative (pure, (<$>), (*>), (<|>))
import Control.Monad (when)
import Data.Attoparsec.Text (Parser, char, digit)
import qualified Data.Attoparsec.Text as A
import Data.Char (isDigit, ord)
import Data.Fixed (Pico, showFixed)
import Data.Maybe (maybeToList)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TB
import qualified Data.Text.Lazy.Builder.Int as TBI
import qualified Data.Text.Read as TR
import Data.Time
import Data.Time.Calendar.MonthDay (monthLength)
-- | XSD @dateTime@ data structure
-- <http://www.w3.org/TR/xmlschema-2/#dateTime>. Briefly, a @dateTime@
-- uses the Gregorian calendar and may or may not have an associated
-- timezone. If it has a timezone, then the canonical representation
-- of that date time is in UTC.
--
-- Note, it is not possible to establish a total order on @dateTime@
-- since non-timezoned are considered to belong to some unspecified
-- timezone.
data DateTime = DtZoned UTCTime
| DtUnzoned LocalTime
deriving (Eq)
-- | Internal helper that creates a date time. Note, if the given hour
-- is 24 then the minutes and seconds are assumed to be 0.
mkDateTime :: Integer -- ^ Year
-> Int -- ^ Month
-> Int -- ^ Day
-> Int -- ^ Hours
-> Int -- ^ Minutes
-> Pico -- ^ Seconds
-> Maybe Pico -- ^ Time zone offset
-> DateTime
mkDateTime y m d hh mm ss mz =
case mz of
Just z -> DtZoned $ addUTCTime (negate $ realToFrac z) uTime
Nothing -> DtUnzoned lTime
where
day = addDays (if hh == 24 then 1 else 0) (fromGregorian y m d)
tod = TimeOfDay (if hh == 24 then 0 else hh) mm ss
lTime = LocalTime day tod
uTime = UTCTime day (timeOfDayToTime tod)
instance Show DateTime where
show = T.unpack . toText
instance Read DateTime where
readList s = [(maybeToList (dateTime . T.pack $ s), [])]
-- | Parses the string into a @dateTime@ or may fail with a parse error.
dateTime' :: Text -> Either String DateTime
dateTime' = A.parseOnly (parseDateTime <|> fail "bad date time")
-- | Parses the string into a @dateTime@ or may fail.
dateTime :: Text -> Maybe DateTime
dateTime = either (const Nothing) Just . dateTime'
toText :: DateTime -> Text
toText = TL.toStrict . TB.toLazyText . dtBuilder
where
dtBuilder (DtZoned uTime) = ltBuilder (utcToLocalTime utc uTime) <> "Z"
dtBuilder (DtUnzoned lTime) = ltBuilder lTime
ltBuilder (LocalTime day (TimeOfDay hh mm sss)) =
let (y, m, d) = toGregorian day
in buildInt4 y
<> "-"
<> buildUInt2 m
<> "-"
<> buildUInt2 d
<> "T"
<> buildUInt2 hh
<> ":"
<> buildUInt2 mm
<> ":"
<> buildSeconds sss
buildInt4 :: Integer -> TB.Builder
buildInt4 year =
let absYear = abs year
k x = if absYear < x then ("0" <>) else id
in k 1000 . k 100 . k 10 $ TBI.decimal year
buildUInt2 :: Int -> TB.Builder
buildUInt2 x = (if x < 10 then ("0" <>) else id) $ TBI.decimal x
buildSeconds :: Pico -> TB.Builder
buildSeconds secs = (if secs < 10 then ("0" <>) else id)
$ TB.fromString (showFixed True secs)
-- | Converts a zoned time to a @dateTime@.
fromZonedTime :: ZonedTime -> DateTime
fromZonedTime = fromUTCTime . zonedTimeToUTC
-- | Whether the given @dateTime@ is timezoned.
isZoned :: DateTime -> Bool
isZoned (DtZoned _) = True
isZoned (DtUnzoned _) = False
-- | Whether the given @dateTime@ is non-timezoned.
isUnzoned :: DateTime -> Bool
isUnzoned = not . isZoned
-- | Attempts to convert a @dateTime@ to a UTC time. The attempt fails
-- if the given @dateTime@ is non-timezoned.
toUTCTime :: DateTime -> Maybe UTCTime
toUTCTime (DtZoned time) = Just time
toUTCTime _ = Nothing
-- | Converts a UTC time to a timezoned @dateTime@.
fromUTCTime :: UTCTime -> DateTime
fromUTCTime = DtZoned
-- | Attempts to convert a @dateTime@ to a local time. The attempt
-- fails if the given @dateTime@ is timezoned.
toLocalTime :: DateTime -> Maybe LocalTime
toLocalTime (DtUnzoned time) = Just time
toLocalTime _ = Nothing
-- | Converts a local time to an non-timezoned @dateTime@.
fromLocalTime :: LocalTime -> DateTime
fromLocalTime = DtUnzoned
-- | Parses the string in a @dateTime@ then converts to a UTC time and
-- may fail with a parse error.
utcTime' :: Text -> Either String UTCTime
utcTime' txt = dateTime' txt >>= maybe (Left err) Right . toUTCTime
where
err = "input time is non-timezoned"
-- | Parses the string in a @dateTime@ then converts to a UTC time and
-- may fail.
utcTime :: Text -> Maybe UTCTime
utcTime txt = dateTime txt >>= toUTCTime
-- | Parses the string in a @dateTime@ then converts to a local time
-- and may fail with a parse error.
localTime' :: Text -> Either String LocalTime
localTime' txt = dateTime' txt >>= maybe (Left err) Right . toLocalTime
where
err = "input time is non-timezoned"
-- | Parses the string in a @dateTime@ then converts to a local time
-- time and may fail.
localTime :: Text -> Maybe LocalTime
localTime txt = dateTime txt >>= toLocalTime
-- | Parser of the @dateTime@ lexical representation.
parseDateTime :: Parser DateTime
parseDateTime = do yy <- yearParser
_ <- char '-'
mm <- p2imax 12
_ <- char '-'
dd <- p2imax (monthLength (isLeapYear $ fromIntegral yy) mm)
_ <- char 'T'
hhh <- p2imax 24
_ <- char ':'
mmm <- p2imax 59
_ <- char ':'
sss <- secondParser
when (hhh == 24 && (mmm /= 0 || sss /= 0))
$ fail "invalid time, past 24:00:00"
o <- parseOffset
return $ mkDateTime yy mm dd hhh mmm sss o
-- | Parse timezone offset.
parseOffset :: Parser (Maybe Pico)
parseOffset = (A.endOfInput *> pure Nothing)
<|>
(char 'Z' *> pure (Just 0))
<|>
(do sign <- (char '+' *> pure 1) <|> (char '-' *> pure (-1))
hh <- fromIntegral <$> p2imax 14
_ <- char ':'
mm <- fromIntegral <$> p2imax (if hh == 14 then 0 else 59)
return . Just $ sign * (hh * 3600 + mm * 60))
yearParser :: Parser Integer
yearParser = do sign <- (char '-' *> pure (-1)) <|> pure 1
ds <- A.takeWhile isDigit
when (T.length ds < 4)
$ fail "need at least four digits in year"
when (T.length ds > 4 && T.head ds == '0')
$ fail "leading zero in year"
let Right (absyear, _) = TR.decimal ds
when (absyear == 0)
$ fail "year zero disallowed"
return $ sign * absyear
secondParser :: Parser Pico
secondParser = do d1 <- digit
d2 <- digit
frac <- readFrac <$> (char '.' *> A.takeWhile isDigit)
<|> pure 0
return (read [d1, d2] + frac)
where
readFrac ds = read $ '0' : '.' : T.unpack ds
p2imax :: Int -> Parser Int
p2imax m = do a <- digit
b <- digit
let n = 10 * val a + val b
if n > m
then fail $ "value " ++ show n ++ " exceeded maximum " ++ show m
else return n
where
val c = ord c - ord '0'
|
skogsbaer/xsd
|
Text/XML/XSD/DateTime.hs
|
Haskell
|
bsd-3-clause
| 8,178
|
{-# LANGUAGE FlexibleContexts #-}
module Data.Stack
( Stack
, evalStack
, push
, pop
) where
import Control.Applicative
import Control.Monad.State.Strict
type Stack a = State [a]
pop :: (Applicative m, MonadState [a] m) => m a
pop = gets head <* modify tail
push :: (Applicative m, MonadState [a] m) => a -> m ()
push a = modify (a:)
evalStack = evalState
|
kirbyfan64/sodium
|
src/Data/Stack.hs
|
Haskell
|
bsd-3-clause
| 367
|
-- !!! Testing Read (assuming that Eq, Show and Enum work!)
module TestRead where
import Ratio(Ratio,Rational,(%))
import List(zip4,zip5,zip6,zip7)
import Char(isLatin1)
-- test that expected equality holds
tst :: (Read a, Show a, Eq a) => a -> Bool
tst x = read (show x) == x
-- measure degree of error
diff :: (Read a, Show a, Num a) => a -> a
diff x = read (show x) - x
----------------------------------------------------------------
-- Tests for hand-written instances
----------------------------------------------------------------
test1 = tst ()
test2 = all tst [False,True]
test3 = all tst $ takeWhile isLatin1 [minBound::Char ..]
test4 = all tst [Nothing, Just (Just True)]
test5 = all tst [Left True, Right (Just True)]
test6 = all tst [LT .. GT]
test7 = all tst [[],['a'..'z'],['A'..'Z']]
test8 = all tst $ [minBound,maxBound]
++ [-100..100 :: Int]
test9 = all tst $ [(fromIntegral (minBound::Int))-1, (fromIntegral (maxBound::Int))+1]
++ [-100..100 :: Integer]
-- we don't test fractional Floats/Doubles because they don't work
test10 = all tst $ [-100..100 :: Float]
test11 = all tst $ [-100..100 :: Double]
test12 = all tst $ [-2%2,-1%2,0%2,1%2,2%2]
++ [-10.0,-9.9..10.0 :: Ratio Int]
test13 = all tst $ [-2%2,-1%2,0%2,1%2,2%2]
++ [-10.0,-9.9..10.0 :: Rational]
----------------------------------------------------------------
-- Tests for derived instances
----------------------------------------------------------------
-- Tuples
test21 = all tst $ [-1..1]
test22 = all tst $ zip [-1..1] [-1..1]
test23 = all tst $ zip3 [-1..1] [-1..1] [-1..1]
test24 = all tst $ zip4 [-1..1] [-1..1] [-1..1] [-1..1]
test25 = all tst $ zip5 [-1..1] [-1..1] [-1..1] [-1..1] [-1..1]
{- Not derived automatically
test26 = all tst $ zip6 [-1..1] [-1..1] [-1..1] [-1..1] [-1..1] [-1..1]
test27 = all tst $ zip7 [-1..1] [-1..1] [-1..1] [-1..1] [-1..1] [-1..1] [-1..1]
-}
-- Enumeration
data T1 = C1 | C2 | C3 | C4 | C5 | C6 | C7
deriving (Eq, Enum, Read, Show)
test30 = all tst [C1 .. C7]
-- Records
data T2 = A Int | B {x,y::Int, z::Bool} | C Bool
deriving (Eq, Read, Show)
test31 = all tst [A 1, B 1 2 True, C True]
-- newtype
newtype T3 = T3 Int
deriving (Eq, Read, Show)
test32 = all tst [ T3 i | i <- [-10..10] ]
----------------------------------------------------------------
-- Random tests for things which have failed in the past
----------------------------------------------------------------
test100 = read "(True)" :: Bool
test101 = tst (pi :: Float)
test102 = diff (pi :: Float)
test103 = tst (pi :: Double)
test104 = diff (pi :: Double)
|
FranklinChen/Hugs
|
tests/rts/read.hs
|
Haskell
|
bsd-3-clause
| 2,665
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
-- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE DeriveFunctor #-}
-- | Abstract Haskell syntax for expressions.
module HsExpr where
#include "HsVersions.h"
-- friends:
import GhcPrelude
import HsDecls
import HsPat
import HsLit
import PlaceHolder ( NameOrRdrName )
import HsExtension
import HsTypes
import HsBinds
-- others:
import TcEvidence
import CoreSyn
import DynFlags ( gopt, GeneralFlag(Opt_PrintExplicitCoercions) )
import Name
import NameSet
import RdrName ( GlobalRdrEnv )
import BasicTypes
import ConLike
import SrcLoc
import Util
import Outputable
import FastString
import Type
-- libraries:
import Data.Data hiding (Fixity(..))
import qualified Data.Data as Data (Fixity(..))
import Data.Maybe (isNothing)
import GHCi.RemoteTypes ( ForeignRef )
import qualified Language.Haskell.TH as TH (Q)
{-
************************************************************************
* *
\subsection{Expressions proper}
* *
************************************************************************
-}
-- * Expressions proper
-- | Located Haskell Expression
type LHsExpr p = Located (HsExpr p)
-- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
-- in a list
-- For details on above see note [Api annotations] in ApiAnnotation
-------------------------
-- | Post-Type checking Expression
--
-- PostTcExpr is an evidence expression attached to the syntax tree by the
-- type checker (c.f. postTcType).
type PostTcExpr = HsExpr GhcTc
-- | Post-Type checking Table
--
-- We use a PostTcTable where there are a bunch of pieces of evidence, more
-- than is convenient to keep individually.
type PostTcTable = [(Name, PostTcExpr)]
noPostTcExpr :: PostTcExpr
noPostTcExpr = HsLit (HsString noSourceText (fsLit "noPostTcExpr"))
noPostTcTable :: PostTcTable
noPostTcTable = []
-------------------------
-- | Syntax Expression
--
-- SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier,
-- by the renamer. It's used for rebindable syntax.
--
-- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for
-- @(>>=)@, and then instantiated by the type checker with its type args
-- etc
--
-- This should desugar to
--
-- > syn_res_wrap $ syn_expr (syn_arg_wraps[0] arg0)
-- > (syn_arg_wraps[1] arg1) ...
--
-- where the actual arguments come from elsewhere in the AST.
-- This could be defined using @PostRn@ and @PostTc@ and such, but it's
-- harder to get it all to work out that way. ('noSyntaxExpr' is hard to
-- write, for example.)
data SyntaxExpr p = SyntaxExpr { syn_expr :: HsExpr p
, syn_arg_wraps :: [HsWrapper]
, syn_res_wrap :: HsWrapper }
deriving instance (DataId p) => Data (SyntaxExpr p)
-- | This is used for rebindable-syntax pieces that are too polymorphic
-- for tcSyntaxOp (trS_fmap and the mzip in ParStmt)
noExpr :: SourceTextX p => HsExpr p
noExpr = HsLit (HsString (sourceText "noExpr") (fsLit "noExpr"))
noSyntaxExpr :: SourceTextX p => SyntaxExpr p
-- Before renaming, and sometimes after,
-- (if the syntax slot makes no sense)
noSyntaxExpr = SyntaxExpr { syn_expr = HsLit (HsString noSourceText
(fsLit "noSyntaxExpr"))
, syn_arg_wraps = []
, syn_res_wrap = WpHole }
-- | Make a 'SyntaxExpr Name' (the "rn" is because this is used in the
-- renamer), missing its HsWrappers.
mkRnSyntaxExpr :: Name -> SyntaxExpr GhcRn
mkRnSyntaxExpr name = SyntaxExpr { syn_expr = HsVar $ noLoc name
, syn_arg_wraps = []
, syn_res_wrap = WpHole }
-- don't care about filling in syn_arg_wraps because we're clearly
-- not past the typechecker
instance (SourceTextX p, OutputableBndrId p) => Outputable (SyntaxExpr p) where
ppr (SyntaxExpr { syn_expr = expr
, syn_arg_wraps = arg_wraps
, syn_res_wrap = res_wrap })
= sdocWithDynFlags $ \ dflags ->
getPprStyle $ \s ->
if debugStyle s || gopt Opt_PrintExplicitCoercions dflags
then ppr expr <> braces (pprWithCommas ppr arg_wraps)
<> braces (ppr res_wrap)
else ppr expr
-- | Command Syntax Table (for Arrow syntax)
type CmdSyntaxTable p = [(Name, HsExpr p)]
-- See Note [CmdSyntaxTable]
{-
Note [CmdSyntaxtable]
~~~~~~~~~~~~~~~~~~~~~
Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps
track of the methods needed for a Cmd.
* Before the renamer, this list is an empty list
* After the renamer, it takes the form @[(std_name, HsVar actual_name)]@
For example, for the 'arr' method
* normal case: (GHC.Control.Arrow.arr, HsVar GHC.Control.Arrow.arr)
* with rebindable syntax: (GHC.Control.Arrow.arr, arr_22)
where @arr_22@ is whatever 'arr' is in scope
* After the type checker, it takes the form [(std_name, <expression>)]
where <expression> is the evidence for the method. This evidence is
instantiated with the class, but is still polymorphic in everything
else. For example, in the case of 'arr', the evidence has type
forall b c. (b->c) -> a b c
where 'a' is the ambient type of the arrow. This polymorphism is
important because the desugarer uses the same evidence at multiple
different types.
This is Less Cool than what we normally do for rebindable syntax, which is to
make fully-instantiated piece of evidence at every use site. The Cmd way
is Less Cool because
* The renamer has to predict which methods are needed.
See the tedious RnExpr.methodNamesCmd.
* The desugarer has to know the polymorphic type of the instantiated
method. This is checked by Inst.tcSyntaxName, but is less flexible
than the rest of rebindable syntax, where the type is less
pre-ordained. (And this flexibility is useful; for example we can
typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.)
-}
-- | An unbound variable; used for treating out-of-scope variables as
-- expression holes
data UnboundVar
= OutOfScope OccName GlobalRdrEnv -- ^ An (unqualified) out-of-scope
-- variable, together with the GlobalRdrEnv
-- with respect to which it is unbound
-- See Note [OutOfScope and GlobalRdrEnv]
| TrueExprHole OccName -- ^ A "true" expression hole (_ or _x)
deriving Data
instance Outputable UnboundVar where
ppr (OutOfScope occ _) = text "OutOfScope" <> parens (ppr occ)
ppr (TrueExprHole occ) = text "ExprHole" <> parens (ppr occ)
unboundVarOcc :: UnboundVar -> OccName
unboundVarOcc (OutOfScope occ _) = occ
unboundVarOcc (TrueExprHole occ) = occ
{-
Note [OutOfScope and GlobalRdrEnv]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To understand why we bundle a GlobalRdrEnv with an out-of-scope variable,
consider the following module:
module A where
foo :: ()
foo = bar
bat :: [Double]
bat = [1.2, 3.4]
$(return [])
bar = ()
bad = False
When A is compiled, the renamer determines that `bar` is not in scope in the
declaration of `foo` (since `bar` is declared in the following inter-splice
group). Once it has finished typechecking the entire module, the typechecker
then generates the associated error message, which specifies both the type of
`bar` and a list of possible in-scope alternatives:
A.hs:6:7: error:
• Variable not in scope: bar :: ()
• ‘bar’ (line 13) is not in scope before the splice on line 11
Perhaps you meant ‘bat’ (line 9)
When it calls RnEnv.unknownNameSuggestions to identify these alternatives, the
typechecker must provide a GlobalRdrEnv. If it provided the current one, which
contains top-level declarations for the entire module, the error message would
incorrectly suggest the out-of-scope `bar` and `bad` as possible alternatives
for `bar` (see Trac #11680). Instead, the typechecker must use the same
GlobalRdrEnv the renamer used when it determined that `bar` is out-of-scope.
To obtain this GlobalRdrEnv, can the typechecker simply use the out-of-scope
`bar`'s location to either reconstruct it (from the current GlobalRdrEnv) or to
look it up in some global store? Unfortunately, no. The problem is that
location information is not always sufficient for this task. This is most
apparent when dealing with the TH function addTopDecls, which adds its
declarations to the FOLLOWING inter-splice group. Consider these declarations:
ex9 = cat -- cat is NOT in scope here
$(do -------------------------------------------------------------
ds <- [d| f = cab -- cat and cap are both in scope here
cat = ()
|]
addTopDecls ds
[d| g = cab -- only cap is in scope here
cap = True
|])
ex10 = cat -- cat is NOT in scope here
$(return []) -----------------------------------------------------
ex11 = cat -- cat is in scope
Here, both occurrences of `cab` are out-of-scope, and so the typechecker needs
the GlobalRdrEnvs which were used when they were renamed. These GlobalRdrEnvs
are different (`cat` is present only in the GlobalRdrEnv for f's `cab'), but the
locations of the two `cab`s are the same (they are both created in the same
splice). Thus, we must include some additional information with each `cab` to
allow the typechecker to obtain the correct GlobalRdrEnv. Clearly, the simplest
information to use is the GlobalRdrEnv itself.
-}
-- | A Haskell expression.
data HsExpr p
= HsVar (Located (IdP p)) -- ^ Variable
-- See Note [Located RdrNames]
| HsUnboundVar UnboundVar -- ^ Unbound variable; also used for "holes"
-- (_ or _x).
-- Turned from HsVar to HsUnboundVar by the
-- renamer, when it finds an out-of-scope
-- variable or hole.
-- Turned into HsVar by type checker, to support
-- deferred type errors.
| HsConLikeOut ConLike -- ^ After typechecker only; must be different
-- HsVar for pretty printing
| HsRecFld (AmbiguousFieldOcc p) -- ^ Variable pointing to record selector
-- Not in use after typechecking
| HsOverLabel (Maybe (IdP p)) FastString
-- ^ Overloaded label (Note [Overloaded labels] in GHC.OverloadedLabels)
-- @Just id@ means @RebindableSyntax@ is in use, and gives the id of the
-- in-scope 'fromLabel'.
-- NB: Not in use after typechecking
| HsIPVar HsIPName -- ^ Implicit parameter (not in use after typechecking)
| HsOverLit (HsOverLit p) -- ^ Overloaded literals
| HsLit (HsLit p) -- ^ Simple (non-overloaded) literals
| HsLam (MatchGroup p (LHsExpr p))
-- ^ Lambda abstraction. Currently always a single match
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
-- 'ApiAnnotation.AnnRarrow',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsLamCase (MatchGroup p (LHsExpr p)) -- ^ Lambda-case
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
-- 'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsApp (LHsExpr p) (LHsExpr p) -- ^ Application
| HsAppType (LHsExpr p) (LHsWcType p) -- ^ Visible type application
--
-- Explicit type argument; e.g f @Int x y
-- NB: Has wildcards, but no implicit quantification
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt',
-- TODO:AZ: Sort out Name
| HsAppTypeOut (LHsExpr p) (LHsWcType GhcRn) -- just for pretty-printing
-- | Operator applications:
-- NB Bracketed ops such as (+) come out as Vars.
-- NB We need an expr for the operator in an OpApp/Section since
-- the typechecker may need to apply the operator to a few types.
| OpApp (LHsExpr p) -- left operand
(LHsExpr p) -- operator
(PostRn p Fixity) -- Renamer adds fixity; bottom until then
(LHsExpr p) -- right operand
-- | Negation operator. Contains the negated expression and the name
-- of 'negate'
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus'
-- For details on above see note [Api annotations] in ApiAnnotation
| NegApp (LHsExpr p)
(SyntaxExpr p)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
-- 'ApiAnnotation.AnnClose' @')'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsPar (LHsExpr p) -- ^ Parenthesised expr; see Note [Parens in HsSyn]
| SectionL (LHsExpr p) -- operand; see Note [Sections in HsSyn]
(LHsExpr p) -- operator
| SectionR (LHsExpr p) -- operator; see Note [Sections in HsSyn]
(LHsExpr p) -- operand
-- | Used for explicit tuples and sections thereof
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| ExplicitTuple
[LHsTupArg p]
Boxity
-- | Used for unboxed sum types
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(#'@,
-- 'ApiAnnotation.AnnVbar', 'ApiAnnotation.AnnClose' @'#)'@,
--
-- There will be multiple 'ApiAnnotation.AnnVbar', (1 - alternative) before
-- the expression, (arity - alternative) after it
| ExplicitSum
ConTag -- Alternative (one-based)
Arity -- Sum arity
(LHsExpr p)
(PostTc p [Type]) -- the type arguments
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
-- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCase (LHsExpr p)
(MatchGroup p (LHsExpr p))
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
-- 'ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnElse',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsIf (Maybe (SyntaxExpr p)) -- cond function
-- Nothing => use the built-in 'if'
-- See Note [Rebindable if]
(LHsExpr p) -- predicate
(LHsExpr p) -- then part
(LHsExpr p) -- else part
-- | Multi-way if
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf'
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsMultiIf (PostTc p Type) [LGRHS p (LHsExpr p)]
-- | let(rec)
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
-- 'ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsLet (LHsLocalBinds p)
(LHsExpr p)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
-- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsDo (HsStmtContext Name) -- The parameterisation is unimportant
-- because in this context we never use
-- the PatGuard or ParStmt variant
(Located [ExprLStmt p]) -- "do":one or more stmts
(PostTc p Type) -- Type of the whole expression
-- | Syntactic list: [a,b,c,...]
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
-- 'ApiAnnotation.AnnClose' @']'@
-- For details on above see note [Api annotations] in ApiAnnotation
| ExplicitList
(PostTc p Type) -- Gives type of components of list
(Maybe (SyntaxExpr p))
-- For OverloadedLists, the fromListN witness
[LHsExpr p]
-- | Syntactic parallel array: [:e1, ..., en:]
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
-- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma',
-- 'ApiAnnotation.AnnVbar'
-- 'ApiAnnotation.AnnClose' @':]'@
-- For details on above see note [Api annotations] in ApiAnnotation
| ExplicitPArr
(PostTc p Type) -- type of elements of the parallel array
[LHsExpr p]
-- | Record construction
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| RecordCon
{ rcon_con_name :: Located (IdP p) -- The constructor name;
-- not used after type checking
, rcon_con_like :: PostTc p ConLike
-- The data constructor or pattern synonym
, rcon_con_expr :: PostTcExpr -- Instantiated constructor function
, rcon_flds :: HsRecordBinds p } -- The fields
-- | Record update
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| RecordUpd
{ rupd_expr :: LHsExpr p
, rupd_flds :: [LHsRecUpdField p]
, rupd_cons :: PostTc p [ConLike]
-- Filled in by the type checker to the
-- _non-empty_ list of DataCons that have
-- all the upd'd fields
, rupd_in_tys :: PostTc p [Type] -- Argument types of *input* record type
, rupd_out_tys :: PostTc p [Type] -- and *output* record type
-- The original type can be reconstructed
-- with conLikeResTy
, rupd_wrap :: PostTc p HsWrapper -- See note [Record Update HsWrapper]
}
-- For a type family, the arg types are of the *instance* tycon,
-- not the family tycon
-- | Expression with an explicit type signature. @e :: type@
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
-- For details on above see note [Api annotations] in ApiAnnotation
| ExprWithTySig
(LHsExpr p)
(LHsSigWcType p)
| ExprWithTySigOut -- Post typechecking
(LHsExpr p)
(LHsSigWcType GhcRn) -- Retain the signature,
-- as HsSigType Name, for
-- round-tripping purposes
-- | Arithmetic sequence
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
-- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
-- 'ApiAnnotation.AnnClose' @']'@
-- For details on above see note [Api annotations] in ApiAnnotation
| ArithSeq
PostTcExpr
(Maybe (SyntaxExpr p))
-- For OverloadedLists, the fromList witness
(ArithSeqInfo p)
-- | Arithmetic sequence for parallel array
--
-- > [:e1..e2:] or [:e1, e2..e3:]
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
-- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
-- 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnClose' @':]'@
-- For details on above see note [Api annotations] in ApiAnnotation
| PArrSeq
PostTcExpr
(ArithSeqInfo p)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@,
-- 'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr',
-- 'ApiAnnotation.AnnClose' @'\#-}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsSCC SourceText -- Note [Pragma source text] in BasicTypes
StringLiteral -- "set cost centre" SCC pragma
(LHsExpr p) -- expr whose cost is to be measured
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CORE'@,
-- 'ApiAnnotation.AnnVal', 'ApiAnnotation.AnnClose' @'\#-}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCoreAnn SourceText -- Note [Pragma source text] in BasicTypes
StringLiteral -- hdaume: core annotation
(LHsExpr p)
-----------------------------------------------------------
-- MetaHaskell Extensions
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnOpenE','ApiAnnotation.AnnOpenEQ',
-- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnCloseQ'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsBracket (HsBracket p)
-- See Note [Pending Splices]
| HsRnBracketOut
(HsBracket GhcRn) -- Output of the renamer is the *original* renamed
-- expression, plus
[PendingRnSplice] -- _renamed_ splices to be type checked
| HsTcBracketOut
(HsBracket GhcRn) -- Output of the type checker is the *original*
-- renamed expression, plus
[PendingTcSplice] -- _typechecked_ splices to be
-- pasted back in by the desugarer
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsSpliceE (HsSplice p)
-----------------------------------------------------------
-- Arrow notation extension
-- | @proc@ notation for Arrows
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc',
-- 'ApiAnnotation.AnnRarrow'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsProc (LPat p) -- arrow abstraction, proc
(LHsCmdTop p) -- body of the abstraction
-- always has an empty stack
---------------------------------------
-- static pointers extension
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsStatic (PostRn p NameSet) -- Free variables of the body
(LHsExpr p) -- Body
---------------------------------------
-- The following are commands, not expressions proper
-- They are only used in the parsing stage and are removed
-- immediately in parser.RdrHsSyn.checkCommand
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
-- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
-- 'ApiAnnotation.AnnRarrowtail'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsArrApp -- Arrow tail, or arrow application (f -< arg)
(LHsExpr p) -- arrow expression, f
(LHsExpr p) -- input expression, arg
(PostTc p Type) -- type of the arrow expressions f,
-- of the form a t t', where arg :: t
HsArrAppType -- higher-order (-<<) or first-order (-<)
Bool -- True => right-to-left (f -< arg)
-- False => left-to-right (arg >- f)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpenB' @'(|'@,
-- 'ApiAnnotation.AnnCloseB' @'|)'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
(LHsExpr p) -- the operator
-- after type-checking, a type abstraction to be
-- applied to the type of the local environment tuple
(Maybe Fixity) -- fixity (filled in by the renamer), for forms that
-- were converted from OpApp's by the renamer
[LHsCmdTop p] -- argument commands
---------------------------------------
-- Haskell program coverage (Hpc) Support
| HsTick
(Tickish (IdP p))
(LHsExpr p) -- sub-expression
| HsBinTick
Int -- module-local tick number for True
Int -- module-local tick number for False
(LHsExpr p) -- sub-expression
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@,
-- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnMinus',
-- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon',
-- 'ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnClose' @'\#-}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsTickPragma -- A pragma introduced tick
SourceText -- Note [Pragma source text] in BasicTypes
(StringLiteral,(Int,Int),(Int,Int))
-- external span for this tick
((SourceText,SourceText),(SourceText,SourceText))
-- Source text for the four integers used in the span.
-- See note [Pragma source text] in BasicTypes
(LHsExpr p)
---------------------------------------
-- These constructors only appear temporarily in the parser.
-- The renamer translates them into the Right Thing.
| EWildPat -- wildcard
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt'
-- For details on above see note [Api annotations] in ApiAnnotation
| EAsPat (Located (IdP p)) -- as pattern
(LHsExpr p)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow'
-- For details on above see note [Api annotations] in ApiAnnotation
| EViewPat (LHsExpr p) -- view pattern
(LHsExpr p)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
-- For details on above see note [Api annotations] in ApiAnnotation
| ELazyPat (LHsExpr p) -- ~ pattern
---------------------------------------
-- Finally, HsWrap appears only in typechecker output
-- The contained Expr is *NOT* itself an HsWrap.
-- See Note [Detecting forced eta expansion] in DsExpr. This invariant
-- is maintained by HsUtils.mkHsWrap.
| HsWrap HsWrapper -- TRANSLATION
(HsExpr p)
deriving instance (DataId p) => Data (HsExpr p)
-- | Located Haskell Tuple Argument
--
-- 'HsTupArg' is used for tuple sections
-- @(,a,)@ is represented by
-- @ExplicitTuple [Missing ty1, Present a, Missing ty3]@
-- Which in turn stands for @(\x:ty1 \y:ty2. (x,a,y))@
type LHsTupArg id = Located (HsTupArg id)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma'
-- For details on above see note [Api annotations] in ApiAnnotation
-- | Haskell Tuple Argument
data HsTupArg id
= Present (LHsExpr id) -- ^ The argument
| Missing (PostTc id Type) -- ^ The argument is missing, but this is its type
deriving instance (DataId id) => Data (HsTupArg id)
tupArgPresent :: LHsTupArg id -> Bool
tupArgPresent (L _ (Present {})) = True
tupArgPresent (L _ (Missing {})) = False
{-
Note [Parens in HsSyn]
~~~~~~~~~~~~~~~~~~~~~~
HsPar (and ParPat in patterns, HsParTy in types) is used as follows
* HsPar is required; the pretty printer does not add parens.
* HsPars are respected when rearranging operator fixities.
So a * (b + c) means what it says (where the parens are an HsPar)
* For ParPat and HsParTy the pretty printer does add parens but this should be
a no-op for ParsedSource, based on the pretty printer round trip feature
introduced in
https://phabricator.haskell.org/rGHC499e43824bda967546ebf95ee33ec1f84a114a7c
* ParPat and HsParTy are pretty printed as '( .. )' regardless of whether or
not they are strictly necessary. This should be addressed when #13238 is
completed, to be treated the same as HsPar.
Note [Sections in HsSyn]
~~~~~~~~~~~~~~~~~~~~~~~~
Sections should always appear wrapped in an HsPar, thus
HsPar (SectionR ...)
The parser parses sections in a wider variety of situations
(See Note [Parsing sections]), but the renamer checks for those
parens. This invariant makes pretty-printing easier; we don't need
a special case for adding the parens round sections.
Note [Rebindable if]
~~~~~~~~~~~~~~~~~~~~
The rebindable syntax for 'if' is a bit special, because when
rebindable syntax is *off* we do not want to treat
(if c then t else e)
as if it was an application (ifThenElse c t e). Why not?
Because we allow an 'if' to return *unboxed* results, thus
if blah then 3# else 4#
whereas that would not be possible using a all to a polymorphic function
(because you can't call a polymorphic function at an unboxed type).
So we use Nothing to mean "use the old built-in typing rule".
Note [Record Update HsWrapper]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is a wrapper in RecordUpd which is used for the *required*
constraints for pattern synonyms. This wrapper is created in the
typechecking and is then directly used in the desugaring without
modification.
For example, if we have the record pattern synonym P,
pattern P :: (Show a) => a -> Maybe a
pattern P{x} = Just x
foo = (Just True) { x = False }
then `foo` desugars to something like
foo = case Just True of
P x -> P False
hence we need to provide the correct dictionaries to P's matcher on
the RHS so that we can build the expression.
Note [Located RdrNames]
~~~~~~~~~~~~~~~~~~~~~~~
A number of syntax elements have seemingly redundant locations attached to them.
This is deliberate, to allow transformations making use of the API Annotations
to easily correlate a Located Name in the RenamedSource with a Located RdrName
in the ParsedSource.
There are unfortunately enough differences between the ParsedSource and the
RenamedSource that the API Annotations cannot be used directly with
RenamedSource, so this allows a simple mapping to be used based on the location.
-}
instance (SourceTextX p, OutputableBndrId p) => Outputable (HsExpr p) where
ppr expr = pprExpr expr
-----------------------
-- pprExpr, pprLExpr, pprBinds call pprDeeper;
-- the underscore versions do not
pprLExpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc
pprLExpr (L _ e) = pprExpr e
pprExpr :: (SourceTextX p, OutputableBndrId p) => HsExpr p -> SDoc
pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
| otherwise = pprDeeper (ppr_expr e)
isQuietHsExpr :: HsExpr id -> Bool
-- Parentheses do display something, but it gives little info and
-- if we go deeper when we go inside them then we get ugly things
-- like (...)
isQuietHsExpr (HsPar _) = True
-- applications don't display anything themselves
isQuietHsExpr (HsApp _ _) = True
isQuietHsExpr (HsAppType _ _) = True
isQuietHsExpr (HsAppTypeOut _ _) = True
isQuietHsExpr (OpApp _ _ _ _) = True
isQuietHsExpr _ = False
pprBinds :: (SourceTextX idL, SourceTextX idR,
OutputableBndrId idL, OutputableBndrId idR)
=> HsLocalBindsLR idL idR -> SDoc
pprBinds b = pprDeeper (ppr b)
-----------------------
ppr_lexpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc
ppr_lexpr e = ppr_expr (unLoc e)
ppr_expr :: forall p. (SourceTextX p, OutputableBndrId p) => HsExpr p -> SDoc
ppr_expr (HsVar (L _ v)) = pprPrefixOcc v
ppr_expr (HsUnboundVar uv)= pprPrefixOcc (unboundVarOcc uv)
ppr_expr (HsConLikeOut c) = pprPrefixOcc c
ppr_expr (HsIPVar v) = ppr v
ppr_expr (HsOverLabel _ l)= char '#' <> ppr l
ppr_expr (HsLit lit) = ppr lit
ppr_expr (HsOverLit lit) = ppr lit
ppr_expr (HsPar e) = parens (ppr_lexpr e)
ppr_expr (HsCoreAnn stc (StringLiteral sta s) e)
= vcat [pprWithSourceText stc (text "{-# CORE")
<+> pprWithSourceText sta (doubleQuotes $ ftext s) <+> text "#-}"
, ppr_lexpr e]
ppr_expr e@(HsApp {}) = ppr_apps e []
ppr_expr e@(HsAppType {}) = ppr_apps e []
ppr_expr e@(HsAppTypeOut {}) = ppr_apps e []
ppr_expr (OpApp e1 op _ e2)
| Just pp_op <- should_print_infix (unLoc op)
= pp_infixly pp_op
| otherwise
= pp_prefixly
where
should_print_infix (HsVar (L _ v)) = Just (pprInfixOcc v)
should_print_infix (HsConLikeOut c)= Just (pprInfixOcc (conLikeName c))
should_print_infix (HsRecFld f) = Just (pprInfixOcc f)
should_print_infix (HsUnboundVar h@TrueExprHole{})
= Just (pprInfixOcc (unboundVarOcc h))
should_print_infix EWildPat = Just (text "`_`")
should_print_infix (HsWrap _ e) = should_print_infix e
should_print_infix _ = Nothing
pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
pp_prefixly
= hang (ppr op) 2 (sep [pp_e1, pp_e2])
pp_infixly pp_op
= hang pp_e1 2 (sep [pp_op, nest 2 pp_e2])
ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
ppr_expr (SectionL expr op)
= case unLoc op of
HsVar (L _ v) -> pp_infixly v
HsConLikeOut c -> pp_infixly (conLikeName c)
_ -> pp_prefixly
where
pp_expr = pprDebugParendExpr expr
pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
4 (hsep [pp_expr, text "x_ )"])
pp_infixly v = (sep [pp_expr, pprInfixOcc v])
ppr_expr (SectionR op expr)
= case unLoc op of
HsVar (L _ v) -> pp_infixly v
HsConLikeOut c -> pp_infixly (conLikeName c)
_ -> pp_prefixly
where
pp_expr = pprDebugParendExpr expr
pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, text "x_"])
4 (pp_expr <> rparen)
pp_infixly v = sep [pprInfixOcc v, pp_expr]
ppr_expr (ExplicitTuple exprs boxity)
= tupleParens (boxityTupleSort boxity) (fcat (ppr_tup_args $ map unLoc exprs))
where
ppr_tup_args [] = []
ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es
ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es
punc (Present {} : _) = comma <> space
punc (Missing {} : _) = comma
punc [] = empty
ppr_expr (ExplicitSum alt arity expr _)
= text "(#" <+> ppr_bars (alt - 1) <+> ppr expr <+> ppr_bars (arity - alt) <+> text "#)"
where
ppr_bars n = hsep (replicate n (char '|'))
ppr_expr (HsLam matches)
= pprMatches matches
ppr_expr (HsLamCase matches)
= sep [ sep [text "\\case"],
nest 2 (pprMatches matches) ]
ppr_expr (HsCase expr matches@(MG { mg_alts = L _ [_] }))
= sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")],
nest 2 (pprMatches matches) <+> char '}']
ppr_expr (HsCase expr matches)
= sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of")],
nest 2 (pprMatches matches) ]
ppr_expr (HsIf _ e1 e2 e3)
= sep [hsep [text "if", nest 2 (ppr e1), ptext (sLit "then")],
nest 4 (ppr e2),
text "else",
nest 4 (ppr e3)]
ppr_expr (HsMultiIf _ alts)
= hang (text "if") 3 (vcat (map ppr_alt alts))
where ppr_alt (L _ (GRHS guards expr)) =
hang vbar 2 (ppr_one one_alt)
where
ppr_one [] = panic "ppr_exp HsMultiIf"
ppr_one (h:t) = hang h 2 (sep t)
one_alt = [ interpp'SP guards
, text "->" <+> pprDeeper (ppr expr) ]
-- special case: let ... in let ...
ppr_expr (HsLet (L _ binds) expr@(L _ (HsLet _ _)))
= sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
ppr_lexpr expr]
ppr_expr (HsLet (L _ binds) expr)
= sep [hang (text "let") 2 (pprBinds binds),
hang (text "in") 2 (ppr expr)]
ppr_expr (HsDo do_or_list_comp (L _ stmts) _) = pprDo do_or_list_comp stmts
ppr_expr (ExplicitList _ _ exprs)
= brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
ppr_expr (ExplicitPArr _ exprs)
= paBrackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
ppr_expr (RecordCon { rcon_con_name = con_id, rcon_flds = rbinds })
= hang (ppr con_id) 2 (ppr rbinds)
ppr_expr (RecordUpd { rupd_expr = L _ aexp, rupd_flds = rbinds })
= hang (ppr aexp) 2 (braces (fsep (punctuate comma (map ppr rbinds))))
ppr_expr (ExprWithTySig expr sig)
= hang (nest 2 (ppr_lexpr expr) <+> dcolon)
4 (ppr sig)
ppr_expr (ExprWithTySigOut expr sig)
= hang (nest 2 (ppr_lexpr expr) <+> dcolon)
4 (ppr sig)
ppr_expr (ArithSeq _ _ info) = brackets (ppr info)
ppr_expr (PArrSeq _ info) = paBrackets (ppr info)
ppr_expr EWildPat = char '_'
ppr_expr (ELazyPat e) = char '~' <> ppr e
ppr_expr (EAsPat v e) = ppr v <> char '@' <> ppr e
ppr_expr (EViewPat p e) = ppr p <+> text "->" <+> ppr e
ppr_expr (HsSCC st (StringLiteral stl lbl) expr)
= sep [ pprWithSourceText st (text "{-# SCC")
-- no doublequotes if stl empty, for the case where the SCC was written
-- without quotes.
<+> pprWithSourceText stl (ftext lbl) <+> text "#-}",
ppr expr ]
ppr_expr (HsWrap co_fn e)
= pprHsWrapper co_fn (\parens -> if parens then pprExpr e
else pprExpr e)
ppr_expr (HsSpliceE s) = pprSplice s
ppr_expr (HsBracket b) = pprHsBracket b
ppr_expr (HsRnBracketOut e []) = ppr e
ppr_expr (HsRnBracketOut e ps) = ppr e $$ text "pending(rn)" <+> ppr ps
ppr_expr (HsTcBracketOut e []) = ppr e
ppr_expr (HsTcBracketOut e ps) = ppr e $$ text "pending(tc)" <+> ppr ps
ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
= hsep [text "proc", ppr pat, ptext (sLit "->"), ppr cmd]
ppr_expr (HsStatic _ e)
= hsep [text "static", ppr e]
ppr_expr (HsTick tickish exp)
= pprTicks (ppr exp) $
ppr tickish <+> ppr_lexpr exp
ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
= pprTicks (ppr exp) $
hcat [text "bintick<",
ppr tickIdTrue,
text ",",
ppr tickIdFalse,
text ">(",
ppr exp, text ")"]
ppr_expr (HsTickPragma _ externalSrcLoc _ exp)
= pprTicks (ppr exp) $
hcat [text "tickpragma<",
pprExternalSrcLoc externalSrcLoc,
text ">(",
ppr exp,
text ")"]
ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
= hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
= hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
= hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
= hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
ppr_expr (HsArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2])
= sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]]
ppr_expr (HsArrForm (L _ (HsConLikeOut c)) (Just _) [arg1, arg2])
= sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc (conLikeName c), pprCmdArg (unLoc arg2)]]
ppr_expr (HsArrForm op _ args)
= hang (text "(|" <+> ppr_lexpr op)
4 (sep (map (pprCmdArg.unLoc) args) <+> text "|)")
ppr_expr (HsRecFld f) = ppr f
-- We must tiresomely make the "id" parameter to the LHsWcType existential
-- because it's different in the HsAppType case and the HsAppTypeOut case
-- | Located Haskell Wildcard Type Expression
data LHsWcTypeX = forall p. (SourceTextX p, OutputableBndrId p)
=> LHsWcTypeX (LHsWcType p)
ppr_apps :: (SourceTextX p, OutputableBndrId p) => HsExpr p
-> [Either (LHsExpr p) LHsWcTypeX]
-> SDoc
ppr_apps (HsApp (L _ fun) arg) args
= ppr_apps fun (Left arg : args)
ppr_apps (HsAppType (L _ fun) arg) args
= ppr_apps fun (Right (LHsWcTypeX arg) : args)
ppr_apps (HsAppTypeOut (L _ fun) arg) args
= ppr_apps fun (Right (LHsWcTypeX arg) : args)
ppr_apps fun args = hang (ppr_expr fun) 2 (sep (map pp args))
where
pp (Left arg) = ppr arg
pp (Right (LHsWcTypeX (HsWC { hswc_body = L _ arg })))
= char '@' <> pprHsType arg
pprExternalSrcLoc :: (StringLiteral,(Int,Int),(Int,Int)) -> SDoc
pprExternalSrcLoc (StringLiteral _ src,(n1,n2),(n3,n4))
= ppr (src,(n1,n2),(n3,n4))
{-
HsSyn records exactly where the user put parens, with HsPar.
So generally speaking we print without adding any parens.
However, some code is internally generated, and in some places
parens are absolutely required; so for these places we use
pprParendLExpr (but don't print double parens of course).
For operator applications we don't add parens, because the operator
fixities should do the job, except in debug mode (-dppr-debug) so we
can see the structure of the parse tree.
-}
pprDebugParendExpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc
pprDebugParendExpr expr
= getPprStyle (\sty ->
if debugStyle sty then pprParendLExpr expr
else pprLExpr expr)
pprParendLExpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc
pprParendLExpr (L _ e) = pprParendExpr e
pprParendExpr :: (SourceTextX p, OutputableBndrId p) => HsExpr p -> SDoc
pprParendExpr expr
| hsExprNeedsParens expr = parens (pprExpr expr)
| otherwise = pprExpr expr
-- Using pprLExpr makes sure that we go 'deeper'
-- I think that is usually (always?) right
hsExprNeedsParens :: HsExpr id -> Bool
-- True of expressions for which '(e)' and 'e'
-- mean the same thing
hsExprNeedsParens (ArithSeq {}) = False
hsExprNeedsParens (PArrSeq {}) = False
hsExprNeedsParens (HsLit {}) = False
hsExprNeedsParens (HsOverLit {}) = False
hsExprNeedsParens (HsVar {}) = False
hsExprNeedsParens (HsUnboundVar {}) = False
hsExprNeedsParens (HsConLikeOut {}) = False
hsExprNeedsParens (HsIPVar {}) = False
hsExprNeedsParens (HsOverLabel {}) = False
hsExprNeedsParens (ExplicitTuple {}) = False
hsExprNeedsParens (ExplicitList {}) = False
hsExprNeedsParens (ExplicitPArr {}) = False
hsExprNeedsParens (HsPar {}) = False
hsExprNeedsParens (HsBracket {}) = False
hsExprNeedsParens (HsRnBracketOut {}) = False
hsExprNeedsParens (HsTcBracketOut {}) = False
hsExprNeedsParens (HsDo sc _ _)
| isListCompExpr sc = False
hsExprNeedsParens (HsRecFld{}) = False
hsExprNeedsParens (RecordCon{}) = False
hsExprNeedsParens (HsSpliceE{}) = False
hsExprNeedsParens (RecordUpd{}) = False
hsExprNeedsParens (HsWrap _ e) = hsExprNeedsParens e
hsExprNeedsParens _ = True
isAtomicHsExpr :: HsExpr id -> Bool
-- True of a single token
isAtomicHsExpr (HsVar {}) = True
isAtomicHsExpr (HsConLikeOut {}) = True
isAtomicHsExpr (HsLit {}) = True
isAtomicHsExpr (HsOverLit {}) = True
isAtomicHsExpr (HsIPVar {}) = True
isAtomicHsExpr (HsOverLabel {}) = True
isAtomicHsExpr (HsUnboundVar {}) = True
isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
isAtomicHsExpr (HsRecFld{}) = True
isAtomicHsExpr _ = False
{-
************************************************************************
* *
\subsection{Commands (in arrow abstractions)}
* *
************************************************************************
We re-use HsExpr to represent these.
-}
-- | Located Haskell Command (for arrow syntax)
type LHsCmd id = Located (HsCmd id)
-- | Haskell Command (e.g. a "statement" in an Arrow proc block)
data HsCmd id
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
-- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
-- 'ApiAnnotation.AnnRarrowtail'
-- For details on above see note [Api annotations] in ApiAnnotation
= HsCmdArrApp -- Arrow tail, or arrow application (f -< arg)
(LHsExpr id) -- arrow expression, f
(LHsExpr id) -- input expression, arg
(PostTc id Type) -- type of the arrow expressions f,
-- of the form a t t', where arg :: t
HsArrAppType -- higher-order (-<<) or first-order (-<)
Bool -- True => right-to-left (f -< arg)
-- False => left-to-right (arg >- f)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpenB' @'(|'@,
-- 'ApiAnnotation.AnnCloseB' @'|)'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |)
(LHsExpr id) -- The operator.
-- After type-checking, a type abstraction to be
-- applied to the type of the local environment tuple
LexicalFixity -- Whether the operator appeared prefix or infix when
-- parsed.
(Maybe Fixity) -- fixity (filled in by the renamer), for forms that
-- were converted from OpApp's by the renamer
[LHsCmdTop id] -- argument commands
| HsCmdApp (LHsCmd id)
(LHsExpr id)
| HsCmdLam (MatchGroup id (LHsCmd id)) -- kappa
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
-- 'ApiAnnotation.AnnRarrow',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdPar (LHsCmd id) -- parenthesised command
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
-- 'ApiAnnotation.AnnClose' @')'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdCase (LHsExpr id)
(MatchGroup id (LHsCmd id)) -- bodies are HsCmd's
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
-- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdIf (Maybe (SyntaxExpr id)) -- cond function
(LHsExpr id) -- predicate
(LHsCmd id) -- then part
(LHsCmd id) -- else part
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
-- 'ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnElse',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdLet (LHsLocalBinds id) -- let(rec)
(LHsCmd id)
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
-- 'ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdDo (Located [CmdLStmt id])
(PostTc id Type) -- Type of the whole expression
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
-- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdWrap HsWrapper
(HsCmd id) -- If cmd :: arg1 --> res
-- wrap :: arg1 "->" arg2
-- Then (HsCmdWrap wrap cmd) :: arg2 --> res
deriving instance (DataId id) => Data (HsCmd id)
-- | Haskell Array Application Type
data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
deriving Data
{- | Top-level command, introducing a new arrow.
This may occur inside a proc (where the stack is empty) or as an
argument of a command-forming operator.
-}
-- | Located Haskell Top-level Command
type LHsCmdTop p = Located (HsCmdTop p)
-- | Haskell Top-level Command
data HsCmdTop p
= HsCmdTop (LHsCmd p)
(PostTc p Type) -- Nested tuple of inputs on the command's stack
(PostTc p Type) -- return type of the command
(CmdSyntaxTable p) -- See Note [CmdSyntaxTable]
deriving instance (DataId p) => Data (HsCmdTop p)
instance (SourceTextX p, OutputableBndrId p) => Outputable (HsCmd p) where
ppr cmd = pprCmd cmd
-----------------------
-- pprCmd and pprLCmd call pprDeeper;
-- the underscore versions do not
pprLCmd :: (SourceTextX p, OutputableBndrId p) => LHsCmd p -> SDoc
pprLCmd (L _ c) = pprCmd c
pprCmd :: (SourceTextX p, OutputableBndrId p) => HsCmd p -> SDoc
pprCmd c | isQuietHsCmd c = ppr_cmd c
| otherwise = pprDeeper (ppr_cmd c)
isQuietHsCmd :: HsCmd id -> Bool
-- Parentheses do display something, but it gives little info and
-- if we go deeper when we go inside them then we get ugly things
-- like (...)
isQuietHsCmd (HsCmdPar _) = True
-- applications don't display anything themselves
isQuietHsCmd (HsCmdApp _ _) = True
isQuietHsCmd _ = False
-----------------------
ppr_lcmd :: (SourceTextX p, OutputableBndrId p) => LHsCmd p -> SDoc
ppr_lcmd c = ppr_cmd (unLoc c)
ppr_cmd :: forall p. (SourceTextX p, OutputableBndrId p) => HsCmd p -> SDoc
ppr_cmd (HsCmdPar c) = parens (ppr_lcmd c)
ppr_cmd (HsCmdApp c e)
= let (fun, args) = collect_args c [e] in
hang (ppr_lcmd fun) 2 (sep (map ppr args))
where
collect_args (L _ (HsCmdApp fun arg)) args = collect_args fun (arg:args)
collect_args fun args = (fun, args)
ppr_cmd (HsCmdLam matches)
= pprMatches matches
ppr_cmd (HsCmdCase expr matches)
= sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of")],
nest 2 (pprMatches matches) ]
ppr_cmd (HsCmdIf _ e ct ce)
= sep [hsep [text "if", nest 2 (ppr e), ptext (sLit "then")],
nest 4 (ppr ct),
text "else",
nest 4 (ppr ce)]
-- special case: let ... in let ...
ppr_cmd (HsCmdLet (L _ binds) cmd@(L _ (HsCmdLet _ _)))
= sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
ppr_lcmd cmd]
ppr_cmd (HsCmdLet (L _ binds) cmd)
= sep [hang (text "let") 2 (pprBinds binds),
hang (text "in") 2 (ppr cmd)]
ppr_cmd (HsCmdDo (L _ stmts) _) = pprDo ArrowExpr stmts
ppr_cmd (HsCmdWrap w cmd)
= pprHsWrapper w (\_ -> parens (ppr_cmd cmd))
ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp True)
= hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp False)
= hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp True)
= hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp False)
= hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) _ (Just _) [arg1, arg2])
= hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc v
, pprCmdArg (unLoc arg2)])
ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) Infix _ [arg1, arg2])
= hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc v
, pprCmdArg (unLoc arg2)])
ppr_cmd (HsCmdArrForm (L _ (HsConLikeOut c)) _ (Just _) [arg1, arg2])
= hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc (conLikeName c)
, pprCmdArg (unLoc arg2)])
ppr_cmd (HsCmdArrForm (L _ (HsConLikeOut c)) Infix _ [arg1, arg2])
= hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc (conLikeName c)
, pprCmdArg (unLoc arg2)])
ppr_cmd (HsCmdArrForm op _ _ args)
= hang (text "(|" <> ppr_lexpr op)
4 (sep (map (pprCmdArg.unLoc) args) <> text "|)")
pprCmdArg :: (SourceTextX p, OutputableBndrId p) => HsCmdTop p -> SDoc
pprCmdArg (HsCmdTop cmd _ _ _)
= ppr_lcmd cmd
instance (SourceTextX p, OutputableBndrId p) => Outputable (HsCmdTop p) where
ppr = pprCmdArg
{-
************************************************************************
* *
\subsection{Record binds}
* *
************************************************************************
-}
-- | Haskell Record Bindings
type HsRecordBinds p = HsRecFields p (LHsExpr p)
{-
************************************************************************
* *
\subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
* *
************************************************************************
@Match@es are sets of pattern bindings and right hand sides for
functions, patterns or case branches. For example, if a function @g@
is defined as:
\begin{verbatim}
g (x,y) = y
g ((x:ys),y) = y+1,
\end{verbatim}
then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
It is always the case that each element of an @[Match]@ list has the
same number of @pats@s inside it. This corresponds to saying that
a function defined by pattern matching must have the same number of
patterns in each equation.
-}
data MatchGroup p body
= MG { mg_alts :: Located [LMatch p body] -- The alternatives
, mg_arg_tys :: [PostTc p Type] -- Types of the arguments, t1..tn
, mg_res_ty :: PostTc p Type -- Type of the result, tr
, mg_origin :: Origin }
-- The type is the type of the entire group
-- t1 -> ... -> tn -> tr
-- where there are n patterns
deriving instance (Data body,DataId p) => Data (MatchGroup p body)
-- | Located Match
type LMatch id body = Located (Match id body)
-- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a
-- list
-- For details on above see note [Api annotations] in ApiAnnotation
data Match p body
= Match {
m_ctxt :: HsMatchContext (NameOrRdrName (IdP p)),
-- See note [m_ctxt in Match]
m_pats :: [LPat p], -- The patterns
m_grhss :: (GRHSs p body)
}
deriving instance (Data body,DataId p) => Data (Match p body)
instance (SourceTextX idR, OutputableBndrId idR, Outputable body)
=> Outputable (Match idR body) where
ppr = pprMatch
{-
Note [m_ctxt in Match]
~~~~~~~~~~~~~~~~~~~~~~
A Match can occur in a number of contexts, such as a FunBind, HsCase, HsLam and
so on.
In order to simplify tooling processing and pretty print output, the provenance
is captured in an HsMatchContext.
This is particularly important for the API Annotations for a multi-equation
FunBind.
The parser initially creates a FunBind with a single Match in it for
every function definition it sees.
These are then grouped together by getMonoBind into a single FunBind,
where all the Matches are combined.
In the process, all the original FunBind fun_id's bar one are
discarded, including the locations.
This causes a problem for source to source conversions via API
Annotations, so the original fun_ids and infix flags are preserved in
the Match, when it originates from a FunBind.
Example infix function definition requiring individual API Annotations
(&&& ) [] [] = []
xs &&& [] = xs
( &&& ) [] ys = ys
-}
isInfixMatch :: Match id body -> Bool
isInfixMatch match = case m_ctxt match of
FunRhs {mc_fixity = Infix} -> True
_ -> False
isEmptyMatchGroup :: MatchGroup id body -> Bool
isEmptyMatchGroup (MG { mg_alts = ms }) = null $ unLoc ms
-- | Is there only one RHS in this list of matches?
isSingletonMatchGroup :: [LMatch id body] -> Bool
isSingletonMatchGroup matches
| [L _ match] <- matches
, Match { m_grhss = GRHSs { grhssGRHSs = [_] } } <- match
= True
| otherwise
= False
matchGroupArity :: MatchGroup id body -> Arity
-- Precondition: MatchGroup is non-empty
-- This is called before type checking, when mg_arg_tys is not set
matchGroupArity (MG { mg_alts = alts })
| L _ (alt1:_) <- alts = length (hsLMatchPats alt1)
| otherwise = panic "matchGroupArity"
hsLMatchPats :: LMatch id body -> [LPat id]
hsLMatchPats (L _ (Match { m_pats = pats })) = pats
-- | Guarded Right-Hand Sides
--
-- GRHSs are used both for pattern bindings and for Matches
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose'
-- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnSemi'
-- For details on above see note [Api annotations] in ApiAnnotation
data GRHSs p body
= GRHSs {
grhssGRHSs :: [LGRHS p body], -- ^ Guarded RHSs
grhssLocalBinds :: LHsLocalBinds p -- ^ The where clause
}
deriving instance (Data body,DataId p) => Data (GRHSs p body)
-- | Located Guarded Right-Hand Side
type LGRHS id body = Located (GRHS id body)
-- | Guarded Right Hand Side.
data GRHS id body = GRHS [GuardLStmt id] -- Guards
body -- Right hand side
deriving instance (Data body,DataId id) => Data (GRHS id body)
-- We know the list must have at least one @Match@ in it.
pprMatches :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
=> MatchGroup idR body -> SDoc
pprMatches MG { mg_alts = matches }
= vcat (map pprMatch (map unLoc (unLoc matches)))
-- Don't print the type; it's only a place-holder before typechecking
-- Exported to HsBinds, which can't see the defn of HsMatchContext
pprFunBind :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
=> MatchGroup idR body -> SDoc
pprFunBind matches = pprMatches matches
-- Exported to HsBinds, which can't see the defn of HsMatchContext
pprPatBind :: forall bndr p body. (SourceTextX p, SourceTextX bndr,
OutputableBndrId bndr,
OutputableBndrId p,
Outputable body)
=> LPat bndr -> GRHSs p body -> SDoc
pprPatBind pat (grhss)
= sep [ppr pat, nest 2 (pprGRHSs (PatBindRhs :: HsMatchContext (IdP p)) grhss)]
pprMatch :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
=> Match idR body -> SDoc
pprMatch match
= sep [ sep (herald : map (nest 2 . pprParendLPat) other_pats)
, nest 2 (pprGRHSs ctxt (m_grhss match)) ]
where
ctxt = m_ctxt match
(herald, other_pats)
= case ctxt of
FunRhs {mc_fun=L _ fun, mc_fixity=fixity, mc_strictness=strictness}
| strictness == SrcStrict -> ASSERT(null $ m_pats match)
(char '!'<>pprPrefixOcc fun, m_pats match)
-- a strict variable binding
| fixity == Prefix -> (pprPrefixOcc fun, m_pats match)
-- f x y z = e
-- Not pprBndr; the AbsBinds will
-- have printed the signature
| null pats2 -> (pp_infix, [])
-- x &&& y = e
| otherwise -> (parens pp_infix, pats2)
-- (x &&& y) z = e
where
pp_infix = pprParendLPat pat1 <+> pprInfixOcc fun <+> pprParendLPat pat2
LambdaExpr -> (char '\\', m_pats match)
_ -> ASSERT2( null pats1, ppr ctxt $$ ppr pat1 $$ ppr pats1 )
(ppr pat1, []) -- No parens around the single pat
(pat1:pats1) = m_pats match
(pat2:pats2) = pats1
pprGRHSs :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
=> HsMatchContext idL -> GRHSs idR body -> SDoc
pprGRHSs ctxt (GRHSs grhss (L _ binds))
= vcat (map (pprGRHS ctxt . unLoc) grhss)
-- Print the "where" even if the contents of the binds is empty. Only
-- EmptyLocalBinds means no "where" keyword
$$ ppUnless (eqEmptyLocalBinds binds)
(text "where" $$ nest 4 (pprBinds binds))
pprGRHS :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
=> HsMatchContext idL -> GRHS idR body -> SDoc
pprGRHS ctxt (GRHS [] body)
= pp_rhs ctxt body
pprGRHS ctxt (GRHS guards body)
= sep [vbar <+> interpp'SP guards, pp_rhs ctxt body]
pp_rhs :: Outputable body => HsMatchContext idL -> body -> SDoc
pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
{-
************************************************************************
* *
\subsection{Do stmts and list comprehensions}
* *
************************************************************************
-}
-- | Located @do@ block Statement
type LStmt id body = Located (StmtLR id id body)
-- | Located Statement with separate Left and Right id's
type LStmtLR idL idR body = Located (StmtLR idL idR body)
-- | @do@ block Statement
type Stmt id body = StmtLR id id body
-- | Command Located Statement
type CmdLStmt id = LStmt id (LHsCmd id)
-- | Command Statement
type CmdStmt id = Stmt id (LHsCmd id)
-- | Expression Located Statement
type ExprLStmt id = LStmt id (LHsExpr id)
-- | Expression Statement
type ExprStmt id = Stmt id (LHsExpr id)
-- | Guard Located Statement
type GuardLStmt id = LStmt id (LHsExpr id)
-- | Guard Statement
type GuardStmt id = Stmt id (LHsExpr id)
-- | Ghci Located Statement
type GhciLStmt id = LStmt id (LHsExpr id)
-- | Ghci Statement
type GhciStmt id = Stmt id (LHsExpr id)
-- The SyntaxExprs in here are used *only* for do-notation and monad
-- comprehensions, which have rebindable syntax. Otherwise they are unused.
-- | API Annotations when in qualifier lists or guards
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen',
-- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy',
-- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing'
-- For details on above see note [Api annotations] in ApiAnnotation
data StmtLR idL idR body -- body should always be (LHs**** idR)
= LastStmt -- Always the last Stmt in ListComp, MonadComp, PArrComp,
-- and (after the renamer) DoExpr, MDoExpr
-- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff
body
Bool -- True <=> return was stripped by ApplicativeDo
(SyntaxExpr idR) -- The return operator, used only for
-- MonadComp For ListComp, PArrComp, we
-- use the baked-in 'return' For DoExpr,
-- MDoExpr, we don't apply a 'return' at
-- all See Note [Monad Comprehensions] |
-- - 'ApiAnnotation.AnnKeywordId' :
-- 'ApiAnnotation.AnnLarrow'
-- For details on above see note [Api annotations] in ApiAnnotation
| BindStmt (LPat idL)
body
(SyntaxExpr idR) -- The (>>=) operator; see Note [The type of bind in Stmts]
(SyntaxExpr idR) -- The fail operator
-- The fail operator is noSyntaxExpr
-- if the pattern match can't fail
(PostTc idR Type) -- result type of the function passed to bind;
-- that is, S in (>>=) :: Q -> (R -> S) -> T
-- | 'ApplicativeStmt' represents an applicative expression built with
-- <$> and <*>. It is generated by the renamer, and is desugared into the
-- appropriate applicative expression by the desugarer, but it is intended
-- to be invisible in error messages.
--
-- For full details, see Note [ApplicativeDo] in RnExpr
--
| ApplicativeStmt
[ ( SyntaxExpr idR
, ApplicativeArg idL idR) ]
-- [(<$>, e1), (<*>, e2), ..., (<*>, en)]
(Maybe (SyntaxExpr idR)) -- 'join', if necessary
(PostTc idR Type) -- Type of the body
| BodyStmt body -- See Note [BodyStmt]
(SyntaxExpr idR) -- The (>>) operator
(SyntaxExpr idR) -- The `guard` operator; used only in MonadComp
-- See notes [Monad Comprehensions]
(PostTc idR Type) -- Element type of the RHS (used for arrows)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet'
-- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@,
-- For details on above see note [Api annotations] in ApiAnnotation
| LetStmt (LHsLocalBindsLR idL idR)
-- ParStmts only occur in a list/monad comprehension
| ParStmt [ParStmtBlock idL idR]
(HsExpr idR) -- Polymorphic `mzip` for monad comprehensions
(SyntaxExpr idR) -- The `>>=` operator
-- See notes [Monad Comprehensions]
(PostTc idR Type) -- S in (>>=) :: Q -> (R -> S) -> T
-- After renaming, the ids are the binders
-- bound by the stmts and used after themp
| TransStmt {
trS_form :: TransForm,
trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group'
-- which generates the tuples to be grouped
trS_bndrs :: [(IdP idR, IdP idR)], -- See Note [TransStmt binder map]
trS_using :: LHsExpr idR,
trS_by :: Maybe (LHsExpr idR), -- "by e" (optional)
-- Invariant: if trS_form = GroupBy, then grp_by = Just e
trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for
-- the inner monad comprehensions
trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator
trS_bind_arg_ty :: PostTc idR Type, -- R in (>>=) :: Q -> (R -> S) -> T
trS_fmap :: HsExpr idR -- The polymorphic 'fmap' function for desugaring
-- Only for 'group' forms
-- Just a simple HsExpr, because it's
-- too polymorphic for tcSyntaxOp
} -- See Note [Monad Comprehensions]
-- Recursive statement (see Note [How RecStmt works] below)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec'
-- For details on above see note [Api annotations] in ApiAnnotation
| RecStmt
{ recS_stmts :: [LStmtLR idL idR body]
-- The next two fields are only valid after renaming
, recS_later_ids :: [IdP idR]
-- The ids are a subset of the variables bound by the
-- stmts that are used in stmts that follow the RecStmt
, recS_rec_ids :: [IdP idR]
-- Ditto, but these variables are the "recursive" ones,
-- that are used before they are bound in the stmts of
-- the RecStmt.
-- An Id can be in both groups
-- Both sets of Ids are (now) treated monomorphically
-- See Note [How RecStmt works] for why they are separate
-- Rebindable syntax
, recS_bind_fn :: SyntaxExpr idR -- The bind function
, recS_ret_fn :: SyntaxExpr idR -- The return function
, recS_mfix_fn :: SyntaxExpr idR -- The mfix function
, recS_bind_ty :: PostTc idR Type -- S in (>>=) :: Q -> (R -> S) -> T
-- These fields are only valid after typechecking
, recS_later_rets :: [PostTcExpr] -- (only used in the arrow version)
, recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1
-- with recS_later_ids and recS_rec_ids,
-- and are the expressions that should be
-- returned by the recursion.
-- They may not quite be the Ids themselves,
-- because the Id may be *polymorphic*, but
-- the returned thing has to be *monomorphic*,
-- so they may be type applications
, recS_ret_ty :: PostTc idR Type -- The type of
-- do { stmts; return (a,b,c) }
-- With rebindable syntax the type might not
-- be quite as simple as (m (tya, tyb, tyc)).
}
deriving instance (Data body, DataId idL, DataId idR)
=> Data (StmtLR idL idR body)
data TransForm -- The 'f' below is the 'using' function, 'e' is the by function
= ThenForm -- then f or then f by e (depending on trS_by)
| GroupForm -- then group using f or then group by e using f (depending on trS_by)
deriving Data
-- | Parenthesised Statement Block
data ParStmtBlock idL idR
= ParStmtBlock
[ExprLStmt idL]
[IdP idR] -- The variables to be returned
(SyntaxExpr idR) -- The return operator
deriving instance (DataId idL, DataId idR) => Data (ParStmtBlock idL idR)
-- | Applicative Argument
data ApplicativeArg idL idR
= ApplicativeArgOne -- A single statement (BindStmt or BodyStmt)
(LPat idL) -- WildPat if it was a BodyStmt (see below)
(LHsExpr idL)
Bool -- True <=> was a BodyStmt
-- False <=> was a BindStmt
-- See Note [Applicative BodyStmt]
| ApplicativeArgMany -- do { stmts; return vars }
[ExprLStmt idL] -- stmts
(HsExpr idL) -- return (v1,..,vn), or just (v1,..,vn)
(LPat idL) -- (v1,...,vn)
deriving instance (DataId idL, DataId idR) => Data (ApplicativeArg idL idR)
{-
Note [The type of bind in Stmts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some Stmts, notably BindStmt, keep the (>>=) bind operator.
We do NOT assume that it has type
(>>=) :: m a -> (a -> m b) -> m b
In some cases (see Trac #303, #1537) it might have a more
exotic type, such as
(>>=) :: m i j a -> (a -> m j k b) -> m i k b
So we must be careful not to make assumptions about the type.
In particular, the monad may not be uniform throughout.
Note [TransStmt binder map]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The [(idR,idR)] in a TransStmt behaves as follows:
* Before renaming: []
* After renaming:
[ (x27,x27), ..., (z35,z35) ]
These are the variables
bound by the stmts to the left of the 'group'
and used either in the 'by' clause,
or in the stmts following the 'group'
Each item is a pair of identical variables.
* After typechecking:
[ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ]
Each pair has the same unique, but different *types*.
Note [BodyStmt]
~~~~~~~~~~~~~~~
BodyStmts are a bit tricky, because what they mean
depends on the context. Consider the following contexts:
A do expression of type (m res_ty)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BodyStmt E any_ty: do { ....; E; ... }
E :: m any_ty
Translation: E >> ...
A list comprehensions of type [elt_ty]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BodyStmt E Bool: [ .. | .... E ]
[ .. | ..., E, ... ]
[ .. | .... | ..., E | ... ]
E :: Bool
Translation: if E then fail else ...
A guard list, guarding a RHS of type rhs_ty
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs...
E :: Bool
Translation: if E then fail else ...
A monad comprehension of type (m res_ty)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BodyStmt E Bool: [ .. | .... E ]
E :: Bool
Translation: guard E >> ...
Array comprehensions are handled like list comprehensions.
Note [How RecStmt works]
~~~~~~~~~~~~~~~~~~~~~~~~
Example:
HsDo [ BindStmt x ex
, RecStmt { recS_rec_ids = [a, c]
, recS_stmts = [ BindStmt b (return (a,c))
, LetStmt a = ...b...
, BindStmt c ec ]
, recS_later_ids = [a, b]
, return (a b) ]
Here, the RecStmt binds a,b,c; but
- Only a,b are used in the stmts *following* the RecStmt,
- Only a,c are used in the stmts *inside* the RecStmt
*before* their bindings
Why do we need *both* rec_ids and later_ids? For monads they could be
combined into a single set of variables, but not for arrows. That
follows from the types of the respective feedback operators:
mfix :: MonadFix m => (a -> m a) -> m a
loop :: ArrowLoop a => a (b,d) (c,d) -> a b c
* For mfix, the 'a' covers the union of the later_ids and the rec_ids
* For 'loop', 'c' is the later_ids and 'd' is the rec_ids
Note [Typing a RecStmt]
~~~~~~~~~~~~~~~~~~~~~~~
A (RecStmt stmts) types as if you had written
(v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) ->
do { stmts
; return (v1,..vn, r1, ..., rm) })
where v1..vn are the later_ids
r1..rm are the rec_ids
Note [Monad Comprehensions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Monad comprehensions require separate functions like 'return' and
'>>=' for desugaring. These functions are stored in the statements
used in monad comprehensions. For example, the 'return' of the 'LastStmt'
expression is used to lift the body of the monad comprehension:
[ body | stmts ]
=>
stmts >>= \bndrs -> return body
In transform and grouping statements ('then ..' and 'then group ..') the
'return' function is required for nested monad comprehensions, for example:
[ body | stmts, then f, rest ]
=>
f [ env | stmts ] >>= \bndrs -> [ body | rest ]
BodyStmts require the 'Control.Monad.guard' function for boolean
expressions:
[ body | exp, stmts ]
=>
guard exp >> [ body | stmts ]
Parallel statements require the 'Control.Monad.Zip.mzip' function:
[ body | stmts1 | stmts2 | .. ]
=>
mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body
In any other context than 'MonadComp', the fields for most of these
'SyntaxExpr's stay bottom.
Note [Applicative BodyStmt]
(#12143) For the purposes of ApplicativeDo, we treat any BodyStmt
as if it was a BindStmt with a wildcard pattern. For example,
do
x <- A
B
return x
is transformed as if it were
do
x <- A
_ <- B
return x
so it transforms to
(\(x,_) -> x) <$> A <*> B
But we have to remember when we treat a BodyStmt like a BindStmt,
because in error messages we want to emit the original syntax the user
wrote, not our internal representation. So ApplicativeArgOne has a
Bool flag that is True when the original statement was a BodyStmt, so
that we can pretty-print it correctly.
-}
instance (SourceTextX idL, OutputableBndrId idL)
=> Outputable (ParStmtBlock idL idR) where
ppr (ParStmtBlock stmts _ _) = interpp'SP stmts
instance (SourceTextX idL, SourceTextX idR,
OutputableBndrId idL, OutputableBndrId idR, Outputable body)
=> Outputable (StmtLR idL idR body) where
ppr stmt = pprStmt stmt
pprStmt :: forall idL idR body . (SourceTextX idL, SourceTextX idR,
OutputableBndrId idL, OutputableBndrId idR,
Outputable body)
=> (StmtLR idL idR body) -> SDoc
pprStmt (LastStmt expr ret_stripped _)
= whenPprDebug (text "[last]") <+>
(if ret_stripped then text "return" else empty) <+>
ppr expr
pprStmt (BindStmt pat expr _ _ _) = hsep [ppr pat, larrow, ppr expr]
pprStmt (LetStmt (L _ binds)) = hsep [text "let", pprBinds binds]
pprStmt (BodyStmt expr _ _ _) = ppr expr
pprStmt (ParStmt stmtss _ _ _) = sep (punctuate (text " | ") (map ppr stmtss))
pprStmt (TransStmt { trS_stmts = stmts, trS_by = by, trS_using = using, trS_form = form })
= sep $ punctuate comma (map ppr stmts ++ [pprTransStmt by using form])
pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids
, recS_later_ids = later_ids })
= text "rec" <+>
vcat [ ppr_do_stmts segment
, whenPprDebug (vcat [ text "rec_ids=" <> ppr rec_ids
, text "later_ids=" <> ppr later_ids])]
pprStmt (ApplicativeStmt args mb_join _)
= getPprStyle $ \style ->
if userStyle style
then pp_for_user
else pp_debug
where
-- make all the Applicative stuff invisible in error messages by
-- flattening the whole ApplicativeStmt nest back to a sequence
-- of statements.
pp_for_user = vcat $ concatMap flattenArg args
-- ppr directly rather than transforming here, because we need to
-- inject a "return" which is hard when we're polymorphic in the id
-- type.
flattenStmt :: ExprLStmt idL -> [SDoc]
flattenStmt (L _ (ApplicativeStmt args _ _)) = concatMap flattenArg args
flattenStmt stmt = [ppr stmt]
flattenArg (_, ApplicativeArgOne pat expr isBody)
| isBody = -- See Note [Applicative BodyStmt]
[ppr (BodyStmt expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
:: ExprStmt idL)]
| otherwise =
[ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
:: ExprStmt idL)]
flattenArg (_, ApplicativeArgMany stmts _ _) =
concatMap flattenStmt stmts
pp_debug =
let
ap_expr = sep (punctuate (text " |") (map pp_arg args))
in
if isNothing mb_join
then ap_expr
else text "join" <+> parens ap_expr
pp_arg (_, ApplicativeArgOne pat expr isBody)
| isBody = -- See Note [Applicative BodyStmt]
ppr (BodyStmt expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
:: ExprStmt idL)
| otherwise =
ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
:: ExprStmt idL)
pp_arg (_, ApplicativeArgMany stmts return pat) =
ppr pat <+>
text "<-" <+>
ppr (HsDo DoExpr (noLoc
(stmts ++ [noLoc (LastStmt (noLoc return) False noSyntaxExpr)]))
(error "pprStmt"))
pprTransformStmt :: (SourceTextX p, OutputableBndrId p)
=> [IdP p] -> LHsExpr p -> Maybe (LHsExpr p) -> SDoc
pprTransformStmt bndrs using by
= sep [ text "then" <+> whenPprDebug (braces (ppr bndrs))
, nest 2 (ppr using)
, nest 2 (pprBy by)]
pprTransStmt :: Outputable body => Maybe body -> body -> TransForm -> SDoc
pprTransStmt by using ThenForm
= sep [ text "then", nest 2 (ppr using), nest 2 (pprBy by)]
pprTransStmt by using GroupForm
= sep [ text "then group", nest 2 (pprBy by), nest 2 (ptext (sLit "using") <+> ppr using)]
pprBy :: Outputable body => Maybe body -> SDoc
pprBy Nothing = empty
pprBy (Just e) = text "by" <+> ppr e
pprDo :: (SourceTextX p, OutputableBndrId p, Outputable body)
=> HsStmtContext any -> [LStmt p body] -> SDoc
pprDo DoExpr stmts = text "do" <+> ppr_do_stmts stmts
pprDo GhciStmtCtxt stmts = text "do" <+> ppr_do_stmts stmts
pprDo ArrowExpr stmts = text "do" <+> ppr_do_stmts stmts
pprDo MDoExpr stmts = text "mdo" <+> ppr_do_stmts stmts
pprDo ListComp stmts = brackets $ pprComp stmts
pprDo PArrComp stmts = paBrackets $ pprComp stmts
pprDo MonadComp stmts = brackets $ pprComp stmts
pprDo _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
ppr_do_stmts :: (SourceTextX idL, SourceTextX idR,
OutputableBndrId idL, OutputableBndrId idR, Outputable body)
=> [LStmtLR idL idR body] -> SDoc
-- Print a bunch of do stmts
ppr_do_stmts stmts = pprDeeperList vcat (map ppr stmts)
pprComp :: (SourceTextX p, OutputableBndrId p, Outputable body)
=> [LStmt p body] -> SDoc
pprComp quals -- Prints: body | qual1, ..., qualn
| Just (initStmts, L _ (LastStmt body _ _)) <- snocView quals
= if null initStmts
-- If there are no statements in a list comprehension besides the last
-- one, we simply treat it like a normal list. This does arise
-- occasionally in code that GHC generates, e.g., in implementations of
-- 'range' for derived 'Ix' instances for product datatypes with exactly
-- one constructor (e.g., see Trac #12583).
then ppr body
else hang (ppr body <+> vbar) 2 (pprQuals initStmts)
| otherwise
= pprPanic "pprComp" (pprQuals quals)
pprQuals :: (SourceTextX p, OutputableBndrId p, Outputable body)
=> [LStmt p body] -> SDoc
-- Show list comprehension qualifiers separated by commas
pprQuals quals = interpp'SP quals
{-
************************************************************************
* *
Template Haskell quotation brackets
* *
************************************************************************
-}
-- | Haskell Splice
data HsSplice id
= HsTypedSplice -- $$z or $$(f 4)
SpliceDecoration -- Whether $$( ) variant found, for pretty printing
(IdP id) -- A unique name to identify this splice point
(LHsExpr id) -- See Note [Pending Splices]
| HsUntypedSplice -- $z or $(f 4)
SpliceDecoration -- Whether $( ) variant found, for pretty printing
(IdP id) -- A unique name to identify this splice point
(LHsExpr id) -- See Note [Pending Splices]
| HsQuasiQuote -- See Note [Quasi-quote overview] in TcSplice
(IdP id) -- Splice point
(IdP id) -- Quoter
SrcSpan -- The span of the enclosed string
FastString -- The enclosed string
| HsSpliced -- See Note [Delaying modFinalizers in untyped splices] in
-- RnSplice.
-- This is the result of splicing a splice. It is produced by
-- the renamer and consumed by the typechecker. It lives only
-- between the two.
ThModFinalizers -- TH finalizers produced by the splice.
(HsSplicedThing id) -- The result of splicing
deriving Typeable
deriving instance (DataId id) => Data (HsSplice id)
-- | A splice can appear with various decorations wrapped around it. This data
-- type captures explicitly how it was originally written, for use in the pretty
-- printer.
data SpliceDecoration
= HasParens -- ^ $( splice ) or $$( splice )
| HasDollar -- ^ $splice or $$splice
| NoParens -- ^ bare splice
deriving (Data, Eq, Show)
instance Outputable SpliceDecoration where
ppr x = text $ show x
isTypedSplice :: HsSplice id -> Bool
isTypedSplice (HsTypedSplice {}) = True
isTypedSplice _ = False -- Quasi-quotes are untyped splices
-- | Finalizers produced by a splice with
-- 'Language.Haskell.TH.Syntax.addModFinalizer'
--
-- See Note [Delaying modFinalizers in untyped splices] in RnSplice. For how
-- this is used.
--
newtype ThModFinalizers = ThModFinalizers [ForeignRef (TH.Q ())]
-- A Data instance which ignores the argument of 'ThModFinalizers'.
instance Data ThModFinalizers where
gunfold _ z _ = z $ ThModFinalizers []
toConstr a = mkConstr (dataTypeOf a) "ThModFinalizers" [] Data.Prefix
dataTypeOf a = mkDataType "HsExpr.ThModFinalizers" [toConstr a]
-- | Haskell Spliced Thing
--
-- Values that can result from running a splice.
data HsSplicedThing id
= HsSplicedExpr (HsExpr id) -- ^ Haskell Spliced Expression
| HsSplicedTy (HsType id) -- ^ Haskell Spliced Type
| HsSplicedPat (Pat id) -- ^ Haskell Spliced Pattern
deriving Typeable
deriving instance (DataId id) => Data (HsSplicedThing id)
-- See Note [Pending Splices]
type SplicePointName = Name
-- | Pending Renamer Splice
data PendingRnSplice
-- AZ:TODO: The hard-coded GhcRn feels wrong. How to force the PostRn?
= PendingRnSplice UntypedSpliceFlavour SplicePointName (LHsExpr GhcRn)
deriving Data
data UntypedSpliceFlavour
= UntypedExpSplice
| UntypedPatSplice
| UntypedTypeSplice
| UntypedDeclSplice
deriving Data
-- | Pending Type-checker Splice
data PendingTcSplice
-- AZ:TODO: The hard-coded GhcTc feels wrong. How to force the PostTc?
= PendingTcSplice SplicePointName (LHsExpr GhcTc)
deriving Data
{-
Note [Pending Splices]
~~~~~~~~~~~~~~~~~~~~~~
When we rename an untyped bracket, we name and lift out all the nested
splices, so that when the typechecker hits the bracket, it can
typecheck those nested splices without having to walk over the untyped
bracket code. So for example
[| f $(g x) |]
looks like
HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x)))
which the renamer rewrites to
HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x)))
[PendingRnSplice UntypedExpSplice sn (g x)]
* The 'sn' is the Name of the splice point, the SplicePointName
* The PendingRnExpSplice gives the splice that splice-point name maps to;
and the typechecker can now conveniently find these sub-expressions
* The other copy of the splice, in the second argument of HsSpliceE
in the renamed first arg of HsRnBracketOut
is used only for pretty printing
There are four varieties of pending splices generated by the renamer,
distinguished by their UntypedSpliceFlavour
* Pending expression splices (UntypedExpSplice), e.g.,
[|$(f x) + 2|]
UntypedExpSplice is also used for
* quasi-quotes, where the pending expression expands to
$(quoter "...blah...")
(see RnSplice.makePending, HsQuasiQuote case)
* cross-stage lifting, where the pending expression expands to
$(lift x)
(see RnSplice.checkCrossStageLifting)
* Pending pattern splices (UntypedPatSplice), e.g.,
[| \$(f x) -> x |]
* Pending type splices (UntypedTypeSplice), e.g.,
[| f :: $(g x) |]
* Pending declaration (UntypedDeclSplice), e.g.,
[| let $(f x) in ... |]
There is a fifth variety of pending splice, which is generated by the type
checker:
* Pending *typed* expression splices, (PendingTcSplice), e.g.,
[||1 + $$(f 2)||]
It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the
output of the renamer. However, when pretty printing the output of the renamer,
e.g., in a type error message, we *do not* want to print out the pending
splices. In contrast, when pretty printing the output of the type checker, we
*do* want to print the pending splices. So splitting them up seems to make
sense, although I hate to add another constructor to HsExpr.
-}
instance (SourceTextX p, OutputableBndrId p)
=> Outputable (HsSplicedThing p) where
ppr (HsSplicedExpr e) = ppr_expr e
ppr (HsSplicedTy t) = ppr t
ppr (HsSplicedPat p) = ppr p
instance (SourceTextX p, OutputableBndrId p) => Outputable (HsSplice p) where
ppr s = pprSplice s
pprPendingSplice :: (SourceTextX p, OutputableBndrId p)
=> SplicePointName -> LHsExpr p -> SDoc
pprPendingSplice n e = angleBrackets (ppr n <> comma <+> ppr e)
pprSpliceDecl :: (SourceTextX p, OutputableBndrId p)
=> HsSplice p -> SpliceExplicitFlag -> SDoc
pprSpliceDecl e@HsQuasiQuote{} _ = pprSplice e
pprSpliceDecl e ExplicitSplice = text "$(" <> ppr_splice_decl e <> text ")"
pprSpliceDecl e ImplicitSplice = ppr_splice_decl e
ppr_splice_decl :: (SourceTextX p, OutputableBndrId p) => HsSplice p -> SDoc
ppr_splice_decl (HsUntypedSplice _ n e) = ppr_splice empty n e empty
ppr_splice_decl e = pprSplice e
pprSplice :: (SourceTextX p, OutputableBndrId p) => HsSplice p -> SDoc
pprSplice (HsTypedSplice HasParens n e)
= ppr_splice (text "$$(") n e (text ")")
pprSplice (HsTypedSplice HasDollar n e)
= ppr_splice (text "$$") n e empty
pprSplice (HsTypedSplice NoParens n e)
= ppr_splice empty n e empty
pprSplice (HsUntypedSplice HasParens n e)
= ppr_splice (text "$(") n e (text ")")
pprSplice (HsUntypedSplice HasDollar n e)
= ppr_splice (text "$") n e empty
pprSplice (HsUntypedSplice NoParens n e)
= ppr_splice empty n e empty
pprSplice (HsQuasiQuote n q _ s) = ppr_quasi n q s
pprSplice (HsSpliced _ thing) = ppr thing
ppr_quasi :: OutputableBndr p => p -> p -> FastString -> SDoc
ppr_quasi n quoter quote = whenPprDebug (brackets (ppr n)) <>
char '[' <> ppr quoter <> vbar <>
ppr quote <> text "|]"
ppr_splice :: (SourceTextX p, OutputableBndrId p)
=> SDoc -> (IdP p) -> LHsExpr p -> SDoc -> SDoc
ppr_splice herald n e trail
= herald <> whenPprDebug (brackets (ppr n)) <> ppr e <> trail
-- | Haskell Bracket
data HsBracket p = ExpBr (LHsExpr p) -- [| expr |]
| PatBr (LPat p) -- [p| pat |]
| DecBrL [LHsDecl p] -- [d| decls |]; result of parser
| DecBrG (HsGroup p) -- [d| decls |]; result of renamer
| TypBr (LHsType p) -- [t| type |]
| VarBr Bool (IdP p) -- True: 'x, False: ''T
-- (The Bool flag is used only in pprHsBracket)
| TExpBr (LHsExpr p) -- [|| expr ||]
deriving instance (DataId p) => Data (HsBracket p)
isTypedBracket :: HsBracket id -> Bool
isTypedBracket (TExpBr {}) = True
isTypedBracket _ = False
instance (SourceTextX p, OutputableBndrId p) => Outputable (HsBracket p) where
ppr = pprHsBracket
pprHsBracket :: (SourceTextX p, OutputableBndrId p) => HsBracket p -> SDoc
pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp)
pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds))
pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
pprHsBracket (VarBr True n)
= char '\'' <> pprPrefixOcc n
pprHsBracket (VarBr False n)
= text "''" <> pprPrefixOcc n
pprHsBracket (TExpBr e) = thTyBrackets (ppr e)
thBrackets :: SDoc -> SDoc -> SDoc
thBrackets pp_kind pp_body = char '[' <> pp_kind <> vbar <+>
pp_body <+> text "|]"
thTyBrackets :: SDoc -> SDoc
thTyBrackets pp_body = text "[||" <+> pp_body <+> ptext (sLit "||]")
instance Outputable PendingRnSplice where
ppr (PendingRnSplice _ n e) = pprPendingSplice n e
instance Outputable PendingTcSplice where
ppr (PendingTcSplice n e) = pprPendingSplice n e
{-
************************************************************************
* *
\subsection{Enumerations and list comprehensions}
* *
************************************************************************
-}
-- | Arithmetic Sequence Information
data ArithSeqInfo id
= From (LHsExpr id)
| FromThen (LHsExpr id)
(LHsExpr id)
| FromTo (LHsExpr id)
(LHsExpr id)
| FromThenTo (LHsExpr id)
(LHsExpr id)
(LHsExpr id)
deriving instance (DataId id) => Data (ArithSeqInfo id)
instance (SourceTextX p, OutputableBndrId p)
=> Outputable (ArithSeqInfo p) where
ppr (From e1) = hcat [ppr e1, pp_dotdot]
ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
ppr (FromThenTo e1 e2 e3)
= hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
pp_dotdot :: SDoc
pp_dotdot = text " .. "
{-
************************************************************************
* *
\subsection{HsMatchCtxt}
* *
************************************************************************
-}
-- | Haskell Match Context
--
-- Context of a pattern match. This is more subtle than it would seem. See Note
-- [Varieties of pattern matches].
data HsMatchContext id -- Not an extensible tag
= FunRhs { mc_fun :: Located id -- ^ function binder of @f@
, mc_fixity :: LexicalFixity -- ^ fixing of @f@
, mc_strictness :: SrcStrictness -- ^ was @f@ banged?
-- See Note [FunBind vs PatBind]
}
-- ^A pattern matching on an argument of a
-- function binding
| LambdaExpr -- ^Patterns of a lambda
| CaseAlt -- ^Patterns and guards on a case alternative
| IfAlt -- ^Guards of a multi-way if alternative
| ProcExpr -- ^Patterns of a proc
| PatBindRhs -- ^A pattern binding eg [y] <- e = e
| RecUpd -- ^Record update [used only in DsExpr to
-- tell matchWrapper what sort of
-- runtime error message to generate]
| StmtCtxt (HsStmtContext id) -- ^Pattern of a do-stmt, list comprehension,
-- pattern guard, etc
| ThPatSplice -- ^A Template Haskell pattern splice
| ThPatQuote -- ^A Template Haskell pattern quotation [p| (a,b) |]
| PatSyn -- ^A pattern synonym declaration
deriving Functor
deriving instance (Data id) => Data (HsMatchContext id)
instance OutputableBndr id => Outputable (HsMatchContext id) where
ppr m@(FunRhs{}) = text "FunRhs" <+> ppr (mc_fun m) <+> ppr (mc_fixity m)
ppr LambdaExpr = text "LambdaExpr"
ppr CaseAlt = text "CaseAlt"
ppr IfAlt = text "IfAlt"
ppr ProcExpr = text "ProcExpr"
ppr PatBindRhs = text "PatBindRhs"
ppr RecUpd = text "RecUpd"
ppr (StmtCtxt _) = text "StmtCtxt _"
ppr ThPatSplice = text "ThPatSplice"
ppr ThPatQuote = text "ThPatQuote"
ppr PatSyn = text "PatSyn"
isPatSynCtxt :: HsMatchContext id -> Bool
isPatSynCtxt ctxt =
case ctxt of
PatSyn -> True
_ -> False
-- | Haskell Statement Context. It expects to be parameterised with one of
-- 'RdrName', 'Name' or 'Id'
data HsStmtContext id
= ListComp
| MonadComp
| PArrComp -- ^Parallel array comprehension
| DoExpr -- ^do { ... }
| MDoExpr -- ^mdo { ... } ie recursive do-expression
| ArrowExpr -- ^do-notation in an arrow-command context
| GhciStmtCtxt -- ^A command-line Stmt in GHCi pat <- rhs
| PatGuard (HsMatchContext id) -- ^Pattern guard for specified thing
| ParStmtCtxt (HsStmtContext id) -- ^A branch of a parallel stmt
| TransStmtCtxt (HsStmtContext id) -- ^A branch of a transform stmt
deriving Functor
deriving instance (Data id) => Data (HsStmtContext id)
isListCompExpr :: HsStmtContext id -> Bool
-- Uses syntax [ e | quals ]
isListCompExpr ListComp = True
isListCompExpr PArrComp = True
isListCompExpr MonadComp = True
isListCompExpr (ParStmtCtxt c) = isListCompExpr c
isListCompExpr (TransStmtCtxt c) = isListCompExpr c
isListCompExpr _ = False
isMonadCompExpr :: HsStmtContext id -> Bool
isMonadCompExpr MonadComp = True
isMonadCompExpr (ParStmtCtxt ctxt) = isMonadCompExpr ctxt
isMonadCompExpr (TransStmtCtxt ctxt) = isMonadCompExpr ctxt
isMonadCompExpr _ = False
-- | Should pattern match failure in a 'HsStmtContext' be desugared using
-- 'MonadFail'?
isMonadFailStmtContext :: HsStmtContext id -> Bool
isMonadFailStmtContext MonadComp = True
isMonadFailStmtContext DoExpr = True
isMonadFailStmtContext MDoExpr = True
isMonadFailStmtContext GhciStmtCtxt = True
isMonadFailStmtContext _ = False
matchSeparator :: HsMatchContext id -> SDoc
matchSeparator (FunRhs {}) = text "="
matchSeparator CaseAlt = text "->"
matchSeparator IfAlt = text "->"
matchSeparator LambdaExpr = text "->"
matchSeparator ProcExpr = text "->"
matchSeparator PatBindRhs = text "="
matchSeparator (StmtCtxt _) = text "<-"
matchSeparator RecUpd = text "=" -- This can be printed by the pattern
-- match checker trace
matchSeparator ThPatSplice = panic "unused"
matchSeparator ThPatQuote = panic "unused"
matchSeparator PatSyn = panic "unused"
pprMatchContext :: (Outputable (NameOrRdrName id),Outputable id)
=> HsMatchContext id -> SDoc
pprMatchContext ctxt
| want_an ctxt = text "an" <+> pprMatchContextNoun ctxt
| otherwise = text "a" <+> pprMatchContextNoun ctxt
where
want_an (FunRhs {}) = True -- Use "an" in front
want_an ProcExpr = True
want_an _ = False
pprMatchContextNoun :: (Outputable (NameOrRdrName id),Outputable id)
=> HsMatchContext id -> SDoc
pprMatchContextNoun (FunRhs {mc_fun=L _ fun})
= text "equation for"
<+> quotes (ppr fun)
pprMatchContextNoun CaseAlt = text "case alternative"
pprMatchContextNoun IfAlt = text "multi-way if alternative"
pprMatchContextNoun RecUpd = text "record-update construct"
pprMatchContextNoun ThPatSplice = text "Template Haskell pattern splice"
pprMatchContextNoun ThPatQuote = text "Template Haskell pattern quotation"
pprMatchContextNoun PatBindRhs = text "pattern binding"
pprMatchContextNoun LambdaExpr = text "lambda abstraction"
pprMatchContextNoun ProcExpr = text "arrow abstraction"
pprMatchContextNoun (StmtCtxt ctxt) = text "pattern binding in"
$$ pprStmtContext ctxt
pprMatchContextNoun PatSyn = text "pattern synonym declaration"
-----------------
pprAStmtContext, pprStmtContext :: (Outputable id,
Outputable (NameOrRdrName id))
=> HsStmtContext id -> SDoc
pprAStmtContext ctxt = article <+> pprStmtContext ctxt
where
pp_an = text "an"
pp_a = text "a"
article = case ctxt of
MDoExpr -> pp_an
PArrComp -> pp_an
GhciStmtCtxt -> pp_an
_ -> pp_a
-----------------
pprStmtContext GhciStmtCtxt = text "interactive GHCi command"
pprStmtContext DoExpr = text "'do' block"
pprStmtContext MDoExpr = text "'mdo' block"
pprStmtContext ArrowExpr = text "'do' block in an arrow command"
pprStmtContext ListComp = text "list comprehension"
pprStmtContext MonadComp = text "monad comprehension"
pprStmtContext PArrComp = text "array comprehension"
pprStmtContext (PatGuard ctxt) = text "pattern guard for" $$ pprMatchContext ctxt
-- Drop the inner contexts when reporting errors, else we get
-- Unexpected transform statement
-- in a transformed branch of
-- transformed branch of
-- transformed branch of monad comprehension
pprStmtContext (ParStmtCtxt c) =
ifPprDebug (sep [text "parallel branch of", pprAStmtContext c])
(pprStmtContext c)
pprStmtContext (TransStmtCtxt c) =
ifPprDebug (sep [text "transformed branch of", pprAStmtContext c])
(pprStmtContext c)
instance (Outputable p, Outputable (NameOrRdrName p))
=> Outputable (HsStmtContext p) where
ppr = pprStmtContext
-- Used to generate the string for a *runtime* error message
matchContextErrString :: Outputable id
=> HsMatchContext id -> SDoc
matchContextErrString (FunRhs{mc_fun=L _ fun}) = text "function" <+> ppr fun
matchContextErrString CaseAlt = text "case"
matchContextErrString IfAlt = text "multi-way if"
matchContextErrString PatBindRhs = text "pattern binding"
matchContextErrString RecUpd = text "record update"
matchContextErrString LambdaExpr = text "lambda"
matchContextErrString ProcExpr = text "proc"
matchContextErrString ThPatSplice = panic "matchContextErrString" -- Not used at runtime
matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime
matchContextErrString PatSyn = panic "matchContextErrString" -- Not used at runtime
matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
matchContextErrString (StmtCtxt (TransStmtCtxt c)) = matchContextErrString (StmtCtxt c)
matchContextErrString (StmtCtxt (PatGuard _)) = text "pattern guard"
matchContextErrString (StmtCtxt GhciStmtCtxt) = text "interactive GHCi command"
matchContextErrString (StmtCtxt DoExpr) = text "'do' block"
matchContextErrString (StmtCtxt ArrowExpr) = text "'do' block"
matchContextErrString (StmtCtxt MDoExpr) = text "'mdo' block"
matchContextErrString (StmtCtxt ListComp) = text "list comprehension"
matchContextErrString (StmtCtxt MonadComp) = text "monad comprehension"
matchContextErrString (StmtCtxt PArrComp) = text "array comprehension"
pprMatchInCtxt :: (SourceTextX idR, OutputableBndrId idR,
-- TODO:AZ these constraints do not make sense
Outputable (NameOrRdrName (NameOrRdrName (IdP idR))),
Outputable body)
=> Match idR body -> SDoc
pprMatchInCtxt match = hang (text "In" <+> pprMatchContext (m_ctxt match)
<> colon)
4 (pprMatch match)
pprStmtInCtxt :: (SourceTextX idL, SourceTextX idR,
OutputableBndrId idL, OutputableBndrId idR,
Outputable body)
=> HsStmtContext (IdP idL) -> StmtLR idL idR body -> SDoc
pprStmtInCtxt ctxt (LastStmt e _ _)
| isListCompExpr ctxt -- For [ e | .. ], do not mutter about "stmts"
= hang (text "In the expression:") 2 (ppr e)
pprStmtInCtxt ctxt stmt
= hang (text "In a stmt of" <+> pprAStmtContext ctxt <> colon)
2 (ppr_stmt stmt)
where
-- For Group and Transform Stmts, don't print the nested stmts!
ppr_stmt (TransStmt { trS_by = by, trS_using = using
, trS_form = form }) = pprTransStmt by using form
ppr_stmt stmt = pprStmt stmt
|
ezyang/ghc
|
compiler/hsSyn/HsExpr.hs
|
Haskell
|
bsd-3-clause
| 104,032
|
module J ( module J
, module J.Store
) where
import J.Store
data J = J { key :: String
, dst :: String
}
|
KenetJervet/j
|
src/J.hs
|
Haskell
|
bsd-3-clause
| 147
|
module Diag.Util.RecursiveContents (getRecursiveContents) where
import Control.Monad (forM)
import System.Directory (doesDirectoryExist, getDirectoryContents)
import System.FilePath ((</>))
getRecursiveContents :: FilePath -> IO [FilePath]
getRecursiveContents topdir = do
names <- getDirectoryContents topdir
let properNames = filter (`notElem` [".", ".."]) names
paths <- forM properNames $ \name -> do
let path = topdir </> name
isDirectory <- doesDirectoryExist path
if isDirectory
then getRecursiveContents path
else return [path]
return (concat paths)
|
marcmo/hsDiagnosis
|
src/Diag/Util/RecursiveContents.hs
|
Haskell
|
bsd-3-clause
| 593
|
{-# LANGUAGE RankNTypes, TypeOperators, DefaultSignatures #-}
-- | No comparison that I'm aware of
module MHask.Indexed.Layered where
import MHask.Arrow
import qualified MHask.Indexed.Join as MHask
import qualified MHask.Indexed.Duplicate as MHask
-- | IxLayered is its own dual.
class (MHask.IxJoin t, MHask.IxDuplicate t)
=> IxLayered t where
-- | Any instances must satisfy the following laws:
--
-- > iduplicate ~>~ ijoin ≡ identityArrow ∷ t i j m -> t i j m
--
-- Custom implementations should be equivalent to the
-- default implementation
--
-- iwithLayer f ≡ iduplicate ~>~ f ~>~ ijoin
--
-- From all laws required so far, it follows that:
--
-- > iwithLayer (imap (imap f)) ≡ imap f
-- > iwithLayer (imap ijoin) ≡ join
-- > iwithLayer (imap iduplicate) ≡ duplicate
-- > iwithLayer identityArrow ≡ identityArrow
--
-- However, take note that the following are not guaranteed,
-- and are usually not true:
--
-- > ijoin ~>~ iduplicate ≟ identityArrow
-- > iwithLayer (f ~>~ g) ≟ iwithLayer f ~>~ iwithLayer g
iwithLayer :: (Monad m, Monad n)
=> (t i j (t j k m) ~> t i' j' (t j' k' n))
-> (t i k m ~> t i' k' n )
default iwithLayer
:: (Monad m, Monad n,
Monad (t i k m), Monad (t i' k' n),
Monad (t i j (t j k m)), Monad (t i' j' (t j' k' n)))
=> (t i j (t j k m) ~> t i' j' (t j' k' n))
-> (t i k m ~> t i' k' n )
iwithLayer f = MHask.iduplicate ~>~ f ~>~ MHask.ijoin
|
DanBurton/MHask
|
MHask/Indexed/Layered.hs
|
Haskell
|
bsd-3-clause
| 1,543
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Servant.FileUpload.Client.GHC where
import Data.Proxy (Proxy (..))
import Data.Void (Void, absurd)
import Servant.API ((:>))
import Servant.Client (HasClient (..))
import Servant.FileUpload.API
instance (HasClient sublayout)
=> HasClient (MultiPartBody a :> sublayout) where
type Client (MultiPartBody a :> sublayout) = Void -> Client sublayout
clientWithRoute Proxy req void = absurd void
|
rimmington/servant-file-upload
|
servant-file-upload-client/src/Servant/FileUpload/Client/GHC.hs
|
Haskell
|
bsd-3-clause
| 550
|
module Chapter9Exercises where
import Data.Maybe
import Data.Char
-- exercise 2
str = "HbEfLrLxO"
onlyUpperHello = filter isUpper str
-- exercise 3
julie = "julie"
capitalize :: [Char] -> [Char]
capitalize [] = []
capitalize (a:as) = toUpper a : as
-- exercise 4
toAllUpper :: [Char] -> [Char]
toAllUpper [] = []
toAllUpper (a:as) = toUpper a : toAllUpper as
-- exercise 5
capitalizeFirst :: [Char] -> Maybe Char
capitalizeFirst [] = Nothing
capitalizeFirst (a:as) = Just $ toUpper a
capitalizeFirst' :: [Char] -> [Char]
capitalizeFirst' [] = []
capitalizeFirst' (a:as) = [toUpper a]
-- exercise 6
-- as composed
capitalizeFirst'' :: [Char] -> [Char]
capitalizeFirst'' [] = []
capitalizeFirst'' as = [(toUpper . head) as]
-- as composed point-free
-- I can't figure out how to make this point-free
-- *and* total. If I include [] = [] and the
-- point-free version together (without the case
-- version) I get:
-- Chapter9.hs:45:1: error:
-- Equations for `capitalizeFirst_' have different numbers of arguments
-- Chapter9.hs:45:1-24
-- Chapter9.hs:46:1-47
-- Failed, modules loaded: none.
-- but if I change it to handle the empty list
-- it's not point-free...
capitalizeFirst_ :: [Char] -> [Char]
-- capitalizeFirst_ [] = []
capitalizeFirst_ xs =
case length xs of
0 -> []
_ -> ((\c -> [c]) . toUpper . head) xs
--capitalizeFirst_ = (\c -> [c]) . toUpper . head
|
brodyberg/Notes
|
ProjectRosalind.hsproj/LearnHaskell/lib/HaskellBook/Chapter9.hs
|
Haskell
|
mit
| 1,403
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ParallelListComp #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RecordWildCards #-}
-- | A very simple Graphical User Interface (GUI) for user interaction with
-- buttons, checkboxes, sliders and a few others.
module Extras.Widget(
-- $intro
guiDrawingOf, guiActivityOf
-- * Widgets
, Widget, toggle, button, slider, randomBox, timer, counter
-- * Convenience functions
, withConversion, setConversion
-- * Examples
, widgetExample1, widgetExample2, widgetExample3, widgetExample4
) where
import Prelude
--------------------------------------------------------------------------------
-- $intro
-- = Widget API
--
-- To use the extra features in this module, you must begin your code with this
-- line:
--
-- > import Extras.Widget
-- | The function @guiDrawingOf@ is an entry point for drawing that allows
-- access to a simple GUI. It needs two arguments: a list of
-- Widgets and a function to create your drawing. This user-supplied drawing
-- function will have access to the list of the current values of the widgets,
-- which is passed as an argument.
--
-- Example of use:
--
-- > program = guiDrawingOf(widgets,draw)
-- > where
-- > widgets = [ withConversion(\v -> 1 + 19 * v , slider("width" ,-7,-7))
-- > , withConversion(\v -> 1 + 19 * v , slider("height" ,-7,-9))
-- > , withConversion(flipflop , toggle("show circle" ,-7,-5))
-- > , withConversion(flipflop , button("show in green",-7,-3))
-- > , withConversion(\v -> 0.2 + 0.8 * v, randomBox("radius" ,-7,-1))
-- > ]
-- >
-- > flipflop(v) = truncation(1 + 2 * v)
-- >
-- > draw(values) = blank
-- > & [blank, circle(r)]#s
-- > & colored(solidRectangle(w,h),[red,green]#c)
-- > where
-- > w = values#1
-- > h = values#2
-- > s = values#3
-- > c = values#4
-- > r = values#5
--
-- Note that the order in which the widgets are defined is important,
-- because it determines how to access the correct value.
-- Each widget fits in a box 4 units wide and 1 unit high.
guiDrawingOf :: ([Widget],[Number] -> Picture) -> Program
guiDrawingOf(widgetsUser,drawUser) = activityOf(initAll,updateAll,drawAll)
where
initAll(rs) = initRandom(widgetsUser,rs)
updateAll(ws,event) = ws.$updateWidget(event)
drawAll(ws) = pictures(ws.$drawWidget) & drawUser(ws.$value)
-- | The function @guiActivityOf@ is similar to @activityOf@, but it also
-- takes in a list of widgets. The updating and drawing functions also
-- receive a list of the current values of the widgets.
--
-- Example of use:
--
-- > program = guiActivityOf(widgets,init,update,draw)
-- > where
-- > widgets = [ withConversion(\v -> 20 * v, slider("width",-7,-7))
-- > , withConversion(\v -> 2 + 3 * v, slider("height",-7,-9))
-- > , withConversion
-- > (\v -> truncation(1 + 2*v), toggle("show circle",-7,-5))
-- > , button("restart",-7,-3)
-- > , randomBox("new color",-7,-1)
-- > ]
-- >
-- > draw(values,(color@(RGB(r1,r2,r3)),angle,_)) = colored(base,color)
-- > & [blank, circle(5)]#s
-- > & translated(lettering(msg),0,9)
-- > where
-- > msg = joined(["(",printed(r1),",",printed(r2),",",printed(r3),")"])
-- > base = rotated(solidRectangle(w,h),angle)
-- > w = values#1
-- > h = values#2
-- > s = values#3
-- >
-- > init(rs) = (RGB(rs#1,rs#2,rs#3),0,0)
-- >
-- > update(values,(color@(RGB(r1,r2,r3)),angle,wait),TimePassing(_))
-- > | values#4 > 0 , wait == 0 = (RGB(r2,r3,r),0,values#4)
-- > | otherwise = (color,angle+1,wait)
-- > where
-- > r = values#5
-- >
-- > update(values,(color,angle,wait),PointerRelease(_)) = (color,angle,0)
-- >
-- > update(values,state,event) = state
--
-- Note that pre-defined actions on the widgets take precedence over
-- anything that you define in your updating function, so you cannot
-- alter the default behavior of the widgets.
guiActivityOf :: ( [Widget]
, [Number] -> state
, ([Number],state,Event) -> state
, ([Number],state) -> Picture) -> Program
guiActivityOf(widgetsUser,initUser,updateUser,drawUser) =
activityOf(initAll,updateAll,drawAll)
where
initAll(rs) = ( initRandom(widgetsUser,rest(rs,1))
, initUser(randomNumbers(rs#1)))
updateAll((widgets,state),event) =
(newWidgets,updateUser(widgets.$value,state,event))
where
newWidgets = widgets.$updateWidget(event)
drawAll(widgets,state) =
pictures(widgets.$drawWidget) & drawUser(widgets.$value,state)
initRandom(ws,rs) = [ t(w,r) | w <- ws | r <- rs ]
where
t(w,r) | isRandom(w) = let rp = randomNumbers(r)
in w { value_ = rp#1, randomPool = rest(rp,1) }
| otherwise = w
isRandom(Widget{widget = Random}) = True
isRandom(_ ) = False
-- | A button placed at the given location. While
-- the button is pressed, the value produced is 0.5,
-- but when the button is released, the value reverts
-- back to 0.
button :: (Text,Number,Number) -> Widget
button(p) = (newWidget(p)) { widget = Button }
-- | A toggle (checkbox) with the given label at the given location.
-- When the box is not set, the value produced is 0. When the
-- box is set, the value produced is 0.5
toggle :: (Text,Number,Number) -> Widget
toggle(p) = (newWidget(p)) { widget = Toggle }
-- | A slider with the given label at the given location.
-- The possible values will range from 0 to 1, and the initial
-- value will be 0.
slider :: (Text,Number,Number) -> Widget
slider(p) = (newWidget(p)) { widget = Slider }
-- | A box that produces a random number between 0 and 1.
-- Each time you click on it, the value will change. The
-- value 1 is never produced, so the actual range of
-- values is 0 to 0.99999...
randomBox :: (Text,Number,Number) -> Widget
randomBox(p) = (newWidget(p)) { widget = Random }
-- | A button that keeps incrementing the value each time you press it.
-- The initial value is 1.
counter :: (Text,Number,Number) -> Widget
counter(p) = (newWidget(p)) { widget = Counter, value_ = 1 }
-- | A toggle that counts time up when you set it. When you click on
-- the left side of the widget, the current value is reset to 0.
-- You can stop the timer and start it again, and the value will increase
-- from where it was when you stopped it.
--
-- Example:
--
-- > program = guiDrawingOf(widgets,draw)
-- > where
-- > widgets = [ withConversion(\v -> 1 + 9 * v , slider("length",-7,-7))
-- > , withConversion(\v -> v * 30 , timer("angle" ,-7,-9)) ]
-- >
-- > draw([l,a]) = rotated(translated(colored(solidRectangle(l,0.25),red),l/2,0),a)
--
-- The timer operates in seconds, including decimals. However, the precision
-- of the timer is not guaranteed beyond one or two decimals.
--
timer :: (Text,Number,Number) -> Widget
timer(p) = (newWidget(p)) { widget = Timer }
-- | Make the widget use the provided function to convert values from
-- the default range of a widget to a different range.
--
-- Example:
--
-- > newSlider = withConversion(\v -> 20 * v - 10, oldSlider)
--
-- Assuming that the old slider did not have any conversion function applied
-- to it, the example above will make the new slider produce values
-- between -10 and 10, while the old slider will still produce values
-- between 0 and 1
withConversion :: (Number -> Number, Widget) -> Widget
withConversion(conv,w) = w { conversion = conv }
-- | Same functionality as @withConversion@, but using a different convention
-- for the arguments.
setConversion :: (Number -> Number) -> Widget -> Widget
setConversion(conv)(w) = w { conversion = conv }
-- | This is the example shown in the documentation for @guiDrawingOf@
widgetExample1 :: Program
widgetExample1 = guiDrawingOf(widgets,draw)
where
widgets = [ withConversion(\v -> 1 + 19 * v , slider("width" ,-7,-7))
, withConversion(\v -> 1 + 19 * v , slider("height" ,-7,-9))
, withConversion(flipflop , toggle("show circle" ,-7,-5))
, withConversion(flipflop , button("show in green",-7,-3))
, withConversion(\v -> 0.2 + 0.8 * v, randomBox("radius" ,-7,-1))
]
flipflop(v) = truncation(1 + 2 * v)
draw(values) = blank
& [blank, circle(r)]#s
& colored(solidRectangle(w,h),[red,green]#c)
where
w = values#1
h = values#2
s = values#3
c = values#4
r = values#5
-- | This is the example shown in the documentation for @guiActivityOf@
widgetExample2 :: Program
widgetExample2 = guiActivityOf(widgets,init,update,draw)
where
widgets = [ withConversion(\v -> 20 * v, slider("width",-7,-7))
, withConversion(\v -> 2 + 3 * v, slider("height",-7,-9))
, withConversion
(\v -> truncation(1 + 2*v), toggle("show circle",-7,-5))
, button("restart",-7,-3)
, randomBox("new color",-7,-1)
]
draw(values,(color@(RGB(r1,r2,r3)),angle,_)) = colored(base,color)
& [blank, circle(5)]#s
& translated(lettering(msg),0,9)
where
msg = joined(["(",printed(r1),",",printed(r2),",",printed(r3),")"])
base = rotated(solidRectangle(w,h),angle)
w = values#1
h = values#2
s = values#3
init(rs) = (RGB(rs#1,rs#2,rs#3),0,0)
update(values,(color@(RGB(r1,r2,r3)),angle,wait),TimePassing(_))
| values#4 > 0 , wait == 0 = (RGB(r2,r3,r),0,values#4)
| otherwise = (color,angle+1,wait)
where
r = values#5
update(values,(color,angle,wait),PointerRelease(_)) = (color,angle,0)
update(values,state,event) = state
-- | This is the example shown in the documentation for @timer@
widgetExample3 = guiDrawingOf(widgets,draw)
where
widgets = [ withConversion(\v -> 1 + 9 * v , slider("length",-7,-7))
, withConversion(\v -> v * 30 , timer("angle" ,-7,-9)) ]
draw([l,a]) = rotated(translated(colored(solidRectangle(l,0.25),red),l/2,0),a)
-- | This example shows a tree created by a recursive function
widgetExample4 = guiDrawingOf(widgets,draw)
-- Example copied from code shared by cdsmith
where
-- depth = 6 : 6 levels of detail
-- decay = 0.5 : Each smaller branch decreases in size by 50%.
-- stem = 0.5 : Branches occur 50% of the way up the stem.
-- angle = 30 : Branches point 30 degrees away from the stem.
widgets = [ slider("depth",-8,9.5).#setConversion(\p -> truncation(3 + 4*p))
, timer("decay",-8,8).#setConversion(\p -> 0.3 + 0.25*saw(p,5))
, timer("stem",-8,6.5).#setConversion(\p -> saw(p,17))
, slider("angle",-8,5).#setConversion(\p -> 5 + 30*p)
]
draw([depth,decay,stem,angle]) =
translated(scaled(branch(depth,decay,stem,angle), 2*decay, 2*decay),0,-5)
branch(0, _, _, _) = polyline[(0,0), (0,5)]
branch(depth, decay, stem, angle) = blank
& polyline[(0,0), (0, 5)]
& translated(smallBranch, 0, 5)
& translated(rotated(smallBranch, angle), 0, stem * 5)
& translated(rotated(smallBranch, -angle), 0, stem * 5)
where
smallBranch = scaled(branch(depth-1, decay, stem, angle), 1-decay, 1-decay)
saw(t,p) = 1 - abs(2*abs(remainder(t,p))/p - 1)
--------------------------------------------------------------------------------
-- Internal
--------------------------------------------------------------------------------
data WidgetType = Button | Toggle | Slider | Random | Counter | Timer
-- | The internal structure of a @Widget@ is not exposed in the user interface. You
-- have access only to the current value of each widget.
data Widget = Widget
{ selected :: Truth
, highlight :: Truth
, width :: Number
, height :: Number
, centerAt :: (Number,Number)
, label :: Text
, conversion :: Number -> Number
, value_ :: Number
, widget :: WidgetType
, randomPool :: [Number]
}
newWidget(l,x,y) = Widget
{ selected = False, highlight = False, width = 4, height = 1
, centerAt = (x,y), label = l
, value_ = 0, conversion = (\v -> v)
, widget = Button, randomPool = []
}
-- The value, adjusted according to the conversion function
value :: Widget -> Number
value(Widget{..}) = value_.#conversion
-- The current value of a widget is set as follows.
-- For sliders, the value is a Number
-- between 0 and 1 (both included). For buttons and checkboxes,
-- the value is 0 when they are not set and 0.5 when they are set.
-- These values allow user programs to work with either
-- @guiDrawingOf@ or @randomDrawingOf@ interchangeably, without having
-- to alter the calculations in the code.
hit(mx,my,Widget {..}) = abs(mx-x) < width/2 && abs(my-y) < height/2
where
(x,y) = centerAt
hitReset(mx,my,Widget {..}) = mx - xmin < 0.3 && abs(my - y) < height/2
where
(x,y) = centerAt
xmin = x - width/2
drawWidget(w) = case w.#widget of
Button -> drawButton(w)
Toggle -> drawToggle(w)
Slider -> drawSlider(w)
Random -> drawRandom(w)
Counter -> drawCounter(w)
Timer -> drawTimer(w)
drawButton(Widget{..}) = drawLabel & drawSelection & drawHighlight
where
solid = scaled(solidCircle(0.5),w,h)
outline = scaled(circle(0.5),w,h)
(x,y) = centerAt
msg = dilated(lettering(label),0.5)
w = 0.9 * width
h = 0.9 * height
drawLabel = translated(msg,x,y)
drawSelection
| selected = translated(colored(solid,grey),x,y)
| otherwise = translated(outline,x,y)
drawHighlight
| highlight = translated(colored(rectangle(width,height),light(grey)),x,y)
| otherwise = blank
drawCounter(Widget{..}) = drawLabel & drawSelection
where
solid = scaled(solidPolygon(points),w,h)
outline = scaled(polygon(points),w,h)
points = [(0.5,0.3),(0,0.5),(-0.5,0.3),(-0.5,-0.3),(0,-0.5),(0.5,-0.3)]
(x,y) = centerAt
msg(txt) = translated(dilated(lettering(txt),0.5),x,y)
w = 0.9 * width
h = 0.9 * height
drawLabel
| highlight = msg(printed(value_.#conversion))
| otherwise = msg(label)
drawSelection
| selected = translated(colored(solid,grey),x,y)
| highlight = translated(colored(outline,black),x,y)
| otherwise = translated(colored(outline,grey),x,y)
drawToggle(Widget{..}) = drawSelection & drawLabel & drawHighlight
where
w = 0.5
h = 0.5
x' = x + 2/5*width
drawSelection
| selected = translated(colored(solidRectangle(w,h),grey),x',y)
| otherwise = translated(rectangle(0.9*w,0.9*h),x',y)
drawLabel = translated(msg,x - width/10,y)
drawHighlight
| highlight = colored(outline,light(grey))
& translated(rectangle(w,h),x',y)
| otherwise = colored(outline,light(light(grey)))
outline = translated(rectangle(width,height),x,y)
(x,y) = centerAt
msg = dilated(lettering(label),0.5)
drawTimer(Widget{..}) = drawLabel & drawSelection & drawReset & drawHighlight
where
x' = x + 2/5*width
xmin = x - width/2
drawLabel
| highlight = msg(printed(value_.#conversion))
| otherwise = msg(label)
drawSelection
| selected = translated(box(0.5,0.5), x', y)
| otherwise = translated(rectangle(0.45,0.45),x',y)
drawReset = translated(box(0.3,height), xmin+0.15, y)
drawHighlight
| highlight = outline
& translated(rectangle(0.5,0.5),x',y)
| otherwise = colored(outline,light(grey))
outline = translated(rectangle(width,height),x,y)
(x,y) = centerAt
msg(txt) = translated(dilated(lettering(txt),0.5), x-width/10, y)
box(w,h) = colored(solidRectangle(w,h),grey)
drawSlider(Widget{..}) = info & foreground & background
where
info = translated(infoMsg,x,y-height/4)
foreground = translated(solidCircle(height/4),x',y')
& translated(colored(solidRectangle(width,height/4),grey),x,y')
x' = x - width/2 + value_ * width
y' = y + height/4
background
| highlight = translated(colored(rectangle(width,height),light(grey)),x,y)
| otherwise = blank
(x,y) = centerAt
infoMsg = dilated(lettering(label<>": "<>printed(value_.#conversion)),0.5)
drawRandom(Widget{..}) = drawLabel & drawSelection & drawHighlight
where
solid = scaled(solidRectangle(1,1),width,height)
outline = scaled(rectangle(1,1),width,height)
(x,y) = centerAt
msg(txt) = translated(dilated(lettering(txt),0.5),x,y)
drawLabel
| highlight = msg(printed(value_.#conversion))
| otherwise = msg(label)
drawSelection
| selected = translated(colored(solid,grey),x,y)
| otherwise = blank
drawHighlight
| highlight = translated(outline,x,y)
| otherwise = colored(translated(outline,x,y),grey)
updateWidget(PointerPress(mx,my))(w@Widget{..})
| widget == Button, hit(mx,my,w) = w { selected = True, highlight = False
, value_ = 0.5
}
| widget == Button = w { selected = False, highlight = False
, value_ = 0
}
| widget == Counter, hit(mx,my,w) = w { selected = True, highlight = True
, value_ = 1 + value_
}
| widget == Toggle, hit(mx,my,w) = w { selected = not(selected)
, value_ = 0.5 - value_
, highlight = True
}
| widget == Timer, hitReset(mx,my,w) = w { value_ = 0 }
| widget == Timer, hit(mx,my,w) = w { selected = not(selected)
, highlight = True
}
| widget == Slider, hit(mx,my,w) = w { selected = True, highlight = True
, value_ = updateSliderValue(mx,w)
}
| widget == Random, hit(mx,my,w) = w { selected = True, highlight = True
, value_ = randomPool#1
, randomPool = rest(randomPool,1)
}
| otherwise = w
updateWidget(PointerMovement(mx,my))(w) =
w.#updateHighlight(mx,my).#updateSlider(mx)
updateWidget(PointerRelease(_))(w@Widget{..})
| widget == Toggle = w
| widget == Timer = w
| selected = w { selected = False, highlight = False
, value_ = if widget == Button then 0 else value_
}
| otherwise = w
updateWidget(TimePassing(dt))(w@Widget{..})
| widget == Timer, selected = w { value_ = dt + value_ }
| otherwise = w
updateWidget(_)(widget) = widget
updateHighlight(mx,my)(w)
| hit(mx,my,w) = w { highlight = True }
| otherwise = w { highlight = False }
updateSlider(mx)(w@Widget{..})
| widget == Slider, selected = w { value_ = updateSliderValue(mx,w) }
| otherwise = w
updateSliderValue(mx,s@Widget{..}) =
(mx' - x + width/2) / width
where
mx' = max(x-width/2,min(x+width/2,mx))
(x,_) = centerAt
x .# f = f(x)
xs .$ f = [f(x) | x <- xs]
|
alphalambda/codeworld
|
codeworld-base/src/Extras/Widget.hs
|
Haskell
|
apache-2.0
| 19,161
|
{-
Teak synthesiser for the Balsa language
Copyright (C) 2007-2010 The University of Manchester
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/>.
Andrew Bardsley <bardsley@cs.man.ac.uk> (and others, see AUTHORS)
School of Computer Science, The University of Manchester
Oxford Road, MANCHESTER, M13 9PL, UK
-}
module Type (
TypeClass (..),
arrayInterval,
arrayElemType,
bitArrayType,
bitType,
intervalFromRange,
intervalIndex,
intervalIndices,
intervalSize,
builtinTypeWidth,
classOfType,
consTypeElemTypes,
constExpr,
constImpExpr,
constImpOrIntExpr,
constIndexExpr,
exprValue,
findRecElemByName,
intCoercable,
isStructType,
isTokenValueExpr,
makeConsValue,
numTypeUnsignedWidth,
rangeOfEnumType,
rangeOfIndexType,
rangeOfNumType,
recoverValue,
showTypeName,
smallestNumTypeEnclosing,
typeBuiltinOffsets,
typeCoercable,
typeEquiv,
typeExpr,
typeForInt,
typeGetUnaliasedBody,
typeIsSigned,
typeLvalue,
typeOfChan,
typeOfDecl,
typeOfExpr,
typeOfLvalue,
typeOfRange,
typeOfRef,
typeToStructType,
unaliasType,
widthOfType
) where
import ParseTree
import Context
import Report
import Bits
import qualified Data.Ix as Ix
import Data.List
import Data.Maybe
import Data.Bits
bitType :: Type
bitType = Bits 1
builtinTypeWidth :: Int
builtinTypeWidth = 64
bitArrayType :: Int -> Type
bitArrayType n = ArrayType (Interval (0, n' - 1) (typeForInt (n' - 1))) bitType
where n' = toInteger n
isTokenValueExpr :: [Context Decl] -> Expr -> Bool
isTokenValueExpr cs (ValueExpr _ typ (IntValue 0)) = widthOfType cs typ == 0
isTokenValueExpr _ _ = False
typeForInt :: Integer -> Type
typeForInt int
| int == -1 = SignedBits 1
| int < -1 = SignedBits $ 1 + intWidth (-int - 1)
| otherwise = Bits $ intWidth int
notNumeric :: [Type] -> a
notNumeric [t] = error $ "`" ++ show t ++ "' is not a numeric type"
notNumeric ts = error $ "one of" ++ types ++ " is not a numeric type"
where
types = concatMap showType ts
showType t = " `" ++ show t ++ "'"
rangeOfNumType :: Type -> (Integer, Integer)
rangeOfNumType (Bits width) = (0, bit width - 1)
rangeOfNumType (SignedBits width) = (- (bit (width - 1)), bit (width - 1) - 1)
rangeOfNumType t = notNumeric [t]
typeOfRange :: (Integer, Integer) -> Type
typeOfRange (low, high) = smallestNumTypeEnclosing (typeForInt high) (typeForInt low)
rangeOfEnumType :: TypeBody -> (Integer, Integer)
rangeOfEnumType (EnumType _ es _) = range
where
range = (minimum values, maximum values)
values = map enumElemValue $ contextBindingsList es
enumElemValue binding = fromJust $ constExpr $ declExpr $ bindingValue binding
rangeOfEnumType typ = error $ "rangeOfEnumType: not an enum type `" ++ show typ ++ "'"
rangeOfIndexType :: [Context Decl] -> Type -> (Integer, Integer)
rangeOfIndexType cs typ = body $ typeGetUnaliasedBody cs typ
where
body typ@(EnumType {}) = rangeOfEnumType typ
body (AliasType _ typ@(Bits {})) = rangeOfNumType typ
body (AliasType _ typ@(SignedBits {})) = rangeOfNumType typ
body typ = error $ "rangeOfIndexType: not an index type `" ++ show typ ++ "'"
smallestNumTypeEnclosing :: Type -> Type -> Type
smallestNumTypeEnclosing (Bits uw1) (Bits uw2) = Bits $ max uw1 uw2
smallestNumTypeEnclosing (SignedBits w1) (Bits uw2) = SignedBits $ 1 + max (w1 - 1) uw2
smallestNumTypeEnclosing (Bits uw1) (SignedBits w2) = SignedBits $ 1 + max uw1 (w2 - 1)
smallestNumTypeEnclosing (SignedBits w1) (SignedBits w2) = SignedBits $ max w1 w2
smallestNumTypeEnclosing t1 t2 = notNumeric [t1, t2]
widthOfType :: [Context Decl] -> Type -> Int
widthOfType _ (Bits width) = width
widthOfType _ (SignedBits width) = width
widthOfType cs (ArrayType interval elemType) = (widthOfType cs elemType) * (intervalSize interval)
widthOfType cs (StructArrayType interval elemType) = (widthOfType cs elemType) * (intervalSize interval)
widthOfType _ (BuiltinType _) = builtinTypeWidth
widthOfType cs (StructRecordType _ _ overType) = widthOfType cs overType
widthOfType cs (StructEnumType _ _ overType) = widthOfType cs overType
widthOfType _ NoType = 0
widthOfType cs typ = widthOfTypeBody cs $ typeGetUnaliasedBody cs typ
widthOfTypeBody :: [Context Decl] -> TypeBody -> Int
widthOfTypeBody cs (AliasType _ typ) = widthOfType cs typ
widthOfTypeBody cs (RecordType _ _ typ) = widthOfType cs typ
widthOfTypeBody cs (EnumType _ _ typ) = widthOfType cs typ
typeIsSigned :: [Context Decl] -> Type -> Bool
typeIsSigned _ (SignedBits {}) = True
typeIsSigned _ (Bits {}) = False
typeIsSigned _ (ArrayType {}) = False
typeIsSigned _ (StructArrayType {}) = False
typeIsSigned _ (StructRecordType {}) = False
typeIsSigned cs (StructEnumType _ _ overType) = typeIsSigned cs overType
typeIsSigned _ NoType = False
typeIsSigned cs typ = typeBodyIsSigned cs $ typeGetUnaliasedBody cs typ
typeBodyIsSigned :: [Context Decl] -> TypeBody -> Bool
typeBodyIsSigned cs (AliasType _ typ) = typeIsSigned cs typ
typeBodyIsSigned cs (EnumType _ _ typ) = typeIsSigned cs typ
typeBodyIsSigned _ _ = False
data TypeClass = NumClass | EnumClass | ArrayClass | RecordClass | BuiltinClass | NoTypeClass
deriving (Eq, Show, Read)
classOfType :: [Context Decl] -> Type -> TypeClass
classOfType _ NoType = NoTypeClass
classOfType _ (Bits {}) = NumClass
classOfType _ (SignedBits {}) = NumClass
classOfType _ (ArrayType {}) = ArrayClass
classOfType _ (BuiltinType {}) = BuiltinClass
classOfType cs typ = classOfTypeBody cs $ typeGetUnaliasedBody cs typ
classOfTypeBody :: [Context Decl] -> TypeBody -> TypeClass
classOfTypeBody cs (AliasType _ typ) = classOfType cs typ
classOfTypeBody _ (EnumType {}) = EnumClass
classOfTypeBody _ (RecordType {}) = RecordClass
intInWidth :: Integer -> Int -> Integer
intInWidth i w = if i < 0 then bit w + i else i
makeConsValue :: [Context Decl] -> Type -> [Expr] -> Value
makeConsValue cs typ es
| dcs == 0 = IntValue value
| otherwise = ImpValue $ Imp value dcs
where
valueDcPairs = map getImpPairs es
valueDcPairs' = map insertValue $ zip3 offsets valueDcPairs widths
(value, dcs) = foldl' addImp (0, 0) valueDcPairs'
addImp (v1, dc1) (v2, dc2) = (v1 + v2, dc1 + dc2)
widths = map (widthOfType cs) $ fromJust $ consTypeElemTypes cs typ
getImpPairs expr
| isJust int = (fromJust int, 0)
| otherwise = (value, dcs)
where
int = constExpr expr
Just (Imp value dcs) = constImpExpr expr
offsets = scanl (+) 0 widths
insertValue (offset, (value, dcs), width) = (insert value, insert dcs)
where insert value = (intInWidth value width) `shiftL` offset
consTypeElemTypes :: [Context Decl] -> Type -> Maybe [Type]
consTypeElemTypes cs typ = elemTypes $ typeGetUnaliasedBody cs typ
where
elemTypes (RecordType _ formals _) = Just $ map recordElemType formals
where recordElemType (RecordElem _ _ elemType) = elemType
elemTypes (AliasType _ (ArrayType interval elemType)) = Just $
map (const elemType) $ intervalIndices interval
elemTypes _ = Nothing
arrayElemType :: Type -> Type
arrayElemType (ArrayType _ elemType) = elemType
arrayElemType typ = error $ "arrayElemType: not an array type `" ++ show typ ++ "'"
arrayInterval :: Type -> Interval
arrayInterval (ArrayType interval _) = interval
arrayInterval typ = error $ "arrayInterval: not an array type `" ++ show typ ++ "'"
typeCoercable :: [Context Decl] -> Type -> Type -> Bool
typeCoercable cs fromType toType = coercable (unaliasType cs fromType) (unaliasType cs toType)
where
coercable (SignedBits _) (Bits _) = False
coercable (Bits wFrom) (SignedBits wTo) = wTo > wFrom
coercable (Bits wFrom) (Bits wTo) = wTo >= wFrom
coercable (SignedBits wFrom) (SignedBits wTo) = wTo >= wFrom
-- coercable fromType toType = typeEquiv cs fromType toType
coercable _ _ = False
intCoercable :: [Context Decl] -> Integer -> Type -> Bool
intCoercable cs int toType = coercable (unaliasType cs toType)
where
coercable (Bits wTo) = int >= 0 && int <= maxInt wTo
coercable (SignedBits wTo)
| int >= 0 = int <= maxInt (wTo - 1)
| int < 0 = int >= (-1 - maxInt (wTo - 1))
coercable _ = False
maxInt width = bit width - 1
typeEquiv :: [Context Decl] -> Type -> Type -> Bool
typeEquiv cs typ1 typ2 = equiv (unaliasType cs typ1) (unaliasType cs typ2)
where
equiv (Bits w1) (Bits w2) = w1 == w2
equiv (SignedBits w1) (SignedBits w2) = w1 == w2
equiv (Type ref1) (Type ref2) = ref1 == ref2 -- for the same context path
equiv (BuiltinType name1) (BuiltinType name2) = name1 == name2
equiv (ArrayType interval1 elemType1) (ArrayType interval2 elemType2) = interval1 == interval2 &&
elemType1 `equiv` elemType2
equiv _ _ = False
unaliasType :: [Context Decl] -> Type -> Type
unaliasType cs (ArrayType interval elemType) = ArrayType interval $ unaliasType cs elemType
unaliasType cs (Type ref) = case decl of
TypeDecl {} -> unaliasedType
TypeParamDecl {} -> Type ref
_ -> error $ "unaliasType: not a type decl: " ++ show decl ++ " " ++ show ref
where
decl = bindingValue $ findBindingByRef cs ref
unaliasedType = case declTypeBody decl of
AliasType _ typ -> unaliasType cs typ
_ -> Type ref
unaliasType _ typ = typ
typeExpr :: Type -> Expr -> Expr
typeExpr typ (BinExpr pos _ op left right) = BinExpr pos typ op left right
typeExpr typ (AppendExpr pos _ left right) = AppendExpr pos typ left right
typeExpr typ (UnExpr pos _ op expr) = UnExpr pos typ op expr
typeExpr typ (ConsExpr pos _ consType es) = ConsExpr pos typ consType es
typeExpr typ (BuiltinCallExpr pos callable ctx actuals _) = BuiltinCallExpr pos callable ctx actuals typ
typeExpr typ (BitfieldExpr pos _ range expr) = BitfieldExpr pos typ range expr
typeExpr typ (ExtendExpr pos _ width signedness expr) = ExtendExpr pos typ width signedness expr
typeExpr typ (ValueExpr pos _ value) = ValueExpr pos typ value
typeExpr typ (CaseExpr pos expr impss exprs) = CaseExpr pos expr impss (map (typeExpr typ) exprs)
typeExpr typ (VarRead pos _ range ref) = VarRead pos typ range ref
typeExpr typ (OpenChanRead pos _ range ref) = OpenChanRead pos typ range ref
typeExpr _ expr = expr
typeOfRef :: [Context Decl] -> Ref -> Type
typeOfRef cs ref = typeOfDecl $ bindingValue $ findBindingByRef cs ref
typeOfExpr :: [Context Decl] -> Expr -> Type
typeOfExpr _ (BinExpr _ typ _ _ _) = typ
typeOfExpr _ (AppendExpr _ typ _ _) = typ
typeOfExpr _ (UnExpr _ typ _ _) = typ
typeOfExpr _ (CastExpr _ typ _) = typ
typeOfExpr _ (TypeCheckExpr _ _ typ _) = typ
typeOfExpr cs (ConstCheckExpr _ expr) = typeOfExpr cs expr
typeOfExpr cs (ArrayElemTypeCheckExpr _ _ expr) = typeOfExpr cs expr
typeOfExpr _ (BuiltinCallExpr _ _ _ _ typ) = typ
typeOfExpr _ (ConsExpr _ typ _ _) = typ
typeOfExpr _ (BitfieldExpr _ typ _ _) = typ
typeOfExpr _ (ExtendExpr _ typ _ _ _) = typ
typeOfExpr _ (ValueExpr _ typ _) = typ
typeOfExpr _ (VarRead _ typ _ _) = typ
typeOfExpr _ (OpenChanRead _ typ _ _) = typ
typeOfExpr cs (PartialArrayedRead _ ref) = typeOfRef cs ref
typeOfExpr cs (MaybeTypeExpr _ ref) = typeOfRef cs ref
typeOfExpr cs (MaybeOtherExpr _ ref) = typeOfRef cs ref
typeOfExpr cs (Expr _ ref) = typeOfRef cs ref
typeOfExpr cs (CaseExpr _ _ _ (expr:_)) = typeOfExpr cs expr
typeOfExpr _ expr = error $ "can't type " ++ show expr
typeOfChan :: [Context Decl] -> Chan -> Type
typeOfChan cs (Chan _ ref) = typeOfRef cs ref
typeOfChan cs (CheckChan _ _ chan) = typeOfChan cs chan
typeOfChan _ _ = NoType
typeOfDecl :: Decl -> Type
typeOfDecl decl = declType decl
typeLvalue :: Type -> Lvalue -> Lvalue
typeLvalue typ (BitfieldLvalue pos _ range lvalue) = BitfieldLvalue pos typ range lvalue
typeLvalue typ (VarWrite pos _ range ref) = VarWrite pos typ range ref
typeLvalue typ (CaseLvalue pos expr impss lvalues) = CaseLvalue pos expr impss (map (typeLvalue typ) lvalues)
typeLvalue _ lvalue = lvalue
typeOfLvalue :: [Context Decl] -> Lvalue -> Type
typeOfLvalue _ (BitfieldLvalue _ typ _ _) = typ
typeOfLvalue _ (VarWrite _ typ _ _) = typ
typeOfLvalue cs (CaseLvalue _ _ _ (lvalue:_)) = typeOfLvalue cs lvalue
typeOfLvalue _ lvalue = error $ "can't type " ++ show lvalue
exprValue :: Expr -> Maybe Value
exprValue (ValueExpr _ _ value) = Just value
exprValue _ = Nothing
constExpr :: Expr -> Maybe Integer
constExpr (ValueExpr _ _ (IntValue int)) = Just int
constExpr _ = Nothing
constImpExpr :: Expr -> Maybe Implicant
constImpExpr (ValueExpr _ _ (ImpValue imp)) = Just imp
constImpExpr _ = Nothing
constImpOrIntExpr :: Expr -> Maybe Implicant
constImpOrIntExpr (ValueExpr _ _ (IntValue int)) = Just $ Imp int 0
constImpOrIntExpr (ValueExpr _ _ (ImpValue imp)) = Just imp
constImpOrIntExpr _ = Nothing
constIndexExpr :: [Context Decl] -> Expr -> Maybe Integer
constIndexExpr cs (ValueExpr _ typ (IntValue int)) = case classOfType cs typ of
EnumClass -> Just int
NumClass -> Just int
_ -> Nothing
constIndexExpr _ _ = Nothing
typeGetUnaliasedBody :: [Context Decl] -> Type -> TypeBody
typeGetUnaliasedBody cs typ = typeGetBody cs $ unaliasType cs typ
typeGetBody :: [Context Decl] -> Type -> TypeBody
typeGetBody cs (Type ref) = body
where
body = declBody $ bindingValue $ findBindingByRef cs ref
declBody (TypeDecl _ typeBody) = typeBody
declBody decl = error $ "Huh2? " ++ show decl
typeGetBody _ typ = AliasType NoPos typ
intervalIndices :: Interval -> [Integer]
intervalIndices = Ix.range . intervalRange
intervalSize :: Interval -> Int
intervalSize = Ix.rangeSize . intervalRange
intervalIndex :: Interval -> Integer -> Int
intervalIndex = Ix.index . intervalRange
-- intervalFromRange : make an Interval over the given range. This involves synthesising the interval range type.
intervalFromRange :: (Integer, Integer) -> Interval
intervalFromRange range = Interval range (typeOfRange range)
showTypeName :: [Context Decl] -> Type -> String
showTypeName cs (Type ref) = string
where
binding = findBindingByRef cs ref
name = bindingName $ binding
decl = bindingValue $ binding
string = name ++ case decl of
TypeDecl _ (AliasType _ typ) -> " (" ++ showTypeName cs typ ++ ")"
_ -> ""
showTypeName _ (Bits width) = show width ++ " bits"
showTypeName _ (SignedBits width) = show width ++ " signed bits"
showTypeName cs (ArrayType (Interval (low, high) ivType) elemType) = "array " ++ intervalStr
++ " of " ++ elemTypeStr
where
asStr val typ = "(" ++ show val ++ " as " ++ showTypeName cs typ ++ ")"
intervalStr = if classOfType cs ivType == EnumClass
then asStr low ivType ++ " .. " ++ asStr high ivType
else show low ++ " .. " ++ show high
elemTypeStr = showTypeName cs elemType
showTypeName _ (StructRecordType name _ _) = name
showTypeName _ (StructEnumType name _ _) = name
showTypeName cs (StructArrayType interval elemType) = showTypeName cs (ArrayType interval elemType)
showTypeName _ other = show other
numTypeUnsignedWidth :: Type -> Int
numTypeUnsignedWidth (Bits width) = width
numTypeUnsignedWidth (SignedBits width) = width - 1
numTypeUnsignedWidth _ = error "numTypeUnsignedWidth: not a numeric type"
findRecElemByName :: [Context Decl] -> TypeBody -> String -> Maybe (Int, Type)
findRecElemByName cs (RecordType _ es _) name = findRecElem es 0
where
findRecElem [] _ = Nothing
findRecElem ((RecordElem _ name' typ):recElems) offset
| name' == name = Just (offset, typ)
| otherwise = findRecElem recElems (offset + (widthOfType cs typ))
findRecElemByName _ _ _ = error "findRecElemByName: not a RecordType"
typeToStructType :: [Context Decl] -> Type -> Type
typeToStructType cs typ = body $ unaliasType cs typ
where
self = typeToStructType cs
body (Type ref) = typeBodyToStructType cs name $ declTypeBody decl
where
decl = bindingValue binding
name = bindingName binding
binding = findBindingByRef cs ref
body (ArrayType interval subType) = StructArrayType interval $ self subType
body otherType = otherType
isStructType :: Type -> Bool
isStructType (StructRecordType {}) = True
isStructType (StructArrayType {}) = True
isStructType (StructEnumType {}) = True
isStructType _ = False
typeBodyToStructType :: [Context Decl] -> String -> TypeBody -> Type
typeBodyToStructType _ _ (AliasType _ typ) = typ
typeBodyToStructType cs typeName (RecordType _ es overType) = StructRecordType typeName
(map (recElemToST cs) es) (typeToStructType cs overType)
typeBodyToStructType cs typeName (EnumType _ context overType) = StructEnumType typeName
(mapMaybe bindingToEnumPair bindings) (typeToStructType cs overType)
where
bindings = contextBindingsList context
bindingToEnumPair (Binding _ name _ _ (ExprDecl _ (ValueExpr _ _ (IntValue int)))) =
Just (SimpleBinding name int)
bindingToEnumPair _ = Nothing
-- typeBuiltinOffsets : produces a list of bit offsets for the given type which identify
-- each builtin typed element of a value of that type. `offset' is added to each offset in the returned list
typeBuiltinOffsets :: [Context Decl] -> Int -> Type -> [Int]
typeBuiltinOffsets cs offset typ = body $ unaliasType cs typ
where
body (Type ref) = typeBodyBuiltinOffsets cs offset $ declTypeBody decl
where
decl = bindingValue binding
binding = findBindingByRef cs ref
body (ArrayType interval subType) = array interval subType
body (StructArrayType interval subType) = array interval subType
body (StructRecordType _ es overType) =
typeBodyBuiltinOffsets cs offset (RecordType undefined es overType)
body (BuiltinType {}) = [offset]
body _ = []
array interval subType = concatMap offsetElemRanges elemOffsets
where
offsetElemRanges elemOffset = map (+ elemOffset) elemRanges
elemOffsets = map (* elemWidth) [0..intervalSize interval - 1]
elemWidth = widthOfType cs subType
elemRanges = typeBuiltinOffsets cs offset subType
typeBodyBuiltinOffsets :: [Context Decl] -> Int -> TypeBody -> [Int]
typeBodyBuiltinOffsets cs offset (AliasType _ typ) = typeBuiltinOffsets cs offset typ
typeBodyBuiltinOffsets cs offset0 (RecordType _ es _) = concat elemRangess
where
(_, elemRangess) = mapAccumL elemRanges offset0 es
elemRanges offset (RecordElem _ _ elemType) = (offset + width, typeBuiltinOffsets cs offset elemType)
where width = widthOfType cs elemType
typeBodyBuiltinOffsets _ _ (EnumType {}) = []
recElemToST :: [Context Decl] -> RecordElem -> RecordElem
recElemToST cs (RecordElem pos name typ) = RecordElem pos name (typeToStructType cs typ)
recoverValue :: [Context Decl] -> Type -> Integer -> Integer
recoverValue cs typ val
| typeIsSigned cs typ = recoverSign (widthOfType cs typ) val
| otherwise = val
|
Mahdi89/eTeak
|
src/Type.hs
|
Haskell
|
bsd-3-clause
| 21,407
|
module State.TreeSpec (treeSpec) where
import State.Tree
import Test.Hspec
import Control.Monad.Identity
testTree :: Integer -> Identity ([Integer], String)
testTree 0 = return ([1, 2], "0")
testTree 1 = return ([3], "1")
testTree 2 = return ([], "2")
testTree 3 = return ([], "3")
testTree _ = error "No node"
loopTree1 :: Integer -> Identity ([Integer], String)
loopTree1 0 = return ([1], "0")
loopTree1 1 = return ([0], "1")
loopTree1 _ = error "No node"
loopTree2 :: Integer -> Identity ([Integer], String)
loopTree2 0 = return ([1], "0")
loopTree2 1 = return ([0, 2, 3], "1")
loopTree2 2 = return ([3], "2")
loopTree2 3 = return ([2], "3")
loopTree2 _ = error "No node"
treeSpec :: Spec
treeSpec = do
describe "Tree" $ do
dfFlattenTreeSpec
dfFlattenTreeSpec :: Spec
dfFlattenTreeSpec = do
describe "dfFlattenTree" $ do
it "flattens the tree using DFS" $ do
let expected = return ["3", "1", "2", "0"]
dfFlattenTree testTree [0] `shouldBe` expected
it "does not include data in loops more than once" $ do
let expected = return ["1", "0"]
dfFlattenTree loopTree1 [0] `shouldBe` expected
it "visits braches of loops" $ do
let expected = return ["3", "2", "1", "0"]
dfFlattenTree loopTree2 [0] `shouldBe` expected
|
BakerSmithA/Turing
|
test/State/TreeSpec.hs
|
Haskell
|
bsd-3-clause
| 1,334
|
{-# LANGUAGE GeneralizedNewtypeDeriving, ScopedTypeVariables, BangPatterns #-}
module Halfs.Inode
(
InodeRef(..)
, blockAddrToInodeRef
, buildEmptyInodeEnc
, decLinkCount
, fileStat
, incLinkCount
, inodeKey
, inodeRefToBlockAddr
, isNilIR
, nilIR
, readStream
, writeStream
-- * for internal use only!
, atomicModifyInode
, atomicReadInode
, bsReplicate
, drefInode
, expandExts -- for use by fsck
, fileStat_lckd
, freeInode
, withLockedInode
, writeStream_lckd
-- * for testing: ought not be used by actual clients of this module!
, Inode(..)
, Ext(..)
, ExtRef(..)
, bsDrop
, bsTake
, computeMinimalInodeSize
, computeNumAddrs
, computeNumInodeAddrsM
, computeNumExtAddrsM
, computeSizes
, decodeExt
, decodeInode
, minimalExtSize
, minInodeBlocks
, minExtBlocks
, nilER
, safeToInt
, truncSentinel
)
where
import Control.Exception
import Data.ByteString(ByteString)
import qualified Data.ByteString as BS
import Data.Char
import Data.List (genericDrop, genericLength, genericTake)
import Data.Serialize
import qualified Data.Serialize.Get as G
import Data.Word
import Halfs.BlockMap (BlockMap)
import qualified Halfs.BlockMap as BM
import Halfs.Classes
import Halfs.Errors
import Halfs.HalfsState
import Halfs.Protection
import Halfs.Monad
import Halfs.MonadUtils
import Halfs.Types
import Halfs.Utils
import System.Device.BlockDevice
-- import System.IO.Unsafe (unsafePerformIO)
dbug :: String -> a -> a
-- dbug = seq . unsafePerformIO . putStrLn
dbug _ = id
dbugM :: Monad m => String -> m ()
--dbugM s = dbug s $ return ()
dbugM _ = return ()
type HalfsM b r l m a = HalfsT HalfsError (Maybe (HalfsState b r l m)) m a
--------------------------------------------------------------------------------
-- Inode/Ext constructors, geometry calculation, and helpful constructors
type StreamIdx = (Word64, Word64, Word64)
-- | Obtain a 64 bit "key" for an inode; useful for building maps etc.
-- For now, this is the same as inodeRefToBlockAddr, but clients should
-- be using this function rather than inodeRefToBlockAddr in case the
-- underlying inode representation changes.
inodeKey :: InodeRef -> Word64
inodeKey = inodeRefToBlockAddr
-- | Convert a disk block address into an Inode reference.
blockAddrToInodeRef :: Word64 -> InodeRef
blockAddrToInodeRef = IR
-- | Convert an inode reference into a block address
inodeRefToBlockAddr :: InodeRef -> Word64
inodeRefToBlockAddr = unIR
-- | The nil Inode reference. With the current Word64 representation and the
-- block layout assumptions, block 0 is the superblock, and thus an invalid
-- Inode reference.
nilIR :: InodeRef
nilIR = IR 0
isNilIR :: InodeRef -> Bool
isNilIR = (==) nilIR
-- | The nil Ext reference. With the current Word64 representation and
-- the block layout assumptions, block 0 is the superblock, and thus an
-- invalid Ext reference.
nilER :: ExtRef
nilER = ER 0
isNilER :: ExtRef -> Bool
isNilER = (==) nilER
-- | The sentinel byte written to partial blocks when doing truncating writes
truncSentinel :: Word8
truncSentinel = 0xBA
-- | The sentinel byte written to the padded region at the end of Inodes/Exts
padSentinel :: Word8
padSentinel = 0xAD
-- We semi-arbitrarily state that an Inode must be capable of maintaining a
-- minimum of 35 block addresses in its embedded Ext while the Ext must be
-- capable of maintaining 57 block addresses. These values, together with
-- specific padding values for inodes and exts (4 and 0, respectively), give us
-- a minimum inode AND ext size of 512 bytes each (in the IO monad variant,
-- which uses the our Serialize instance for the UTCTime when writing the time
-- fields).
--
-- These can be adjusted as needed according to inode metadata sizes, but it's
-- very important that (computeMinimalInodeSize =<< getTime) and minimalExtSize yield
-- the same value!
-- | The size, in bytes, of the padding region at the end of Inodes
iPadSize :: Int
iPadSize = 4
-- | The size, in bytes, of the padding region at the end of Exts
cPadSize :: Int
cPadSize = 0
minInodeBlocks :: Word64
minInodeBlocks = 35
minExtBlocks :: Word64
minExtBlocks = 57
-- | The structure of an Inode. Pretty standard, except that we use the Ext
-- structure (the first of which is embedded in the inode) to hold block
-- references and use its ext field to allow multiple runs of block
-- addresses.
data Inode t = Inode
{ inoParent :: InodeRef -- ^ block addr of parent directory
-- inode: This is nilIR for the
-- root directory inode
, inoLastExt :: (ExtRef, Word64) -- ^ The last-accessed ER and its ext
-- idx. For the "faster end-of-stream
-- access" hack.
-- begin fstat metadata
, inoAddress :: InodeRef -- ^ block addr of this inode
, inoFileSize :: Word64 -- ^ in bytes
, inoAllocBlocks :: Word64 -- ^ number of blocks allocated to this inode
-- (includes its own allocated block, blocks
-- allocated for Exts, and and all blocks in
-- the ext chain itself)
, inoFileType :: FileType
, inoMode :: FileMode
, inoNumLinks :: Word64 -- ^ number of hardlinks to this inode
, inoCreateTime :: t -- ^ time of creation
, inoModifyTime :: t -- ^ time of last data modification
, inoAccessTime :: t -- ^ time of last data access
, inoChangeTime :: t -- ^ time of last change to inode data
, inoUser :: UserID -- ^ userid of inode's owner
, inoGroup :: GroupID -- ^ groupid of inode's owner
-- end fstat metadata
, inoExt :: Ext -- The "embedded" inode extension ("ext")
}
deriving (Show, Eq)
-- An "Inode extension" datatype
data Ext = Ext
{ address :: ExtRef -- ^ Address of this Ext (nilER for an
-- inode's embedded Ext)
, nextExt :: ExtRef -- ^ Next Ext in the chain; nilER terminates
, blockCount :: Word64
, blockAddrs :: [Word64] -- ^ references to blocks governed by this Ext
-- Fields below here are not persisted, and are populated via decodeExt
, numAddrs :: Word64 -- ^ Maximum number of blocks addressable by *this*
-- Ext. NB: Does not include blocks further down
-- the chain.
}
deriving (Show, Eq)
-- | Size of a minimal inode structure when serialized, in bytes. This will
-- vary based on the space required for type t when serialized. Note that
-- minimal inode structure always contains minInodeBlocks InodeRefs in
-- its blocks region.
--
-- You can check this value interactively in ghci by doing, e.g.
-- computeMinimalInodeSize =<< (getTime :: IO UTCTime)
computeMinimalInodeSize :: (Monad m, Ord t, Serialize t, Show t) =>
t -> m Word64
computeMinimalInodeSize t = do
return $ fromIntegral $ BS.length $ encode $
let e = emptyInode minInodeBlocks t RegularFile (FileMode [] [] [])
nilIR nilIR rootUser rootGroup
c = inoExt e
in e{ inoExt = c{ blockAddrs = replicate (safeToInt minInodeBlocks) 0 } }
-- | The size of a minimal Ext structure when serialized, in bytes.
minimalExtSize :: Monad m => m (Word64)
minimalExtSize = return $ fromIntegral $ BS.length $ encode $
(emptyExt minExtBlocks nilER){
blockAddrs = replicate (safeToInt minExtBlocks) 0
}
-- | Computes the number of block addresses storable by an inode/ext
computeNumAddrs :: Monad m =>
Word64 -- ^ block size, in bytes
-> Word64 -- ^ minimum number of blocks for inode/ext
-> Word64 -- ^ minimum inode/ext total size, in bytes
-> m Word64
computeNumAddrs blkSz minBlocks minSize = do
unless (minSize <= blkSz) $
fail "computeNumAddrs: Block size too small to accomodate minimal inode"
let
-- # bytes required for the blocks region of the minimal inode
padding = minBlocks * refSize
-- # bytes of the inode excluding the blocks region
notBlocksSize = minSize - padding
-- # bytes available for storing the blocks region
blkSz' = blkSz - notBlocksSize
unless (0 == blkSz' `mod` refSize) $
fail "computeNumAddrs: Inexplicably bad block size"
return $ blkSz' `div` refSize
computeNumInodeAddrsM :: (Serialize t, Timed t m, Show t) =>
Word64 -> m Word64
computeNumInodeAddrsM blkSz =
computeNumAddrs blkSz minInodeBlocks =<< computeMinimalInodeSize =<< getTime
computeNumExtAddrsM :: (Serialize t, Timed t m) =>
Word64 -> m Word64
computeNumExtAddrsM blkSz = do
minSize <- minimalExtSize
computeNumAddrs blkSz minExtBlocks minSize
computeSizes :: (Serialize t, Timed t m, Show t) =>
Word64
-> m ( Word64 -- #inode bytes
, Word64 -- #ext bytes
, Word64 -- #inode addrs
, Word64 -- #ext addrs
)
computeSizes blkSz = do
startExtAddrs <- computeNumInodeAddrsM blkSz
extAddrs <- computeNumExtAddrsM blkSz
return (startExtAddrs * blkSz, extAddrs * blkSz, startExtAddrs, extAddrs)
-- Builds and encodes an empty inode
buildEmptyInodeEnc :: (Serialize t, Timed t m, Show t) =>
BlockDevice m -- ^ The block device
-> FileType -- ^ This inode's filetype
-> FileMode -- ^ This inode's access mode
-> InodeRef -- ^ This inode's block address
-> InodeRef -- ^ Parent's block address
-> UserID
-> GroupID
-> m ByteString
buildEmptyInodeEnc bd ftype fmode me mommy usr grp =
liftM encode $ buildEmptyInode bd ftype fmode me mommy usr grp
buildEmptyInode :: (Serialize t, Timed t m, Show t) =>
BlockDevice m
-> FileType -- ^ This inode's filetype
-> FileMode -- ^ This inode's access mode
-> InodeRef -- ^ This inode's block address
-> InodeRef -- ^ Parent block's address
-> UserID -- ^ This inode's owner's userid
-> GroupID -- ^ This inode's owner's groupid
-> m (Inode t)
buildEmptyInode bd ftype fmode me mommy usr grp = do
now <- getTime
minSize <- computeMinimalInodeSize =<< return now
minimalExtSize >>= (`assert` return ()) . (==) minSize
nAddrs <- computeNumAddrs (bdBlockSize bd) minInodeBlocks minSize
return $ emptyInode nAddrs now ftype fmode me mommy usr grp
emptyInode :: (Ord t, Serialize t) =>
Word64 -- ^ number of block addresses
-> t -- ^ creation timestamp
-> FileType -- ^ inode's filetype
-> FileMode -- ^ inode's access mode
-> InodeRef -- ^ block addr for this inode
-> InodeRef -- ^ parent block address
-> UserID
-> GroupID
-> Inode t
emptyInode nAddrs now ftype fmode me mommy usr grp =
Inode
{ inoParent = mommy
, inoLastExt = (nilER, 0)
, inoAddress = me
, inoFileSize = 0
, inoAllocBlocks = 1
, inoFileType = ftype
, inoMode = fmode
, inoNumLinks = 1
, inoCreateTime = now
, inoModifyTime = now
, inoAccessTime = now
, inoChangeTime = now
, inoUser = usr
, inoGroup = grp
, inoExt = emptyExt nAddrs nilER
}
buildEmptyExt :: (Serialize t, Timed t m) =>
BlockDevice m -- ^ The block device
-> ExtRef -- ^ This ext's block address
-> m Ext
buildEmptyExt bd me = do
minSize <- minimalExtSize
nAddrs <- computeNumAddrs (bdBlockSize bd) minExtBlocks minSize
return $ emptyExt nAddrs me
emptyExt :: Word64 -- ^ number of block addresses
-> ExtRef -- ^ block addr for this ext
-> Ext
emptyExt nAddrs me =
Ext
{ address = me
, nextExt = nilER
, blockCount = 0
, blockAddrs = []
, numAddrs = nAddrs
}
--------------------------------------------------------------------------------
-- Inode stream functions
-- | Provides a stream over the bytes governed by a given Inode and its
-- extensions (exts). This function performs a write to update inode metadata
-- (e.g., access time).
readStream :: HalfsCapable b t r l m =>
InodeRef -- ^ Starting inode reference
-> Word64 -- ^ Starting stream (byte) offset
-> Maybe Word64 -- ^ Stream length (Nothing => read
-- until end of stream, including
-- entire last block)
-> HalfsM b r l m ByteString -- ^ Stream contents
readStream startIR start mlen = withLockedInode startIR $ do
-- ====================== Begin inode critical section ======================
dev <- hasks hsBlockDev
startInode <- drefInode startIR
let bs = bdBlockSize dev
readB c b = lift $ readBlock dev c b
fileSz = inoFileSize startInode
gsi = getStreamIdx (bdBlockSize dev) fileSz
if 0 == blockCount (inoExt startInode)
then return BS.empty
else dbug ("==== readStream begin ===") $ do
(sExtI, sBlkOff, sByteOff) <- gsi start
sExt <- findExt startInode sExtI
(eExtI, _, _) <- gsi $ case mlen of
Nothing -> fileSz - 1
Just len -> start + len - 1
dbugM ("start = " ++ show start)
dbugM ("(sExtI, sBlkOff, sByteOff) = " ++ show (sExtI, sBlkOff, sByteOff))
dbugM ("eExtI = " ++ show eExtI)
rslt <- case mlen of
Just len | len == 0 -> return BS.empty
_ -> do
assert (maybe True (> 0) mlen) $ return ()
-- 'hdr' is the (possibly partial) first block
hdr <- bsDrop sByteOff `fmap` readB sExt sBlkOff
-- 'rest' is the list of block-sized bytestrings containing the
-- requested content from blocks in subsequent conts, accounting for
-- the (Maybe) maximum length requested.
rest <- do
let hdrLen = fromIntegral (BS.length hdr)
totalToRead = maybe (fileSz - start) id mlen
--
howManyBlks ext bsf blkOff =
let bc = blockCount ext - blkOff
in
maybe bc (\len -> min bc ((len - bsf) `divCeil` bs)) mlen
--
readExt (_, [], _) = error "The impossible happened"
readExt ((cExt, cExtI), blkOff:boffs, bytesSoFar)
| cExtI > eExtI =
assert (bytesSoFar >= totalToRead) $ return Nothing
| bytesSoFar >= totalToRead =
return Nothing
| otherwise = do
let remBlks = howManyBlks cExt bytesSoFar blkOff
range = if remBlks > 0
then [blkOff .. blkOff + remBlks - 1]
else []
theData <- BS.concat `fmap` mapM (readB cExt) range
assert (fromIntegral (BS.length theData) == remBlks * bs) $ return ()
let rslt c = return $ Just $
( theData -- accumulated by unfoldr
, ( (c, cExtI+1)
, boffs
, bytesSoFar + remBlks * bs
)
)
if isNilER (nextExt cExt)
then rslt (error "Ext DNE and expected termination!")
else rslt =<< drefExt (nextExt cExt)
-- ==> Bulk reading starts here <==
if (sBlkOff + 1 < blockCount sExt || sExtI < eExtI)
then unfoldrM readExt ((sExt, sExtI), (sBlkOff+1):repeat 0, hdrLen)
else return []
return $ bsTake (maybe (fileSz - start) id mlen) $
hdr `BS.append` BS.concat rest
now <- getTime
lift $ writeInode dev $
startInode { inoAccessTime = now, inoChangeTime = now }
dbug ("==== readStream end ===") $ return ()
return rslt
-- ======================= End inode critical section =======================
-- | Writes to the inode stream at the given starting inode and starting byte
-- offset, overwriting data and allocating new space on disk as needed. If the
-- write is a truncating write, all resources after the end of the written data
-- are freed. Whenever the data to be written exceeds the the end of the
-- stream, the trunc flag is ignored.
writeStream :: HalfsCapable b t r l m =>
InodeRef -- ^ Starting inode ref
-> Word64 -- ^ Starting stream (byte) offset
-> Bool -- ^ Truncating write?
-> ByteString -- ^ Data to write
-> HalfsM b r l m ()
writeStream _ _ False bytes | 0 == BS.length bytes = return ()
writeStream startIR start trunc bytes = do
withLockedInode startIR $ writeStream_lckd startIR start trunc bytes
writeStream_lckd :: HalfsCapable b t r l m =>
InodeRef -- ^ Starting inode ref
-> Word64 -- ^ Starting stream (byte) offset
-> Bool -- ^ Truncating write?
-> ByteString -- ^ Data to write
-> HalfsM b r l m ()
writeStream_lckd _ _ False bytes | 0 == BS.length bytes = return ()
writeStream_lckd startIR start trunc bytes = do
-- ====================== Begin inode critical section ======================
-- NB: This implementation currently 'flattens' Contig/Discontig block groups
-- from the BlockMap allocator (see allocFill and truncUnalloc below), which
-- will force us to treat them as Discontig when we unallocate, which is more
-- expensive. We may want to have the Exts hold onto these block groups
-- directly and split/merge them as needed to reduce the number of
-- unallocation actions required, but we leave this as a TODO for now.
startInode@Inode{ inoLastExt = lcInfo } <- drefInode startIR
dev <- hasks hsBlockDev
let bs = bdBlockSize dev
len = fromIntegral $ BS.length bytes
fileSz = inoFileSize startInode
newFileSz = if trunc then start + len else max (start + len) fileSz
fszRndBlk = (fileSz `divCeil` bs) * bs
availBlks c = numAddrs c - blockCount c
bytesToAlloc = if newFileSz > fszRndBlk then newFileSz - fszRndBlk else 0
blksToAlloc = bytesToAlloc `divCeil` bs
(_, _, _, apc) <- hasks hsSizes
sIdx@(sExtI, sBlkOff, sByteOff) <- getStreamIdx bs fileSz start
sExt <- findExt startInode sExtI
lastExt <- getLastExt Nothing sExt
-- TODO: Track a ptr to this? Traversing
-- the allocated region is yucky.
let extsToAlloc = (blksToAlloc - availBlks lastExt) `divCeil` apc
------------------------------------------------------------------------------
-- Debugging miscellany
dbugM ("\nwriteStream: " ++ show (sExtI, sBlkOff, sByteOff)
++ " (start=" ++ show start ++ ")"
++ " len = " ++ show len ++ ", trunc = " ++ show trunc
++ ", fileSz/newFileSz = " ++ show fileSz ++ "/" ++ show newFileSz
++ ", toAlloc(exts/blks/bytes) = " ++ show extsToAlloc ++ "/"
++ show blksToAlloc ++ "/" ++ show bytesToAlloc)
-- dbug ("inoLastExt startInode = " ++ show (lcInfo) ) $ return ()
-- dbug ("inoExt startInode = " ++ show (inoExt startInode)) $ return ()
-- dbug ("Exts on entry, from inode ext:") $ return ()
-- dumpExts (inoExt startInode)
------------------------------------------------------------------------------
-- Allocation:
-- Allocate if needed and obtain (1) the post-alloc start ext and (2)
-- possibly a dirty ext to write back into the inode (ie, when its
-- nextExt field is modified as a result of allocation -- all other
-- modified exts are written by allocFill, but the inode write is the last
-- thing we do, so we defer the update).
(sExt', minodeExt) <- do
if blksToAlloc == 0
then return (sExt, Nothing)
else do
lastExt' <- allocFill availBlks blksToAlloc extsToAlloc lastExt
let st = if address lastExt' == address sExt then lastExt' else sExt
-- Our starting location remains the same, but in case of an
-- update of the start ext, we can use lastExt' instead of
-- re-reading.
lci = snd lcInfo
st' <- if lci < sExtI
then getLastExt (Just $ sExtI - lci + 1) st
-- NB: We need to start ahead of st, but couldn't adjust
-- until after we allocated. This is to catch a corner case
-- where the "start" ext coming into writeStream_lckd
-- refers to a ext that hasn't been allocated yet.
else return st
return (st', if isEmbedded st then Just st else Nothing)
-- dbug ("sExt' = " ++ show sExt') $ return ()
-- dbug ("minodeExt = " ++ show minodeExt) $ return ()
-- dbug ("Exts immediately after alloc, from sExt'") $ return ()
-- dumpExts (sExt')
assert (sBlkOff < blockCount sExt') $ return ()
------------------------------------------------------------------------------
-- Truncation
-- Truncate if needed and obtain (1) the new start ext at which to start
-- writing data and (2) possibly a dirty ext to write back into the inode
(sExt'', numBlksFreed, minodeExt') <-
if trunc && bytesToAlloc == 0
then do
(ext, nbf) <- truncUnalloc start len (sExt', sExtI)
return ( ext
, nbf
, if isEmbedded ext
then case minodeExt of
Nothing -> Just ext
Just _ -> -- This "can't happen" ...
error $ "Internal: dirty inode ext from "
++ "both allocFill & truncUnalloc!?"
else Nothing
)
else return (sExt', 0, minodeExt)
assert (blksToAlloc + extsToAlloc == 0 || numBlksFreed == 0) $ return ()
------------------------------------------------------------------------------
-- Data streaming
(eExtI, _, _) <- decomp (bdBlockSize dev) (bytesToEnd start len)
eExt <- getLastExt (Just $ (eExtI - sExtI) + 1) sExt''
when (len > 0) $ writeInodeData (sIdx, sExt'') eExtI trunc bytes
--------------------------------------------------------------------------------
-- Inode metadata adjustments & persist
now <- getTime
lift $ writeInode dev $
startInode
{ inoLastExt = if eExtI == sExtI
then (address sExt'', sExtI)
else (address eExt, eExtI)
, inoFileSize = newFileSz
, inoAllocBlocks = inoAllocBlocks startInode
+ blksToAlloc
+ extsToAlloc
- numBlksFreed
, inoAccessTime = now
, inoModifyTime = now
, inoChangeTime = now
, inoExt = maybe (inoExt startInode) id minodeExt'
}
-- ======================= End inode critical section =======================
--------------------------------------------------------------------------------
-- Inode operations
incLinkCount :: HalfsCapable b t r l m =>
InodeRef -- ^ Source inode ref
-> HalfsM b r l m ()
incLinkCount inr =
atomicModifyInode inr $ \nd ->
return $ nd{ inoNumLinks = inoNumLinks nd + 1 }
decLinkCount :: HalfsCapable b t r l m =>
InodeRef -- ^ Source inode ref
-> HalfsM b r l m ()
decLinkCount inr =
atomicModifyInode inr $ \nd ->
return $ nd{ inoNumLinks = inoNumLinks nd - 1 }
-- | Atomically modifies an inode; always updates inoChangeTime, but
-- callers are responsible for other metadata modifications.
atomicModifyInode :: HalfsCapable b t r l m =>
InodeRef
-> (Inode t -> HalfsM b r l m (Inode t))
-> HalfsM b r l m ()
atomicModifyInode inr f =
withLockedInode inr $ do
dev <- hasks hsBlockDev
inode <- drefInode inr
now <- getTime
inode' <- setChangeTime now `fmap` f inode
lift $ writeInode dev inode'
atomicReadInode :: HalfsCapable b t r l m =>
InodeRef
-> (Inode t -> a)
-> HalfsM b r l m a
atomicReadInode inr f =
withLockedInode inr $ f `fmap` drefInode inr
fileStat :: HalfsCapable b t r l m =>
InodeRef
-> HalfsM b r l m (FileStat t)
fileStat inr =
withLockedInode inr $ fileStat_lckd inr
fileStat_lckd :: HalfsCapable b t r l m =>
InodeRef
-> HalfsM b r l m (FileStat t)
fileStat_lckd inr = do
inode <- drefInode inr
return $ FileStat
{ fsInode = inr
, fsType = inoFileType inode
, fsMode = inoMode inode
, fsNumLinks = inoNumLinks inode
, fsUID = inoUser inode
, fsGID = inoGroup inode
, fsSize = inoFileSize inode
, fsNumBlocks = inoAllocBlocks inode
, fsAccessTime = inoAccessTime inode
, fsModifyTime = inoModifyTime inode
, fsChangeTime = inoChangeTime inode
}
--------------------------------------------------------------------------------
-- Inode/Ext stream helper & utility functions
isEmbedded :: Ext -> Bool
isEmbedded = isNilER . address
freeInode :: HalfsCapable b t r l m =>
InodeRef -- ^ reference to the inode to remove
-> HalfsM b r l m ()
freeInode inr@(IR addr) =
withLockedInode inr $ do
bm <- hasks hsBlockMap
start <- inoExt `fmap` drefInode inr
freeBlocks bm (blockAddrs start)
_numFreed :: Word64 <- freeExts bm start
BM.unalloc1 bm addr
freeBlocks :: HalfsCapable b t r l m =>
BlockMap b r l -> [Word64] -> HalfsM b r l m ()
freeBlocks _ [] = return ()
freeBlocks bm addrs =
lift $ BM.unallocBlocks bm $ BM.Discontig $ map (`BM.Extent` 1) addrs
-- NB: Freeing all of the blocks this way (as unit extents) is ugly and
-- inefficient, but we need to be tracking BlockGroups (or reconstitute them
-- here by digging for contiguous address subsequences in addrs) before we can
-- do better.
-- | Frees all exts after the given ext, returning the number of blocks freed.
freeExts :: (HalfsCapable b t r l m, Num a) =>
BlockMap b r l -> Ext -> HalfsM b r l m a
freeExts bm Ext{ nextExt = cr }
| isNilER cr = return $ fromInteger 0
| otherwise = drefExt cr >>= extFoldM freeExt (fromInteger 0)
where
freeExt !acc c =
freeBlocks bm toFree >> return (acc + genericLength toFree)
where toFree = unER (address c) : blockAddrs c
withLockedInode :: HalfsCapable b t r l m =>
InodeRef -- ^ reference to inode to lock
-> HalfsM b r l m a -- ^ action to take while holding lock
-> HalfsM b r l m a
withLockedInode inr act =
-- Inode locking: We currently use a single reader/writer lock tracked by the
-- InodeRef -> (lock, ref count) map in HalfsState. Reference counting is used
-- to determine when it is safe to remove a lock from the map.
--
-- We use the map to track lock info so that we don't hold locks for lengthy
-- intervals when we have access requests for disparate inode refs.
hbracket before after (const act {- inode lock doesn't escape! -})
where
before = do
-- When the InodeRef is already in the map, atomically increment its
-- reference count and acquire; otherwise, create a new lock and acquire.
inodeLock <- do
lm <- hasks hsInodeLockMap
withLockedRscRef lm $ \mapRef -> do
-- begin inode lock map critical section
lockInfo <- lookupRM inr mapRef
case lockInfo of
Nothing -> do
l <- newLock
insertRM inr (l, 1) mapRef
return l
Just (l, r) -> do
insertRM inr (l, r + 1) mapRef
return l
-- end inode lock map critical section
lock inodeLock
return inodeLock
--
after inodeLock = do
-- Atomically decrement the reference count for the InodeRef and then
-- release the lock
lm <- hasks hsInodeLockMap
withLockedRscRef lm $ \mapRef -> do
-- begin inode lock map critical section
lockInfo <- lookupRM inr mapRef
case lockInfo of
Nothing -> fail "withLockedInode internal: No InodeRef in lock map"
Just (l, r) | r == 1 -> deleteRM inr mapRef
| otherwise -> insertRM inr (l, r - 1) mapRef
-- end inode lock map critical section
release inodeLock
-- | A wrapper around Data.Serialize.decode that populates transient fields. We
-- do this to avoid occupying valuable on-disk inode space where possible. Bare
-- applications of 'decode' should not occur when deserializing inodes!
decodeInode :: HalfsCapable b t r l m =>
ByteString
-> HalfsM b r l m (Inode t)
decodeInode bs = do
(_, _, numAddrs', _) <- hasks hsSizes
case decode bs of
Left s -> throwError $ HE_DecodeFail_Inode s
Right n -> do
return n{ inoExt = (inoExt n){ numAddrs = numAddrs' } }
-- | A wrapper around Data.Serialize.decode that populates transient fields. We
-- do this to avoid occupying valuable on-disk Ext space where possible. Bare
-- applications of 'decode' should not occur when deserializing Exts!
decodeExt :: HalfsCapable b t r l m =>
Word64
-> ByteString
-> HalfsM b r l m Ext
decodeExt blkSz bs = do
numAddrs' <- computeNumExtAddrsM blkSz
case decode bs of
Left s -> throwError $ HE_DecodeFail_Ext s
Right c -> return c{ numAddrs = numAddrs' }
-- | Obtain the ext with the given ext index in the ext chain.
-- Currently traverses Exts from either the inode's embedded ext or
-- from the (saved) ext from the last operation, whichever is
-- closest.
findExt :: HalfsCapable b t r l m =>
Inode t -> Word64 -> HalfsM b r l m Ext
findExt Inode{ inoLastExt = (ler, lci), inoExt = defExt } sci
| isNilER ler || lci > sci = getLastExt (Just $ sci + 1) defExt
| otherwise = getLastExt (Just $ sci - lci + 1) =<< drefExt ler
-- | Allocate the given number of Exts and blocks, and fill blocks into the
-- ext chain starting at the given ext. Persists dirty exts and yields a new
-- start ext to use.
allocFill :: HalfsCapable b t r l m =>
(Ext -> Word64) -- ^ Available blocks function
-> Word64 -- ^ Number of blocks to allocate
-> Word64 -- ^ Number of exts to allocate
-> Ext -- ^ Last allocated ext
-> HalfsM b r l m Ext -- ^ Updated last ext
allocFill _ 0 _ eExt = return eExt
allocFill avail blksToAlloc extsToAlloc eExt = do
dev <- hasks hsBlockDev
bm <- hasks hsBlockMap
newExts <- allocExts dev bm
blks <- allocBlocks bm
-- Fill nextExt fields to form the region that we'll fill with the newly
-- allocated blocks (i.e., starting at the end of the already-allocated region
-- from the start ext, but including the newly allocated exts as well).
let (_, region) = foldr (\c (er, !acc) ->
( address c
, c{ nextExt = er } : acc
)
)
(nilER, [])
(eExt : newExts)
-- "Spill" the allocated blocks into the empty region
let (blks', k) = foldl fillBlks (blks, id) region
dirtyExts@(eExt':_) = k []
fillBlks (remBlks, k') c =
let cnt = min (safeToInt $ avail c) (length remBlks)
c' = c { blockCount = blockCount c + fromIntegral cnt
, blockAddrs = blockAddrs c ++ take cnt remBlks
}
in
(drop cnt remBlks, k' . (c':))
assert (null blks') $ return ()
forM_ (dirtyExts) $ \c -> unless (isEmbedded c) $ lift $ writeExt dev c
return eExt'
where
allocBlocks bm = do
-- currently "flattens" BlockGroup; see comment in writeStream
mbg <- lift $ BM.allocBlocks bm blksToAlloc
case mbg of
Nothing -> throwError HE_AllocFailed
Just bg -> return $ BM.blkRangeBG bg
--
allocExts dev bm =
if 0 == extsToAlloc
then return []
else do
-- TODO: Unalloc partial allocs on HE_AllocFailed?
mexts <- fmap sequence $ replicateM (safeToInt extsToAlloc) $ do
mcr <- fmap ER `fmap` BM.alloc1 bm
case mcr of
Nothing -> return Nothing
Just cr -> Just `fmap` lift (buildEmptyExt dev cr)
maybe (throwError HE_AllocFailed) (return) mexts
-- | Truncates the stream at the given a stream index and length offset, and
-- unallocates all resources in the corresponding free region, yielding a new
-- Ext for the truncated chain.
truncUnalloc ::
HalfsCapable b t r l m =>
Word64 -- ^ Starting stream byte index
-> Word64 -- ^ Length from start at which to truncate
-> (Ext, Word64) -- ^ Start ext of chain to truncate, start ext idx
-> HalfsM b r l m (Ext, Word64)
-- ^ new start ext, number of blocks freed
truncUnalloc start len (stExt, sExtI) = do
dev <- hasks hsBlockDev
bm <- hasks hsBlockMap
(eExtI, eBlkOff, _) <- decomp (bdBlockSize dev) (bytesToEnd start len)
assert (eExtI >= sExtI) $ return ()
-- Get the (new) end of the ext chain. Retain all exts in [sExtI, eExtI].
eExt <- getLastExt (Just $ eExtI - sExtI + 1) stExt
let keepBlkCnt = if start + len == 0 then 0 else eBlkOff + 1
endExtRem = genericDrop keepBlkCnt (blockAddrs eExt)
freeBlocks bm endExtRem
numFreed <- (+ (genericLength endExtRem)) `fmap` freeExts bm eExt
-- Currently, only eExt is considered dirty; we do *not* do any writes to any
-- of the Exts that are detached from the chain & freed (we just toss them
-- out); this may have implications for fsck.
let dirtyExts@(firstDirty:_) =
[
-- eExt, adjusted to discard the freed blocks and clear the
-- nextExt field.
eExt { blockCount = keepBlkCnt
, blockAddrs = genericTake keepBlkCnt (blockAddrs eExt)
, nextExt = nilER
}
]
stExt' = if sExtI == eExtI then firstDirty else stExt
forM_ (dirtyExts) $ \c -> unless (isEmbedded c) $ lift $ writeExt dev c
return (stExt', numFreed)
-- | Write the given bytes to the already-allocated/truncated inode data stream
-- starting at the given start indices (ext/blk/byte offsets) and ending when
-- we have traversed up (and including) to the end ext index. Assumes the
-- inode lock is held.
writeInodeData :: HalfsCapable b t r l m =>
(StreamIdx, Ext)
-> Word64
-> Bool
-> ByteString
-> HalfsM b r l m ()
writeInodeData ((sExtI, sBlkOff, sByteOff), sExt) eExtI trunc bytes = do
dev <- hasks hsBlockDev
sBlk <- lift $ readBlock dev sExt sBlkOff
let bs = bdBlockSize dev
toWrite =
-- The first block-sized chunk to write is the region in the start block
-- prior to the start byte offset (header), followed by the first bytes
-- of the data. The trailer is nonempty and must be included when
-- BS.length bytes < bs. We adjust the input bytestring by this
-- first-block padding below.
let (sData, bytes') = bsSplitAt (bs - sByteOff) bytes
header = bsTake sByteOff sBlk
trailLen = sByteOff + fromIntegral (BS.length sData)
trailer = if trunc
then bsReplicate (bs - trailLen) truncSentinel
else bsDrop trailLen sBlk
fstBlk = header `BS.append` sData `BS.append` trailer
in assert (fromIntegral (BS.length fstBlk) == bs) $
fstBlk `BS.append` bytes'
-- The unfoldr seed is: current ext/idx, a block offset "supply", and the
-- data that remains to be written.
unfoldrM_ (fillExt dev) ((sExt, sExtI), sBlkOff : repeat 0, toWrite)
where
fillExt _ (_, [], _) = error "The impossible happened"
fillExt dev ((cExt, cExtI), blkOff:boffs, toWrite)
| cExtI > eExtI || BS.null toWrite = return Nothing
| otherwise = do
let blkAddrs = genericDrop blkOff (blockAddrs cExt)
split crs = let (cs, rems) = unzip crs in (cs, last rems)
gbc = lift . getBlockContents dev trunc
(chunks, remBytes) <- split `fmap` unfoldrM gbc (toWrite, blkAddrs)
assert (let lc = length chunks; lb = length blkAddrs
in lc == lb || (BS.length remBytes == 0 && lc < lb)) $ return ()
mapM_ (lift . uncurry (bdWriteBlock dev)) (blkAddrs `zip` chunks)
if isNilER (nextExt cExt)
then assert (BS.null remBytes) $ return Nothing
else do
nextExt' <- drefExt (nextExt cExt)
return $ Just $ ((), ((nextExt', cExtI+1), boffs, remBytes))
-- | Splits the input bytestring into block-sized chunks; may read from the
-- block device in order to preserve contents of blocks if needed.
getBlockContents ::
(Monad m, Functor m) =>
BlockDevice m
-- ^ The block device
-> Bool
-- ^ Truncating write? (Impacts partial block retention)
-> (ByteString, [Word64])
-- ^ Input bytestring, block addresses for each chunk (for retention)
-> m (Maybe ((ByteString, ByteString), (ByteString, [Word64])))
-- ^ When unfolding, the collected result type here of (ByteString,
-- ByteString) is (chunk, remaining data), in case the entire input bytestring
-- is not consumed. The seed value is (bytestring for all data, block
-- addresses for each chunk).
getBlockContents _ _ (s, _) | BS.null s = return Nothing
getBlockContents _ _ (_, []) = return Nothing
getBlockContents dev trunc (s, blkAddr:blkAddrs) = do
let (newBlkData, remBytes) = bsSplitAt bs s
bs = bdBlockSize dev
if BS.null remBytes
then do
-- Last block; retain the relevant portion of its data
trailer <-
if trunc
then return $ bsReplicate bs truncSentinel
else
bsDrop (BS.length newBlkData) `fmap` bdReadBlock dev blkAddr
let rslt = bsTake bs $ newBlkData `BS.append` trailer
return $ Just ((rslt, remBytes), (remBytes, blkAddrs))
else do
-- Full block; nothing to see here
return $ Just ((newBlkData, remBytes), (remBytes, blkAddrs))
-- | Reads the contents of the given exts's ith block
readBlock :: (Monad m) =>
BlockDevice m
-> Ext
-> Word64
-> m ByteString
readBlock dev c i = do
assert (i < blockCount c) $ return ()
bdReadBlock dev (blockAddrs c !! safeToInt i)
writeExt :: Monad m =>
BlockDevice m -> Ext -> m ()
writeExt dev c =
dbug (" ==> Writing ext: " ++ show c ) $
bdWriteBlock dev (unER $ address c) (encode c)
writeInode :: (Monad m, Ord t, Serialize t, Show t) =>
BlockDevice m -> Inode t -> m ()
writeInode dev n = bdWriteBlock dev (unIR $ inoAddress n) (encode n)
-- | Expands the given Ext into a Ext list containing itself followed by zero
-- or more Exts; can be bounded by a positive nonzero value to only retrieve
-- (up to) the given number of exts.
expandExts :: HalfsCapable b t r l m =>
Maybe Word64 -> Ext -> HalfsM b r l m [Ext]
expandExts (Just bnd) start@Ext{ nextExt = cr }
| bnd == 0 = throwError HE_InvalidExtIdx
| isNilER cr || bnd == 1 = return [start]
| otherwise = do
(start:) `fmap` (drefExt cr >>= expandExts (Just (bnd - 1)))
expandExts Nothing start@Ext{ nextExt = cr }
| isNilER cr = return [start]
| otherwise = do
(start:) `fmap` (drefExt cr >>= expandExts Nothing)
getLastExt :: HalfsCapable b t r l m =>
Maybe Word64 -> Ext -> HalfsM b r l m Ext
getLastExt mbnd c = last `fmap` expandExts mbnd c
extFoldM :: HalfsCapable b t r l m =>
(a -> Ext -> HalfsM b r l m a) -> a -> Ext -> HalfsM b r l m a
extFoldM f a c@Ext{ nextExt = cr }
| isNilER cr = f a c
| otherwise = f a c >>= \fac -> drefExt cr >>= extFoldM f fac
extMapM :: HalfsCapable b t r l m =>
(Ext -> HalfsM b r l m a) -> Ext -> HalfsM b r l m [a]
extMapM f c@Ext{ nextExt = cr }
| isNilER cr = liftM (:[]) (f c)
| otherwise = liftM2 (:) (f c) (drefExt cr >>= extMapM f)
drefExt :: HalfsCapable b t r l m =>
ExtRef -> HalfsM b r l m Ext
drefExt cr@(ER addr) | isNilER cr = throwError HE_InvalidExtIdx
| otherwise = do
dev <- hasks hsBlockDev
lift (bdReadBlock dev addr) >>= decodeExt (bdBlockSize dev)
drefInode :: HalfsCapable b t r l m =>
InodeRef -> HalfsM b r l m (Inode t)
drefInode (IR addr) = do
dev <- hasks hsBlockDev
lift (bdReadBlock dev addr) >>= decodeInode
setChangeTime :: (Ord t, Serialize t) => t -> Inode t -> Inode t
setChangeTime t nd = nd{ inoChangeTime = t }
-- | Decompose the given absolute byte offset into an inode's data stream into
-- Ext index (i.e., 0-based index into the ext chain), a block offset within
-- that Ext, and a byte offset within that block.
decomp :: (Serialize t, Timed t m, Monad m, Show t) =>
Word64 -- ^ Block size, in bytes
-> Word64 -- ^ Offset into the data stream
-> HalfsM b r l m StreamIdx
decomp blkSz streamOff = do
-- Note that the first Ext in a Ext chain always gets embedded in an Inode,
-- and thus has differing capacity than the rest of the Exts, which are of
-- uniform size.
(stExtBytes, extBytes, _, _) <- hasks hsSizes
let (extIdx, extByteIdx) =
if streamOff >= stExtBytes
then fmapFst (+1) $ (streamOff - stExtBytes) `divMod` extBytes
else (0, streamOff)
(blkOff, byteOff) = extByteIdx `divMod` blkSz
return (extIdx, blkOff, byteOff)
getStreamIdx :: HalfsCapable b t r l m =>
Word64 -- block size in bytse
-> Word64 -- file size in bytes
-> Word64 -- start byte index
-> HalfsM b r l m StreamIdx
getStreamIdx blkSz fileSz start = do
when (start > fileSz) $ throwError $ HE_InvalidStreamIndex start
decomp blkSz start
bytesToEnd :: Word64 -> Word64 -> Word64
bytesToEnd start len
| start + len == 0 = 0
| otherwise = max (start + len - 1) start
-- "Safe" (i.e., emits runtime assertions on overflow) versions of
-- BS.{take,drop,replicate}. We want the efficiency of these functions without
-- the danger of an unguarded fromIntegral on the Word64 types we use throughout
-- this module, as this could overflow for absurdly large device geometries. We
-- may need to revisit some implementation decisions should this occur (e.g.,
-- because many Prelude and Data.ByteString functions yield and take values of
-- type Int).
safeToInt :: Integral a => a -> Int
safeToInt n =
assert (toInteger n <= toInteger (maxBound :: Int)) $ fromIntegral n
makeSafeIntF :: Integral a => (Int -> b) -> a -> b
makeSafeIntF f n = f $ safeToInt n
-- | "Safe" version of Data.ByteString.take
bsTake :: Integral a => a -> ByteString -> ByteString
bsTake = makeSafeIntF BS.take
-- | "Safe" version of Data.ByteString.drop
bsDrop :: Integral a => a -> ByteString -> ByteString
bsDrop = makeSafeIntF BS.drop
-- | "Safe" version of Data.ByteString.replicate
bsReplicate :: Integral a => a -> Word8 -> ByteString
bsReplicate = makeSafeIntF BS.replicate
bsSplitAt :: Integral a => a -> ByteString -> (ByteString, ByteString)
bsSplitAt = makeSafeIntF BS.splitAt
--------------------------------------------------------------------------------
-- Magic numbers
magicStr :: String
magicStr = "This is a halfs Inode structure!"
magicBytes :: [Word8]
magicBytes = assert (length magicStr == 32) $
map (fromIntegral . ord) magicStr
magic1, magic2, magic3, magic4 :: ByteString
magic1 = BS.pack $ take 8 $ drop 0 magicBytes
magic2 = BS.pack $ take 8 $ drop 8 magicBytes
magic3 = BS.pack $ take 8 $ drop 16 magicBytes
magic4 = BS.pack $ take 8 $ drop 24 magicBytes
magicExtStr :: String
magicExtStr = "!!erutcurts tnoC sflah a si sihT"
magicExtBytes :: [Word8]
magicExtBytes = assert (length magicExtStr == 32) $
map (fromIntegral . ord) magicExtStr
cmagic1, cmagic2, cmagic3, cmagic4 :: ByteString
cmagic1 = BS.pack $ take 8 $ drop 0 magicExtBytes
cmagic2 = BS.pack $ take 8 $ drop 8 magicExtBytes
cmagic3 = BS.pack $ take 8 $ drop 16 magicExtBytes
cmagic4 = BS.pack $ take 8 $ drop 24 magicExtBytes
--------------------------------------------------------------------------------
-- Typeclass instances
instance (Show t, Eq t, Ord t, Serialize t) => Serialize (Inode t) where
put n = do
putByteString $ magic1
put $ inoParent n
put $ inoLastExt n
put $ inoAddress n
putWord64be $ inoFileSize n
putWord64be $ inoAllocBlocks n
put $ inoFileType n
put $ inoMode n
putByteString $ magic2
putWord64be $ inoNumLinks n
put $ inoCreateTime n
put $ inoModifyTime n
put $ inoAccessTime n
put $ inoChangeTime n
put $ inoUser n
put $ inoGroup n
putByteString $ magic3
put $ inoExt n
-- NB: For Exts that are inside inodes, the Serialize instance for Ext
-- relies on only 8 + iPadSize bytes beyond this point (the inode magic
-- number and some padding). If you change this, you'll need to update the
-- related calculations in Serialize Ext's get function!
putByteString magic4
replicateM_ iPadSize $ putWord8 padSentinel
get = do
checkMagic magic1
par <- get
lcr <- get
addr <- get
fsz <- getWord64be
blks <- getWord64be
ftype <- get
fmode <- get
checkMagic magic2
nlnks <- getWord64be
ctm <- get
mtm <- get
atm <- get
chtm <- get
unless (ctm <= mtm && ctm <= atm) $
fail "Inode: Incoherent modified / creation / access times."
usr <- get
grp <- get
checkMagic magic3
c <- get
checkMagic magic4
padding <- replicateM iPadSize $ getWord8
assert (all (== padSentinel) padding) $ return ()
return Inode
{ inoParent = par
, inoLastExt = lcr
, inoAddress = addr
, inoFileSize = fsz
, inoAllocBlocks = blks
, inoFileType = ftype
, inoMode = fmode
, inoNumLinks = nlnks
, inoCreateTime = ctm
, inoModifyTime = mtm
, inoAccessTime = atm
, inoChangeTime = chtm
, inoUser = usr
, inoGroup = grp
, inoExt = c
}
where
checkMagic x = do
magic <- getBytes 8
unless (magic == x) $ fail "Invalid Inode: magic number mismatch"
instance Serialize Ext where
put c = do
unless (numBlocks <= numAddrs') $
fail $ "Corrupted Ext structure put: too many blocks"
-- dbugM $ "Ext.put: numBlocks = " ++ show numBlocks
-- dbugM $ "Ext.put: blocks = " ++ show blocks
-- dbugM $ "Ext.put: fillBlocks = " ++ show fillBlocks
putByteString $ cmagic1
put $ address c
put $ nextExt c
putByteString $ cmagic2
putWord64be $ blockCount c
putByteString $ cmagic3
forM_ blocks put
replicateM_ fillBlocks $ put nilIR
putByteString cmagic4
replicateM_ cPadSize $ putWord8 padSentinel
where
blocks = blockAddrs c
numBlocks = length blocks
numAddrs' = safeToInt $ numAddrs c
fillBlocks = numAddrs' - numBlocks
get = do
checkMagic cmagic1
addr <- get
dbugM $ "decodeExt: addr = " ++ show addr
ext <- get
dbugM $ "decodeExt: ext = " ++ show ext
checkMagic cmagic2
blkCnt <- getWord64be
dbugM $ "decodeExt: blkCnt = " ++ show blkCnt
checkMagic cmagic3
-- Some calculations differ slightly based on whether or not this Ext is
-- embedded in an inode; in particular, the Inode writes a terminating magic
-- number after the end of the serialized Ext, so we must account for that
-- when calculating the number of blocks to read below.
let isEmbeddedExt = addr == nilER
dbugM $ "decodeExt: isEmbeddedExt = " ++ show isEmbeddedExt
numBlockBytes <- do
remb <- fmap fromIntegral G.remaining
dbugM $ "decodeExt: remb = " ++ show remb
dbugM $ "--"
let numTrailingBytes =
if isEmbeddedExt
then 8 + fromIntegral cPadSize + 8 + fromIntegral iPadSize
-- cmagic4, padding, inode's magic4, inode's padding <EOS>
else 8 + fromIntegral cPadSize
-- cmagic4, padding, <EOS>
dbugM $ "decodeExt: numTrailingBytes = " ++ show numTrailingBytes
return (remb - numTrailingBytes)
dbugM $ "decodeExt: numBlockBytes = " ++ show numBlockBytes
let (numBlocks, check) = numBlockBytes `divMod` refSize
dbugM $ "decodeExt: numBlocks = " ++ show numBlocks
-- dbugM $ "decodeExt: numBlockBytes = " ++ show numBlockBytes
-- dbugM $ "decodeExt: refSzie = " ++ show refSize
-- dbugM $ "decodeExt: check = " ++ show check
unless (check == 0) $ fail "Ext: Bad remaining byte count for block list."
unless (not isEmbeddedExt && numBlocks >= minExtBlocks ||
isEmbeddedExt && numBlocks >= minInodeBlocks) $
fail "Ext: Not enough space left for minimum number of blocks."
blks <- filter (/= 0) `fmap` replicateM (safeToInt numBlocks) get
checkMagic cmagic4
padding <- replicateM cPadSize $ getWord8
assert (all (== padSentinel) padding) $ return ()
let na = error $ "numAddrs has not been populated via Data.Serialize.get "
++ "for Ext; did you forget to use the "
++ "Inode.decodeExt wrapper?"
return Ext
{ address = addr
, nextExt = ext
, blockCount = blkCnt
, blockAddrs = blks
, numAddrs = na
}
where
checkMagic x = do
magic <- getBytes 8
unless (magic == x) $ fail "Invalid Ext: magic number mismatch"
--------------------------------------------------------------------------------
-- Debugging cruft
_dumpExts :: HalfsCapable b t r l m =>
Ext -> HalfsM b r l m ()
_dumpExts stExt = do
exts <- expandExts Nothing stExt
if null exts
then dbug ("=== No exts ===") $ return ()
else do
dbug ("=== Exts ===") $ return ()
mapM_ (\c -> dbug (" " ++ show c) $ return ()) exts
_allowNoUsesOf :: HalfsCapable b t r l m => HalfsM b r l m ()
_allowNoUsesOf = do
extMapM undefined undefined >> return ()
|
hackern/halfs
|
Halfs/Inode.hs
|
Haskell
|
bsd-3-clause
| 51,840
|
{-# LANGUAGE Rank2Types, RecordWildCards #-}
module OS.Internal
( OS(..)
, genericOS
)
where
import Data.Version (showVersion)
import Development.Shake
import Development.Shake.FilePath
import Dirs
import Paths
import Types
import Utils
data OS = OS
{
-- These paths are all on the target machine.
-- They should all be absolute paths.
-- During the build, they will be made relative to targetDir
-- | Where HP will be installed
osHpPrefix :: FilePath
-- | Where GHC will be installed
, osGhcPrefix :: FilePath
-- | Platform-specific actions needed to finish the ghc-bindist/local
-- install step (and before any HP packages are built)
, osGhcLocalInstall :: GhcInstall
-- | Platform-specific actions needed to finish the target-ghc
-- install step
, osGhcTargetInstall :: GhcInstall
-- | Where each package is installed
, osPackageTargetDir :: forall p. (PackagePattern p) => p -> FilePath
-- | Set True if GHC in this build supports creating shared libs
, osDoShared :: Bool
-- | Any action to take, after creation of the package conf file,
-- before the package's haddock files are created.
, osPackagePostRegister :: Package -> Action ()
-- | Extra action to install the package from the build dir to the
-- target image.
, osPackageInstallAction :: Package -> Action ()
-- | Extra actions run after GHC and the packages have been assembled
-- into the target image.
, osTargetAction :: Action ()
-- | Directory relative to ghc install for package.conf.d
-- (e.g., "lib/7.8.2/package.conf.d")
, osGhcDbDir :: FilePath
-- | Additional switches/options for "ghc-pkg"
-- querying the 'haddock-html' field with ghc-pkg.
, osGhcPkgHtmlFieldExtras :: [String]
-- | If needed by the platform, make needed changes to the path
-- which will be used for the relative urls for platform packages
-- when referenced by other packages. The first argument is the
-- base path, to which the 2nd argument should be made relative
-- (after munging).
, osPlatformPkgPathMunge :: FilePath -> HaddockPkgLoc -> HaddockPkgLoc
-- | If needed by the platform, make needed changes to the path
-- which will be used for the relative urls for GHC packages when
-- referenced by other packages. The first argument is the
-- base path, to which the 2nd argument should be made relative
-- (after munging).
, osGhcPkgPathMunge :: FilePath -> HaddockPkgLoc -> HaddockPkgLoc
-- | Path, relative to targetDir, expanded for the given package,
-- where that package's html docs are installed.
, osPkgHtmlDir :: Package -> FilePath
-- | Extra actions run after haddock has built the master doc
, osDocAction :: Action ()
-- | Final, OS specific, product. Usually a tarball or installer.
-- Should be located in productDir
, osProduct :: FilePath
-- | Rules for building the product and anything from osTargetExtraNeeds
, osRules :: Release -> BuildConfig -> Rules ()
-- | Extra arguments that are needed for "cabal configure"
, osPackageConfigureExtraArgs :: Package -> [String]
}
genericOS :: BuildConfig -> OS
genericOS BuildConfig{..} = OS{..}
where
HpVersion{..} = bcHpVersion
GhcVersion{..} = bcGhcVersion
osHpPrefix = "/usr/local/haskell-platform" </> showVersion hpVersion
osGhcPrefix = "/usr/local/ghc" </> showVersion ghcVersion
osGhcLocalInstall = GhcInstallConfigure
osGhcTargetInstall = GhcInstallConfigure
osPackageTargetDir p = osHpPrefix </> "lib" </> packagePattern p
osDoShared = True
osPackagePostRegister _ = return ()
osPackageInstallAction p = do
let confFile = packageTargetConf p
let regDir = targetDir </+> osHpPrefix </> "etc" </> "registrations"
let regFile = regDir </> show p
makeDirectory regDir
hasReg <- doesFileExist confFile
if hasReg
then command_ [] "cp" [confFile, regFile]
else command_ [] "rm" ["-f", regFile]
osTargetAction = return ()
osGhcDbDir = "lib" </> show bcGhcVersion </> "package.conf.d"
osGhcPkgHtmlFieldExtras = []
osPlatformPkgPathMunge = flip const
osGhcPkgPathMunge = flip const
osPkgHtmlDir pkg = osPackageTargetDir pkg </> "doc" </> "html"
osDocAction = return ()
osProduct = productDir </> "generic.tar.gz"
osRules _hpRelease _bc =
osProduct %> \out -> do
need [phonyTargetDir, vdir ghcVirtualTarget]
command_ [Cwd buildRoot]
"tar" ["czf", out `relativeToDir` buildRoot, targetDir `relativeToDir` buildRoot]
osPackageConfigureExtraArgs _pkg = []
|
erantapaa/haskell-platform
|
hptool/src/OS/Internal.hs
|
Haskell
|
bsd-3-clause
| 4,934
|
module SDL.Raw.Basic (
-- * Initialization and Shutdown
init,
initSubSystem,
quit,
quitSubSystem,
setMainReady,
wasInit,
-- * Configuration Variables
addHintCallback,
clearHints,
delHintCallback,
getHint,
setHint,
setHintWithPriority,
-- * Log Handling
log,
logCritical,
logDebug,
logError,
logGetOutputFunction,
logGetPriority,
logInfo,
logMessage,
logResetPriorities,
logSetAllPriority,
logSetOutputFunction,
logSetPriority,
logVerbose,
logWarn,
-- * Assertions
-- | Use Haskell's own assertion primitives rather than SDL's.
-- * Querying SDL Version
getRevision,
getRevisionNumber,
getVersion
) where
import Control.Monad.IO.Class
import Foreign.C.String
import Foreign.C.Types
import Foreign.Ptr
import SDL.Raw.Enum
import SDL.Raw.Types
import Prelude hiding (init, log)
foreign import ccall "SDL.h SDL_Init" initFFI :: InitFlag -> IO CInt
foreign import ccall "SDL.h SDL_InitSubSystem" initSubSystemFFI :: InitFlag -> IO CInt
foreign import ccall "SDL.h SDL_Quit" quitFFI :: IO ()
foreign import ccall "SDL.h SDL_QuitSubSystem" quitSubSystemFFI :: InitFlag -> IO ()
foreign import ccall "SDL.h SDL_SetMainReady" setMainReadyFFI :: IO ()
foreign import ccall "SDL.h SDL_WasInit" wasInitFFI :: InitFlag -> IO InitFlag
foreign import ccall "SDL.h SDL_AddHintCallback" addHintCallbackFFI :: CString -> HintCallback -> Ptr () -> IO ()
foreign import ccall "SDL.h SDL_ClearHints" clearHintsFFI :: IO ()
foreign import ccall "SDL.h SDL_DelHintCallback" delHintCallbackFFI :: CString -> HintCallback -> Ptr () -> IO ()
foreign import ccall "SDL.h SDL_GetHint" getHintFFI :: CString -> IO CString
foreign import ccall "SDL.h SDL_SetHint" setHintFFI :: CString -> CString -> IO Bool
foreign import ccall "SDL.h SDL_SetHintWithPriority" setHintWithPriorityFFI :: CString -> CString -> HintPriority -> IO Bool
foreign import ccall "SDL.h SDL_LogGetOutputFunction" logGetOutputFunctionFFI :: Ptr LogOutputFunction -> Ptr (Ptr ()) -> IO ()
foreign import ccall "SDL.h SDL_LogGetPriority" logGetPriorityFFI :: CInt -> IO LogPriority
foreign import ccall "sdlhelper.c SDLHelper_LogMessage" logMessageFFI :: CInt -> LogPriority -> CString -> IO ()
foreign import ccall "SDL.h SDL_LogResetPriorities" logResetPrioritiesFFI :: IO ()
foreign import ccall "SDL.h SDL_LogSetAllPriority" logSetAllPriorityFFI :: LogPriority -> IO ()
foreign import ccall "SDL.h SDL_LogSetOutputFunction" logSetOutputFunctionFFI :: LogOutputFunction -> Ptr () -> IO ()
foreign import ccall "SDL.h SDL_LogSetPriority" logSetPriorityFFI :: CInt -> LogPriority -> IO ()
foreign import ccall "SDL.h SDL_GetRevision" getRevisionFFI :: IO CString
foreign import ccall "SDL.h SDL_GetRevisionNumber" getRevisionNumberFFI :: IO CInt
foreign import ccall "SDL.h SDL_GetVersion" getVersionFFI :: Ptr Version -> IO ()
init :: MonadIO m => InitFlag -> m CInt
init v1 = liftIO $ initFFI v1
{-# INLINE init #-}
initSubSystem :: MonadIO m => InitFlag -> m CInt
initSubSystem v1 = liftIO $ initSubSystemFFI v1
{-# INLINE initSubSystem #-}
quit :: MonadIO m => m ()
quit = liftIO quitFFI
{-# INLINE quit #-}
quitSubSystem :: MonadIO m => InitFlag -> m ()
quitSubSystem v1 = liftIO $ quitSubSystemFFI v1
{-# INLINE quitSubSystem #-}
setMainReady :: MonadIO m => m ()
setMainReady = liftIO setMainReadyFFI
{-# INLINE setMainReady #-}
wasInit :: MonadIO m => InitFlag -> m InitFlag
wasInit v1 = liftIO $ wasInitFFI v1
{-# INLINE wasInit #-}
addHintCallback :: MonadIO m => CString -> HintCallback -> Ptr () -> m ()
addHintCallback v1 v2 v3 = liftIO $ addHintCallbackFFI v1 v2 v3
{-# INLINE addHintCallback #-}
clearHints :: MonadIO m => m ()
clearHints = liftIO clearHintsFFI
{-# INLINE clearHints #-}
delHintCallback :: MonadIO m => CString -> HintCallback -> Ptr () -> m ()
delHintCallback v1 v2 v3 = liftIO $ delHintCallbackFFI v1 v2 v3
{-# INLINE delHintCallback #-}
getHint :: MonadIO m => CString -> m CString
getHint v1 = liftIO $ getHintFFI v1
{-# INLINE getHint #-}
setHint :: MonadIO m => CString -> CString -> m Bool
setHint v1 v2 = liftIO $ setHintFFI v1 v2
{-# INLINE setHint #-}
setHintWithPriority :: MonadIO m => CString -> CString -> HintPriority -> m Bool
setHintWithPriority v1 v2 v3 = liftIO $ setHintWithPriorityFFI v1 v2 v3
{-# INLINE setHintWithPriority #-}
log :: CString -> IO ()
log = logMessage SDL_LOG_CATEGORY_APPLICATION SDL_LOG_PRIORITY_INFO
{-# INLINE log #-}
logCritical :: CInt -> CString -> IO ()
logCritical category = logMessage category SDL_LOG_PRIORITY_CRITICAL
{-# INLINE logCritical #-}
logDebug :: CInt -> CString -> IO ()
logDebug category = logMessage category SDL_LOG_PRIORITY_DEBUG
{-# INLINE logDebug #-}
logError :: CInt -> CString -> IO ()
logError category = logMessage category SDL_LOG_PRIORITY_ERROR
{-# INLINE logError #-}
logGetOutputFunction :: MonadIO m => Ptr LogOutputFunction -> Ptr (Ptr ()) -> m ()
logGetOutputFunction v1 v2 = liftIO $ logGetOutputFunctionFFI v1 v2
{-# INLINE logGetOutputFunction #-}
logGetPriority :: MonadIO m => CInt -> m LogPriority
logGetPriority v1 = liftIO $ logGetPriorityFFI v1
{-# INLINE logGetPriority #-}
logInfo :: CInt -> CString -> IO ()
logInfo category = logMessage category SDL_LOG_PRIORITY_INFO
{-# INLINE logInfo #-}
logMessage :: MonadIO m => CInt -> LogPriority -> CString -> m ()
logMessage v1 v2 v3 = liftIO $ logMessageFFI v1 v2 v3
{-# INLINE logMessage #-}
logResetPriorities :: MonadIO m => m ()
logResetPriorities = liftIO logResetPrioritiesFFI
{-# INLINE logResetPriorities #-}
logSetAllPriority :: MonadIO m => LogPriority -> m ()
logSetAllPriority v1 = liftIO $ logSetAllPriorityFFI v1
{-# INLINE logSetAllPriority #-}
logSetOutputFunction :: MonadIO m => LogOutputFunction -> Ptr () -> m ()
logSetOutputFunction v1 v2 = liftIO $ logSetOutputFunctionFFI v1 v2
{-# INLINE logSetOutputFunction #-}
logSetPriority :: MonadIO m => CInt -> LogPriority -> m ()
logSetPriority v1 v2 = liftIO $ logSetPriorityFFI v1 v2
{-# INLINE logSetPriority #-}
logVerbose :: CInt -> CString -> IO ()
logVerbose category = logMessage category SDL_LOG_PRIORITY_VERBOSE
{-# INLINE logVerbose #-}
logWarn :: CInt -> CString -> IO ()
logWarn category = logMessage category SDL_LOG_PRIORITY_WARN
{-# INLINE logWarn #-}
getRevision :: MonadIO m => m CString
getRevision = liftIO getRevisionFFI
{-# INLINE getRevision #-}
getRevisionNumber :: MonadIO m => m CInt
getRevisionNumber = liftIO getRevisionNumberFFI
{-# INLINE getRevisionNumber #-}
getVersion :: MonadIO m => Ptr Version -> m ()
getVersion v1 = liftIO $ getVersionFFI v1
{-# INLINE getVersion #-}
|
Velro/sdl2
|
src/SDL/Raw/Basic.hs
|
Haskell
|
bsd-3-clause
| 6,592
|
{-# LANGUAGE DeriveGeneric, DeriveDataTypeable #-}
-- | Types used while planning how to build everything in a project.
--
-- Primarily this is the 'ElaboratedInstallPlan'.
--
module Distribution.Client.ProjectPlanning.Types (
SolverInstallPlan,
-- * Elaborated install plan types
ElaboratedInstallPlan,
ElaboratedConfiguredPackage(..),
ElaboratedPlanPackage,
ElaboratedSharedConfig(..),
ElaboratedReadyPackage,
BuildStyle(..),
CabalFileText,
-- * Types used in executing an install plan
--TODO: [code cleanup] these types should live with execution, not with
-- plan definition. Need to better separate InstallPlan definition.
GenericBuildResult(..),
BuildResult,
BuildSuccess(..),
BuildFailure(..),
DocsResult(..),
TestsResult(..),
-- * Build targets
PackageTarget(..),
ComponentTarget(..),
SubComponentTarget(..),
-- * Setup script
SetupScriptStyle(..),
) where
import Distribution.Client.PackageHash
import Distribution.Client.Types
hiding ( BuildResult, BuildSuccess(..), BuildFailure(..)
, DocsResult(..), TestsResult(..) )
import Distribution.Client.InstallPlan
( GenericInstallPlan, SolverInstallPlan, GenericPlanPackage )
import Distribution.Package
hiding (InstalledPackageId, installedPackageId)
import Distribution.System
import qualified Distribution.PackageDescription as Cabal
import Distribution.InstalledPackageInfo (InstalledPackageInfo)
import Distribution.Simple.Compiler
import Distribution.Simple.Program.Db
import Distribution.ModuleName (ModuleName)
import Distribution.Simple.LocalBuildInfo (ComponentName(..))
import qualified Distribution.Simple.InstallDirs as InstallDirs
import Distribution.Simple.InstallDirs (PathTemplate)
import Distribution.Version
import Distribution.Solver.Types.ComponentDeps (ComponentDeps)
import Distribution.Solver.Types.OptionalStanza
import Distribution.Solver.Types.PackageFixedDeps
import Data.Map (Map)
import Data.Set (Set)
import qualified Data.ByteString.Lazy as LBS
import Distribution.Compat.Binary
import GHC.Generics (Generic)
import Data.Typeable (Typeable)
import Control.Exception
-- | The combination of an elaborated install plan plus a
-- 'ElaboratedSharedConfig' contains all the details necessary to be able
-- to execute the plan without having to make further policy decisions.
--
-- It does not include dynamic elements such as resources (such as http
-- connections).
--
type ElaboratedInstallPlan
= GenericInstallPlan InstalledPackageInfo
ElaboratedConfiguredPackage
BuildSuccess BuildFailure
type ElaboratedPlanPackage
= GenericPlanPackage InstalledPackageInfo
ElaboratedConfiguredPackage
BuildSuccess BuildFailure
--TODO: [code cleanup] decide if we really need this, there's not much in it, and in principle
-- even platform and compiler could be different if we're building things
-- like a server + client with ghc + ghcjs
data ElaboratedSharedConfig
= ElaboratedSharedConfig {
pkgConfigPlatform :: Platform,
pkgConfigCompiler :: Compiler, --TODO: [code cleanup] replace with CompilerInfo
-- | The programs that the compiler configured (e.g. for GHC, the progs
-- ghc & ghc-pkg). Once constructed, only the 'configuredPrograms' are
-- used.
pkgConfigCompilerProgs :: ProgramDb
}
deriving (Show, Generic)
--TODO: [code cleanup] no Eq instance
instance Binary ElaboratedSharedConfig
data ElaboratedConfiguredPackage
= ElaboratedConfiguredPackage {
pkgInstalledId :: InstalledPackageId,
pkgSourceId :: PackageId,
-- | TODO: [code cleanup] we don't need this, just a few bits from it:
-- build type, spec version
pkgDescription :: Cabal.PackageDescription,
-- | A total flag assignment for the package
pkgFlagAssignment :: Cabal.FlagAssignment,
-- | The original default flag assignment, used only for reporting.
pkgFlagDefaults :: Cabal.FlagAssignment,
-- | The exact dependencies (on other plan packages)
--
pkgDependencies :: ComponentDeps [ConfiguredId],
-- | Which optional stanzas (ie testsuites, benchmarks) can be built.
-- This means the solver produced a plan that has them available.
-- This doesn't necessary mean we build them by default.
pkgStanzasAvailable :: Set OptionalStanza,
-- | Which optional stanzas the user explicitly asked to enable or
-- to disable. This tells us which ones we build by default, and
-- helps with error messages when the user asks to build something
-- they explicitly disabled.
--
-- TODO: The 'Bool' here should be refined into an ADT with three
-- cases: NotRequested, ExplicitlyRequested and
-- ImplicitlyRequested. A stanza is explicitly requested if
-- the user asked, for this *specific* package, that the stanza
-- be enabled; it's implicitly requested if the user asked for
-- all global packages to have this stanza enabled. The
-- difference between an explicit and implicit request is
-- error reporting behavior: if a user asks for tests to be
-- enabled for a specific package that doesn't have any tests,
-- we should warn them about it, but we shouldn't complain
-- that a user enabled tests globally, and some local packages
-- just happen not to have any tests. (But perhaps we should
-- warn if ALL local packages don't have any tests.)
pkgStanzasRequested :: Map OptionalStanza Bool,
-- | Which optional stanzas (ie testsuites, benchmarks) will actually
-- be enabled during the package configure step.
pkgStanzasEnabled :: Set OptionalStanza,
-- | Where the package comes from, e.g. tarball, local dir etc. This
-- is not the same as where it may be unpacked to for the build.
pkgSourceLocation :: PackageLocation (Maybe FilePath),
-- | The hash of the source, e.g. the tarball. We don't have this for
-- local source dir packages.
pkgSourceHash :: Maybe PackageSourceHash,
--pkgSourceDir ? -- currently passed in later because they can use temp locations
--pkgBuildDir ? -- but could in principle still have it here, with optional instr to use temp loc
pkgBuildStyle :: BuildStyle,
pkgSetupPackageDBStack :: PackageDBStack,
pkgBuildPackageDBStack :: PackageDBStack,
pkgRegisterPackageDBStack :: PackageDBStack,
-- | The package contains a library and so must be registered
pkgRequiresRegistration :: Bool,
pkgDescriptionOverride :: Maybe CabalFileText,
pkgVanillaLib :: Bool,
pkgSharedLib :: Bool,
pkgDynExe :: Bool,
pkgGHCiLib :: Bool,
pkgProfLib :: Bool,
pkgProfExe :: Bool,
pkgProfLibDetail :: ProfDetailLevel,
pkgProfExeDetail :: ProfDetailLevel,
pkgCoverage :: Bool,
pkgOptimization :: OptimisationLevel,
pkgSplitObjs :: Bool,
pkgStripLibs :: Bool,
pkgStripExes :: Bool,
pkgDebugInfo :: DebugInfoLevel,
pkgProgramPaths :: Map String FilePath,
pkgProgramArgs :: Map String [String],
pkgProgramPathExtra :: [FilePath],
pkgConfigureScriptArgs :: [String],
pkgExtraLibDirs :: [FilePath],
pkgExtraFrameworkDirs :: [FilePath],
pkgExtraIncludeDirs :: [FilePath],
pkgProgPrefix :: Maybe PathTemplate,
pkgProgSuffix :: Maybe PathTemplate,
pkgInstallDirs :: InstallDirs.InstallDirs FilePath,
pkgHaddockHoogle :: Bool,
pkgHaddockHtml :: Bool,
pkgHaddockHtmlLocation :: Maybe String,
pkgHaddockExecutables :: Bool,
pkgHaddockTestSuites :: Bool,
pkgHaddockBenchmarks :: Bool,
pkgHaddockInternal :: Bool,
pkgHaddockCss :: Maybe FilePath,
pkgHaddockHscolour :: Bool,
pkgHaddockHscolourCss :: Maybe FilePath,
pkgHaddockContents :: Maybe PathTemplate,
-- Setup.hs related things:
-- | One of four modes for how we build and interact with the Setup.hs
-- script, based on whether it's a build-type Custom, with or without
-- explicit deps and the cabal spec version the .cabal file needs.
pkgSetupScriptStyle :: SetupScriptStyle,
-- | The version of the Cabal command line interface that we are using
-- for this package. This is typically the version of the Cabal lib
-- that the Setup.hs is built against.
pkgSetupScriptCliVersion :: Version,
-- Build time related:
pkgBuildTargets :: [ComponentTarget],
pkgReplTarget :: Maybe ComponentTarget,
pkgBuildHaddocks :: Bool
}
deriving (Eq, Show, Generic)
instance Binary ElaboratedConfiguredPackage
instance Package ElaboratedConfiguredPackage where
packageId = pkgSourceId
instance HasUnitId ElaboratedConfiguredPackage where
installedUnitId = pkgInstalledId
instance PackageFixedDeps ElaboratedConfiguredPackage where
depends = fmap (map installedPackageId) . pkgDependencies
-- | This is used in the install plan to indicate how the package will be
-- built.
--
data BuildStyle =
-- | The classic approach where the package is built, then the files
-- installed into some location and the result registered in a package db.
--
-- If the package came from a tarball then it's built in a temp dir and
-- the results discarded.
BuildAndInstall
-- | The package is built, but the files are not installed anywhere,
-- rather the build dir is kept and the package is registered inplace.
--
-- Such packages can still subsequently be installed.
--
-- Typically 'BuildAndInstall' packages will only depend on other
-- 'BuildAndInstall' style packages and not on 'BuildInplaceOnly' ones.
--
| BuildInplaceOnly
deriving (Eq, Show, Generic)
instance Binary BuildStyle
type CabalFileText = LBS.ByteString
type ElaboratedReadyPackage = GenericReadyPackage ElaboratedConfiguredPackage
--TODO: [code cleanup] this duplicates the InstalledPackageInfo quite a bit in an install plan
-- because the same ipkg is used by many packages. So the binary file will be big.
-- Could we keep just (ipkgid, deps) instead of the whole InstalledPackageInfo?
-- or transform to a shared form when serialising / deserialising
data GenericBuildResult ipkg iresult ifailure
= BuildFailure ifailure
| BuildSuccess [ipkg] iresult
deriving (Eq, Show, Generic)
instance (Binary ipkg, Binary iresult, Binary ifailure) =>
Binary (GenericBuildResult ipkg iresult ifailure)
type BuildResult = GenericBuildResult InstalledPackageInfo
BuildSuccess BuildFailure
data BuildSuccess = BuildOk DocsResult TestsResult
deriving (Eq, Show, Generic)
data DocsResult = DocsNotTried | DocsFailed | DocsOk
deriving (Eq, Show, Generic)
data TestsResult = TestsNotTried | TestsOk
deriving (Eq, Show, Generic)
data BuildFailure = PlanningFailed --TODO: [required eventually] not yet used
| DependentFailed PackageId
| DownloadFailed String --TODO: [required eventually] not yet used
| UnpackFailed String --TODO: [required eventually] not yet used
| ConfigureFailed String
| BuildFailed String
| TestsFailed String --TODO: [required eventually] not yet used
| InstallFailed String
deriving (Eq, Show, Typeable, Generic)
instance Exception BuildFailure
instance Binary BuildFailure
instance Binary BuildSuccess
instance Binary DocsResult
instance Binary TestsResult
---------------------------
-- Build targets
--
-- | The various targets within a package. This is more of a high level
-- specification than a elaborated prescription.
--
data PackageTarget =
-- | Build the default components in this package. This usually means
-- just the lib and exes, but it can also mean the testsuites and
-- benchmarks if the user explicitly requested them.
BuildDefaultComponents
-- | Build a specific component in this package.
| BuildSpecificComponent ComponentTarget
| ReplDefaultComponent
| ReplSpecificComponent ComponentTarget
| HaddockDefaultComponents
deriving (Eq, Show, Generic)
data ComponentTarget = ComponentTarget ComponentName SubComponentTarget
deriving (Eq, Show, Generic)
data SubComponentTarget = WholeComponent
| ModuleTarget ModuleName
| FileTarget FilePath
deriving (Eq, Show, Generic)
instance Binary PackageTarget
instance Binary ComponentTarget
instance Binary SubComponentTarget
---------------------------
-- Setup.hs script policy
--
-- | There are four major cases for Setup.hs handling:
--
-- 1. @build-type@ Custom with a @custom-setup@ section
-- 2. @build-type@ Custom without a @custom-setup@ section
-- 3. @build-type@ not Custom with @cabal-version > $our-cabal-version@
-- 4. @build-type@ not Custom with @cabal-version <= $our-cabal-version@
--
-- It's also worth noting that packages specifying @cabal-version: >= 1.23@
-- or later that have @build-type@ Custom will always have a @custom-setup@
-- section. Therefore in case 2, the specified @cabal-version@ will always be
-- less than 1.23.
--
-- In cases 1 and 2 we obviously have to build an external Setup.hs script,
-- while in case 4 we can use the internal library API. In case 3 we also have
-- to build an external Setup.hs script because the package needs a later
-- Cabal lib version than we can support internally.
--
data SetupScriptStyle = SetupCustomExplicitDeps
| SetupCustomImplicitDeps
| SetupNonCustomExternalLib
| SetupNonCustomInternalLib
deriving (Eq, Show, Generic)
instance Binary SetupScriptStyle
|
bennofs/cabal
|
cabal-install/Distribution/Client/ProjectPlanning/Types.hs
|
Haskell
|
bsd-3-clause
| 14,755
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TemplateHaskell #-}
-- Determine which packages are already installed
module Stack.Build.Installed
( InstalledMap
, Installed (..)
, GetInstalledOpts (..)
, getInstalled
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Catch (MonadCatch, MonadMask)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Resource
import Data.Conduit
import qualified Data.Conduit.List as CL
import Data.Function
import qualified Data.HashSet as HashSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path
import Prelude hiding (FilePath, writeFile)
import Stack.Build.Cache
import Stack.Types.Build
import Stack.Constants
import Stack.GhcPkg
import Stack.PackageDump
import Stack.Types
import Stack.Types.Internal
type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,HasEnvConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,MonadMask m,HasLogLevel env)
data LoadHelper = LoadHelper
{ lhId :: !GhcPkgId
, lhDeps :: ![GhcPkgId]
, lhPair :: !(PackageName, (Version, InstallLocation, Installed)) -- TODO Version is now redundant and can be gleaned from Installed
}
deriving Show
type InstalledMap = Map PackageName (Version, InstallLocation, Installed) -- TODO Version is now redundant and can be gleaned from Installed
-- | Options for 'getInstalled'.
data GetInstalledOpts = GetInstalledOpts
{ getInstalledProfiling :: !Bool
-- ^ Require profiling libraries?
, getInstalledHaddock :: !Bool
-- ^ Require haddocks?
}
-- | Returns the new InstalledMap and all of the locally registered packages.
getInstalled :: (M env m, PackageInstallInfo pii)
=> EnvOverride
-> GetInstalledOpts
-> Map PackageName pii -- ^ does not contain any installed information
-> m (InstalledMap, Set GhcPkgId)
getInstalled menv opts sourceMap = do
snapDBPath <- packageDatabaseDeps
localDBPath <- packageDatabaseLocal
bconfig <- asks getBuildConfig
mcache <-
if getInstalledProfiling opts || getInstalledHaddock opts
then liftM Just $ loadInstalledCache $ configInstalledCache bconfig
else return Nothing
let loadDatabase' = loadDatabase menv opts mcache sourceMap
(installedLibs', localInstalled) <-
loadDatabase' Nothing [] >>=
loadDatabase' (Just (Snap, snapDBPath)) . fst >>=
loadDatabase' (Just (Local, localDBPath)) . fst
let installedLibs = M.fromList $ map lhPair installedLibs'
case mcache of
Nothing -> return ()
Just pcache -> saveInstalledCache (configInstalledCache bconfig) pcache
-- Add in the executables that are installed, making sure to only trust a
-- listed installation under the right circumstances (see below)
let exesToSM loc = Map.unions . map (exeToSM loc)
exeToSM loc (PackageIdentifier name version) =
case Map.lookup name sourceMap of
-- Doesn't conflict with anything, so that's OK
Nothing -> m
Just pii
-- Not the version we want, ignore it
| version /= piiVersion pii || loc /= piiLocation pii -> Map.empty
| otherwise -> m
where
m = Map.singleton name (version, loc, Executable $ PackageIdentifier name version)
exesSnap <- getInstalledExes Snap
exesLocal <- getInstalledExes Local
let installedMap = Map.unions
[ exesToSM Local exesLocal
, exesToSM Snap exesSnap
, installedLibs
]
return (installedMap, localInstalled)
-- | Outputs both the modified InstalledMap and the Set of all installed packages in this database
--
-- The goal is to ascertain that the dependencies for a package are present,
-- that it has profiling if necessary, and that it matches the version and
-- location needed by the SourceMap
loadDatabase :: (M env m, PackageInstallInfo pii)
=> EnvOverride
-> GetInstalledOpts
-> Maybe InstalledCache -- ^ if Just, profiling or haddock is required
-> Map PackageName pii -- ^ to determine which installed things we should include
-> Maybe (InstallLocation, Path Abs Dir) -- ^ package database, Nothing for global
-> [LoadHelper] -- ^ from parent databases
-> m ([LoadHelper], Set GhcPkgId)
loadDatabase menv opts mcache sourceMap mdb lhs0 = do
(lhs1, gids) <- ghcPkgDump menv (fmap snd mdb)
$ conduitDumpPackage =$ sink
let lhs = pruneDeps
(packageIdentifierName . ghcPkgIdPackageIdentifier)
lhId
lhDeps
const
(lhs0 ++ lhs1)
return (map (\lh -> lh { lhDeps = [] }) $ Map.elems lhs, Set.fromList gids)
where
conduitProfilingCache =
case mcache of
Just cache | getInstalledProfiling opts -> addProfiling cache
-- Just an optimization to avoid calculating the profiling
-- values when they aren't necessary
_ -> CL.map (\dp -> dp { dpProfiling = False })
conduitHaddockCache =
case mcache of
Just cache | getInstalledHaddock opts -> addHaddock cache
-- Just an optimization to avoid calculating the haddock
-- values when they aren't necessary
_ -> CL.map (\dp -> dp { dpHaddock = False })
sinkDP = conduitProfilingCache
=$ conduitHaddockCache
=$ CL.mapMaybe (isAllowed opts mcache sourceMap (fmap fst mdb))
=$ CL.consume
sinkGIDs = CL.map dpGhcPkgId =$ CL.consume
sink = getZipSink $ (,)
<$> ZipSink sinkDP
<*> ZipSink sinkGIDs
-- | Check if a can be included in the set of installed packages or not, based
-- on the package selections made by the user. This does not perform any
-- dirtiness or flag change checks.
isAllowed :: PackageInstallInfo pii
=> GetInstalledOpts
-> Maybe InstalledCache
-> Map PackageName pii
-> Maybe InstallLocation
-> DumpPackage Bool Bool
-> Maybe LoadHelper
isAllowed opts mcache sourceMap mloc dp
-- Check that it can do profiling if necessary
| getInstalledProfiling opts && isJust mcache && not (dpProfiling dp) = Nothing
-- Check that it has haddocks if necessary
| getInstalledHaddock opts && isJust mcache && not (dpHaddock dp) = Nothing
| toInclude = Just LoadHelper
{ lhId = gid
, lhDeps =
-- We always want to consider the wired in packages as having all
-- of their dependencies installed, since we have no ability to
-- reinstall them. This is especially important for using different
-- minor versions of GHC, where the dependencies of wired-in
-- packages may change slightly and therefore not match the
-- snapshot.
if name `HashSet.member` wiredInPackages
then []
else dpDepends dp
, lhPair = (name, (version, fromMaybe Snap mloc, Library gid))
}
| otherwise = Nothing
where
toInclude =
case Map.lookup name sourceMap of
Nothing ->
case mloc of
-- The sourceMap has nothing to say about this global
-- package, so we can use it
Nothing -> True
-- For non-global packages, don't include unknown packages.
-- See:
-- https://github.com/commercialhaskell/stack/issues/292
Just _ -> False
Just pii ->
version == piiVersion pii -- only accept the desired version
&& checkLocation (piiLocation pii)
-- Ensure that the installed location matches where the sourceMap says it
-- should be installed
checkLocation Snap = mloc /= Just Local -- we can allow either global or snap
checkLocation Local = mloc == Just Local
gid = dpGhcPkgId dp
PackageIdentifier name version = ghcPkgIdPackageIdentifier gid
|
duplode/stack
|
src/Stack/Build/Installed.hs
|
Haskell
|
bsd-3-clause
| 8,898
|
main = drawingOf(thing(1) & thing(2))
thing(n) = if n > 1 rectangle(n, n) else circle(n)
|
venkat24/codeworld
|
codeworld-compiler/test/testcase/test_ifCondition/source.hs
|
Haskell
|
apache-2.0
| 89
|
-- | This module provides numerical routines for minimizing linear and nonlinear multidimensional functions.
-- Multidimensional optimization is significantly harder than one dimensional optimization.
-- In general, there are no black box routines that work well on every function,
-- even if the function has only a single local minimum.
--
-- FIXME: better documentation
module HLearn.Optimization.Multivariate
(
-- * Simple interface
-- * Advanced interface
-- ** Conjugate gradient descent
-- | A great introduction is:
-- "An introduction to the conjugate gradient method without the pain" by Jonathan Richard Shewchuk
--
-- NOTE: Does this paper has a mistake in the calculation of the optimal step size;
-- it should be multiplied by 1/2?
fminunc_cgd_
, Iterator_cgd
-- *** Conjugation methods
, ConjugateMethod
, steepestDescent
, fletcherReeves
, polakRibiere
, hestenesStiefel
-- ** Newton-Raphson (quadratic gradient descent)
, Iterator_nr
, fminunc_nr_
-- ** Quasi Newton methods
, Iterator_bfgs
, fminunc_bfgs_
-- ** Multivariate line search
, LineSearch
, mkLineSearch
, lineSearch_brent
, lineSearch_gss
-- *** Backtracking
-- | Backtracking is much faster than univariate line search methods.
-- It typically requires 1-3 function evaluations, whereas the univariate optimizations typically require 5-50.
-- The downside is that backtracking is not guaranteed to converge to the minimum along the line search.
-- In many cases, however, this is okay.
-- We make up for the lack of convergence by being able to run many more iterations of the multivariate optimization.
, Backtracking (..)
, backtracking
, wolfe
, amijo
, weakCurvature
, strongCurvature
-- * Test functions
-- | See <https://en.wikipedia.org/wiki/Test_functions_for_optimization wikipedia> for more detail.
--
-- FIXME: Include graphs in documentation.
--
-- FIXME: Implement the rest of the functions.
, sphere
, ackley
, beale
, rosenbrock
)
where
import SubHask
import SubHask.Algebra.Vector
import SubHask.Category.Trans.Derivative
import HLearn.History
import HLearn.Optimization.Univariate
-------------------------------------------------------------------------------
type MultivariateMinimizer (n::Nat) cxt opt v
= LineSearch cxt v
-> StopCondition (opt v)
-> v
-> Diff n v (Scalar v)
-> History cxt (opt v)
-------------------------------------------------------------------------------
-- generic transforms
-- FIXME: broken by new History
-- projectOrthant opt1 = do
-- mopt0 <- prevValueOfType opt1
-- return $ case mopt0 of
-- Nothing -> opt1
-- Just opt0 -> set x1 (VG.zipWith go (opt0^.x1) (opt1^.x1)) $ opt1
-- where
-- go a0 a1 = if (a1>=0 && a0>=0) || (a1<=0 && a0<=0)
-- then a1
-- else 0
-------------------------------------------------------------------------------
-- Conjugate gradient descent
data Iterator_cgd a = Iterator_cgd
{ _cgd_x1 :: !a
, _cgd_fx1 :: !(Scalar a)
, _cgd_f'x1 :: !a
, _cgd_alpha :: !(Scalar a)
, _cgd_f'x0 :: !a
, _cgd_s0 :: !a
, _cgd_f :: !(a -> Scalar a)
}
deriving (Typeable)
type instance Scalar (Iterator_cgd a) = Scalar a
type instance Logic (Iterator_cgd a) = Bool
instance (Eq (Scalar a), Eq a) => Eq_ (Iterator_cgd a) where
a1==a2
= (_cgd_x1 a1 == _cgd_x1 a2)
&& (_cgd_fx1 a1 == _cgd_fx1 a2)
&& (_cgd_f'x1 a1 == _cgd_f'x1 a2)
-- && (_cgd_alpha a1 == _cgd_alpha a2)
-- && (_cgd_f'x0 a1 == _cgd_f'x0 a2)
-- && (_cgd_s0 a1 == _cgd_s0 a2)
instance (Hilbert a, Show a, Show (Scalar a)) => Show (Iterator_cgd a) where
-- show cgd = "CGD; x="++show (_cgd_x1 cgd)++"; f'x="++show (_cgd_f'x1 cgd)++"; fx="++show (_cgd_fx1 cgd)
show cgd = "CGD; |f'x|="++show (size $ _cgd_f'x1 cgd)++"; fx="++show (_cgd_fx1 cgd)
instance Has_x1 Iterator_cgd v where x1 = _cgd_x1
instance Has_fx1 Iterator_cgd v where fx1 = _cgd_fx1
---------------------------------------
-- | method for determining the conjugate direction;
-- See <https://en.wikipedia.org/wiki/Nonlinear_conjugate_gradient wikipedia> for more details.
type ConjugateMethod v = Module v => v -> v -> v -> Scalar v
{-# INLINABLE steepestDescent #-}
steepestDescent :: ConjugateMethod v
steepestDescent _ _ _ = 0
{-# INLINABLE fletcherReeves #-}
fletcherReeves :: Hilbert v => ConjugateMethod v
fletcherReeves f'x1 f'x0 _ = f'x1 <> f'x1 / f'x0 <> f'x0
{-# INLINABLE polakRibiere #-}
polakRibiere :: Hilbert v => ConjugateMethod v
polakRibiere f'x1 f'x0 _ = (f'x1 <> (f'x1 - f'x0)) / (f'x0 <> f'x0)
{-# INLINABLE hestenesStiefel #-}
hestenesStiefel :: Hilbert v => ConjugateMethod v
hestenesStiefel f'x1 f'x0 s0 = -(f'x1 <> (f'x1 - f'x0)) / (s0 <> (f'x1 - f'x0))
----------------------------------------
-- | A generic method for conjugate gradient descent that gives you more control over the optimization parameters
{-# INLINEABLE fminunc_cgd_ #-}
fminunc_cgd_ ::
( Hilbert v
, ClassicalLogic v
) => ConjugateMethod v -> MultivariateMinimizer 1 cxt Iterator_cgd v
fminunc_cgd_ conj lineSearch stop x0 f = {-# SCC fminunc_cgd #-}
iterate (step_cgd lineSearch conj f) stop $ Iterator_cgd
{ _cgd_x1 = x0
, _cgd_fx1 = f $ x0
, _cgd_f'x1 = f' $ x0
, _cgd_alpha = 1e-2
, _cgd_f'x0 = 2 *. f' x0
, _cgd_s0 = f' x0
, _cgd_f = (f $)
}
where
f' = (derivative f $)
step_cgd ::
( Hilbert v
, ClassicalLogic v
) => LineSearch cxt v
-> ConjugateMethod v
-> C1 (v -> Scalar v)
-> Iterator_cgd v
-> History cxt (Iterator_cgd v)
step_cgd stepMethod conjMethod f (Iterator_cgd x1 fx1 f'x1 alpha1 f'x0 s0 _) = {-# SCC step_cgd #-} do
let f' = (derivative f $)
-- This test on beta ensures that conjugacy will be reset when it is lost.
-- The formula is taken from equation 1.174 of the book "Nonlinear Programming".
--
-- FIXME:
-- This test isn't needed in linear optimization, and the inner products are mildly expensive.
-- It also makes CGD work only in a Hilbert space.
-- Is the restriction worth it?
-- let beta = if abs (f'x1<>f'x0) > 0.2*(f'x0<>f'x0)
-- then 0
-- else max 0 $ conjMethod f'x1 f'x0 s0
let beta = conjMethod f'x1 f'x0 s0
let s1 = -f'x1 + beta *. s0
alpha <- stepMethod (f $) f' x1 s1 alpha1
let x = x1 + alpha *. s1
return $ Iterator_cgd
{ _cgd_x1 = x
, _cgd_fx1 = f $ x
, _cgd_f'x1 = f' $ x
, _cgd_alpha = alpha
, _cgd_f'x0 = f'x1
, _cgd_s0 = s1
, _cgd_f = (f $)
}
-------------------------------------------------------------------------------
-- The Newton-Raphson method (quadratic gradient descent)
data Iterator_nr v = Iterator_nr
{ _nr_x1 :: !v
, _nr_fx1 :: !(Scalar v)
, _nr_fx0 :: !(Scalar v)
, _nr_f'x1 :: !v
, _nr_alpha1 :: !(Scalar v)
}
deriving (Typeable)
instance Show (Iterator_nr v) where
show _ = "Iterator_nr"
type instance Scalar (Iterator_nr a) = Scalar a
instance Has_x1 Iterator_nr a where x1 = _nr_x1
instance Has_fx1 Iterator_nr a where fx1 = _nr_fx1
----------------------------------------
{-# INLINEABLE fminunc_nr_ #-}
fminunc_nr_ ::
( Hilbert v
, BoundedField (Scalar v)
) => MultivariateMinimizer 2 cxt Iterator_nr v
fminunc_nr_ _ stop x0 f = iterate (step_nr f) stop $ Iterator_nr
{ _nr_x1 = x0
, _nr_fx1 = f $ x0
, _nr_fx0 = infinity
, _nr_f'x1 = derivative f $ x0
, _nr_alpha1 = 1
}
step_nr :: forall v cxt.
( Hilbert v
, BoundedField (Scalar v)
) => C2 (v -> Scalar v)
-> Iterator_nr v
-> History cxt (Iterator_nr v)
step_nr f (Iterator_nr x0 fx0 _ f'x0 alpha0) = do
let f' = (derivative f $)
f'' = ((derivative . derivative $ f) $)
-- FIXME: We need regularization when the 2nd derivative is degenerate
let dir = reciprocal (f'' x0) `mXv` f'x0
-- FIXME: We should have the option to do line searches using any method
-- alpha <- do
-- let g :: v -> Scalar v
-- g y = f $ x0 + (y .* dir)
--
-- bracket <- LineMin.lineBracket g (alpha0/2) (alpha0*2)
-- brent <- LineMin.fminuncM_brent_ (return.g) bracket
-- ( maxIterations 100
-- -- + fx1grows
-- )
-- return $ LineMin._brent_x brent
let alpha=1
let x1 = x0 + alpha*.dir
return $ Iterator_nr
{ _nr_x1 = x1
, _nr_fx1 = f $ x1
, _nr_fx0 = fx0
, _nr_f'x1 = f' $ x1
, _nr_alpha1 = 1 -- alpha
}
-------------------------------------------------------------------------------
-- The BFGS quasi-newton method
-- | FIXME:
-- We currently build the full matrix, making things slower than they need to be.
-- Fixing this probably requires extending the linear algebra in subhask.
--
-- FIXME:
-- Also, the code converges much slower than I would expect for some reason.
data Iterator_bfgs v = Iterator_bfgs
{ _bfgs_x1 :: !v
, _bfgs_fx1 :: !(Scalar v)
, _bfgs_fx0 :: !(Scalar v)
, _bfgs_f'x1 :: !v
, _bfgs_f''x1 :: !((v><v))
, _bfgs_alpha1 :: !(Scalar v)
}
deriving (Typeable)
type instance Scalar (Iterator_bfgs v) = Scalar v
instance (Show v, Show (Scalar v)) => Show (Iterator_bfgs v) where
show i = "BFGS; x="++show (_bfgs_x1 i)++"; f'x="++show (_bfgs_f'x1 i)++"; fx="++show (_bfgs_fx1 i)
instance Has_x1 Iterator_bfgs a where x1 = _bfgs_x1
instance Has_fx1 Iterator_bfgs a where fx1 = _bfgs_fx1
{-# INLINEABLE fminunc_bfgs_ #-}
fminunc_bfgs_ ::
( Hilbert v
, BoundedField (Scalar v)
) => MultivariateMinimizer 1 cxt Iterator_bfgs v
fminunc_bfgs_ linesearch stop x0 f = iterate (step_bfgs f linesearch) stop $ Iterator_bfgs
{ _bfgs_x1 = x0
, _bfgs_fx1 = f $ x0
, _bfgs_fx0 = infinity
, _bfgs_f'x1 = derivative f $ x0
, _bfgs_f''x1 = 1
, _bfgs_alpha1 = 1e-10
}
step_bfgs :: forall v cxt.
( Hilbert v
, BoundedField (Scalar v)
) => C1 ( v -> Scalar v)
-> LineSearch cxt v
-> Iterator_bfgs v
-> History cxt (Iterator_bfgs v)
step_bfgs f linesearch opt = do
let f' = (derivative f $)
let x0 = _bfgs_x1 opt
fx0 = _bfgs_fx1 opt
f'x0 = _bfgs_f'x1 opt
f''x0 = _bfgs_f''x1 opt
alpha0 = _bfgs_alpha1 opt
let d = -f''x0 `mXv` f'x0
-- g alpha = f $ x0 + alpha *. d
-- g' alpha = f' $ x0 + alpha *. d
-- bracket <- lineBracket g (alpha0/2) (alpha0*2)
-- brent <- fminuncM_brent_ (return.g) bracket (maxIterations 200 || stop_brent 1e-6)
-- let alpha = x1 brent
alpha <- linesearch (f $) f' x0 f'x0 alpha0
let x1 = x0 - alpha *. d
f'x1 = f' x1
let p = x1 - x0
q = f'x1 - f'x0
let xsi = 1
tao = q <> (f''x0 `mXv` q)
v = p ./ (p<>q) - (f''x0 `mXv` q) ./ tao
f''x1 = f''x0
+ (p >< p) ./ (p<>q)
- (f''x0 * (q><q) * f''x0) ./ tao
+ (xsi*tao) *. (v><v)
-- let go a1 a0 = if (a1>=0 && a0 >=0) || (a1<=0&&a0<=0)
-- then a1
-- else a1
-- x1mod = VG.zipWith go x1 x0
let x1mod = x1
return $ Iterator_bfgs
{ _bfgs_x1 = x1mod
, _bfgs_fx1 = f $ x1mod
, _bfgs_fx0 = fx0
, _bfgs_f'x1 = f' $ x1mod
, _bfgs_f''x1 = f''x1
, _bfgs_alpha1 = alpha
}
-------------------------------------------------------------------------------
-- Line search
-- | Functions of this type determine how far to go in a particular direction.
-- These functions perform the same task as "UnivariateMinimizer",
-- but the arguments are explicitly multidimensional.
type LineSearch cxt v
= (v -> Scalar v) -- ^ f = function
-> (v -> v) -- ^ f' = derivative of the function
-> v -- ^ x0 = starting position
-> v -- ^ f'(x0) = direction
-> Scalar v -- ^ initial guess at distance to minimum
-> History cxt (Scalar v)
-- | Convert a "UnivariateMinimizer" into a "LineSearch".
{-# INLINEABLE mkLineSearch #-}
mkLineSearch ::
( Has_x1 opt (Scalar v)
, VectorSpace v
, OrdField (Scalar v)
, cxt (LineBracket (Scalar v))
, cxt (opt (Scalar v))
, cxt (Scalar (opt (Scalar v)))
) => proxy opt -- ^ required for type checking
-> UnivariateMinimizer cxt opt (Scalar v)
-> StopCondition (opt (Scalar v)) -- ^ controls the number of iterations
-> LineSearch cxt v
mkLineSearch _ fminuncM stops f _ x0 dir stepGuess = {-# SCC uni2multiLineSearch #-} do
let g y = f $ x0 + dir.*y
opt <- fminuncM stops stepGuess (return . g)
return $ x1 opt
-- | Brent's method promoted to work on a one dimension subspace.
{-# INLINEABLE lineSearch_brent #-}
lineSearch_brent ::
( VectorSpace v
, OrdField (Scalar v)
, cxt (LineBracket (Scalar v))
, cxt (Iterator_brent (Scalar v))
) => StopCondition (Iterator_brent (Scalar v))
-> LineSearch cxt v
lineSearch_brent stops = mkLineSearch (Proxy::Proxy Iterator_brent) fminuncM_brent stops
-- | Golden section search promoted to work on a one dimension subspace.
{-# INLINEABLE lineSearch_gss #-}
lineSearch_gss ::
( VectorSpace v
, OrdField (Scalar v)
, cxt (LineBracket (Scalar v))
, cxt (Iterator_gss (Scalar v))
) => StopCondition (Iterator_gss (Scalar v))
-> LineSearch cxt v
lineSearch_gss stops = mkLineSearch (Proxy::Proxy Iterator_gss) fminuncM_gss stops
-------------------------------------------------------------------------------
-- backtracking
data Backtracking v = Backtracking
{ _bt_x :: !(Scalar v)
, _bt_fx :: !(Scalar v)
, _bt_f'x :: !v
, _init_dir :: !v
, _init_f'x :: !v
, _init_fx :: !(Scalar v)
, _init_x :: !v
}
deriving (Typeable)
type instance Scalar (Backtracking v) = Scalar v
instance Show (Backtracking v) where
show _ = "Backtracking"
instance Has_fx1 Backtracking v where
fx1 = _bt_fx
-- | Backtracking linesearch is NOT guaranteed to converge.
-- It is frequently used as the linesearch for multidimensional problems.
-- In this case, the overall minimization problem can converge significantly
-- faster than if one of the safer methods is used.
{-# INLINABLE backtracking #-}
backtracking ::
( Hilbert v
, cxt (Backtracking v)
) => StopCondition (Backtracking v)
-> LineSearch cxt v
backtracking stop f f' x0 f'x0 stepGuess = {-# SCC backtracking #-} beginFunction "backtracking" $ do
let g y = f $ x0 + y *. f'x0
let grow=1.65
fmap _bt_x $ iterate (step_backtracking 0.85 f f') stop $ Backtracking
{ _bt_x = (grow*stepGuess)
, _bt_fx = g (grow*stepGuess)
, _bt_f'x = grow *. (f' $ x0 + grow*stepGuess *. f'x0)
, _init_dir = f'x0
, _init_x = x0
, _init_fx = f x0
, _init_f'x = f'x0
}
step_backtracking ::
( Module v
) => Scalar v
-> (v -> Scalar v)
-> (v -> v)
-> Backtracking v
-> History cxt (Backtracking v)
step_backtracking !tao !f !f' !bt = {-# SCC step_backtracking #-} do
let x1 = tao * _bt_x bt
return $ bt
{ _bt_x = x1
, _bt_fx = g x1
, _bt_f'x = g' x1
}
where
g alpha = f (_init_x bt + alpha *. _init_dir bt)
g' alpha = alpha *. f' (_init_x bt + alpha *. _init_dir bt)
---------------------------------------
-- stop conditions
{-# INLINABLE wolfe #-}
wolfe :: Hilbert v => Scalar v -> Scalar v -> StopCondition (Backtracking v)
wolfe !c1 !c2 !bt0 !bt1 = {-# SCC wolfe #-} do
a <- amijo c1 bt0 bt1
b <- strongCurvature c2 bt0 bt1
return $ a && b
{-# INLINABLE amijo #-}
amijo :: Hilbert v => Scalar v -> StopCondition (Backtracking v)
amijo !c1 _ !bt = {-# SCC amijo #-} return $
_bt_fx bt <= _init_fx bt + c1 * (_bt_x bt) * ((_init_f'x bt) <> (_init_dir bt))
{-# INLINABLE weakCurvature #-}
weakCurvature :: Hilbert v => Scalar v -> StopCondition (Backtracking v)
weakCurvature !c2 _ !bt = {-# SCC weakCurvature #-} return $
_init_dir bt <> _bt_f'x bt >= c2 * (_init_dir bt <> _init_f'x bt)
{-# INLINABLE strongCurvature #-}
strongCurvature :: Hilbert v => Scalar v -> StopCondition (Backtracking v)
strongCurvature !c2 _ !bt = {-# SCC strongCurvature #-} return $
abs (_init_dir bt <> _bt_f'x bt) <= c2 * abs (_init_dir bt <> _init_f'x bt)
--------------------------------------------------------------------------------
-- | The simplest quadratic function
{-# INLINEABLE sphere #-}
sphere :: Hilbert v => C1 (v -> Scalar v)
sphere = unsafeProveC1 f f' -- f''
where
f v = v<>v+3
f' v = 2*.v
-- f'' _ = 2
-- |
--
-- > ackley [0,0] == 0
--
-- ackley :: (IsScalar r, Field r) => SVector 2 r -> r
{-# INLINEABLE ackley #-}
ackley :: SVector 2 Double -> Double
ackley v = -20 * exp (-0.2 * sqrt $ 0.5 * (x*x + y*y)) - exp(0.5*cos(2*pi*x)+0.5*cos(2*pi*y)) + exp 1 + 20
where
x=v!0
y=v!1
-- |
--
-- > beale [3,0.5] = 0
{-# INLINEABLE beale #-}
beale :: SVector 2 Double -> Double
beale v = (1.5-x+x*y)**2 + (2.25-x+x*y*y)**2 + (2.625-x+x*y*y*y)**2
where
x=v!0
y=v!1
-- | The Rosenbrock function is hard to optimize because it has a narrow quadratically shaped valley.
--
-- See <https://en.wikipedia.org/wiki/Rosenbrock_function wikipedia> for more details.
--
-- FIXME:
-- The derivatives of this function are rather nasty.
-- We need to expand "SubHask.Category.Trans.Derivative" to handle these harder cases automatically.
{-# INLINEABLE rosenbrock #-}
rosenbrock :: (ValidElem v (Scalar v), ExpRing (Scalar v), FiniteModule v) => C1 (v -> Scalar v)
rosenbrock = unsafeProveC1 f f'
where
f v = sum [ 100*(v!(i+1) - (v!i)**2)**2 + (v!i - 1)**2 | i <- [0..dim v-2] ]
f' v = imap go v
where
go i x = if i==dim v-1
then pt2
else if i== 0
then pt1
else pt1+pt2
where
pt1 = 400*x*x*x - 400*xp1*x + 2*x -2
pt2 = 200*x - 200*xm1*xm1
xp1 = v!(i+1)
xm1 = v!(i-1)
|
arnabgho/HLearn
|
src/HLearn/Optimization/Multivariate.hs
|
Haskell
|
bsd-3-clause
| 18,644
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hu-HU">
<title>Front-End Scanner | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/frontendscanner/src/main/javahelp/org/zaproxy/zap/extension/frontendscanner/resources/help_hu_HU/helpset_hu_HU.hs
|
Haskell
|
apache-2.0
| 978
|
module SDL.Raw.Platform (
-- * Platform Detection
getPlatform
) where
import Control.Monad.IO.Class
import Foreign.C.String
foreign import ccall "SDL.h SDL_GetPlatform" getPlatformFFI :: IO CString
getPlatform :: MonadIO m => m CString
getPlatform = liftIO getPlatformFFI
{-# INLINE getPlatform #-}
|
dalaing/sdl2
|
src/SDL/Raw/Platform.hs
|
Haskell
|
bsd-3-clause
| 306
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
#if __GLASGOW_HASKELL__ >= 707
{-# LANGUAGE RoleAnnotations #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Internal.Magma
-- Copyright : (C) 2012-2015 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
----------------------------------------------------------------------------
module Control.Lens.Internal.Magma
(
-- * Magma
Magma(..)
, runMagma
-- * Molten
, Molten(..)
-- * Mafic
, Mafic(..)
, runMafic
-- * TakingWhile
, TakingWhile(..)
, runTakingWhile
) where
import Control.Applicative
import Control.Category
import Control.Comonad
import Control.Lens.Internal.Bazaar
import Control.Lens.Internal.Context
import Control.Lens.Internal.Indexed
import Data.Foldable
import Data.Functor.Apply
import Data.Functor.Contravariant
import Data.Monoid
import Data.Profunctor.Rep
import Data.Profunctor.Sieve
import Data.Profunctor.Unsafe
import Data.Traversable
import Prelude hiding ((.),id)
------------------------------------------------------------------------------
-- Magma
------------------------------------------------------------------------------
-- | This provides a way to peek at the internal structure of a
-- 'Control.Lens.Traversal.Traversal' or 'Control.Lens.Traversal.IndexedTraversal'
data Magma i t b a where
MagmaAp :: Magma i (x -> y) b a -> Magma i x b a -> Magma i y b a
MagmaPure :: x -> Magma i x b a
MagmaFmap :: (x -> y) -> Magma i x b a -> Magma i y b a
Magma :: i -> a -> Magma i b b a
#if __GLASGOW_HASKELL__ >= 707
-- note the 3rd argument infers as phantom, but that would be unsound
type role Magma representational nominal nominal nominal
#endif
instance Functor (Magma i t b) where
fmap f (MagmaAp x y) = MagmaAp (fmap f x) (fmap f y)
fmap _ (MagmaPure x) = MagmaPure x
fmap f (MagmaFmap xy x) = MagmaFmap xy (fmap f x)
fmap f (Magma i a) = Magma i (f a)
instance Foldable (Magma i t b) where
foldMap f (MagmaAp x y) = foldMap f x `mappend` foldMap f y
foldMap _ MagmaPure{} = mempty
foldMap f (MagmaFmap _ x) = foldMap f x
foldMap f (Magma _ a) = f a
instance Traversable (Magma i t b) where
traverse f (MagmaAp x y) = MagmaAp <$> traverse f x <*> traverse f y
traverse _ (MagmaPure x) = pure (MagmaPure x)
traverse f (MagmaFmap xy x) = MagmaFmap xy <$> traverse f x
traverse f (Magma i a) = Magma i <$> f a
instance (Show i, Show a) => Show (Magma i t b a) where
showsPrec d (MagmaAp x y) = showParen (d > 4) $
showsPrec 4 x . showString " <*> " . showsPrec 5 y
showsPrec d (MagmaPure _) = showParen (d > 10) $
showString "pure .."
showsPrec d (MagmaFmap _ x) = showParen (d > 4) $
showString ".. <$> " . showsPrec 5 x
showsPrec d (Magma i a) = showParen (d > 10) $
showString "Magma " . showsPrec 11 i . showChar ' ' . showsPrec 11 a
-- | Run a 'Magma' where all the individual leaves have been converted to the
-- expected type
runMagma :: Magma i t a a -> t
runMagma (MagmaAp l r) = runMagma l (runMagma r)
runMagma (MagmaFmap f r) = f (runMagma r)
runMagma (MagmaPure x) = x
runMagma (Magma _ a) = a
------------------------------------------------------------------------------
-- Molten
------------------------------------------------------------------------------
-- | This is a a non-reassociating initially encoded version of 'Bazaar'.
newtype Molten i a b t = Molten { runMolten :: Magma i t b a }
instance Functor (Molten i a b) where
fmap f (Molten xs) = Molten (MagmaFmap f xs)
{-# INLINE fmap #-}
instance Apply (Molten i a b) where
(<.>) = (<*>)
{-# INLINE (<.>) #-}
instance Applicative (Molten i a b) where
pure = Molten #. MagmaPure
{-# INLINE pure #-}
Molten xs <*> Molten ys = Molten (MagmaAp xs ys)
{-# INLINE (<*>) #-}
instance Sellable (Indexed i) (Molten i) where
sell = Indexed (\i -> Molten #. Magma i)
{-# INLINE sell #-}
instance Bizarre (Indexed i) (Molten i) where
bazaar f (Molten (MagmaAp x y)) = bazaar f (Molten x) <*> bazaar f (Molten y)
bazaar f (Molten (MagmaFmap g x)) = g <$> bazaar f (Molten x)
bazaar _ (Molten (MagmaPure x)) = pure x
bazaar f (Molten (Magma i a)) = indexed f i a
instance IndexedFunctor (Molten i) where
ifmap f (Molten xs) = Molten (MagmaFmap f xs)
{-# INLINE ifmap #-}
instance IndexedComonad (Molten i) where
iextract (Molten (MagmaAp x y)) = iextract (Molten x) (iextract (Molten y))
iextract (Molten (MagmaFmap f y)) = f (iextract (Molten y))
iextract (Molten (MagmaPure x)) = x
iextract (Molten (Magma _ a)) = a
iduplicate (Molten (Magma i a)) = Molten #. Magma i <$> Molten (Magma i a)
iduplicate (Molten (MagmaPure x)) = pure (pure x)
iduplicate (Molten (MagmaFmap f y)) = iextend (fmap f) (Molten y)
iduplicate (Molten (MagmaAp x y)) = iextend (<*>) (Molten x) <*> iduplicate (Molten y)
iextend k (Molten (Magma i a)) = (k .# Molten) . Magma i <$> Molten (Magma i a)
iextend k (Molten (MagmaPure x)) = pure (k (pure x))
iextend k (Molten (MagmaFmap f y)) = iextend (k . fmap f) (Molten y)
iextend k (Molten (MagmaAp x y)) = iextend (\x' y' -> k $ x' <*> y') (Molten x) <*> iduplicate (Molten y)
instance a ~ b => Comonad (Molten i a b) where
extract = iextract
{-# INLINE extract #-}
extend = iextend
{-# INLINE extend #-}
duplicate = iduplicate
{-# INLINE duplicate #-}
------------------------------------------------------------------------------
-- Mafic
------------------------------------------------------------------------------
-- | This is used to generate an indexed magma from an unindexed source
--
-- By constructing it this way we avoid infinite reassociations in sums where possible.
data Mafic a b t = Mafic Int (Int -> Magma Int t b a)
-- | Generate a 'Magma' using from a prefix sum.
runMafic :: Mafic a b t -> Magma Int t b a
runMafic (Mafic _ k) = k 0
instance Functor (Mafic a b) where
fmap f (Mafic w k) = Mafic w (MagmaFmap f . k)
{-# INLINE fmap #-}
instance Apply (Mafic a b) where
Mafic wf mf <.> ~(Mafic wa ma) = Mafic (wf + wa) $ \o -> MagmaAp (mf o) (ma (o + wf))
{-# INLINE (<.>) #-}
instance Applicative (Mafic a b) where
pure a = Mafic 0 $ \_ -> MagmaPure a
{-# INLINE pure #-}
Mafic wf mf <*> ~(Mafic wa ma) = Mafic (wf + wa) $ \o -> MagmaAp (mf o) (ma (o + wf))
{-# INLINE (<*>) #-}
instance Sellable (->) Mafic where
sell a = Mafic 1 $ \ i -> Magma i a
{-# INLINE sell #-}
instance Bizarre (Indexed Int) Mafic where
bazaar (pafb :: Indexed Int a (f b)) (Mafic _ k) = go (k 0) where
go :: Magma Int t b a -> f t
go (MagmaAp x y) = go x <*> go y
go (MagmaFmap f x) = f <$> go x
go (MagmaPure x) = pure x
go (Magma i a) = indexed pafb (i :: Int) a
{-# INLINE bazaar #-}
instance IndexedFunctor Mafic where
ifmap f (Mafic w k) = Mafic w (MagmaFmap f . k)
{-# INLINE ifmap #-}
------------------------------------------------------------------------------
-- TakingWhile
------------------------------------------------------------------------------
-- | This is used to generate an indexed magma from an unindexed source
--
-- By constructing it this way we avoid infinite reassociations where possible.
--
-- In @'TakingWhile' p g a b t@, @g@ has a @nominal@ role to avoid exposing an illegal _|_ via 'Contravariant',
-- while the remaining arguments are degraded to a @nominal@ role by the invariants of 'Magma'
data TakingWhile p (g :: * -> *) a b t = TakingWhile Bool t (Bool -> Magma () t b (Corep p a))
#if __GLASGOW_HASKELL__ >= 707
type role TakingWhile nominal nominal nominal nominal nominal
#endif
-- | Generate a 'Magma' with leaves only while the predicate holds from left to right.
runTakingWhile :: TakingWhile p f a b t -> Magma () t b (Corep p a)
runTakingWhile (TakingWhile _ _ k) = k True
instance Functor (TakingWhile p f a b) where
fmap f (TakingWhile w t k) = let ft = f t in TakingWhile w ft $ \b -> if b then MagmaFmap f (k b) else MagmaPure ft
{-# INLINE fmap #-}
instance Apply (TakingWhile p f a b) where
TakingWhile wf tf mf <.> ~(TakingWhile wa ta ma) = TakingWhile (wf && wa) (tf ta) $ \o ->
if o then MagmaAp (mf True) (ma wf) else MagmaPure (tf ta)
{-# INLINE (<.>) #-}
instance Applicative (TakingWhile p f a b) where
pure a = TakingWhile True a $ \_ -> MagmaPure a
{-# INLINE pure #-}
TakingWhile wf tf mf <*> ~(TakingWhile wa ta ma) = TakingWhile (wf && wa) (tf ta) $ \o ->
if o then MagmaAp (mf True) (ma wf) else MagmaPure (tf ta)
{-# INLINE (<*>) #-}
instance Corepresentable p => Bizarre p (TakingWhile p g) where
bazaar (pafb :: p a (f b)) ~(TakingWhile _ _ k) = go (k True) where
go :: Magma () t b (Corep p a) -> f t
go (MagmaAp x y) = go x <*> go y
go (MagmaFmap f x) = f <$> go x
go (MagmaPure x) = pure x
go (Magma _ wa) = cosieve pafb wa
{-# INLINE bazaar #-}
-- This constraint is unused intentionally, it protects TakingWhile
instance Contravariant f => Contravariant (TakingWhile p f a b) where
contramap _ = (<$) (error "contramap: TakingWhile")
{-# INLINE contramap #-}
instance IndexedFunctor (TakingWhile p f) where
ifmap = fmap
{-# INLINE ifmap #-}
|
rpglover64/lens
|
src/Control/Lens/Internal/Magma.hs
|
Haskell
|
bsd-3-clause
| 9,589
|
{-# LANGUAGE UnboxedSums #-}
module UbxSumLevPoly where
-- this failed thinking that (# Any | True #) :: TYPE (SumRep [LiftedRep, b])
-- But of course that b should be Lifted!
-- It was due to silliness in TysWiredIn using the same uniques for different
-- things in mk_sum.
p = True
where (# _x | #) = (# | True #)
|
ezyang/ghc
|
testsuite/tests/unboxedsums/UbxSumLevPoly.hs
|
Haskell
|
bsd-3-clause
| 322
|
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances, TypeFamilies, GeneralizedNewtypeDeriving #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module T4809_IdentityT
( evalIdentityT
, IdentityT(..)
, XML(..)
) where
import Control.Applicative (Applicative, Alternative)
import Control.Monad (MonadPlus)
import Control.Monad.Trans (MonadTrans(lift), MonadIO(liftIO))
import T4809_XMLGenerator (XMLGenT(..), EmbedAsChild(..), Name)
import qualified T4809_XMLGenerator as HSX
data XML
= Element Name [Int] [XML] | CDATA Bool String
deriving Show
-- * IdentityT Monad Transformer
newtype IdentityT m a = IdentityT { runIdentityT :: m a }
deriving (Functor, Applicative, Alternative, Monad, MonadIO, MonadPlus)
instance MonadTrans IdentityT where
lift = IdentityT
evalIdentityT :: (Functor m, Monad m) => XMLGenT (IdentityT m) XML -> m XML
evalIdentityT = runIdentityT . HSX.unXMLGenT
-- * HSX.XMLGenerator for IdentityT
instance (Functor m, Monad m) => HSX.XMLGen (IdentityT m) where
type XML (IdentityT m) = XML
newtype Child (IdentityT m) = IChild { unIChild :: XML }
genElement n _attrs children = HSX.XMLGenT $
do children' <- HSX.unXMLGenT (fmap (map unIChild . concat) (sequence children))
return (Element n [] children')
instance (Monad m, MonadIO m, Functor m) => EmbedAsChild (IdentityT m) String where
asChild s =
do liftIO $ putStrLn "EmbedAsChild (IdentityT m) String"
XMLGenT . return . (:[]) . IChild . CDATA True $ s
|
philderbeast/ghcjs
|
test/ghc/typecheck/T4809_IdentityT.hs
|
Haskell
|
mit
| 1,601
|
module Vectorise.Generic.PADict
( buildPADict
) where
import Vectorise.Monad
import Vectorise.Builtins
import Vectorise.Generic.Description
import Vectorise.Generic.PAMethods ( buildPAScAndMethods )
import Vectorise.Utils
import BasicTypes
import CoreSyn
import CoreUtils
import CoreUnfold
import Module
import TyCon
import CoAxiom
import Type
import Id
import Var
import Name
import FastString
-- |Build the PA dictionary function for some type and hoist it to top level.
--
-- The PA dictionary holds fns that convert values to and from their vectorised representations.
--
-- @Recall the definition:
-- class PR (PRepr a) => PA a where
-- toPRepr :: a -> PRepr a
-- fromPRepr :: PRepr a -> a
-- toArrPRepr :: PData a -> PData (PRepr a)
-- fromArrPRepr :: PData (PRepr a) -> PData a
-- toArrPReprs :: PDatas a -> PDatas (PRepr a)
-- fromArrPReprs :: PDatas (PRepr a) -> PDatas a
--
-- Example:
-- df :: forall a. PR (PRepr a) -> PA a -> PA (T a)
-- df = /\a. \(c:PR (PRepr a)) (d:PA a). MkPA c ($PR_df a d) ($toPRepr a d) ...
-- $dPR_df :: forall a. PA a -> PR (PRepr (T a))
-- $dPR_df = ....
-- $toRepr :: forall a. PA a -> T a -> PRepr (T a)
-- $toPRepr = ...
-- The "..." stuff is filled in by buildPAScAndMethods
-- @
--
buildPADict
:: TyCon -- ^ tycon of the type being vectorised.
-> CoAxiom Unbranched
-- ^ Coercion between the type and
-- its vectorised representation.
-> TyCon -- ^ PData instance tycon
-> TyCon -- ^ PDatas instance tycon
-> SumRepr -- ^ representation used for the type being vectorised.
-> VM Var -- ^ name of the top-level dictionary function.
buildPADict vect_tc prepr_ax pdata_tc pdatas_tc repr
= polyAbstract tvs $ \args -> -- The args are the dictionaries we lambda abstract over; and they
-- are put in the envt, so when we need a (PA a) we can find it in
-- the envt; they don't include the silent superclass args yet
do { mod <- liftDs getModule
; let dfun_name = mkLocalisedOccName mod mkPADFunOcc vect_tc_name
-- The superclass dictionary is a (silent) argument if the tycon is polymorphic...
; let mk_super_ty = do { r <- mkPReprType inst_ty
; pr_cls <- builtin prClass
; return $ mkClassPred pr_cls [r]
}
; super_tys <- sequence [mk_super_ty | not (null tvs)]
; super_args <- mapM (newLocalVar (fsLit "pr")) super_tys
; let val_args = super_args ++ args
all_args = tvs ++ val_args
-- ...it is constant otherwise
; super_consts <- sequence [prDictOfPReprInstTyCon inst_ty prepr_ax [] | null tvs]
-- Get ids for each of the methods in the dictionary, including superclass
; paMethodBuilders <- buildPAScAndMethods
; method_ids <- mapM (method val_args dfun_name) paMethodBuilders
-- Expression to build the dictionary.
; pa_dc <- builtin paDataCon
; let dict = mkLams all_args (mkConApp pa_dc con_args)
con_args = Type inst_ty
: map Var super_args -- the superclass dictionary is either
++ super_consts -- lambda-bound or constant
++ map (method_call val_args) method_ids
-- Build the type of the dictionary function.
; pa_cls <- builtin paClass
; let dfun_ty = mkForAllTys tvs
$ mkFunTys (map varType val_args)
(mkClassPred pa_cls [inst_ty])
-- Set the unfolding for the inliner.
; raw_dfun <- newExportedVar dfun_name dfun_ty
; let dfun_unf = mkDFunUnfolding all_args pa_dc con_args
dfun = raw_dfun `setIdUnfolding` dfun_unf
`setInlinePragma` dfunInlinePragma
-- Add the new binding to the top-level environment.
; hoistBinding dfun dict
; return dfun
}
where
tvs = tyConTyVars vect_tc
arg_tys = mkTyVarTys tvs
inst_ty = mkTyConApp vect_tc arg_tys
vect_tc_name = getName vect_tc
method args dfun_name (name, build)
= localV
$ do expr <- build vect_tc prepr_ax pdata_tc pdatas_tc repr
let body = mkLams (tvs ++ args) expr
raw_var <- newExportedVar (method_name dfun_name name) (exprType body)
let var = raw_var
`setIdUnfolding` mkInlineUnfolding (Just (length args)) body
`setInlinePragma` alwaysInlinePragma
hoistBinding var body
return var
method_call args id = mkApps (Var id) (map Type arg_tys ++ map Var args)
method_name dfun_name name = mkVarOcc $ occNameString dfun_name ++ ('$' : name)
|
urbanslug/ghc
|
compiler/vectorise/Vectorise/Generic/PADict.hs
|
Haskell
|
bsd-3-clause
| 4,973
|
{-# LANGUAGE Arrows #-}
{-# OPTIONS -fno-warn-redundant-constraints #-}
-- Test for Trac #1662
module Arrow where
import Control.Arrow
expr' :: Arrow a => a Int Int
expr' = error "urk"
term :: Arrow a => a () Int
term = error "urk"
expr1 :: Arrow a => a () Int
expr1 = proc () -> do
x <- term -< ()
expr' -< x
expr2 :: Arrow a => a () Int
expr2 = proc y -> do
x <- term -< y
expr' -< x
|
urbanslug/ghc
|
testsuite/tests/arrows/should_compile/arrowpat.hs
|
Haskell
|
bsd-3-clause
| 433
|
-- | This is a library which colourises Haskell code.
-- It currently has six output formats:
--
-- * ANSI terminal codes
--
-- * LaTeX macros
--
-- * HTML 3.2 with font tags
--
-- * HTML 4.01 with external CSS.
--
-- * XHTML 1.0 with internal CSS.
--
-- * mIRC chat client colour codes.
--
module Language.Haskell.HsColour (Output(..), ColourPrefs(..),
hscolour) where
import Language.Haskell.HsColour.Colourise (ColourPrefs(..))
import qualified Language.Haskell.HsColour.TTY as TTY
import qualified Language.Haskell.HsColour.HTML as HTML
import qualified Language.Haskell.HsColour.CSS as CSS
import qualified Language.Haskell.HsColour.ACSS as ACSS
import qualified Language.Haskell.HsColour.InlineCSS as ICSS
import qualified Language.Haskell.HsColour.LaTeX as LaTeX
import qualified Language.Haskell.HsColour.MIRC as MIRC
import Data.List(mapAccumL, isPrefixOf)
import Data.Maybe
import Language.Haskell.HsColour.Output
--import Debug.Trace
-- | Colourise Haskell source code with the given output format.
hscolour :: Output -- ^ Output format.
-> ColourPrefs -- ^ Colour preferences (for formats that support them).
-> Bool -- ^ Whether to include anchors.
-> Bool -- ^ Whether output document is partial or complete.
-> String -- ^ Title for output.
-> Bool -- ^ Whether input document is literate haskell or not
-> String -- ^ Haskell source code.
-> String -- ^ Coloured Haskell source code.
hscolour output pref anchor partial title False =
(if partial then id else top'n'tail output title) .
hscolour' output pref anchor
hscolour output pref anchor partial title True =
(if partial then id else top'n'tail output title) .
concatMap chunk . joinL . classify . inlines
where
chunk (Code c) = hscolour' output pref anchor c
chunk (Lit c) = c
-- | The actual colourising worker, despatched on the chosen output format.
hscolour' :: Output -- ^ Output format.
-> ColourPrefs -- ^ Colour preferences (for formats that support them)
-> Bool -- ^ Whether to include anchors.
-> String -- ^ Haskell source code.
-> String -- ^ Coloured Haskell source code.
hscolour' TTY pref _ = TTY.hscolour pref
hscolour' (TTYg tt) pref _ = TTY.hscolourG tt pref
hscolour' MIRC pref _ = MIRC.hscolour pref
hscolour' LaTeX pref _ = LaTeX.hscolour pref
hscolour' HTML pref anchor = HTML.hscolour pref anchor
hscolour' CSS _ anchor = CSS.hscolour anchor
hscolour' ICSS pref anchor = ICSS.hscolour pref anchor
hscolour' ACSS _ anchor = ACSS.hscolour anchor
-- | Choose the right headers\/footers, depending on the output format.
top'n'tail :: Output -- ^ Output format
-> String -- ^ Title for output
-> (String->String) -- ^ Output transformer
top'n'tail TTY _ = id
top'n'tail (TTYg _) _ = id
top'n'tail MIRC _ = id
top'n'tail LaTeX title = LaTeX.top'n'tail title
top'n'tail HTML title = HTML.top'n'tail title
top'n'tail CSS title = CSS.top'n'tail title
top'n'tail ICSS title = ICSS.top'n'tail title
top'n'tail ACSS title = CSS.top'n'tail title
-- | Separating literate files into code\/comment chunks.
data Lit = Code {unL :: String} | Lit {unL :: String} deriving (Show)
-- Re-implementation of 'lines', for better efficiency (but decreased laziness).
-- Also, importantly, accepts non-standard DOS and Mac line ending characters.
-- And retains the trailing '\n' character in each resultant string.
inlines :: String -> [String]
inlines s = lines' s id
where
lines' [] acc = [acc []]
lines' ('\^M':'\n':s) acc = acc ['\n'] : lines' s id -- DOS
--lines' ('\^M':s) acc = acc ['\n'] : lines' s id -- MacOS
lines' ('\n':s) acc = acc ['\n'] : lines' s id -- Unix
lines' (c:s) acc = lines' s (acc . (c:))
-- | The code for classify is largely stolen from Language.Preprocessor.Unlit.
classify :: [String] -> [Lit]
classify [] = []
classify (x:xs) | "\\begin{code}"`isPrefixOf`x
= Lit x: allProg xs
where allProg [] = [] -- Should give an error message,
-- but I have no good position information.
allProg (x:xs) | "\\end{code}"`isPrefixOf`x
= Lit x: classify xs
allProg (x:xs) = Code x: allProg xs
classify (('>':x):xs) = Code ('>':x) : classify xs
classify (x:xs) = Lit x: classify xs
-- | Join up chunks of code\/comment that are next to each other.
joinL :: [Lit] -> [Lit]
joinL [] = []
joinL (Code c:Code c2:xs) = joinL (Code (c++c2):xs)
joinL (Lit c :Lit c2 :xs) = joinL (Lit (c++c2):xs)
joinL (any:xs) = any: joinL xs
|
kyoungrok0517/linguist
|
samples/Haskell/HsColour.hs
|
Haskell
|
mit
| 4,949
|
-- Hugs failed this test Jan06
module Mod172 where
import Mod172_B (f,g)
|
urbanslug/ghc
|
testsuite/tests/module/mod172.hs
|
Haskell
|
bsd-3-clause
| 75
|
module Ghci025C (f, g, h) where
import Ghci025D
g x = f x + 1
h x = x `div` 2
data C = C {x :: Int}
|
urbanslug/ghc
|
testsuite/tests/ghci/scripts/Ghci025C.hs
|
Haskell
|
bsd-3-clause
| 104
|
#!/usr/bin/env stack
-- stack --install-ghc runghc --package turtle
{-# LANGUAGE OverloadedStrings #-}
import Turtle
main = stdout $ input "README.md"
|
JoshuaGross/haskell-learning-log
|
Code/turtle/input.hs
|
Haskell
|
mit
| 164
|
-----------------------------------------------------------------------------
-- |
-- Module : TestQueue
-- Copyright : (c) Phil Hargett 2014
-- License : MIT (see LICENSE file)
--
-- Maintainer : phil@haphazardhouse.net
-- Stability : experimental
-- Portability : non-portable (requires STM)
--
-- (..... module description .....)
--
-----------------------------------------------------------------------------
module TestQueue (
tests
) where
-- local imports
import qualified Distributed.Data.Queue as Q
import Distributed.Data.Container
import TestHelpers
-- external imports
import Control.Consensus.Raft
import Data.Serialize
import Network.Endpoints
import Network.Transport.Memory
import Prelude hiding (log)
import Test.Framework
import Test.HUnit
import Test.Framework.Providers.HUnit
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
tests :: IO [Test.Framework.Test]
tests = return [
testCase "queue-1server" $ test1Server,
testCase "queue-3server" $ test3Servers
-- testCase "queue-3server" $ troubleshoot $ test3Servers
]
test1Server :: Assertion
test1Server = timeBound (2 * 1000 * 1000) $ do
let name = servers !! 0
cfg = newTestConfiguration [name]
withTransport newMemoryTransport $ \transport ->
withEndpoint transport name $ \endpoint -> do
withQueueServer endpoint cfg name $ \vQueue -> causally $ do
checkSize "Empty queue should have size 0" 0 vQueue
Q.enqueue (0 :: Int) vQueue
checkSize "Queue size should be 1" 1 vQueue
Q.enqueue 1 vQueue
checkSize "Queue size should be 2" 2 vQueue
Q.enqueue 2 vQueue
checkSize "Queue size should be 3" 3 vQueue
value1 <- Q.dequeue vQueue
checkSize "Queue size should again be 2" 2 vQueue
liftIO $ assertEqual "Initial value should be 0" 0 value1
value2 <- Q.dequeue vQueue
checkSize "Queue size should again be 1" 1 vQueue
liftIO $ assertEqual "Second value should be 1" 1 value2
value3 <- Q.dequeue vQueue
checkSize "Queue size should again be 0" 0 vQueue
liftIO $ assertEqual "Third value should be 2" 2 value3
test3Servers :: Assertion
test3Servers = with3QueueServers $ \vQueues -> timeBound (30 * 1000000) $
causally $ do
let [vQueue1,vQueue2,vQueue3] = vQueues
checkSize "Empty queue should have size 0" 0 vQueue1
Q.enqueue (0 :: Int) vQueue1
checkSize "Queue size should be 1" 1 vQueue1
Q.enqueue 1 vQueue1
checkSize "Queue size should be 2" 2 vQueue3
Q.enqueue 2 vQueue2
checkSize "Queue size should be 3" 3 vQueue2
value1 <- Q.dequeue vQueue1
checkSize "Queue size should again be 2" 2 vQueue2
liftIO $ assertEqual "Initial value should be 0" 0 value1
value2 <- Q.dequeue vQueue3
checkSize "Queue size should again be 1" 1 vQueue2
liftIO $ assertEqual "Second value should be 1" 1 value2
value3 <- Q.dequeue vQueue1
checkSize "Queue size should again be 0" 0 vQueue2
liftIO $ assertEqual "Third value should be 2" 2 value3
--------------------------------------------------------------------------------
-- Helpers
--------------------------------------------------------------------------------
withQueueServer :: (Serialize v) => Endpoint -> RaftConfiguration -> Name -> (Q.Queue v -> IO ()) -> IO ()
withQueueServer endpoint cfg name fn = do
initialLog <- Q.mkQueueLog
initialState <- Q.empty name
Q.withQueue endpoint cfg name initialLog initialState fn
with3QueueServers :: (Serialize v) => ([Q.Queue v ] -> IO ()) -> IO ()
with3QueueServers fn = do
let names = take 3 servers
[name1,name2,name3] = names
cfg = newTestConfiguration names
withTransport newMemoryTransport $ \transport ->
withEndpoint transport name1 $ \endpoint1 -> do
withQueueServer endpoint1 cfg name1 $ \vQueue1 -> do
withEndpoint transport name2 $ \endpoint2 -> do
withQueueServer endpoint2 cfg name2 $ \vQueue2 -> do
withEndpoint transport name3 $ \endpoint3 -> do
withQueueServer endpoint3 cfg name3 $ \vQueue3 -> do
fn [vQueue1,vQueue2,vQueue3]
checkSize :: (Serialize v) => String -> Int -> Q.Queue v -> Causal ()
checkSize msg esz q = do
sz <- Q.size q
liftIO $ assertEqual msg esz sz
|
hargettp/distributed-containers
|
test/TestQueue.hs
|
Haskell
|
mit
| 4,727
|
module ListyInstances where
import Data.Monoid
import Listy
instance Monoid (Listy a) where
mempty = Listy []
mappend (Listy l) (Listy l') = Listy $ mappend l l'
|
diminishedprime/.org
|
reading-list/haskell_programming_from_first_principles/orphan-instance/ListyInstances.hs
|
Haskell
|
mit
| 167
|
import Data.List
import Data.List.Extra
import Data.Maybe
import qualified Data.Map as Map
parseLine :: String -> [Int]
parseLine s =
let [name, _, _, speed, "km/s", _, endurance, "seconds,",
_, _, _, _, _, rest, "seconds."] = words s
in
concat $ repeat $ replicate (read endurance) (read speed) ++ replicate (read rest) 0
allDistances :: [String] -> [[Int]]
allDistances = map parseLine
totalDistance :: [Int] -> [Int]
totalDistance = tail . scanl (+) 0
leadingDistance :: [[Int]] -> [Int]
leadingDistance = map maximum . transpose
currentScore :: [Int] -> [Int] -> [Int]
currentScore =
zipWith (\lead x -> if lead == x then 1 else 0)
time = 2503
furthest :: [[Int]] -> Int
furthest speeds = maximum $ map (sum . take time) scores
where leader = leadingDistance totals
totals = map totalDistance speeds
scores = map (currentScore leader) totals
solve :: String -> Int
solve = furthest . allDistances . lines
answer f = interact $ (++"\n") . show . f
main = answer solve
|
msullivan/advent-of-code
|
2015/A14b.hs
|
Haskell
|
mit
| 1,018
|
module Problem8 ( removeDuplicates ) where
removeDuplicates :: (Eq a) => [a] -> [a]
removeDuplicates [] = []
removeDuplicates [x] = [x]
removeDuplicates (x:xs) = if x == head xs then removeDuplicates xs else x : removeDuplicates xs
|
chanind/haskell-99-problems
|
Problem8.hs
|
Haskell
|
mit
| 232
|
lastPart :: Int -> [a] -> [a]
lastPart _ [] = []
lastPart _ [x] = [x]
lastPart x l@(h:t) | x > 0 = lastPart nx t
| otherwise = l
where nx = x - 1
firstPart :: Int -> [a] -> [a]
firstPart _ [] = []
firstPart _ [x] = [x]
firstPart x l@(h:t) | x > 0 = h:(firstPart nx t)
| otherwise = []
where nx = x - 1
{- Rotate a list N places to the left. -}
rotateList :: Int -> [a] -> [a]
rotateList _ [] = []
rotateList 0 l = l
rotateList x l | x > 0 = lastPart x l ++ firstPart x l
| otherwise = lastPart nx l ++ firstPart nx l
where nx = length l - abs x
|
andrewaguiar/s99-haskell
|
p19.hs
|
Haskell
|
mit
| 660
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( getApplicationDev
, appMain
, develMain
, makeFoundation
-- * for DevelMain
, getApplicationRepl
, shutdownApp
-- * for GHCI
, handler
, db
) where
import Control.Monad.Logger (liftLoc, runLoggingT)
import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr,
pgPoolSize, runSqlPool)
import Import
import Language.Haskell.TH.Syntax (qLocation)
import Network.Wai.Handler.Warp (Settings, defaultSettings,
defaultShouldDisplayException,
runSettings, setHost,
setOnException, setPort, getPort)
import Network.Wai.Middleware.RequestLogger (Destination (Logger),
IPAddrSource (..),
OutputFormat (..), destination,
mkRequestLogger, outputFormat)
import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet,
toLogStr)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Common
import Handler.Home
import Handler.Readable
import Handler.Record
import Handler.Entry
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- | This function allocates resources (such as a database connection pool),
-- performs initialization and return a foundation datatype value. This is also
-- the place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeFoundation :: AppSettings -> IO App
makeFoundation appSettings = do
-- Some basic initializations: HTTP connection manager, logger, and static
-- subsite.
appHttpManager <- newManager
appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger
appStatic <-
(if appMutableStatic appSettings then staticDevel else static)
(appStaticDir appSettings)
-- We need a log function to create a connection pool. We need a connection
-- pool to create our foundation. And we need our foundation to get a
-- logging function. To get out of this loop, we initially create a
-- temporary foundation without a real connection pool, get a log function
-- from there, and then create the real foundation.
let mkFoundation appConnPool = App {..}
tempFoundation = mkFoundation $ error "connPool forced in tempFoundation"
logFunc = messageLoggerSource tempFoundation appLogger
-- Create the database connection pool
pool <- flip runLoggingT logFunc $ createPostgresqlPool
(pgConnStr $ appDatabaseConf appSettings)
(pgPoolSize $ appDatabaseConf appSettings)
-- Perform database migration using our application's logging settings.
runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc
-- Return the foundation
return $ mkFoundation pool
-- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and
-- applyng some additional middlewares.
makeApplication :: App -> IO Application
makeApplication foundation = do
logWare <- mkRequestLogger def
{ outputFormat =
if appDetailedRequestLogging $ appSettings foundation
then Detailed True
else Apache
(if appIpFromHeader $ appSettings foundation
then FromFallback
else FromSocket)
, destination = Logger $ loggerSet $ appLogger foundation
}
-- Create the WAI application and apply middlewares
appPlain <- toWaiAppPlain foundation
return $ logWare $ defaultMiddlewaresNoLogging appPlain
-- | Warp settings for the given foundation value.
warpSettings :: App -> Settings
warpSettings foundation =
setPort (appPort $ appSettings foundation)
$ setHost (appHost $ appSettings foundation)
$ setOnException (\_req e ->
when (defaultShouldDisplayException e) $ messageLoggerSource
foundation
(appLogger foundation)
$(qLocation >>= liftLoc)
"yesod"
LevelError
(toLogStr $ "Exception from Warp: " ++ show e))
defaultSettings
-- | For yesod devel, return the Warp settings and WAI Application.
getApplicationDev :: IO (Settings, Application)
getApplicationDev = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app <- makeApplication foundation
return (wsettings, app)
getAppSettings :: IO AppSettings
getAppSettings = loadAppSettings [configSettingsYml] [] useEnv
-- | main function for use by yesod devel
develMain :: IO ()
develMain = develMainHelper getApplicationDev
-- | The @main@ function for an executable running this site.
appMain :: IO ()
appMain = do
-- Get the settings from all relevant sources
settings <- loadAppSettingsArgs
-- fall back to compile-time values, set to [] to require values at runtime
[configSettingsYmlValue]
-- allow environment variables to override
useEnv
-- Generate the foundation from the settings
foundation <- makeFoundation settings
-- Generate a WAI Application from the foundation
app <- makeApplication foundation
-- Run the application with Warp
runSettings (warpSettings foundation) app
--------------------------------------------------------------
-- Functions for DevelMain.hs (a way to run the app from GHCi)
--------------------------------------------------------------
getApplicationRepl :: IO (Int, App, Application)
getApplicationRepl = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app1 <- makeApplication foundation
return (getPort wsettings, foundation, app1)
shutdownApp :: App -> IO ()
shutdownApp _ = return ()
---------------------------------------------
-- Functions for use in development with GHCi
---------------------------------------------
-- | Run a handler
handler :: Handler a -> IO a
handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h
-- | Run DB queries
db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a
db = handler . runDB
|
darthdeus/reedink
|
Application.hs
|
Haskell
|
mit
| 6,680
|
{-# LANGUAGE TypeFamilies, ScopedTypeVariables #-}
import Data.Acid
import Data.Acid.Centered
import Control.Monad (when)
import Control.Concurrent (threadDelay)
import System.Exit (exitSuccess, exitFailure)
import System.Directory (doesDirectoryExist, removeDirectoryRecursive)
import Control.Exception (catch, SomeException)
-- state structures
import IntCommon
-- helpers
delaySec :: Int -> IO ()
delaySec n = threadDelay $ n*1000*1000
cleanup :: FilePath -> IO ()
cleanup path = do
sp <- doesDirectoryExist path
when sp $ removeDirectoryRecursive path
-- actual test
slave :: IO ()
slave = do
acid <- enslaveStateFrom "state/SyncTimeout/s1" "localhost" 3333 (IntState 0)
delaySec 11 -- SyncTimeout happens at 10 seconds
closeAcidState acid
main :: IO ()
main = do
cleanup "state/SyncTimeout"
catch slave $ \(e :: SomeException) ->
if show e == "Data.Acid.Centered.Slave: Took too long to sync. Timeout."
then exitSuccess
else exitFailure
|
sdx23/acid-state-dist
|
test/SyncTimeout.hs
|
Haskell
|
mit
| 1,014
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
module Init (
(@/=), (@==), (==@)
, assertNotEqual
, assertNotEmpty
, assertEmpty
, isTravis
, BackendMonad
, runConn
, MonadIO
, persistSettings
, MkPersistSettings (..)
#ifdef WITH_NOSQL
, dbName
, db'
, setup
, mkPersistSettings
, Action
, Context
#else
, db
, sqlite_database
#endif
, BackendKey(..)
, generateKey
-- re-exports
, module Database.Persist
, module Test.Hspec
, module Test.HUnit
, liftIO
, mkPersist, mkMigrate, share, sqlSettings, persistLowerCase, persistUpperCase
, Int32, Int64
, Text
, module Control.Monad.Trans.Reader
, module Control.Monad
#ifndef WITH_NOSQL
, module Database.Persist.Sql
#else
, PersistFieldSql(..)
#endif
) where
-- re-exports
import Control.Monad.Trans.Reader
import Test.Hspec
import Database.Persist.TH (mkPersist, mkMigrate, share, sqlSettings, persistLowerCase, persistUpperCase, MkPersistSettings(..))
-- testing
import Test.HUnit ((@?=),(@=?), Assertion, assertFailure, assertBool)
import Test.QuickCheck
import Database.Persist
import Database.Persist.TH ()
import Data.Text (Text, unpack)
import System.Environment (getEnvironment)
import qualified Data.ByteString as BS
#ifdef WITH_NOSQL
import Language.Haskell.TH.Syntax (Type(..))
import Database.Persist.TH (mkPersistSettings)
import Database.Persist.Sql (PersistFieldSql(..))
import Control.Monad (void, replicateM, liftM)
# ifdef WITH_MONGODB
import qualified Database.MongoDB as MongoDB
import Database.Persist.MongoDB (Action, withMongoPool, runMongoDBPool, defaultMongoConf, applyDockerEnv, BackendKey(..))
# endif
# ifdef WITH_ZOOKEEPER
import qualified Database.Zookeeper as Z
import Database.Persist.Zookeeper (Action, withZookeeperPool, runZookeeperPool, ZookeeperConf(..), defaultZookeeperConf, BackendKey(..), deleteRecursive)
import Data.IORef (newIORef, IORef, writeIORef, readIORef)
import System.IO.Unsafe (unsafePerformIO)
import qualified Data.Text as T
# endif
#else
import Control.Monad (liftM)
import Database.Persist.Sql
import Control.Monad.Trans.Resource (ResourceT, runResourceT)
import Control.Monad.Logger
import System.Log.FastLogger (fromLogStr)
# ifdef WITH_POSTGRESQL
import Control.Applicative ((<$>))
import Database.Persist.Postgresql
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
# else
# ifndef WITH_MYSQL
import Database.Persist.Sqlite
# endif
# endif
# ifdef WITH_MYSQL
import Database.Persist.MySQL
# endif
import Data.IORef (newIORef, IORef, writeIORef, readIORef)
import System.IO.Unsafe (unsafePerformIO)
#endif
import Control.Monad (unless, (>=>))
import Control.Monad.Trans.Control (MonadBaseControl)
-- Data types
import Data.Int (Int32, Int64)
import Control.Monad.IO.Class
#ifdef WITH_MONGODB
setup :: Action IO ()
setup = setupMongo
type Context = MongoDB.MongoContext
#endif
#ifdef WITH_ZOOKEEPER
setup :: Action IO ()
setup = setupZookeeper
type Context = Z.Zookeeper
#endif
(@/=), (@==), (==@) :: (Eq a, Show a, MonadIO m) => a -> a -> m ()
infix 1 @/= --, /=@
actual @/= expected = liftIO $ assertNotEqual "" expected actual
infix 1 @==, ==@
expected @== actual = liftIO $ expected @?= actual
expected ==@ actual = liftIO $ expected @=? actual
{-
expected /=@ actual = liftIO $ assertNotEqual "" expected actual
-}
assertNotEqual :: (Eq a, Show a) => String -> a -> a -> Assertion
assertNotEqual preface expected actual =
unless (actual /= expected) (assertFailure msg)
where msg = (if null preface then "" else preface ++ "\n") ++
"expected: " ++ show expected ++ "\n to not equal: " ++ show actual
assertEmpty :: (Monad m, MonadIO m) => [a] -> m ()
assertEmpty xs = liftIO $ assertBool "" (null xs)
assertNotEmpty :: (Monad m, MonadIO m) => [a] -> m ()
assertNotEmpty xs = liftIO $ assertBool "" (not (null xs))
isTravis :: IO Bool
isTravis = do
env <- liftIO getEnvironment
return $ case lookup "TRAVIS" env of
Just "true" -> True
_ -> False
#ifdef WITH_POSTGRESQL
dockerPg :: IO (Maybe BS.ByteString)
dockerPg = do
env <- liftIO getEnvironment
return $ case lookup "POSTGRES_NAME" env of
Just _name -> Just "postgres" -- /persistent/postgres
_ -> Nothing
#endif
#ifdef WITH_NOSQL
persistSettings :: MkPersistSettings
persistSettings = (mkPersistSettings $ ConT ''Context) { mpsGeneric = True }
dbName :: Text
dbName = "persistent"
type BackendMonad = Context
#ifdef WITH_MONGODB
runConn :: (MonadIO m, MonadBaseControl IO m) => Action m backend -> m ()
runConn f = do
conf <- liftIO $ applyDockerEnv $ defaultMongoConf dbName -- { mgRsPrimary = Just "replicaset" }
void $ withMongoPool conf $ runMongoDBPool MongoDB.master f
setupMongo :: Action IO ()
setupMongo = void $ MongoDB.dropDatabase dbName
#endif
#ifdef WITH_ZOOKEEPER
runConn :: (MonadIO m, MonadBaseControl IO m) => Action m backend -> m ()
runConn f = do
let conf = defaultZookeeperConf {zCoord = "localhost:2181/" ++ T.unpack dbName}
void $ withZookeeperPool conf $ runZookeeperPool f
setupZookeeper :: Action IO ()
setupZookeeper = do
liftIO $ Z.setDebugLevel Z.ZLogError
deleteRecursive "/"
#endif
db' :: Action IO () -> Action IO () -> Assertion
db' actions cleanDB = do
r <- runConn (actions >> cleanDB)
return r
instance Arbitrary PersistValue where
arbitrary = PersistObjectId `fmap` BS.pack `fmap` replicateM 12 arbitrary
#else
persistSettings :: MkPersistSettings
persistSettings = sqlSettings { mpsGeneric = True }
type BackendMonad = SqlBackend
sqlite_database :: Text
sqlite_database = "test/testdb.sqlite3"
-- sqlite_database = ":memory:"
runConn :: (MonadIO m, MonadBaseControl IO m) => SqlPersistT (LoggingT m) t -> m ()
#ifdef DEBUG
runConn f = flip runLoggingT (\_ _ _ s -> print $ fromLogStr s) $ do
#else
runConn f = flip runLoggingT (\_ _ _ s -> return ()) $ do
#endif
# ifdef WITH_POSTGRESQL
travis <- liftIO isTravis
_ <- if travis
then withPostgresqlPool "host=localhost port=5432 user=postgres dbname=persistent" 1 $ runSqlPool f
else do
host <- fromMaybe "localhost" <$> liftIO dockerPg
withPostgresqlPool ("host=" <> host <> " port=5432 user=postgres dbname=test") 1 $ runSqlPool f
# else
# ifdef WITH_MYSQL
travis <- liftIO isTravis
_ <- if not travis
then withMySQLPool defaultConnectInfo
{ connectHost = "localhost"
, connectUser = "test"
, connectPassword = "test"
, connectDatabase = "test"
} 1 $ runSqlPool f
else withMySQLPool defaultConnectInfo
{ connectHost = "localhost"
, connectUser = "travis"
, connectPassword = ""
, connectDatabase = "persistent"
} 1 $ runSqlPool f
# else
_<-withSqlitePool sqlite_database 1 $ runSqlPool f
# endif
# endif
return ()
db :: SqlPersistT (LoggingT (ResourceT IO)) () -> Assertion
db actions = do
runResourceT $ runConn $ actions >> transactionUndo
#if !MIN_VERSION_random(1,0,1)
instance Random Int32 where
random g =
let ((i::Int), g') = random g in
(fromInteger $ toInteger i, g')
randomR (lo, hi) g =
let ((i::Int), g') = randomR (fromInteger $ toInteger lo, fromInteger $ toInteger hi) g in
(fromInteger $ toInteger i, g')
instance Random Int64 where
random g =
let ((i0::Int32), g0) = random g
((i1::Int32), g1) = random g0 in
(fromInteger (toInteger i0) + fromInteger (toInteger i1) * 2 ^ (32::Int), g1)
randomR (lo, hi) g = -- TODO : generate on the whole range, and not only on a part of it
let ((i::Int), g') = randomR (fromInteger $ toInteger lo, fromInteger $ toInteger hi) g in
(fromInteger $ toInteger i, g')
#endif
instance Arbitrary PersistValue where
arbitrary = PersistInt64 `fmap` choose (0, maxBound)
#endif
instance PersistStore backend => Arbitrary (BackendKey backend) where
arbitrary = (errorLeft . fromPersistValue) `fmap` arbitrary
where
errorLeft x = case x of
Left e -> error $ unpack e
Right r -> r
#ifdef WITH_NOSQL
#ifdef WITH_MONGODB
generateKey :: IO (BackendKey Context)
generateKey = MongoKey `liftM` MongoDB.genObjectId
#endif
#ifdef WITH_ZOOKEEPER
keyCounter :: IORef Int64
keyCounter = unsafePerformIO $ newIORef 1
{-# NOINLINE keyCounter #-}
generateKey :: IO (BackendKey Context)
generateKey = do
i <- readIORef keyCounter
writeIORef keyCounter (i + 1)
return $ ZooKey $ T.pack $ show i
#endif
#else
keyCounter :: IORef Int64
keyCounter = unsafePerformIO $ newIORef 1
{-# NOINLINE keyCounter #-}
generateKey :: IO (BackendKey SqlBackend)
generateKey = do
i <- readIORef keyCounter
writeIORef keyCounter (i + 1)
return $ SqlBackendKey $ i
#endif
|
greydot/persistent
|
persistent-test/Init.hs
|
Haskell
|
mit
| 9,069
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
import Hate
import Hate.Graphics
import Vec2Lens (x,y)
import Control.Applicative
import Control.Lens
import System.Random
-- sample 4
data Sehe = Sehe {
_pos :: Vec2,
_vel :: Vec2
}
makeLenses ''Sehe
data SampleState = SampleState {
_seheSprite :: Sprite,
_sehes :: [Sehe]
}
makeLenses ''SampleState
generateSehes :: IO [Sehe]
generateSehes = replicateM 100 generateSehe
generateSehe :: IO Sehe
generateSehe = do
px <- getStdRandom $ randomR (0,300)
py <- getStdRandom $ randomR (0,300)
vx <- getStdRandom $ randomR (-5, 5)
vy <- getStdRandom $ randomR (-5, 5)
return $ Sehe (Vec2 px py) (Vec2 vx vy)
sampleLoad :: LoadFn SampleState
sampleLoad = SampleState <$> loadSprite "samples/image.png"
<*> generateSehes
sampleDraw :: DrawFn SampleState
sampleDraw s = map (\(Sehe p v) -> translate p $ sprite TopLeft (s ^. seheSprite)) $ s ^. sehes
moveSehe :: Sehe -> Sehe
moveSehe = updatePos . updateVel
where
updateVel :: Sehe -> Sehe
updateVel s = s & (if bounceX then vel . x %~ negate else id)
& (if bounceY then vel . y %~ negate else id)
where
bounceX = outOfBounds (s ^. pos . x) (0, 1024 - 128)
bounceY = outOfBounds (s ^. pos . y) (0, 786 - 128)
outOfBounds v (lo, hi) = v < lo || v > hi
updatePos :: Sehe -> Sehe
updatePos (Sehe p v) = Sehe (p + v) v
sampleUpdate :: UpdateFn SampleState
sampleUpdate _ = sehes . traverse %= moveSehe
config :: Config
config =
Config
{ windowTitle = "Sample - Sprite"
, windowSize = (1024, 768)
}
main :: IO ()
main = runApp config sampleLoad sampleUpdate sampleDraw
|
maque/Hate
|
samples/sample_sprite.hs
|
Haskell
|
mit
| 1,876
|
import System.Environment
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
| bmi <= 18.5 = "You're underweight, you emo, you!"
| bmi <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!"
| bmi <= 30.0 = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
where bmi = weight / height ^ 2
main = do
[weight,height] <- getArgs
putStrLn (bmiTell (read weight :: Float) (read height :: Float))
|
dmitrinesterenko/haskell_io_examples
|
bmiCalc.hs
|
Haskell
|
mit
| 503
|
-- Write a function that takes a list and returns the same list in reverse
module Main (reverseList) where
aux [] acc = acc
aux (h:t) acc = aux t (h:acc)
reverseList xs = aux xs []
|
ryanplusplus/seven-languages-in-seven-weeks
|
haskell/day1/reverse_list.hs
|
Haskell
|
mit
| 189
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html
module Stratosphere.ResourceProperties.ElasticLoadBalancingLoadBalancerPolicies where
import Stratosphere.ResourceImports
-- | Full data type definition for ElasticLoadBalancingLoadBalancerPolicies.
-- See 'elasticLoadBalancingLoadBalancerPolicies' for a more convenient
-- constructor.
data ElasticLoadBalancingLoadBalancerPolicies =
ElasticLoadBalancingLoadBalancerPolicies
{ _elasticLoadBalancingLoadBalancerPoliciesAttributes :: [Object]
, _elasticLoadBalancingLoadBalancerPoliciesInstancePorts :: Maybe (ValList Text)
, _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts :: Maybe (ValList Text)
, _elasticLoadBalancingLoadBalancerPoliciesPolicyName :: Val Text
, _elasticLoadBalancingLoadBalancerPoliciesPolicyType :: Val Text
} deriving (Show, Eq)
instance ToJSON ElasticLoadBalancingLoadBalancerPolicies where
toJSON ElasticLoadBalancingLoadBalancerPolicies{..} =
object $
catMaybes
[ (Just . ("Attributes",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesAttributes
, fmap (("InstancePorts",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesInstancePorts
, fmap (("LoadBalancerPorts",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts
, (Just . ("PolicyName",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesPolicyName
, (Just . ("PolicyType",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesPolicyType
]
-- | Constructor for 'ElasticLoadBalancingLoadBalancerPolicies' containing
-- required fields as arguments.
elasticLoadBalancingLoadBalancerPolicies
:: [Object] -- ^ 'elblbpAttributes'
-> Val Text -- ^ 'elblbpPolicyName'
-> Val Text -- ^ 'elblbpPolicyType'
-> ElasticLoadBalancingLoadBalancerPolicies
elasticLoadBalancingLoadBalancerPolicies attributesarg policyNamearg policyTypearg =
ElasticLoadBalancingLoadBalancerPolicies
{ _elasticLoadBalancingLoadBalancerPoliciesAttributes = attributesarg
, _elasticLoadBalancingLoadBalancerPoliciesInstancePorts = Nothing
, _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts = Nothing
, _elasticLoadBalancingLoadBalancerPoliciesPolicyName = policyNamearg
, _elasticLoadBalancingLoadBalancerPoliciesPolicyType = policyTypearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-attributes
elblbpAttributes :: Lens' ElasticLoadBalancingLoadBalancerPolicies [Object]
elblbpAttributes = lens _elasticLoadBalancingLoadBalancerPoliciesAttributes (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesAttributes = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-instanceports
elblbpInstancePorts :: Lens' ElasticLoadBalancingLoadBalancerPolicies (Maybe (ValList Text))
elblbpInstancePorts = lens _elasticLoadBalancingLoadBalancerPoliciesInstancePorts (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesInstancePorts = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-loadbalancerports
elblbpLoadBalancerPorts :: Lens' ElasticLoadBalancingLoadBalancerPolicies (Maybe (ValList Text))
elblbpLoadBalancerPorts = lens _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-policyname
elblbpPolicyName :: Lens' ElasticLoadBalancingLoadBalancerPolicies (Val Text)
elblbpPolicyName = lens _elasticLoadBalancingLoadBalancerPoliciesPolicyName (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesPolicyName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-policytype
elblbpPolicyType :: Lens' ElasticLoadBalancingLoadBalancerPolicies (Val Text)
elblbpPolicyType = lens _elasticLoadBalancingLoadBalancerPoliciesPolicyType (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesPolicyType = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/ElasticLoadBalancingLoadBalancerPolicies.hs
|
Haskell
|
mit
| 4,306
|
module Book ( Book, load, compile ) where
import Control.Applicative
import Control.Arrow
import Control.Dangerous hiding ( Exit, Warning, execute )
import Control.Monad
import Control.Monad.Trans
import Data.List
import Data.Focus
import Data.Maybe
import Data.Scope
import System.FilePath
import System.FilePath.Utils
import Text.Printf
import Target hiding ( load )
import qualified Path
import qualified Target
import qualified Target.Config as Config
import qualified Section
import Options
data Book = Book
{ _title :: String
, _scope :: Scope
, _root :: Section.Section
, _build :: FilePath
, _targets :: [Target] }
-- | Loading
load :: Options -> DangerousT IO Book
load opts = do
-- Canonicalize the root, in case we have a weird relative path
start <- liftIO $ canonicalizeHere $ optRoot opts
-- Detect the top if they are currently within the book
let dirs = map ($ opts) [optSourceDir, optTargetDir, optBuildDir]
top <- if optDetect opts
then liftIO (start `ancestorWith` dirs) >>=
maybe (throw $ CantDetect start dirs) return
else return start
-- Ensure that the other directories exist
let ensure dir err = let path = top </> dir opts in do
there <- liftIO $ exists path
unless there $ throw (err path)
return path
srcDir <- ensure optSourceDir NoSource
buildDir <- ensure optBuildDir NoBuild
targetDir <- ensure optTargetDir NoTarget
-- Load the data
let title = Path.title $ takeFileName top
let scope = getScope start srcDir opts
root <- liftIO $ Section.load srcDir "" scope
-- Load the targets
conf <- Config.setValue "book-title" title <$> Config.load targetDir
let conf' = if optDebug opts then Config.setDebug conf else conf
-- Filter the targets included by '-t' options
let inTargets path = case optTargets opts of
[] -> True
xs -> (dropExtension . takeFileName) path `elem` xs
let included path = not (Config.isSpecial path) && inTargets path
paths <- filter included <$> liftIO (ls targetDir)
targets <- mapM (Target.load conf') paths
-- Build the book
return Book{ _title = title
, _scope = scope
, _root = root
, _build = buildDir
, _targets = targets }
getScope :: FilePath -> FilePath -> Options -> Scope
getScope start src opts | optDetect opts = use $ let
path = start `from` src
path' = if path == start then "" else path
parts = splitPath path'
locations = mapMaybe fromString parts
location = foldr focus unfocused locations
in if null path' then unfocused else location
| otherwise = use unfocused
where use = fromTuple . (get optStart &&& get optEnd)
get = flip fromMaybe . ($ opts)
-- | Writing
compile :: Book -> IO ()
compile book = mapM_ (execute book) (_targets book) where
execute :: Book -> Target -> IO ()
execute book target = do
let d = dest book target
let t = text book target
putStrLn $ statusMsg d target
when (debug target) $ writeTemp d t target
write d t target
text :: Book -> Target -> String
text book target = Section.flatten (_title book) (_root book)
(render target) (expand target)
dest :: Book -> Target -> FilePath
dest book target = let
title = _title book
scope = _scope book
suffix = strRange scope
name = fromMaybe title (theme target)
in _build book </> name ++ suffix <.> ext target
strRange :: Scope -> String
strRange scope | isEverywhere scope = ""
strRange scope = intercalate "-" [lo, hi] where
(lo, hi) = both (intercalate "_" . map show . toList) (toTuple scope)
both f = f *** f
statusMsg :: FilePath -> Target -> String
statusMsg path target = printf "%s [%s]" path (show target)
-- | Errors
data Error = NoSource FilePath
| NoTarget FilePath
| NoBuild FilePath
| CantDetect FilePath [FilePath]
instance Show Error where
show (NoSource path) = printf "source directory '%s' not found\n" path
show (NoTarget path) = printf "target directory '%s' not found\n" path
show (NoBuild path) = printf "build directory '%s' not found\n" path
show (CantDetect path dirs) = "can't detect book root.\n" ++
printf "\tSearched from: %s\n" path ++
printf "\tLooked for directories: %s\n" (intercalate ", " dirs)
|
Soares/Bookbuilder
|
src/Book.hs
|
Haskell
|
mit
| 4,473
|
{-# Language ParallelListComp #-}
{-# Language ViewPatterns #-}
{-# Language RecordWildCards #-}
{-# Language ScopedTypeVariables #-}
module Symmetry.IL.Model.HaskellSpec where
import Data.Generics
import Data.Foldable as Fold
import Data.List
import Data.Maybe
import Language.Haskell.Exts.Pretty
import Language.Haskell.Exts.Syntax hiding (Stmt)
import Language.Haskell.Exts.SrcLoc
import Language.Haskell.Exts.Build
import Language.Fixpoint.Types as F
import Text.Printf
import qualified Symmetry.IL.AST as IL hiding (Op(..))
import Symmetry.IL.AST (ident, isAbs, Stmt(..), Pid(..), Set(..), Var(..), Config(..))
import Symmetry.IL.ConfigInfo
import Symmetry.IL.Model
import Symmetry.IL.Model.HaskellDefs
instance Symbolic Name where
symbol (Ident x) = symbol x
pp :: Pretty a => a -> String
pp = prettyPrint
eRange :: F.Expr -> F.Expr -> F.Expr -> F.Expr
eRange v elow ehigh
= pAnd [PAtom Le elow v, PAtom Lt v ehigh]
eRangeI :: F.Expr -> F.Expr -> F.Expr -> F.Expr
eRangeI v elow ehigh
= pAnd [PAtom Le elow v, PAtom Le v ehigh]
eEq :: F.Expr -> F.Expr -> F.Expr
eEq e1 e2 = PAtom Eq e1 e2
eLe :: F.Expr -> F.Expr -> F.Expr
eLe e1 e2 = PAtom Le e1 e2
eLt :: F.Expr -> F.Expr -> F.Expr
eLt e1 e2 = PAtom Lt e1 e2
eGt :: F.Expr -> F.Expr -> F.Expr
eGt e1 e2 = PAtom Gt e1 e2
eDec :: F.Expr -> F.Expr
eDec e = EBin Minus e (F.expr (1 :: Int))
ePlus :: F.Expr -> F.Expr -> F.Expr
ePlus e1 e2 = EBin Plus e1 e2
eILVar :: Var -> F.Expr
eILVar (V v) = eVar v
eILVar (GV v) = eVar v
eZero :: F.Expr
eZero = F.expr (0 :: Int)
eEqZero :: F.Expr -> F.Expr
eEqZero e = eEq e eZero
eApp :: Symbolic a => a -> [F.Expr] -> F.Expr
eApp f = eApps (F.eVar f)
eMember :: F.Expr -> F.Expr -> F.Expr
eMember i s = eApps mem [i, s]
where
mem = F.eVar "Set_mem"
eImp p q
= F.PImp p q
pidToExpr :: IL.Pid -> F.Expr
pidToExpr p@(PConc _) = eVar $ pid p
pidToExpr p@(PAbs (V v) s) = eApp (pid p) [eVar $ pidIdx p]
eReadState :: (Symbolic a, Symbolic b) => a -> b -> F.Expr
eReadState s f
= eApp (symbol f) [eVar s]
eReadMap e k
= eApp "Map_select" {- mapGetSpecString -} [e, k]
eRdPtr, eWrPtr :: (IL.Identable i, Symbolic a)
=> ConfigInfo i -> IL.Pid -> IL.Type -> a -> F.Expr
eRdPtr ci p t s
= eReadState s (ptrR ci p t)
eWrPtr ci p t s
= eReadState s (ptrW ci p t)
initOfPid :: forall a. (Data a, IL.Identable a)
=> ConfigInfo a -> IL.Process a -> F.Expr
initOfPid ci (p@(PAbs _ s), stmt)
= pAnd preds
where
preds = [ counterInit
, eEq counterSum setSize
] ++ counterInits
++ counterBounds
st = "v"
counterInit = eEq setSize (readCtr 0)
setSize = eReadState st (pidBound p)
counterSum = foldl' (\e i -> ePlus e (readCtr i)) (readCtr (-1)) stmts
counterInits = (\i -> eEq eZero (readCtr i)) <$> filter (/= 0) ((-1) : stmts)
counterBounds= (\i -> eLe eZero (readCtr i)) <$> filter (/= 0) stmts
readCtr :: Int -> F.Expr
readCtr i = eReadMap (eReadState st (pidPcCounter p)) (fixE i)
fixE i = if i < 0 then ECst (F.expr i) FInt else F.expr i
stmts :: [Int]
stmts = everything (++) (mkQ [] go) stmt
go :: Stmt a -> [Int]
go s = [ident s]
initOfPid ci (p@(PConc _), stmt)
= pAnd ([pcEqZero] ++ ptrBounds ++ loopVarBounds)
where
s = "v"
ptrBounds = concat [[ rdEqZero t, rdGeZero t
, wrEqZero t, wrGeZero t
, rdLeWr t ] | t <- fst <$> tyMap ci ]
loopVarBounds = [ eEqZero (eReadState s v) | (p', v) <- intVars (stateVars ci), p == p' ]
pcEqZero = eEq (eReadState s (pc p)) (F.expr initStmt)
rdEqZero t = eEqZero (eRdPtr ci p t s)
rdGeZero t = eLe eZero (eRdPtr ci p t s)
wrEqZero t = eEqZero (eWrPtr ci p t s)
wrGeZero t = eLe eZero (eWrPtr ci p t s)
rdLeWr t = eLe (eRdPtr ci p t s) (eWrPtr ci p t s)
initStmt = firstNonBlock stmt
firstNonBlock Block { blkBody = bs } = ident (head bs)
firstNonBlock s = ident s
schedExprOfPid :: IL.Identable a
=> ConfigInfo a -> IL.Process a -> Symbol -> F.Expr
schedExprOfPid ci (p@(IL.PAbs v s), prog) state
= subst1 (pAnd ([pcEqZero, idxBounds, isEnabledP] ++
concat [[rdEqZero t, wrEqZero t, wrGtZero t] | t <- fst <$> tyMap ci] ++
[] ))
(symbol (pidIdx p), vv)
where
vv = eVar "v"
idx = IL.setName s
idxBounds = eRange vv (F.expr (0 :: Int)) (eReadState state idx)
pcEqZero = eEqZero (eReadMap (eReadState state (pc p)) (eILVar v))
rdEqZero t = eRangeI eZero (eReadMap (eRdPtr ci p t state) (eILVar v)) (eReadMap (eRdPtr ci p t state) (eILVar v))
wrEqZero t = eEqZero (eReadMap (eWrPtr ci p t state) (eILVar v))
wrGtZero t = eLe eZero (eReadMap (eWrPtr ci p t state) (eILVar v))
isEnabled = eMember (eILVar v) (eReadState state (enabledSet ci p))
isEnabledP = case prog of
Recv{} -> F.PNot isEnabled
_ -> isEnabled
schedExprsOfConfig :: IL.Identable a
=> ConfigInfo a -> Symbol -> [F.Expr]
schedExprsOfConfig ci s
= go <$> filter (isAbs . fst) ps
where
ps = cProcs (config ci)
go p = schedExprOfPid ci p s
predToString :: F.Expr -> String
predToString = show . pprint
lhSpec :: String -> String
lhSpec x = "{-@\n" ++ x ++ "\n@-}"
specBind :: String -> String -> String
specBind x s = x ++ " :: " ++ s
specFmt :: String
specFmt = "{-@ assume %s :: {v:%s | %s} @-}"
printSpec :: String -> String -> F.Expr -> String
printSpec x t p = printf specFmt x t (predToString p)
initStateReft :: F.Expr -> String
initStateReft p
= printSpec initState stateRecordCons p
initSchedReft :: (Symbol -> [F.Expr]) -> String
initSchedReft p
= printf "{-@ assume %s :: %s:State -> [%s %s] @-}"
initSched
initState
pidPre
(unwords args)
where
args = printf "{v:Int | %s}" . predToString
<$> p (symbol initState)
nonDetSpec :: String
nonDetSpec
= printf "{-@ %s :: %s -> {v:Int | true} @-}" nondet (pp schedType)
measuresOfConfig :: Config a -> String
measuresOfConfig Config { cProcs = ps }
= unlines [ printf "{-@ measure %s @-}" (pidInj p) | (p, _) <- ps]
valMeasures :: String
valMeasures
= unlines [ printf "{-@ measure %s @-}" (valInj v) | v <- valCons ]
builtinSpec :: [String]
builtinSpec = [nonDetSpec]
---------------------
-- Type Declarations
---------------------
intType, mapTyCon :: Type
intType = TyCon (UnQual (name "Int"))
mapTyCon = TyCon (UnQual (name "Map_t"))
mapType :: Type -> Type -> Type
mapType k v = TyApp (TyApp mapTyCon k) v
intSetType :: Type
intSetType = TyApp (TyCon (UnQual (name "Set"))) intType
stateRecord :: [([Name], Type)] -> QualConDecl
stateRecord fs
= QualConDecl noLoc [] [] (RecDecl (name stateRecordCons) fs)
removeDerives :: Decl -> Decl
removeDerives (DataDecl s d c n ts qs _) = DataDecl s d c n ts qs []
removeDerives _ = undefined
---------------
-- State Fields
---------------
data StateFieldVisitor a b
= SFV { absF :: Pid -> String -> String -> String -> a
, pcF :: Pid -> String -> a
, ptrF :: Pid -> String -> String -> a
, valF :: Pid -> String -> a
, intF :: Pid -> String -> a
, globF :: String -> a
, globIntF :: String -> a
, combine :: [a] -> b
}
defaultVisitor :: StateFieldVisitor [String] [String]
defaultVisitor = SFV { absF = \_ x y z -> [x,y,z]
, pcF = \_ s -> [s]
, ptrF = \_ s1 s2 -> [s1,s2]
, valF = \_ s -> [s]
, intF = \_ s -> [s]
, globF = \s -> [s]
, globIntF = \s -> [s]
, combine = concat
}
withStateFields :: ConfigInfo t -> StateFieldVisitor a b -> b
withStateFields ci SFV{..}
= combine (globIntFs ++
absFs ++
pcFs ++
ptrFs ++
valFs ++
intFs ++
globFs)
where
globIntFs = [ globIntF v | V v <- setBoundVars ci ]
absFs = [ absF p (pidBound p) (pcCounter p) (enabledSet ci p)
| p <- pids ci, isAbs p ]
pcFs = [ pcF p (pc p) | p <- pids ci ]
ptrFs = [ ptrF p (ptrR ci p t) (ptrW ci p t) | p <- pids ci, t <- fst <$> tyMap ci ]
valFs = [ valF p v | (p, v) <- valVars (stateVars ci) ]
intFs = [ intF p v | (p, v) <- intVars (stateVars ci) ]
globFs = [ globF v | v <- globVals (stateVars ci) ]
derivin ci ns = ifQC_l ci $ map (\n -> (UnQual $ name n, [])) ns
stateDecl :: ConfigInfo a
-> ([Decl], String)
stateDecl ci
= ([dataDecl], specStrings)
where
ds = derivin ci ["Show", "Eq"]
dataDecl = DataDecl noLoc DataType [] (name stateRecordCons) [] [stateRecord fs] ds
specStrings = unlines [ dataReft
, ""
, recQuals
, ""
]
-- remove deriving classes (lh fails with them)
dataReft = printf "{-@ %s @-}" (pp (removeDerives dataDecl))
fs = withStateFields ci SFV { combine = concat
, absF = mkAbs
, pcF = mkPC
, ptrF = mkPtrs
, valF = mkVal
, intF = mkInt
, globF = mkGlob
, globIntF = mkGlobInt
}
mkAbs _ b pcv blkd = [mkBound b, mkCounter pcv, ([name blkd], intSetType)]
mkPtrs p rd wr = mkInt p rd ++ mkInt p wr
mkGlob v = [([name v], valHType ci)]
mkGlobInt v = [([name v], intType) | v `notElem` absPidSets]
absPidSets = [ IL.setName s | PAbs _ s <- fst <$> cProcs (config ci) ]
mkBound p = ([name p], intType)
mkCounter p = ([name p], mapType intType intType)
recQuals = unlines [ mkDeref f t ++ "\n" ++ mkEq f | ([f], t) <- fs ]
mkDeref f t = printf "{-@ qualif Deref_%s(v:%s, w:%s): v = %s w @-}"
(pp f) (pp (fixupQualType t)) stateRecordCons (pp f)
mkEq f = printf "{-@ qualif Eq_%s(v:%s, w:%s ): %s v = %s w @-}"
(pp f) stateRecordCons stateRecordCons (pp f) (pp f)
mkPC = liftMap intType
mkVal = liftMap (valHType ci)
mkInt = liftMap intType
liftMap t p v = [([name v], if isAbs p then mapType intType t else t)]
fixupQualType (TyApp (TyCon (UnQual (Ident "Set"))) _)
= TyApp (TyCon (UnQual (name "Set_Set"))) (TyVar (name "a"))
fixupQualType t
= t
valHType :: ConfigInfo a -> Type
valHType ci = TyApp (TyCon (UnQual (name valType)))
(pidPreApp ci)
pidPreApp :: ConfigInfo a -> Type
pidPreApp ci
= foldl' TyApp (TyCon . UnQual $ name pidPre) pidPreArgs
where
pidPreArgs :: [Type]
pidPreArgs = const intType <$> filter isAbs (pids ci)
pidDecl :: ConfigInfo a
-> [Decl]
pidDecl ci
= [ DataDecl noLoc DataType [] (name pidPre) tvbinds cons ds
, TypeDecl noLoc (name pidType) [] (pidPreApp ci)
] ++
(pidFn <$> pids ci)
where
mkPidCons pt = QualConDecl noLoc [] [] (mkPidCons' pt)
mkPidCons' (p, t) = if isAbs p then
ConDecl (name (pidConstructor p)) [TyVar t]
else
ConDecl (name (pidConstructor p)) []
cons = mkPidCons <$> ts
tvbinds = [ UnkindedVar t | (p, t) <- ts, isAbs p ]
ts = [ (p, mkTy t) | p <- pids ci | t <- [0..] ]
mkTy = name . ("p" ++) . show
ds = derivin ci ["Show", "Eq", "Ord"]
pidFn :: IL.Pid -> Decl
pidFn p
= FunBind [ Match noLoc (name $ pidInj p) [pidPattern p] Nothing truerhs Nothing
, Match noLoc (name $ pidInj p) [PWildCard] Nothing falserhs Nothing
]
where
truerhs = UnGuardedRhs (var (sym "True"))
falserhs = UnGuardedRhs (var (sym "False"))
boundPred :: IL.SetBound -> F.Expr
boundPred (IL.Known (S s) n)
= eEq (F.expr n) (eReadState "v" s)
boundPred (IL.Unknown (S s) (V x))
= eEq (eReadState "v" x) (eReadState "v" s)
initSpecOfConfig :: (Data a, IL.Identable a)
=> ConfigInfo a -> String
initSpecOfConfig ci
= unlines [ initStateReft concExpr
, initSchedReft schedExprs
, stateSpec
, unlines (pp <$> stateDecls)
, ""
, unlines (pp <$> pidDecls)
, ""
, measuresOfConfig (config ci)
-- , stateRecordSpec ci
-- , valTypeSpec
]
++ (unlines $ scrapeQuals ci)
where
concExpr = pAnd ((initOfPid ci <$> cProcs (config ci)) ++
[ eEqZero (eReadState (symbol "v") (symbol v))
| V v <- iters ] ++
[ eGt (eReadState (symbol "v") (symbol v)) eZero
| S v <- globSets (stateVars ci) ] ++ -- TODO do not assume this...
catMaybes [ boundPred <$> setBound ci s | (PAbs _ s) <- pids ci ])
iters = everything (++) (mkQ [] goVars) (cProcs (config ci))
goVars :: IL.Stmt Int -> [Var]
goVars Iter {iterVar = v} = [v]
goVars _ = []
schedExprs = schedExprsOfConfig ci
(stateDecls, stateSpec) = stateDecl ci
pidDecls = pidDecl ci
recvTy :: [IL.Stmt Int] -> [IL.Type]
recvTy = everything (++) (mkQ [] go)
where
go :: IL.Stmt Int -> [IL.Type]
go (Recv (t, _) _) = [t]
go _ = []
---------------------
-- Qualifiers
---------------------
mkQual :: String
-> [(String, String)]
-> F.Expr
-> String
mkQual n args e
= printf "{-@ qualif %s(%s): %s @-}" n argString eString
where
eString = show $ pprint e
argString = intercalate ", " (go <$> args)
go (a,t) = printf "%s:%s" a t
scrapeQuals :: (IL.Identable a, Data a)
=> ConfigInfo a
-> [String]
scrapeQuals ci
= scrapeIterQuals ci ++
scrapeAssertQuals ci
scrapeIterQuals :: (Data a, IL.Identable a)
=> ConfigInfo a
-> [String]
scrapeIterQuals ci
= concat [ everything (++) (mkQ [] (go p)) s | (p, s) <- cProcs (config ci) ]
where
go :: IL.Pid -> IL.Stmt Int -> [String]
go p Iter { iterVar = V v, iterSet = S set, iterBody = b, annot = a }
= [mkQual "IterInv" [("v", stateRecordCons)]
(eImp (eReadState "v" (pc p) `eEq` F.expr i)
(eReadState "v" v `eEq` eReadState "v" set)) | i <- pcAfter (ident a)] ++
iterQuals p v set b
go _ _
= []
pcAfter i = (-1) : [ j | j <- pcVals, j > i ]
pcVals :: [Int]
pcVals = Fold.foldl (\is (_, s) -> ident s : is) [] (cProcs $ config ci)
iterQuals :: (IL.Identable a, Data a)
=> IL.Pid -> String -> String -> IL.Stmt a -> [String]
iterQuals p@(PConc _) v set b
= [mkQual "IterInv" [("v", stateRecordCons)]
(eReadState "v" v `eLe` eReadState "v" set)] ++
everything (++) (mkQ [] go) b
where
go :: IL.Stmt Int -> [String]
go s
= [mkQual "Iter" [("v", stateRecordCons)]
(pcImpl p (ident s) (eReadState "v" v `eLt` eReadState "v" set))]
pcImpl :: IL.Pid -> Int -> F.Expr -> F.Expr
pcImpl p i e
= eImp (eReadState "v" (pc p) `eEq` (F.expr i)) e
scrapeAssertQuals :: ConfigInfo a
-> [String]
scrapeAssertQuals _
= []
|
gokhankici/symmetry
|
checker/src/Symmetry/IL/Model/HaskellSpec.hs
|
Haskell
|
mit
| 16,206
|
module Triangle (area) where
area :: Float -> Float -> Float
area b h = b * h
|
tonilopezmr/Learning-Haskell
|
Exercises/3/Exercise 1/Triangle.hs
|
Haskell
|
apache-2.0
| 80
|
module KeyBind
( Key (..)
, Keyset
, updateKeyset
, keysetToXY
) where
import Data.Complex
import Data.Set
import Graphics.UI.SDL
import Graphics.UI.SDL.Keysym
data Key = A | B | C | RB | LB | UB | DB | QUIT
deriving (Eq, Ord, Show)
type Keyset = Set Key
eventToKey :: Event -> Keyset -> Keyset
eventToKey Quit = insert QUIT
eventToKey (KeyDown k) = normalKey insert k
eventToKey (KeyUp k) = normalKey delete k
eventToKey _ = id
normalKey :: (Key -> Keyset -> Keyset) -> Keysym -> Keyset -> Keyset
normalKey f (Keysym {symKey = k})
| k == SDLK_z = f A
| k == SDLK_x = f B
| k == SDLK_c = f C
| k == SDLK_RIGHT = f RB
| k == SDLK_LEFT = f LB
| k == SDLK_UP = f UB
| k == SDLK_DOWN = f DB
| k == SDLK_ESCAPE= f QUIT
| otherwise = id
updateKeyset :: Keyset -> IO Keyset
updateKeyset k = do
event <- pollEvent
case event of
NoEvent -> return k
some -> updateKeyset (eventToKey some k)
keysetToXY :: (RealFloat a) => Keyset -> Complex a
keysetToXY k = (right - left) :+ (up - down)
where
right = b2i $ member RB k
left = b2i $ member LB k
up = b2i $ member UB k
down = b2i $ member DB k
b2i False = 0
b2i True = 1
|
c000/PaperPuppet
|
src/KeyBind.hs
|
Haskell
|
bsd-3-clause
| 1,216
|
{-# LANGUAGE
CPP
, DeriveDataTypeable
, FlexibleInstances
, FlexibleContexts
, MultiParamTypeClasses
, TypeFamilies
, UndecidableInstances #-}
{- |
Copyright : (c) Andy Sonnenburg 2013
License : BSD3
Maintainer : andy22286@gmail.com
-}
module Data.Tuple.IO
( module Data.Tuple.MTuple
, IOTuple
, ArraySlice
, IOUTuple
) where
#ifdef MODULE_Control_Monad_ST_Safe
import Control.Monad.ST.Safe (RealWorld)
#else
import Control.Monad.ST (RealWorld)
#endif
import Data.ByteArraySlice
import Data.Tuple.Array
import Data.Tuple.ByteArray
import Data.Tuple.ITuple
import Data.Tuple.MTuple
import Data.Typeable (Typeable)
newtype IOTuple a =
IOTuple { unIOTuple :: ArrayTuple RealWorld a
} deriving (Eq, Typeable)
instance ( ITuple t
, ArraySlice (Tuple (ListRep t))
) => MTuple IOTuple t IO where
thawTuple = fmap IOTuple . thawTuple
freezeTuple = freezeTuple . unIOTuple
instance ( ITuple t
, ArraySlice (Tuple (ListRep t))
) => MField1 IOTuple t IO where
read1 = read1 . unIOTuple
write1 = write1 . unIOTuple
instance ( ITuple t
, ArraySlice (Tuple (ListRep t))
) => MField2 IOTuple t IO where
read2 = read2 . unIOTuple
write2 = write2 . unIOTuple
instance ( ITuple t
, ArraySlice (Tuple (ListRep t))
) => MField3 IOTuple t IO where
read3 = read3 . unIOTuple
write3 = write3 . unIOTuple
instance ( ITuple t
, ArraySlice (Tuple (ListRep t))
) => MField4 IOTuple t IO where
read4 = read4 . unIOTuple
write4 = write4 . unIOTuple
instance ( ITuple t
, ArraySlice (Tuple (ListRep t))
) => MField5 IOTuple t IO where
read5 = read5 . unIOTuple
write5 = write5 . unIOTuple
instance ( ITuple t
, ArraySlice (Tuple (ListRep t))
) => MField6 IOTuple t IO where
read6 = read6 . unIOTuple
write6 = write6 . unIOTuple
instance ( ITuple t
, ArraySlice (Tuple (ListRep t))
) => MField7 IOTuple t IO where
read7 = read7 . unIOTuple
write7 = write7 . unIOTuple
instance ( ITuple t
, ArraySlice (Tuple (ListRep t))
) => MField8 IOTuple t IO where
read8 = read8 . unIOTuple
write8 = write8 . unIOTuple
instance ( ITuple t
, ArraySlice (Tuple (ListRep t))
) => MField9 IOTuple t IO where
read9 = read9 . unIOTuple
write9 = write9 . unIOTuple
newtype IOUTuple a =
IOUTuple { unIOUTuple :: ByteArrayTuple RealWorld a
} deriving (Eq, Typeable)
instance ( ITuple t
, ByteArraySlice (Tuple (ListRep t))
) => MTuple IOUTuple t IO where
thawTuple = fmap IOUTuple . thawTuple
freezeTuple = freezeTuple . unIOUTuple
instance ( ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
) => MField1 IOUTuple t IO where
read1 = read1 . unIOUTuple
write1 = write1 . unIOUTuple
instance ( ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
) => MField2 IOUTuple t IO where
read2 = read2 . unIOUTuple
write2 = write2 . unIOUTuple
instance ( ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
) => MField3 IOUTuple t IO where
read3 = read3 . unIOUTuple
write3 = write3 . unIOUTuple
instance ( ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
, ByteArraySlice (Field4 t)
) => MField4 IOUTuple t IO where
read4 = read4 . unIOUTuple
write4 = write4 . unIOUTuple
instance ( ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
, ByteArraySlice (Field4 t)
, ByteArraySlice (Field5 t)
) => MField5 IOUTuple t IO where
read5 = read5 . unIOUTuple
write5 = write5 . unIOUTuple
instance ( ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
, ByteArraySlice (Field4 t)
, ByteArraySlice (Field5 t)
, ByteArraySlice (Field6 t)
) => MField6 IOUTuple t IO where
read6 = read6 . unIOUTuple
write6 = write6 . unIOUTuple
instance ( ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
, ByteArraySlice (Field4 t)
, ByteArraySlice (Field5 t)
, ByteArraySlice (Field6 t)
, ByteArraySlice (Field7 t)
) => MField7 IOUTuple t IO where
read7 = read7 . unIOUTuple
write7 = write7 . unIOUTuple
instance ( ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
, ByteArraySlice (Field4 t)
, ByteArraySlice (Field5 t)
, ByteArraySlice (Field6 t)
, ByteArraySlice (Field7 t)
, ByteArraySlice (Field8 t)
) => MField8 IOUTuple t IO where
read8 = read8 . unIOUTuple
write8 = write8 . unIOUTuple
instance ( ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
, ByteArraySlice (Field4 t)
, ByteArraySlice (Field5 t)
, ByteArraySlice (Field6 t)
, ByteArraySlice (Field7 t)
, ByteArraySlice (Field8 t)
, ByteArraySlice (Field9 t)
) => MField9 IOUTuple t IO where
read9 = read9 . unIOUTuple
write9 = write9 . unIOUTuple
|
sonyandy/var
|
src/Data/Tuple/IO.hs
|
Haskell
|
bsd-3-clause
| 5,909
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module Control.ConstraintClasses.Key
(
-- * Key classes
CKey
) where
import Prelude hiding (lookup)
import Data.Functor.Identity
import Data.Functor.Product
import Data.Functor.Sum
import Data.Functor.Compose
-- vector
import qualified Data.Vector as Vector
import qualified Data.Vector.Storable as VectorStorable
import qualified Data.Vector.Unboxed as VectorUnboxed
--------------------------------------------------------------------------------
-- | Equivalent to the @Key@ type family.
type family CKey (f :: * -> *)
type instance CKey [] = Int
type instance CKey Identity = ()
type instance CKey (Compose f g) = (CKey f, CKey g)
type instance CKey (Product f g) = Either (CKey f) (CKey g)
type instance CKey (Sum f g) = (CKey f, CKey g)
type instance CKey Vector.Vector = Int
type instance CKey VectorStorable.Vector = Int
type instance CKey VectorUnboxed.Vector = Int
|
guaraqe/constraint-classes
|
src/Control/ConstraintClasses/Key.hs
|
Haskell
|
bsd-3-clause
| 1,028
|
module Khronos.AssignModules
( assignModules
) where
import Algebra.Graph.AdjacencyIntMap
hiding ( empty )
import qualified Data.IntMap.Strict as IntMap
import qualified Data.IntSet as Set
import qualified Data.List.Extra as List
import qualified Data.Map as Map
import qualified Data.Set
import qualified Data.Text.Extra as T
import Data.Vector ( Vector )
import qualified Data.Vector.Extra as V
import Data.Version
import Polysemy
import Polysemy.Input
import Polysemy.State
import Relude hiding ( State
, ask
, evalState
, execState
, get
, gets
, modify'
, put
, runState
)
import Error
import Haskell
import Render.Element
import Render.SpecInfo
import Spec.Types
import Data.Char ( isUpper )
import Khronos.Render
-- | Assign all render elements a module
assignModules
:: forall r t
. (HasErr r, HasRenderParams r, HasSpecInfo r)
=> Spec t
-> RenderedSpec RenderElement
-> Sem r [(ModName, Vector RenderElement)]
assignModules spec rs = do
let indexed = run . evalState (0 :: Int) $ traverse
(\r -> do
i <- get @Int
modify' @Int succ
pure (i, r)
)
rs
flat = fromList . toList $ indexed
lookupRe i = case flat V.!? i of
Nothing -> throw "Unable to find element at index"
Just (_, e) -> pure e
(exporterMap, rel) <- buildRelation (fromList . toList $ indexed)
let getExporter n =
note ("Unable to find " <> show n <> " in any render element")
$ Map.lookup n exporterMap
initialState = mempty :: S
exports <- execState initialState
$ assign (raise . getExporter) rel (closure rel) spec indexed
--
-- Check that everything is exported
--
unexportedNames <- unexportedNames spec
forV_ indexed $ \(i, re) -> case IntMap.lookup i exports of
Nothing -> do
let exportedNames = exportName <$> toList (reExports re)
forV_ (List.nubOrd exportedNames List.\\ unexportedNames)
$ \n -> throw $ show n <> " is not exported from any module"
Just _ -> pure ()
let declaredNames = Map.fromListWith
(<>)
( IntMap.toList exports
<&> \(n, ExportLocation d _) -> (d, Set.singleton n)
)
reexportingMap = Map.fromListWith
(<>)
[ (m, Set.singleton n)
| (n, ExportLocation _ ms) <- IntMap.toList exports
, m <- toList ms
]
forV (Map.toList declaredNames) $ \(modname, is) -> do
declaringRenderElements <- traverseV lookupRe (fromList (Set.toList is))
reexportingRenderElements <- case Map.lookup modname reexportingMap of
Nothing -> pure mempty
Just is -> do
res <-
filter (getAll . reReexportable) <$> forV (Set.toList is) lookupRe
pure
$ reexportingRenderElement
. Data.Set.fromList
. toList
. reExports
<$> res
pure
(modname, declaringRenderElements <> fromList reexportingRenderElements)
reexportingRenderElement :: Data.Set.Set Export -> RenderElement
reexportingRenderElement exports =
(emptyRenderElement ("reexporting " <> show exports))
{ reReexportedNames = Data.Set.filter
((== Reexportable) . exportReexportable)
exports
}
data ExportLocation = ExportLocation
{ _elDeclaringModule :: ModName
, _elReExportingModules :: [ModName]
}
type S = IntMap ExportLocation
data ReqDeps = ReqDeps
{ commands :: Vector Int
, types :: Vector Int
, enumValues :: Vector Int
, directExporters :: Vector Int
-- ^ The union of all the above
}
-- The type is put into the first rule that applies, and reexported from any
-- subsequent matching rules in that feature.
--
-- - For each feature
-- - All reachable enums are put under the Feature.Enums module
-- - Commands are put into their respective components
-- - All types directly used by a command are put into the same module
--
-- - For each extension
-- -
assign
:: forall r t
. (HasErr r, Member (State S) r, HasRenderParams r)
=> (HName -> Sem r Int)
-> AdjacencyIntMap
-> AdjacencyIntMap
-> Spec t
-> RenderedSpec (Int, RenderElement)
-> Sem r ()
assign getExporter rel closedRel Spec {..} rs@RenderedSpec {..} = do
RenderParams {..} <- input
let
allEnums = IntMap.fromList (toList rsEnums)
allHandles = IntMap.fromList (toList rsHandles)
allFuncPointers = IntMap.fromList (toList rsFuncPointers)
-- Handy for debugging
_elemName = let l = toList rs in \i -> reName <$> List.lookup i l
--
-- Perform an action over all Features
--
forFeatures
:: (Feature -> Text -> (Maybe Text -> ModName) -> Sem r a)
-> Sem r (Vector a)
forFeatures f = forV specFeatures $ \feat@Feature {..} -> do
let prefix =
modulePrefix <> ".Core" <> foldMap show (versionBranch fVersion)
f feat prefix (featureCommentToModuleName prefix)
forFeatures_ = void . forFeatures
extensionModulePrefix = modulePrefix <> "." <> "Extensions"
forExtensionRequires
:: (Text -> ModName -> ReqDeps -> Require -> Sem r ()) -> Sem r ()
forExtensionRequires f = forV_ specExtensions $ \Extension {..} ->
forRequires_
exRequires
(const $ extensionNameToModuleName extensionModulePrefix exName)
$ \modname -> f extensionModulePrefix modname
forRequires
:: Traversable f
=> f Require
-> (Maybe Text -> ModName)
-> (ModName -> ReqDeps -> Require -> Sem r a)
-> Sem r [a]
forRequires requires commentToModName f =
forV (sortOn (isNothing . rComment) . toList $ requires) $ \r -> do
commands <- traverseV (getExporter . mkFunName) (rCommandNames r)
types <- traverseV (getExporter . mkTyName) (rTypeNames r)
enumValues <- traverseV (getExporter . mkPatternName)
(rEnumValueNames r)
let directExporters = commands <> types <> enumValues
f (commentToModName (rComment r)) ReqDeps { .. } r
forRequires_ requires commentToModName =
void . forRequires requires commentToModName
--
-- Perform an action over all 'Require's of all features and elements
--
forFeaturesAndExtensions
:: (Text -> ModName -> Bool -> ReqDeps -> Require -> Sem r ()) -> Sem r ()
forFeaturesAndExtensions f = do
forFeatures_ $ \feat prefix commentToModName ->
forRequires_ (fRequires feat) commentToModName
$ \modname -> f prefix modname True
forExtensionRequires $ \prefix modname -> f prefix modname False
--
-- Export all elements both in world and reachable, optionally from a
-- specifically named submodule.
--
exportReachable
:: Bool -> Text -> IntMap RenderElement -> IntSet -> Sem r ()
exportReachable namedSubmodule prefix world reachable = do
let reachableWorld = world `IntMap.restrictKeys` reachable
forV_ (IntMap.toList reachableWorld) $ \(i, re) -> do
modName <- if namedSubmodule
then do
name <- firstTypeName re
pure (ModName (prefix <> "." <> name))
else pure (ModName prefix)
export modName i
allCoreExports <-
fmap (Set.unions . concat . toList)
. forFeatures
$ \Feature {..} _ mkName ->
forRequires fRequires mkName $ \_ ReqDeps {..} _ ->
let direct = Set.fromList (toList directExporters)
in pure $ direct `postIntSets` closedRel
----------------------------------------------------------------
-- Explicit elements
----------------------------------------------------------------
forV_ rs $ \(i, re) -> forV_ (reExplicitModule re) $ \m -> export m i
----------------------------------------------------------------
-- API Constants
----------------------------------------------------------------
constantModule <- mkModuleName ["Core10", "APIConstants"]
forV_ rsAPIConstants $ \(i, _) -> export constantModule i
----------------------------------------------------------------
-- Explicit Enums, Handles and FuncPointers for each feature
----------------------------------------------------------------
forFeaturesAndExtensions $ \prefix _ isFeature ReqDeps {..} _ -> do
let reachable =
Set.unions . toList $ (`postIntSet` closedRel) <$> directExporters
----------------------------------------------------------------
-- Reachable Enums
----------------------------------------------------------------
when isFeature
$ exportReachable True (prefix <> ".Enums") allEnums reachable
----------------------------------------------------------------
-- Reachable Handles
----------------------------------------------------------------
exportReachable False (prefix <> ".Handles") allHandles reachable
----------------------------------------------------------------
-- Reachable FuncPointers
----------------------------------------------------------------
when isFeature $ exportReachable False
(prefix <> ".FuncPointers")
allFuncPointers
reachable
----------------------------------------------------------------
-- Explicit exports of all features and extensions
----------------------------------------------------------------
forFeaturesAndExtensions $ \_ modname isFeature ReqDeps {..} _ -> if isFeature
then forV_ directExporters $ export modname
else
let noCore = Set.toList
( Set.fromList (toList directExporters)
`Set.difference` allCoreExports
)
in forV_ noCore $ export modname
----------------------------------------------------------------
-- Assign aliases to be with their targets if they're not already assigned
----------------------------------------------------------------
forV_ specAliases $ \Alias {..} -> do
let mkName = case aType of
TypeAlias -> mkTyName
TermAlias -> mkFunName -- TODO, terms other than functions?
PatternAlias -> mkPatternName
i <- getExporter (mkName aName)
j <- getExporter (mkName aTarget)
gets @S (IntMap.lookup i) >>= \case
Just _ -> pure ()
Nothing -> gets @S (IntMap.lookup j) >>= \case
Just (ExportLocation jMod _) ->
modify' (IntMap.insert i (ExportLocation jMod []))
Nothing -> pure ()
----------------------------------------------------------------
-- Go over the features one by one and close them
----------------------------------------------------------------
forFeatures_ $ \feat _ getModName -> do
-- Types directly referred to by the commands and types
forRequires_ (fRequires feat) getModName $ \modname ReqDeps {..} _ ->
forV_ directExporters
$ \i -> exportManyNoReexport modname (i `postIntSet` rel)
-- Types indirectly referred to by the commands and types
forRequires_ (fRequires feat) getModName $ \modname ReqDeps {..} _ ->
forV_ directExporters
$ \i -> exportManyNoReexport modname (i `postIntSet` closedRel)
----------------------------------------------------------------
-- Close the extensions
----------------------------------------------------------------
forExtensionRequires $ \_ modname ReqDeps {..} _ ->
forV_ directExporters $ \i -> do
exportManyNoReexport modname (i `postIntSet` rel)
exportMany modname ((i `postIntSet` rel) `Set.difference` allCoreExports)
forExtensionRequires $ \_ modname ReqDeps {..} _ ->
forV_ directExporters $ \i -> exportMany
modname
((i `postIntSet` closedRel) `Set.difference` allCoreExports)
-- | This will try to ignore the "Bits" elements of flags and only return them
-- if they are the only definition.
--
-- The reason is that initially this library exported the "Bits" synonym for
-- flags last and the modules were named accordingly. Now they're exported
-- first, but we don't want to change the module names
firstTypeName :: HasErr r => RenderElement -> Sem r Text
firstTypeName re =
let ns = mapMaybe getTyConName (V.toList (exportName <$> reExports re))
noBits = filter (("Bits" `T.isSuffixOf`) . stripVendor) ns
in case noBits <> ns of
[] -> throw "Unable to get type name from RenderElement"
x : _ -> pure x
export :: Member (State S) r => ModName -> Int -> Sem r ()
export m i = modify' (IntMap.alter ins i)
where
ins = \case
Nothing -> Just (ExportLocation m [])
Just (ExportLocation t rs) -> Just (ExportLocation t (m : rs))
exportMany :: Member (State S) r => ModName -> IntSet -> Sem r ()
exportMany m is =
let newMap = IntMap.fromSet (const (ExportLocation m [])) is
in modify' (\s -> IntMap.unionWith ins s newMap)
where
ins (ExportLocation r rs) (ExportLocation n _) = ExportLocation r (n : rs)
exportManyNoReexport :: Member (State S) r => ModName -> IntSet -> Sem r ()
exportManyNoReexport m is =
let newMap = IntMap.fromSet (const (ExportLocation m [])) is
in modify' (\s -> IntMap.unionWith ins s newMap)
where ins (ExportLocation r rs) (ExportLocation _ _) = ExportLocation r rs
----------------------------------------------------------------
-- Making module names
----------------------------------------------------------------
extensionNameToModuleName :: Text -> Text -> ModName
extensionNameToModuleName extensionModulePrefix =
ModName . ((extensionModulePrefix <> ".") <>)
featureCommentToModuleName :: Text -> Maybe Text -> ModName
featureCommentToModuleName prefix = \case
Nothing -> ModName prefix
Just t ->
ModName
$ ((prefix <> ".") <>)
. mconcat
. fmap (T.upperCaseFirst . replaceSymbols)
. dropLast "API"
. dropLast "commands"
. T.words
. T.replace "Promoted from" "Promoted_From_"
. T.replace "Originally based on" "Originally_Based_On_"
. T.takeWhile (/= ',')
. removeParens
. featureCommentMap
$ t
featureCommentMap :: Text -> Text
featureCommentMap = \case
"These types are part of the API and should always be defined, even when no enabled features require them."
-> "OtherTypes"
"These types are part of the API, though not directly used in API commands or data structures"
-> "OtherTypes"
"Types not directly used by the API" -> "OtherTypes"
"Fundamental types used by many commands and structures" ->
"FundamentalTypes"
t -> t
----------------------------------------------------------------
-- Utils
----------------------------------------------------------------
buildRelation
:: HasErr r
=> Vector (Int, RenderElement)
-> Sem r (Map HName Int, AdjacencyIntMap)
buildRelation elements = do
let elementExports RenderElement {..} =
reInternal <> reExports <> V.concatMap exportWith reExports
elementImports =
fmap importName . filter (not . importSource) . toList . reLocalImports
numbered = elements
allNames = sortOn
fst
[ (n, i)
| (i, x) <- toList numbered
, n <- fmap exportName . V.toList . elementExports $ x
]
nameMap = Map.fromAscList allNames
lookup n = case Map.lookup n nameMap of
Nothing -> pure 0 -- throw $ "Unable to find " <> show n <> " in any vertex"
Just i -> pure i
es <- concat <$> forV
numbered
(\(n, x) -> forV (elementImports x) (fmap (n, ) . lookup))
let relation = vertices (fst <$> toList numbered) `overlay` edges es
pure (nameMap, relation)
getTyConName :: HName -> Maybe Text
getTyConName = \case
TyConName n -> Just n
_ -> Nothing
removeParens :: Text -> Text
removeParens t =
let (x, y) = T.breakOn "(" t in x <> T.takeWhileEnd (/= ')') y
replaceSymbols :: Text -> Text
replaceSymbols = \case
"+" -> "And"
t -> t
dropLast :: Eq a => a -> [a] -> [a]
dropLast x l = case nonEmpty l of
Nothing -> []
Just xs -> if last xs == x then init xs else toList xs
postIntSets :: IntSet -> AdjacencyIntMap -> IntSet
postIntSets is rel = Set.unions $ (`postIntSet` rel) <$> Set.toList is
----------------------------------------------------------------
-- Ignored unexported names
----------------------------------------------------------------
unexportedNames :: HasRenderParams r => Spec t -> Sem r [HName]
unexportedNames Spec {..} = do
RenderParams {..} <- input
let apiVersions = toList specFeatures <&> \Feature {..} ->
let major : minor : _ = versionBranch fVersion
in mkTyName
(CName $ "VK_API_VERSION_" <> show major <> "_" <> show minor)
pure
$ [ mkFunName "vkGetSwapchainGrallocUsageANDROID"
, mkFunName "vkGetSwapchainGrallocUsage2ANDROID"
, mkFunName "vkAcquireImageANDROID"
, mkFunName "vkQueueSignalReleaseImageANDROID"
, mkTyName "VkSwapchainImageUsageFlagBitsANDROID"
, mkTyName "VkSwapchainImageUsageFlagsANDROID"
, mkTyName "VkNativeBufferUsage2ANDROID"
, mkTyName "VkNativeBufferANDROID"
, mkTyName "VkSwapchainImageCreateInfoANDROID"
, mkTyName "VkPhysicalDevicePresentationPropertiesANDROID"
-- TODO: Export these
, mkTyName "VkSemaphoreCreateFlagBits"
-- TODO: Export these
, mkTyName "InstanceCreateFlagBits"
, mkTyName "SessionCreateFlagBits"
, mkTyName "SwapchainCreateFlagBits"
, mkTyName "ViewStateFlagBits"
, mkTyName "CompositionLayerFlagBits"
, mkTyName "SpaceLocationFlagBits"
, mkTyName "SpaceVelocityFlagBits"
, mkTyName "InputSourceLocalizedNameFlagBits"
, mkTyName "VulkanInstanceCreateFlagBitsKHR"
, mkTyName "VulkanDeviceCreateFlagBitsKHR"
, mkTyName "DebugUtilsMessageSeverityFlagBitsEXT"
, mkTyName "DebugUtilsMessageTypeFlagBitsEXT"
, mkTyName "OverlayMainSessionFlagBitsEXTX"
, mkTyName "OverlaySessionCreateFlagBitsEXTX"
-- TODO: export these
, mkFunName "xrSetInputDeviceActiveEXT"
, mkFunName "xrSetInputDeviceStateBoolEXT"
, mkFunName "xrSetInputDeviceStateFloatEXT"
, mkFunName "xrSetInputDeviceStateVector2fEXT"
, mkFunName "xrSetInputDeviceLocationEXT"
]
<> apiVersions
----------------------------------------------------------------
-- Utils
----------------------------------------------------------------
stripVendor :: Text -> Text
stripVendor = T.dropWhileEnd isUpper
|
expipiplus1/vulkan
|
generate-new/khronos-spec/Khronos/AssignModules.hs
|
Haskell
|
bsd-3-clause
| 19,322
|
{-# LANGUAGE DeriveFunctor, LambdaCase #-}
module Data.Boombox.Head where
import Data.Boombox.Player
import Data.Boombox.Tape
import Control.Comonad
import Control.Applicative
-- | 'Head' is a Store-like comonad which handles seeking.
data Head i a = Head !i (Maybe i -> a) deriving Functor
instance Comonad (Head i) where
extract (Head _ f) = f Nothing
extend k (Head i f) = Head i $ \case
Nothing -> k $ Head i f
Just j -> k $ Head j $ f . Just . maybe j id
instance Ord i => Chronological (Head i) where
coincidence (Head i f) (Head j g) = case compare i j of
EQ -> Simultaneous (Head i (liftA2 (,) f g))
LT -> LeftFirst
GT -> RightFirst
-- | Seek to an arbitrary position.
seeksTape :: Monad m => (i -> Maybe i) -> Tape (Head i) m a -> Tape (Head i) m a
seeksTape t (Tape m) = Tape $ m >>= \(_, Head i f) -> unconsTape (f (t i))
-- | Get the current offset.
posP :: PlayerT (Head i) s m i
posP = control $ \(Head i f) -> (f Nothing, pure i)
-- | Apply the given function to the current offset and jump to the resulting offset.
seeksP :: (i -> Maybe i) -> PlayerT (Head i) s m ()
seeksP t = control $ \(Head i f) -> (f (t i), pure ())
-- | Seek to the given offset.
seekP :: i -> PlayerT (Head i) s m ()
seekP i = seeksP (const (Just i))
|
fumieval/boombox
|
src/Data/Boombox/Head.hs
|
Haskell
|
bsd-3-clause
| 1,274
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Configuration.Screen where
import Lens.Simple ( makeLenses
, (^.)
)
import Data.Yaml ( FromJSON(..)
, (.!=)
, (.:?)
)
import qualified Data.Yaml as Y
data ImprovizScreenConfig = ImprovizScreenConfig
{ _front :: Float
, _back :: Float
} deriving (Show)
makeLenses ''ImprovizScreenConfig
defaultScreenConfig = ImprovizScreenConfig { _front = 0.1, _back = 100 }
instance FromJSON ImprovizScreenConfig where
parseJSON (Y.Object v) =
ImprovizScreenConfig
<$> v
.:? "front"
.!= (defaultScreenConfig ^. front)
<*> v
.:? "back"
.!= (defaultScreenConfig ^. back)
parseJSON _ = fail "Expected Object for ScreenConfig value"
|
rumblesan/proviz
|
src/Configuration/Screen.hs
|
Haskell
|
bsd-3-clause
| 1,069
|
module Main where
import Control.Applicative
import Control.Concurrent
import Control.Monad
import Control.Monad.IO.Class
import Data.Aeson
import Data.DateTime (DateTime)
import Data.Function
import Data.Monoid
import Data.Text (Text)
import Network.API.Builder
import Reddit
import Reddit.Types.Subreddit
import Reddit.Types.Wiki
import Text.Read
import qualified Data.DateTime as DateTime
import qualified Data.Text as Text
import qualified System.Environment as System
subreddit :: SubredditName
subreddit = R "dota2"
main :: IO ()
main = do
[user, pass] <- fmap Text.pack <$> System.getArgs
go user pass
go :: Text -> Text -> IO ()
go user pass = every 30 $
getSightings >>= \case
Left _ -> putStrLn "couldn't get sightings"
Right (Sightings (sighting : _)) -> do
time <- DateTime.getCurrentTime
let status = getYearBeastStatus time sighting
void $ runReddit user pass $ do
updateBanner status "config/sidebar"
updateBanner status "sidebar"
Right (Sightings []) -> return ()
data YearBeastStatus = ArrivingIn Integer
| LeavingIn Integer
| Missing
deriving (Show, Read, Eq)
getYearBeastStatus :: DateTime -> Sighting -> YearBeastStatus
getYearBeastStatus cur (Sighting _ t d _) =
case (cur < DateTime.addSeconds d t, cur < t) of
(True, True) -> ArrivingIn $ DateTime.diffSeconds t cur `div` 60
(True, False) -> LeavingIn $ DateTime.diffSeconds (DateTime.addSeconds d t) cur `div` 60
_ -> Missing
foo :: Text -> Bool
foo = Text.isPrefixOf "#### "
updateBanner :: YearBeastStatus -> Text -> Reddit ()
updateBanner status page = do
p <- getWikiPage subreddit page
editWikiPage subreddit page (genLink status <> Text.dropWhile (/= '\n') (contentMarkdown p)) ""
genLink :: YearBeastStatus -> Text
genLink (ArrivingIn 0) = "#### [**The Year Beasts will arrive in less than a minute!**](http://2015.yearbeast.com)"
genLink (ArrivingIn 1) = "#### [**The Year Beasts will arrive in 1 minute!**](http://2015.yearbeast.com)"
genLink (ArrivingIn n) = "#### [**The Year Beasts will arrive in " <> tshow n <> " minutes!**](http://2015.yearbeast.com)"
genLink (LeavingIn 0) = "#### [**The Year Beasts will leave in less than a minute!**](http://2015.yearbeast.com)"
genLink (LeavingIn 1) = "#### [**The Year Beasts will leave in 1 minute!**](http://2015.yearbeast.com)"
genLink (LeavingIn n) = "#### [**The Year Beasts will leave in " <> tshow n <> " minutes!**](http://2015.yearbeast.com)"
genLink Missing = ""
tshow :: Show a => a -> Text
tshow = Text.pack . show
data Sighting =
Sighting { sightingID :: Integer
, timestamp :: DateTime
, duration :: Integer
, comment :: Text }
deriving (Show, Read, Eq)
instance Ord Sighting where
compare = compare `on` sightingID
instance FromJSON Sighting where
parseJSON (Object o) =
Sighting <$> (o .: "id" >>= readParse)
<*> (DateTime.fromSeconds <$> (o .: "timestamp" >>= readParse))
<*> (o .: "duration" >>= readParse)
<*> o .: "comment"
parseJSON _ = mempty
newtype Sightings = Sightings [Sighting]
deriving (Show, Read, Eq)
instance FromJSON Sightings where parseJSON x = Sightings <$> parseJSON x
instance Receivable Sightings where receive = useFromJSON
yearBeast :: Builder
yearBeast = basicBuilder "Year Beast" "http://2015.yearbeast.com"
sightingsRoute :: Route
sightingsRoute =
Route [ "history.json" ]
[ ]
"GET"
getSightings :: IO (Either (APIError ()) Sightings)
getSightings = execAPI yearBeast () $ runRoute sightingsRoute
readParse :: (MonadPlus m, Read a) => String -> m a
readParse x =
case readMaybe x of
Just r -> return r
Nothing -> mzero
every :: MonadIO m => Int -> m a -> m ()
every s x = forever $ do
_ <- x
liftIO $ threadDelay $ s * 1000 * 1000
|
intolerable/year-beast
|
src/Main.hs
|
Haskell
|
bsd-3-clause
| 3,857
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Migrate.Internal.Types
( TransferMonad
, TransferState(..)
, TransactionError(..)
, getInformation, get, write, append, modify, getPreviousError
, runTransferMonad
) where
import ClassyPrelude
import Control.Arrow
import Control.Exception
import Control.Monad
import Control.Monad.Trans.Except
import Data.Maybe (fromMaybe)
import Data.Monoid
import Data.Serialize (Serialize)
import GHC.Generics
data TransactionError
= ServiceError String
| SystemError String
| SerializationError String
| Unexpected String
deriving (Show, Eq, Ord, Generic)
instance Serialize TransactionError where
data TransferEnvironment env w = TransferEnvironment
{ readableEnv :: env
, writableRef :: MVar w
, prevError :: Maybe TransactionError
}
newtype TransferMonad environment written return =
TransferMonad { unTransferMonad :: ExceptT
TransactionError
(ReaderT (TransferEnvironment environment written) IO)
return
} deriving (Monad, Applicative, Functor, MonadIO)
runTransferMonad :: r -> MVar w -> Maybe TransactionError -> TransferMonad r w a -> IO (Either TransactionError a)
runTransferMonad r mvar exc = flip runReaderT (TransferEnvironment r mvar exc) . runExceptT . unTransferMonad
data TransferState initialData dataRead dataWritten
= Initializing initialData
| Reading initialData dataRead
| Writing initialData dataRead dataWritten
| Finished initialData dataRead dataWritten
deriving (Eq, Ord, Show, Generic)
instance (Serialize d, Serialize r, Serialize w) => Serialize (TransferState d r w) where
getInformation :: TransferMonad r w r
getInformation = TransferMonad (readableEnv <$> lift ask)
get :: TransferMonad r w w
get = TransferMonad (lift ask >>= readMVar . writableRef)
write :: w -> TransferMonad r w ()
write w = TransferMonad (lift ask >>= void . flip swapMVar w . writableRef)
modify :: (w -> w) -> TransferMonad r w w
modify f = TransferMonad $ do
mvar <- writableRef <$> lift ask
modifyMVar mvar (\val -> let x = f val in return (x, x))
append :: Monoid w => w -> TransferMonad r w w
append d = modify $ flip mappend d
succeed :: a -> TransferMonad r w a
succeed = return
safeFail :: TransactionError -> TransferMonad r w a
safeFail = TransferMonad . throwE
getPreviousError :: TransferMonad r w (Maybe TransactionError)
getPreviousError = TransferMonad $ prevError <$> lift ask
|
JustusAdam/bitbucket-github-migrate
|
src/Migrate/Internal/Types.hs
|
Haskell
|
bsd-3-clause
| 2,765
|
{-# LANGUAGE MagicHash, UnboxedTuples #-}
module CasIORef (casIORef) where
import GHC.IORef
import GHC.STRef
import GHC.Exts
import GHC.IO
casIORef :: IORef a -> a -> a -> IO Bool
casIORef (IORef (STRef r#)) old new = IO $ \s ->
case casMutVar# r# old new s of
(# s', did, val #) ->
if did ==# 0# then (# s', True #)
else (# s', False #)
|
mono0926/ParallelConcurrentHaskell
|
CasIORef.hs
|
Haskell
|
bsd-3-clause
| 379
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.