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
|
|---|---|---|---|---|---|
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
import Data.List (sort)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import Prelude hiding (null)
import CustomSet
( delete
, difference
, fromList
, insert
, isDisjointFrom
, isSubsetOf
, intersection
, member
, null
, size
, toList
, union
)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = do
describe "standard tests" $ do
describe "null" $ do
it "sets with no elements are empty" $
null (fromList ([] :: [Integer])) `shouldBe` True
it "sets with elements are not empty" $
null (fromList [1]) `shouldBe` False
describe "member" $ do
it "nothing is contained in an empty set" $
1 `member` fromList [] `shouldBe` False
it "when the element is in the set" $
1 `member` fromList [1, 2, 3] `shouldBe` True
it "when the element is not in the set" $
4 `member` fromList [1, 2, 3] `shouldBe` False
describe "isSubsetOf" $ do
it "empty set is a subset of another empty set" $
fromList ([] :: [Integer]) `isSubsetOf` fromList [] `shouldBe` True
it "empty set is a subset of non-empty set" $
fromList [] `isSubsetOf` fromList [1] `shouldBe` True
it "non-empty set is not a subset of empty set" $
fromList [1] `isSubsetOf` fromList [] `shouldBe` False
it "set is a subset of set with exact same elements" $
fromList [1, 2, 3] `isSubsetOf` fromList [1, 2, 3] `shouldBe` True
it "set is a subset of larger set with same elements" $
fromList [1, 2, 3] `isSubsetOf` fromList [4, 1, 2, 3] `shouldBe` True
it "set is not a subset of set that does not contain its elements" $
fromList [1, 2, 3] `isSubsetOf` fromList [4, 1, 3] `shouldBe` False
describe "isDisjointFrom" $ do
it "the empty set is disjoint with itself" $
fromList ([] :: [Integer]) `isDisjointFrom` fromList [] `shouldBe` True
it "empty set is disjoint with non-empty set" $
fromList [] `isDisjointFrom` fromList [1] `shouldBe` True
it "non-empty set is disjoint with empty set" $
fromList [1] `isDisjointFrom` fromList [] `shouldBe` True
it "sets are not disjoint if they share an element" $
fromList [1, 2] `isDisjointFrom` fromList [2, 3] `shouldBe` False
it "sets are disjoint if they share no elements" $
fromList [1, 2] `isDisjointFrom` fromList [3, 4] `shouldBe` True
describe "Eq" $ do
it "empty sets are equal" $
(fromList ([] :: [Integer]) == fromList []) `shouldBe` True
it "empty set is not equal to non-empty set" $
(fromList [] == fromList [1, 2, 3]) `shouldBe` False
it "non-empty set is not equal to empty set" $
(fromList [1, 2, 3] == fromList []) `shouldBe` False
it "sets with the same elements are equal" $
(fromList [1, 2] == fromList [2, 1]) `shouldBe` True
it "sets with different elements are not equal" $
(fromList [1, 2, 3] == fromList [1, 2, 4]) `shouldBe` False
it "set is not equal to larger set with same elements" $
(fromList [1, 2, 3] == fromList [1, 2, 3, 4]) `shouldBe` False
describe "insert" $ do
it "add to empty set" $
insert 3 (fromList []) `shouldBe` fromList [3]
it "add to non-empty set" $
insert 3 (fromList [1, 2, 4]) `shouldBe` fromList [1, 2, 3, 4]
it "adding an existing element does not change the set" $
insert 3 (fromList [1, 2, 3]) `shouldBe` fromList [1, 2, 3]
describe "intersection" $ do
it "intersection of two empty sets is an empty set" $
fromList ([] :: [Integer]) `intersection` fromList [] `shouldBe` fromList []
it "intersection of an empty set and non-empty set is an empty set" $
fromList [] `intersection` fromList [3, 2, 5] `shouldBe` fromList []
it "intersection of a non-empty set and an empty set is an empty set" $
fromList [1, 2, 3, 4] `intersection` fromList [] `shouldBe` fromList []
it "intersection of two sets with no shared elements is an empty set" $
fromList [1, 2, 3] `intersection` fromList [4, 5, 6] `shouldBe` fromList []
it "intersection of two sets with shared elements is a set of the shared elements" $
fromList [1, 2, 3, 4] `intersection` fromList [3, 2, 5] `shouldBe` fromList [2, 3]
describe "difference" $ do
it "difference of two empty sets is an empty set" $
fromList ([] :: [Integer]) `difference` fromList [] `shouldBe` fromList []
it "difference of empty set and non-empty set is an empty set" $
fromList [] `difference` fromList [3, 2, 5] `shouldBe` fromList []
it "difference of a non-empty set and an empty set is the non-empty set" $
fromList [1, 2, 3, 4] `difference` fromList [] `shouldBe` fromList [1, 2, 3, 4]
it "difference of two non-empty sets is a set of elements that are only in the first set" $
fromList [3, 2, 1] `difference` fromList [2, 4] `shouldBe` fromList [1, 3]
describe "union" $ do
it "union of empty sets is an empty set" $
fromList ([] :: [Integer]) `union` fromList [] `shouldBe` fromList []
it "union of an empty set and non-empty set is the non-empty set" $
fromList [] `union` fromList [2] `shouldBe` fromList [2]
it "union of a non-empty set and empty set is the non-empty set" $
fromList [1, 3] `union` fromList [] `shouldBe` fromList [1, 3]
it "union of non-empty sets contains all unique elements" $
fromList [1, 3] `union` fromList [2, 3] `shouldBe` fromList [3, 2, 1]
describe "track-specific tests" $ do
-- Track-specific test cases.
describe "delete" $
it "delete existing element" $
delete 2 (fromList [1, 2, 3]) `shouldBe` fromList [1, 3]
describe "size" $ do
it "size of an empty set is zero" $
size (fromList ([] :: [Integer])) `shouldBe` 0
it "size is the number of elements" $
size (fromList [1, 2, 3]) `shouldBe` 3
it "size doesn't count repetition in `fromList`" $
size (fromList [1, 2, 3, 2]) `shouldBe` 3
it "size does count inserted element" $
size (insert 3 (fromList [1, 2])) `shouldBe` 3
it "size doesn't count element removed by `delete`" $
size (delete 3 (fromList [1, 2, 3, 4])) `shouldBe` 3
describe "toList" $ do
it "an empty set has an empty list of elements" $
(sort . toList . fromList) ([] :: [Integer]) `shouldBe `[]
it "a set has the list of its elements" $
(sort . toList . fromList) [3, 1, 2] `shouldBe `[1, 2, 3]
it "a set doesn't keep repeated elements" $
(sort . toList . fromList) [3, 1, 2, 1] `shouldBe `[1, 2, 3]
-- 54d64bc5e2ff20c76b6c16138ed8ce97cf6f9981
|
exercism/xhaskell
|
exercises/practice/custom-set/test/Tests.hs
|
Haskell
|
mit
| 7,179
|
main = do cs <- getContents
putStr $ numbering cs
numbering :: String -> String
numbering cs = unlines $ map format $ zipLineNumber $ lines cs
zipLineNumber :: [String] -> [(String, String)]
zipLineNumber xs = zip (map show [1..]) xs
format (s1, s2) = s1++" "++s2
|
kazuya030/haskell-test
|
old/catn.hs
|
Haskell
|
mit
| 280
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLHeadingElement
(js_setAlign, setAlign, js_getAlign, getAlign, HTMLHeadingElement,
castToHTMLHeadingElement, gTypeHTMLHeadingElement)
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[\"align\"] = $2;" js_setAlign
:: HTMLHeadingElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadingElement.align Mozilla HTMLHeadingElement.align documentation>
setAlign ::
(MonadIO m, ToJSString val) => HTMLHeadingElement -> val -> m ()
setAlign self val = liftIO (js_setAlign (self) (toJSString val))
foreign import javascript unsafe "$1[\"align\"]" js_getAlign ::
HTMLHeadingElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadingElement.align Mozilla HTMLHeadingElement.align documentation>
getAlign ::
(MonadIO m, FromJSString result) => HTMLHeadingElement -> m result
getAlign self = liftIO (fromJSString <$> (js_getAlign (self)))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLHeadingElement.hs
|
Haskell
|
mit
| 1,809
|
module GHCJS.DOM.OESStandardDerivatives (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/OESStandardDerivatives.hs
|
Haskell
|
mit
| 52
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies, FlexibleContexts, ConstraintKinds #-}
module Database.Persist.Class.PersistUnique
(PersistUniqueRead(..)
,PersistUniqueWrite(..)
,getByValue
,insertBy
,insertUniqueEntity
,replaceUnique
,checkUnique
,onlyUnique)
where
import Database.Persist.Types
import Control.Exception (throwIO)
import Control.Monad (liftM)
import Control.Monad.IO.Class (liftIO, MonadIO)
import Data.List ((\\))
import Control.Monad.Trans.Reader (ReaderT)
import Database.Persist.Class.PersistStore
import Database.Persist.Class.PersistEntity
import Data.Monoid (mappend)
import Data.Text (unpack, Text)
-- | Queries against 'Unique' keys (other than the id 'Key').
--
-- Please read the general Persistent documentation to learn how to create
-- 'Unique' keys.
--
-- Using this with an Entity without a Unique key leads to undefined
-- behavior. A few of these functions require a /single/ 'Unique', so using
-- an Entity with multiple 'Unique's is also undefined. In these cases
-- persistent's goal is to throw an exception as soon as possible, but
-- persistent is still transitioning to that.
--
-- SQL backends automatically create uniqueness constraints, but for MongoDB
-- you must manually place a unique index on a field to have a uniqueness
-- constraint.
--
class (PersistCore backend, PersistStoreRead backend) =>
PersistUniqueRead backend where
-- | Get a record by unique key, if available. Returns also the identifier.
getBy
:: (MonadIO m, PersistRecordBackend record backend)
=> Unique record -> ReaderT backend m (Maybe (Entity record))
-- | Some functions in this module ('insertUnique', 'insertBy', and
-- 'replaceUnique') first query the unique indexes to check for
-- conflicts. You could instead optimistically attempt to perform the
-- operation (e.g. 'replace' instead of 'replaceUnique'). However,
--
-- * there is some fragility to trying to catch the correct exception and
-- determing the column of failure;
--
-- * an exception will automatically abort the current SQL transaction.
class (PersistUniqueRead backend, PersistStoreWrite backend) =>
PersistUniqueWrite backend where
-- | Delete a specific record by unique key. Does nothing if no record
-- matches.
deleteBy
:: (MonadIO m, PersistRecordBackend record backend)
=> Unique record -> ReaderT backend m ()
-- | Like 'insert', but returns 'Nothing' when the record
-- couldn't be inserted because of a uniqueness constraint.
insertUnique
:: (MonadIO m, PersistRecordBackend record backend)
=> record -> ReaderT backend m (Maybe (Key record))
insertUnique datum = do
conflict <- checkUnique datum
case conflict of
Nothing -> Just `liftM` insert datum
Just _ -> return Nothing
-- | Update based on a uniqueness constraint or insert:
--
-- * insert the new record if it does not exist;
-- * If the record exists (matched via it's uniqueness constraint), then update the existing record with the parameters which is passed on as list to the function.
--
-- Throws an exception if there is more than 1 uniqueness contraint.
upsert
:: (MonadIO m, PersistRecordBackend record backend)
=> record -- ^ new record to insert
-> [Update record] -- ^ updates to perform if the record already exists (leaving
-- this empty is the equivalent of performing a 'repsert' on a
-- unique key)
-> ReaderT backend m (Entity record) -- ^ the record in the database after the operation
upsert record updates = do
uniqueKey <- onlyUnique record
upsertBy uniqueKey record updates
-- | Update based on a given uniqueness constraint or insert:
--
-- * insert the new record if it does not exist;
-- * update the existing record that matches the given uniqueness contraint.
upsertBy
:: (MonadIO m, PersistRecordBackend record backend)
=> Unique record -- ^ uniqueness constraint to find by
-> record -- ^ new record to insert
-> [Update record] -- ^ updates to perform if the record already exists (leaving
-- this empty is the equivalent of performing a 'repsert' on a
-- unique key)
-> ReaderT backend m (Entity record) -- ^ the record in the database after the operation
upsertBy uniqueKey record updates = do
mrecord <- getBy uniqueKey
maybe (insertEntity record) (`updateGetEntity` updates) mrecord
where
updateGetEntity (Entity k _) upds =
(Entity k) `liftM` (updateGet k upds)
-- | Insert a value, checking for conflicts with any unique constraints. If a
-- duplicate exists in the database, it is returned as 'Left'. Otherwise, the
-- new 'Key is returned as 'Right'.
insertBy
:: (MonadIO m
,PersistUniqueWrite backend
,PersistRecordBackend record backend)
=> record -> ReaderT backend m (Either (Entity record) (Key record))
insertBy val = do
res <- getByValue val
case res of
Nothing -> Right `liftM` insert val
Just z -> return $ Left z
-- | Insert a value, checking for conflicts with any unique constraints. If a
-- duplicate exists in the database, it is left untouched. The key of the
-- existing or new entry is returned
_insertOrGet :: (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend)
=> record -> ReaderT backend m (Key record)
_insertOrGet val = do
res <- getByValue val
case res of
Nothing -> insert val
Just (Entity key _) -> return key
-- | Like 'insertEntity', but returns 'Nothing' when the record
-- couldn't be inserted because of a uniqueness constraint.
--
-- @since 2.7.1
insertUniqueEntity
:: (MonadIO m
,PersistRecordBackend record backend
,PersistUniqueWrite backend)
=> record -> ReaderT backend m (Maybe (Entity record))
insertUniqueEntity datum =
fmap (\key -> Entity key datum) `liftM` insertUnique datum
-- | Return the single unique key for a record.
onlyUnique
:: (MonadIO m
,PersistUniqueWrite backend
,PersistRecordBackend record backend)
=> record -> ReaderT backend m (Unique record)
onlyUnique record =
case onlyUniqueEither record of
Right u -> return u
Left us ->
requireUniques record us >>=
liftIO . throwIO . OnlyUniqueException . show . length
onlyUniqueEither
:: (PersistEntity record)
=> record -> Either [Unique record] (Unique record)
onlyUniqueEither record =
case persistUniqueKeys record of
[u] -> Right u
us -> Left us
-- | A modification of 'getBy', which takes the 'PersistEntity' itself instead
-- of a 'Unique' record. Returns a record matching /one/ of the unique keys. This
-- function makes the most sense on entities with a single 'Unique'
-- constructor.
getByValue
:: (MonadIO m
,PersistUniqueRead backend
,PersistRecordBackend record backend)
=> record -> ReaderT backend m (Maybe (Entity record))
getByValue record =
checkUniques =<< requireUniques record (persistUniqueKeys record)
where
checkUniques [] = return Nothing
checkUniques (x:xs) = do
y <- getBy x
case y of
Nothing -> checkUniques xs
Just z -> return $ Just z
requireUniques
:: (MonadIO m, PersistEntity record)
=> record -> [Unique record] -> m [Unique record]
requireUniques record [] = liftIO $ throwIO $ userError errorMsg
where
errorMsg = "getByValue: " `Data.Monoid.mappend` unpack (recordName record) `mappend` " does not have any Unique"
requireUniques _ xs = return xs
-- TODO: expose this to users
recordName
:: (PersistEntity record)
=> record -> Text
recordName = unHaskellName . entityHaskell . entityDef . Just
-- | Attempt to replace the record of the given key with the given new record.
-- First query the unique fields to make sure the replacement maintains
-- uniqueness constraints.
--
-- Return 'Nothing' if the replacement was made.
-- If uniqueness is violated, return a 'Just' with the 'Unique' violation
--
-- @since 1.2.2.0
replaceUnique
:: (MonadIO m
,Eq record
,Eq (Unique record)
,PersistRecordBackend record backend
,PersistUniqueWrite backend)
=> Key record -> record -> ReaderT backend m (Maybe (Unique record))
replaceUnique key datumNew = getJust key >>= replaceOriginal
where
uniqueKeysNew = persistUniqueKeys datumNew
replaceOriginal original = do
conflict <- checkUniqueKeys changedKeys
case conflict of
Nothing -> replace key datumNew >> return Nothing
(Just conflictingKey) -> return $ Just conflictingKey
where
changedKeys = uniqueKeysNew \\ uniqueKeysOriginal
uniqueKeysOriginal = persistUniqueKeys original
-- | Check whether there are any conflicts for unique keys with this entity and
-- existing entities in the database.
--
-- Returns 'Nothing' if the entity would be unique, and could thus safely be inserted.
-- on a conflict returns the conflicting key
checkUnique
:: (MonadIO m
,PersistRecordBackend record backend
,PersistUniqueRead backend)
=> record -> ReaderT backend m (Maybe (Unique record))
checkUnique = checkUniqueKeys . persistUniqueKeys
checkUniqueKeys
:: (MonadIO m
,PersistEntity record
,PersistUniqueRead backend
,PersistRecordBackend record backend)
=> [Unique record] -> ReaderT backend m (Maybe (Unique record))
checkUniqueKeys [] = return Nothing
checkUniqueKeys (x:xs) = do
y <- getBy x
case y of
Nothing -> checkUniqueKeys xs
Just _ -> return (Just x)
|
psibi/persistent
|
persistent/Database/Persist/Class/PersistUnique.hs
|
Haskell
|
mit
| 9,836
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
module Config (
asks
, ConfigHandler(..)
, Config(..)
, readConfigFromEnv
, convertServer
) where
import System.Environment
import qualified Data.Map as M
import Data.Maybe
import Control.Monad.Reader
import Control.Monad.Except
import Servant
import Servant.Utils.Enter
newtype ConfigHandler a = ConfigHandler {
runConfigHandler :: ReaderT Config (ExceptT ServantErr IO) a
} deriving ( Functor, Applicative, Monad, MonadReader Config,
MonadError ServantErr, MonadIO)
data Config = Config {
configDataDir :: !FilePath
, configStaticDir :: !FilePath
, configDataUri :: !String
, configPort :: !Int
, configOrigins :: !(Maybe [String])
, configUserFile :: !(Maybe FilePath)
, configNewCmdFile :: !(Maybe FilePath)
}
convertHandler :: Config -> ConfigHandler :~> Handler
convertHandler cfg = NT (Handler . flip runReaderT cfg . runConfigHandler)
convertServer :: Enter (Entered Handler ConfigHandler t) ConfigHandler Handler t
=> Config -> Entered Handler ConfigHandler t -> t
convertServer cfg = enter (convertHandler cfg)
readConfigFromEnv :: IO Config
readConfigFromEnv = do
env <- M.fromList <$> getEnvironment
return Config {
configDataDir = fromMaybe "data" $ M.lookup "MARKCO_DATA_DIR" env
, configStaticDir = fromMaybe "../client/dist" $ M.lookup "MARKCO_STATIC_DIR" env
, configDataUri = fromMaybe "/data" $ M.lookup "MARKCO_DATA_URI" env
, configPort = fromMaybe 8081 (read <$> M.lookup "MARKCO_PORT" env)
, configOrigins = words <$> M.lookup "MARKCO_ORIGINS" env
, configUserFile = M.lookup "MARKCO_USER_FILE" env
, configNewCmdFile = M.lookup "MARKCO_NEWCOMMANDS" env
}
|
lierdakil/markco
|
server/src/Config.hs
|
Haskell
|
mit
| 1,820
|
module Graphics.Urho3D.UI.Internal.Menu(
Menu
, menuCntx
, sharedMenuPtrCntx
, SharedMenu
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Context as C
import qualified Language.C.Types as C
import Graphics.Urho3D.Container.Ptr
import qualified Data.Map as Map
data Menu
menuCntx :: C.Context
menuCntx = mempty {
C.ctxTypesTable = Map.fromList [
(C.TypeName "Menu", [t| Menu |])
]
}
sharedPtrImpl "Menu"
|
Teaspot-Studio/Urho3D-Haskell
|
src/Graphics/Urho3D/UI/Internal/Menu.hs
|
Haskell
|
mit
| 471
|
{-# Language BangPatterns #-}
module Main where
import System.IO
import System.Environment
import System.Console.Haskeline
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Error
import Control.Monad.State
import Control.DeepSeq
import Data.Either
import Types
import Parser
import Interpreter
import Builtins
import Environment
processExpr :: LispVal -> Environment -> (LispVal, Environment, LispVal)
processExpr !expr !env = result
where
(!expr', !env') = expandInterpreter (expr, env)
!tco = tailCallOptimize env' expr'
(!ret, !env'') = evalInterpreter (tco, env')
!result = (ret, env'', tco)
processRepl :: String -> Environment -> IO Environment
processRepl line env = do
let expr = parseForm "<stdin>" $ C.pack line
let (ret, env'', tco) = processExpr expr env
print ret
return env''
runRepl :: Environment -> IO ()
runRepl env = runInputT defaultSettings (loop env)
where
loop env = do
minput <- getInputLine "hl> "
case minput of
Nothing -> outputStrLn "Goodbye."
Just input -> do
env' <- liftIO $ processRepl input env
loop env'
processFile :: Bool -> [LispVal] -> Environment -> IO Environment
processFile verbose !exprs !env = loop exprs env
where
loop ![] !env = return env
loop (expr:exprs) !env = do
let (ret, env'', tco) = processExpr expr env
if isLispError ret
then do
print "Error: "
print ret
return env''
else do
when verbose $ case tco of
(Definition _ _) -> return ()
_ -> print ret
loop exprs env''
runFile :: String -> Bool -> Environment -> IO Environment
runFile fname verbose !env = do
!source <- B.readFile fname
let !res = parseTopLevel fname source
case res of
Left err -> do
print err
return env
Right !exprs -> result where !result = processFile verbose exprs env
main :: IO ()
main = do
args <- getArgs
env <- liftM force runFile "stdlib.hl" False makeBuiltinEnvironment
let !env' = makeChildEnvironment env
case args of
[] -> runRepl env'
[fname] -> void $ runFile fname True env'
|
mhlakhani/hlisp
|
src/Main.hs
|
Haskell
|
mit
| 2,229
|
module Hasql.Postgres.Session.Execution where
import Hasql.Postgres.Prelude
import qualified Data.HashTable.IO as Hashtables
import qualified Database.PostgreSQL.LibPQ as PQ
import qualified Hasql.Postgres.Statement as Statement
import qualified Hasql.Postgres.TemplateConverter as TemplateConverter
import qualified Hasql.Postgres.Session.ResultProcessing as ResultProcessing
-- * Environment
-------------------------
type Env =
(PQ.Connection, IORef Word16, Hashtables.BasicHashTable LocalKey RemoteKey)
newEnv :: PQ.Connection -> IO Env
newEnv c =
(,,) <$> pure c <*> newIORef 0 <*> Hashtables.new
-- |
-- Local statement key.
data LocalKey =
LocalKey !ByteString ![Word32]
deriving (Show, Eq)
instance Hashable LocalKey where
hashWithSalt salt (LocalKey template types) =
hashWithSalt salt template
localKey :: ByteString -> [PQ.Oid] -> LocalKey
localKey t ol =
LocalKey t (map oidMapper ol)
where
oidMapper (PQ.Oid x) = fromIntegral x
-- |
-- Remote statement key.
type RemoteKey =
ByteString
data Error =
UnexpectedResult Text |
ErroneousResult Text |
UnparsableTemplate ByteString Text |
TransactionConflict
-- * Monad
-------------------------
newtype M r =
M (ReaderT Env (EitherT Error IO) r)
deriving (Functor, Applicative, Monad, MonadIO)
run :: Env -> M r -> IO (Either Error r)
run e (M m) =
runEitherT $ runReaderT m e
throwError :: Error -> M a
throwError = M . lift . left
prepare :: ByteString -> [PQ.Oid] -> M RemoteKey
prepare s tl =
do
(c, counter, table) <- M $ ask
let lk = localKey s tl
rk <- liftIO $ Hashtables.lookup table lk
($ rk) $ ($ return) $ maybe $ do
w <- liftIO $ readIORef counter
let rk = fromString $ show w
unitResult =<< do liftIO $ PQ.prepare c rk s (partial (not . null) tl)
liftIO $ Hashtables.insert table lk rk
liftIO $ writeIORef counter (succ w)
return rk
statement :: Statement.Statement -> M (Maybe PQ.Result)
statement s =
do
(c, _, _) <- M $ ask
let (template, params, preparable) = s
convertedTemplate <-
either (throwError . UnparsableTemplate template) return $
TemplateConverter.convert template
case preparable of
True -> do
let (tl, vl) = unzip params
key <- prepare convertedTemplate tl
liftIO $ PQ.execPrepared c key vl PQ.Binary
False -> do
let params' = map (\(t, v) -> (\(vb, vf) -> (t, vb, vf)) <$> v) params
liftIO $ PQ.execParams c convertedTemplate params' PQ.Binary
liftResultProcessing :: ResultProcessing.M a -> M a
liftResultProcessing m =
M $ ReaderT $ \(c, _, _) ->
EitherT $ fmap (either (Left . mapError) Right) $ ResultProcessing.run c m
where
mapError =
\case
ResultProcessing.UnexpectedResult t -> UnexpectedResult t
ResultProcessing.ErroneousResult t -> ErroneousResult t
ResultProcessing.TransactionConflict -> TransactionConflict
{-# INLINE unitResult #-}
unitResult :: Maybe PQ.Result -> M ()
unitResult =
liftResultProcessing . (ResultProcessing.unit <=< ResultProcessing.just)
{-# INLINE vectorResult #-}
vectorResult :: Maybe PQ.Result -> M (Vector (Vector (Maybe ByteString)))
vectorResult =
liftResultProcessing . (ResultProcessing.vector <=< ResultProcessing.just)
{-# INLINE countResult #-}
countResult :: Maybe PQ.Result -> M Word64
countResult =
liftResultProcessing . (ResultProcessing.count <=< ResultProcessing.just)
|
begriffs/hasql-postgres
|
library/Hasql/Postgres/Session/Execution.hs
|
Haskell
|
mit
| 3,467
|
module PureScript.Ide.Watcher where
import Control.Concurrent (threadDelay)
import Control.Concurrent.STM
import Control.Monad (forever, when)
import qualified Data.Map as M
import Data.Maybe (isJust)
import PureScript.Ide.Externs
import PureScript.Ide.Types
import System.FilePath
import System.FSNotify
reloadFile :: TVar PscState -> FilePath -> IO ()
reloadFile stateVar fp = do
Right (name, decls) <- readExternFile fp
reloaded <- atomically $ do
st <- readTVar stateVar
if isLoaded name st
then
loadModule name decls *> pure True
else
pure False
when reloaded $ putStrLn $ "Reloaded File at: " ++ fp
where
isLoaded name st = isJust (M.lookup name (pscStateModules st))
loadModule name decls = modifyTVar stateVar $ \x ->
x { pscStateModules = M.insert name decls (pscStateModules x)}
watcher :: TVar PscState -> FilePath -> IO ()
watcher stateVar fp = withManager $ \mgr -> do
_ <- watchTree mgr fp
(\ev -> takeFileName (eventPath ev) == "externs.json")
(reloadFile stateVar . eventPath)
forever (threadDelay 10000)
|
nwolverson/psc-ide
|
src/PureScript/Ide/Watcher.hs
|
Haskell
|
mit
| 1,218
|
import qualified Problem01 as P01
import qualified Problem02 as P02
import qualified Problem03 as P03
import qualified Problem04 as P04
import qualified Problem05 as P05
import qualified Problem06 as P06
import qualified Problem07 as P07
import qualified Problem08 as P08
import qualified Problem14 as P14
cine = False :: Bool
main = P14.partB
--main = do
-- putStrLn "Day 1:"
-- putStr "\tPart A: "
-- P01.partA
-- putStr "\tPart B: "
-- P01.partB
--
-- putStrLn "Day 2:"
-- putStr "\tPart A: "
-- P02.partA
-- putStr "\tPart B: "
-- P02.partB
--
-- putStrLn "Day 3:"
-- putStr "\tPart A: "
-- P03.partA
-- putStr "\tPart B: "
-- P03.partB
--
-- putStrLn "Day 4:"
-- putStr "\tPart A: "
-- P04.partA
-- putStr "\tPart B: "
-- P04.partB
--
-- putStrLn "Day 5:"
-- putStr "\tPart A: "
-- P05.partA
-- putStr "\tPart B: "
-- if cine then P05.partBCine else P05.partB
--
-- putStrLn "Day 6:"
-- putStr "\tPart A: "
-- P06.partA
-- putStr "\tPart B: "
-- P06.partB
--
-- putStrLn "Day 7:"
-- putStr "\tPart A: "
-- P07.partA
-- putStr "\tPart B: "
-- P07.partB
--
-- putStrLn "Day 8:"
-- putStr "\tPart A: "
-- P08.partA
-- putStrLn "\tPart B: "
-- P08.partB
|
edwardwas/adventOfCodeTwo
|
src/Main.hs
|
Haskell
|
mit
| 1,278
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Brainfuck.Cell
( Cell
, Math (..)
, stepCell
) where
import ClassyPrelude
import Data.Monoid (Sum)
type Cell = Sum Word8
data Math = Inc | Dec
deriving Show
stepCell :: Math -> (Cell -> Cell)
stepCell Inc = fmap $ \case
255 -> 0
s -> s + 1
stepCell Dec = fmap $ \case
0 -> 255
s -> s - 1
|
expede/brainfucker
|
src/Brainfuck/Cell.hs
|
Haskell
|
apache-2.0
| 412
|
cnt' n ('O':'I':xs) = cnt' (n+1) xs
cnt' n x = n
cnt [] = []
cnt ('I':xs) =
let n = cnt' 0 xs
r = drop (2*n) xs
in
n:(cnt r)
cnt ('O':xs) = cnt xs
ans ("0":_) = []
ans (n:_:s:xs) =
let n' = read n :: Int
r = cnt s
a = sum $ map (\x -> if x >= n' then (x-n'+1) else 0) r
in
a:(ans xs)
main = do
c <- getContents
let i = lines c
o = ans i
mapM_ print o
|
a143753/AOJ
|
0538.hs
|
Haskell
|
apache-2.0
| 405
|
{-# LANGUAGE BangPatterns, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Messages.Type (Type(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data Type = GET
| PUT
| REMOVE
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable Type
instance Prelude'.Bounded Type where
minBound = GET
maxBound = REMOVE
instance P'.Default Type where
defaultValue = GET
toMaybe'Enum :: Prelude'.Int -> P'.Maybe Type
toMaybe'Enum 1 = Prelude'.Just GET
toMaybe'Enum 2 = Prelude'.Just PUT
toMaybe'Enum 3 = Prelude'.Just REMOVE
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum Type where
fromEnum GET = 1
fromEnum PUT = 2
fromEnum REMOVE = 3
toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Messages.Type") . toMaybe'Enum
succ GET = PUT
succ PUT = REMOVE
succ _ = Prelude'.error "hprotoc generated code: succ failure for type Messages.Type"
pred PUT = GET
pred REMOVE = PUT
pred _ = Prelude'.error "hprotoc generated code: pred failure for type Messages.Type"
instance P'.Wire Type where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB Type
instance P'.MessageAPI msg' (msg' -> Type) Type where
getVal m' f' = f' m'
instance P'.ReflectEnum Type where
reflectEnum = [(1, "GET", GET), (2, "PUT", PUT), (3, "REMOVE", REMOVE)]
reflectEnumInfo _
= P'.EnumInfo (P'.makePNF (P'.pack ".messages.Type") [] ["Messages"] "Type") ["Messages", "Type.hs"]
[(1, "GET"), (2, "PUT"), (3, "REMOVE")]
instance P'.TextType Type where
tellT = P'.tellShow
getT = P'.getRead
|
JDrit/MemDB
|
client.hs/src/Messages/Type.hs
|
Haskell
|
apache-2.0
| 2,139
|
module Tables.A268057Spec (main, spec) where
import Test.Hspec
import Tables.A268057 (a268057)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A268057" $
it "correctly computes the first 20 elements" $
take 20 (map a268057 [1..]) `shouldBe` expectedValue where
expectedValue = [1,1,1,1,2,1,1,1,2,1,1,2,3,2,1,1,1,1,2,2]
|
peterokagey/haskellOEIS
|
test/Tables/A268057Spec.hs
|
Haskell
|
apache-2.0
| 347
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QResizeEvent.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:20
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QResizeEvent (
QqqResizeEvent(..), QqResizeEvent(..)
,QqqResizeEvent_nf(..), QqResizeEvent_nf(..)
,qoldSize, oldSize
,qResizeEvent_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqqResizeEvent x1 where
qqResizeEvent :: x1 -> IO (QResizeEvent ())
class QqResizeEvent x1 where
qResizeEvent :: x1 -> IO (QResizeEvent ())
instance QqResizeEvent ((QResizeEvent t1)) where
qResizeEvent (x1)
= withQResizeEventResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QResizeEvent cobj_x1
foreign import ccall "qtc_QResizeEvent" qtc_QResizeEvent :: Ptr (TQResizeEvent t1) -> IO (Ptr (TQResizeEvent ()))
instance QqqResizeEvent ((QSize t1, QSize t2)) where
qqResizeEvent (x1, x2)
= withQResizeEventResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QResizeEvent1 cobj_x1 cobj_x2
foreign import ccall "qtc_QResizeEvent1" qtc_QResizeEvent1 :: Ptr (TQSize t1) -> Ptr (TQSize t2) -> IO (Ptr (TQResizeEvent ()))
instance QqResizeEvent ((Size, Size)) where
qResizeEvent (x1, x2)
= withQResizeEventResult $
withCSize x1 $ \csize_x1_w csize_x1_h ->
withCSize x2 $ \csize_x2_w csize_x2_h ->
qtc_QResizeEvent2 csize_x1_w csize_x1_h csize_x2_w csize_x2_h
foreign import ccall "qtc_QResizeEvent2" qtc_QResizeEvent2 :: CInt -> CInt -> CInt -> CInt -> IO (Ptr (TQResizeEvent ()))
class QqqResizeEvent_nf x1 where
qqResizeEvent_nf :: x1 -> IO (QResizeEvent ())
class QqResizeEvent_nf x1 where
qResizeEvent_nf :: x1 -> IO (QResizeEvent ())
instance QqResizeEvent_nf ((QResizeEvent t1)) where
qResizeEvent_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QResizeEvent cobj_x1
instance QqqResizeEvent_nf ((QSize t1, QSize t2)) where
qqResizeEvent_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QResizeEvent1 cobj_x1 cobj_x2
instance QqResizeEvent_nf ((Size, Size)) where
qResizeEvent_nf (x1, x2)
= withObjectRefResult $
withCSize x1 $ \csize_x1_w csize_x1_h ->
withCSize x2 $ \csize_x2_w csize_x2_h ->
qtc_QResizeEvent2 csize_x1_w csize_x1_h csize_x2_w csize_x2_h
qoldSize :: QResizeEvent a -> (()) -> IO (QSize ())
qoldSize x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QResizeEvent_oldSize cobj_x0
foreign import ccall "qtc_QResizeEvent_oldSize" qtc_QResizeEvent_oldSize :: Ptr (TQResizeEvent a) -> IO (Ptr (TQSize ()))
oldSize :: QResizeEvent a -> (()) -> IO (Size)
oldSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QResizeEvent_oldSize_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QResizeEvent_oldSize_qth" qtc_QResizeEvent_oldSize_qth :: Ptr (TQResizeEvent a) -> Ptr CInt -> Ptr CInt -> IO ()
instance Qqqsize (QResizeEvent a) (()) (IO (QSize ())) where
qqsize x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QResizeEvent_size cobj_x0
foreign import ccall "qtc_QResizeEvent_size" qtc_QResizeEvent_size :: Ptr (TQResizeEvent a) -> IO (Ptr (TQSize ()))
instance Qqsize (QResizeEvent a) (()) (IO (Size)) where
qsize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QResizeEvent_size_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QResizeEvent_size_qth" qtc_QResizeEvent_size_qth :: Ptr (TQResizeEvent a) -> Ptr CInt -> Ptr CInt -> IO ()
qResizeEvent_delete :: QResizeEvent a -> IO ()
qResizeEvent_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QResizeEvent_delete cobj_x0
foreign import ccall "qtc_QResizeEvent_delete" qtc_QResizeEvent_delete :: Ptr (TQResizeEvent a) -> IO ()
|
keera-studios/hsQt
|
Qtc/Gui/QResizeEvent.hs
|
Haskell
|
bsd-2-clause
| 4,324
|
{-| Implementation of the Ganeti Query2 export queries.
-}
{-
Copyright (C) 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Query.Export
( Runtime
, fieldsMap
, collectLiveData
) where
import Control.Monad (liftM)
import qualified Data.Map as Map
import Ganeti.Objects
import Ganeti.Rpc
import Ganeti.Query.Language
import Ganeti.Query.Common
import Ganeti.Query.Types
-- | The parsed result of the ExportList. This is a bit tricky, in
-- that we already do parsing of the results in the RPC calls, so the
-- runtime type is a plain 'ResultEntry', as we have just one type.
type Runtime = ResultEntry
-- | Small helper for rpc to rs.
rpcErrToRs :: RpcError -> ResultEntry
rpcErrToRs err = ResultEntry (rpcErrorToStatus err) Nothing
-- | Helper for extracting fields from RPC result.
rpcExtractor :: Node -> Either RpcError RpcResultExportList
-> [(Node, ResultEntry)]
rpcExtractor node (Right res) =
[(node, rsNormal path) | path <- rpcResExportListExports res]
rpcExtractor node (Left err) = [(node, rpcErrToRs err)]
-- | List of all node fields.
exportFields :: FieldList Node Runtime
exportFields =
[ (FieldDefinition "node" "Node" QFTText "Node name",
FieldRuntime (\_ n -> rsNormal $ nodeName n), QffHostname)
, (FieldDefinition "export" "Export" QFTText "Export name",
FieldRuntime (curry fst), QffNormal)
]
-- | The node fields map.
fieldsMap :: FieldMap Node Runtime
fieldsMap =
Map.fromList $ map (\v@(f, _, _) -> (fdefName f, v)) exportFields
-- | Collect live data from RPC query if enabled.
--
-- Note that this function is \"funny\": the returned rows will not be
-- 1:1 with the input, as nodes without exports will be pruned,
-- whereas nodes with multiple exports will be listed multiple times.
collectLiveData:: Bool -> ConfigData -> [Node] -> IO [(Node, Runtime)]
collectLiveData False _ nodes =
return [(n, rpcErrToRs $ RpcResultError "Live data disabled") | n <- nodes]
collectLiveData True _ nodes =
concatMap (uncurry rpcExtractor) `liftM`
executeRpcCall nodes RpcCallExportList
|
apyrgio/snf-ganeti
|
src/Ganeti/Query/Export.hs
|
Haskell
|
bsd-2-clause
| 3,309
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
-- | A module collecting the toy grammars used for testing and
-- unit test examples themselves.
module NLP.TAG.Vanilla.Tests
( Test (..)
, TestRes (..)
, mkGram1
, gram1Tests
, mkGram2
, gram2Tests
, mkGram3
, gram3Tests
, mkGram4
, gram4Tests
-- Temporary
, mkGram5
, mkGramAcidRains
, mkGramSetPoints
, Gram
, WeightedGram
, testTree
) where
import Control.Applicative ((<$>), (<*>))
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import Test.Tasty (TestTree, testGroup, withResource)
import Test.HUnit (Assertion, (@?=))
import Test.Tasty.HUnit (testCase)
import NLP.TAG.Vanilla.Core (Cost)
import NLP.TAG.Vanilla.Tree (Tree (..), AuxTree (..))
import NLP.TAG.Vanilla.Rule (Rule)
import qualified NLP.TAG.Vanilla.Rule as R
import qualified NLP.TAG.Vanilla.WRule as W
import NLP.TAG.Vanilla.SubtreeSharing (compile)
---------------------------------------------------------------------
-- Prerequisites
---------------------------------------------------------------------
type Tr = Tree String String
type AuxTr = AuxTree String String
type Rl = Rule String String
type WRl = W.Rule String String
-- | A compiled grammar.
type Gram = S.Set Rl
-- | A compiled grammar with weights.
type WeightedTree = (Tr, Cost)
type WeightedAux = (AuxTr, Cost)
type WeightedGram = S.Set WRl
---------------------------------------------------------------------
-- Tests
---------------------------------------------------------------------
-- | A single test case.
data Test = Test {
-- | Starting symbol
startSym :: String
-- | The sentence to parse (list of words)
, testSent :: [String]
-- | The expected recognition result
, testRes :: TestRes
} deriving (Show, Eq, Ord)
-- | The expected test result. The set of parsed trees can be optionally
-- specified.
data TestRes
= No
-- ^ No parse
| Yes
-- ^ Parse
| Trees (S.Set Tr)
-- ^ Parsing results
| WeightedTrees (M.Map Tr Cost)
-- ^ Parsing results with weights
deriving (Show, Eq, Ord)
---------------------------------------------------------------------
-- Grammar1
---------------------------------------------------------------------
tom :: Tr
tom = INode "NP"
[ INode "N"
[FNode "Tom"]
]
sleeps :: Tr
sleeps = INode "S"
[ INode "NP" []
, INode "VP"
[INode "V" [FNode "sleeps"]]
]
caught :: Tr
caught = INode "S"
[ INode "NP" []
, INode "VP"
[ INode "V" [FNode "caught"]
, INode "NP" [] ]
]
almost :: AuxTr
almost = AuxTree (INode "V"
[ INode "Ad" [FNode "almost"]
, INode "V" []
]) [1]
quickly :: AuxTr
quickly = AuxTree (INode "V"
[ INode "Ad" [FNode "quickly"]
, INode "V" []
]) [1]
a :: Tr
a = INode "D" [FNode "a"]
mouse :: Tr
mouse = INode "NP"
[ INode "D" []
, INode "N"
[FNode "mouse"]
]
-- | Compile the first grammar.
mkGram1 :: IO Gram
mkGram1 = compile $
map Left [tom, sleeps, caught, a, mouse] ++
map Right [almost, quickly]
---------------------------------------------------------------------
-- Grammar1 Tests
---------------------------------------------------------------------
gram1Tests :: [Test]
gram1Tests =
-- group 1
[ Test "S" ["Tom", "sleeps"] . Trees . S.singleton $
INode "S"
[ INode "NP"
[ INode "N"
[FNode "Tom"]
]
, INode "VP"
[INode "V" [FNode "sleeps"]]
]
, Test "S" ["Tom"] No
, Test "NP" ["Tom"] Yes
-- group 2
, Test "S" ["Tom", "almost", "caught", "a", "mouse"] . Trees . S.singleton $
INode "S"
[ INode "NP"
[ INode "N"
[ FNode "Tom" ] ]
, INode "VP"
[ INode "V"
[ INode "Ad"
[FNode "almost"]
, INode "V"
[FNode "caught"]
]
, INode "NP"
[ INode "D"
[FNode "a"]
, INode "N"
[FNode "mouse"]
]
]
]
, Test "S" ["Tom", "caught", "almost", "a", "mouse"] No
, Test "S" ["Tom", "quickly", "almost", "caught", "Tom"] Yes
, Test "S" ["Tom", "caught", "a", "mouse"] Yes
, Test "S" ["Tom", "caught", "Tom"] Yes
, Test "S" ["Tom", "caught", "a", "Tom"] No
, Test "S" ["Tom", "caught"] No
, Test "S" ["caught", "a", "mouse"] No ]
---------------------------------------------------------------------
-- Grammar2
---------------------------------------------------------------------
alpha :: Tr
alpha = INode "S"
[ INode "X"
[FNode "e"] ]
beta1 :: AuxTr
beta1 = AuxTree (INode "X"
[ FNode "a"
, INode "X"
[ INode "X" []
, FNode "a" ] ]
) [1,0]
beta2 :: AuxTr
beta2 = AuxTree (INode "X"
[ FNode "b"
, INode "X"
[ INode "X" []
, FNode "b" ] ]
) [1,0]
mkGram2 :: IO Gram
mkGram2 = compile $
map Left [alpha] ++
map Right [beta1, beta2]
---------------------------------------------------------------------
-- Grammar2 Tests
---------------------------------------------------------------------
-- | What we test is not really a copy language but rather a
-- language in which there is always the same number of `a`s and
-- `b`s on the left and on the right of the empty `e` symbol.
-- To model the real copy language with a TAG we would need to
-- use either adjunction constraints or feature structures.
gram2Tests :: [Test]
gram2Tests =
[ Test "S" (words "a b e a b") Yes
, Test "S" (words "a b e a a") No
, Test "S" (words "a b a b a b a b e a b a b a b a b") Yes
, Test "S" (words "a b a b a b a b e a b a b a b a ") No
, Test "S" (words "a b e b a") Yes
, Test "S" (words "b e a") No
, Test "S" (words "a b a b") No ]
---------------------------------------------------------------------
-- Grammar 3
---------------------------------------------------------------------
mkGram3 :: IO Gram
mkGram3 = compile $
map Left [sent] ++
map Right [xtree]
where
sent = INode "S"
[ FNode "p"
, INode "X"
[FNode "e"]
, FNode "b" ]
xtree = AuxTree (INode "X"
[ FNode "a"
, INode "X" []
, FNode "b" ]
) [1]
-- | Here we check that the auxiliary tree must be fully
-- recognized before it can be adjoined.
gram3Tests :: [Test]
gram3Tests =
[ Test "S" (words "p a e b b") Yes
, Test "S" (words "p a e b") No ]
---------------------------------------------------------------------
-- Grammar 4 (make a cat drink)
---------------------------------------------------------------------
make1 :: WeightedTree
make1 = ( INode "S"
[ INode "VP"
[ INode "V" [FNode "make"]
, INode "NP" [] ]
], 1)
make2 :: WeightedTree
make2 = ( INode "S"
[ INode "VP"
[ INode "V" [FNode "make"]
, INode "NP" []
, INode "VP" [] ]
], 1)
a' :: WeightedTree
a' = (INode "D" [FNode "a"], 1)
cat :: WeightedTree
cat = ( INode "NP"
[ INode "D" []
, INode "N"
[FNode "cat"]
], 1)
drink :: WeightedTree
drink = ( INode "VP"
[ INode "V"
[FNode "drink"]
], 1)
catDrink :: WeightedTree
catDrink = ( INode "NP"
[ INode "D" []
, INode "N"
[FNode "cat"]
, INode "N"
[FNode "drink"]
], 0)
almostW :: WeightedAux
almostW = ( AuxTree (INode "V"
[ INode "Ad" [FNode "almost"]
, INode "V" []
]) [1], 1)
-- | Compile the first grammar.
mkGram4 :: IO WeightedGram
mkGram4 = W.compileWeights $
map Left
[ make1, make2, a', cat
, drink, catDrink ] ++
map Right [almostW]
-- | Here we check that the auxiliary tree must be fully
-- recognized before it can be adjoined.
gram4Tests :: [Test]
gram4Tests =
[ Test "S" ["make", "a", "cat", "drink"] . WeightedTrees $ M.fromList
[ ( INode "S"
[ INode "VP"
[ INode "V" [FNode "make"]
, INode "NP"
[ INode "D" [FNode "a"]
, INode "N" [FNode "cat"] ]
, INode "VP"
[ INode "V" [FNode "drink"] ]
]
], 4)
, ( INode "S"
[ INode "VP"
[ INode "V" [FNode "make"]
, INode "NP"
[ INode "D" [FNode "a"]
, INode "N" [FNode "cat"]
, INode "N" [FNode "drink"] ]
]
], 2)
]
]
---------------------------------------------------------------------
-- Grammar 5 (give a lift)
---------------------------------------------------------------------
-- | Compile the first grammar.
mkGram5 :: IO WeightedGram
mkGram5 = W.compileWeights $
map Left trees ++ map Right auxTrees
where
trees = concat
[ det "a", det "my", det "your" , det "the" , noun "lift"
, noun "car", noun "house", pron "me"
, give1, give2 , give_a_lift_to, give_a_lift
, train_station, noun "train", noun "station" ]
auxTrees = concat
[ ppVPMod "with", ppVPMod "to"
, ppNPMod "with", ppNPMod "to"
, adj "main", adj "nearest" ]
det x = single (INode "D" [FNode x], 1)
noun x =
[ ( INode "NP"
[ INode "D" []
, INode "N"
[FNode x]
], 1 )
, ( INode "NP"
[ INode "D" []
, INode "N"
[ FNode x
, INode "N" [] ]
], 1 )
, (INode "N" [FNode x], 1) ]
pron x = single ( INode "NP"
[ INode "Pron"
[FNode x]
], 1)
give1 = single ( INode "VP"
[ INode "V" [FNode "give"]
, INode "NP" []
, INode "NP" []
], 1)
give2 = single ( INode "VP"
[ INode "V" [FNode "give"]
, INode "NP" []
, INode "PP"
[ INode "P" [FNode "to"]
, INode "NP" [] ]
], 1)
give_a_lift_to = single ( INode "VP"
[ INode "V-MWE" [FNode "give"]
, INode "NP" []
, INode "NP"
[ INode "D" [FNode "a"]
, INode "N" [FNode "lift"] ]
, INode "PP"
[ INode "P" [FNode "to"]
, INode "NP" [] ]
], 1)
give_a_lift = single ( INode "VP"
[ INode "V-MWE" [FNode "give"]
, INode "NP" []
, INode "NP"
[ INode "D" [FNode "a"]
, INode "N" [FNode "lift"] ]
], 1)
ppVPMod x = single ( AuxTree (INode "VP"
[ INode "VP" []
, INode "PP"
[ INode "P" [FNode x]
, INode "NP" [] ]
]) [0], 1)
ppNPMod x = single ( AuxTree (INode "NP"
[ INode "NP" []
, INode "PP"
[ INode "P" [FNode x]
, INode "NP" [] ]
]) [0], 1)
train_station = single ( INode "NP"
[ INode "D" []
, INode "N"
[ FNode "train"
, FNode "station" ]
], 1)
adj x = single ( AuxTree (INode "N"
[ INode "Adj" [FNode x]
, INode "N" []
]) [1], 1)
-- Utils
single x = [x]
---------------------------------------------------------------------
-- Misc Grammars
---------------------------------------------------------------------
-- | Compile the first grammar and return two results: a simple factorized
-- grammar (fst) and factorized grammar with subtree sharing (snd).
mkGramAcidRains :: IO (Gram, Gram)
mkGramAcidRains = do
gramPlain <- R.compile trees
gramShare <- compile trees
return (gramPlain, gramShare)
where
trees =
-- map Left [rainsN, rainsV, acid_rains, ghana] ++
-- map Right [ppMod "in" "S", ppMod "in" "NP"]
map Left [rainsN, rainsV, acidNP, acid_rains] ++
map Right [nounM "acid" "A", nounM "acid" "N"]
rainsN = INode "NP"
[ INode "N"
[FNode "rains"]
]
rainsV = INode "S"
[ INode "NP" []
, INode "VP"
[ INode "V"
[FNode "rains"]
]
]
acidNP = INode "NP"
[ INode "N"
[FNode "acid"]
]
acid_rains = INode "NP"
[ INode "N" [FNode "acid"]
, INode "N" [FNode "rains"]
]
nounM x cat = AuxTree (INode "N"
[ INode cat [FNode x]
, INode "N" []
]) [1]
-- ghana = INode "NP"
-- [ INode "N"
-- [FNode "Ghana"]
-- ]
-- ppMod x cat = AuxTree (INode cat
-- [ INode cat []
-- , INode "PP"
-- [ INode "P" [FNode x]
-- , INode "NP" [] ]
-- ]) [0]
-- | Compile the first grammar and return two results: a simple factorized
-- grammar (fst) and factorized grammar with subtree sharing (snd).
mkGramSetPoints :: IO Gram
mkGramSetPoints = do
-- gramPlain <- R.compile trees
gramShare <- compile trees
-- return (gramPlain, gramShare)
return gramShare
where
trees =
( map Left
-- [ nounNoDet "set"
[ nounNoDet "points"
, imperVerbNPprepNP "set" "in"
-- , transVerb "set"
-- , inTransVerb "lunches"
-- , verbNPatNP "points"
, nounNounComp "set" "points" ] ) ++
( map Right
[ nounLeftMod "set" "Adj"
, nounLeftMod "set" "N"
, nounLeftMod "set" "Ppart" ] )
nounNoDet x = INode "NP"
[ INode "N"
[FNode x]
]
transVerb x = INode "S"
[ INode "NP" []
, INode "VP"
[ INode "V"
[FNode x]
, INode "NP" []
]
]
inTransVerb x = INode "S"
[ INode "NP" []
, INode "VP"
[ INode "V"
[FNode x]
]
]
transVerbImper x = INode "S"
[ INode "VP"
[ INode "V"
[FNode x]
, INode "NP" []
]
]
imperVerbNPprepNP v p = INode "S"
[ INode "VP"
[ INode "V"
[FNode v]
, INode "NP" []
, INode "PP"
[ INode "P" [FNode p]
, INode "NP" [] ]
]
]
verbNPatNP x = INode "S"
[ INode "NP" []
, INode "VP"
[ INode "V"
[FNode x]
, INode "NP" []
, INode "PP"
[ INode "P" [FNode "at"]
, INode "NP" [] ]
]
]
nounLeftMod x cat = AuxTree (INode "N"
[ INode cat [FNode x]
, INode "N" []
]) [1]
nounNounComp x y = INode "NP"
[ INode "N" [FNode x]
, INode "N" [FNode y]
]
adjNounComp x y = INode "NP"
[ INode "Adj" [FNode x]
, INode "N" [FNode y]
]
---------------------------------------------------------------------
-- Resources
---------------------------------------------------------------------
-- | Compiled grammars.
data Res = Res
{ gram1 :: Gram
, gram2 :: Gram
, gram3 :: Gram
, gram4 :: WeightedGram }
-- | Construct the shared resource (i.e. the grammars) used in
-- tests.
mkGrams :: IO Res
mkGrams = Res <$> mkGram1 <*> mkGram2 <*> mkGram3 <*> mkGram4
---------------------------------------------------------------------
-- Test Tree
---------------------------------------------------------------------
-- | All the tests of the parsing algorithm.
testTree
:: String
-- ^ Name of the tested module
-> (Gram -> String -> [String] -> IO Bool)
-- ^ Recognition function
-> Maybe (Gram -> String -> [String] -> IO (S.Set Tr))
-- ^ Parsing function (optional)
-> Maybe (WeightedGram -> String -> [String] -> IO (M.Map Tr Cost))
-- ^ Parsing with weights (optional)
-> TestTree
testTree modName reco parse parseW = withResource mkGrams (const $ return ()) $
\resIO -> testGroup modName $
map (testIt resIO gram1) gram1Tests ++
map (testIt resIO gram2) gram2Tests ++
map (testIt resIO gram3) gram3Tests ++
map (testWe resIO gram4) gram4Tests
where
testIt resIO getGram test = testCase (show test) $ do
gram <- getGram <$> resIO
doTest gram test
testWe resIO getGram test = testCase (show test) $ do
gram <- getGram <$> resIO
doTestW gram test
doTest gram test@Test{..} = case (parse, testRes) of
(Nothing, _) ->
reco gram startSym testSent @@?= simplify testRes
(Just pa, Trees ts) ->
pa gram startSym testSent @@?= ts
_ ->
reco gram startSym testSent @@?= simplify testRes
doTestW gram test@Test{..} = case (parseW, parse, testRes) of
-- (Nothing, Nothing, _) ->
-- reco gram startSym testSent @@?= simplify testRes
(_, Just pa, Trees ts) ->
pa (unWeighGram gram) startSym testSent @@?= ts
(Just pa, _, WeightedTrees ts) ->
fmap smoothOut (pa gram startSym testSent) @@?= ts
(Nothing, Just pa, WeightedTrees ts) ->
pa (unWeighGram gram) startSym testSent @@?= remWeights ts
_ ->
reco (unWeighGram gram) startSym testSent @@?= simplify testRes
smoothOut = fmap $ roundWeight 5
roundWeight n x = fromInteger (round $ x * (10^n)) / (10.0^^n)
remWeights = M.keysSet
unWeighGram
= S.fromList
. map W.unWeighRule
. S.toList
simplify No = False
simplify Yes = True
simplify (Trees _) = True
simplify (WeightedTrees _)
= True
---------------------------------------------------------------------
-- Utils
---------------------------------------------------------------------
(@@?=) :: (Show a, Eq a) => IO a -> a -> Assertion
mx @@?= y = do
x <- mx
x @?= y
|
kawu/tag-vanilla
|
src/NLP/TAG/Vanilla/Tests.hs
|
Haskell
|
bsd-2-clause
| 18,182
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
module NLP.Albemarle.Cooccur
( -- * Sliding Window
geometricSkips,
harmonicSkips,
packIDs,
unpackIDs,
cooccurify,
wordSlice,
frequency,
wordFrequency,
probability,
predict
) where
import Lens.Micro
import Lens.Micro.TH
import qualified Data.IntMap.Strict as IntMap
import Data.Bits
import Data.Maybe
import Debug.Trace
type Cooccur = IntMap.IntMap Double
-- | Windowing function for skip-grams
geometricSkips :: Double -- ^ Exponential decay with distance
-> Int -- ^ Window radius (actual size is 2*radius + 1)
-> [a] -- ^ Document
-> [(a, a, Double)] -- ^ (Source, target, weight) triple
geometricSkips dropoff radius [] = []
geometricSkips dropoff radius (s:ss) =
-- Tack on source and get two tuples each, because it is symmetric
(concatMap (\(t, w) -> [(s, t, w), (t, s, w)])
$ zip ss -- Pair the weights with the upcoming words
$ take radius -- Limit to a horizon
$ iterate (dropoff*) 1) -- The decaying weights
++ geometricSkips dropoff radius ss -- Repeat for the next word
-- | Windowing function for skip-grams
harmonicSkips :: Int -- ^ Window radius (actual size is 2*radius + 1)
-> [a] -- ^ Document
-> [(a, a, Double)] -- ^ (Source, target, weight) triple
harmonicSkips radius [] = []
harmonicSkips radius (s:ss) =
(concatMap (\(t, w) -> [(s, t, w), (t, s, w)])
$ zip ss
$ fmap (1/) [1..fromIntegral radius])
++ harmonicSkips radius ss
-- | This is dangerous but great for Intmaps: convert two 32 bit integers into
-- a single packed 64 bit integer. But Intmaps can't guarantee 64 bits, so
-- this will not work on 32-bit machines. Be warned!
packIDs :: Int -> Int -> Int
packIDs a b = (a `shiftL` 32) .|. b
-- | This is dangerous but great for Intmaps: convert one 64 bit integer into
-- two 32 bit integers. But Intmaps can't guarantee 64 bits, so
-- this will not work on 32-bit machines. Be warned!
unpackIDs :: Int -> (Int, Int)
unpackIDs a = (a `shiftR` 32, a .&. 0x00000000FFFFFFFF)
-- | Make a word-word cooccurance matrix out of a series of weighted
-- cooccurances (like harmonicSkips will make for you)
cooccurify :: [(Int, Int, Double)] -> Cooccur
cooccurify = IntMap.fromListWith (+)
. fmap (\(s, t, w) -> (packIDs s t, w))
-- | Get all of the frequencies associated with a source word
wordSlice :: Int -> Cooccur -> Cooccur
wordSlice a = let
start = packIDs a 0 -- Will be inclusive
end = packIDs (a+1) 0 -- Will be exclusive
split target c = let
(left, mayv, right) = IntMap.splitLookup target c
in (maybe left (\v -> IntMap.insert target v left) mayv, right)
in snd . split start -- after the beginning
. fst . split end -- before the end
-- | Get the frequency of a specific word pair.
frequency :: Int -> Int -> Cooccur -> Double
frequency a b = fromMaybe 0 . IntMap.lookup (packIDs a b)
wordFrequency :: Int -> Cooccur -> Double
wordFrequency wd = sum . fmap snd . IntMap.toList . wordSlice wd
probability :: Int -> Int -> Cooccur -> Double
probability a b cooccur = let
denom = wordFrequency a cooccur
in if denom == 0 then 0 else frequency a b cooccur / denom
predict :: Int -> Cooccur -> [(Int, Double)]
predict wd cooccur = let
normalize = wordFrequency wd cooccur
in fmap (\(p, f) -> (snd $ unpackIDs p, f/normalize))
$ IntMap.toList $ wordSlice wd cooccur
|
SeanTater/albemarle
|
src/NLP/Albemarle/Cooccur.hs
|
Haskell
|
bsd-3-clause
| 3,483
|
module TriangleKata.Day1 (triangle, TriangleType(..)) where
data TriangleType = Illegal | Equilateral | Isosceles | Scalene
deriving (Show, Eq)
type Triangle = (Int, Int, Int)
triangle :: Triangle -> TriangleType
triangle (0, 0, 0) = Illegal
triangle (a, b, c)
| a + b < c
|| b + c < a
|| c + a < b = Illegal
| a == b
&& b == c = Equilateral
| a == b
|| b == c
|| c == a = Isosceles
| otherwise = Scalene
|
Alex-Diez/haskell-tdd-kata
|
old-katas/src/TriangleKata/Day1.hs
|
Haskell
|
bsd-3-clause
| 552
|
module Config
( scPre
) where
import Data.Monoid
import Common
genDefaultNav galNav = N { navTitle = "Home"
, navPath = Just ""
, subs =
[ galNav
, N { navTitle = "Webdesign"
, navPath = Just "webdesign.html"
, subs = []}
, N { navTitle = "Kontakt"
, navPath = Just "kontakt.html"
, subs =
[ N { navTitle = "gpg-pubkey"
, navPath = Just "gpg-pubkey.html"
, subs = []}
, N { navTitle = "GitHub"
, navPath = Just
"https://github.com/maxhbr"
, subs = []}
, N { navTitle = "Impress"
, navPath = Just "impress.html"
, subs = []}]}]}
scPre galNav = SC { statics = ["css","galerie","images","scripts"
,"gpg-pubkey.asc","favicon.ico"
,"qr.jpg","qr_large.jpg"]
, url = "https://maximilian-huber.de"
, outPath = "_site"
, defaultP = P { pPath = []
, pTitle = Nothing
, pStyle = TextStyle
, pCtn = mempty
, pNav = genDefaultNav galNav
, pLine = Nothing
, pSocial = Nothing}
, indexP = Just "galerie/index.html"}
|
maximilianhuber/maximilian-huber.de
|
src/Config.hs
|
Haskell
|
bsd-3-clause
| 1,929
|
#!/usr/bin/env runhaskell
import Distribution.Simple (defaultMainWithHooks, simpleUserHooks,
UserHooks(..), Args)
{-
-- The test-related options have been disabled due to incompitibilities
-- in various Cabal release versions. In particular, the type expected for
-- runTests has changed, and joinPaths was not exported in Cabal 1.1.6
import Distribution.PackageDescription (PackageDescription)
import Distribution.Simple.LocalBuildInfo (LocalBuildInfo)
import qualified Distribution.Simple.LocalBuildInfo as LBI
import Distribution.Simple.Utils (rawSystemVerbose)
import Distribution.Compat.FilePath (joinPaths)
import System.Exit(ExitCode(..))
-}
main :: IO ()
main = defaultMainWithHooks (simpleUserHooks)
-- main = defaultMainWithHooks (defaultUserHooks{runTests = tests})
{-
-- Definition of tests for Cabal 1.1.3
tests :: Args -> Bool -> LocalBuildInfo -> IO ExitCode
tests args _ lbi =
let testCmd = foldl1 joinPaths [LBI.buildDir lbi, "ListMergeTest", "ListMergeTest"]
in rawSystemVerbose 1 testCmd
("+RTS" : "-M32m" : "-c30" : "-RTS" : args)
-}
{-
-- Definition of tests for Cabal 1.1.7
tests :: Args -> Bool -> PackageDescription -> LocalBuildInfo -> IO ExitCode
tests args _ _ lbi =
let testCmd = foldl1 joinPaths [LBI.buildDir lbi, "ListMergeTest", "ListMergeTest"]
in rawSystemVerbose 1 testCmd
("+RTS" : "-M32m" : "-c30" : "-RTS" : args)
-}
|
kfish/hogg
|
Setup.hs
|
Haskell
|
bsd-3-clause
| 1,463
|
-- Copyright (c) 2011, Mark Wright. All rights reserved.
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
module Main (main) where
import Control.Exception as E
import qualified Data.List as L
import Data.Char (toLower)
import Distribution.Compiler
import Distribution.ModuleName (components, ModuleName)
import Distribution.Package
import Distribution.PackageDescription
import Distribution.PackageDescription.Parse
import Distribution.PackageDescription.Configuration (finalizePackageDescription)
import Distribution.System (buildPlatform)
import Distribution.Verbosity
import Distribution.Version
import System.Console.CmdArgs.Implicit
import System.IO
import System.Process (readProcess)
import Data.String.Utils
import Text.Regex.TDFA
deriving instance Data CompilerFlavor
deriving instance Data Version
deriving instance Typeable CompilerFlavor
instance Default CompilerFlavor where
def = buildCompilerFlavor
data VersionInfo = NotDisplayed
| Displayed
| DisplayedInSquareBrackets
deriving (Data, Enum, Typeable, Show)
data ModuleInfo = ExposedAndNonExposed
| Exposed
| NonExposed
deriving (Data, Enum, Typeable, Show)
data CmdOpts = Depends
{ delim :: String
, prefix :: String
, compilerFlavor :: CompilerFlavor
, compilerVersion :: Version
, versionInfo :: VersionInfo
, cabalFilePath :: FilePath
}
| Modules
{ delim :: String
, prefix :: String
, compilerFlavor :: CompilerFlavor
, compilerVersion :: Version
, moduleInfo :: ModuleInfo
, cabalFilePath :: FilePath
} deriving (Data, Typeable, Show)
lowercase :: String -> String
lowercase = map toLower
depends_ :: CmdOpts
depends_ = Depends { delim = " "
, prefix = ""
, compilerFlavor = enum [ GHC &= help "ghc"
, NHC &= help "nhc"
, YHC &= help "yhc"
, Hugs &= help "hugs"
, HBC &= help "hbc"
, Helium &= help "helium"
, JHC &= help "jhc"
, LHC &= help "lhc"
, UHC &= help "uhc"
, OtherCompiler "" &= help ""
]
, compilerVersion = Version { versionBranch = []
, versionTags = [] }
, versionInfo = enum [ NotDisplayed &= help "Version info not displayed"
, Displayed &= help "Version info displayed"
, DisplayedInSquareBrackets &= help "Version info displayed in square brackets"
]
, cabalFilePath = "" &= typFile &= args
} &= help "List dependencies"
modules :: CmdOpts
modules = Modules { delim = " "
, prefix = ""
, compilerFlavor = enum [ GHC &= help "ghc"
, NHC &= help "nhc"
, YHC &= help "yhc"
, Hugs &= help "hugs"
, HBC &= help "hbc"
, Helium &= help "helium"
, JHC &= help "jhc"
, LHC &= help "lhc"
, UHC &= help "uhc"
, OtherCompiler "" &= help ""
]
, compilerVersion = Version { versionBranch = []
, versionTags = []
}
, moduleInfo = enum [ ExposedAndNonExposed &= help "Both exposed and non-exposed modules"
, Exposed &= help "Exposed modules"
, NonExposed &= help "Non-exposed modules"
]
, cabalFilePath = "" &= typFile &= args
} &= help "List modules"
-- | display dependency and optionally version information
depVerStr :: VersionInfo -> -- ^ controls the optional display of dependency version information
Dependency -> -- ^ the dependency
String -- ^ output dependency string and optionally dependency version information
depVerStr vi (Dependency (PackageName pn) vr) = case vi of
NotDisplayed -> pn
Displayed -> pn ++ " " ++ show vr
DisplayedInSquareBrackets -> pn ++ "[" ++ show vr ++ "]"
-- | list dependencies in the cabal file
lsdeps :: VersionInfo -> -- ^ optionally list dependency version information
String -> -- ^ delimiter string between dependencies
String -> -- ^ optional prefix string before each dependency
Library -> -- ^ library
IO () -- ^ return nothing
lsdeps vi d p l =
let ds = (map (depVerStr vi) . targetBuildDepends . libBuildInfo) l
prefixedDeps = map (p ++) ds
deps = L.intercalate d prefixedDeps
in
do
putStrLn deps
return ()
nonExposedModules :: Library ->
[ModuleName]
nonExposedModules = otherModules . libBuildInfo
mods :: String -> -- ^ delimiter string between dependencies
String -> -- ^ optional prefix string before each dependency
Library -> -- ^ library
(Library -> [ModuleName]) -> -- ^ function to obtain list of modules from Library
IO () -- ^ return nothing
mods d p l f =
let ds = map (L.intercalate "." . components) (f l)
prefixedMods = map (p ++) ds
ms = L.intercalate d prefixedMods
in
putStrLn ms
-- | list modules in the cabal file
lsmods :: ModuleInfo -> -- ^ optionally list exposed and/or non-exposed modules
String -> -- ^ delimiter string between dependencies
String -> -- ^ optional prefix string before each dependency
Library -> -- ^ library
IO () -- ^ return nothing
lsmods mi d p l =
case mi of
ExposedAndNonExposed ->
do
mods d p l exposedModules
mods d p l nonExposedModules
return ()
Exposed -> mods d p l exposedModules
NonExposed -> mods d p l nonExposedModules
-- | Replace all occurrances of escaped line feed, carriage return and
-- tab characters.
escapeReplace :: String -> -- ^ input string
String -- ^ output string with escaped characters replaced with corresponding characters
escapeReplace = replace "\\n" "\n" . replace "\\r" "\r" . replace "\\t" "\t"
compVer :: CompilerFlavor ->
Version ->
IO CompilerId
compVer c v@(Version [] []) =
do
let comp = (lowercase . show) c
eitherH <- (E.try :: IO String -> IO (Either SomeException String)) $ readProcess comp ["--version"] []
case eitherH of
Left err ->
do
putStrLn $ "Failed to obtain " ++ (lowercase . show) c ++ " version: " ++ show err
return $ CompilerId c v
Right vs ->
do
let vw = words (vs =~ "[Vv]ersion [0-9]+([.][0-9])+" :: String)
let ns = if length vw == 2
then (words . replace "." " " . last) vw
else []
eitherR <- (E.try :: IO [Int] -> IO (Either SomeException [Int])) $ return $ map (read :: String -> Int) ns
case eitherR of
Left _ ->
return $ CompilerId c Version { versionBranch = []
, versionTags = ns
}
Right is ->
return $ CompilerId c Version { versionBranch = is
, versionTags = ns
}
compVer c v@Version {} =
return $ CompilerId c v
-- | Process command line options
processOpts :: CmdOpts -> -- ^ command line options
IO Int -- ^ return 0 on success, 1 on failure
processOpts cmdOpts =
do
let inputFilePath = cabalFilePath cmdOpts
cv <- compVer (compilerFlavor cmdOpts) (compilerVersion cmdOpts)
eitherH <- E.try $ readPackageDescription verbose inputFilePath
case eitherH of
Left err ->
putStrLn "Failed to open output file " >> ioError err >> return 1
Right genericPackageDescription ->
let eitherP = finalizePackageDescription
[ (FlagName "small_base", True)
]
(\_ -> True)
buildPlatform
cv
[]
genericPackageDescription
in
case eitherP of
Left ds ->
let missingDeps = (L.unwords . map show) ds
in
do
putStrLn $ "Missing deps: " ++ missingDeps
return 1
Right (pd, _) ->
case cmdOpts of
Depends {} ->
do
let
d = escapeReplace $ delim cmdOpts
p = escapeReplace $ prefix cmdOpts
vi = versionInfo cmdOpts
withLib pd (lsdeps vi d p)
return 0
Modules {} ->
do
let
d = escapeReplace $ delim cmdOpts
p = escapeReplace $ prefix cmdOpts
mi = moduleInfo cmdOpts
withLib pd (lsmods mi d p)
return 0
main :: IO Int
main = do
cmdOpts <- cmdArgs $ modes [ depends_
, modules
]
&= program "cquery"
&= summary "cquery"
processOpts cmdOpts
|
markwright/cquery
|
Main.hs
|
Haskell
|
bsd-3-clause
| 10,420
|
{-# LANGUAGE OverloadedStrings #-}
module Language.Brainfuck.Internals.CCodeGen where
import Data.Int
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as TIO
import qualified Data.Text.Lazy.Builder as TB
import Data.Text.Format
import Control.Monad.State
import Language.Brainfuck.Internals.Instructions
data CProgram = CProgram
{ statements :: TB.Builder
, indent :: Int64 }
type Compiler = State CProgram ()
addLine :: T.Text -> CProgram -> CProgram
addLine l p = p { statements = statements p
`mappend` (TB.fromLazyText (T.replicate (indent p) " ")
`mappend` (TB.fromLazyText l
`mappend` TB.singleton '\n')) }
incrIndent :: CProgram -> CProgram
incrIndent p = p { indent=indent p + 1 }
decrIndent :: CProgram -> CProgram
decrIndent p = p { indent=indent p - 1 }
emptyProgram :: CProgram
emptyProgram = CProgram
{ statements=TB.fromLazyText ""
, indent=1 }
gen :: Instr -> Compiler
gen (Incr i) = modify' . addLine . format "mem[ptr] += {};" $ Only i
gen (Decr i) = modify' . addLine . format "mem[ptr] -= {};" $ Only i
gen (Set i) = modify' . addLine . format "mem[ptr] = {};" $ Only i
gen (Mul x 1) = modify' . addLine . format "mem[ptr + {}] += mem[ptr];" $ Only x
gen (Mul x y) = modify' . addLine . format "mem[ptr + {}] += mem[ptr] * {};" $ (x, y)
gen (Copy n) = modify' . addLine . format "mem[ptr + {}] = mem[ptr]" $ Only n
gen (MoveRight n) = modify' . addLine . format "ptr += {};" $ Only n
gen (MoveLeft n) = modify' . addLine . format "ptr -= {};" $ Only n
gen Read = modify' (addLine "mem[ptr] = getchar();")
gen Print = modify' (addLine "putchar(mem[ptr]);")
gen (Loop body) = do
modify' (addLine "while (mem[ptr]) {")
modify' incrIndent
mapM_ gen body
modify' decrIndent
modify' (addLine "}")
gen _ = return ()
genCode :: Program -> T.Text
genCode prog = TB.toLazyText . statements . execState (mapM_ gen prog) $ emptyProgram
wrapCode :: T.Text -> T.Text
wrapCode program = T.unlines
[ "#include <stdio.h>"
, ""
, "int main() {"
, " char mem[30000] = {0};"
, " int ptr = 0;"
, program
, "}"
]
compile :: Program -> FilePath -> IO ()
compile [] _ = putStrLn "Empty program would result in empty file. No file created."
compile prog path = TIO.writeFile path . wrapCode . genCode $ prog
|
remusao/Hodor
|
src/Language/Brainfuck/Internals/CCodeGen.hs
|
Haskell
|
bsd-3-clause
| 2,368
|
{-# LANGUAGE GeneralizedNewtypeDeriving
, MultiParamTypeClasses
, TypeSynonymInstances
, FlexibleContexts
, FlexibleInstances
, StandaloneDeriving
#-}
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.TwoD.Spiro
-- Copyright : (c) 2011 diagrams-lib team (see LICENSE)
-- License : BSD-style (see LICENSE)
-- Maintainer : diagrams-discuss@googlegroups.com
--
-- Generic functionality for constructing cubic splines
--
-----------------------------------------------------------------------------
module Diagrams.TwoD.Spiro
( spiro
, SpiroPoint(..)
, SpiroConstraint(..)
) where
import System.IO.Unsafe(unsafePerformIO)
import Graphics.Spiro.Raw
import Diagrams.Prelude
import Diagrams.TwoD.Spiro.PathContext (PathContext,toDiagram,zeroPathContext)
import qualified Diagrams.TwoD.Spiro.PathContext as P
import Data.Monoid
import Data.NumInstances
import Control.Monad.IO.Class
import Control.Applicative
import Control.Monad
import Control.Monad.State
import Control.Newtype
newtype PathPostscriptT s m a = PathPostscriptT { runPathPostscriptT :: StateT (PathContext s) m a }
deriving (Functor,Applicative,Monad,MonadIO,MonadTrans)
deriving instance Monad m => MonadState (PathContext s) (PathPostscriptT s m)
instance Newtype (PathPostscriptT s m a) (StateT (PathContext s) m a) where
pack = PathPostscriptT
unpack = runPathPostscriptT
instance MonadIO m => PostscriptLike (PathPostscriptT R2 m) where
moveTo' x y b = modify $ P.moveTo' (x,y) b
moveTo x y = modify $ P.moveTo (x,y)
lineTo x y = modify $ P.lineTo (x,y)
quadTo x y x' y' = modify $ P.quadTo (x,y) (x',y')
curveTo x y x' y' x'' y'' = modify $ P.curveTo (x,y) (x',y') (x'',y'')
markKnot _ = return ()
-- | Computes a diagram from the given spiro control points.
spiro :: Renderable (Path R2) b
=> Bool -- ^ 'True' for a closed path.
-> [SpiroPoint] -- ^ Set of control points with their constrints.
-> Diagram b R2
spiro closed ps = unsafePerformIO $ do
let p = runPathPostscriptT $ spiroToBezier closed ps
execStateT p zeroPathContext >>= return . toDiagram
|
fryguybob/diagrams-spiro
|
src/Diagrams/TwoD/Spiro.hs
|
Haskell
|
bsd-3-clause
| 2,294
|
-- SG library
-- Copyright (c) 2009, Neil Brown.
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are
-- met:
--
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * The author's name may not be used to endorse or promote products derived
-- from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-- IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
-- THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-- PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-- EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-- | Some types that are very basic vectors. Most of the use that can be made
-- of the vectors is in their type-class instances, which support a powerful set
-- of operations. For example:
--
-- > fmap (*3) v -- Scales vector v by 3
-- > pure 0 -- Creates a vector filled with zeroes
-- > v + w -- Adds two vectors (there is a 'Num' instance, basically)
--
-- Plus all the instances for the classes in "Data.SG.Vector", which allows you
-- to use 'getX' and so on.
--
-- You will probably want to create more friendly type synonyms, such as:
--
-- > type Vector2 = Pair Double
-- > type Vector3 = Triple Double
-- > type Line2 = LinePair Double
-- > type Line3 = LineTriple Double
module Data.SG.Vector.Basic where
import Control.Applicative
import Data.Foldable
import Data.Traversable
import Data.SG.Vector
-- | A pair, which acts as a 2D vector.
newtype Pair a = Pair (a, a)
deriving (Eq, Ord, Show, Read)
-- | A triple, which acts as a 3D vector.
newtype Triple a = Triple (a, a, a)
deriving (Eq, Ord, Show, Read)
-- | A quad, which acts as a 4D vector.
newtype Quad a = Quad (a, a, a, a)
deriving (Eq, Ord, Show, Read)
-- | A pair of (position vector, direction vector) to be used as a 2D line.
newtype LinePair a = LinePair (Pair a, Pair a)
deriving (Eq, Ord, Show, Read)
-- | A pair of (position vector, direction vector) to be used as a 3D line.
newtype LineTriple a = LineTriple (Triple a, Triple a)
deriving (Eq, Ord, Show, Read)
instance VectorNum Pair where
fmapNum1 = fmap
fmapNum1inv = fmap
fmapNum2 = liftA2
simpleVec = pure
instance VectorNum Triple where
fmapNum1 = fmap
fmapNum1inv = fmap
fmapNum2 = liftA2
simpleVec = pure
instance VectorNum Quad where
fmapNum1 = fmap
fmapNum1inv = fmap
fmapNum2 = liftA2
simpleVec = pure
instance (Show a, Eq a, Num a) => Num (Pair a) where
(+) = fmapNum2 (+)
(-) = fmapNum2 (-)
(*) = fmapNum2 (*)
abs = fmapNum1inv abs
signum = fmapNum1 signum
negate = fmapNum1inv negate
fromInteger = simpleVec . fromInteger
instance (Show a, Eq a, Num a) => Num (Triple a) where
(+) = fmapNum2 (+)
(-) = fmapNum2 (-)
(*) = fmapNum2 (*)
abs = fmapNum1inv abs
signum = fmapNum1 signum
negate = fmapNum1inv negate
fromInteger = simpleVec . fromInteger
instance (Show a, Eq a, Num a) => Num (Quad a) where
(+) = fmapNum2 (+)
(-) = fmapNum2 (-)
(*) = fmapNum2 (*)
abs = fmapNum1inv abs
signum = fmapNum1 signum
negate = fmapNum1inv negate
fromInteger = simpleVec . fromInteger
instance Applicative Pair where
pure a = Pair (a, a)
(<*>) (Pair (fa, fb)) (Pair (a, b)) = Pair (fa a, fb b)
instance Foldable Pair where
foldr f t (Pair (x, y)) = x `f` (y `f` t)
instance Traversable Pair where
traverse f (Pair (x, y)) = Pair <$> liftA2 (,) (f x) (f y)
instance Applicative Triple where
pure a = Triple (a, a, a)
(<*>) (Triple (fa, fb, fc)) (Triple (a, b, c)) = Triple (fa a, fb b, fc c)
instance Foldable Triple where
foldr f t (Triple (x, y, z)) = x `f` (y `f` (z `f` t))
instance Traversable Triple where
traverse f (Triple (x, y, z)) = Triple <$> liftA3 (,,) (f x) (f y) (f z)
instance Applicative Quad where
pure a = Quad (a, a, a, a)
(<*>) (Quad (fa, fb, fc, fd)) (Quad (a, b, c, d))
= Quad (fa a, fb b, fc c, fd d)
instance Foldable Quad where
foldr f t (Quad (x, y, z, a)) = x `f` (y `f` (z `f` (a `f` t)))
instance Traversable Quad where
traverse f (Quad (x, y, z, a)) = Quad <$> ((,,,) <$> f x <*> f y <*> f z <*> f a)
instance Functor Pair where
fmap = fmapDefault
instance Functor Triple where
fmap = fmapDefault
instance Functor Quad where
fmap = fmapDefault
instance Coord Pair where
getComponents (Pair (a, b)) = [a, b]
fromComponents (a:b:_) = Pair (a, b)
fromComponents xs = fromComponents $ xs ++ repeat 0
instance Coord2 Pair where
getX (Pair (a, _)) = a
getY (Pair (_, b)) = b
instance Coord Triple where
getComponents (Triple (a, b, c)) = [a, b, c]
fromComponents (a:b:c:_) = Triple (a, b, c)
fromComponents xs = fromComponents $ xs ++ repeat 0
instance Coord2 Triple where
getX (Triple (a, _, _)) = a
getY (Triple (_, b, _)) = b
instance Coord3 Triple where
getZ (Triple (_, _, c)) = c
instance Coord Quad where
getComponents (Quad (a, b, c, d)) = [a, b, c, d]
fromComponents (a:b:c:d:_) = Quad (a, b, c, d)
fromComponents xs = fromComponents $ xs ++ repeat 0
instance Coord2 Quad where
getX (Quad (a, _, _, _)) = a
getY (Quad (_, b, _, _)) = b
instance Coord3 Quad where
getZ (Quad (_, _, c, _)) = c
|
eigengrau/haskell-sg
|
Data/SG/Vector/Basic.hs
|
Haskell
|
bsd-3-clause
| 6,065
|
-- To run, package aivika-experiment-cairo must be installed.
import Simulation.Aivika.Experiment
import Simulation.Aivika.Experiment.Chart
import Simulation.Aivika.Experiment.Chart.Backend.Cairo
import Graphics.Rendering.Chart.Backend.Cairo
import Model
import Experiment
main = do
-- run the ordinary simulation
putStrLn "*** The simulation with default parameters..."
runExperiment
singleExperiment singleGenerators
(WebPageRenderer (CairoRenderer PNG) experimentFilePath) (model defaultParams)
putStrLn ""
-- run the Monte-Carlo simulation
putStrLn "*** The Monte-Carlo simulation..."
randomParams >>= runExperimentParallel
monteCarloExperiment monteCarloGenerators
(WebPageRenderer (CairoRenderer PNG) experimentFilePath) . model
|
dsorokin/aivika-experiment-chart
|
examples/Financial/MainUsingCairo.hs
|
Haskell
|
bsd-3-clause
| 774
|
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, BangPatterns #-}
module Valkyria.Type where
import Air.Data.Default
import Air.TH
import Air.Env
import Prelude ()
import Air.Data.Record.SimpleLabel
import Control.Concurrent.STM
import Data.ByteString.Char8 (ByteString)
import Data.Map (Map)
import Data.StateVar
import Text.JSON.Generic
data Code = Code
{
path :: String
, parent :: String
, depth :: Integer
, filesize :: Integer
, content :: String
, is_directory :: Integer
}
deriving (Show, Eq)
mkDefault ''Code
data UnpackStatus =
Unpacking
| UnpackComplete
deriving (Show, Eq, Data, Typeable)
data DBJobStatus =
DBInit
| DBAnalysing
| DBImporting Int
| DBIndexing
| DBComplete
deriving (Show, Eq, Data, Typeable)
data JobError =
FailedToFetchRepo
| Exception String
deriving (Show, Eq, Data, Typeable)
data JobStatus =
Initialized
| UnpackStage UnpackStatus
| DBStage DBJobStatus
| Bouncing
| Cleanup
| Completed Project
| Failed JobError
deriving (Show, Eq, Data, Typeable)
instance Default JobStatus where
def = Initialized
data FetchStatus =
FetchInQueue Integer
| Fetching JobStatus
| FetchFailed String
type StatusCallback = JobStatus -> IO ()
type FetchCallback = FetchStatus -> IO ()
type FetchMonitorCallback = IO () -> IO ()
data Repo = Git | Darcs | SVN | Hg | Archive | Raw
deriving (Show, Eq, Data, Typeable, Read)
instance Default Repo where
def = Git
data Project = Project
{
project_id :: Integer
, project_name :: String
, repo :: Repo
, project_url :: String
}
deriving (Show, Eq, Data, Typeable)
mkDefault ''Project
data RepoState = RepoState
{
states_map :: Map Integer (TVar JobStatus)
}
instance Default RepoState where
def = RepoState
{
states_map = def
}
-- Datatypes
data JobQueryResponse =
JobQueryFailed String
| JobQuerySuccess JobStatus
deriving (Eq, Show, Data, Typeable)
data JobCreateResponse =
JobCreateFailed String
| JobCreateSuccess Integer
deriving (Eq, Show, Data, Typeable)
instance HasGetter TVar where
get = atomically < readTVar
instance HasSetter TVar where
($=) x = atomically < writeTVar x
data SourceCode = SourceCode
{
project_ref :: Project
, fetch_status :: FetchStatus
}
data ClientState = ClientState
{
source_codes :: [SourceCode]
}
data LocalRepoStatus =
LocalInQueue
| LocalUnpacking
| LocalAnalysing
| LocalImporting Double
| LocalBouncing
| LocalDownloading Double
| LocalDone
| LocalError String
| LocalRefreshReachMaximumNumber
deriving (Show, Eq, Data, Typeable)
instance Default LocalRepoStatus where
def = LocalInQueue
data RepoControlHandle = RepoControlHandle
{
set_ui_repo_status :: Integer -> LocalRepoStatus -> IO ()
, set_global_error :: String -> IO ()
}
data RepoControlInput = RepoControlInput
{
create_repo :: TaskID -> Repo -> String-> IO ()
}
{-
instance Default (Event a) where
def = NoEvent
-}
type TaskID = Int
type CallbackMap = Map Int RepoControlHandle
data FetchTask =
CreateRepo !Repo !ByteString
| MonitorRepo !Integer !Integer
| DownloadRepo !Integer
| NoTask
deriving (Show, Eq)
instance Default FetchTask where
def = NoTask
data ReactInput = ReactInput
{
input_id :: !TaskID
, fetch_task :: !FetchTask
}
deriving (Show, Eq)
mkDefault ''ReactInput
data FetchUpdate =
PerformCreateRepo !Repo !ByteString
| PerformMonitorRepo !Integer !Integer
| PerformDownloadRepo !Integer
| SetRepoInQueue
| NoUpdate
deriving (Show, Eq)
instance Default FetchUpdate where
def = NoUpdate
data ReactState = ReactState
{
update_id :: !TaskID
, fetch_update :: !FetchUpdate
}
deriving (Show, Eq)
mkDefault ''ReactState
data LocalRepo = LocalRepo
{
repo_id :: Integer
, repo_url :: String
, repo_type :: Repo
, repo_name :: String
, repo_status :: LocalRepoStatus
}
deriving (Show, Eq, Data, Typeable)
mkDefault ''LocalRepo
type LocalRepoIndex = Integer
{-}
type FetchIn = Event ReactInput
type FetchOut = Event ReactState
type SenseRef = TVar [ReactInput]
type TaskRef = TVar CallbackMap
type LocalState = Map LocalRepoIndex LocalRepo
type LocalStateRef = TVar LocalState
-}
mkLabels
[
''RepoState
]
|
nfjinjing/source-code-server
|
src/Valkyria/Type.hs
|
Haskell
|
bsd-3-clause
| 4,315
|
-- | Refreshes the shared simulation state. The new state will be calculated:
--
-- * Regularly, according to the speed selected by the user
--
-- * Every time there's a change in the status (running, paused, stopped, etc).
module Controller.Conditions.ShowState
( installHandlers )
where
-- External imports
import Control.Monad
import Control.Monad.IfElse
import Hails.MVC.Model.ProtectedModel.Reactive
-- Local imports
import Data.History
import CombinedEnvironment
import Graphics.UI.Gtk.Display.SoOSiMState
import Model.Model
import Model.SystemStatus
-- | Updates the simulation regularly and when there are changes
-- in the simulation status. There's an initial 1-second delay.
installHandlers :: CEnv -> IO()
installHandlers cenv = void $
onEvent (model cenv) SimStateChanged $ condition cenv
condition :: CEnv -> IO ()
condition cenv = onViewAsync $ do
stateM <- getter simStateField (model cenv)
awhen stateM $ \state -> do
let systemSt = simGLSystemStatus state
simstate = simGLSimState state
sel = selection $ systemSt
mcs = present $ multiCoreStatus systemSt
soosimSetSimState soosim $ Just simstate
soosimSetMCS soosim $ Just mcs
soosimSetSelection soosim $ Just sel
where soosim = soosimView (view cenv)
|
ivanperez-keera/SoOSiM-ui
|
src/Controller/Conditions/ShowState.hs
|
Haskell
|
bsd-3-clause
| 1,289
|
{-# LANGUAGE ScopedTypeVariables #-}
module Spec.ExecuteF where
import Spec.Decode
import Spec.Machine
import Utility.Utility
import Spec.VirtualMemory
import qualified Spec.CSRField as Field
import Data.Bits
import Data.Word
import Data.Int
import SoftFloat
import Prelude hiding (isNaN)
canonicalNaN = 0x7fc00000 :: Int32
negativeZero = 0x80000000 :: Int32
positiveZero = 0x00000000 :: Int32
negativeInfinity = 0xff800000 :: Int32
positiveInfinity = 0x7f800000 :: Int32
intToRoundingMode :: MachineInt -> Maybe RoundingMode
intToRoundingMode 0 = Just RoundNearEven
intToRoundingMode 1 = Just RoundMinMag
intToRoundingMode 2 = Just RoundMin
intToRoundingMode 3 = Just RoundMax
intToRoundingMode 4 = Just RoundNearMaxMag
intToRoundingMode _ = Nothing
isNaN :: (Integral t) => t -> Bool
isNaN x = not notNaN
where Result notNaN _ = f32Eq (fromIntegral x :: Word32) (fromIntegral x :: Word32)
getRoundMode :: (RiscvMachine p t) => MachineInt -> p RoundingMode
getRoundMode rm = do
frm <- (if rm == 7 then
getCSRField Field.FRM
else
return rm)
case intToRoundingMode frm of
Just roundMode -> return roundMode
Nothing -> raiseException 0 2
boolBit :: (Bits t) => Int -> Bool -> t
boolBit i b = if b then bit i else zeroBits
updateFFlags :: (RiscvMachine p t) => ExceptionFlags -> p ()
updateFFlags (ExceptionFlags inexact underflow overflow infinite invalid) = do
flags <- getCSRField Field.FFlags
let flags' = flags .|. boolBit 0 inexact .|. boolBit 1 underflow .|.
boolBit 2 overflow .|. boolBit 3 infinite .|. boolBit 4 invalid
setCSRField Field.FFlags flags'
runFPUnary :: (RiscvMachine p t) => (RoundingMode -> Word32 -> F32Result) -> RoundingMode -> Int32 -> p Int32
runFPUnary f roundMode x = do
let Result y flags = f roundMode (fromIntegral x)
updateFFlags flags
if (invalid flags) then
return canonicalNaN
else
return (fromIntegral y)
runFPBinary :: (RiscvMachine p t) => (RoundingMode -> Word32 -> Word32 -> F32Result) -> RoundingMode -> Int32 -> Int32 -> p Int32
runFPBinary f roundMode x y = do
let Result z flags = f roundMode (fromIntegral x) (fromIntegral y)
updateFFlags flags
if (invalid flags) then
return canonicalNaN
else
return (fromIntegral z)
execute :: forall p t. (RiscvMachine p t) => InstructionF -> p ()
execute (Flw rd rs1 oimm12) = do
a <- getRegister rs1
addr <- translate Load 4 (a + fromImm oimm12)
x <- loadWord Execute addr
setFPRegister rd x
execute (Fsw rs1 rs2 simm12) = do
a <- getRegister rs1
addr <- translate Store 4 (a + fromImm simm12)
x <- getFPRegister rs2
storeWord Execute addr x
execute (Fmadd_s rd rs1 rs2 rs3 rm) = do
roundMode <- getRoundMode rm
v <- getFPRegister rs1
w <- getFPRegister rs2
x <- getFPRegister rs3
y <- runFPBinary f32Mul roundMode v w
z <- runFPBinary f32Add roundMode y x
setFPRegister rd z
execute (Fmsub_s rd rs1 rs2 rs3 rm) = do
roundMode <- getRoundMode rm
v <- getFPRegister rs1
w <- getFPRegister rs2
x <- getFPRegister rs3
y <- runFPBinary f32Mul roundMode v w
z <- runFPBinary f32Sub roundMode y x
setFPRegister rd z
execute (Fnmsub_s rd rs1 rs2 rs3 rm) = do
roundMode <- getRoundMode rm
v <- getFPRegister rs1
w <- getFPRegister rs2
x <- getFPRegister rs3
y <- runFPBinary f32Mul roundMode v w
z <- runFPBinary f32Sub roundMode x y
setFPRegister rd z
execute (Fnmadd_s rd rs1 rs2 rs3 rm) = do
roundMode <- getRoundMode rm
v <- getFPRegister rs1
w <- getFPRegister rs2
x <- getFPRegister rs3
y <- runFPBinary f32Mul roundMode v w
z <- runFPBinary f32Sub roundMode (xor y (bit 31)) x
setFPRegister rd z
execute (Fadd_s rd rs1 rs2 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
y <- getFPRegister rs2
z <- runFPBinary f32Add roundMode x y
setFPRegister rd z
execute (Fsub_s rd rs1 rs2 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
y <- getFPRegister rs2
z <- runFPBinary f32Sub roundMode x y
setFPRegister rd z
execute (Fmul_s rd rs1 rs2 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
y <- getFPRegister rs2
z <- runFPBinary f32Mul roundMode x y
setFPRegister rd z
execute (Fdiv_s rd rs1 rs2 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
y <- getFPRegister rs2
z <- runFPBinary f32Div roundMode x y
setFPRegister rd z
execute (Fsqrt_s rd rs1 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
y <- runFPUnary f32Sqrt roundMode x
setFPRegister rd y
execute (Fsgnj_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
setFPRegister rd (bitSlice x 0 31 .|. (y .&. bit 31))
execute (Fsgnjn_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
setFPRegister rd (bitSlice x 0 31 .|. (complement y .&. bit 31))
execute (Fsgnjx_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
setFPRegister rd (x `xor` (y .&. bit 31))
execute (Fmin_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
let Result z flags = f32LtQuiet (fromIntegral x :: Word32) (fromIntegral y :: Word32)
updateFFlags flags
-- Special cases and other sheNaNigans. Current behavior (v2.3-draft) differs
-- from v2.2 of spec.
let result | x == negativeZero && y == positiveZero = x
| isNaN x && isNaN y = canonicalNaN
| isNaN y = x
| isNaN x = y
| z = x
| otherwise = y
setFPRegister rd result
execute (Fmax_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
let Result z flags = f32LtQuiet (fromIntegral x :: Word32) (fromIntegral y :: Word32)
updateFFlags flags
-- Special cases and other sheNaNigans. Current behavior (v2.3-draft) differs
-- from v2.2 of spec.
let result | x == negativeZero && y == positiveZero = y
| isNaN x && isNaN y = canonicalNaN
| isNaN y = x
| isNaN x = y
| z = y
| otherwise = x
setFPRegister rd result
execute (Fcvt_w_s rd rs1 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
let Result y flags = f32ToI32 roundMode (fromIntegral x :: Word32)
updateFFlags flags
-- Special case for the softfloat library.
let result | isNaN x || (y == 2^31 && not (testBit x 31)) = 2^31 - 1
| otherwise = y
setRegister rd (fromIntegral result)
execute (Fcvt_wu_s rd rs1 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
let Result y flags = f32ToUi32 roundMode (fromIntegral x :: Word32)
updateFFlags flags
-- Another special case for the softfloat library.
let result | not (isNaN x) && testBit x 31 = 0
| otherwise = y
setRegister rd (fromIntegral (fromIntegral result :: Int32))
execute (Fmv_x_w rd rs1) = do
x <- getFPRegister rs1
setRegister rd (fromIntegral x)
execute (Feq_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
let Result z flags = f32Eq (fromIntegral x :: Word32) (fromIntegral y :: Word32)
updateFFlags flags
let result = fromIntegral (fromEnum z)
setRegister rd result
execute (Flt_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
let Result z flags = f32Lt (fromIntegral x :: Word32) (fromIntegral y :: Word32)
updateFFlags flags
let result = fromIntegral (fromEnum z)
setRegister rd result
execute (Fle_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
let Result z flags = f32Le (fromIntegral x :: Word32) (fromIntegral y :: Word32)
updateFFlags flags
let result = fromIntegral (fromEnum z)
setRegister rd result
execute (Fclass_s rd rs1) = do
x <- getFPRegister rs1
let special = bitSlice x 23 31 == 2^8 - 1
let result | x == negativeInfinity = bit 0
| x == negativeZero = bit 3
| x == positiveZero = bit 4
| x == positiveInfinity = bit 7
| testBit x 22 && special = bit 9 -- quiet NaN
| special = bit 8 -- signaling NaN
| testBit x 22 && testBit x 31 = bit 2 -- negative subnormal
| testBit x 22 = bit 5 -- positive subnormal
| testBit x 31 = bit 1 -- negative normal
| otherwise = bit 6 -- positive normal
setRegister rd result
execute (Fcvt_s_w rd rs1 rm) = do
roundMode <- getRoundMode rm
x <- getRegister rs1
let Result y flags = i32ToF32 roundMode (fromIntegral x :: Int32)
updateFFlags flags
setFPRegister rd (fromIntegral y)
execute (Fcvt_s_wu rd rs1 rm) = do
roundMode <- getRoundMode rm
x <- getRegister rs1
let Result y flags = ui32ToF32 roundMode (fromIntegral x :: Word32)
updateFFlags flags
setFPRegister rd (fromIntegral y)
execute (Fmv_w_x rd rs1) = do
x <- getRegister rs1
setFPRegister rd (fromIntegral x)
execute inst = error $ "dispatch bug: " ++ show inst
|
mit-plv/riscv-semantics
|
src/Spec/ExecuteF.hs
|
Haskell
|
bsd-3-clause
| 8,803
|
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1996-1998
TcTyClsDecls: Typecheck type and class declarations
-}
{-# LANGUAGE TupleSections #-}
module ETA.TypeCheck.TcTyClsDecls (
tcTyAndClassDecls, tcAddImplicits,
-- Functions used by TcInstDcls to check
-- data/type family instance declarations
kcDataDefn, tcConDecls, dataDeclChecks, checkValidTyCon,
tcFamTyPats, tcTyFamInstEqn, famTyConShape,
tcAddTyFamInstCtxt, tcAddDataFamInstCtxt,
wrongKindOfFamily, dataConCtxt, badDataConTyCon
) where
import ETA.HsSyn.HsSyn
import ETA.Main.HscTypes
import ETA.Iface.BuildTyCl
import ETA.TypeCheck.TcRnMonad
import ETA.TypeCheck.TcEnv
import ETA.TypeCheck.TcValidity
import ETA.TypeCheck.TcHsSyn
import ETA.TypeCheck.TcSimplify( growThetaTyVars )
import ETA.TypeCheck.TcBinds( tcRecSelBinds )
import ETA.TypeCheck.TcTyDecls
import ETA.TypeCheck.TcClassDcl
import ETA.TypeCheck.TcHsType
import ETA.TypeCheck.TcMType
import ETA.TypeCheck.TcType
import ETA.Prelude.TysWiredIn( unitTy )
import ETA.TypeCheck.FamInst
import ETA.Types.FamInstEnv( isDominatedBy, mkCoAxBranch, mkBranchedCoAxiom )
import ETA.Types.Coercion( pprCoAxBranch, ltRole )
import ETA.Types.Type
import ETA.Types.TypeRep -- for checkValidRoles
import ETA.Types.Kind
import ETA.Types.Class
import ETA.Types.CoAxiom
import ETA.Types.TyCon
import ETA.BasicTypes.DataCon
import ETA.BasicTypes.Id
import ETA.Core.MkCore ( rEC_SEL_ERROR_ID )
import ETA.BasicTypes.IdInfo
import ETA.BasicTypes.Var
import ETA.BasicTypes.VarEnv
import ETA.BasicTypes.VarSet
import ETA.BasicTypes.Module
import ETA.BasicTypes.Name
import ETA.BasicTypes.NameSet
import ETA.BasicTypes.NameEnv
import ETA.Utils.Outputable
import qualified ETA.Utils.Outputable as Outputable
import ETA.Utils.Maybes
import ETA.Types.Unify
import ETA.Utils.Util
import ETA.BasicTypes.SrcLoc
import ETA.Utils.ListSetOps
import ETA.Utils.Digraph
import ETA.Main.DynFlags
import ETA.Utils.FastString
import ETA.BasicTypes.Unique ( mkBuiltinUnique )
import ETA.BasicTypes.BasicTypes
import ETA.Utils.Bag
import Control.Monad
import Data.List
{-
************************************************************************
* *
\subsection{Type checking for type and class declarations}
* *
************************************************************************
Note [Grouping of type and class declarations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tcTyAndClassDecls is called on a list of `TyClGroup`s. Each group is a strongly
connected component of mutually dependent types and classes. We kind check and
type check each group separately to enhance kind polymorphism. Take the
following example:
type Id a = a
data X = X (Id Int)
If we were to kind check the two declarations together, we would give Id the
kind * -> *, since we apply it to an Int in the definition of X. But we can do
better than that, since Id really is kind polymorphic, and should get kind
forall (k::BOX). k -> k. Since it does not depend on anything else, it can be
kind-checked by itself, hence getting the most general kind. We then kind check
X, which works fine because we then know the polymorphic kind of Id, and simply
instantiate k to *.
Note [Check role annotations in a second pass]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Role inference potentially depends on the types of all of the datacons declared
in a mutually recursive group. The validity of a role annotation, in turn,
depends on the result of role inference. Because the types of datacons might
be ill-formed (see #7175 and Note [Checking GADT return types]) we must check
*all* the tycons in a group for validity before checking *any* of the roles.
Thus, we take two passes over the resulting tycons, first checking for general
validity and then checking for valid role annotations.
-}
tcTyAndClassDecls :: ModDetails
-> [TyClGroup Name] -- Mutually-recursive groups in dependency order
-> TcM TcGblEnv -- Input env extended by types and classes
-- and their implicit Ids,DataCons
-- Fails if there are any errors
tcTyAndClassDecls boot_details tyclds_s
= checkNoErrs $ -- The code recovers internally, but if anything gave rise to
-- an error we'd better stop now, to avoid a cascade
fold_env tyclds_s -- Type check each group in dependency order folding the global env
where
fold_env :: [TyClGroup Name] -> TcM TcGblEnv
fold_env [] = getGblEnv
fold_env (tyclds:tyclds_s)
= do { tcg_env <- tcTyClGroup boot_details tyclds
; setGblEnv tcg_env $ fold_env tyclds_s }
-- remaining groups are typecheck in the extended global env
tcTyClGroup :: ModDetails -> TyClGroup Name -> TcM TcGblEnv
-- Typecheck one strongly-connected component of type and class decls
tcTyClGroup boot_details tyclds
= do { -- Step 1: kind-check this group and returns the final
-- (possibly-polymorphic) kind of each TyCon and Class
-- See Note [Kind checking for type and class decls]
names_w_poly_kinds <- kcTyClGroup tyclds
; traceTc "tcTyAndCl generalized kinds" (ppr names_w_poly_kinds)
-- Step 2: type-check all groups together, returning
-- the final TyCons and Classes
; let role_annots = extractRoleAnnots tyclds
decls = group_tyclds tyclds
; tyclss <- fixM $ \ rec_tyclss -> do
{ is_boot <- tcIsHsBootOrSig
; let rec_flags = calcRecFlags boot_details is_boot
role_annots rec_tyclss
-- Populate environment with knot-tied ATyCon for TyCons
-- NB: if the decls mention any ill-staged data cons
-- (see Note [Recusion and promoting data constructors]
-- we will have failed already in kcTyClGroup, so no worries here
; tcExtendRecEnv (zipRecTyClss names_w_poly_kinds rec_tyclss) $
-- Also extend the local type envt with bindings giving
-- the (polymorphic) kind of each knot-tied TyCon or Class
-- See Note [Type checking recursive type and class declarations]
tcExtendKindEnv names_w_poly_kinds $
-- Kind and type check declarations for this group
concatMapM (tcTyClDecl rec_flags) decls }
-- Step 3: Perform the validity check
-- We can do this now because we are done with the recursive knot
-- Do it before Step 4 (adding implicit things) because the latter
-- expects well-formed TyCons
; tcExtendGlobalEnv tyclss $ do
{ traceTc "Starting validity check" (ppr tyclss)
; checkNoErrs $
mapM_ (recoverM (return ()) . checkValidTyCl) tyclss
-- We recover, which allows us to report multiple validity errors
-- the checkNoErrs is necessary to fix #7175.
; mapM_ (recoverM (return ()) . checkValidRoleAnnots role_annots) tyclss
-- See Note [Check role annotations in a second pass]
-- Step 4: Add the implicit things;
-- we want them in the environment because
-- they may be mentioned in interface files
; tcExtendGlobalValEnv (mkDefaultMethodIds tyclss) $
tcAddImplicits tyclss } }
tcAddImplicits :: [TyThing] -> TcM TcGblEnv
tcAddImplicits tyclss
= tcExtendGlobalEnvImplicit implicit_things $
tcRecSelBinds rec_sel_binds
where
implicit_things = concatMap implicitTyThings tyclss
rec_sel_binds = mkRecSelBinds tyclss
zipRecTyClss :: [(Name, Kind)]
-> [TyThing] -- Knot-tied
-> [(Name,TyThing)]
-- Build a name-TyThing mapping for the things bound by decls
-- being careful not to look at the [TyThing]
-- The TyThings in the result list must have a visible ATyCon,
-- because typechecking types (in, say, tcTyClDecl) looks at this outer constructor
zipRecTyClss kind_pairs rec_things
= [ (name, ATyCon (get name)) | (name, _kind) <- kind_pairs ]
where
rec_type_env :: TypeEnv
rec_type_env = mkTypeEnv rec_things
get name = case lookupTypeEnv rec_type_env name of
Just (ATyCon tc) -> tc
other -> pprPanic "zipRecTyClss" (ppr name <+> ppr other)
{-
************************************************************************
* *
Kind checking
* *
************************************************************************
Note [Kind checking for type and class decls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Kind checking is done thus:
1. Make up a kind variable for each parameter of the *data* type, class,
and closed type family decls, and extend the kind environment (which is
in the TcLclEnv)
2. Dependency-analyse the type *synonyms* (which must be non-recursive),
and kind-check them in dependency order. Extend the kind envt.
3. Kind check the data type and class decls
Synonyms are treated differently to data type and classes,
because a type synonym can be an unboxed type
type Foo = Int#
and a kind variable can't unify with UnboxedTypeKind
So we infer their kinds in dependency order
We need to kind check all types in the mutually recursive group
before we know the kind of the type variables. For example:
class C a where
op :: D b => a -> b -> b
class D c where
bop :: (Monad c) => ...
Here, the kind of the locally-polymorphic type variable "b"
depends on *all the uses of class D*. For example, the use of
Monad c in bop's type signature means that D must have kind Type->Type.
However type synonyms work differently. They can have kinds which don't
just involve (->) and *:
type R = Int# -- Kind #
type S a = Array# a -- Kind * -> #
type T a b = (# a,b #) -- Kind * -> * -> (# a,b #)
So we must infer their kinds from their right-hand sides *first* and then
use them, whereas for the mutually recursive data types D we bring into
scope kind bindings D -> k, where k is a kind variable, and do inference.
Open type families
~~~~~~~~~~~~~~~~~~
This treatment of type synonyms only applies to Haskell 98-style synonyms.
General type functions can be recursive, and hence, appear in `alg_decls'.
The kind of an open type family is solely determinded by its kind signature;
hence, only kind signatures participate in the construction of the initial
kind environment (as constructed by `getInitialKind'). In fact, we ignore
instances of families altogether in the following. However, we need to include
the kinds of *associated* families into the construction of the initial kind
environment. (This is handled by `allDecls').
-}
kcTyClGroup :: TyClGroup Name -> TcM [(Name,Kind)]
-- Kind check this group, kind generalize, and return the resulting local env
-- This bindds the TyCons and Classes of the group, but not the DataCons
-- See Note [Kind checking for type and class decls]
kcTyClGroup (TyClGroup { group_tyclds = decls })
= do { mod <- getModule
; traceTc "kcTyClGroup" (ptext (sLit "module") <+> ppr mod $$ vcat (map ppr decls))
-- Kind checking;
-- 1. Bind kind variables for non-synonyms
-- 2. Kind-check synonyms, and bind kinds of those synonyms
-- 3. Kind-check non-synonyms
-- 4. Generalise the inferred kinds
-- See Note [Kind checking for type and class decls]
-- Step 1: Bind kind variables for non-synonyms
; let (syn_decls, non_syn_decls) = partition (isSynDecl . unLoc) decls
; initial_kinds <- getInitialKinds non_syn_decls
; traceTc "kcTyClGroup: initial kinds" (ppr initial_kinds)
-- Step 2: Set initial envt, kind-check the synonyms
; lcl_env <- tcExtendKindEnv2 initial_kinds $
kcSynDecls (calcSynCycles syn_decls)
-- Step 3: Set extended envt, kind-check the non-synonyms
; setLclEnv lcl_env $
mapM_ kcLTyClDecl non_syn_decls
-- Step 4: generalisation
-- Kind checking done for this group
-- Now we have to kind generalize the flexis
; res <- concatMapM (generaliseTCD (tcl_env lcl_env)) decls
; traceTc "kcTyClGroup result" (ppr res)
; return res }
where
generalise :: TcTypeEnv -> Name -> TcM (Name, Kind)
-- For polymorphic things this is a no-op
generalise kind_env name
= do { let kc_kind = case lookupNameEnv kind_env name of
Just (AThing k) -> k
_ -> pprPanic "kcTyClGroup" (ppr name $$ ppr kind_env)
; kvs <- kindGeneralize (tyVarsOfType kc_kind)
; kc_kind' <- zonkTcKind kc_kind -- Make sure kc_kind' has the final,
-- skolemised kind variables
; traceTc "Generalise kind" (vcat [ ppr name, ppr kc_kind, ppr kvs, ppr kc_kind' ])
; return (name, mkForAllTys kvs kc_kind') }
generaliseTCD :: TcTypeEnv -> LTyClDecl Name -> TcM [(Name, Kind)]
generaliseTCD kind_env (L _ decl)
| ClassDecl { tcdLName = (L _ name), tcdATs = ats } <- decl
= do { first <- generalise kind_env name
; rest <- mapM ((generaliseFamDecl kind_env) . unLoc) ats
; return (first : rest) }
| FamDecl { tcdFam = fam } <- decl
= do { res <- generaliseFamDecl kind_env fam
; return [res] }
| otherwise
= do { res <- generalise kind_env (tcdName decl)
; return [res] }
generaliseFamDecl :: TcTypeEnv -> FamilyDecl Name -> TcM (Name, Kind)
generaliseFamDecl kind_env (FamilyDecl { fdLName = L _ name })
= generalise kind_env name
mk_thing_env :: [LTyClDecl Name] -> [(Name, TcTyThing)]
mk_thing_env [] = []
mk_thing_env (decl : decls)
| L _ (ClassDecl { tcdLName = L _ nm, tcdATs = ats }) <- decl
= (nm, APromotionErr ClassPE) :
(map (, APromotionErr TyConPE) $ map (unLoc . fdLName . unLoc) ats) ++
(mk_thing_env decls)
| otherwise
= (tcdName (unLoc decl), APromotionErr TyConPE) :
(mk_thing_env decls)
getInitialKinds :: [LTyClDecl Name] -> TcM [(Name, TcTyThing)]
getInitialKinds decls
= tcExtendKindEnv2 (mk_thing_env decls) $
do { pairss <- mapM (addLocM getInitialKind) decls
; return (concat pairss) }
getInitialKind :: TyClDecl Name -> TcM [(Name, TcTyThing)]
-- Allocate a fresh kind variable for each TyCon and Class
-- For each tycon, return (tc, AThing k)
-- where k is the kind of tc, derived from the LHS
-- of the definition (and probably including
-- kind unification variables)
-- Example: data T a b = ...
-- return (T, kv1 -> kv2 -> kv3)
--
-- This pass deals with (ie incorporates into the kind it produces)
-- * The kind signatures on type-variable binders
-- * The result kinds signature on a TyClDecl
--
-- ALSO for each datacon, return (dc, APromotionErr RecDataConPE)
-- Note [ARecDataCon: Recursion and promoting data constructors]
--
-- No family instances are passed to getInitialKinds
getInitialKind decl@(ClassDecl { tcdLName = L _ name, tcdTyVars = ktvs, tcdATs = ats })
= do { (cl_kind, inner_prs) <-
kcHsTyVarBndrs (hsDeclHasCusk decl) ktvs $
do { inner_prs <- getFamDeclInitialKinds ats
; return (constraintKind, inner_prs) }
; let main_pr = (name, AThing cl_kind)
; return (main_pr : inner_prs) }
getInitialKind decl@(DataDecl { tcdLName = L _ name
, tcdTyVars = ktvs
, tcdDataDefn = HsDataDefn { dd_kindSig = m_sig
, dd_cons = cons' } })
= let cons = cons' -- AZ list monad coming
in
do { (decl_kind, _) <-
kcHsTyVarBndrs (hsDeclHasCusk decl) ktvs $
do { res_k <- case m_sig of
Just ksig -> tcLHsKind ksig
Nothing -> return liftedTypeKind
; return (res_k, ()) }
; let main_pr = (name, AThing decl_kind)
inner_prs = [ (unLoc con, APromotionErr RecDataConPE)
| L _ con' <- cons, con <- con_names con' ]
; return (main_pr : inner_prs) }
getInitialKind (FamDecl { tcdFam = decl })
= getFamDeclInitialKind decl
getInitialKind decl@(SynDecl {})
= pprPanic "getInitialKind" (ppr decl)
---------------------------------
getFamDeclInitialKinds :: [LFamilyDecl Name] -> TcM [(Name, TcTyThing)]
getFamDeclInitialKinds decls
= tcExtendKindEnv2 [ (n, APromotionErr TyConPE)
| L _ (FamilyDecl { fdLName = L _ n }) <- decls] $
concatMapM (addLocM getFamDeclInitialKind) decls
getFamDeclInitialKind :: FamilyDecl Name
-> TcM [(Name, TcTyThing)]
getFamDeclInitialKind decl@(FamilyDecl { fdLName = L _ name
, fdTyVars = ktvs
, fdKindSig = ksig })
= do { (fam_kind, _) <-
kcHsTyVarBndrs (famDeclHasCusk decl) ktvs $
do { res_k <- case ksig of
Just k -> tcLHsKind k
Nothing
| famDeclHasCusk decl -> return liftedTypeKind
| otherwise -> newMetaKindVar
; return (res_k, ()) }
; return [ (name, AThing fam_kind) ] }
----------------
kcSynDecls :: [SCC (LTyClDecl Name)]
-> TcM TcLclEnv -- Kind bindings
kcSynDecls [] = getLclEnv
kcSynDecls (group : groups)
= do { (n,k) <- kcSynDecl1 group
; lcl_env <- tcExtendKindEnv [(n,k)] (kcSynDecls groups)
; return lcl_env }
kcSynDecl1 :: SCC (LTyClDecl Name)
-> TcM (Name,TcKind) -- Kind bindings
kcSynDecl1 (AcyclicSCC (L _ decl)) = kcSynDecl decl
kcSynDecl1 (CyclicSCC decls) = do { recSynErr decls; failM }
-- Fail here to avoid error cascade
-- of out-of-scope tycons
kcSynDecl :: TyClDecl Name -> TcM (Name, TcKind)
kcSynDecl decl@(SynDecl { tcdTyVars = hs_tvs, tcdLName = L _ name
, tcdRhs = rhs })
-- Returns a possibly-unzonked kind
= tcAddDeclCtxt decl $
do { (syn_kind, _) <-
kcHsTyVarBndrs (hsDeclHasCusk decl) hs_tvs $
do { traceTc "kcd1" (ppr name <+> brackets (ppr hs_tvs))
; (_, rhs_kind) <- tcLHsType rhs
; traceTc "kcd2" (ppr name)
; return (rhs_kind, ()) }
; return (name, syn_kind) }
kcSynDecl decl = pprPanic "kcSynDecl" (ppr decl)
------------------------------------------------------------------------
kcLTyClDecl :: LTyClDecl Name -> TcM ()
-- See Note [Kind checking for type and class decls]
kcLTyClDecl (L loc decl)
= setSrcSpan loc $ tcAddDeclCtxt decl $ kcTyClDecl decl
kcTyClDecl :: TyClDecl Name -> TcM ()
-- This function is used solely for its side effect on kind variables
-- NB kind signatures on the type variables and
-- result kind signature have aready been dealt with
-- by getInitialKind, so we can ignore them here.
kcTyClDecl (DataDecl { tcdLName = L _ name, tcdTyVars = hs_tvs, tcdDataDefn = defn })
| HsDataDefn { dd_cons = cons, dd_kindSig = Just _ } <- defn
= mapM_ (wrapLocM kcConDecl) cons
-- hs_tvs and dd_kindSig already dealt with in getInitialKind
-- If dd_kindSig is Just, this must be a GADT-style decl,
-- (see invariants of DataDefn declaration)
-- so (a) we don't need to bring the hs_tvs into scope, because the
-- ConDecls bind all their own variables
-- (b) dd_ctxt is not allowed for GADT-style decls, so we can ignore it
| HsDataDefn { dd_ctxt = ctxt, dd_cons = cons } <- defn
= kcTyClTyVars name hs_tvs $
do { _ <- tcHsContext ctxt
; mapM_ (wrapLocM kcConDecl) cons }
kcTyClDecl decl@(SynDecl {}) = pprPanic "kcTyClDecl" (ppr decl)
kcTyClDecl (ClassDecl { tcdLName = L _ name, tcdTyVars = hs_tvs
, tcdCtxt = ctxt, tcdSigs = sigs })
= kcTyClTyVars name hs_tvs $
do { _ <- tcHsContext ctxt
; mapM_ (wrapLocM kc_sig) sigs }
where
kc_sig (TypeSig _ op_ty _) = discardResult (tcHsLiftedType op_ty)
kc_sig (GenericSig _ op_ty) = discardResult (tcHsLiftedType op_ty)
kc_sig _ = return ()
-- closed type families look at their equations, but other families don't
-- do anything here
kcTyClDecl (FamDecl (FamilyDecl { fdLName = L _ fam_tc_name
, fdTyVars = hs_tvs
, fdInfo = ClosedTypeFamily eqns }))
= do { tc_kind <- kcLookupKind fam_tc_name
; let fam_tc_shape = ( fam_tc_name, length (hsQTvBndrs hs_tvs), tc_kind)
; mapM_ (kcTyFamInstEqn fam_tc_shape) eqns }
kcTyClDecl (FamDecl {}) = return ()
-------------------
kcConDecl :: ConDecl Name -> TcM ()
kcConDecl (ConDecl { con_names = names, con_qvars = ex_tvs
, con_cxt = ex_ctxt, con_details = details
, con_res = res })
= addErrCtxt (dataConCtxtName names) $
-- the 'False' says that the existentials don't have a CUSK, as the
-- concept doesn't really apply here. We just need to bring the variables
-- into scope!
do { _ <- kcHsTyVarBndrs False ex_tvs $
do { _ <- tcHsContext ex_ctxt
; mapM_ (tcHsOpenType . getBangType) (hsConDeclArgTys details)
; _ <- tcConRes res
; return (panic "kcConDecl", ()) }
; return () }
{-
Note [Recursion and promoting data constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't want to allow promotion in a strongly connected component
when kind checking.
Consider:
data T f = K (f (K Any))
When kind checking the `data T' declaration the local env contains the
mappings:
T -> AThing <some initial kind>
K -> ARecDataCon
ANothing is only used for DataCons, and only used during type checking
in tcTyClGroup.
************************************************************************
* *
\subsection{Type checking}
* *
************************************************************************
Note [Type checking recursive type and class declarations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At this point we have completed *kind-checking* of a mutually
recursive group of type/class decls (done in kcTyClGroup). However,
we discarded the kind-checked types (eg RHSs of data type decls);
note that kcTyClDecl returns (). There are two reasons:
* It's convenient, because we don't have to rebuild a
kinded HsDecl (a fairly elaborate type)
* It's necessary, because after kind-generalisation, the
TyCons/Classes may now be kind-polymorphic, and hence need
to be given kind arguments.
Example:
data T f a = MkT (f a) (T f a)
During kind-checking, we give T the kind T :: k1 -> k2 -> *
and figure out constraints on k1, k2 etc. Then we generalise
to get T :: forall k. (k->*) -> k -> *
So now the (T f a) in the RHS must be elaborated to (T k f a).
However, during tcTyClDecl of T (above) we will be in a recursive
"knot". So we aren't allowed to look at the TyCon T itself; we are only
allowed to put it (lazily) in the returned structures. But when
kind-checking the RHS of T's decl, we *do* need to know T's kind (so
that we can correctly elaboarate (T k f a). How can we get T's kind
without looking at T? Delicate answer: during tcTyClDecl, we extend
*Global* env with T -> ATyCon (the (not yet built) TyCon for T)
*Local* env with T -> AThing (polymorphic kind of T)
Then:
* During TcHsType.kcTyVar we look in the *local* env, to get the
known kind for T.
* But in TcHsType.ds_type (and ds_var_app in particular) we look in
the *global* env to get the TyCon. But we must be careful not to
force the TyCon or we'll get a loop.
This fancy footwork (with two bindings for T) is only necesary for the
TyCons or Classes of this recursive group. Earlier, finished groups,
live in the global env only.
-}
tcTyClDecl :: RecTyInfo -> LTyClDecl Name -> TcM [TyThing]
tcTyClDecl rec_info (L loc decl)
= setSrcSpan loc $ tcAddDeclCtxt decl $
traceTc "tcTyAndCl-x" (ppr decl) >>
tcTyClDecl1 NoParentTyCon rec_info decl
-- "type family" declarations
tcTyClDecl1 :: TyConParent -> RecTyInfo -> TyClDecl Name -> TcM [TyThing]
tcTyClDecl1 parent _rec_info (FamDecl { tcdFam = fd })
= tcFamDecl1 parent fd
-- "type" synonym declaration
tcTyClDecl1 _parent rec_info
(SynDecl { tcdLName = L _ tc_name, tcdTyVars = tvs, tcdRhs = rhs })
= --ASSERT( isNoParent _parent )
tcTyClTyVars tc_name tvs $ \ tvs' kind ->
tcTySynRhs rec_info tc_name tvs' kind rhs
-- "data/newtype" declaration
tcTyClDecl1 _parent rec_info
(DataDecl { tcdLName = L _ tc_name, tcdTyVars = tvs, tcdDataDefn = defn })
= --ASSERT( isNoParent _parent )
tcTyClTyVars tc_name tvs $ \ tvs' kind ->
tcDataDefn rec_info tc_name tvs' kind defn
tcTyClDecl1 _parent rec_info
(ClassDecl { tcdLName = L _ class_name, tcdTyVars = tvs
, tcdCtxt = ctxt, tcdMeths = meths
, tcdFDs = fundeps, tcdSigs = sigs
, tcdATs = ats, tcdATDefs = at_defs })
= --ASSERT( isNoParent _parent )
do { (clas, tvs', gen_dm_env) <- fixM $ \ ~(clas,_,_) ->
tcTyClTyVars class_name tvs $ \ tvs' kind ->
do { --MASSERT( isConstraintKind kind )
-- This little knot is just so we can get
-- hold of the name of the class TyCon, which we
-- need to look up its recursiveness
; let tycon_name = tyConName (classTyCon clas)
tc_isrec = rti_is_rec rec_info tycon_name
roles = rti_roles rec_info tycon_name
; ctxt' <- tcHsContext ctxt
; ctxt' <- zonkTcTypeToTypes emptyZonkEnv ctxt'
-- Squeeze out any kind unification variables
; fds' <- mapM (addLocM tc_fundep) fundeps
; (sig_stuff, gen_dm_env) <- tcClassSigs class_name sigs meths
; at_stuff <- tcClassATs class_name (AssocFamilyTyCon clas) ats at_defs
; mindef <- tcClassMinimalDef class_name sigs sig_stuff
; clas <- buildClass
class_name tvs' roles ctxt' fds' at_stuff
sig_stuff mindef tc_isrec
; traceTc "tcClassDecl" (ppr fundeps $$ ppr tvs' $$ ppr fds')
; return (clas, tvs', gen_dm_env) }
; let { gen_dm_ids = [ AnId (mkExportedLocalId VanillaId gen_dm_name gen_dm_ty)
| (sel_id, GenDefMeth gen_dm_name) <- classOpItems clas
, let gen_dm_tau = expectJust "tcTyClDecl1" $
lookupNameEnv gen_dm_env (idName sel_id)
, let gen_dm_ty = mkSigmaTy tvs'
[mkClassPred clas (mkTyVarTys tvs')]
gen_dm_tau
]
; class_ats = map ATyCon (classATs clas) }
; return (ATyCon (classTyCon clas) : gen_dm_ids ++ class_ats ) }
-- NB: Order is important due to the call to `mkGlobalThings' when
-- tying the the type and class declaration type checking knot.
where
tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM (tc_fd_tyvar . unLoc) tvs1 ;
; tvs2' <- mapM (tc_fd_tyvar . unLoc) tvs2 ;
; return (tvs1', tvs2') }
tc_fd_tyvar name -- Scoped kind variables are bound to unification variables
-- which are now fixed, so we can zonk
= do { tv <- tcLookupTyVar name
; ty <- zonkTyVarOcc emptyZonkEnv tv
-- Squeeze out any kind unification variables
; case getTyVar_maybe ty of
Just tv' -> return tv'
Nothing -> pprPanic "tc_fd_tyvar" (ppr name $$ ppr tv $$ ppr ty) }
tcFamDecl1 :: TyConParent -> FamilyDecl Name -> TcM [TyThing]
tcFamDecl1 parent
(FamilyDecl {fdInfo = OpenTypeFamily, fdLName = L _ tc_name, fdTyVars = tvs})
= tcTyClTyVars tc_name tvs $ \ tvs' kind -> do
{ traceTc "open type family:" (ppr tc_name)
; checkFamFlag tc_name
; tycon <- buildFamilyTyCon tc_name tvs' OpenSynFamilyTyCon kind parent
; return [ATyCon tycon] }
tcFamDecl1 parent
(FamilyDecl { fdInfo = ClosedTypeFamily eqns
, fdLName = lname@(L _ tc_name), fdTyVars = tvs })
-- Closed type families are a little tricky, because they contain the definition
-- of both the type family and the equations for a CoAxiom.
-- Note: eqns might be empty, in a hs-boot file!
= do { traceTc "closed type family:" (ppr tc_name)
-- the variables in the header have no scope:
; (tvs', kind) <- tcTyClTyVars tc_name tvs $ \ tvs' kind ->
return (tvs', kind)
; checkFamFlag tc_name -- make sure we have -XTypeFamilies
-- Process the equations, creating CoAxBranches
; tc_kind <- kcLookupKind tc_name
; let fam_tc_shape = (tc_name, length (hsQTvBndrs tvs), tc_kind)
; branches <- mapM (tcTyFamInstEqn fam_tc_shape) eqns
-- we need the tycon that we will be creating, but it's in scope.
-- just look it up.
; fam_tc <- tcLookupLocatedTyCon lname
-- create a CoAxiom, with the correct src location. It is Vitally
-- Important that we do not pass the branches into
-- newFamInstAxiomName. They have types that have been zonked inside
-- the knot and we will die if we look at them. This is OK here
-- because there will only be one axiom, so we don't need to
-- differentiate names.
-- See [Zonking inside the knot] in TcHsType
; loc <- getSrcSpanM
; co_ax_name <- newFamInstAxiomName loc tc_name []
-- mkBranchedCoAxiom will fail on an empty list of branches, but
-- we'll never look at co_ax in this case
; let co_ax = mkBranchedCoAxiom co_ax_name fam_tc branches
-- now, finally, build the TyCon
; let syn_rhs = if null eqns
then AbstractClosedSynFamilyTyCon
else ClosedSynFamilyTyCon co_ax
; tycon <- buildFamilyTyCon tc_name tvs' syn_rhs kind parent
; let result = if null eqns
then [ATyCon tycon]
else [ATyCon tycon, ACoAxiom co_ax]
; return result }
-- We check for instance validity later, when doing validity checking for
-- the tycon
tcFamDecl1 parent
(FamilyDecl {fdInfo = DataFamily, fdLName = L _ tc_name, fdTyVars = tvs})
= tcTyClTyVars tc_name tvs $ \ tvs' kind -> do
{ traceTc "data family:" (ppr tc_name)
; checkFamFlag tc_name
; extra_tvs <- tcDataKindSig kind
; let final_tvs = tvs' ++ extra_tvs -- we may not need these
roles = map (const Nominal) final_tvs
tycon = buildAlgTyCon tc_name final_tvs roles Nothing []
DataFamilyTyCon Recursive
False -- Not promotable to the kind level
True -- GADT syntax
parent
; return [ATyCon tycon] }
tcTySynRhs :: RecTyInfo
-> Name
-> [TyVar] -> Kind
-> LHsType Name -> TcM [TyThing]
tcTySynRhs rec_info tc_name tvs kind hs_ty
= do { env <- getLclEnv
; traceTc "tc-syn" (ppr tc_name $$ ppr (tcl_env env))
; rhs_ty <- tcCheckLHsType hs_ty kind
; rhs_ty <- zonkTcTypeToType emptyZonkEnv rhs_ty
; let roles = rti_roles rec_info tc_name
; tycon <- buildSynonymTyCon tc_name tvs roles rhs_ty kind
; return [ATyCon tycon] }
tcDataDefn :: RecTyInfo -> Name
-> [TyVar] -> Kind
-> HsDataDefn Name -> TcM [TyThing]
-- NB: not used for newtype/data instances (whether associated or not)
tcDataDefn rec_info tc_name tvs kind
(HsDataDefn { dd_ND = new_or_data, dd_cType = cType
, dd_ctxt = ctxt, dd_kindSig = mb_ksig
, dd_cons = cons' })
= let cons = cons' -- AZ List monad coming
in do { extra_tvs <- tcDataKindSig kind
; let final_tvs = tvs ++ extra_tvs
roles = rti_roles rec_info tc_name
; stupid_tc_theta <- tcHsContext ctxt
; stupid_theta <- zonkTcTypeToTypes emptyZonkEnv stupid_tc_theta
; kind_signatures <- xoptM Opt_KindSignatures
; is_boot <- tcIsHsBootOrSig -- Are we compiling an hs-boot file?
-- Check that we don't use kind signatures without Glasgow extensions
; case mb_ksig of
Nothing -> return ()
Just hs_k -> do { checkTc (kind_signatures) (badSigTyDecl tc_name)
; tc_kind <- tcLHsKind hs_k
; checkKind kind tc_kind
; return () }
; gadt_syntax <- dataDeclChecks tc_name new_or_data stupid_theta cons
; tycon <- fixM $ \ tycon -> do
{ let res_ty = mkTyConApp tycon (mkTyVarTys final_tvs)
; data_cons <- tcConDecls new_or_data tycon (final_tvs, res_ty) cons
; tc_rhs <-
if null cons && is_boot -- In a hs-boot file, empty cons means
then return totallyAbstractTyConRhs -- "don't know"; hence totally Abstract
else case new_or_data of
DataType -> return (mkDataTyConRhs data_cons)
NewType -> --ASSERT( not (null data_cons) )
mkNewTyConRhs tc_name tycon (head data_cons)
; return (buildAlgTyCon tc_name final_tvs roles (fmap unLoc cType)
stupid_theta tc_rhs
(rti_is_rec rec_info tc_name)
(rti_promotable rec_info)
gadt_syntax NoParentTyCon) }
; return [ATyCon tycon] }
{-
************************************************************************
* *
Typechecking associated types (in class decls)
(including the associated-type defaults)
* *
************************************************************************
Note [Associated type defaults]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following is an example of associated type defaults:
class C a where
data D a
type F a b :: *
type F a Z = [a] -- Default
type F a (S n) = F a n -- Default
Note that:
- We can have more than one default definition for a single associated type,
as long as they do not overlap (same rules as for instances)
- We can get default definitions only for type families, not data families
-}
tcClassATs :: Name -- The class name (not knot-tied)
-> TyConParent -- The class parent of this associated type
-> [LFamilyDecl Name] -- Associated types.
-> [LTyFamDefltEqn Name] -- Associated type defaults.
-> TcM [ClassATItem]
tcClassATs class_name parent ats at_defs
= do { -- Complain about associated type defaults for non associated-types
sequence_ [ failWithTc (badATErr class_name n)
| n <- map at_def_tycon at_defs
, not (n `elemNameSet` at_names) ]
; mapM tc_at ats }
where
at_def_tycon :: LTyFamDefltEqn Name -> Name
at_def_tycon (L _ eqn) = unLoc (tfe_tycon eqn)
at_fam_name :: LFamilyDecl Name -> Name
at_fam_name (L _ decl) = unLoc (fdLName decl)
at_names = mkNameSet (map at_fam_name ats)
at_defs_map :: NameEnv [LTyFamDefltEqn Name]
-- Maps an AT in 'ats' to a list of all its default defs in 'at_defs'
at_defs_map = foldr (\at_def nenv -> extendNameEnv_C (++) nenv
(at_def_tycon at_def) [at_def])
emptyNameEnv at_defs
tc_at at = do { [ATyCon fam_tc] <- addLocM (tcFamDecl1 parent) at
; let at_defs = lookupNameEnv at_defs_map (at_fam_name at)
`orElse` []
; atd <- tcDefaultAssocDecl fam_tc at_defs
; return (ATI fam_tc atd) }
-------------------------
tcDefaultAssocDecl :: TyCon -- ^ Family TyCon
-> [LTyFamDefltEqn Name] -- ^ Defaults
-> TcM (Maybe (Type, SrcSpan)) -- ^ Type checked RHS
tcDefaultAssocDecl _ []
= return Nothing -- No default declaration
tcDefaultAssocDecl _ (d1:_:_)
= failWithTc (ptext (sLit "More than one default declaration for")
<+> ppr (tfe_tycon (unLoc d1)))
tcDefaultAssocDecl fam_tc [L loc (TyFamEqn { tfe_tycon = L _ tc_name
, tfe_pats = hs_tvs
, tfe_rhs = rhs })]
= setSrcSpan loc $
tcAddFamInstCtxt (ptext (sLit "default type instance")) tc_name $
tcTyClTyVars tc_name hs_tvs $ \ tvs rhs_kind ->
do { traceTc "tcDefaultAssocDecl" (ppr tc_name)
; checkTc (isTypeFamilyTyCon fam_tc) (wrongKindOfFamily fam_tc)
; let (fam_name, fam_pat_arity, _) = famTyConShape fam_tc
; --ASSERT( fam_name == tc_name )
checkTc (length (hsQTvBndrs hs_tvs) == fam_pat_arity)
(wrongNumberOfParmsErr fam_pat_arity)
; rhs_ty <- tcCheckLHsType rhs rhs_kind
; rhs_ty <- zonkTcTypeToType emptyZonkEnv rhs_ty
; let fam_tc_tvs = tyConTyVars fam_tc
subst = zipTopTvSubst tvs (mkTyVarTys fam_tc_tvs)
; return ( --ASSERT( equalLength fam_tc_tvs tvs )
Just (substTy subst rhs_ty, loc) ) }
-- We check for well-formedness and validity later, in checkValidClass
-------------------------
kcTyFamInstEqn :: FamTyConShape -> LTyFamInstEqn Name -> TcM ()
kcTyFamInstEqn fam_tc_shape
(L loc (TyFamEqn { tfe_pats = pats, tfe_rhs = hs_ty }))
= setSrcSpan loc $
discardResult $
tc_fam_ty_pats fam_tc_shape pats (discardResult . (tcCheckLHsType hs_ty))
tcTyFamInstEqn :: FamTyConShape -> LTyFamInstEqn Name -> TcM CoAxBranch
-- Needs to be here, not in TcInstDcls, because closed families
-- (typechecked here) have TyFamInstEqns
tcTyFamInstEqn fam_tc_shape@(fam_tc_name,_,_)
(L loc (TyFamEqn { tfe_tycon = L _ eqn_tc_name
, tfe_pats = pats
, tfe_rhs = hs_ty }))
= setSrcSpan loc $
tcFamTyPats fam_tc_shape pats (discardResult . (tcCheckLHsType hs_ty)) $
\tvs' pats' res_kind ->
do { checkTc (fam_tc_name == eqn_tc_name)
(wrongTyFamName fam_tc_name eqn_tc_name)
; rhs_ty <- tcCheckLHsType hs_ty res_kind
; rhs_ty <- zonkTcTypeToType emptyZonkEnv rhs_ty
; traceTc "tcTyFamInstEqn" (ppr fam_tc_name <+> ppr tvs')
-- don't print out the pats here, as they might be zonked inside the knot
; return (mkCoAxBranch tvs' pats' rhs_ty loc) }
kcDataDefn :: HsDataDefn Name -> TcKind -> TcM ()
-- Used for 'data instance' only
-- Ordinary 'data' is handled by kcTyClDec
kcDataDefn (HsDataDefn { dd_ctxt = ctxt, dd_cons = cons, dd_kindSig = mb_kind }) res_k
= do { _ <- tcHsContext ctxt
; checkNoErrs $ mapM_ (wrapLocM kcConDecl) cons
-- See Note [Failing early in kcDataDefn]
; kcResultKind mb_kind res_k }
------------------
kcResultKind :: Maybe (LHsKind Name) -> Kind -> TcM ()
kcResultKind Nothing res_k
= checkKind res_k liftedTypeKind
-- type family F a
-- defaults to type family F a :: *
kcResultKind (Just k) res_k
= do { k' <- tcLHsKind k
; checkKind k' res_k }
{-
Kind check type patterns and kind annotate the embedded type variables.
type instance F [a] = rhs
* Here we check that a type instance matches its kind signature, but we do
not check whether there is a pattern for each type index; the latter
check is only required for type synonym instances.
Note [tc_fam_ty_pats vs tcFamTyPats]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tc_fam_ty_pats does the type checking of the patterns, but it doesn't
zonk or generate any desugaring. It is used when kind-checking closed
type families.
tcFamTyPats type checks the patterns, zonks, and then calls thing_inside
to generate a desugaring. It is used during type-checking (not kind-checking).
Note [Type-checking type patterns]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When typechecking the patterns of a family instance declaration, we can't
rely on using the family TyCon, because this is sometimes called
from within a type-checking knot. (Specifically for closed type families.)
The type FamTyConShape gives just enough information to do the job.
The "arity" field of FamTyConShape is the *visible* arity of the family
type constructor, i.e. what the users sees and writes, not including kind
arguments.
See also Note [tc_fam_ty_pats vs tcFamTyPats]
Note [Failing early in kcDataDefn]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to use checkNoErrs when calling kcConDecl. This is because kcConDecl
calls tcConDecl, which checks that the return type of a GADT-like constructor
is actually an instance of the type head. Without the checkNoErrs, potentially
two bad things could happen:
1) Duplicate error messages, because tcConDecl will be called again during
*type* checking (as opposed to kind checking)
2) If we just keep blindly forging forward after both kind checking and type
checking, we can get a panic in rejigConRes. See Trac #8368.
-}
-----------------
type FamTyConShape = (Name, Arity, Kind) -- See Note [Type-checking type patterns]
famTyConShape :: TyCon -> FamTyConShape
famTyConShape fam_tc
= ( tyConName fam_tc
, length (filterOut isKindVar (tyConTyVars fam_tc))
, tyConKind fam_tc )
tc_fam_ty_pats :: FamTyConShape
-> HsWithBndrs Name [LHsType Name] -- Patterns
-> (TcKind -> TcM ()) -- Kind checker for RHS
-- result is ignored
-> TcM ([Kind], [Type], Kind)
-- Check the type patterns of a type or data family instance
-- type instance F <pat1> <pat2> = <type>
-- The 'tyvars' are the free type variables of pats
--
-- NB: The family instance declaration may be an associated one,
-- nested inside an instance decl, thus
-- instance C [a] where
-- type F [a] = ...
-- In that case, the type variable 'a' will *already be in scope*
-- (and, if C is poly-kinded, so will its kind parameter).
tc_fam_ty_pats (name, arity, kind)
(HsWB { hswb_cts = arg_pats, hswb_kvs = kvars, hswb_tvs = tvars })
kind_checker
= do { let (fam_kvs, fam_body) = splitForAllTys kind
-- We wish to check that the pattern has the right number of arguments
-- in checkValidFamPats (in TcValidity), so we can do the check *after*
-- we're done with the knot. But, the splitKindFunTysN below will panic
-- if there are *too many* patterns. So, we do a preliminary check here.
-- Note that we don't have enough information at hand to do a full check,
-- as that requires the full declared arity of the family, which isn't
-- nearby.
; checkTc (length arg_pats == arity) $
wrongNumberOfParmsErr arity
-- Instantiate with meta kind vars
; fam_arg_kinds <- mapM (const newMetaKindVar) fam_kvs
; loc <- getSrcSpanM
; let (arg_kinds, res_kind)
= splitKindFunTysN (length arg_pats) $
substKiWith fam_kvs fam_arg_kinds fam_body
hs_tvs = HsQTvs { hsq_kvs = kvars
, hsq_tvs = userHsTyVarBndrs loc tvars }
-- Kind-check and quantify
-- See Note [Quantifying over family patterns]
; typats <- tcHsTyVarBndrs hs_tvs $ \ _ ->
do { kind_checker res_kind
; tcHsArgTys (quotes (ppr name)) arg_pats arg_kinds }
; return (fam_arg_kinds, typats, res_kind) }
-- See Note [tc_fam_ty_pats vs tcFamTyPats]
tcFamTyPats :: FamTyConShape
-> HsWithBndrs Name [LHsType Name] -- patterns
-> (TcKind -> TcM ()) -- kind-checker for RHS
-> ([TKVar] -- Kind and type variables
-> [TcType] -- Kind and type arguments
-> Kind -> TcM a)
-> TcM a
tcFamTyPats fam_shape@(name,_,_) pats kind_checker thing_inside
= do { (fam_arg_kinds, typats, res_kind)
<- tc_fam_ty_pats fam_shape pats kind_checker
; let all_args = fam_arg_kinds ++ typats
-- Find free variables (after zonking) and turn
-- them into skolems, so that we don't subsequently
-- replace a meta kind var with AnyK
-- Very like kindGeneralize
; qtkvs <- quantifyTyVars emptyVarSet (tyVarsOfTypes all_args)
-- Zonk the patterns etc into the Type world
; (ze, qtkvs') <- zonkTyBndrsX emptyZonkEnv qtkvs
; all_args' <- zonkTcTypeToTypes ze all_args
; res_kind' <- zonkTcTypeToType ze res_kind
; traceTc "tcFamTyPats" (ppr name)
-- don't print out too much, as we might be in the knot
; tcExtendTyVarEnv qtkvs' $
thing_inside qtkvs' all_args' res_kind' }
{-
Note [Quantifying over family patterns]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to quantify over two different lots of kind variables:
First, the ones that come from the kinds of the tyvar args of
tcTyVarBndrsKindGen, as usual
data family Dist a
-- Proxy :: forall k. k -> *
data instance Dist (Proxy a) = DP
-- Generates data DistProxy = DP
-- ax8 k (a::k) :: Dist * (Proxy k a) ~ DistProxy k a
-- The 'k' comes from the tcTyVarBndrsKindGen (a::k)
Second, the ones that come from the kind argument of the type family
which we pick up using the (tyVarsOfTypes typats) in the result of
the thing_inside of tcHsTyvarBndrsGen.
-- Any :: forall k. k
data instance Dist Any = DA
-- Generates data DistAny k = DA
-- ax7 k :: Dist k (Any k) ~ DistAny k
-- The 'k' comes from kindGeneralizeKinds (Any k)
Note [Quantified kind variables of a family pattern]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider type family KindFam (p :: k1) (q :: k1)
data T :: Maybe k1 -> k2 -> *
type instance KindFam (a :: Maybe k) b = T a b -> Int
The HsBSig for the family patterns will be ([k], [a])
Then in the family instance we want to
* Bring into scope [ "k" -> k:BOX, "a" -> a:k ]
* Kind-check the RHS
* Quantify the type instance over k and k', as well as a,b, thus
type instance [k, k', a:Maybe k, b:k']
KindFam (Maybe k) k' a b = T k k' a b -> Int
Notice that in the third step we quantify over all the visibly-mentioned
type variables (a,b), but also over the implicitly mentioned kind variables
(k, k'). In this case one is bound explicitly but often there will be
none. The role of the kind signature (a :: Maybe k) is to add a constraint
that 'a' must have that kind, and to bring 'k' into scope.
************************************************************************
* *
Data types
* *
************************************************************************
-}
dataDeclChecks :: Name -> NewOrData -> ThetaType -> [LConDecl Name] -> TcM Bool
dataDeclChecks tc_name new_or_data stupid_theta cons
= do { -- Check that we don't use GADT syntax in H98 world
gadtSyntax_ok <- xoptM Opt_GADTSyntax
; let gadt_syntax = consUseGadtSyntax cons
; checkTc (gadtSyntax_ok || not gadt_syntax) (badGadtDecl tc_name)
-- Check that the stupid theta is empty for a GADT-style declaration
; checkTc (null stupid_theta || not gadt_syntax) (badStupidTheta tc_name)
-- Check that a newtype has exactly one constructor
-- Do this before checking for empty data decls, so that
-- we don't suggest -XEmptyDataDecls for newtypes
; checkTc (new_or_data == DataType || isSingleton cons)
(newtypeConError tc_name (length cons))
-- Check that there's at least one condecl,
-- or else we're reading an hs-boot file, or -XEmptyDataDecls
; empty_data_decls <- xoptM Opt_EmptyDataDecls
; is_boot <- tcIsHsBootOrSig -- Are we compiling an hs-boot file?
; checkTc (not (null cons) || empty_data_decls || is_boot)
(emptyConDeclsErr tc_name)
; return gadt_syntax }
-----------------------------------
consUseGadtSyntax :: [LConDecl a] -> Bool
consUseGadtSyntax (L _ (ConDecl { con_res = ResTyGADT _ _ }) : _) = True
consUseGadtSyntax _ = False
-- All constructors have same shape
-----------------------------------
tcConDecls :: NewOrData -> TyCon -> ([TyVar], Type)
-> [LConDecl Name] -> TcM [DataCon]
tcConDecls new_or_data rep_tycon (tmpl_tvs, res_tmpl) cons
= concatMapM (addLocM $ tcConDecl new_or_data rep_tycon tmpl_tvs res_tmpl)
cons
tcConDecl :: NewOrData
-> TyCon -- Representation tycon
-> [TyVar] -> Type -- Return type template (with its template tyvars)
-- (tvs, T tys), where T is the family TyCon
-> ConDecl Name
-> TcM [DataCon]
tcConDecl new_or_data rep_tycon tmpl_tvs res_tmpl -- Data types
(ConDecl { con_names = names
, con_qvars = hs_tvs, con_cxt = hs_ctxt
, con_details = hs_details, con_res = hs_res_ty })
= addErrCtxt (dataConCtxtName names) $
do { traceTc "tcConDecl 1" (ppr names)
; (ctxt, arg_tys, res_ty, field_lbls, stricts)
<- tcHsTyVarBndrs hs_tvs $ \ _ ->
do { ctxt <- tcHsContext hs_ctxt
; details <- tcConArgs new_or_data hs_details
; res_ty <- tcConRes hs_res_ty
; let (field_lbls, btys) = details
(arg_tys, stricts) = unzip btys
; return (ctxt, arg_tys, res_ty, field_lbls, stricts)
}
-- Generalise the kind variables (returning quantified TcKindVars)
-- and quantify the type variables (substituting their kinds)
-- REMEMBER: 'tkvs' are:
-- ResTyH98: the *existential* type variables only
-- ResTyGADT: *all* the quantified type variables
-- c.f. the comment on con_qvars in HsDecls
; tkvs <- case res_ty of
ResTyH98 -> quantifyTyVars (mkVarSet tmpl_tvs)
(tyVarsOfTypes (ctxt++arg_tys))
ResTyGADT _ res_ty -> quantifyTyVars emptyVarSet
(tyVarsOfTypes (res_ty:ctxt++arg_tys))
-- Zonk to Types
; (ze, qtkvs) <- zonkTyBndrsX emptyZonkEnv tkvs
; arg_tys <- zonkTcTypeToTypes ze arg_tys
; ctxt <- zonkTcTypeToTypes ze ctxt
; res_ty <- case res_ty of
ResTyH98 -> return ResTyH98
ResTyGADT ls ty -> ResTyGADT ls <$> zonkTcTypeToType ze ty
; let (univ_tvs, ex_tvs, eq_preds, res_ty') = rejigConRes tmpl_tvs res_tmpl qtkvs res_ty
; fam_envs <- tcGetFamInstEnvs
; let
buildOneDataCon (L _ name) = do
{ is_infix <- tcConIsInfix name hs_details res_ty
; buildDataCon fam_envs name is_infix
stricts field_lbls
univ_tvs ex_tvs eq_preds ctxt arg_tys
res_ty' rep_tycon
-- NB: we put data_tc, the type constructor gotten from the
-- constructor type signature into the data constructor;
-- that way checkValidDataCon can complain if it's wrong.
}
; mapM buildOneDataCon names
}
tcConIsInfix :: Name
-> HsConDetails (LHsType Name) (Located [LConDeclField Name])
-> ResType Type
-> TcM Bool
tcConIsInfix _ details ResTyH98
= case details of
InfixCon {} -> return True
_ -> return False
tcConIsInfix con details (ResTyGADT _ _)
= case details of
InfixCon {} -> return True
RecCon {} -> return False
PrefixCon arg_tys -- See Note [Infix GADT cons]
| isSymOcc (getOccName con)
, [_ty1,_ty2] <- arg_tys
-> do { fix_env <- getFixityEnv
; return (con `elemNameEnv` fix_env) }
| otherwise -> return False
tcConArgs :: NewOrData -> HsConDeclDetails Name
-> TcM ([Name], [(TcType, HsSrcBang)])
tcConArgs new_or_data (PrefixCon btys)
= do { btys' <- mapM (tcConArg new_or_data) btys
; return ([], btys') }
tcConArgs new_or_data (InfixCon bty1 bty2)
= do { bty1' <- tcConArg new_or_data bty1
; bty2' <- tcConArg new_or_data bty2
; return ([], [bty1', bty2']) }
tcConArgs new_or_data (RecCon fields)
= do { btys' <- mapM (tcConArg new_or_data) btys
; return (field_names, btys') }
where
-- We need a one-to-one mapping from field_names to btys
combined = map (\(L _ f) -> (cd_fld_names f,cd_fld_type f)) (unLoc fields)
explode (ns,ty) = zip (map unLoc ns) (repeat ty)
exploded = concatMap explode combined
(field_names,btys) = unzip exploded
tcConArg :: NewOrData -> LHsType Name -> TcM (TcType, HsSrcBang)
tcConArg new_or_data bty
= do { traceTc "tcConArg 1" (ppr bty)
; arg_ty <- tcHsConArgType new_or_data bty
; traceTc "tcConArg 2" (ppr bty)
; return (arg_ty, getBangStrictness bty) }
tcConRes :: ResType (LHsType Name) -> TcM (ResType Type)
tcConRes ResTyH98 = return ResTyH98
tcConRes (ResTyGADT ls res_ty) = do { res_ty' <- tcHsLiftedType res_ty
; return (ResTyGADT ls res_ty') }
{-
Note [Infix GADT constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We do not currently have syntax to declare an infix constructor in GADT syntax,
but it makes a (small) difference to the Show instance. So as a slightly
ad-hoc solution, we regard a GADT data constructor as infix if
a) it is an operator symbol
b) it has two arguments
c) there is a fixity declaration for it
For example:
infix 6 (:--:)
data T a where
(:--:) :: t1 -> t2 -> T Int
Note [Checking GADT return types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is a delicacy around checking the return types of a datacon. The
central problem is dealing with a declaration like
data T a where
MkT :: a -> Q a
Note that the return type of MkT is totally bogus. When creating the T
tycon, we also need to create the MkT datacon, which must have a "rejigged"
return type. That is, the MkT datacon's type must be transformed to have
a uniform return type with explicit coercions for GADT-like type parameters.
This rejigging is what rejigConRes does. The problem is, though, that checking
that the return type is appropriate is much easier when done over *Type*,
not *HsType*.
So, we want to make rejigConRes lazy and then check the validity of the return
type in checkValidDataCon. But, if the return type is bogus, rejigConRes can't
work -- it will have a failed pattern match. Luckily, if we run
checkValidDataCon before ever looking at the rejigged return type
(checkValidDataCon checks the dataConUserType, which is not rejigged!), we
catch the error before forcing the rejigged type and panicking.
-}
-- Example
-- data instance T (b,c) where
-- TI :: forall e. e -> T (e,e)
--
-- The representation tycon looks like this:
-- data :R7T b c where
-- TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
-- In this case orig_res_ty = T (e,e)
rejigConRes :: [TyVar] -> Type -- Template for result type; e.g.
-- data instance T [a] b c = ...
-- gives template ([a,b,c], T [a] b c)
-> [TyVar] -- where MkT :: forall x y z. ...
-> ResType Type
-> ([TyVar], -- Universal
[TyVar], -- Existential (distinct OccNames from univs)
[(TyVar,Type)], -- Equality predicates
Type) -- Typechecked return type
-- We don't check that the TyCon given in the ResTy is
-- the same as the parent tycon, because checkValidDataCon will do it
rejigConRes tmpl_tvs res_ty dc_tvs ResTyH98
= (tmpl_tvs, dc_tvs, [], res_ty)
-- In H98 syntax the dc_tvs are the existential ones
-- data T a b c = forall d e. MkT ...
-- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
rejigConRes tmpl_tvs res_tmpl dc_tvs (ResTyGADT _ res_ty)
-- E.g. data T [a] b c where
-- MkT :: forall x y z. T [(x,y)] z z
-- Then we generate
-- Univ tyvars Eq-spec
-- a a~(x,y)
-- b b~z
-- z
-- Existentials are the leftover type vars: [x,y]
-- So we return ([a,b,z], [x,y], [a~(x,y),b~z], T [(x,y)] z z)
= (univ_tvs, ex_tvs, eq_spec, res_ty)
where
Just subst = tcMatchTy (mkVarSet tmpl_tvs) res_tmpl res_ty
-- This 'Just' pattern is sure to match, because if not
-- checkValidDataCon will complain first.
-- See Note [Checking GADT return types]
-- /Lazily/ figure out the univ_tvs etc
-- Each univ_tv is either a dc_tv or a tmpl_tv
(univ_tvs, eq_spec) = foldr choose ([], []) tmpl_tvs
choose tmpl (univs, eqs)
| Just ty <- lookupTyVar subst tmpl
= case tcGetTyVar_maybe ty of
Just tv | not (tv `elem` univs)
-> (tv:univs, eqs)
_other -> (new_tmpl:univs, (new_tmpl,ty):eqs)
where -- see Note [Substitution in template variables kinds]
new_tmpl = updateTyVarKind (substTy subst) tmpl
| otherwise = pprPanic "tcResultType" (ppr res_ty)
ex_tvs = dc_tvs `minusList` univ_tvs
{-
Note [Substitution in template variables kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
data List a = Nil | Cons a (List a)
data SList s as where
SNil :: SList s Nil
We call tcResultType with
tmpl_tvs = [(k :: BOX), (s :: k -> *), (as :: List k)]
res_tmpl = SList k s as
res_ty = ResTyGADT (SList k1 (s1 :: k1 -> *) (Nil k1))
We get subst:
k -> k1
s -> s1
as -> Nil k1
Now we want to find out the universal variables and the equivalences
between some of them and types (GADT).
In this example, k and s are mapped to exactly variables which are not
already present in the universal set, so we just add them without any
coercion.
But 'as' is mapped to 'Nil k1', so we add 'as' to the universal set,
and add the equivalence with 'Nil k1' in 'eqs'.
The problem is that with kind polymorphism, as's kind may now contain
kind variables, and we have to apply the template substitution to it,
which is why we create new_tmpl.
The template substitution only maps kind variables to kind variables,
since GADTs are not kind indexed.
************************************************************************
* *
Validity checking
* *
************************************************************************
Validity checking is done once the mutually-recursive knot has been
tied, so we can look at things freely.
-}
checkClassCycleErrs :: Class -> TcM ()
checkClassCycleErrs cls = mapM_ recClsErr (calcClassCycles cls)
checkValidTyCl :: TyThing -> TcM ()
checkValidTyCl thing
= setSrcSpan (getSrcSpan thing) $
addTyThingCtxt thing $
case thing of
ATyCon tc -> checkValidTyCon tc
AnId _ -> return () -- Generic default methods are checked
-- with their parent class
ACoAxiom _ -> return () -- Axioms checked with their parent
-- closed family tycon
_ -> pprTrace "checkValidTyCl" (ppr thing) $ return ()
-------------------------
-- For data types declared with record syntax, we require
-- that each constructor that has a field 'f'
-- (a) has the same result type
-- (b) has the same type for 'f'
-- modulo alpha conversion of the quantified type variables
-- of the constructor.
--
-- Note that we allow existentials to match because the
-- fields can never meet. E.g
-- data T where
-- T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
-- T2 { f1 :: c, f2 :: c, f3 ::Int } :: T
-- Here we do not complain about f1,f2 because they are existential
checkValidTyCon :: TyCon -> TcM ()
checkValidTyCon tc
| Just cl <- tyConClass_maybe tc
= checkValidClass cl
| Just syn_rhs <- synTyConRhs_maybe tc
= checkValidType syn_ctxt syn_rhs
| Just fam_flav <- famTyConFlav_maybe tc
= case fam_flav of
{ ClosedSynFamilyTyCon ax -> checkValidClosedCoAxiom ax
; AbstractClosedSynFamilyTyCon ->
do { hsBoot <- tcIsHsBootOrSig
; checkTc hsBoot $
ptext (sLit "You may omit the equations in a closed type family") $$
ptext (sLit "only in a .hs-boot file") }
; OpenSynFamilyTyCon -> return ()
; BuiltInSynFamTyCon _ -> return () }
| otherwise
= do { -- Check the context on the data decl
traceTc "cvtc1" (ppr tc)
; checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
; traceTc "cvtc2" (ppr tc)
; dflags <- getDynFlags
; existential_ok <- xoptM Opt_ExistentialQuantification
; gadt_ok <- xoptM Opt_GADTs
; let ex_ok = existential_ok || gadt_ok -- Data cons can have existential context
; mapM_ (checkValidDataCon dflags ex_ok tc) data_cons
-- Check that fields with the same name share a type
; mapM_ check_fields groups }
where
syn_ctxt = TySynCtxt name
name = tyConName tc
data_cons = tyConDataCons tc
groups = equivClasses cmp_fld (concatMap get_fields data_cons)
cmp_fld (f1,_) (f2,_) = f1 `compare` f2
get_fields con = dataConFieldLabels con `zip` repeat con
-- dataConFieldLabels may return the empty list, which is fine
-- See Note [GADT record selectors] in MkId.lhs
-- We must check (a) that the named field has the same
-- type in each constructor
-- (b) that those constructors have the same result type
--
-- However, the constructors may have differently named type variable
-- and (worse) we don't know how the correspond to each other. E.g.
-- C1 :: forall a b. { f :: a, g :: b } -> T a b
-- C2 :: forall d c. { f :: c, g :: c } -> T c d
--
-- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
-- result type against other candidates' types BOTH WAYS ROUND.
-- If they magically agrees, take the substitution and
-- apply them to the latter ones, and see if they match perfectly.
check_fields ((label, con1) : other_fields)
-- These fields all have the same name, but are from
-- different constructors in the data type
= recoverM (return ()) $ mapM_ checkOne other_fields
-- Check that all the fields in the group have the same type
-- NB: this check assumes that all the constructors of a given
-- data type use the same type variables
where
(tvs1, _, _, res1) = dataConSig con1
ts1 = mkVarSet tvs1
fty1 = dataConFieldType con1 label
checkOne (_, con2) -- Do it bothways to ensure they are structurally identical
= do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
where
(tvs2, _, _, res2) = dataConSig con2
ts2 = mkVarSet tvs2
fty2 = dataConFieldType con2 label
check_fields [] = panic "checkValidTyCon/check_fields []"
checkValidClosedCoAxiom :: CoAxiom Branched -> TcM ()
checkValidClosedCoAxiom (CoAxiom { co_ax_branches = branches, co_ax_tc = tc })
= tcAddClosedTypeFamilyDeclCtxt tc $
do { brListFoldlM_ check_accessibility [] branches
; void $ brListMapM (checkValidTyFamInst Nothing tc) branches }
where
check_accessibility :: [CoAxBranch] -- prev branches (in reverse order)
-> CoAxBranch -- cur branch
-> TcM [CoAxBranch] -- cur : prev
-- Check whether the branch is dominated by earlier
-- ones and hence is inaccessible
check_accessibility prev_branches cur_branch
= do { when (cur_branch `isDominatedBy` prev_branches) $
addWarnAt (coAxBranchSpan cur_branch) $
inaccessibleCoAxBranch tc cur_branch
; return (cur_branch : prev_branches) }
checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
-> Type -> Type -> Type -> Type -> TcM ()
checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
= do { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
where
mb_subst1 = tcMatchTy tvs1 res1 res2
mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
-------------------------------
checkValidDataCon :: DynFlags -> Bool -> TyCon -> DataCon -> TcM ()
checkValidDataCon dflags existential_ok tc con
= setSrcSpan (srcLocSpan (getSrcLoc con)) $
addErrCtxt (dataConCtxt con) $
do { -- Check that the return type of the data constructor
-- matches the type constructor; eg reject this:
-- data T a where { MkT :: Bogus a }
-- c.f. Note [Check role annotations in a second pass]
-- and Note [Checking GADT return types]
let tc_tvs = tyConTyVars tc
res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs)
orig_res_ty = dataConOrigResTy con
; traceTc "checkValidDataCon" (vcat
[ ppr con, ppr tc, ppr tc_tvs
, ppr res_ty_tmpl <+> dcolon <+> ppr (typeKind res_ty_tmpl)
, ppr orig_res_ty <+> dcolon <+> ppr (typeKind orig_res_ty)])
; checkTc (isJust (tcMatchTy (mkVarSet tc_tvs)
res_ty_tmpl
orig_res_ty))
(badDataConTyCon con res_ty_tmpl orig_res_ty)
-- Check that the result type is a *monotype*
-- e.g. reject this: MkT :: T (forall a. a->a)
-- Reason: it's really the argument of an equality constraint
; checkValidMonoType orig_res_ty
-- Check all argument types for validity
; checkValidType ctxt (dataConUserType con)
-- Extra checks for newtype data constructors
; when (isNewTyCon tc) (checkNewDataCon con)
-- Check that UNPACK pragmas and bangs work out
-- E.g. reject data T = MkT {-# UNPACK #-} Int -- No "!"
-- data T = MkT {-# UNPACK #-} !a -- Can't unpack
; mapM_ check_bang (zip3 (dataConSrcBangs con) (dataConImplBangs con) [1..])
-- Check that existentials are allowed if they are used
; checkTc (existential_ok || isVanillaDataCon con)
(badExistential con)
-- Check that we aren't doing GADT type refinement on kind variables
-- e.g reject data T (a::k) where
-- T1 :: T Int
-- T2 :: T Maybe
; checkTc (not (any (isKindVar . fst) (dataConEqSpec con)))
(badGadtKindCon con)
; traceTc "Done validity of data con" (ppr con <+> ppr (dataConRepType con))
}
where
ctxt = ConArgCtxt (dataConName con)
check_bang (HsSrcBang _ (Just want_unpack) has_bang, rep_bang, n)
| want_unpack, not has_bang
= addWarnTc (bad_bang n (ptext (sLit "UNPACK pragma lacks '!'")))
| want_unpack
, case rep_bang of { HsUnpack {} -> False; _ -> True }
, not (gopt Opt_OmitInterfacePragmas dflags)
-- If not optimising, se don't unpack, so don't complain!
-- See MkId.dataConArgRep, the (HsBang True) case
= addWarnTc (bad_bang n (ptext (sLit "Ignoring unusable UNPACK pragma")))
check_bang _
= return ()
bad_bang n herald
= hang herald 2 (ptext (sLit "on the") <+> speakNth n
<+> ptext (sLit "argument of") <+> quotes (ppr con))
-------------------------------
checkNewDataCon :: DataCon -> TcM ()
-- Further checks for the data constructor of a newtype
checkNewDataCon con
= do { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
-- One argument
; check_con (null eq_spec) $
ptext (sLit "A newtype constructor must have a return type of form T a1 ... an")
-- Return type is (T a b c)
; check_con (null theta) $
ptext (sLit "A newtype constructor cannot have a context in its type")
; check_con (null ex_tvs) $
ptext (sLit "A newtype constructor cannot have existential type variables")
-- No existentials
; checkTc (not (any isBanged (dataConSrcBangs con)))
(newtypeStrictError con)
-- No strictness
}
where
(_univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _res_ty) = dataConFullSig con
check_con what msg
= checkTc what (msg $$ ppr con <+> dcolon <+> ppr (dataConUserType con))
-------------------------------
checkValidClass :: Class -> TcM ()
checkValidClass cls
= do { constrained_class_methods <- xoptM Opt_ConstrainedClassMethods
; multi_param_type_classes <- xoptM Opt_MultiParamTypeClasses
; nullary_type_classes <- xoptM Opt_NullaryTypeClasses
; fundep_classes <- xoptM Opt_FunctionalDependencies
-- Check that the class is unary, unless multiparameter type classes
-- are enabled; also recognize deprecated nullary type classes
-- extension (subsumed by multiparameter type classes, Trac #8993)
; checkTc (multi_param_type_classes || cls_arity == 1 ||
(nullary_type_classes && cls_arity == 0))
(classArityErr cls_arity cls)
; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
-- Check the super-classes
; checkValidTheta (ClassSCCtxt (className cls)) theta
-- Now check for cyclic superclasses
-- If there are superclass cycles, checkClassCycleErrs bails.
; checkClassCycleErrs cls
-- Check the class operations.
-- But only if there have been no earlier errors
-- See Note [Abort when superclass cycle is detected]
; whenNoErrs $
mapM_ (check_op constrained_class_methods) op_stuff
-- Check the associated type defaults are well-formed and instantiated
; mapM_ check_at_defs at_stuff }
where
(tyvars, fundeps, theta, _, at_stuff, op_stuff) = classExtraBigSig cls
cls_arity = count isTypeVar tyvars -- Ignore kind variables
cls_tv_set = mkVarSet tyvars
mini_env = zipVarEnv tyvars (mkTyVarTys tyvars)
check_op constrained_class_methods (sel_id, dm)
= addErrCtxt (classOpCtxt sel_id tau) $ do
{ checkValidTheta ctxt (tail theta)
-- The 'tail' removes the initial (C a) from the
-- class itself, leaving just the method type
; traceTc "class op type" (ppr op_ty <+> ppr tau)
; checkValidType ctxt tau
-- Check that the method type mentions a class variable
-- But actually check that the variables *reachable from*
-- the method type include a class variable.
-- Example: tc223
-- class Error e => Game b mv e | b -> mv e where
-- newBoard :: MonadState b m => m ()
-- Here, MonadState has a fundep m->b, so newBoard is fine
; check_mentions (growThetaTyVars theta (tyVarsOfType tau))
(ptext (sLit "class method") <+> quotes (ppr sel_id))
; case dm of
GenDefMeth dm_name -> do { dm_id <- tcLookupId dm_name
; checkValidType (FunSigCtxt op_name) (idType dm_id) }
_ -> return ()
}
where
ctxt = FunSigCtxt op_name
op_name = idName sel_id
op_ty = idType sel_id
(_,theta1,tau1) = tcSplitSigmaTy op_ty
(_,theta2,tau2) = tcSplitSigmaTy tau1
(theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
| otherwise = (theta1, mkPhiTy (tail theta1) tau1)
-- Ugh! The function might have a type like
-- op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
-- With -XConstrainedClassMethods, we want to allow this, even though the inner
-- forall has an (Eq a) constraint. Whereas in general, each constraint
-- in the context of a for-all must mention at least one quantified
-- type variable. What a mess!
check_at_defs (ATI fam_tc m_dflt_rhs)
= do { check_mentions (mkVarSet fam_tvs) $
ptext (sLit "associated type") <+> quotes (ppr fam_tc)
; whenIsJust m_dflt_rhs $ \ (rhs, loc) ->
checkValidTyFamEqn (Just (cls, mini_env)) fam_tc
fam_tvs (mkTyVarTys fam_tvs) rhs loc }
where
fam_tvs = tyConTyVars fam_tc
check_mentions :: TyVarSet -> SDoc -> TcM ()
-- Check that the thing (method or associated type) mentions at least
-- one of the class type variables
-- The check is disabled for nullary type classes,
-- since there is no possible ambiguity (Trac #10020)
check_mentions thing_tvs thing_doc
= checkTc (cls_arity == 0 || thing_tvs `intersectsVarSet` cls_tv_set)
(noClassTyVarErr cls thing_doc)
checkFamFlag :: Name -> TcM ()
-- Check that we don't use families without -XTypeFamilies
-- The parser won't even parse them, but I suppose a GHC API
-- client might have a go!
checkFamFlag tc_name
= do { idx_tys <- xoptM Opt_TypeFamilies
; checkTc idx_tys err_msg }
where
err_msg = hang (ptext (sLit "Illegal family declaration for") <+> quotes (ppr tc_name))
2 (ptext (sLit "Use TypeFamilies to allow indexed type families"))
{-
Note [Abort when superclass cycle is detected]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We must avoid doing the ambiguity check for the methods (in
checkValidClass.check_op) when there are already errors accumulated.
This is because one of the errors may be a superclass cycle, and
superclass cycles cause canonicalization to loop. Here is a
representative example:
class D a => C a where
meth :: D a => ()
class C a => D a
This fixes Trac #9415, #9739
************************************************************************
* *
Checking role validity
* *
************************************************************************
-}
checkValidRoleAnnots :: RoleAnnots -> TyThing -> TcM ()
checkValidRoleAnnots role_annots thing
= case thing of
{ ATyCon tc
| isTypeSynonymTyCon tc -> check_no_roles
| isFamilyTyCon tc -> check_no_roles
| isAlgTyCon tc -> check_roles
where
name = tyConName tc
-- Role annotations are given only on *type* variables, but a tycon stores
-- roles for all variables. So, we drop the kind roles (which are all
-- Nominal, anyway).
tyvars = tyConTyVars tc
roles = tyConRoles tc
(kind_vars, type_vars) = span isKindVar tyvars
type_roles = dropList kind_vars roles
role_annot_decl_maybe = lookupRoleAnnots role_annots name
check_roles
= whenIsJust role_annot_decl_maybe $
\decl@(L loc (RoleAnnotDecl _ the_role_annots)) ->
addRoleAnnotCtxt name $
setSrcSpan loc $ do
{ role_annots_ok <- xoptM Opt_RoleAnnotations
; checkTc role_annots_ok $ needXRoleAnnotations tc
; checkTc (type_vars `equalLength` the_role_annots)
(wrongNumberOfRoles type_vars decl)
; _ <- zipWith3M checkRoleAnnot type_vars the_role_annots type_roles
-- Representational or phantom roles for class parameters
-- quickly lead to incoherence. So, we require
-- IncoherentInstances to have them. See #8773.
; incoherent_roles_ok <- xoptM Opt_IncoherentInstances
; checkTc ( incoherent_roles_ok
|| (not $ isClassTyCon tc)
|| (all (== Nominal) type_roles))
incoherentRoles
; lint <- goptM Opt_DoCoreLinting
; when lint $ checkValidRoles tc }
check_no_roles
= whenIsJust role_annot_decl_maybe illegalRoleAnnotDecl
; _ -> return () }
checkRoleAnnot :: TyVar -> Located (Maybe Role) -> Role -> TcM ()
checkRoleAnnot _ (L _ Nothing) _ = return ()
checkRoleAnnot tv (L _ (Just r1)) r2
= when (r1 /= r2) $
addErrTc $ badRoleAnnot (tyVarName tv) r1 r2
-- This is a double-check on the role inference algorithm. It is only run when
-- -dcore-lint is enabled. See Note [Role inference] in TcTyDecls
checkValidRoles :: TyCon -> TcM ()
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism] in CoreLint
checkValidRoles tc
| isAlgTyCon tc
-- tyConDataCons returns an empty list for data families
= mapM_ check_dc_roles (tyConDataCons tc)
| Just rhs <- synTyConRhs_maybe tc
= check_ty_roles (zipVarEnv (tyConTyVars tc) (tyConRoles tc)) Representational rhs
| otherwise
= return ()
where
check_dc_roles datacon
= do { traceTc "check_dc_roles" (ppr datacon <+> ppr (tyConRoles tc))
; mapM_ (check_ty_roles role_env Representational) $
eqSpecPreds eq_spec ++ theta ++ arg_tys }
-- See Note [Role-checking data constructor arguments] in TcTyDecls
where
(univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _res_ty) = dataConFullSig datacon
univ_roles = zipVarEnv univ_tvs (tyConRoles tc)
-- zipVarEnv uses zipEqual, but we don't want that for ex_tvs
ex_roles = mkVarEnv (zip ex_tvs (repeat Nominal))
role_env = univ_roles `plusVarEnv` ex_roles
check_ty_roles env role (TyVarTy tv)
= case lookupVarEnv env tv of
Just role' -> unless (role' `ltRole` role || role' == role) $
report_error $ ptext (sLit "type variable") <+> quotes (ppr tv) <+>
ptext (sLit "cannot have role") <+> ppr role <+>
ptext (sLit "because it was assigned role") <+> ppr role'
Nothing -> report_error $ ptext (sLit "type variable") <+> quotes (ppr tv) <+>
ptext (sLit "missing in environment")
check_ty_roles env Representational (TyConApp tc tys)
= let roles' = tyConRoles tc in
zipWithM_ (maybe_check_ty_roles env) roles' tys
check_ty_roles env Nominal (TyConApp _ tys)
= mapM_ (check_ty_roles env Nominal) tys
check_ty_roles _ Phantom ty@(TyConApp {})
= pprPanic "check_ty_roles" (ppr ty)
check_ty_roles env role (AppTy ty1 ty2)
= check_ty_roles env role ty1
>> check_ty_roles env Nominal ty2
check_ty_roles env role (FunTy ty1 ty2)
= check_ty_roles env role ty1
>> check_ty_roles env role ty2
check_ty_roles env role (ForAllTy tv ty)
= check_ty_roles (extendVarEnv env tv Nominal) role ty
check_ty_roles _ _ (LitTy {}) = return ()
maybe_check_ty_roles env role ty
= when (role == Nominal || role == Representational) $
check_ty_roles env role ty
report_error doc
= addErrTc $ vcat [ptext (sLit "Internal error in role inference:"),
doc,
ptext (sLit "Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug")]
{-
************************************************************************
* *
Building record selectors
* *
************************************************************************
-}
mkDefaultMethodIds :: [TyThing] -> [Id]
-- See Note [Default method Ids and Template Haskell]
mkDefaultMethodIds things
= [ mkExportedLocalId VanillaId dm_name (idType sel_id)
| ATyCon tc <- things
, Just cls <- [tyConClass_maybe tc]
, (sel_id, DefMeth dm_name) <- classOpItems cls ]
{-
Note [Default method Ids and Template Haskell]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (Trac #4169):
class Numeric a where
fromIntegerNum :: a
fromIntegerNum = ...
ast :: Q [Dec]
ast = [d| instance Numeric Int |]
When we typecheck 'ast' we have done the first pass over the class decl
(in tcTyClDecls), but we have not yet typechecked the default-method
declarations (because they can mention value declarations). So we
must bring the default method Ids into scope first (so they can be seen
when typechecking the [d| .. |] quote, and typecheck them later.
-}
mkRecSelBinds :: [TyThing] -> HsValBinds Name
-- NB We produce *un-typechecked* bindings, rather like 'deriving'
-- This makes life easier, because the later type checking will add
-- all necessary type abstractions and applications
mkRecSelBinds tycons
= ValBindsOut [(NonRecursive, b) | b <- binds] sigs
where
(sigs, binds) = unzip rec_sels
rec_sels = map mkRecSelBind [ (tc,fld)
| ATyCon tc <- tycons
, fld <- tyConFields tc ]
mkRecSelBind :: (TyCon, FieldLabel) -> (LSig Name, LHsBinds Name)
mkRecSelBind (tycon, sel_name)
= (L loc (IdSig sel_id), unitBag (L loc sel_bind))
where
loc = getSrcSpan sel_name
sel_id = mkExportedLocalId rec_details sel_name sel_ty
rec_details = RecSelId { sel_tycon = tycon, sel_naughty = is_naughty }
-- Find a representative constructor, con1
all_cons = tyConDataCons tycon
cons_w_field = [ con | con <- all_cons
, sel_name `elem` dataConFieldLabels con ]
con1 = {-ASSERT( not (null cons_w_field) )-} head cons_w_field
-- Selector type; Note [Polymorphic selectors]
field_ty = dataConFieldType con1 sel_name
data_ty = dataConOrigResTy con1
data_tvs = tyVarsOfType data_ty
is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tvs)
(field_tvs, field_theta, field_tau) = tcSplitSigmaTy field_ty
sel_ty | is_naughty = unitTy -- See Note [Naughty record selectors]
| otherwise = mkForAllTys (varSetElemsKvsFirst $
data_tvs `extendVarSetList` field_tvs) $
mkPhiTy (dataConStupidTheta con1) $ -- Urgh!
mkPhiTy field_theta $ -- Urgh!
mkFunTy data_ty field_tau
-- Make the binding: sel (C2 { fld = x }) = x
-- sel (C7 { fld = x }) = x
-- where cons_w_field = [C2,C7]
sel_bind = mkTopFunBind Generated sel_lname alts
where
alts | is_naughty = [mkSimpleMatch [] unit_rhs]
| otherwise = map mk_match cons_w_field ++ deflt
mk_match con = mkSimpleMatch [L loc (mk_sel_pat con)]
(L loc (HsVar field_var))
mk_sel_pat con = ConPatIn (L loc (getName con)) (RecCon rec_fields)
rec_fields = HsRecFields { rec_flds = [rec_field], rec_dotdot = Nothing }
rec_field = noLoc (HsRecField { hsRecFieldId = sel_lname
, hsRecFieldArg = L loc (VarPat field_var)
, hsRecPun = False })
sel_lname = L loc sel_name
field_var = mkInternalName (mkBuiltinUnique 1) (getOccName sel_name) loc
-- Add catch-all default case unless the case is exhaustive
-- We do this explicitly so that we get a nice error message that
-- mentions this particular record selector
deflt | all dealt_with all_cons = []
| otherwise = [mkSimpleMatch [L loc (WildPat placeHolderType)]
(mkHsApp (L loc (HsVar (getName rEC_SEL_ERROR_ID)))
(L loc (HsLit msg_lit)))]
-- Do not add a default case unless there are unmatched
-- constructors. We must take account of GADTs, else we
-- get overlap warning messages from the pattern-match checker
-- NB: we need to pass type args for the *representation* TyCon
-- to dataConCannotMatch, hence the calculation of inst_tys
-- This matters in data families
-- data instance T Int a where
-- A :: { fld :: Int } -> T Int Bool
-- B :: { fld :: Int } -> T Int Char
dealt_with con = con `elem` cons_w_field || dataConCannotMatch inst_tys con
inst_tys = substTyVars (mkTopTvSubst (dataConEqSpec con1)) (dataConUnivTyVars con1)
unit_rhs = mkLHsTupleExpr []
msg_lit = HsStringPrim "" $ unsafeMkByteString $
occNameString (getOccName sel_name)
---------------
tyConFields :: TyCon -> [FieldLabel]
tyConFields tc
| isAlgTyCon tc = nub (concatMap dataConFieldLabels (tyConDataCons tc))
| otherwise = []
{-
Note [Polymorphic selectors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When a record has a polymorphic field, we pull the foralls out to the front.
data T = MkT { f :: forall a. [a] -> a }
Then f :: forall a. T -> [a] -> a
NOT f :: T -> forall a. [a] -> a
This is horrid. It's only needed in deeply obscure cases, which I hate.
The only case I know is test tc163, which is worth looking at. It's far
from clear that this test should succeed at all!
Note [Naughty record selectors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A "naughty" field is one for which we can't define a record
selector, because an existential type variable would escape. For example:
data T = forall a. MkT { x,y::a }
We obviously can't define
x (MkT v _) = v
Nevertheless we *do* put a RecSelId into the type environment
so that if the user tries to use 'x' as a selector we can bleat
helpfully, rather than saying unhelpfully that 'x' is not in scope.
Hence the sel_naughty flag, to identify record selectors that don't really exist.
In general, a field is "naughty" if its type mentions a type variable that
isn't in the result type of the constructor. Note that this *allows*
GADT record selectors (Note [GADT record selectors]) whose types may look
like sel :: T [a] -> a
For naughty selectors we make a dummy binding
sel = ()
for naughty selectors, so that the later type-check will add them to the
environment, and they'll be exported. The function is never called, because
the tyepchecker spots the sel_naughty field.
Note [GADT record selectors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For GADTs, we require that all constructors with a common field 'f' have the same
result type (modulo alpha conversion). [Checked in TcTyClsDecls.checkValidTyCon]
E.g.
data T where
T1 { f :: Maybe a } :: T [a]
T2 { f :: Maybe a, y :: b } :: T [a]
T3 :: T Int
and now the selector takes that result type as its argument:
f :: forall a. T [a] -> Maybe a
Details: the "real" types of T1,T2 are:
T1 :: forall r a. (r~[a]) => a -> T r
T2 :: forall r a b. (r~[a]) => a -> b -> T r
So the selector loooks like this:
f :: forall a. T [a] -> Maybe a
f (a:*) (t:T [a])
= case t of
T1 c (g:[a]~[c]) (v:Maybe c) -> v `cast` Maybe (right (sym g))
T2 c d (g:[a]~[c]) (v:Maybe c) (w:d) -> v `cast` Maybe (right (sym g))
T3 -> error "T3 does not have field f"
Note the forall'd tyvars of the selector are just the free tyvars
of the result type; there may be other tyvars in the constructor's
type (e.g. 'b' in T2).
Note the need for casts in the result!
Note [Selector running example]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's OK to combine GADTs and type families. Here's a running example:
data instance T [a] where
T1 { fld :: b } :: T [Maybe b]
The representation type looks like this
data :R7T a where
T1 { fld :: b } :: :R7T (Maybe b)
and there's coercion from the family type to the representation type
:CoR7T a :: T [a] ~ :R7T a
The selector we want for fld looks like this:
fld :: forall b. T [Maybe b] -> b
fld = /\b. \(d::T [Maybe b]).
case d `cast` :CoR7T (Maybe b) of
T1 (x::b) -> x
The scrutinee of the case has type :R7T (Maybe b), which can be
gotten by appying the eq_spec to the univ_tvs of the data con.
************************************************************************
* *
Error messages
* *
************************************************************************
-}
tcAddTyFamInstCtxt :: TyFamInstDecl Name -> TcM a -> TcM a
tcAddTyFamInstCtxt decl
= tcAddFamInstCtxt (ptext (sLit "type instance")) (tyFamInstDeclName decl)
tcAddDataFamInstCtxt :: DataFamInstDecl Name -> TcM a -> TcM a
tcAddDataFamInstCtxt decl
= tcAddFamInstCtxt (pprDataFamInstFlavour decl <+> ptext (sLit "instance"))
(unLoc (dfid_tycon decl))
tcAddFamInstCtxt :: SDoc -> Name -> TcM a -> TcM a
tcAddFamInstCtxt flavour tycon thing_inside
= addErrCtxt ctxt thing_inside
where
ctxt = hsep [ptext (sLit "In the") <+> flavour
<+> ptext (sLit "declaration for"),
quotes (ppr tycon)]
tcAddClosedTypeFamilyDeclCtxt :: TyCon -> TcM a -> TcM a
tcAddClosedTypeFamilyDeclCtxt tc
= addErrCtxt ctxt
where
ctxt = ptext (sLit "In the equations for closed type family") <+>
quotes (ppr tc)
resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
resultTypeMisMatch field_name con1 con2
= vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
nest 2 $ ptext (sLit "but have different result types")]
fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
fieldTypeMisMatch field_name con1 con2
= sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
ptext (sLit "give different types for field"), quotes (ppr field_name)]
dataConCtxtName :: [Located Name] -> SDoc
dataConCtxtName [con]
= ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
dataConCtxtName con
= ptext (sLit "In the definition of data constructors") <+> interpp'SP con
dataConCtxt :: Outputable a => a -> SDoc
dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
classOpCtxt :: Var -> Type -> SDoc
classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
nest 2 (pprPrefixOcc sel_id <+> dcolon <+> ppr tau)]
classArityErr :: Int -> Class -> SDoc
classArityErr n cls
| n == 0 = mkErr "No" "no-parameter"
| otherwise = mkErr "Too many" "multi-parameter"
where
mkErr howMany allowWhat =
vcat [ptext (sLit $ howMany ++ " parameters for class") <+> quotes (ppr cls),
parens (ptext (sLit $ "Use MultiParamTypeClasses to allow "
++ allowWhat ++ " classes"))]
classFunDepsErr :: Class -> SDoc
classFunDepsErr cls
= vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
parens (ptext (sLit "Use FunctionalDependencies to allow fundeps"))]
noClassTyVarErr :: Class -> SDoc -> SDoc
noClassTyVarErr clas what
= sep [ptext (sLit "The") <+> what,
ptext (sLit "mentions none of the type or kind variables of the class") <+>
quotes (ppr clas <+> hsep (map ppr (classTyVars clas)))]
recSynErr :: [LTyClDecl Name] -> TcRn ()
recSynErr syn_decls
= setSrcSpan (getLoc (head sorted_decls)) $
addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
nest 2 (vcat (map ppr_decl sorted_decls))])
where
sorted_decls = sortLocated syn_decls
ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
recClsErr :: [TyCon] -> TcRn ()
recClsErr cycles
= addErr (sep [ptext (sLit "Cycle in class declaration (via superclasses):"),
nest 2 (hsep (intersperse (text "->") (map ppr cycles)))])
badDataConTyCon :: DataCon -> Type -> Type -> SDoc
badDataConTyCon data_con res_ty_tmpl actual_res_ty
= hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
ptext (sLit "returns type") <+> quotes (ppr actual_res_ty))
2 (ptext (sLit "instead of an instance of its parent type") <+> quotes (ppr res_ty_tmpl))
badGadtKindCon :: DataCon -> SDoc
badGadtKindCon data_con
= hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con)
<+> ptext (sLit "cannot be GADT-like in its *kind* arguments"))
2 (ppr data_con <+> dcolon <+> ppr (dataConUserType data_con))
badGadtDecl :: Name -> SDoc
badGadtDecl tc_name
= vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
, nest 2 (parens $ ptext (sLit "Use GADTs to allow GADTs")) ]
badExistential :: DataCon -> SDoc
badExistential con
= hang (ptext (sLit "Data constructor") <+> quotes (ppr con) <+>
ptext (sLit "has existential type variables, a context, or a specialised result type"))
2 (vcat [ ppr con <+> dcolon <+> ppr (dataConUserType con)
, parens $ ptext (sLit "Use ExistentialQuantification or GADTs to allow this") ])
badStupidTheta :: Name -> SDoc
badStupidTheta tc_name
= ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
newtypeConError :: Name -> Int -> SDoc
newtypeConError tycon n
= sep [ptext (sLit "A newtype must have exactly one constructor,"),
nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
newtypeStrictError :: DataCon -> SDoc
newtypeStrictError con
= sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
newtypeFieldErr :: DataCon -> Int -> SDoc
newtypeFieldErr con_name n_flds
= sep [ptext (sLit "The constructor of a newtype must have exactly one field"),
nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
badSigTyDecl :: Name -> SDoc
badSigTyDecl tc_name
= vcat [ ptext (sLit "Illegal kind signature") <+>
quotes (ppr tc_name)
, nest 2 (parens $ ptext (sLit "Use KindSignatures to allow kind signatures")) ]
emptyConDeclsErr :: Name -> SDoc
emptyConDeclsErr tycon
= sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
nest 2 $ ptext (sLit "(EmptyDataDecls permits this)")]
wrongKindOfFamily :: TyCon -> SDoc
wrongKindOfFamily family
= ptext (sLit "Wrong category of family instance; declaration was for a")
<+> kindOfFamily
where
kindOfFamily | isTypeFamilyTyCon family = text "type family"
| isDataFamilyTyCon family = text "data family"
| otherwise = pprPanic "wrongKindOfFamily" (ppr family)
wrongNumberOfParmsErr :: Arity -> SDoc
wrongNumberOfParmsErr max_args
= ptext (sLit "Number of parameters must match family declaration; expected")
<+> ppr max_args
wrongTyFamName :: Name -> Name -> SDoc
wrongTyFamName fam_tc_name eqn_tc_name
= hang (ptext (sLit "Mismatched type name in type family instance."))
2 (vcat [ ptext (sLit "Expected:") <+> ppr fam_tc_name
, ptext (sLit " Actual:") <+> ppr eqn_tc_name ])
inaccessibleCoAxBranch :: TyCon -> CoAxBranch -> SDoc
inaccessibleCoAxBranch tc fi
= ptext (sLit "Overlapped type family instance equation:") $$
(pprCoAxBranch tc fi)
badRoleAnnot :: Name -> Role -> Role -> SDoc
badRoleAnnot var annot inferred
= hang (ptext (sLit "Role mismatch on variable") <+> ppr var <> colon)
2 (sep [ ptext (sLit "Annotation says"), ppr annot
, ptext (sLit "but role"), ppr inferred
, ptext (sLit "is required") ])
wrongNumberOfRoles :: [a] -> LRoleAnnotDecl Name -> SDoc
wrongNumberOfRoles tyvars d@(L _ (RoleAnnotDecl _ annots))
= hang (ptext (sLit "Wrong number of roles listed in role annotation;") $$
ptext (sLit "Expected") <+> (ppr $ length tyvars) <> comma <+>
ptext (sLit "got") <+> (ppr $ length annots) <> colon)
2 (ppr d)
illegalRoleAnnotDecl :: LRoleAnnotDecl Name -> TcM ()
illegalRoleAnnotDecl (L loc (RoleAnnotDecl tycon _))
= setErrCtxt [] $
setSrcSpan loc $
addErrTc (ptext (sLit "Illegal role annotation for") <+> ppr tycon <> char ';' $$
ptext (sLit "they are allowed only for datatypes and classes."))
needXRoleAnnotations :: TyCon -> SDoc
needXRoleAnnotations tc
= ptext (sLit "Illegal role annotation for") <+> ppr tc <> char ';' $$
ptext (sLit "did you intend to use RoleAnnotations?")
incoherentRoles :: SDoc
incoherentRoles = (text "Roles other than" <+> quotes (text "nominal") <+>
text "for class parameters can lead to incoherence.") $$
(text "Use IncoherentInstances to allow this; bad role found")
addTyThingCtxt :: TyThing -> TcM a -> TcM a
addTyThingCtxt thing
= addErrCtxt ctxt
where
name = getName thing
flav = case thing of
ATyCon tc
| isClassTyCon tc -> ptext (sLit "class")
| isTypeFamilyTyCon tc -> ptext (sLit "type family")
| isDataFamilyTyCon tc -> ptext (sLit "data family")
| isTypeSynonymTyCon tc -> ptext (sLit "type")
| isNewTyCon tc -> ptext (sLit "newtype")
| isDataTyCon tc -> ptext (sLit "data")
_ -> pprTrace "addTyThingCtxt strange" (ppr thing)
Outputable.empty
ctxt = hsep [ ptext (sLit "In the"), flav
, ptext (sLit "declaration for"), quotes (ppr name) ]
addRoleAnnotCtxt :: Name -> TcM a -> TcM a
addRoleAnnotCtxt name
= addErrCtxt $
text "while checking a role annotation for" <+> quotes (ppr name)
|
alexander-at-github/eta
|
compiler/ETA/TypeCheck/TcTyClsDecls.hs
|
Haskell
|
bsd-3-clause
| 100,819
|
{-
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.0
Kubernetes API version: v1.9.12
Generated by Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
-}
{-|
Module : Kubernetes.OpenAPI.API.Storage
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing -fno-warn-unused-binds -fno-warn-unused-imports #-}
module Kubernetes.OpenAPI.API.Storage where
import Kubernetes.OpenAPI.Core
import Kubernetes.OpenAPI.MimeTypes
import Kubernetes.OpenAPI.Model as M
import qualified Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Data as P (Typeable, TypeRep, typeOf, typeRep)
import qualified Data.Foldable as P
import qualified Data.Map as Map
import qualified Data.Maybe as P
import qualified Data.Proxy as P (Proxy(..))
import qualified Data.Set as Set
import qualified Data.String as P
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Time as TI
import qualified Network.HTTP.Client.MultipartFormData as NH
import qualified Network.HTTP.Media as ME
import qualified Network.HTTP.Types as NH
import qualified Web.FormUrlEncoded as WH
import qualified Web.HttpApiData as WH
import Data.Text (Text)
import GHC.Base ((<|>))
import Prelude ((==),(/=),($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor)
import qualified Prelude as P
-- * Operations
-- ** Storage
-- *** getAPIGroup
-- | @GET \/apis\/storage.k8s.io\/@
--
-- get information of a group
--
-- AuthMethod: 'AuthApiKeyBearerToken'
--
getAPIGroup
:: Accept accept -- ^ request accept ('MimeType')
-> KubernetesRequest GetAPIGroup MimeNoContent V1APIGroup accept
getAPIGroup _ =
_mkRequest "GET" ["/apis/storage.k8s.io/"]
`_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyBearerToken)
data GetAPIGroup
-- | @application/json@
instance Consumes GetAPIGroup MimeJSON
-- | @application/yaml@
instance Consumes GetAPIGroup MimeYaml
-- | @application/vnd.kubernetes.protobuf@
instance Consumes GetAPIGroup MimeVndKubernetesProtobuf
-- | @application/json@
instance Produces GetAPIGroup MimeJSON
-- | @application/yaml@
instance Produces GetAPIGroup MimeYaml
-- | @application/vnd.kubernetes.protobuf@
instance Produces GetAPIGroup MimeVndKubernetesProtobuf
|
denibertovic/haskell
|
kubernetes/lib/Kubernetes/OpenAPI/API/Storage.hs
|
Haskell
|
bsd-3-clause
| 2,717
|
module ScrapYourImports where
data Exports = Exports
{ greet :: IO ()
}
makeExports :: String -> Exports
makeExports str = Exports
{ greet = putStrLn str
}
|
sleexyz/haskell-fun
|
ScrapYourImports.hs
|
Haskell
|
bsd-3-clause
| 168
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Text.Syntax.Parser.Attoparsec.Text (
runAsAttoparsec', runAsAttoparsec,
runAsIAttoparsec'
) where
import Data.Attoparsec.Types (Parser)
import Text.Syntax.Parser.Instances ()
import Text.Syntax.Poly (RunAsIParser,
RunAsParser, Syntax (..), TryAlternative (try, (<|>)),
(<||>))
import qualified Data.Attoparsec.Text as A (anyChar, parse, try)
import qualified Data.Attoparsec.Text.Lazy as L
import Data.Text (Text)
import qualified Data.Text.Lazy as L (Text)
import Text.Syntax.Parser.Attoparsec.RunResult (runIResult, runResult)
instance TryAlternative (Parser Text) where
try = A.try
p <|> q = try p <||> q
instance Syntax Char (Parser Text) where
token = A.anyChar
runAsAttoparsec' :: RunAsParser Char Text a ([String], String)
runAsAttoparsec' parser tks = runResult $ A.parse parser tks where
runAsAttoparsec :: RunAsParser Char L.Text a ([String], String)
runAsAttoparsec parser tks =
case L.parse parser tks of
L.Fail _ estack msg -> Left (estack, msg)
L.Done _ r -> Right r
runAsIAttoparsec' :: RunAsIParser Char Text a ([String], String)
runAsIAttoparsec' parser tks = runIResult $ A.parse parser tks
|
schernichkin/haskell-invertible-syntax-attoparsec
|
Text/Syntax/Parser/Attoparsec/Text.hs
|
Haskell
|
bsd-3-clause
| 1,550
|
{- Data/Singletons/Syntax.hs
(c) Richard Eisenberg 2014
eir@cis.upenn.edu
Converts a list of DLetDecs into a LetDecEnv for easier processing,
and contains various other AST definitions.
-}
{-# LANGUAGE DataKinds, TypeFamilies, PolyKinds, DeriveDataTypeable,
StandaloneDeriving, FlexibleInstances #-}
module Data.Singletons.Syntax where
import Prelude hiding ( exp )
import Data.Monoid
import Language.Haskell.TH.Syntax
import Language.Haskell.TH.Desugar
import Data.Map.Strict ( Map )
import qualified Data.Map.Strict as Map
type VarPromotions = [(Name, Name)] -- from term-level name to type-level name
-- the relevant part of declarations
data DataDecl = DataDecl NewOrData Name [DTyVarBndr] [DCon] [DPred]
data ClassDecl ann = ClassDecl { cd_cxt :: DCxt
, cd_name :: Name
, cd_tvbs :: [DTyVarBndr]
, cd_fds :: [FunDep]
, cd_lde :: LetDecEnv ann }
data InstDecl ann = InstDecl { id_cxt :: DCxt
, id_name :: Name
, id_arg_tys :: [DType]
, id_meths :: [(Name, LetDecRHS ann)] }
type UClassDecl = ClassDecl Unannotated
type UInstDecl = InstDecl Unannotated
type AClassDecl = ClassDecl Annotated
type AInstDecl = InstDecl Annotated
{-
We see below several datatypes beginning with "A". These are annotated structures,
necessary for Promote to communicate key things to Single. In particular, promotion
of expressions is *not* deterministic, due to the necessity to create unique names
for lets, cases, and lambdas. So, we put these promotions into an annotated AST
so that Single can use the right promotions.
-}
-- A DExp with let and lambda nodes annotated with their type-level equivalents
data ADExp = ADVarE Name
| ADConE Name
| ADLitE Lit
| ADAppE ADExp ADExp
| ADLamE VarPromotions -- bind these type variables to these term vars
DType -- the promoted lambda
[Name] ADExp
| ADCaseE ADExp DType [ADMatch] DType
-- the first type is the promoted scrutinee;
-- the second type is the return type
| ADLetE ALetDecEnv ADExp
| ADSigE ADExp DType
-- unlike in other places, the DType in an ADMatch (the promoted "case" statement)
-- should be used with DAppT, *not* apply! (Case statements are not defunctionalized.)
data ADMatch = ADMatch VarPromotions DType DPat ADExp
data ADClause = ADClause VarPromotions
[DPat] ADExp
data AnnotationFlag = Annotated | Unannotated
-- These are used at the type-level exclusively
type Annotated = 'Annotated
type Unannotated = 'Unannotated
type family IfAnn (ann :: AnnotationFlag) (yes :: k) (no :: k) :: k
type instance IfAnn Annotated yes no = yes
type instance IfAnn Unannotated yes no = no
data family LetDecRHS (ann :: AnnotationFlag)
data instance LetDecRHS Annotated
= AFunction DType -- promote function (unapplied)
Int -- number of arrows in type
[ADClause]
| AValue DType -- promoted exp
Int -- number of arrows in type
ADExp
data instance LetDecRHS Unannotated = UFunction [DClause]
| UValue DExp
type ALetDecRHS = LetDecRHS Annotated
type ULetDecRHS = LetDecRHS Unannotated
data LetDecEnv ann = LetDecEnv
{ lde_defns :: Map Name (LetDecRHS ann)
, lde_types :: Map Name DType -- type signatures
, lde_infix :: [(Fixity, Name)] -- infix declarations
, lde_proms :: IfAnn ann (Map Name DType) () -- possibly, promotions
}
type ALetDecEnv = LetDecEnv Annotated
type ULetDecEnv = LetDecEnv Unannotated
instance Monoid ULetDecEnv where
mempty = LetDecEnv Map.empty Map.empty [] ()
mappend (LetDecEnv defns1 types1 infx1 _) (LetDecEnv defns2 types2 infx2 _) =
LetDecEnv (defns1 <> defns2) (types1 <> types2) (infx1 <> infx2) ()
valueBinding :: Name -> ULetDecRHS -> ULetDecEnv
valueBinding n v = emptyLetDecEnv { lde_defns = Map.singleton n v }
typeBinding :: Name -> DType -> ULetDecEnv
typeBinding n t = emptyLetDecEnv { lde_types = Map.singleton n t }
infixDecl :: Fixity -> Name -> ULetDecEnv
infixDecl f n = emptyLetDecEnv { lde_infix = [(f,n)] }
emptyLetDecEnv :: ULetDecEnv
emptyLetDecEnv = mempty
buildLetDecEnv :: Quasi q => [DLetDec] -> q ULetDecEnv
buildLetDecEnv = go emptyLetDecEnv
where
go acc [] = return acc
go acc (DFunD name clauses : rest) =
go (valueBinding name (UFunction clauses) <> acc) rest
go acc (DValD (DVarPa name) exp : rest) =
go (valueBinding name (UValue exp) <> acc) rest
go acc (dec@(DValD {}) : rest) = do
flattened <- flattenDValD dec
go acc (flattened ++ rest)
go acc (DSigD name ty : rest) =
go (typeBinding name ty <> acc) rest
go acc (DInfixD f n : rest) =
go (infixDecl f n <> acc) rest
|
int-index/singletons
|
src/Data/Singletons/Syntax.hs
|
Haskell
|
bsd-3-clause
| 5,063
|
module Arion.Utilities (
associate,
dependencies,
findHaskellFiles
) where
import Arion.Types
import Control.Applicative ((<*>))
import Data.List (nub, sort, union, isInfixOf)
import Data.Map (Map, fromList)
import System.FilePath.Find (always, extension, find, (==?),
(||?))
associate :: [SourceFile] -> [TestFile] -> Map FilePath [TestFile]
associate sourceFiles testFiles = let sourcesAndDependencies = dependencies sourceFiles
in fromList $ map (\(source, dependencies) ->
let testFilesFor source = filter (\testFile -> moduleName source `elem` imports testFile) testFiles
testFilesForSource = testFilesFor source
testFilesForDependencies = concatMap testFilesFor dependencies
in (sourceFilePath source, testFilesForSource ++ testFilesForDependencies)
) sourcesAndDependencies
dependencies :: [SourceFile] -> [(SourceFile, [SourceFile])]
dependencies sourceFiles = map (\file -> let dependencies = transitiveDependencies sourceFiles [] file
in (file, nub $ (filter ((/=) file) dependencies))
) sourceFiles
transitiveDependencies :: [SourceFile] -> [SourceFile] -> SourceFile -> [SourceFile]
transitiveDependencies allSourceFiles sourcesThatIHaveSeenSoFar theSourceFile =
let sourcesThatImportMe = sourcesThatImport allSourceFiles (moduleName theSourceFile)
in case any (\source -> source `elem` sourcesThatIHaveSeenSoFar) sourcesThatImportMe of
True -> sourcesThatImportMe
False -> let soFar = sourcesThatIHaveSeenSoFar ++ [theSourceFile]
in sourcesThatImportMe ++ concatMap (transitiveDependencies allSourceFiles soFar) sourcesThatImportMe
findSourcesByModule :: [SourceFile] -> String -> [SourceFile]
findSourcesByModule sourceFiles theModuleName = filter (\file -> moduleName file == theModuleName) sourceFiles
sourcesThatImport :: [SourceFile] -> String -> [SourceFile]
sourcesThatImport sourceFiles theModuleName = filter (\file -> theModuleName `elem` (importedModules file)) sourceFiles
findHaskellFiles :: String -> IO [String]
findHaskellFiles path = do
files <- find always (extension ==? ".hs" ||? extension ==? ".lhs") path
return $ filter (not . isInfixOf ".#") files
|
saturday06/arion
|
src/Arion/Utilities.hs
|
Haskell
|
mit
| 2,916
|
--main = do
-- contents <- getContents
-- putStr (shortLinesOnly contents)
main = interact shortLinesOnly
shortLinesOnly :: String -> String
shortLinesOnly input =
let allLines = lines input
shortLines = filter (\line -> length line < 10) allLines
result = unlines shortLines
in result
--main = interact $ unlines . filter ((<10) . length) . lines
|
leichunfeng/learnyouahaskell
|
shortlinesonly.hs
|
Haskell
|
mit
| 382
|
-- Body of the HTML page for a package
{-# LANGUAGE PatternGuards, RecordWildCards #-}
module Distribution.Server.Pages.Package (
packagePage,
renderDependencies,
renderVersion,
renderFields,
renderDownloads
) where
import Distribution.Server.Features.PreferredVersions
import Distribution.Server.Pages.Template (hackagePageWith)
import Distribution.Server.Pages.Package.HaddockParse (parseHaddockParagraphs)
import Distribution.Server.Pages.Package.HaddockLex (tokenise)
import Distribution.Server.Pages.Package.HaddockHtml
import Distribution.Server.Packages.ModuleForest
import Distribution.Server.Packages.Render
import Distribution.Server.Users.Types (userStatus, userName, isActiveAccount)
import Distribution.Package
import Distribution.PackageDescription as P
import Distribution.Simple.Utils ( cabalVersion )
import Distribution.Version
import Distribution.Text (display)
import Text.XHtml.Strict hiding (p, name, title, content)
import Data.Monoid (Monoid(..))
import Data.Maybe (maybeToList)
import Data.List (intersperse, intercalate)
import System.FilePath.Posix ((</>), (<.>))
import System.Locale (defaultTimeLocale)
import Data.Time.Format (formatTime)
packagePage :: PackageRender -> [Html] -> [Html] -> [(String, Html)] -> [(String, Html)] -> Maybe URL -> Bool -> Html
packagePage render headLinks top sections bottom docURL isCandidate =
hackagePageWith [] docTitle docSubtitle docBody [docFooter]
where
pkgid = rendPkgId render
docTitle = display (packageName pkgid)
++ case synopsis (rendOther render) of
"" -> ""
short -> ": " ++ short
docSubtitle = toHtml docTitle
docBody = h1 << bodyTitle
: concat [
renderHeads,
top,
pkgBody render sections,
moduleSection render docURL,
packageFlags render,
downloadSection render,
maintainerSection pkgid isCandidate,
map pair bottom
]
bodyTitle = "The " ++ display (pkgName pkgid) ++ " package"
renderHeads = case headLinks of
[] -> []
items -> [thediv ! [thestyle "font-size: small"] <<
(map (\item -> "[" +++ item +++ "] ") items)]
docFooter = thediv ! [identifier "footer"]
<< paragraph
<< [ toHtml "Produced by "
, anchor ! [href "/"] << "hackage"
, toHtml " and "
, anchor ! [href cabalHomeURL] << "Cabal"
, toHtml (" " ++ display cabalVersion) ]
pair (title, content) =
toHtml [ h2 << title, content ]
-- | Body of the package page
pkgBody :: PackageRender -> [(String, Html)] -> [Html]
pkgBody render sections =
descriptionSection render
++ propertySection sections
descriptionSection :: PackageRender -> [Html]
descriptionSection PackageRender{..} =
prologue (description rendOther)
++ [ hr
, ulist << li << changelogLink]
where
changelogLink
| rendHasChangeLog = anchor ! [href changeLogURL] << "Changelog"
| otherwise = toHtml << "No changelog available"
changeLogURL = rendPkgUri </> "changelog"
prologue :: String -> [Html]
prologue [] = []
prologue desc = case tokenise desc >>= parseHaddockParagraphs of
Nothing -> [paragraph << p | p <- paragraphs desc]
Just doc -> [markup htmlMarkup doc]
-- Break text into paragraphs (separated by blank lines)
paragraphs :: String -> [String]
paragraphs = map unlines . paras . lines
where paras xs = case dropWhile null xs of
[] -> []
xs' -> case break null xs' of
(para, xs'') -> para : paras xs''
downloadSection :: PackageRender -> [Html]
downloadSection PackageRender{..} =
[ h2 << "Downloads"
, ulist << map (li <<) downloadItems
]
where
downloadItems =
[ if rendHasTarball
then [ anchor ! [href downloadURL] << tarGzFileName
, toHtml << " ["
, anchor ! [href srcURL] << "browse"
, toHtml << "]"
, toHtml << " (Cabal source package)"
]
else [ toHtml << "Package tarball not uploaded" ]
, [ anchor ! [href cabalURL] << "Package description"
, toHtml $ if rendHasTarball then " (included in the package)" else ""
]
]
downloadURL = rendPkgUri </> display rendPkgId <.> "tar.gz"
cabalURL = rendPkgUri </> display (packageName rendPkgId) <.> "cabal"
srcURL = rendPkgUri </> "src/"
tarGzFileName = display rendPkgId ++ ".tar.gz"
maintainerSection :: PackageId -> Bool -> [Html]
maintainerSection pkgid isCandidate =
[ h4 << "Maintainers' corner"
, paragraph << "For package maintainers and hackage trustees"
, ulist << li << anchor ! [href maintainURL]
<< "edit package information"
]
where
maintainURL | isCandidate = "candidate/maintain"
| otherwise = display (packageName pkgid) </> "maintain"
-- | Render a table of the package's flags and along side it a tip
-- indicating how to enable/disable flags with Cabal.
packageFlags :: PackageRender -> [Html]
packageFlags render =
case rendFlags render of
[] -> mempty
flags ->
[h2 << "Flags"
,flagsTable flags
,tip]
where tip =
paragraph ! [theclass "tip"] <<
[thespan << "Use "
,code "-f <flag>"
,thespan << " to enable a flag, or "
,code "-f -<flag>"
,thespan << " to disable that flag. "
,anchor ! [href tipLink] << "More info"
]
tipLink = "http://www.haskell.org/cabal/users-guide/installing-packages.html#controlling-flag-assignments"
flagsTable flags =
table ! [theclass "flags-table"] <<
[thead << flagsHeadings
,tbody << map flagRow flags]
flagsHeadings = [th << "Name"
,th << "Description"
,th << "Default"]
flagRow flag =
tr << [td ! [theclass "flag-name"] << code (case flagName flag of FlagName name -> name)
,td ! [theclass "flag-desc"] << flagDescription flag
,td ! [theclass (if flagDefault flag then "flag-enabled" else "flag-disabled")] <<
if flagDefault flag then "Enabled" else "Disabled"]
code = (thespan ! [theclass "code"] <<)
moduleSection :: PackageRender -> Maybe URL -> [Html]
moduleSection render docURL = maybeToList $ fmap msect (rendModules render)
where msect lib = toHtml
[ h2 << "Modules"
, renderModuleForest docURL lib
, renderDocIndexLink docURL
]
renderDocIndexLink = maybe mempty $ \docURL' ->
let docIndexURL = docURL' </> "doc-index.html"
in paragraph ! [thestyle "font-size: small"]
<< ("[" +++ anchor ! [href docIndexURL] << "Index" +++ "]")
propertySection :: [(String, Html)] -> [Html]
propertySection sections =
[ h2 << "Properties"
, tabulate $ filter (not . isNoHtml . snd) sections
]
tabulate :: [(String, Html)] -> Html
tabulate items = table ! [theclass "properties"] <<
[tr << [th << t, td << d] | (t, d) <- items]
renderDependencies :: PackageRender -> (String, Html)
renderDependencies render = ("Dependencies", case htmlDepsList of
[] -> toHtml "None"
_ -> foldr (+++) noHtml htmlDepsList)
where htmlDepsList =
intersperse (toHtml " " +++ bold (toHtml "or") +++ br) $
map showDependencies (rendDepends render)
showDependencies :: [Dependency] -> Html
showDependencies deps = commaList (map showDependency deps)
showDependency :: Dependency -> Html
showDependency (Dependency (PackageName pname) vs) = showPkg +++ vsHtml
where vsHtml = if vs == anyVersion then noHtml
else toHtml (" (" ++ display vs ++ ")")
-- mb_vers links to latest version in range. This is a bit computationally
-- expensive, not cache-friendly, and perhaps unexpected in some cases
{-mb_vers = maybeLast $ filter (`withinRange` vs) $ map packageVersion $
PackageIndex.lookupPackageName vmap (PackageName pname)-}
-- nonetheless, we should ensure that the package exists /before/
-- passing along the PackageRender, which is not the case here
showPkg = anchor ! [href . packageURL $ PackageIdentifier (PackageName pname) (Version [] [])] << pname
renderVersion :: PackageId -> [(Version, VersionStatus)] -> Maybe String -> (String, Html)
renderVersion (PackageIdentifier pname pversion) allVersions info =
(if null earlierVersions && null laterVersions then "Version" else "Versions", versionList +++ infoHtml)
where (earlierVersions, laterVersionsInc) = span ((<pversion) . fst) allVersions
(mThisVersion, laterVersions) = case laterVersionsInc of
(v:later) | fst v == pversion -> (Just v, later)
later -> (Nothing, later)
versionList = commaList $ map versionedLink earlierVersions
++ (case pversion of
Version [] [] -> []
_ -> [strong ! (maybe [] (status . snd) mThisVersion) << display pversion]
)
++ map versionedLink laterVersions
versionedLink (v, s) = anchor ! (status s ++ [href $ packageURL $ PackageIdentifier pname v]) << display v
status st = case st of
NormalVersion -> []
DeprecatedVersion -> [theclass "deprecated"]
UnpreferredVersion -> [theclass "unpreferred"]
infoHtml = case info of Nothing -> noHtml; Just str -> " (" +++ (anchor ! [href str] << "info") +++ ")"
-- We don't keep currently per-version downloads in memory; if we decide that
-- it is important to show this all the time, we can reenable
renderDownloads :: Int -> Int -> {- Int -> Version -> -} (String, Html)
renderDownloads totalDown recentDown {- versionDown version -} =
("Downloads", toHtml $ {- show versionDown ++ " for " ++ display version ++
" and " ++ -} show totalDown ++ " total (" ++
show recentDown ++ " in last 30 days)")
renderFields :: PackageRender -> [(String, Html)]
renderFields render = [
-- Cabal-Version
("License", toHtml $ rendLicenseName render),
("Copyright", toHtml $ P.copyright desc),
("Author", toHtml $ author desc),
("Maintainer", maintainField $ rendMaintainer render),
("Stability", toHtml $ stability desc),
("Category", commaList . map categoryField $ rendCategory render),
("Home page", linkField $ homepage desc),
("Bug tracker", linkField $ bugReports desc),
("Source repository", vList $ map sourceRepositoryField $ sourceRepos desc),
("Executables", commaList . map toHtml $ rendExecNames render),
("Uploaded", uncurry renderUploadInfo (rendUploadInfo render))
]
++ [ ("Updated", renderUpdateInfo revisionNo utime uinfo)
| (revisionNo, utime, uinfo) <- maybeToList (rendUpdateInfo render) ]
where
desc = rendOther render
renderUploadInfo utime uinfo =
formatTime defaultTimeLocale "%c" utime +++ " by " +++ user
where
uname = maybe "Unknown" (display . userName) uinfo
uactive = maybe False (isActiveAccount . userStatus) uinfo
user | uactive = anchor ! [href $ "/user/" ++ uname] << uname
| otherwise = toHtml uname
renderUpdateInfo revisionNo utime uinfo =
renderUploadInfo utime uinfo +++ " to " +++
anchor ! [href revisionsURL] << ("revision " +++ show revisionNo)
where
revisionsURL = display (rendPkgId render) </> "revisions/"
linkField url = case url of
[] -> noHtml
_ -> anchor ! [href url] << url
categoryField cat = anchor ! [href $ "/packages/#cat:" ++ cat] << cat
maintainField mnt = case mnt of
Nothing -> strong ! [theclass "warning"] << toHtml "none"
Just n -> toHtml n
sourceRepositoryField sr = sourceRepositoryToHtml sr
sourceRepositoryToHtml :: SourceRepo -> Html
sourceRepositoryToHtml sr
= toHtml (display (repoKind sr) ++ ": ")
+++ case repoType sr of
Just Darcs
| (Just url, Nothing, Nothing) <-
(repoLocation sr, repoModule sr, repoBranch sr) ->
concatHtml [toHtml "darcs get ",
anchor ! [href url] << toHtml url,
case repoTag sr of
Just tag' -> toHtml (" --tag " ++ tag')
Nothing -> noHtml,
case repoSubdir sr of
Just sd -> toHtml " ("
+++ (anchor ! [href (url </> sd)]
<< toHtml sd)
+++ toHtml ")"
Nothing -> noHtml]
Just Git
| (Just url, Nothing) <-
(repoLocation sr, repoModule sr) ->
concatHtml [toHtml "git clone ",
anchor ! [href url] << toHtml url,
case repoBranch sr of
Just branch -> toHtml (" -b " ++ branch)
Nothing -> noHtml,
case repoTag sr of
Just tag' -> toHtml ("(tag " ++ tag' ++ ")")
Nothing -> noHtml,
case repoSubdir sr of
Just sd -> toHtml ("(" ++ sd ++ ")")
Nothing -> noHtml]
Just SVN
| (Just url, Nothing, Nothing, Nothing) <-
(repoLocation sr, repoModule sr, repoBranch sr, repoTag sr) ->
concatHtml [toHtml "svn checkout ",
anchor ! [href url] << toHtml url,
case repoSubdir sr of
Just sd -> toHtml ("(" ++ sd ++ ")")
Nothing -> noHtml]
Just CVS
| (Just url, Just m, Nothing, Nothing) <-
(repoLocation sr, repoModule sr, repoBranch sr, repoTag sr) ->
concatHtml [toHtml "cvs -d ",
anchor ! [href url] << toHtml url,
toHtml (" " ++ m),
case repoSubdir sr of
Just sd -> toHtml ("(" ++ sd ++ ")")
Nothing -> noHtml]
Just Mercurial
| (Just url, Nothing) <-
(repoLocation sr, repoModule sr) ->
concatHtml [toHtml "hg clone ",
anchor ! [href url] << toHtml url,
case repoBranch sr of
Just branch -> toHtml (" -b " ++ branch)
Nothing -> noHtml,
case repoTag sr of
Just tag' -> toHtml (" -u " ++ tag')
Nothing -> noHtml,
case repoSubdir sr of
Just sd -> toHtml ("(" ++ sd ++ ")")
Nothing -> noHtml]
Just Bazaar
| (Just url, Nothing, Nothing) <-
(repoLocation sr, repoModule sr, repoBranch sr) ->
concatHtml [toHtml "bzr branch ",
anchor ! [href url] << toHtml url,
case repoTag sr of
Just tag' -> toHtml (" -r " ++ tag')
Nothing -> noHtml,
case repoSubdir sr of
Just sd -> toHtml ("(" ++ sd ++ ")")
Nothing -> noHtml]
_ ->
-- We don't know how to show this SourceRepo.
-- This is a kludge so that we at least show all the info.
toHtml (show sr)
commaList :: [Html] -> Html
commaList = concatHtml . intersperse (toHtml ", ")
vList :: [Html] -> Html
vList = concatHtml . intersperse br
-----------------------------------------------------------------------------
renderModuleForest :: Maybe URL -> ModuleForest -> Html
renderModuleForest mb_url forest =
thediv ! [identifier "module-list"] << renderForest [] forest
where
renderForest _ [] = noHtml
renderForest pathRev ts = myUnordList $ map renderTree ts
where
renderTree (Node s isModule subs) =
( if isModule then moduleEntry newPath else italics << s )
+++ renderForest newPathRev subs
where
newPathRev = s:pathRev
newPath = reverse newPathRev
moduleEntry path =
thespan ! [theclass "module"] << maybe modName linkedName mb_url path
modName path = toHtml (intercalate "." path)
linkedName url path = anchor ! [href modUrl] << modName path
where
modUrl = url ++ "/" ++ intercalate "-" path ++ ".html"
myUnordList :: HTML a => [a] -> Html
myUnordList = unordList ! [theclass "modules"]
------------------------------------------------------------------------------
-- TODO: most of these should be available from the CoreFeature
-- so pass it in to this module
-- | URL describing a package.
packageURL :: PackageIdentifier -> URL
packageURL pkgId = "/package" </> display pkgId
--cabalLogoURL :: URL
--cabalLogoURL = "/built-with-cabal.png"
-- global URLs
cabalHomeURL :: URL
cabalHomeURL = "http://haskell.org/cabal/"
|
haskell-infra/hackage-server
|
Distribution/Server/Pages/Package.hs
|
Haskell
|
bsd-3-clause
| 17,668
|
{-# LANGUAGE OverloadedStrings #-}
module NumberSix.Handlers.Reddit
( handler
) where
--------------------------------------------------------------------------------
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import Control.Monad.Trans (liftIO)
import Data.Aeson (FromJSON (..), Object, Value (..), (.:))
import qualified Data.HashMap.Lazy as HM
import Data.Text (Text)
import qualified Data.Text as T
--------------------------------------------------------------------------------
import NumberSix.Bang
import NumberSix.Irc
import NumberSix.Util
import NumberSix.Util.BitLy
import NumberSix.Util.Error
import NumberSix.Util.Http
--------------------------------------------------------------------------------
data Reddit = Reddit [Link] deriving (Show)
--------------------------------------------------------------------------------
instance FromJSON Reddit where
parseJSON (Object o) = let o' = unData o in Reddit <$> o' .: "children"
parseJSON _ = mzero
--------------------------------------------------------------------------------
data Link = Link Text Text deriving (Show)
--------------------------------------------------------------------------------
instance FromJSON Link where
parseJSON (Object o) =
let o' = unData o in Link <$> o' .: "title" <*> o' .: "url"
parseJSON _ = mzero
--------------------------------------------------------------------------------
-- | Fetch the data attribute from an object. Reddit's ugly json...
unData :: Object -> Object
unData o = case HM.lookup "data" o of Just (Object o') -> o'; _ -> HM.empty
--------------------------------------------------------------------------------
reddit :: Text -> IO Text
reddit query = http url id >>= \bs -> case parseJsonEither bs of
Left _ -> randomError
Right (Reddit ls) -> do
Link t u <- case idx of
Nothing -> randomElement ls
Just i -> return $ ls !! (i - 1)
textAndUrl t u
where
url = "http://reddit.com/r/" <> subreddit <> ".json"
(subreddit, idx) = case T.words query of
[s, i] -> (s, readText i)
[s] -> case readText s of
Just i -> ("all", Just i)
Nothing -> (s, Nothing)
_ -> ("all", Nothing)
--------------------------------------------------------------------------------
handler :: UninitializedHandler
handler = makeBangHandler "Reddit" ["!reddit"] $ liftIO . reddit
|
itkovian/number-six
|
src/NumberSix/Handlers/Reddit.hs
|
Haskell
|
bsd-3-clause
| 2,660
|
-- Copyright (c) 1998 Chris Okasaki.
-- See COPYRIGHT file for terms and conditions.
module CollectionUtils
{-# DEPRECATED "This module is unmaintained, and will disappear soon" #-}
where
import Prelude hiding (map,null,foldr,foldl,foldr1,foldl1,lookup,filter)
import Collection
map :: (Coll cin a, CollX cout b) => (a -> b) -> (cin a -> cout b)
map f xs = fold (\x ys -> insert (f x) ys) empty xs
mapPartial :: (Coll cin a, CollX cout b) => (a -> Maybe b) -> (cin a -> cout b)
mapPartial f xs = fold (\ x ys -> case f x of
Just y -> insert y ys
Nothing -> ys)
empty xs
unsafeMapMonotonic :: (OrdColl cin a, OrdCollX cout b) => (a -> b) -> (cin a -> cout b)
unsafeMapMonotonic f xs = foldr (unsafeInsertMin . f) empty xs
unionMap :: (Coll cin a, CollX cout b) => (a -> cout b) -> (cin a -> cout b)
unionMap f xs = fold (\x ys -> union (f x) ys) empty xs
|
alekar/hugs
|
fptools/hslibs/data/edison/Coll/CollectionUtils.hs
|
Haskell
|
bsd-3-clause
| 959
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module Ros.Std_msgs.UInt16 where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import qualified Data.Word as Word
import Foreign.Storable (Storable(..))
import qualified Ros.Internal.Util.StorableMonad as SM
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data UInt16 = UInt16 { __data :: Word.Word16
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''UInt16)
instance RosBinary UInt16 where
put obj' = put (__data obj')
get = UInt16 <$> get
instance Storable UInt16 where
sizeOf _ = sizeOf (P.undefined::Word.Word16)
alignment _ = 8
peek = SM.runStorable (UInt16 <$> SM.peek)
poke ptr' obj' = SM.runStorable store' ptr'
where store' = SM.poke (__data obj')
instance MsgInfo UInt16 where
sourceMD5 _ = "1df79edf208b629fe6b81923a544552d"
msgTypeName _ = "std_msgs/UInt16"
instance D.Default UInt16
|
acowley/roshask
|
msgs/Std_msgs/Ros/Std_msgs/UInt16.hs
|
Haskell
|
bsd-3-clause
| 1,237
|
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/Attoparsec/Text.hs" #-}
{-# LANGUAGE BangPatterns, CPP, FlexibleInstances, TypeSynonymInstances #-}
{-# LANGUAGE Trustworthy #-} -- Imports internal modules
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
-- |
-- Module : Data.Attoparsec.Text
-- Copyright : Bryan O'Sullivan 2007-2015
-- License : BSD3
--
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : unknown
--
-- Simple, efficient combinator parsing for 'Text' strings,
-- loosely based on the Parsec library.
module Data.Attoparsec.Text
(
-- * Differences from Parsec
-- $parsec
-- * Incremental input
-- $incremental
-- * Performance considerations
-- $performance
-- * Parser types
Parser
, Result
, T.IResult(..)
, I.compareResults
-- * Running parsers
, parse
, feed
, I.parseOnly
, parseWith
, parseTest
-- ** Result conversion
, maybeResult
, eitherResult
-- * Parsing individual characters
, I.char
, I.anyChar
, I.notChar
, I.satisfy
, I.satisfyWith
, I.skip
-- ** Lookahead
, I.peekChar
, I.peekChar'
-- ** Special character parsers
, digit
, letter
, space
-- ** Character classes
, I.inClass
, I.notInClass
-- * Efficient string handling
, I.string
, I.stringCI
, I.asciiCI
, skipSpace
, I.skipWhile
, I.scan
, I.runScanner
, I.take
, I.takeWhile
, I.takeWhile1
, I.takeTill
-- ** String combinators
-- $specalt
, (.*>)
, (<*.)
-- ** Consume all remaining input
, I.takeText
, I.takeLazyText
-- * Text parsing
, I.endOfLine
, isEndOfLine
, isHorizontalSpace
-- * Numeric parsers
, decimal
, hexadecimal
, signed
, double
, Number(..)
, number
, rational
, scientific
-- * Combinators
, try
, (<?>)
, choice
, count
, option
, many'
, many1
, many1'
, manyTill
, manyTill'
, sepBy
, sepBy'
, sepBy1
, sepBy1'
, skipMany
, skipMany1
, eitherP
, I.match
-- * State observation and manipulation functions
, I.endOfInput
, I.atEnd
) where
import Control.Applicative ((<|>))
import Data.Attoparsec.Combinator
import Data.Attoparsec.Number (Number(..))
import Data.Scientific (Scientific)
import qualified Data.Scientific as Sci
import Data.Attoparsec.Text.Internal (Parser, Result, parse, takeWhile1)
import Data.Bits (Bits, (.|.), shiftL)
import Data.Char (isAlpha, isDigit, isSpace, ord)
import Data.Int (Int8, Int16, Int32, Int64)
import Data.List (intercalate)
import Data.Text (Text)
import Data.Word (Word8, Word16, Word32, Word64)
import qualified Data.Attoparsec.Internal as I
import qualified Data.Attoparsec.Internal.Types as T
import qualified Data.Attoparsec.Text.Internal as I
import qualified Data.Text as T
-- $parsec
--
-- Compared to Parsec 3, attoparsec makes several tradeoffs. It is
-- not intended for, or ideal for, all possible uses.
--
-- * While attoparsec can consume input incrementally, Parsec cannot.
-- Incremental input is a huge deal for efficient and secure network
-- and system programming, since it gives much more control to users
-- of the library over matters such as resource usage and the I/O
-- model to use.
--
-- * Much of the performance advantage of attoparsec is gained via
-- high-performance parsers such as 'I.takeWhile' and 'I.string'.
-- If you use complicated combinators that return lists of
-- characters, there is less performance difference between the two
-- libraries.
--
-- * Unlike Parsec 3, attoparsec does not support being used as a
-- monad transformer.
--
-- * attoparsec is specialised to deal only with strict 'Text'
-- input. Efficiency concerns rule out both lists and lazy text.
-- The usual use for lazy text would be to allow consumption of very
-- large input without a large footprint. For this need,
-- attoparsec's incremental input provides an excellent substitute,
-- with much more control over when input takes place. If you must
-- use lazy text, see the 'Lazy' module, which feeds lazy chunks to
-- a regular parser.
--
-- * Parsec parsers can produce more helpful error messages than
-- attoparsec parsers. This is a matter of focus: attoparsec avoids
-- the extra book-keeping in favour of higher performance.
-- $incremental
--
-- attoparsec supports incremental input, meaning that you can feed it
-- a 'Text' that represents only part of the expected total amount
-- of data to parse. If your parser reaches the end of a fragment of
-- input and could consume more input, it will suspend parsing and
-- return a 'T.Partial' continuation.
--
-- Supplying the 'T.Partial' continuation with another string will
-- resume parsing at the point where it was suspended, with the string
-- you supplied used as new input at the end of the existing
-- input. You must be prepared for the result of the resumed parse to
-- be another 'Partial' continuation.
--
-- To indicate that you have no more input, supply the 'Partial'
-- continuation with an 'T.empty' 'Text'.
--
-- Remember that some parsing combinators will not return a result
-- until they reach the end of input. They may thus cause 'T.Partial'
-- results to be returned.
--
-- If you do not need support for incremental input, consider using
-- the 'I.parseOnly' function to run your parser. It will never
-- prompt for more input.
--
-- /Note/: incremental input does /not/ imply that attoparsec will
-- release portions of its internal state for garbage collection as it
-- proceeds. Its internal representation is equivalent to a single
-- 'Text': if you feed incremental input to an a parser, it will
-- require memory proportional to the amount of input you supply.
-- (This is necessary to support arbitrary backtracking.)
-- $performance
--
-- If you write an attoparsec-based parser carefully, it can be
-- realistic to expect it to perform similarly to a hand-rolled C
-- parser (measuring megabytes parsed per second).
--
-- To actually achieve high performance, there are a few guidelines
-- that it is useful to follow.
--
-- Use the 'Text'-oriented parsers whenever possible,
-- e.g. 'I.takeWhile1' instead of 'many1' 'I.anyChar'. There is
-- about a factor of 100 difference in performance between the two
-- kinds of parser.
--
-- For very simple character-testing predicates, write them by hand
-- instead of using 'I.inClass' or 'I.notInClass'. For instance, both
-- of these predicates test for an end-of-line character, but the
-- first is much faster than the second:
--
-- >endOfLine_fast c = c == '\r' || c == '\n'
-- >endOfLine_slow = inClass "\r\n"
--
-- Make active use of benchmarking and profiling tools to measure,
-- find the problems with, and improve the performance of your parser.
-- | Run a parser and print its result to standard output.
parseTest :: (Show a) => I.Parser a -> Text -> IO ()
parseTest p s = print (parse p s)
-- | Run a parser with an initial input string, and a monadic action
-- that can supply more input if needed.
parseWith :: Monad m =>
(m Text)
-- ^ An action that will be executed to provide the parser
-- with more input, if necessary. The action must return an
-- 'T.empty' string when there is no more input available.
-> I.Parser a
-> Text
-- ^ Initial input for the parser.
-> m (Result a)
parseWith refill p s = step $ parse p s
where step (T.Partial k) = (step . k) =<< refill
step r = return r
{-# INLINE parseWith #-}
-- | Convert a 'Result' value to a 'Maybe' value. A 'Partial' result
-- is treated as failure.
maybeResult :: Result r -> Maybe r
maybeResult (T.Done _ r) = Just r
maybeResult _ = Nothing
-- | Convert a 'Result' value to an 'Either' value. A 'Partial' result
-- is treated as failure.
eitherResult :: Result r -> Either String r
eitherResult (T.Done _ r) = Right r
eitherResult (T.Fail _ [] msg) = Left msg
eitherResult (T.Fail _ ctxs msg) = Left (intercalate " > " ctxs ++ ": " ++ msg)
eitherResult _ = Left "Result: incomplete input"
-- | A predicate that matches either a carriage return @\'\\r\'@ or
-- newline @\'\\n\'@ character.
isEndOfLine :: Char -> Bool
isEndOfLine c = c == '\n' || c == '\r'
{-# INLINE isEndOfLine #-}
-- | A predicate that matches either a space @\' \'@ or horizontal tab
-- @\'\\t\'@ character.
isHorizontalSpace :: Char -> Bool
isHorizontalSpace c = c == ' ' || c == '\t'
{-# INLINE isHorizontalSpace #-}
-- | Parse and decode an unsigned hexadecimal number. The hex digits
-- @\'a\'@ through @\'f\'@ may be upper or lower case.
--
-- This parser does not accept a leading @\"0x\"@ string.
hexadecimal :: (Integral a, Bits a) => Parser a
hexadecimal = T.foldl' step 0 `fmap` takeWhile1 isHexDigit
where
isHexDigit c = (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F')
step a c | w >= 48 && w <= 57 = (a `shiftL` 4) .|. fromIntegral (w - 48)
| w >= 97 = (a `shiftL` 4) .|. fromIntegral (w - 87)
| otherwise = (a `shiftL` 4) .|. fromIntegral (w - 55)
where w = ord c
{-# SPECIALISE hexadecimal :: Parser Int #-}
{-# SPECIALISE hexadecimal :: Parser Int8 #-}
{-# SPECIALISE hexadecimal :: Parser Int16 #-}
{-# SPECIALISE hexadecimal :: Parser Int32 #-}
{-# SPECIALISE hexadecimal :: Parser Int64 #-}
{-# SPECIALISE hexadecimal :: Parser Integer #-}
{-# SPECIALISE hexadecimal :: Parser Word #-}
{-# SPECIALISE hexadecimal :: Parser Word8 #-}
{-# SPECIALISE hexadecimal :: Parser Word16 #-}
{-# SPECIALISE hexadecimal :: Parser Word32 #-}
{-# SPECIALISE hexadecimal :: Parser Word64 #-}
-- | Parse and decode an unsigned decimal number.
decimal :: Integral a => Parser a
decimal = T.foldl' step 0 `fmap` takeWhile1 isDecimal
where step a c = a * 10 + fromIntegral (ord c - 48)
{-# SPECIALISE decimal :: Parser Int #-}
{-# SPECIALISE decimal :: Parser Int8 #-}
{-# SPECIALISE decimal :: Parser Int16 #-}
{-# SPECIALISE decimal :: Parser Int32 #-}
{-# SPECIALISE decimal :: Parser Int64 #-}
{-# SPECIALISE decimal :: Parser Integer #-}
{-# SPECIALISE decimal :: Parser Word #-}
{-# SPECIALISE decimal :: Parser Word8 #-}
{-# SPECIALISE decimal :: Parser Word16 #-}
{-# SPECIALISE decimal :: Parser Word32 #-}
{-# SPECIALISE decimal :: Parser Word64 #-}
isDecimal :: Char -> Bool
isDecimal c = c >= '0' && c <= '9'
{-# INLINE isDecimal #-}
-- | Parse a number with an optional leading @\'+\'@ or @\'-\'@ sign
-- character.
signed :: Num a => Parser a -> Parser a
{-# SPECIALISE signed :: Parser Int -> Parser Int #-}
{-# SPECIALISE signed :: Parser Int8 -> Parser Int8 #-}
{-# SPECIALISE signed :: Parser Int16 -> Parser Int16 #-}
{-# SPECIALISE signed :: Parser Int32 -> Parser Int32 #-}
{-# SPECIALISE signed :: Parser Int64 -> Parser Int64 #-}
{-# SPECIALISE signed :: Parser Integer -> Parser Integer #-}
signed p = (negate <$> (I.char '-' *> p))
<|> (I.char '+' *> p)
<|> p
-- | Parse a rational number.
--
-- The syntax accepted by this parser is the same as for 'double'.
--
-- /Note/: this parser is not safe for use with inputs from untrusted
-- sources. An input with a suitably large exponent such as
-- @"1e1000000000"@ will cause a huge 'Integer' to be allocated,
-- resulting in what is effectively a denial-of-service attack.
--
-- In most cases, it is better to use 'double' or 'scientific'
-- instead.
rational :: Fractional a => Parser a
{-# SPECIALIZE rational :: Parser Double #-}
{-# SPECIALIZE rational :: Parser Float #-}
{-# SPECIALIZE rational :: Parser Rational #-}
{-# SPECIALIZE rational :: Parser Scientific #-}
rational = scientifically realToFrac
-- | Parse a rational number.
--
-- This parser accepts an optional leading sign character, followed by
-- at least one decimal digit. The syntax similar to that accepted by
-- the 'read' function, with the exception that a trailing @\'.\'@ or
-- @\'e\'@ /not/ followed by a number is not consumed.
--
-- Examples with behaviour identical to 'read', if you feed an empty
-- continuation to the first result:
--
-- >rational "3" == Done 3.0 ""
-- >rational "3.1" == Done 3.1 ""
-- >rational "3e4" == Done 30000.0 ""
-- >rational "3.1e4" == Done 31000.0, ""
--
-- Examples with behaviour identical to 'read':
--
-- >rational ".3" == Fail "input does not start with a digit"
-- >rational "e3" == Fail "input does not start with a digit"
--
-- Examples of differences from 'read':
--
-- >rational "3.foo" == Done 3.0 ".foo"
-- >rational "3e" == Done 3.0 "e"
--
-- This function does not accept string representations of \"NaN\" or
-- \"Infinity\".
double :: Parser Double
double = scientifically Sci.toRealFloat
-- | Parse a number, attempting to preserve both speed and precision.
--
-- The syntax accepted by this parser is the same as for 'double'.
--
-- This function does not accept string representations of \"NaN\" or
-- \"Infinity\".
number :: Parser Number
number = scientifically $ \s ->
let e = Sci.base10Exponent s
c = Sci.coefficient s
in if e >= 0
then I (c * 10 ^ e)
else D (Sci.toRealFloat s)
{-# DEPRECATED number "Use 'scientific' instead." #-}
-- | Parse a scientific number.
--
-- The syntax accepted by this parser is the same as for 'double'.
scientific :: Parser Scientific
scientific = scientifically id
-- A strict pair
data SP = SP !Integer {-# UNPACK #-}!Int
{-# INLINE scientifically #-}
scientifically :: (Scientific -> a) -> Parser a
scientifically h = do
!positive <- ((== '+') <$> I.satisfy (\c -> c == '-' || c == '+')) <|>
pure True
n <- decimal
let f fracDigits = SP (T.foldl' step n fracDigits)
(negate $ T.length fracDigits)
step a c = a * 10 + fromIntegral (ord c - 48)
SP c e <- (I.satisfy (=='.') *> (f <$> I.takeWhile isDigit)) <|>
pure (SP n 0)
let !signedCoeff | positive = c
| otherwise = -c
(I.satisfy (\w -> w == 'e' || w == 'E') *>
fmap (h . Sci.scientific signedCoeff . (e +)) (signed decimal)) <|>
return (h $ Sci.scientific signedCoeff e)
-- | Parse a single digit, as recognised by 'isDigit'.
digit :: Parser Char
digit = I.satisfy isDigit <?> "digit"
{-# INLINE digit #-}
-- | Parse a letter, as recognised by 'isAlpha'.
letter :: Parser Char
letter = I.satisfy isAlpha <?> "letter"
{-# INLINE letter #-}
-- | Parse a space character, as recognised by 'isSpace'.
space :: Parser Char
space = I.satisfy isSpace <?> "space"
{-# INLINE space #-}
-- | Skip over white space.
skipSpace :: Parser ()
skipSpace = I.skipWhile isSpace
{-# INLINE skipSpace #-}
-- $specalt
--
-- If you enable the @OverloadedStrings@ language extension, you can
-- use the '*>' and '<*' combinators to simplify the common task of
-- matching a statically known string, then immediately parsing
-- something else.
--
-- Instead of writing something like this:
--
-- @
--'I.string' \"foo\" '*>' wibble
-- @
--
-- Using @OverloadedStrings@, you can omit the explicit use of
-- 'I.string', and write a more compact version:
--
-- @
-- \"foo\" '*>' wibble
-- @
--
-- (Note: the '.*>' and '<*.' combinators that were originally
-- provided for this purpose are obsolete and unnecessary, and will be
-- removed in the next major version.)
-- | /Obsolete/. A type-specialized version of '*>' for 'Text'. Use
-- '*>' instead.
(.*>) :: Text -> Parser a -> Parser a
s .*> f = I.string s *> f
{-# DEPRECATED (.*>) "This is no longer necessary, and will be removed. Use '*>' instead." #-}
-- | /Obsolete/. A type-specialized version of '<*' for 'Text'. Use
-- '*>' instead.
(<*.) :: Parser a -> Text -> Parser a
f <*. s = f <* I.string s
{-# DEPRECATED (<*.) "This is no longer necessary, and will be removed. Use '<*' instead." #-}
|
phischu/fragnix
|
tests/packages/scotty/Data.Attoparsec.Text.hs
|
Haskell
|
bsd-3-clause
| 16,149
|
{-# LANGUAGE PolyKinds #-}
module T16326_Fail7 where
import Data.Kind
-- Make sure that this doesn't parse as something goofy like
-- forall (forall :: Type -> Type) (k :: Type). forall k -> k -> Type
data Foo :: forall k -> k -> Type
|
sdiehl/ghc
|
testsuite/tests/dependent/should_fail/T16326_Fail7.hs
|
Haskell
|
bsd-3-clause
| 238
|
{-# LANGUAGE CPP #-}
#if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
{-# LANGUAGE Trustworthy #-}
#endif
#include "containers.h"
-----------------------------------------------------------------------------
-- |
-- Module : Data.Map.Strict
-- Copyright : (c) Daan Leijen 2002
-- (c) Andriy Palamarchuk 2008
-- License : BSD-style
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- An efficient implementation of ordered maps from keys to values
-- (dictionaries).
--
-- API of this module is strict in both the keys and the values.
-- If you need value-lazy maps, use "Data.Map.Lazy" instead.
-- The 'Map' type is shared between the lazy and strict modules,
-- meaning that the same 'Map' value can be passed to functions in
-- both modules (although that is rarely needed).
--
-- These modules are intended to be imported qualified, to avoid name
-- clashes with Prelude functions, e.g.
--
-- > import qualified Data.Map.Strict as Map
--
-- The implementation of 'Map' is based on /size balanced/ binary trees (or
-- trees of /bounded balance/) as described by:
--
-- * Stephen Adams, \"/Efficient sets: a balancing act/\",
-- Journal of Functional Programming 3(4):553-562, October 1993,
-- <http://www.swiss.ai.mit.edu/~adams/BB/>.
--
-- * J. Nievergelt and E.M. Reingold,
-- \"/Binary search trees of bounded balance/\",
-- SIAM journal of computing 2(1), March 1973.
--
-- Note that the implementation is /left-biased/ -- the elements of a
-- first argument are always preferred to the second, for example in
-- 'union' or 'insert'.
--
-- /Warning/: The size of the map must not exceed @maxBound::Int@. Violation of
-- this condition is not detected and if the size limit is exceeded, its
-- behaviour is undefined.
--
-- Operation comments contain the operation time complexity in
-- the Big-O notation (<http://en.wikipedia.org/wiki/Big_O_notation>).
--
-- Be aware that the 'Functor', 'Traversable' and 'Data' instances
-- are the same as for the "Data.Map.Lazy" module, so if they are used
-- on strict maps, the resulting maps will be lazy.
-----------------------------------------------------------------------------
-- See the notes at the beginning of Data.Map.Base.
module Data.Map.Strict
(
-- * Strictness properties
-- $strictness
-- * Map type
#if !defined(TESTING)
Map -- instance Eq,Show,Read
#else
Map(..) -- instance Eq,Show,Read
#endif
-- * Operators
, (!), (\\)
-- * Query
, null
, size
, member
, notMember
, lookup
, findWithDefault
, lookupLT
, lookupGT
, lookupLE
, lookupGE
-- * Construction
, empty
, singleton
-- ** Insertion
, insert
, insertWith
, insertWithKey
, insertLookupWithKey
-- ** Delete\/Update
, delete
, adjust
, adjustWithKey
, update
, updateWithKey
, updateLookupWithKey
, alter
-- * Combine
-- ** Union
, union
, unionWith
, unionWithKey
, unions
, unionsWith
-- ** Difference
, difference
, differenceWith
, differenceWithKey
-- ** Intersection
, intersection
, intersectionWith
, intersectionWithKey
-- ** Universal combining function
, mergeWithKey
-- * Traversal
-- ** Map
, map
, mapWithKey
, traverseWithKey
, mapAccum
, mapAccumWithKey
, mapAccumRWithKey
, mapKeys
, mapKeysWith
, mapKeysMonotonic
-- * Folds
, foldr
, foldl
, foldrWithKey
, foldlWithKey
, foldMapWithKey
-- ** Strict folds
, foldr'
, foldl'
, foldrWithKey'
, foldlWithKey'
-- * Conversion
, elems
, keys
, assocs
, keysSet
, fromSet
-- ** Lists
, toList
, fromList
, fromListWith
, fromListWithKey
-- ** Ordered lists
, toAscList
, toDescList
, fromAscList
, fromAscListWith
, fromAscListWithKey
, fromDistinctAscList
-- * Filter
, filter
, filterWithKey
, partition
, partitionWithKey
, mapMaybe
, mapMaybeWithKey
, mapEither
, mapEitherWithKey
, split
, splitLookup
, splitRoot
-- * Submap
, isSubmapOf, isSubmapOfBy
, isProperSubmapOf, isProperSubmapOfBy
-- * Indexed
, lookupIndex
, findIndex
, elemAt
, updateAt
, deleteAt
-- * Min\/Max
, findMin
, findMax
, deleteMin
, deleteMax
, deleteFindMin
, deleteFindMax
, updateMin
, updateMax
, updateMinWithKey
, updateMaxWithKey
, minView
, maxView
, minViewWithKey
, maxViewWithKey
-- * Debugging
, showTree
, showTreeWith
, valid
#if defined(TESTING)
-- * Internals
, bin
, balanced
, link
, merge
#endif
) where
import Prelude hiding (lookup,map,filter,foldr,foldl,null)
import Data.Map.Base hiding
( findWithDefault
, singleton
, insert
, insertWith
, insertWithKey
, insertLookupWithKey
, adjust
, adjustWithKey
, update
, updateWithKey
, updateLookupWithKey
, alter
, unionWith
, unionWithKey
, unionsWith
, differenceWith
, differenceWithKey
, intersectionWith
, intersectionWithKey
, mergeWithKey
, map
, mapWithKey
, mapAccum
, mapAccumWithKey
, mapAccumRWithKey
, mapKeysWith
, fromSet
, fromList
, fromListWith
, fromListWithKey
, fromAscList
, fromAscListWith
, fromAscListWithKey
, fromDistinctAscList
, mapMaybe
, mapMaybeWithKey
, mapEither
, mapEitherWithKey
, updateAt
, updateMin
, updateMax
, updateMinWithKey
, updateMaxWithKey
)
import qualified Data.Set.Base as Set
import Data.Utils.StrictFold
import Data.Utils.StrictPair
import Data.Bits (shiftL, shiftR)
#if __GLASGOW_HASKELL__ >= 709
import Data.Coerce
#endif
-- $strictness
--
-- This module satisfies the following strictness properties:
--
-- 1. Key arguments are evaluated to WHNF;
--
-- 2. Keys and values are evaluated to WHNF before they are stored in
-- the map.
--
-- Here's an example illustrating the first property:
--
-- > delete undefined m == undefined
--
-- Here are some examples that illustrate the second property:
--
-- > map (\ v -> undefined) m == undefined -- m is not empty
-- > mapKeys (\ k -> undefined) m == undefined -- m is not empty
{--------------------------------------------------------------------
Query
--------------------------------------------------------------------}
-- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
-- the value at key @k@ or returns default value @def@
-- when the key is not in the map.
--
-- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
-- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
-- See Map.Base.Note: Local 'go' functions and capturing
findWithDefault :: Ord k => a -> k -> Map k a -> a
findWithDefault def k = k `seq` go
where
go Tip = def
go (Bin _ kx x l r) = case compare k kx of
LT -> go l
GT -> go r
EQ -> x
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE findWithDefault #-}
#else
{-# INLINE findWithDefault #-}
#endif
{--------------------------------------------------------------------
Construction
--------------------------------------------------------------------}
-- | /O(1)/. A map with a single element.
--
-- > singleton 1 'a' == fromList [(1, 'a')]
-- > size (singleton 1 'a') == 1
singleton :: k -> a -> Map k a
singleton k x = x `seq` Bin 1 k x Tip Tip
{-# INLINE singleton #-}
{--------------------------------------------------------------------
Insertion
--------------------------------------------------------------------}
-- | /O(log n)/. Insert a new key and value in the map.
-- If the key is already present in the map, the associated value is
-- replaced with the supplied value. 'insert' is equivalent to
-- @'insertWith' 'const'@.
--
-- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
-- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
-- > insert 5 'x' empty == singleton 5 'x'
-- See Map.Base.Note: Type of local 'go' function
insert :: Ord k => k -> a -> Map k a -> Map k a
insert = go
where
go :: Ord k => k -> a -> Map k a -> Map k a
STRICT_1_OF_3(go)
STRICT_2_OF_3(go)
go kx x Tip = singleton kx x
go kx x (Bin sz ky y l r) =
case compare kx ky of
LT -> balanceL ky y (go kx x l) r
GT -> balanceR ky y l (go kx x r)
EQ -> Bin sz kx x l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insert #-}
#else
{-# INLINE insert #-}
#endif
-- | /O(log n)/. Insert with a function, combining new value and old value.
-- @'insertWith' f key value mp@
-- will insert the pair (key, value) into @mp@ if key does
-- not exist in the map. If the key does exist, the function will
-- insert the pair @(key, f new_value old_value)@.
--
-- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
-- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
-- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
insertWith f = insertWithKey (\_ x' y' -> f x' y')
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insertWith #-}
#else
{-# INLINE insertWith #-}
#endif
-- | /O(log n)/. Insert with a function, combining key, new value and old value.
-- @'insertWithKey' f key value mp@
-- will insert the pair (key, value) into @mp@ if key does
-- not exist in the map. If the key does exist, the function will
-- insert the pair @(key,f key new_value old_value)@.
-- Note that the key passed to f is the same key passed to 'insertWithKey'.
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
-- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
-- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
-- See Map.Base.Note: Type of local 'go' function
insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
insertWithKey = go
where
go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
STRICT_2_OF_4(go)
go _ kx x Tip = singleton kx x
go f kx x (Bin sy ky y l r) =
case compare kx ky of
LT -> balanceL ky y (go f kx x l) r
GT -> balanceR ky y l (go f kx x r)
EQ -> let x' = f kx x y
in x' `seq` Bin sy kx x' l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insertWithKey #-}
#else
{-# INLINE insertWithKey #-}
#endif
-- | /O(log n)/. Combines insert operation with old value retrieval.
-- The expression (@'insertLookupWithKey' f k x map@)
-- is a pair where the first element is equal to (@'lookup' k map@)
-- and the second element equal to (@'insertWithKey' f k x map@).
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
-- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
-- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
--
-- This is how to define @insertLookup@ using @insertLookupWithKey@:
--
-- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
-- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
-- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
-- See Map.Base.Note: Type of local 'go' function
insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a
-> (Maybe a, Map k a)
insertLookupWithKey f0 kx0 x0 t0 = toPair $ go f0 kx0 x0 t0
where
go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> StrictPair (Maybe a) (Map k a)
STRICT_2_OF_4(go)
go _ kx x Tip = Nothing :*: singleton kx x
go f kx x (Bin sy ky y l r) =
case compare kx ky of
LT -> let (found :*: l') = go f kx x l
in found :*: balanceL ky y l' r
GT -> let (found :*: r') = go f kx x r
in found :*: balanceR ky y l r'
EQ -> let x' = f kx x y
in x' `seq` (Just y :*: Bin sy kx x' l r)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insertLookupWithKey #-}
#else
{-# INLINE insertLookupWithKey #-}
#endif
{--------------------------------------------------------------------
Deletion
--------------------------------------------------------------------}
-- | /O(log n)/. Update a value at a specific key with the result of the provided function.
-- When the key is not
-- a member of the map, the original map is returned.
--
-- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
-- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > adjust ("new " ++) 7 empty == empty
adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
adjust f = adjustWithKey (\_ x -> f x)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE adjust #-}
#else
{-# INLINE adjust #-}
#endif
-- | /O(log n)/. Adjust a value at a specific key. When the key is not
-- a member of the map, the original map is returned.
--
-- > let f key x = (show key) ++ ":new " ++ x
-- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
-- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > adjustWithKey f 7 empty == empty
adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
adjustWithKey f = updateWithKey (\k' x' -> Just (f k' x'))
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE adjustWithKey #-}
#else
{-# INLINE adjustWithKey #-}
#endif
-- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
-- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
-- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
--
-- > let f x = if x == "a" then Just "new a" else Nothing
-- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
-- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
update f = updateWithKey (\_ x -> f x)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE update #-}
#else
{-# INLINE update #-}
#endif
-- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
-- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
-- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
-- to the new value @y@.
--
-- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
-- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
-- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
-- See Map.Base.Note: Type of local 'go' function
updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
updateWithKey = go
where
go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
STRICT_2_OF_3(go)
go _ _ Tip = Tip
go f k(Bin sx kx x l r) =
case compare k kx of
LT -> balanceR kx x (go f k l) r
GT -> balanceL kx x l (go f k r)
EQ -> case f kx x of
Just x' -> x' `seq` Bin sx kx x' l r
Nothing -> glue l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE updateWithKey #-}
#else
{-# INLINE updateWithKey #-}
#endif
-- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
-- The function returns changed value, if it is updated.
-- Returns the original key value if the map entry is deleted.
--
-- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
-- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
-- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
-- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
-- See Map.Base.Note: Type of local 'go' function
updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
updateLookupWithKey f0 k0 t0 = toPair $ go f0 k0 t0
where
go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> StrictPair (Maybe a) (Map k a)
STRICT_2_OF_3(go)
go _ _ Tip = (Nothing :*: Tip)
go f k (Bin sx kx x l r) =
case compare k kx of
LT -> let (found :*: l') = go f k l
in found :*: balanceR kx x l' r
GT -> let (found :*: r') = go f k r
in found :*: balanceL kx x l r'
EQ -> case f kx x of
Just x' -> x' `seq` (Just x' :*: Bin sx kx x' l r)
Nothing -> (Just x :*: glue l r)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE updateLookupWithKey #-}
#else
{-# INLINE updateLookupWithKey #-}
#endif
-- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
-- 'alter' can be used to insert, delete, or update a value in a 'Map'.
-- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
--
-- > let f _ = Nothing
-- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- >
-- > let f _ = Just "c"
-- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
-- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
-- See Map.Base.Note: Type of local 'go' function
alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
alter = go
where
go :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
STRICT_2_OF_3(go)
go f k Tip = case f Nothing of
Nothing -> Tip
Just x -> singleton k x
go f k (Bin sx kx x l r) = case compare k kx of
LT -> balance kx x (go f k l) r
GT -> balance kx x l (go f k r)
EQ -> case f (Just x) of
Just x' -> x' `seq` Bin sx kx x' l r
Nothing -> glue l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE alter #-}
#else
{-# INLINE alter #-}
#endif
{--------------------------------------------------------------------
Indexing
--------------------------------------------------------------------}
-- | /O(log n)/. Update the element at /index/. Calls 'error' when an
-- invalid index is used.
--
-- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
-- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
-- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
-- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
-- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
-- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
-- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
updateAt f i t = i `seq`
case t of
Tip -> error "Map.updateAt: index out of range"
Bin sx kx x l r -> case compare i sizeL of
LT -> balanceR kx x (updateAt f i l) r
GT -> balanceL kx x l (updateAt f (i-sizeL-1) r)
EQ -> case f kx x of
Just x' -> x' `seq` Bin sx kx x' l r
Nothing -> glue l r
where
sizeL = size l
{--------------------------------------------------------------------
Minimal, Maximal
--------------------------------------------------------------------}
-- | /O(log n)/. Update the value at the minimal key.
--
-- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
-- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
updateMin :: (a -> Maybe a) -> Map k a -> Map k a
updateMin f m
= updateMinWithKey (\_ x -> f x) m
-- | /O(log n)/. Update the value at the maximal key.
--
-- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
-- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
updateMax :: (a -> Maybe a) -> Map k a -> Map k a
updateMax f m
= updateMaxWithKey (\_ x -> f x) m
-- | /O(log n)/. Update the value at the minimal key.
--
-- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
-- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
updateMinWithKey _ Tip = Tip
updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
Nothing -> r
Just x' -> x' `seq` Bin sx kx x' Tip r
updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r
-- | /O(log n)/. Update the value at the maximal key.
--
-- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
-- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
updateMaxWithKey _ Tip = Tip
updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
Nothing -> l
Just x' -> x' `seq` Bin sx kx x' l Tip
updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r)
{--------------------------------------------------------------------
Union.
--------------------------------------------------------------------}
-- | The union of a list of maps, with a combining operation:
-- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
--
-- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
-- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
unionsWith f ts
= foldlStrict (unionWith f) empty ts
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE unionsWith #-}
#endif
{--------------------------------------------------------------------
Union with a combining function
--------------------------------------------------------------------}
-- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
--
-- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
unionWith f m1 m2
= unionWithKey (\_ x y -> f x y) m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE unionWith #-}
#endif
-- | /O(n+m)/.
-- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
--
-- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
-- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
unionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) id id t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE unionWithKey #-}
#endif
{--------------------------------------------------------------------
Difference
--------------------------------------------------------------------}
-- | /O(n+m)/. Difference with a combining function.
-- When two equal keys are
-- encountered, the combining function is applied to the values of these keys.
-- If it returns 'Nothing', the element is discarded (proper set difference). If
-- it returns (@'Just' y@), the element is updated with a new value @y@.
-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
-- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
-- > == singleton 3 "b:B"
differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
differenceWith f m1 m2
= differenceWithKey (\_ x y -> f x y) m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE differenceWith #-}
#endif
-- | /O(n+m)/. Difference with a combining function. When two equal keys are
-- encountered, the combining function is applied to the key and both values.
-- If it returns 'Nothing', the element is discarded (proper set difference). If
-- it returns (@'Just' y@), the element is updated with a new value @y@.
-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
-- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
-- > == singleton 3 "3:b|B"
differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
differenceWithKey f t1 t2 = mergeWithKey f id (const Tip) t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE differenceWithKey #-}
#endif
{--------------------------------------------------------------------
Intersection
--------------------------------------------------------------------}
-- | /O(n+m)/. Intersection with a combining function. The implementation uses
-- an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
intersectionWith f m1 m2
= intersectionWithKey (\_ x y -> f x y) m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE intersectionWith #-}
#endif
-- | /O(n+m)/. Intersection with a combining function. The implementation uses
-- an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
-- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
intersectionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) (const Tip) (const Tip) t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE intersectionWithKey #-}
#endif
{--------------------------------------------------------------------
MergeWithKey
--------------------------------------------------------------------}
-- | /O(n+m)/. A high-performance universal combining function. This function
-- is used to define 'unionWith', 'unionWithKey', 'differenceWith',
-- 'differenceWithKey', 'intersectionWith', 'intersectionWithKey' and can be
-- used to define other custom combine functions.
--
-- Please make sure you know what is going on when using 'mergeWithKey',
-- otherwise you can be surprised by unexpected code growth or even
-- corruption of the data structure.
--
-- When 'mergeWithKey' is given three arguments, it is inlined to the call
-- site. You should therefore use 'mergeWithKey' only to define your custom
-- combining functions. For example, you could define 'unionWithKey',
-- 'differenceWithKey' and 'intersectionWithKey' as
--
-- > myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2
-- > myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2
-- > myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2
--
-- When calling @'mergeWithKey' combine only1 only2@, a function combining two
-- 'IntMap's is created, such that
--
-- * if a key is present in both maps, it is passed with both corresponding
-- values to the @combine@ function. Depending on the result, the key is either
-- present in the result with specified value, or is left out;
--
-- * a nonempty subtree present only in the first map is passed to @only1@ and
-- the output is added to the result;
--
-- * a nonempty subtree present only in the second map is passed to @only2@ and
-- the output is added to the result.
--
-- The @only1@ and @only2@ methods /must return a map with a subset (possibly empty) of the keys of the given map/.
-- The values can be modified arbitrarily. Most common variants of @only1@ and
-- @only2@ are 'id' and @'const' 'empty'@, but for example @'map' f@ or
-- @'filterWithKey' f@ could be used for any @f@.
mergeWithKey :: Ord k => (k -> a -> b -> Maybe c) -> (Map k a -> Map k c) -> (Map k b -> Map k c)
-> Map k a -> Map k b -> Map k c
mergeWithKey f g1 g2 = go
where
go Tip t2 = g2 t2
go t1 Tip = g1 t1
go t1 t2 = hedgeMerge NothingS NothingS t1 t2
hedgeMerge _ _ t1 Tip = g1 t1
hedgeMerge blo bhi Tip (Bin _ kx x l r) = g2 $ link kx x (filterGt blo l) (filterLt bhi r)
hedgeMerge blo bhi (Bin _ kx x l r) t2 = let l' = hedgeMerge blo bmi l (trim blo bmi t2)
(found, trim_t2) = trimLookupLo kx bhi t2
r' = hedgeMerge bmi bhi r trim_t2
in case found of
Nothing -> case g1 (singleton kx x) of
Tip -> merge l' r'
(Bin _ _ x' Tip Tip) -> link kx x' l' r'
_ -> error "mergeWithKey: Given function only1 does not fulfil required conditions (see documentation)"
Just x2 -> case f kx x x2 of
Nothing -> merge l' r'
Just x' -> x' `seq` link kx x' l' r'
where bmi = JustS kx
{-# INLINE mergeWithKey #-}
{--------------------------------------------------------------------
Filter and partition
--------------------------------------------------------------------}
-- | /O(n)/. Map values and collect the 'Just' results.
--
-- > let f x = if x == "a" then Just "new a" else Nothing
-- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b
mapMaybe f = mapMaybeWithKey (\_ x -> f x)
-- | /O(n)/. Map keys\/values and collect the 'Just' results.
--
-- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
-- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b
mapMaybeWithKey _ Tip = Tip
mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
Just y -> y `seq` link kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
-- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
--
-- > let f a = if a < "c" then Left a else Right a
-- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
-- >
-- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c)
mapEither f m
= mapEitherWithKey (\_ x -> f x) m
-- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
--
-- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
-- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
-- >
-- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
mapEitherWithKey f0 t0 = toPair $ go f0 t0
where
go _ Tip = (Tip :*: Tip)
go f (Bin _ kx x l r) = case f kx x of
Left y -> y `seq` (link kx y l1 r1 :*: merge l2 r2)
Right z -> z `seq` (merge l1 r1 :*: link kx z l2 r2)
where
(l1 :*: l2) = go f l
(r1 :*: r2) = go f r
{--------------------------------------------------------------------
Mapping
--------------------------------------------------------------------}
-- | /O(n)/. Map a function over all values in the map.
--
-- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
map :: (a -> b) -> Map k a -> Map k b
map _ Tip = Tip
map f (Bin sx kx x l r) = let x' = f x in x' `seq` Bin sx kx x' (map f l) (map f r)
#ifdef __GLASGOW_HASKELL__
{-# NOINLINE [1] map #-}
{-# RULES
"map/map" forall f g xs . map f (map g xs) = map (f . g) xs
#-}
#endif
#if __GLASGOW_HASKELL__ >= 709
-- Safe coercions were introduced in 7.8, but did not work well with RULES yet.
{-# RULES
"mapSeq/coerce" map coerce = coerce
#-}
#endif
-- | /O(n)/. Map a function over all values in the map.
--
-- > let f key x = (show key) ++ ":" ++ x
-- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
mapWithKey _ Tip = Tip
mapWithKey f (Bin sx kx x l r) =
let x' = f kx x
in x' `seq` Bin sx kx x' (mapWithKey f l) (mapWithKey f r)
#ifdef __GLASGOW_HASKELL__
{-# NOINLINE [1] mapWithKey #-}
{-# RULES
"mapWithKey/mapWithKey" forall f g xs . mapWithKey f (mapWithKey g xs) =
mapWithKey (\k a -> f k (g k a)) xs
"mapWithKey/map" forall f g xs . mapWithKey f (map g xs) =
mapWithKey (\k a -> f k (g a)) xs
"map/mapWithKey" forall f g xs . map f (mapWithKey g xs) =
mapWithKey (\k a -> f (g k a)) xs
#-}
#endif
-- | /O(n)/. The function 'mapAccum' threads an accumulating
-- argument through the map in ascending order of keys.
--
-- > let f a b = (a ++ b, b ++ "X")
-- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
mapAccum f a m
= mapAccumWithKey (\a' _ x' -> f a' x') a m
-- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
-- argument through the map in ascending order of keys.
--
-- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
-- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
mapAccumWithKey f a t
= mapAccumL f a t
-- | /O(n)/. The function 'mapAccumL' threads an accumulating
-- argument through the map in ascending order of keys.
mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
mapAccumL _ a Tip = (a,Tip)
mapAccumL f a (Bin sx kx x l r) =
let (a1,l') = mapAccumL f a l
(a2,x') = f a1 kx x
(a3,r') = mapAccumL f a2 r
in x' `seq` (a3,Bin sx kx x' l' r')
-- | /O(n)/. The function 'mapAccumR' threads an accumulating
-- argument through the map in descending order of keys.
mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
mapAccumRWithKey _ a Tip = (a,Tip)
mapAccumRWithKey f a (Bin sx kx x l r) =
let (a1,r') = mapAccumRWithKey f a r
(a2,x') = f a1 kx x
(a3,l') = mapAccumRWithKey f a2 l
in x' `seq` (a3,Bin sx kx x' l' r')
-- | /O(n*log n)/.
-- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
--
-- The size of the result may be smaller if @f@ maps two or more distinct
-- keys to the same new key. In this case the associated values will be
-- combined using @c@.
--
-- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
-- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE mapKeysWith #-}
#endif
{--------------------------------------------------------------------
Conversions
--------------------------------------------------------------------}
-- | /O(n)/. Build a map from a set of keys and a function which for each key
-- computes its value.
--
-- > fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")]
-- > fromSet undefined Data.Set.empty == empty
fromSet :: (k -> a) -> Set.Set k -> Map k a
fromSet _ Set.Tip = Tip
fromSet f (Set.Bin sz x l r) = case f x of v -> v `seq` Bin sz x v (fromSet f l) (fromSet f r)
{--------------------------------------------------------------------
Lists
use [foldlStrict] to reduce demand on the control-stack
--------------------------------------------------------------------}
-- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
-- If the list contains more than one value for the same key, the last value
-- for the key is retained.
--
-- If the keys of the list are ordered, linear-time implementation is used,
-- with the performance equal to 'fromDistinctAscList'.
--
-- > fromList [] == empty
-- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
-- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
-- For some reason, when 'singleton' is used in fromList or in
-- create, it is not inlined, so we inline it manually.
fromList :: Ord k => [(k,a)] -> Map k a
fromList [] = Tip
fromList [(kx, x)] = x `seq` Bin 1 kx x Tip Tip
fromList ((kx0, x0) : xs0) | not_ordered kx0 xs0 = x0 `seq` fromList' (Bin 1 kx0 x0 Tip Tip) xs0
| otherwise = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
where
not_ordered _ [] = False
not_ordered kx ((ky,_) : _) = kx >= ky
{-# INLINE not_ordered #-}
fromList' t0 xs = foldlStrict ins t0 xs
where ins t (k,x) = insert k x t
STRICT_1_OF_3(go)
go _ t [] = t
go _ t [(kx, x)] = x `seq` insertMax kx x t
go s l xs@((kx, x) : xss) | not_ordered kx xss = fromList' l xs
| otherwise = case create s xss of
(r, ys, []) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
(r, _, ys) -> x `seq` fromList' (link kx x l r) ys
-- The create is returning a triple (tree, xs, ys). Both xs and ys
-- represent not yet processed elements and only one of them can be nonempty.
-- If ys is nonempty, the keys in ys are not ordered with respect to tree
-- and must be inserted using fromList'. Otherwise the keys have been
-- ordered so far.
STRICT_1_OF_2(create)
create _ [] = (Tip, [], [])
create s xs@(xp : xss)
| s == 1 = case xp of (kx, x) | not_ordered kx xss -> x `seq` (Bin 1 kx x Tip Tip, [], xss)
| otherwise -> x `seq` (Bin 1 kx x Tip Tip, xss, [])
| otherwise = case create (s `shiftR` 1) xs of
res@(_, [], _) -> res
(l, [(ky, y)], zs) -> y `seq` (insertMax ky y l, [], zs)
(l, ys@((ky, y):yss), _) | not_ordered ky yss -> (l, [], ys)
| otherwise -> case create (s `shiftR` 1) yss of
(r, zs, ws) -> y `seq` (link ky y l r, zs, ws)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromList #-}
#endif
-- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
--
-- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
-- > fromListWith (++) [] == empty
fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
fromListWith f xs
= fromListWithKey (\_ x y -> f x y) xs
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromListWith #-}
#endif
-- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
--
-- > let f k a1 a2 = (show k) ++ a1 ++ a2
-- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
-- > fromListWithKey f [] == empty
fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
fromListWithKey f xs
= foldlStrict ins empty xs
where
ins t (k,x) = insertWithKey f k x t
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromListWithKey #-}
#endif
{--------------------------------------------------------------------
Building trees from ascending/descending lists can be done in linear time.
Note that if [xs] is ascending that:
fromAscList xs == fromList xs
fromAscListWith f xs == fromListWith f xs
--------------------------------------------------------------------}
-- | /O(n)/. Build a map from an ascending list in linear time.
-- /The precondition (input list is ascending) is not checked./
--
-- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
-- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
-- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
-- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
fromAscList :: Eq k => [(k,a)] -> Map k a
fromAscList xs
= fromAscListWithKey (\_ x _ -> x) xs
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromAscList #-}
#endif
-- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
-- /The precondition (input list is ascending) is not checked./
--
-- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
-- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
-- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
fromAscListWith f xs
= fromAscListWithKey (\_ x y -> f x y) xs
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromAscListWith #-}
#endif
-- | /O(n)/. Build a map from an ascending list in linear time with a
-- combining function for equal keys.
-- /The precondition (input list is ascending) is not checked./
--
-- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
-- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
-- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
-- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
fromAscListWithKey f xs
= fromDistinctAscList (combineEq f xs)
where
-- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
combineEq _ xs'
= case xs' of
[] -> []
[x] -> [x]
(x:xx) -> combineEq' x xx
combineEq' z [] = [z]
combineEq' z@(kz,zz) (x@(kx,xx):xs')
| kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
| otherwise = z:combineEq' x xs'
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromAscListWithKey #-}
#endif
-- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
-- /The precondition is not checked./
--
-- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
-- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
-- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
-- For some reason, when 'singleton' is used in fromDistinctAscList or in
-- create, it is not inlined, so we inline it manually.
fromDistinctAscList :: [(k,a)] -> Map k a
fromDistinctAscList [] = Tip
fromDistinctAscList ((kx0, x0) : xs0) = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
where
STRICT_1_OF_3(go)
go _ t [] = t
go s l ((kx, x) : xs) = case create s xs of
(r, ys) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
STRICT_1_OF_2(create)
create _ [] = (Tip, [])
create s xs@(x' : xs')
| s == 1 = case x' of (kx, x) -> x `seq` (Bin 1 kx x Tip Tip, xs')
| otherwise = case create (s `shiftR` 1) xs of
res@(_, []) -> res
(l, (ky, y):ys) -> case create (s `shiftR` 1) ys of
(r, zs) -> y `seq` (link ky y l r, zs)
|
shockkolate/containers
|
Data/Map/Strict.hs
|
Haskell
|
bsd-3-clause
| 45,518
|
-- Stacks: using restricted type synonyms
module Stack where
type Stack a = [a] in emptyStack, push, pop, topOf, isEmpty
emptyStack :: Stack a
emptyStack = []
push :: a -> Stack a -> Stack a
push = (:)
pop :: Stack a -> Stack a
pop [] = error "pop: empty stack"
pop (_:xs) = xs
topOf :: Stack a -> a
topOf [] = error "topOf: empty stack"
topOf (x:_) = x
isEmpty :: Stack a -> Bool
isEmpty = null
instance Eq a => Eq (Stack a) where
s1 == s2 | isEmpty s1 = isEmpty s2
| isEmpty s2 = isEmpty s1
| otherwise = topOf s1 == topOf s2 && pop s1 == pop s2
-- A slightly different presentation:
type Stack' a = [a] in
emptyStack' :: Stack' a,
push' :: a -> Stack' a -> Stack' a,
pop' :: Stack' a -> Stack' a,
topOf' :: Stack' a -> a,
isEmpty' :: Stack' a -> Bool
emptyStack' = []
push' = (:)
pop' [] = error "pop': empty stack"
pop' (_:xs) = xs
topOf' [] = error "topOf': empty stack"
topOf' (x:_) = x
isEmpty' = null
instance Eq a => Eq (Stack' a) where
s1 == s2 | isEmpty' s1 = isEmpty' s2
| isEmpty' s2 = isEmpty' s1
| otherwise = topOf' s1 == topOf' s2 && pop' s1 == pop' s2
|
FranklinChen/Hugs
|
demos/Stack.hs
|
Haskell
|
bsd-3-clause
| 1,249
|
{-# LANGUAGE LambdaCase, MultiWayIf #-}
module Unification
( Equality
, Bindings
, Unifiable
, unifyLiberally
, applyBinding
, applyBinding'
, applyBindingM
, UnificationResult(..)
) where
import qualified Data.Map as M
import Control.Monad
import Control.Applicative
import Control.Monad.Trans.Class
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Writer
--import Debug.Trace
import Data.List
import Propositions
import Unbound.LocallyNameless
import Unbound.LocallyNameless.Fresh
type Equality = (Term, Term)
-- Invariant: If (v1, Var v2), then v1 <= v2
type Bindings = M.Map Var Term
type Unifiable = [Var]
emptyBinding :: Bindings
emptyBinding = M.empty
data UnificationResult = Solved | Failed | Dunno
deriving Show
unifyLiberally :: Unifiable -> [(a,Equality)] -> (Bindings, [(a,UnificationResult)])
unifyLiberally uvs eqns = flip contFreshM highest $
iter (uvs, emptyBinding) $ map (\(n,e) -> (n,Dunno,e)) eqns
where
highest = firstFree (uvs, map snd eqns)
-- Repeatedly go through the list of equalities until we can solve no more
iter :: Fresh m => (Unifiable, Bindings) -> [(a, UnificationResult, Equality)] -> m (Bindings, [(a, UnificationResult)])
iter (uvs, bind) eqns = do
((uvs', bind'), eqns') <- runWriterT $ go (uvs,bind) eqns
if M.size bind' > M.size bind
then iter (uvs', bind') eqns'
else return (bind', map (\(n,r,_) -> (n,r)) eqns')
-- we learned something, so retry
go :: Fresh m => (Unifiable, Bindings) -> [(a,UnificationResult, Equality)] -> WriterT [(a,UnificationResult, Equality)] m (Unifiable, Bindings)
go uvs_bind [] = return uvs_bind
go uvs_bind ((n,Dunno,x):xs) = do
maybe_uvs_bind' <- lift $ runMaybeT (uncurry unif uvs_bind x)
case maybe_uvs_bind' of
Just (uvs',bind') -> do
solved <- x `solvedBy` bind'
if solved
then tell [(n,Solved, x)] >> go (uvs',bind') xs
-- Discard the results of this dunno,
-- potentially less complete, but makes the output easier to understand
else tell [(n,Dunno, x)] >> go uvs_bind xs
Nothing ->
tell [(n, Failed, x)] >> go uvs_bind xs
-- Do not look at solved or failed equations again
go uvs_bind ((n,r,x):xs) = tell [(n,r,x)] >> go uvs_bind xs
-- Code taken from http://www21.in.tum.de/~nipkow/pubs/lics93.html
{-
fun unif (S,(s,t)) = case (devar S s,devar S t) of
(x\s,y\t) => unif (S,(s,if x=y then t else subst x y t))
| (x\s,t) => unif (S,(s,t$(B x)))
| (s,x\t) => unif (S,(s$(B x),t))
| (s,t) => cases S (s,t)
-}
unif :: (MonadPlus m, Fresh m) => [Var] -> Bindings -> (Term, Term) -> m ([Var], Bindings)
unif uvs binds (s,t) = do
s' <- devar binds s
t' <- devar binds t
case (s',t') of
(Lam b1, Lam b2)
-> lunbind2' b1 b2 $ \(Just (_,s,_,t)) -> unif uvs binds (s,t)
(s,t) -> cases uvs binds (s,t)
{-
and cases S (s,t) = case (strip s,strip t) of
((V F,ym),(V G,zn)) => flexflex(F,ym,G,zn,S)
| ((V F,ym),_) => flexrigid(F,ym,t,S)
| (_,(V F,ym)) => flexrigid(F,ym,s,S)
| ((a,sm),(b,tn)) => rigidrigid(a,sm,b,tn,S)
-}
cases :: (MonadPlus m, Fresh m) => [Var] -> Bindings -> (Term, Term) -> m ([Var], Bindings)
cases uvs binds (s,t) = do
case (strip s, strip t) of
((V f, ym), (V g, zn))
| f `elem` uvs && g `elem` uvs -> flexflex uvs binds f ym g zn
((V f, ym), _)
| f `elem` uvs -> flexrigid uvs binds f ym t
(_, (V g, zn))
| g `elem` uvs -> flexrigid uvs binds g zn s
((a, sm), (b, tn))
-> rigidrigid uvs binds a sm b tn
{-
fun flexflex1(F,ym,zn,S) =
if ym=zn then S else (F, hnf(ym, newV(), eqs ym zn)) :: S;
fun flexflex2(F,ym,G,zn,S) =
if ym subset zn then (G, hnf(zn,V F,ym)) :: S else
if zn subset ym then (F, hnf(ym,V G,zn)) :: S
else let val xk = ym /\ zn and H = newV()
in (F, hnf(ym,H,xk)) :: (G, hnf(zn,H,xk)) :: S end;
fun flexflex(F,ym,G,zn,S) = if F=G then flexflex1(F,ym,zn,S)
else flexflex2(F,ym,G,zn,S);
-}
flexflex :: (MonadPlus m, Fresh m) => [Var] -> Bindings -> Var -> [Term] -> Var -> [Term] -> m ([Var], Bindings)
flexflex uvs binds f ym g zn
| f == g && ym == zn = return (uvs, binds)
| f == g
, Just ym' <- allBoundVar uvs ym
= do
newName <- fresh (string2Name "uni")
let rhs = absTerm ym' (App (V newName) (intersect ym zn))
binds' = M.insert f rhs binds
return (newName:uvs, binds')
| f == g = return (uvs, binds) -- non-pattern: Just ignore
| Just ym' <- allBoundVar uvs ym
, Just zn' <- allBoundVar uvs zn
= if | all (`elem` zn') ym' -> do
let rhs = absTerm zn' (App (V f) ym)
binds' = M.insert g rhs binds
return (uvs, binds')
| all (`elem` ym') zn' -> do
let rhs = absTerm ym' (App (V g) zn)
binds' = M.insert f rhs binds
return (uvs, binds')
| otherwise -> do
newName <- fresh (string2Name "uni")
let rhs1 = absTerm ym' (App (V newName) (intersect ym zn))
rhs2 = absTerm zn' (App (V newName) (intersect ym zn))
binds' = M.insert f rhs1 $ M.insert g rhs2 binds
return (newName:uvs, binds')
| otherwise = return (uvs, binds) -- non-pattern: Just ignore
{-
fun occ F S (V G) = (F=G) orelse
(case assoc G S of Some(s) => occ F S s | None => false)
| occ F S (s$t) = occ F S s orelse occ F S t
| occ F S (_\s) = occ F S s
| occ F S (_) = false;
-}
occ :: Alpha b => Bindings -> Name Term -> b -> Bool
occ binds v t = v `elem` vars || any (maybe False (occ binds v) . (`M.lookup` binds)) vars
where vars = fv t::[Var]
{-
fun flexrigid(F,ym,t,S) = if occ F S t then raise Unif
else proj (map B1 ym) (((F,abs(ym,t))::S),t);
-}
flexrigid :: (MonadPlus m, Fresh m) => [Var] -> Bindings -> Var -> [Term] -> Term -> m ([Var], Bindings)
flexrigid uvs binds f ym t
| occ binds f t
= mzero
| Just vs <- allBoundVar uvs ym
= let binds' = M.insert f (absTerm vs t) binds
in proj vs uvs binds' t
| otherwise
= return (uvs, binds) -- not a pattern, ignoring here
{-
fun proj W (S,s) = case strip(devar S s) of
(x\t,_) => proj (x::W) (S,t)
| (C _,ss) => foldl (proj W) (S,ss)
| (B x,ss) => if x mem W then foldl (proj W) (S,ss) else raise Unif
| (V F,ss) => if (map B1 ss) subset W then S
else (F, hnf(ss, newV(), ss /\ (map B W))) :: S;
-}
proj :: (MonadPlus m, Fresh m) => [Var] -> [Var] -> Bindings -> Term -> m ([Var], Bindings)
proj w uvs binds s = do
s' <- devar binds s
case strip s' of
(Lam b, _)
-> lunbind' b $ \(x,t) -> proj (x:w) uvs binds t
(V v, ss) | v `elem` uvs
-> case allBoundVar uvs ss of
Just vs | all (`elem` w) vs -> return (uvs, binds)
Just vs -> do
newName <- fresh (string2Name "uni")
let rhs = absTerm vs (App (V newName) (ss ++ map V w))
let binds' = M.insert v rhs binds
return (newName:uvs, binds')
-- Found a non-pattern use of a free variable, so recurse into the arguments
-- (The correctness of this is a guess by Joachim)
Nothing -> recurse ss
| v `elem` w -> recurse ss
| otherwise -> mzero
(C _, ss) -> recurse ss
(App _ _, _) -> error "Unreachable"
where
recurse = foldM (uncurry (proj w)) (uvs, binds)
allBoundVar :: Unifiable -> [Term] -> Maybe [Var]
allBoundVar _ [] = return []
allBoundVar uvs (V x:xs) | x `notElem` uvs = (x:) <$> allBoundVar uvs xs
allBoundVar _ _ = Nothing
{-
and rigidrigid(a,ss,b,ts,S) = if a <> b then raise Unif
else foldl unif (S,zip ss ts);
-}
rigidrigid :: (MonadPlus m, Fresh m) => [Var] -> Bindings -> Term -> [Term] -> Term -> [Term] -> m ([Var], Bindings)
rigidrigid uvs binds a sm b tn
| a `aeq` b && length sm == length tn
= foldM (uncurry unif) (uvs, binds) (zip sm tn)
| otherwise
= mzero
{-
fun devar S t = case strip t of
(V F,ys) => (case assoc F S of
Some(t) => devar S (red t ys)
| None => t)
| _ => t;
-}
devar :: Fresh m => Bindings -> Term -> m Term
devar binds t = case strip t of
(V v,ys)
| Just t <- M.lookup v binds
-> redsTerm t ys >>= devar binds
_ -> return t
redsTerm :: Fresh m => Term -> [Term] -> m Term
redsTerm t [] = return t
redsTerm (Lam b) (x:xs) = lunbind' b $ \(v,body) -> redsTerm (subst v x body) xs
redsTerm t xs = return $ App t xs
strip :: Term -> (Term, [Term])
strip t = go t []
where go (App t args) args' = go t (args++args')
go t args' = (t, args')
solvedBy :: Fresh m => Equality -> Bindings -> m Bool
solvedBy (t1,t2) b = liftM2 aeq (applyBindingM b t1) (applyBindingM b t2)
-- | This is slow. If possible, use 'applyBinding'' or 'applyBindingM'
applyBinding :: Bindings -> Term -> Term
applyBinding bindings t = applyBinding' (firstFree (M.toList bindings,t)) bindings t
applyBinding' :: Integer -> Bindings -> Term -> Term
applyBinding' free bindings t = flip contFreshM free $ applyBindingM bindings t
applyBindingM :: Fresh m => Bindings -> Term -> m Term
applyBindingM bindings t = go [] t
where
go args (V v) | Just t <- M.lookup v bindings
= go args t
go [] (V v) = return $ V v
go args (V v) = App (V v) <$> mapM (go []) args
go [] (C v) = return $ C v
go args (C v) = App (C v) <$> mapM (go []) args
go args (App t args') = go (args' ++ args) t
go [] (Lam b) = lunbind' b $ \(v,body) -> Lam . bind v <$> go [] body
go (x:xs) (Lam b) = lunbind' b $ \(v,body) -> go xs (subst v x body)
-- This can be dropped once we only support GHC-7.10
infixl 4 <$>
(<$>) = liftM
lunbind' :: (Fresh m, Alpha p, Alpha t) => Bind p t -> ((p, t) -> m c) -> m c
lunbind' b c = unbind b >>= c
lunbind2' :: (Fresh m, Alpha p1, Alpha p2, Alpha t1, Alpha t2) => Bind p1 t1 -> Bind p2 t2 -> (Maybe (p1, t1, p2, t2) -> m r) -> m r
lunbind2' b1 b2 c = unbind2 b1 b2 >>= c
|
psibi/incredible
|
logic/Unification.hs
|
Haskell
|
mit
| 10,729
|
{-# LANGUAGE StandaloneKindSignatures #-}
{-# LANGUAGE PolyKinds, DataKinds, RankNTypes, TypeFamilies,
TypeApplications, TypeOperators, GADTs #-}
module SAKS_030 where
import Data.Kind
import Data.Type.Equality
type T1 :: forall k (a :: k). Bool
type T2 :: k -> Bool
type family T1 where
T1 @Bool @True = False
T1 @Bool @False = True
type family T2 a where
T2 True = False
T2 False = True
type SBool :: Bool -> Type
data SBool b where
STrue :: SBool True
SFalse :: SBool False
proof_t1_eq_t2 :: SBool b -> T1 @Bool @b :~: T2 b
proof_t1_eq_t2 STrue = Refl
proof_t1_eq_t2 SFalse = Refl
|
sdiehl/ghc
|
testsuite/tests/saks/should_compile/saks030.hs
|
Haskell
|
bsd-3-clause
| 619
|
<?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="ar-SA">
<title>دليل البدء</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>محتوى</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>الفهرس</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>بحث</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>المفضلة</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/gettingStarted/src/main/javahelp/org/zaproxy/zap/extension/gettingStarted/resources/help_ar_SA/helpset_ar_SA.hs
|
Haskell
|
apache-2.0
| 978
|
<?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="ur-PK">
<title>Passive Scan Rules | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/pscanrules/src/main/javahelp/org/zaproxy/zap/extension/pscanrules/resources/help_ur_PK/helpset_ur_PK.hs
|
Haskell
|
apache-2.0
| 979
|
{-# LANGUAGE RankNTypes, NamedWildCards #-}
-- See #11098
module NamedWildcardExplicitForall where
foo :: forall _a . _a -> _a -- _a is a type variable
foo = not
bar :: _a -> _a -- _a is a named wildcard
bar = not
baz :: forall _a . _a -> _b -> (_a, _b) -- _a is a variable, _b is a wildcard
baz x y = (not x, not y)
qux :: _a -> (forall _a . _a -> _a) -> _a -- the _a bound by forall is a tyvar
qux x f = let _ = f 7 in not x -- the other _a are wildcards
|
sdiehl/ghc
|
testsuite/tests/partial-sigs/should_fail/NamedWildcardExplicitForall.hs
|
Haskell
|
bsd-3-clause
| 521
|
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-}
module Ros.Internal.Log where
import qualified Prelude as P
import Prelude ((.))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import Ros.Internal.Msg.HeaderSupport
import qualified Data.Word as Word
import qualified Ros.Internal.Header as Header
data Log = Log { header :: Header.Header
, level :: Word.Word8
, name :: P.String
, msg :: P.String
, file :: P.String
, function :: P.String
, line :: Word.Word32
, topics :: [P.String]
} deriving (P.Show, P.Eq, P.Ord, T.Typeable)
instance RosBinary Log where
put obj' = put (header obj') *> put (level obj') *> put (name obj') *> put (msg obj') *> put (file obj') *> put (function obj') *> put (line obj') *> putList (topics obj')
get = Log <$> get <*> get <*> get <*> get <*> get <*> get <*> get <*> getList
putMsg = putStampedMsg
instance HasHeader Log where
getSequence = Header.seq . header
getFrame = Header.frame_id . header
getStamp = Header.stamp . header
setSequence seq x' = x' { header = (header x') { Header.seq = seq } }
instance MsgInfo Log where
sourceMD5 _ = "acffd30cd6b6de30f120938c17c593fb"
msgTypeName _ = "rosgraph_msgs/Log"
dEBUG :: Word.Word8
dEBUG = 1
iNFO :: Word.Word8
iNFO = 2
wARN :: Word.Word8
wARN = 4
eRROR :: Word.Word8
eRROR = 8
fATAL :: Word.Word8
fATAL = 16
|
bitemyapp/roshask
|
src/Ros/Internal/Log.hs
|
Haskell
|
bsd-3-clause
| 1,547
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Provide ability to upload tarballs to Hackage.
module Stack.Upload
( -- * Upload
nopUploader
, mkUploader
, Uploader
, upload
, uploadBytes
, UploadSettings
, defaultUploadSettings
, setUploadUrl
, setGetManager
, setCredsSource
, setSaveCreds
-- * Credentials
, HackageCreds
, loadCreds
, saveCreds
, FromFile
-- ** Credentials source
, HackageCredsSource
, fromAnywhere
, fromPrompt
, fromFile
, fromMemory
) where
import Control.Applicative
import Control.Exception (bracket)
import qualified Control.Exception as E
import Control.Monad (when, unless)
import Data.Aeson (FromJSON (..),
ToJSON (..),
eitherDecode', encode,
object, withObject,
(.:), (.=))
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy as L
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import qualified Data.Text.IO as TIO
import Data.Typeable (Typeable)
import Network.HTTP.Client (BodyReader, Manager,
Response,
RequestBody(RequestBodyLBS),
applyBasicAuth, brRead,
checkStatus, newManager,
parseUrl,
requestHeaders,
responseBody,
responseStatus,
withResponse)
import Network.HTTP.Client.MultipartFormData (formDataBody, partFileRequestBody)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Network.HTTP.Types (statusCode)
import Path (toFilePath)
import Prelude -- Fix redundant import warnings
import Stack.Types
import System.Directory (createDirectoryIfMissing,
removeFile)
import System.FilePath ((</>), takeFileName)
import System.IO (hFlush, hGetEcho, hSetEcho,
stdin, stdout)
-- | Username and password to log into Hackage.
--
-- Since 0.1.0.0
data HackageCreds = HackageCreds
{ hcUsername :: !Text
, hcPassword :: !Text
}
deriving Show
instance ToJSON HackageCreds where
toJSON (HackageCreds u p) = object
[ "username" .= u
, "password" .= p
]
instance FromJSON HackageCreds where
parseJSON = withObject "HackageCreds" $ \o -> HackageCreds
<$> o .: "username"
<*> o .: "password"
-- | A source for getting Hackage credentials.
--
-- Since 0.1.0.0
newtype HackageCredsSource = HackageCredsSource
{ getCreds :: IO (HackageCreds, FromFile)
}
-- | Whether the Hackage credentials were loaded from a file.
--
-- This information is useful since, typically, you only want to save the
-- credentials to a file if it wasn't already loaded from there.
--
-- Since 0.1.0.0
type FromFile = Bool
-- | Load Hackage credentials from the given source.
--
-- Since 0.1.0.0
loadCreds :: HackageCredsSource -> IO (HackageCreds, FromFile)
loadCreds = getCreds
-- | Save the given credentials to the credentials file.
--
-- Since 0.1.0.0
saveCreds :: Config -> HackageCreds -> IO ()
saveCreds config creds = do
fp <- credsFile config
L.writeFile fp $ encode creds
-- | Load the Hackage credentials from the prompt, asking the user to type them
-- in.
--
-- Since 0.1.0.0
fromPrompt :: HackageCredsSource
fromPrompt = HackageCredsSource $ do
putStr "Hackage username: "
hFlush stdout
username <- TIO.getLine
password <- promptPassword
return (HackageCreds
{ hcUsername = username
, hcPassword = password
}, False)
credsFile :: Config -> IO FilePath
credsFile config = do
let dir = toFilePath (configStackRoot config) </> "upload"
createDirectoryIfMissing True dir
return $ dir </> "credentials.json"
-- | Load the Hackage credentials from the JSON config file.
--
-- Since 0.1.0.0
fromFile :: Config -> HackageCredsSource
fromFile config = HackageCredsSource $ do
fp <- credsFile config
lbs <- L.readFile fp
case eitherDecode' lbs of
Left e -> E.throwIO $ Couldn'tParseJSON fp e
Right creds -> return (creds, True)
-- | Load the Hackage credentials from the given arguments.
--
-- Since 0.1.0.0
fromMemory :: Text -> Text -> HackageCredsSource
fromMemory u p = HackageCredsSource $ return (HackageCreds
{ hcUsername = u
, hcPassword = p
}, False)
data HackageCredsExceptions = Couldn'tParseJSON FilePath String
deriving (Show, Typeable)
instance E.Exception HackageCredsExceptions
-- | Try to load the credentials from the config file. If that fails, ask the
-- user to enter them.
--
-- Since 0.1.0.0
fromAnywhere :: Config -> HackageCredsSource
fromAnywhere config = HackageCredsSource $
getCreds (fromFile config) `E.catches`
[ E.Handler $ \(_ :: E.IOException) -> getCreds fromPrompt
, E.Handler $ \(_ :: HackageCredsExceptions) -> getCreds fromPrompt
]
-- | Lifted from cabal-install, Distribution.Client.Upload
promptPassword :: IO Text
promptPassword = do
putStr "Hackage password: "
hFlush stdout
-- save/restore the terminal echoing status
passwd <- bracket (hGetEcho stdin) (hSetEcho stdin) $ \_ -> do
hSetEcho stdin False -- no echoing for entering the password
fmap T.pack getLine
putStrLn ""
return passwd
nopUploader :: Config -> UploadSettings -> IO Uploader
nopUploader _ _ = return (Uploader nop)
where nop :: String -> L.ByteString -> IO ()
nop _ _ = return ()
-- | Turn the given settings into an @Uploader@.
--
-- Since 0.1.0.0
mkUploader :: Config -> UploadSettings -> IO Uploader
mkUploader config us = do
manager <- usGetManager us
(creds, fromFile') <- loadCreds $ usCredsSource us config
when (not fromFile' && usSaveCreds us) $ saveCreds config creds
req0 <- parseUrl $ usUploadUrl us
let req1 = req0
{ requestHeaders = [("Accept", "text/plain")]
, checkStatus = \_ _ _ -> Nothing
}
return Uploader
{ upload_ = \tarName bytes -> do
let formData = [partFileRequestBody "package" tarName (RequestBodyLBS bytes)]
req2 <- formDataBody formData req1
let req3 = applyBasicAuth
(encodeUtf8 $ hcUsername creds)
(encodeUtf8 $ hcPassword creds)
req2
putStr $ "Uploading " ++ tarName ++ "... "
hFlush stdout
withResponse req3 manager $ \res ->
case statusCode $ responseStatus res of
200 -> putStrLn "done!"
401 -> do
putStrLn "authentication failure"
cfp <- credsFile config
handleIO (const $ return ()) (removeFile cfp)
error "Authentication failure uploading to server"
403 -> do
putStrLn "forbidden upload"
putStrLn "Usually means: you've already uploaded this package/version combination"
putStrLn "Ignoring error and continuing, full message from Hackage below:\n"
printBody res
503 -> do
putStrLn "service unavailable"
putStrLn "This error some times gets sent even though the upload succeeded"
putStrLn "Check on Hackage to see if your pacakge is present"
printBody res
code -> do
putStrLn $ "unhandled status code: " ++ show code
printBody res
error $ "Upload failed on " ++ tarName
}
printBody :: Response BodyReader -> IO ()
printBody res =
loop
where
loop = do
bs <- brRead $ responseBody res
unless (S.null bs) $ do
S.hPut stdout bs
loop
-- | The computed value from a @UploadSettings@.
--
-- Typically, you want to use this with 'upload'.
--
-- Since 0.1.0.0
data Uploader = Uploader
{ upload_ :: !(String -> L.ByteString -> IO ())
}
-- | Upload a single tarball with the given @Uploader@.
--
-- Since 0.1.0.0
upload :: Uploader -> FilePath -> IO ()
upload uploader fp = upload_ uploader (takeFileName fp) =<< L.readFile fp
-- | Upload a single tarball with the given @Uploader@. Instead of
-- sending a file like 'upload', this sends a lazy bytestring.
--
-- Since 0.1.2.1
uploadBytes :: Uploader -> String -> L.ByteString -> IO ()
uploadBytes = upload_
-- | Settings for creating an @Uploader@.
--
-- Since 0.1.0.0
data UploadSettings = UploadSettings
{ usUploadUrl :: !String
, usGetManager :: !(IO Manager)
, usCredsSource :: !(Config -> HackageCredsSource)
, usSaveCreds :: !Bool
}
-- | Default value for @UploadSettings@.
--
-- Use setter functions to change defaults.
--
-- Since 0.1.0.0
defaultUploadSettings :: UploadSettings
defaultUploadSettings = UploadSettings
{ usUploadUrl = "https://hackage.haskell.org/packages/"
, usGetManager = newManager tlsManagerSettings
, usCredsSource = fromAnywhere
, usSaveCreds = True
}
-- | Change the upload URL.
--
-- Default: "https://hackage.haskell.org/packages/"
--
-- Since 0.1.0.0
setUploadUrl :: String -> UploadSettings -> UploadSettings
setUploadUrl x us = us { usUploadUrl = x }
-- | How to get an HTTP connection manager.
--
-- Default: @newManager tlsManagerSettings@
--
-- Since 0.1.0.0
setGetManager :: IO Manager -> UploadSettings -> UploadSettings
setGetManager x us = us { usGetManager = x }
-- | How to get the Hackage credentials.
--
-- Default: @fromAnywhere@
--
-- Since 0.1.0.0
setCredsSource :: (Config -> HackageCredsSource) -> UploadSettings -> UploadSettings
setCredsSource x us = us { usCredsSource = x }
-- | Save new credentials to the config file.
--
-- Default: @True@
--
-- Since 0.1.0.0
setSaveCreds :: Bool -> UploadSettings -> UploadSettings
setSaveCreds x us = us { usSaveCreds = x }
handleIO :: (E.IOException -> IO a) -> IO a -> IO a
handleIO = E.handle
|
phadej/stack
|
src/Stack/Upload.hs
|
Haskell
|
bsd-3-clause
| 11,305
|
-- | a module for caching a monadic action based on its return type
--
-- The cache is a HashMap where the key uses the TypeReP from Typeable.
-- The value stored is toDyn from Dynamic to support arbitrary value types in the same Map.
--
-- un-exported newtype wrappers should be used to maintain unique keys in the cache.
-- Note that a TypeRep is unique to a module in a package, so types from different modules will not conflict if they have the same name.
--
-- used in 'Yesod.Core.Handler.cached' and 'Yesod.Core.Handler.cachedBy'
module Yesod.Core.TypeCache (cached, cachedBy, TypeMap, KeyedTypeMap) where
import Prelude hiding (lookup)
import Data.Typeable (Typeable, TypeRep, typeOf)
import Data.HashMap.Strict
import Data.ByteString (ByteString)
import Data.Dynamic (Dynamic, toDyn, fromDynamic)
type TypeMap = HashMap TypeRep Dynamic
type KeyedTypeMap = HashMap (TypeRep, ByteString) Dynamic
-- | avoid performing the same action multiple times.
-- Values are stored by their TypeRep from Typeable.
-- Therefore, you should use un-exported newtype wrappers for each cache.
--
-- For example, yesod-auth uses an un-exported newtype, CachedMaybeAuth and exports functions that utilize it such as maybeAuth.
-- This means that another module can create its own newtype wrapper to cache the same type from a different action without any cache conflicts.
--
-- In Yesod, this is used for a request-local cache that is cleared at the end of every request.
-- See the original announcement: <http://www.yesodweb.com/blog/2013/03/yesod-1-2-cleaner-internals>
--
-- Since 1.4.0
cached :: (Monad m, Typeable a)
=> TypeMap
-> m a -- ^ cache the result of this action
-> m (Either (TypeMap, a) a) -- ^ Left is a cache miss, Right is a hit
cached cache action = case clookup cache of
Just val -> return $ Right val
Nothing -> do
val <- action
return $ Left (cinsert val cache, val)
where
clookup :: Typeable a => TypeMap -> Maybe a
clookup c =
res
where
res = lookup (typeOf $ fromJust res) c >>= fromDynamic
fromJust :: Maybe a -> a
fromJust = error "Yesod.Handler.cached.fromJust: Argument to typeOf was evaluated"
cinsert :: Typeable a => a -> TypeMap -> TypeMap
cinsert v = insert (typeOf v) (toDyn v)
-- | similar to 'cached'.
-- 'cached' can only cache a single value per type.
-- 'cachedBy' stores multiple values per type by indexing on a ByteString key
--
-- 'cached' is ideal to cache an action that has only one value of a type, such as the session's current user
-- 'cachedBy' is required if the action has parameters and can return multiple values per type.
-- You can turn those parameters into a ByteString cache key.
-- For example, caching a lookup of a Link by a token where multiple token lookups might be performed.
--
-- Since 1.4.0
cachedBy :: (Monad m, Typeable a)
=> KeyedTypeMap
-> ByteString -- ^ a cache key
-> m a -- ^ cache the result of this action
-> m (Either (KeyedTypeMap, a) a) -- ^ Left is a cache miss, Right is a hit
cachedBy cache k action = case clookup k cache of
Just val -> return $ Right val
Nothing -> do
val <- action
return $ Left (cinsert k val cache, val)
where
clookup :: Typeable a => ByteString -> KeyedTypeMap -> Maybe a
clookup key c =
res
where
res = lookup (typeOf $ fromJust res, key) c >>= fromDynamic
fromJust :: Maybe a -> a
fromJust = error "Yesod.Handler.cached.fromJust: Argument to typeOf was evaluated"
cinsert :: Typeable a => ByteString -> a -> KeyedTypeMap -> KeyedTypeMap
cinsert key v = insert (typeOf v, key) (toDyn v)
|
ygale/yesod
|
yesod-core/Yesod/Core/TypeCache.hs
|
Haskell
|
mit
| 3,896
|
{-# LANGUAGE OverloadedLists, TypeFamilies #-}
import qualified Data.Set as S
import GHC.Exts
main = do print ([] :: (S.Set Int))
print (['a','b','c'] :: (S.Set Char))
print (['a','c'..'g'] :: (S.Set Char))
instance Ord a => IsList (S.Set a) where
type (Item (S.Set a)) = a
fromList = S.fromList
toList = S.toList
|
lukexi/ghc-7.8-arm64
|
testsuite/tests/overloadedlists/should_run/overloadedlistsrun02.hs
|
Haskell
|
bsd-3-clause
| 350
|
{-# LANGUAGE TemplateHaskell #-}
-- Test for sane reporting on TH code giving up.
module ShouldCompile where
$( fail "Code not written yet..." )
|
urbanslug/ghc
|
testsuite/tests/th/TH_fail.hs
|
Haskell
|
bsd-3-clause
| 148
|
{-# LANGUAGE DeriveGeneric, RecordWildCards, TypeSynonymInstances, FlexibleInstances #-}
module Game.World(
World(..)
, WorldId(..)
, worldInfoMsg
, WorldFindPlayer(..)
) where
import Control.DeepSeq
import Data.Hashable
import Data.HashMap.Strict (HashMap)
import Data.Text (Text)
import Game.Player
import GHC.Generics (Generic)
import Network.Protocol.Message
import qualified Data.HashMap.Strict as M
-- | World are completly isolated environments
data World = World {
worldId :: !WorldId
, worldName :: !Text
, worldPlayers :: !(HashMap PlayerId Player)
, worldPlayersByName :: !(HashMap Text Player)
} deriving (Generic)
instance NFData World
newtype WorldId = WorldId { unWorldId :: Int } deriving (Eq, Show, Generic)
instance NFData WorldId
instance Hashable WorldId
worldInfoMsg :: World -> NetworkMessage
worldInfoMsg (World{..}) = PlayerWorld (unWorldId worldId) worldName
class WorldFindPlayer k where
-- | Finds player by specific key
worldFindPlayer :: World -> k -> Maybe Player
-- | You can search players by name
instance WorldFindPlayer Text where
worldFindPlayer w = (`M.lookup` worldPlayersByName w)
-- | And you can search players by theirs ids
instance WorldFindPlayer PlayerId where
worldFindPlayer w = (`M.lookup` worldPlayers w)
|
NCrashed/sinister
|
src/shared/Game/World.hs
|
Haskell
|
mit
| 1,296
|
{-# LANGUAGE TemplateHaskell #-}
import TemplateHaskell
data MyData = MyData
{ foo :: String
, bar :: Int
}
listFields ''MyData
main = print $ MyData { foo = "what", bar = 1 }
|
limdauto/learning-haskell
|
snippets/TemplateHaskellTests.hs
|
Haskell
|
mit
| 192
|
module System.AtomicWrite.Writer.ByteStringSpec (spec) where
import Test.Hspec (it, describe, shouldBe, Spec)
import System.AtomicWrite.Writer.ByteString (atomicWriteFile)
import System.IO.Temp (withSystemTempDirectory)
import System.FilePath.Posix (joinPath)
import Data.ByteString.Char8 (pack)
spec :: Spec
spec = describe "atomicWriteFile" $
it "writes contents to a file" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let path = joinPath [ tmpDir, "writeTest.tmp" ]
atomicWriteFile path $ pack "just testing"
contents <- readFile path
contents `shouldBe` "just testing"
|
bitemyapp/atomic-write
|
spec/System/AtomicWrite/Writer/ByteStringSpec.hs
|
Haskell
|
mit
| 625
|
{-# LANGUAGE OverloadedStrings #-}
-- | Parser for what seems to be DCPU16 assembly.
--
-- There is some ambiguity between sources: the specification uses uppercase a
-- lot (which I'd rather put in as an option later, with the strict
-- implementation being default).
--
-- A screenshot also shows indirect mode being done with [] instead of (). Go
-- figure.
module DCPU16.Assembly.Parser
( parseFile
, defaults
, Options(..)
) where
import Text.Trifecta hiding (Pop,Push)
import Control.Applicative hiding (Const)
import DCPU16.Instructions
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import Data.Vector (Vector)
import Data.Word (Word16)
import qualified Data.Vector as V
import Data.Char (toUpper)
import Control.Monad (void,unless,when)
import Text.Printf
-- | Default parsing options.
defaults :: Options
defaults = Options False
-- | Parsing options, if you want to override the defaults.
data Options = Options
{ roundedBrackets :: Bool
-- ^ Indirect mode via \(\) instead of \[\]. Default: off.
--
-- Weird, but showed up in a screenshot.
} deriving (Read,Show,Eq)
-- | Parser state.
--
-- Should factor this into a RWS monad wrapper, but don't understand Trifecta
-- well enough to do so. Monads, how do they work?
data Opt = Opt
{ optSymbols :: Vector ByteString
, options :: Options
} deriving (Read,Show,Eq)
-- | Parse a file.
--
-- Detailed errors with line and column numbers (as well as expected values)
-- will be printed to console if parsing fails.
parseFile opt f = do
ss <- parseFromFile symbolDefs f
case ss of
(Just syms) -> parseFromFile (asm (Opt syms opt)) f
Nothing -> return Nothing
symbolDefs :: Parser String (Vector ByteString)
-- | Label definition only parser.
--
-- Meant to be run as the first pass, to extract a table to check label uses
-- against in a future pass.
symbolDefs = process `fmap` (spaces >> ls <* end) where
-- labels appear at the start of lines:
-- if something un-label-like seen, skip to next line
ls = many . lexeme . choice $ [label,nextLine]
nextLine = Data (Const 0) <$ skipSome (satisfy notMark)
notMark c = c/='\n'
process = V.fromList . map (\(Label s)->s) . filter isLabel
isLabel (Label _) = True
isLabel _ = False
-- | Instruction, comment, and label parser.
--
-- Relies on a symbol table parsed in a previous pass to check for label
-- existance.
asm :: Opt -> Parser String (Vector Instruction)
asm o = V.fromList `fmap` (spaces >> instructs <* end) where
instructs = many . lexeme . choice $ [instruction o, label, comment, dat o]
end = eof <?> "comment, end of file, or valid instruction"
-- | For now, data only handles one word.
--
-- Will figure out good syntax sugar (and refactor "asm" to handle multi-word)
-- later.
dat o = Data <$ symbol "dat" <*> word o
label = do
char ':'
l<-labelName
when (isRegName (B.unpack l)) $
err [] $ "label definition "++show l++" clashes with register name"
spaces
return $ Label l
where
isRegName :: String -> Bool
isRegName s = map toUpper s `elem` regs
regs = ["A","B","C","X","Y","Z","I","J"
,"POP","PEEK","PUSH","PC","O"
]
labelName = B.pack `fmap` some labelChars
labelChars = alphaNum <|> char '_' <|> char '.'
comment = do
char ';'
l <- line
Comment (B.head l == ';') <$> manyTill anyChar eofOrNewline
where
eofOrNewline = void (try newline) <|> eof
instruction :: Opt -> Parser String Instruction
instruction o = choice
[ Basic <$> basicOp o <*> operand o <* comma <*> operand o
, NonBasic <$> sym o JSR "jsr" <*> operand o
]
operand :: Opt -> Parser String Operand
operand o = choice
[ sym o Pop "pop"
, sym o Peek "peek"
, sym o Push "push"
, sym o SP "sp"
, sym o PC "pc"
, sym o O "o"
, Direct <$> register o
, DirectLiteral <$> word o
, brace o (indirect o)
]
where
indirect o = choice
[ try $ Offset <$> word o <* symbol "+" <*> register o
, try $ flip Offset <$> register o <* symbol "+" <*> word o
, try $ Indirect <$> register o
, IndirectLiteral <$> word o
]
-- This code is based on the Haskell parser, and thus strips a lot more
-- whitespace than desired. [\na+2] probably shouldn't be valid assembly.
brace o = if roundedBrackets $ options o
then nesting . between (symbolic '(') (symbolic ')')
else brackets
word :: Opt -> Parser String Word
word o = lexeme $ choice
[ Const <$> int
, definedLabel
]
where
definedLabel = do
s <- labelName
unless (s `V.elem` optSymbols o) $
err [] $ "label "++show s++" not defined"
return $ LabelAddr s
int :: Parser String Word16
int = fromInteger <$> (num >>= checkSize)
where
num = choice
[ try $ (char '0' <?> "\"0x\"") >> hexadecimal
, decimal
]
checkSize :: Integer -> Parser String Integer
checkSize n = if n>0xffff
then do
err [] (printf fmt n)
return (mod n 0xffff)
else return n
fmt = "literal 0x%x is wider than 16 bits"
sym o i tok = try $ i <$ token <* notFollowedBy labelChars <* spaces
where
token = string tok <|> string (map toUpper tok)
register o = try $ choice
[ sym o A "a", sym o B "b", sym o C "c"
, sym o X "x", sym o Y "y", sym o Z "z"
, sym o I "i", sym o J "j"
]
basicOp o = choice
[ sym o SET "set", sym o ADD "add", sym o SUB "sub"
, sym o MUL "mul", sym o DIV "div", sym o MOD "mod", sym o SHL "shl"
, sym o SHR "shr", sym o AND "and", sym o BOR "bor", sym o XOR "xor"
, sym o IFE "ife", sym o IFN "ifn", sym o IFG "ifg", sym o IFB "ifb"
]
|
amtal/soyuz
|
DCPU16/Assembly/Parser.hs
|
Haskell
|
mit
| 5,788
|
{-# OPTIONS_GHC -Wall #-}
module Todo.Predicates ( minDate
, maxDate
, minPriority
, maxPriority
, isComplete
) where
import Todo.Data
minDate :: Date -> Task -> Bool
minDate d = maybe False (d >=) . maybeDate
maxDate :: Date -> Task -> Bool
maxDate d = maybe True (d >=) . maybeDate
minPriority :: Priority -> Task -> Bool
minPriority p = maybe False (>= p) . priority
maxPriority :: Priority -> Task -> Bool
maxPriority p = maybe True (<= p) . priority
isComplete :: Task -> Bool
isComplete t = case status t of
Done _ -> True
_ -> False
|
nadirs/todohs
|
src/lib/Todo/Predicates.hs
|
Haskell
|
mit
| 669
|
-- https://projecteuler.net/problem=29
-- Consider all integer combinations of a^b for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
-- 22=4, 23=8, 24=16, 25=32
-- 32=9, 33=27, 34=81, 35=243
-- 42=16, 43=64, 44=256, 45=1024
-- 52=25, 53=125, 54=625, 55=3125
-- If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
-- 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
-- How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
import Data.Set
import qualified Data.Set as Set
import Data.List
cartProd xs ys = [x^y | x <- xs, y <- ys]
countPowers n = size (fromList (cartProd [2..n] [2..n]))
countPowers2 n = length (nub [x^y | x <- [2..n], y <- [2..n]])
|
kirhgoff/haskell-sandbox
|
euler29/countPowers.hs
|
Haskell
|
mit
| 774
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module HsPredictor.LoadCSV where
-- standard
import Control.Exception (bracket, catch, throwIO)
import Control.Monad (when)
import Control.Monad.Error (liftIO)
import Data.Text (pack)
import Prelude hiding (catch)
import System.IO (IOMode (ReadMode), hClose,
hGetContents, openFile)
import System.IO.Error
-- 3rd party
import Database.Persist.Sql (Entity (..), Filter, Key (..),
SelectOpt (LimitTo), SqlBackend,
SqlPersistM, deleteWhere, entityKey,
get, getBy, insert, insertBy,
runMigration, runMigrationSilent,
selectList, selectList, toSqlKey,
update, (+=.), (=.), (==.), (>.))
import Database.Persist.Sqlite (runSqlite)
-- own
import HsPredictor.HashCSV (checkHash, genHash)
import HsPredictor.Models
import HsPredictor.ParserCSV (readMatches)
import HsPredictor.Queries
import HsPredictor.Types (Field (..), Match (..), Result (..))
-- | Inserts match to database
insertMatch :: Match -> SqlPersistM ()
insertMatch (Match {dateM=d,homeM=ht,awayM=at,ghM=gh,gaM=ga,
odds1M=o1,oddsxM=ox,odds2M=o2}) = do
idHome <- getKeyTeams ht
idAway <- getKeyTeams at
insert $ Results d idHome idAway gh ga o1 ox o2
updateTable idHome $ getResult Home gh ga
updateTable idAway $ getResult Away gh ga
-- | Return sql key for a given team name
getKeyTeams :: String -> SqlPersistM (Key Teams)
getKeyTeams team = do
eitherKey <- insertBy $ Teams team
return $ keyFromEither eitherKey
-- | Return result of match
getResult :: Field -> Int -> Int -> Result
getResult Home rh ra
| rh == (-1) = Upcoming
| rh == ra = Draw
| rh > ra = Win
| otherwise = Loss
getResult Away rh ra
| rh == (-1) = Upcoming
| rh == ra = Draw
| rh > ra = Loss
| otherwise = Win
-- | Update team statistics
updateTable :: Key Teams -> Result -> SqlPersistM ()
updateTable team result = do
eitherKey <- insertBy $ StatsTable team 0 0 0
let teamId = keyFromEither eitherKey
case result of
Win -> update teamId [StatsTableWin +=. 1]
Draw -> update teamId [StatsTableDraw +=. 1]
Loss -> update teamId [StatsTableLoss +=. 1]
Upcoming -> return ()
-- | Return sql key form Either
keyFromEither :: Either (Entity record) (Key record) -> Key record
keyFromEither (Left ent) = entityKey ent
keyFromEither (Right key) = key
-- | Insert matches into database. Only if csv was updated.
-- | checkHash prevents from processing the same file twice.
bulkInsert :: [Match] -> String -> String -> SqlPersistM ()
bulkInsert xs hashF hashDB =
when (checkHash hashF hashDB) $ do
deleteWhere ([] :: [Filter Results])
deleteWhere ([] :: [Filter StatsTable])
deleteWhere ([] :: [Filter Teams])
mapM_ insertMatch xs
-- | Main function for processing matches and inserting into database.
action :: [Match] -- ^ list of matches
-> String -- ^ hash of csv file
-> String -- ^ path to database
-> IO ()
action xs hashF dbname = runSqlite (pack dbname) $ do
runMigrationSilent migrateAll
isHashDB <- get (toSqlKey 1 :: MD5Id)
case isHashDB of
Nothing -> do
insertBy $ MD5 hashF
bulkInsert xs hashF ""
Just h -> do
update (toSqlKey 1 :: MD5Id) [MD5Hash =. hashF]
bulkInsert xs hashF $ mD5Hash h
return ()
-- | Return file contents
getFileContents :: String -> IO String
getFileContents fname = readF `catch` handleExists
where
readF = do
csvH <- openFile fname ReadMode
!full <- hGetContents csvH
hClose csvH
return full
handleExists e
| isDoesNotExistError e = return ""
| otherwise = throwIO e
-- | Load csv into database
loadCSV :: String -> String -> IO ()
loadCSV fname dbname = do
full <- getFileContents fname
hash <- genHash full
let matches = readMatches $ lines full
action matches hash dbname
|
Taketrung/HsPredictor
|
library/HsPredictor/LoadCSV.hs
|
Haskell
|
mit
| 4,364
|
module ECL.ClassicChecker where
import ECL.DataTypes
-- | Type Synonyms for pattern
-- * representation
-- *
-- * Basic representations of cases
type Case = [Binder]
type Cases = [Case]
-- * Result
type Result = Cases
-- * Pattern Matching definition
type DefPm = Cases
-- | unmatched: returns the list
-- * of `_` for the first uncovered set
unmatched :: Case -> Cases
unmatched c = [unmatched' c]
unmatched' :: Case -> Case
unmatched' = foldr op []
where
op :: Binder -> Case -> Case
op _ c = NullBinder:c
-- | check: given a pattern matching definition
-- * we check whether or not it is exhaustive
-- * giving the resultant non-covered cases
ccheck :: DefPm -> Result
ccheck [] = []
ccheck pmdef@(pm:_) =
check_uncovers unm pmdef
where
unm = unmatched pm
-- | uncover: single binder uncovering
-- * this returns the difference between
-- * two single binders
uncover :: Binder -> Binder -> Case
uncover Zero Zero = []
uncover _ NullBinder = []
uncover NullBinder b =
concat $ map (\cp -> uncover cp b) all_pat
where
all_pat = [Zero, Succ NullBinder]
uncover (Succ n) (Succ m) =
map Succ ucs
where
ucs = uncover n m
uncover b _ = [b]
-- | uncovers: given an uncovered case and a clause
-- * of a pattern match definition,
-- * returns the uncovered cases
uncovers :: Case -> Case -> Cases
-- empty case
uncovers [] [] = []
-- any-var
uncovers (u:us) (NullBinder:ps) =
map (u:) (uncovers us ps)
-- zero-zero
uncovers (Zero:us) (Zero:ps) =
map (Zero:) (uncovers us ps)
-- succ-zero
uncovers ucs@((Succ _):_) (Zero:_) =
[ucs]
-- zero-succ
uncovers ucs@(Zero:_) ((Succ _):_) =
[ucs]
-- succ-succ
uncovers ((Succ n):us) ((Succ m):ps) =
let ucs = uncovers (n:us) (m:ps)
in map (zip_con Succ) ucs
where
-- This *must* be generalized for all constructors
zip_con :: (Binder -> Binder) -> Case -> Case
zip_con _ [] = []
zip_con b xs = (b hps):rest
where
(hps, rest) = (head xs, tail xs)
-- var-nat
uncovers (NullBinder:us) pats@(_:_) =
-- This must be something that traverse all constructors of a type
let all_pat = [Zero, Succ NullBinder]
uncovered = map (\cp -> uncovers (cp:us) pats) all_pat
in concat uncovered
-- I guess other cases must fail inside a monad
uncovers _ _ = []
-- | uncovering: returns the cases
-- * that are not covered by a single clause
uncovering :: Cases -> Case -> Cases
uncovering unc clause =
concat $ map (\u -> uncovers u clause) unc
-- | check_uncovers: Given an uncovered set and a full pm definition
-- * this calculates the cases that are not covered by
-- * the pattern matching definition
check_uncovers :: Cases -> Cases -> Cases
check_uncovers ucs [] = ucs
check_uncovers ucs (c:cs) =
let ucs' = uncovering ucs c
in check_uncovers ucs' cs
-- | is_exhaustive: returns whether or not
-- * the given definition is exhaustive
is_exhaustive :: DefPm -> Bool
is_exhaustive = null . ccheck
|
nicodelpiano/stlcnat-exhaustivity-checker
|
src/ECL/ClassicChecker.hs
|
Haskell
|
mit
| 2,949
|
module Routes.TH
( module Routes.TH.Types
-- * Functions
, module Routes.TH.RenderRoute
, module Routes.TH.ParseRoute
, module Routes.TH.RouteAttrs
-- ** Dispatch
, module Routes.TH.Dispatch
) where
import Routes.TH.Types
import Routes.TH.RenderRoute
import Routes.TH.ParseRoute
import Routes.TH.RouteAttrs
import Routes.TH.Dispatch
|
ajnsit/wai-routes
|
src/Routes/TH.hs
|
Haskell
|
mit
| 370
|
{-# LANGUAGE RecordWildCards #-}
module Main where
--import Data.ByteString.Char8 (ByteString)
import HlAdif
import HlLog
import HlOptions
import Options.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Semigroup ((<>))
import System.IO
import Text.Regex.TDFA.ByteString
data Options = Options
{ flexps :: [FlExp]
, getInputHandle :: IO Handle
}
optionsParserInfo :: ParserInfo Options
optionsParserInfo = info (helper <*> (
Options
<$> filterOptions
<*> inputHandleArgument
)) (
fullDesc
<> progDesc "Filter ADIF records according to filter expressions"
)
tagMatches :: FlExp -> Tag -> Bool
tagMatches expr (CTag (tname, mbtval)) =
case expr of
FlEx ftname -> ftname == tname
otherexpr ->
case mbtval of
Nothing -> False
Just (tvalue, _) ->
case otherexpr of
FlGte ftname fvalue -> ftname == tname && tvalue >= fvalue
FlGt ftname fvalue -> ftname == tname && tvalue > fvalue
FlLte ftname fvalue -> ftname == tname && tvalue <= fvalue
FlLt ftname fvalue -> ftname == tname && tvalue < fvalue
FlReg ftname fregex -> ftname == tname &&
case execute fregex tvalue of
Right (Just _) -> True
_ -> False
FlEq ftname fvalue -> ftname == tname && tvalue == fvalue
FlNeq ftname fvalue -> ftname == tname && tvalue /= fvalue
_ -> False
recordMatches :: FlExp -> Record -> Bool
recordMatches expr (CRecord ts) = any (tagMatches expr) ts
filterLog :: [FlExp] -> Log -> Log
filterLog flexps Log{..} = Log logHeaderTxt logHeaderTags $ filter (\rec -> any (flip recordMatches rec) flexps) logRecords
doFilterLog :: Options -> IO ()
doFilterLog opt = do
parseResult <- adifLogParser <$> (getInputHandle opt >>= B.hGetContents)
case parseResult of
Left errorMsg -> putStrLn errorMsg
Right l -> B.putStr $ writeLog $ filterLog (flexps opt) l
return ()
main :: IO ()
main = execParser optionsParserInfo >>= doFilterLog
|
netom/hamloghs
|
app/hl-filter.hs
|
Haskell
|
mit
| 2,313
|
-- Problems/Problem063Spec.hs
module Problems.Problem063Spec (main, spec) where
import Test.Hspec
import Problems.Problem063
main :: IO()
main = hspec spec
spec :: Spec
spec = describe "Problem 63" $
it "Should evaluate to 49" $
p63 `shouldBe` 49
|
Sgoettschkes/learning
|
haskell/ProjectEuler/tests/Problems/Problem063Spec.hs
|
Haskell
|
mit
| 262
|
data Quantum =
Yes
| No
| Both deriving (Eq, Show)
convert :: Quantum -> Bool
convert Yes = False
convert No = False
convert Both = False
convert2 Yes = False
convert2 No = False
convert2 Both = True
convert3 Yes = False
convert3 No = True
convert3 Both = True
convert4 Yes = True
convert4 No = True
convert4 Both = True
convert5 Yes = True
convert5 No = True
convert5 Both = False
convert6 Yes = True
convert6 No = False
convert6 Both = False
convert7 Yes = True
convert7 No = False
convert7 Both = True
convert8 Yes = False
convert8 No = True
convert8 Both = False
data Quad =
One
| Two
| Three
| Four
-- eQuad :: Either Quad Quad
-- 4 + 4 = 8
-- prodQuad :: (Quad, Quad)
-- 4 * 4 = 16
-- funcQuad :: Quad -> Quad
-- 4 ^ 4 = 256
-- prodTBool :: (Bool, Bool, Bool)
-- 2 * 2 * 2
-- gTwo :: Bool -> Bool -> Bool
-- 2 ^ 2 ^ 2 = 16
-- fTwo :: Bool -> Quad -> Quad
-- 4 ^ 4 ^ 2 = 65535
-- (2 ^ 4) ^ 4 = 65535
|
JustinUnger/haskell-book
|
ch11/exp.hs
|
Haskell
|
mit
| 946
|
{- |
- Implementation of the IDA* search algorithm
-}
{-# LANGUAGE ScopedTypeVariables, MultiParamTypeClasses,
FunctionalDependencies, FlexibleInstances, UndecidableInstances #-}
module Rubik.IDA where
import qualified Data.Set as S
-- | Type of outgoing edges, labelled and weighted.
data Succ label length node = Succ {
eLabel :: label,
eCost :: length,
eSucc :: node
}
data Search f a l node = Search {
goal :: node -> Bool,
estm :: node -> a,
edges :: node -> f (Succ l a node)
}
type Result a l = Maybe [l]
data SearchResult a l = Next !a | Found [l] | Stop
instance Ord a => Monoid (SearchResult a l) where
{-# INLINE mempty #-}
mempty = Stop
{-# INLINE mappend #-}
mappend f@(Found _) _ = f
mappend _ f@(Found _) = f
mappend (Next a) (Next b) = Next (min a b)
mappend Stop x = x
mappend x Stop = x
-- | Depth-first search up to depth @bound@,
-- and reduce results from the leaves.
dfSearch
:: (Foldable f, Num a, Ord a)
=> Search f a l node
-> node -> a -> [l] -> a -> SearchResult a l
{-# INLINE dfSearch #-}
dfSearch (Search goal estm edges) n g ls bound
= dfs n g ls bound
where
dfs n g ls bound
| g == bound && g == f && goal n = Found (reverse ls)
| f > bound = Next f
| otherwise
= foldMap searchSucc $ edges n
where
isGoal = goal n
f = g + estm n
searchSucc (Succ eLabel eCost eSucc)
= dfs eSucc (g + eCost) (eLabel : ls) bound
-- | IDA* search
--
-- All paths to goal(s) are returned, grouped by length.
--
-- Only searches as deep as necessary thanks to lazy evaluation.
--
-- TODO: Possible memory leak, solving hard cubes eats a lot of memory.
search
:: forall f a l node . (Foldable f, Num a, Ord a)
=> Search f a l node
-> node {- ^ root -} -> Maybe [l]
{-# INLINE search #-}
search s root = rootSearch (estm s root)
where
-- Search from the root up to a distance @d@
-- for increasing values of @d@.
rootSearch :: a -> Maybe [l]
rootSearch d =
case dfSearch s root 0 [] d of
Stop -> Nothing
Found ls -> Just ls
Next d' -> rootSearch d'
data SelfAvoid node = SelfAvoid (S.Set node) node
selfAvoid (Search goal estm edges) = Search {
goal = goal . node,
estm = estm . node,
edges = edges'
}
where
node (SelfAvoid _ n) = n
edges' (SelfAvoid trace n)
= [ Succ l c (SelfAvoid (S.insert s trace) s)
| Succ l c s <- edges n, S.notMember s trace ]
selfAvoidRoot root = (root, S.singleton root)
|
Lysxia/twentyseven
|
src/Rubik/IDA.hs
|
Haskell
|
mit
| 2,548
|
import Control.Monad.Writer
import Control.Monad ((<=<), (>=>))
deeldoorTwee :: (Integral a, Show a) => a -> Maybe String
deeldoorTwee x = if even x
then Just (show x++" is deelbaar door 2." )
else Just (show x++" is niet deelbaar door 2!" )
half :: (Integral a) => a -> Maybe a
half x = if even x
then Just (x `div` 2)
else Nothing
halveer :: Int -> Maybe Int
halveer x = do
if even x
then Just (x `div` 2)
else Nothing
halveer' :: Int -> Maybe Int
halveer' x | even x = Just (x `div` 2)
| otherwise = Nothing
plus2 :: Int -> Maybe Int
plus2 x = Just (x+2)
plus2enhalveer :: Int -> Maybe Int
plus2enhalveer = plus2 >=> halveer
halveerEnplus2 :: Int -> Maybe Int
halveerEnplus2 = plus2 <=< halveer
draaiom :: String -> Maybe String
draaiom s = Just (reverse s)
main =
getLine >>= \x ->
putStrLn x >>= \_ ->
return ()
main1 =
getLine >>= \x ->
putStrLn (x++"hoi") >>= \_ ->
return ()
main2 =
getLine >>= \x ->
putStrLn x >>= \_ ->
return ()
main4 =
getLine >>= \x -> putStrLn (x++"hoi") >>= \_ -> return ()
theodds = do
x <- [1..10]
if odd x
then [x * 2]
else []
theodds' = [x*2 | x <-[1..10], odd x]
f :: Float -> Float
f = \x -> x^2
addWorld :: String -> IO String
addWorld s = return (s++" world")
|
iambernie/tryhaskell
|
useful.hs
|
Haskell
|
mit
| 1,399
|
module Assembler(assemble) where
import Datatypes
import Opcodes
import Text.Printf
assemble :: [IR] -> [String]
assemble instructions =
map (printf "0x%08x") hex
where hex = map assembleInstruction instructions
assembleInstruction :: IR -> Int
assembleInstruction LoadIR = (hexOpcode Lw)
assembleInstruction StoreIR = (hexOpcode Sw)
assembleInstruction (TwoIR (R reg) (I immediate) masked) =
(hexMask masked) + (hexOpcode Addi) + (hexRt reg) + (immediate `mod` 2 ^ 16)
assembleInstruction (TwoIR (R reg) (C address) masked) =
(hexMask masked) + (hexOpcode Ldc) + (hexRt reg) + (address `mod` 2 ^ 16)
assembleInstruction (ThreeIR operator (R rd) (R rs) (R rt) masked) =
(hexMask masked) + (hexOpcode opcode) + (hexRd rd) + (hexRs rs) + (hexRt rt) + (hexAlufunction opcode)
where opcode = case operator of
BitwiseAnd -> And
BitwiseOr -> Or
BitwiseXor -> Xor
Plus -> Add
Minus -> Sub
Multiply -> Mul
LessThan -> Slt
EqualTo -> Seq
assembleInstruction (ThreeIR op rd (I rs) (R rt) masked)
| op == Plus = assembleInstruction (ThreeIR op rd (R rt) (I rs) masked)
assembleInstruction (ThreeIR operator (R rd) (R rs) (I sh) masked) =
(hexMask masked) + (hexOpcode opcode) + (hexRd rd) + (hexRs rs) + sh
where opcode = case operator of
Plus -> Addi
ShiftLeft -> Sll
ShiftRight -> Srl
ShiftRightArithmetic -> Sra
|
aleksanb/hdc
|
src/Assembler.hs
|
Haskell
|
mit
| 1,524
|
module AlecSequences.A280172Spec (main, spec) where
import Test.Hspec
import AlecSequences.A280172 (a280172)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A280172" $
it "correctly computes the first 20 elements" $
take 20 (map a280172 [1..]) `shouldBe` expectedValue where
expectedValue = [1,2,2,3,1,3,4,4,4,4,5,3,1,3,5,6,6,2,2,6]
|
peterokagey/haskellOEIS
|
test/AlecSequences/A280172Spec.hs
|
Haskell
|
apache-2.0
| 361
|
{- |
Module : Data.Time.Zones.Internal
Copyright : (C) 2014 Mihaly Barasz
License : Apache-2.0, see LICENSE
Maintainer : Mihaly Barasz <klao@nilcons.com>
Stability : experimental
-}
{-# LANGUAGE CPP #-}
#ifdef TZ_TH
{-# LANGUAGE TemplateHaskell #-}
#endif
module Data.Time.Zones.Internal (
-- * Time conversion to/from @Int64@
utcTimeToInt64,
utcTimeToInt64Pair,
localTimeToInt64Pair,
int64PairToUTCTime,
int64PairToLocalTime,
-- * Low-level \"coercions\"
picoToInteger,
integerToPico,
diffTimeToPico,
picoToDiffTime,
diffTimeToInteger,
integerToDiffTime,
) where
import Data.Fixed
import Data.Int
import Data.Time
#ifdef TZ_TH
import Data.Time.Zones.Internal.CoerceTH
#else
import Unsafe.Coerce
#endif
utcTimeToInt64Pair :: UTCTime -> (Int64, Int64)
utcTimeToInt64Pair (UTCTime (ModifiedJulianDay d) t)
= (86400 * (fromIntegral d - unixEpochDay) + s, ps)
where
(s, ps) = fromIntegral (diffTimeToInteger t) `divMod` 1000000000000
unixEpochDay = 40587
{-# INLINE utcTimeToInt64Pair #-}
int64PairToLocalTime :: Int64 -> Int64 -> LocalTime
int64PairToLocalTime t ps = LocalTime (ModifiedJulianDay day) (TimeOfDay h m s)
where
(day64, tid64) = t `divMod` 86400
day = fromIntegral $ day64 + 40587
(h, ms) = fromIntegral tid64 `quotRem` 3600
(m, s0) = ms `quotRem` 60
s = integerToPico $ fromIntegral $ ps + 1000000000000 * fromIntegral s0
{-# INLINE int64PairToLocalTime #-}
localTimeToInt64Pair :: LocalTime -> (Int64, Int64)
localTimeToInt64Pair (LocalTime (ModifiedJulianDay day) (TimeOfDay h m s))
= (86400 * (fromIntegral day - unixEpochDay) + tid, ps)
where
(s64, ps) = fromIntegral (picoToInteger s) `divMod` 1000000000000
tid = s64 + fromIntegral (h * 3600 + m * 60)
unixEpochDay = 40587
{-# INLINE localTimeToInt64Pair #-}
int64PairToUTCTime :: Int64 -> Int64 -> UTCTime
int64PairToUTCTime t ps = UTCTime (ModifiedJulianDay day) tid
where
(day64, tid64) = t `divMod` 86400
day = fromIntegral $ day64 + 40587
tid = integerToDiffTime $ fromIntegral $ ps + tid64 * 1000000000000
{-# INLINE int64PairToUTCTime #-}
utcTimeToInt64 :: UTCTime -> Int64
utcTimeToInt64 (UTCTime (ModifiedJulianDay d) t)
= 86400 * (fromIntegral d - unixEpochDay)
+ fromIntegral (diffTimeToInteger t) `div` 1000000000000
where
unixEpochDay = 40587
{-# INLINE utcTimeToInt64 #-}
--------------------------------------------------------------------------------
-- Low-level zero-overhead conversions.
-- Basically we could have used 'coerce' if the constructors were exported.
-- TODO(klao): Is it better to inline them saturated or unsaturated?
#ifdef TZ_TH
picoToInteger :: Pico -> Integer
picoToInteger p = $(destructNewType ''Fixed) p
{-# INLINE picoToInteger #-}
integerToPico :: Integer -> Pico
integerToPico i = $(constructNewType ''Fixed) i
{-# INLINE integerToPico #-}
diffTimeToPico :: DiffTime -> Pico
diffTimeToPico dt = $(destructNewType ''DiffTime) dt
{-# INLINE diffTimeToPico #-}
picoToDiffTime :: Pico -> DiffTime
picoToDiffTime p = $(constructNewType ''DiffTime) p
{-# INLINE picoToDiffTime #-}
diffTimeToInteger :: DiffTime -> Integer
diffTimeToInteger dt = picoToInteger (diffTimeToPico dt)
{-# INLINE diffTimeToInteger #-}
integerToDiffTime :: Integer -> DiffTime
integerToDiffTime i = picoToDiffTime (integerToPico i)
{-# INLINE integerToDiffTime #-}
#else
picoToInteger :: Pico -> Integer
picoToInteger = unsafeCoerce
{-# INLINE picoToInteger #-}
integerToPico :: Integer -> Pico
integerToPico = unsafeCoerce
{-# INLINE integerToPico #-}
diffTimeToPico :: DiffTime -> Pico
diffTimeToPico = unsafeCoerce
{-# INLINE diffTimeToPico #-}
picoToDiffTime :: Pico -> DiffTime
picoToDiffTime = unsafeCoerce
{-# INLINE picoToDiffTime #-}
diffTimeToInteger :: DiffTime -> Integer
diffTimeToInteger = unsafeCoerce
{-# INLINE diffTimeToInteger #-}
integerToDiffTime :: Integer -> DiffTime
integerToDiffTime = unsafeCoerce
{-# INLINE integerToDiffTime #-}
#endif
|
nilcons/haskell-tz
|
Data/Time/Zones/Internal.hs
|
Haskell
|
apache-2.0
| 3,989
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
module Spark.Core.Internal.DatasetStructures where
import Data.Vector(Vector)
import qualified Data.Vector as V
import qualified Data.Text as T
import Spark.Core.StructuresInternal
import Spark.Core.Try
import Spark.Core.Row
import Spark.Core.Internal.OpStructures
import Spark.Core.Internal.TypesStructures
{-| (internal) The main data structure that represents a data node in the
computation graph.
This data structure forms the backbone of computation graphs expressed
with spark operations.
loc is a typed locality tag.
a is the type of the data, as seen by the Haskell compiler. If erased, it
will be a Cell type.
-}
-- TODO: separate the topology info from the node info. It will help when
-- building the graphs.
data ComputeNode loc a = ComputeNode {
-- | The id of the node.
--
-- Non strict because it may be expensive.
_cnNodeId :: NodeId,
-- The following fields are used to build a unique ID to
-- a compute node:
-- | The operation associated to this node.
_cnOp :: !NodeOp,
-- | The type of the node
_cnType :: !DataType,
-- | The direct parents of the node. The order of the parents is important
-- for the semantics of the operation.
_cnParents :: !(Vector UntypedNode),
-- | A set of extra dependencies that can be added to force an order between
-- the nodes.
--
-- The order is not important, they are sorted by ID.
--
-- TODO(kps) add this one to the id
_cnLogicalDeps :: !(Vector UntypedNode),
-- | The locality of this node.
--
-- TODO(kps) add this one to the id
_cnLocality :: !Locality,
-- Attributes that are not included in the id
-- These attributes are mostly for the user to relate to the nodes.
-- They are not necessary for the computation.
--
-- | The name
_cnName :: !(Maybe NodeName),
-- | A set of nodes considered as the logical input for this node.
-- This has no influence on the calculation of the id and is used
-- for organization purposes only.
_cnLogicalParents :: !(Maybe (Vector UntypedNode)),
-- | The path of this oned in a computation flow.
--
-- This path includes the node name.
-- Not strict because it may be expensive to compute.
-- By default it only contains the name of the node (i.e. the node is
-- attached to the root)
_cnPath :: NodePath
} deriving (Eq)
{-| Converts a compute node to an operator node.
-}
nodeOpNode :: ComputeNode loc a -> OperatorNode
nodeOpNode cn = OperatorNode {
onId = _cnNodeId cn,
onPath = _cnPath cn,
onNodeInfo = CoreNodeInfo {
cniShape = NodeShape {
nsType = _cnType cn,
nsLocality = _cnLocality cn
},
cniOp = _cnOp cn
}
}
nodeContext :: ComputeNode loc a -> NodeContext
nodeContext cn = NodeContext {
ncParents = nodeOpNode <$> V.toList (_cnParents cn),
ncLogicalDeps = nodeOpNode <$> V.toList (_cnLogicalDeps cn)
}
-- (internal) Phantom type tags for the locality
data TypedLocality loc = TypedLocality { unTypedLocality :: !Locality } deriving (Eq, Show)
data LocLocal
data LocDistributed
data LocUnknown
{-| (internal/developer)
The core data structure that represents an operator.
This contains all the information that is required in
the compute graph (except topological info), which is
expected to be stored in the edges.
These nodes are meant to be used after path resolution.
-}
data OperatorNode = OperatorNode {
{-| The ID of the node.
Lazy because it may be expensive to compute.
-- TODO: it should not be here?
-}
onId :: NodeId,
{-| The fully resolved path of the node.
Lazy because it may depend on the ID.
-}
onPath :: NodePath,
{-| The core node information. -}
onNodeInfo :: !CoreNodeInfo
} deriving (Eq)
-- Some helper functions:
onShape :: OperatorNode -> NodeShape
onShape = cniShape . onNodeInfo
onOp :: OperatorNode -> NodeOp
onOp = cniOp . onNodeInfo
onType :: OperatorNode -> DataType
onType = nsType . cniShape . onNodeInfo
onLocality :: OperatorNode -> Locality
onLocality = nsLocality . cniShape . onNodeInfo
{-| A node and some information about the parents of this node.
This information is enough to calculate most information relative
to a node.
This is the local context of the compute DAG.
-}
data NodeContext = NodeContext {
ncParents :: ![OperatorNode],
ncLogicalDeps :: ![OperatorNode]
}
-- (developer) The type for which we drop all the information expressed in
-- types.
--
-- This is useful to express parent dependencies (pending a more type-safe
-- interface)
type UntypedNode = ComputeNode LocUnknown Cell
-- (internal) A dataset for which we have dropped type information.
-- Used internally by columns.
type UntypedDataset = Dataset Cell
{-| (internal) An observable which has no associated type information. -}
type UntypedLocalData = LocalData Cell
{-| A typed collection of distributed data.
Most operations on datasets are type-checked by the Haskell
compiler: the type tag associated to this dataset is guaranteed
to be convertible to a proper Haskell type. In particular, building
a Dataset of dynamic cells is guaranteed to never happen.
If you want to do untyped operations and gain
some flexibility, consider using UDataFrames instead.
Computations with Datasets and observables are generally checked for
correctness using the type system of Haskell.
-}
type Dataset a = ComputeNode LocDistributed a
{-|
A unit of data that can be accessed by the user.
This is a typed unit of data. The type is guaranteed to be a proper
type accessible by the Haskell compiler (instead of simply a Cell
type, which represents types only accessible at runtime).
TODO(kps) rename to Observable
-}
type LocalData a = ComputeNode LocLocal a
type Observable a = LocalData a
{-|
The dataframe type. Any dataset can be converted to a dataframe.
For the Spark users: this is different than the definition of the
dataframe in Spark, which is a dataset of rows. Because the support
for single columns is more akward in the case of rows, it is more
natural to generalize datasets to contain cells.
When communicating with Spark, though, single cells are wrapped
into rows with single field, as Spark does.
-}
type DataFrame = Try UntypedDataset
{-| Observable, whose type can only be infered at runtime and
that can fail to be computed at runtime.
Any observable can be converted to an untyped
observable.
Untyped observables are more flexible and can be combined in
arbitrary manner, but they will fail during the validation of
the Spark computation graph.
TODO(kps) rename to DynObservable
-}
type LocalFrame = Observable'
newtype Observable' = Observable' { unObservable' :: Try UntypedLocalData }
type UntypedNode' = Try UntypedNode
{-| The different paths of edges in the compute DAG of nodes, at the
start of computations.
- scope edges specify the scope of a node for naming. They are not included in
the id.
-}
data NodeEdge = ScopeEdge | DataStructureEdge StructureEdge deriving (Show, Eq)
{-| The edges in a compute DAG, after name resolution (which is where most of
the checks and computations are being done)
- parent edges are the direct parents of a node, the only ones required for
defining computations. They are included in the id.
- logical edges define logical dependencies between nodes to force a specific
ordering of the nodes. They are included in the id.
-}
data StructureEdge = ParentEdge | LogicalEdge deriving (Show, Eq)
class CheckedLocalityCast loc where
_validLocalityValues :: [TypedLocality loc]
-- Class to retrieve the locality associated to a type.
-- Is it better to use type classes?
class (CheckedLocalityCast loc) => IsLocality loc where
_getTypedLocality :: TypedLocality loc
instance CheckedLocalityCast LocLocal where
_validLocalityValues = [TypedLocality Local]
instance CheckedLocalityCast LocDistributed where
_validLocalityValues = [TypedLocality Distributed]
instance Show OperatorNode where
show (OperatorNode _ np _) = "OperatorNode[" ++ T.unpack (prettyNodePath np) ++ "]"
-- LocLocal is a locality associated to Local
instance IsLocality LocLocal where
_getTypedLocality = TypedLocality Local
-- LocDistributed is a locality associated to Distributed
instance IsLocality LocDistributed where
_getTypedLocality = TypedLocality Distributed
instance CheckedLocalityCast LocUnknown where
_validLocalityValues = [TypedLocality Distributed, TypedLocality Local]
|
tjhunter/karps
|
haskell/src/Spark/Core/Internal/DatasetStructures.hs
|
Haskell
|
apache-2.0
| 8,561
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE KindSignatures #-}
{-# OPTIONS_HADDOCK hide #-}
-- |
-- Functions which execute DNA routines on remote nodes. Below is
-- general algorithms:
--
-- 1. Obtain auxiliary parameters ('ActorParam')
--
-- 2. Send receive address back to parent ('RecvAddr')
--
-- 3. Receive initial parameters and execute program
--
-- 4. Send result to latest destination received
--
-- One particular problem is related to the need of respawning of
-- processes. We must ensure that actor sends its result to real actor
-- instead of just terminated actor
module DNA.Interpreter.Run (
-- * Run actors
runActor
-- , runActorManyRanks
, runCollectActor
, runTreeActor
-- * Helpers
, doGatherDna
, splitEvenly
-- * CH
, runActor__static
-- , runActorManyRanks__static
, runCollectActor__static
, runTreeActor__static
, __remoteTable
) where
import Control.Monad
import Control.Distributed.Process
import Control.Distributed.Process.Serializable
import Control.Distributed.Process.Closure
import Data.Typeable (Typeable)
import Data.List (findIndex)
import qualified Data.Foldable as T
import DNA.CH
import DNA.Types
import DNA.DSL
import DNA.Interpreter.Types
----------------------------------------------------------------
-- Functions for starting actors
----------------------------------------------------------------
-- | Start execution of standard actor
runActor :: Actor a b -> Process ()
runActor (Actor action) = do
-- Obtain parameters
p <- expect
-- Create channels for communication
(chSendParam,chRecvParam) <- newChan
-- Send data destination back
sendChan (actorSendBack p)
$ RcvSimple (makeRecv chSendParam)
-- Now we can start execution and send back data
a <- receiveChan chRecvParam
!b <- runDnaParam p (action a)
sendResult p b
{-
-- | Run actor for group of processes which allow more than 1 task per
-- actor.
runActorManyRanks :: Actor a b -> Process ()
runActorManyRanks (Actor action) = do
-- Obtain parameters
p <- expect
-- Create channels for communication
(chSendParam,chRecvParam) <- newChan
(chSendDst, chRecvDst ) <- newChan
(chSendRnk, chRecvRnk ) <- newChan
-- Send shell process back
sendChan (actorSendBack p)
(RcvSimple (wrapMessage chSendParam))
-- let shell = ( RecvVal chSendParam
-- , SendVal chSendDst )
-- send (actorParent p) (chSendRnk,shell)
-- -- Start actor execution
-- a <- receiveChan chRecvParam
-- let loop dst = do
-- send (actorParent p) (me,chSendRnk)
-- mrnk <- receiveChan chRecvRnk
-- case mrnk of
-- Nothing -> return ()
-- Just rnk -> do
-- !b <- runDnaParam p{actorRank = rnk} (action a)
-- dst' <- drainChannel0 chRecvDst dst
-- sendToDest dst' b
-- send (actorParent p) (me,DoneTask)
-- loop dst'
-- loop =<< drainChannel chRecvDst
-}
-- | Start execution of collector actor
runCollectActor :: CollectActor a b -> Process ()
runCollectActor (CollectActor step start fini) = do
-- Obtain parameters
p <- expect
-- Create channels for communication
(chSendParam,chRecvParam) <- newChan
(chSendN, chRecvN ) <- newChan
-- Send shell process description back
sendChan (actorSendBack p)
$ RcvReduce (makeRecv chSendParam) chSendN
-- Start execution of an actor
!b <- runDnaParam p $ do
case [pCrash | CrashProbably pCrash <- actorDebugFlags p] of
pCrash : _ -> crashMaybe pCrash
_ -> return ()
s0 <- start
s <- gatherM (Group chRecvParam chRecvN) step s0
fini s
sendResult p b
-- | Start execution of collector actor
runTreeActor :: CollectActor a a -> Process ()
runTreeActor (CollectActor step start fini) = do
-- Obtain parameters
p <- expect
-- Create channels for communication
(chSendParam,chRecvParam) <- newChan
(chSendN, chRecvN ) <- newChan
-- Send shell process description back
sendChan (actorSendBack p)
$ RcvReduce (makeRecv chSendParam) chSendN
-- Start execution of an actor
!a <- runDnaParam p $ do
s0 <- start
s <- gatherM (Group chRecvParam chRecvN) step s0
fini s
sendResult p a
----------------------------------------------------------------
-- Helpers
----------------------------------------------------------------
-- Send result to the destination we
sendResult :: (Serializable a) => ActorParam -> a -> Process ()
sendResult p !a =
sendLoop =<< drainExpect
where
sendLoop dst = do
-- Send data to destination
case dst of
RcvSimple msg -> trySend msg
RcvReduce m _ -> trySend m
RcvTree msgs -> do
let nReducers = length msgs
GroupSize nResults = actorGroupSize p
Rank rnk = actorRank p
case msgs !! findIndexInSplittedList nResults nReducers rnk of
RcvReduce ch _ -> trySend ch
RcvFailed -> return ()
RcvCompleted -> return ()
_ -> doPanic "sendResult: bad tree actor!"
RcvGrp msgs -> forM_ msgs $ \case
RcvSimple m -> trySend m
RcvFailed -> return ()
RcvCompleted -> return ()
_ -> doPanic "sendResult: bad group actor!"
RcvFailed -> return ()
RcvCompleted -> return ()
-- Send confirmation to parent and wait for
T.forM_ (actorParent p) $ \pid -> do
me <- getSelfPid
send pid (SentTo me dst)
receiveWait
[ match $ \(Terminate msg) -> error msg
, match $ \newDest -> sendLoop newDest
, match $ \AckSend -> return ()
]
-- Loop over data
trySend (Recv _ msg) = do
mch <- unwrapMessage msg
case mch of
Just ch -> unsafeSendChan ch a
Nothing -> doPanic "Type error in channel!"
findIndexInSplittedList :: Int -> Int -> Int -> Int
findIndexInSplittedList nElems n rnk =
case findIndex (\(a,b) -> rnk >= a && rnk < b) bins of
Just i -> i
_ -> error "Impossible split!"
where
bins = splitEvenly nElems n
splitEvenly :: Int -> Int -> [(Int,Int)]
splitEvenly nElems n
= offs `zip` tail offs
where
(bin,rest) = nElems `divMod` n
sizes = zipWith (+) (replicate n bin) (replicate rest 1 ++ repeat 0)
offs = scanl (+) 0 sizes
doGatherDna
:: Serializable a
=> [MatchS]
-> Group a
-> (b -> a -> DnaMonad b)
-> b
-> DnaMonad b
doGatherDna ms (Group chA chN) f x0 = do
let loop n tot !b
| n >= tot && tot >= 0 = return b
loop n tot !b = do
r <- handleRecieve ms
[ Right `fmap` matchChan' chA
, Left `fmap` matchChan' chN
]
case r of
Right a -> loop (n + 1) tot =<< f b a
Left k -> loop n k b
loop 0 (-1) x0
----------------------------------------------------------------
-- CH's TH
----------------------------------------------------------------
remotable [ 'runActor
-- , 'runActorManyRanks
, 'runCollectActor
, 'runTreeActor
]
|
SKA-ScienceDataProcessor/RC
|
MS6/dna/core/DNA/Interpreter/Run.hs
|
Haskell
|
apache-2.0
| 8,035
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
#if __GLASGOW_HASKELL__ >= 786
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
#endif
module Data.Complex.Polar (
#if __GLASGOW_HASKELL__ >= 800
Polar((:<)),
#elif __GLASGOW_HASKELL >= 786
Polar,
pattern (:<),
#else
Polar,
#endif
fromPolar,
fromComplex,
realPart,
imagPart,
conjugate,
mkPolar,
cis,
polar,
magnitude,
phase
) where
import Data.Complex (Complex(..))
import qualified Data.Complex as C
import Data.Typeable
#ifdef __GLASGOW_HASKELL__
import Data.Data (Data)
#endif
#ifdef __HUGS__
import Hugs.Prelude(Num(fromInt), Fractional(fromDouble))
#endif
import Text.Read (parens)
import Text.ParserCombinators.ReadPrec (prec, step)
import Text.Read.Lex (Lexeme (Ident))
infix 6 :<<
-- -----------------------------------------------------------------------------
-- The Polar type
-- | Complex numbers are an algebraic type.
--
-- For a complex number @z@, @'abs' z@ is a number with the magnitude of @z@,
-- but oriented in the positive real direction, whereas @'signum' z@
-- has the phase of @z@, but unit magnitude.
data (RealFloat a) => Polar a = !a :<< !a -- ^ forms a complex number from its magnitude
-- and its phase in radians.
#if __GLASGOW_HASKELL__
deriving (Eq, Data, Typeable)
#else
deriving Eq
#endif
#if __GLASGOW_HASKELL__ >= 786
infix 6 :<
-- | Smart constructor that canonicalizes the magnitude and phase.
pattern r :< theta <-
( \(r :<< theta) -> Just (r, theta) ->
Just (r, theta)
)
where
r :< theta = mkPolar r theta
#endif
instance (RealFloat a, Show a) => Show (Polar a) where
{-# SPECIALISE instance Show (Polar Float) #-}
{-# SPECIALISE instance Show (Polar Double) #-}
showsPrec d (r :<< theta) =
showParen (d >= 11) (showString "mkPolar "
. showsPrec 11 r
. showString " "
. showsPrec 11 theta)
instance (RealFloat a, Read a) => Read (Polar a) where
{-# SPECIALISE instance Read (Polar Float) #-}
{-# SPECIALISE instance Read (Polar Double) #-}
readsPrec d = readParen (d > 10)
(\s -> do ("mkPolar", s2) <- lex s
(r, s3) <- readsPrec 11 s2
(theta, s4) <- readsPrec 11 s3
return (mkPolar r theta, s4))
-- | Wrap phase back in interval @(-'pi', 'pi']@.
wrap :: (RealFloat a) => a -> a
{-# SPECIALISE wrap :: Float -> Float #-}
{-# SPECIALISE wrap :: Double -> Double #-}
wrap phi | phi <= (-pi) = wrap (phi+2*pi)
wrap phi | phi > pi = wrap (phi-2*pi)
wrap phi = phi
-- | Convert to rectangular form.
fromPolar :: (RealFloat a) => Polar a -> Complex a
{-# INLINE fromPolar #-}
fromPolar p = realPart p :+ imagPart p
-- | Convert to polar form.
fromComplex :: (RealFloat a) => Complex a -> Polar a
{-# INLINE fromComplex #-}
fromComplex = uncurry mkPolar_ . C.polar
-- | Extracts the real part of a complex number.
realPart :: (RealFloat a) => Polar a -> a
realPart (r :<< theta) = r * cos theta
-- | Extracts the imaginary part of a complex number.
imagPart :: (RealFloat a) => Polar a -> a
imagPart (r :<< theta) = r * sin theta
-- | The conjugate of a complex number.
conjugate :: (RealFloat a) => Polar a -> Polar a
{-# SPECIALISE conjugate :: Polar Float -> Polar Float #-}
{-# SPECIALISE conjugate :: Polar Double -> Polar Double #-}
conjugate (r :<< theta) = mkPolar r (negate theta)
-- | Form a complex number from polar components of magnitude and phase.
-- The magnitude and phase are expected to be in canonical form.
mkPolar_ :: RealFloat a => a -> a -> Polar a
{-# SPECIALISE mkPolar_ :: Float -> Float -> Polar Float #-}
{-# SPECIALISE mkPolar_ :: Double -> Double -> Polar Double #-}
mkPolar_ r theta = r :<< theta
-- | Form a complex number from polar components of magnitude and phase.
mkPolar :: RealFloat a => a -> a -> Polar a
{-# SPECIALISE mkPolar :: Float -> Float -> Polar Float #-}
{-# SPECIALISE mkPolar :: Double -> Double -> Polar Double #-}
mkPolar r theta | r == 0 = 0 :<< 0
mkPolar r theta | r < 0 = mkPolar (- r) (theta + pi)
mkPolar r theta = mkPolar_ r (wrap theta)
-- | @'cis' t@ is a complex value with magnitude @1@
-- and phase @t@ (modulo @2*'pi'@).
cis :: (RealFloat a) => a -> Polar a
{-# SPECIALISE cis :: Float -> Polar Float #-}
{-# SPECIALISE cis :: Double -> Polar Double #-}
cis theta = mkPolar 1 theta
-- | The function 'polar' takes a complex number and
-- returns a (magnitude, phase) pair in canonical form:
-- the magnitude is nonnegative, and the phase in the range @(-'pi', 'pi']@;
-- if the magnitude is zero, then so is the phase.
polar :: (RealFloat a) => Polar a -> (a,a)
{-# SPECIALISE polar :: Polar Double -> (Double,Double) #-}
{-# SPECIALISE polar :: Polar Float -> (Float,Float) #-}
polar (r :<< theta) = (r,theta)
-- | The nonnegative magnitude of a complex number.
magnitude :: (RealFloat a) => Polar a -> a
{-# SPECIALISE magnitude :: Polar Float -> Float #-}
{-# SPECIALISE magnitude :: Polar Double -> Double #-}
magnitude (r :<< _) = r
-- | The phase of a complex number, in the range @(-'pi', 'pi']@.
-- If the magnitude is zero, then so is the phase.
phase :: (RealFloat a) => Polar a -> a
{-# SPECIALISE phase :: Polar Float -> Float #-}
{-# SPECIALISE phase :: Polar Double -> Double #-}
phase (_ :<< theta) = theta
instance (RealFloat a) => Num (Polar a) where
{-# SPECIALISE instance Num (Polar Float) #-}
{-# SPECIALISE instance Num (Polar Double) #-}
z + z' = fromComplex (fromPolar z + fromPolar z')
z - z' = fromComplex (fromPolar z - fromPolar z')
z * z' = mkPolar (magnitude z * magnitude z') (phase z + phase z')
negate z = mkPolar (negate (magnitude z)) (phase z)
abs z = mkPolar_ (magnitude z) 0
signum (0 :<< _) = 0
signum z = mkPolar_ 1 (phase z)
fromInteger = flip mkPolar 0 . fromInteger
instance (RealFloat a) => Fractional (Polar a) where
{-# SPECIALISE instance Fractional (Polar Float) #-}
{-# SPECIALISE instance Fractional (Polar Double) #-}
z / z' = mkPolar (magnitude z / magnitude z') (phase z - phase z')
fromRational r = mkPolar (fromRational r) 0
instance (RealFloat a) => Floating (Polar a) where
{-# SPECIALISE instance Floating (Polar Float) #-}
{-# SPECIALISE instance Floating (Polar Double) #-}
pi = mkPolar_ pi 0
exp (r :<< theta) = mkPolar (exp (r * cos theta)) (r * sin theta)
log (r :<< theta) = fromComplex (log r :+ theta)
-- sqrt (0 :<< _) = 0
-- sqrt z@(r :<< theta) = u :+ (if y < 0 then -v else v)
-- where (u,v) = if x < 0 then (v',u') else (u',v')
-- v' = abs y / (u'*2)
-- u' = sqrt ((magnitude z + abs x) / 2)
sqrt = fromComplex.sqrt.fromPolar
-- sin (x:+y) = sin x * cosh y :+ cos x * sinh y
sin = fromComplex.sin.fromPolar
-- cos (x:+y) = cos x * cosh y :+ (- sin x * sinh y)
cos = fromComplex.cos.fromPolar
-- tan (x:+y) = (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy))
-- where sinx = sin x
-- cosx = cos x
-- sinhy = sinh y
-- coshy = cosh y
tan = fromComplex.tan.fromPolar
-- sinh (x:+y) = cos y * sinh x :+ sin y * cosh x
sinh = fromComplex.sinh.fromPolar
-- cosh (x:+y) = cos y * cosh x :+ sin y * sinh x
cosh = fromComplex.cosh.fromPolar
-- tanh (x:+y) = (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx)
-- where siny = sin y
-- cosy = cos y
-- sinhx = sinh x
-- coshx = cosh x
tanh = fromComplex.tanh.fromPolar
-- asin z@(x:+y) = y':+(-x')
-- where (x':+y') = log (((-y):+x) + sqrt (1 - z*z))
asin = fromComplex.asin.fromPolar
-- acos z = y'':+(-x'')
-- where (x'':+y'') = log (z + ((-y'):+x'))
-- (x':+y') = sqrt (1 - z*z)
acos = fromComplex.acos.fromPolar
-- atan z@(x:+y) = y':+(-x')
-- where (x':+y') = log (((1-y):+x) / sqrt (1+z*z))
atan = fromComplex.atan.fromPolar
asinh z = log (z + sqrt (1+z*z))
acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1)))
atanh z = log ((1+z) / sqrt (1-z*z))
|
kaoskorobase/polar
|
Data/Complex/Polar.hs
|
Haskell
|
bsd-2-clause
| 8,785
|
{-# LANGUAGE TemplateHaskell, QuasiQuotes, DeriveDataTypeable,
MultiParamTypeClasses, TypeFamilies, FlexibleContexts,
FlexibleInstances, OverloadedStrings #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Application.WebLogger.Server.Yesod where
import Control.Applicative
import Data.Acid
import Data.Aeson as A
import Data.Attoparsec as P
import qualified Data.ByteString as S
import Data.Conduit
import qualified Data.Conduit.List as CL
import Data.Foldable
import Network.Wai
import Yesod hiding (update)
--
import Application.WebLogger.Type
import Application.WebLogger.Server.Type
--
import Prelude hiding (concat,concatMap)
-- |
mkYesod "WebLoggerServer" [parseRoutes|
/ HomeR GET
/list ListR GET
/upload UploadR POST
|]
-- |
instance Yesod WebLoggerServer where
maximumContentLength _ _ = 100000000
-- |
getHomeR :: Handler RepHtml
getHomeR = do
liftIO $ putStrLn "getHomeR called"
defaultLayout [whamlet|
!!!
<html>
<head>
<title> weblogger
<body>
<h1> Weblogger
|]
-- |
defhlet :: GWidget s m ()
defhlet = [whamlet| <h1> HTML output not supported |]
-- |
showstr :: String -> GWidget s m ()
showstr str = [whamlet|
<h1> output
<p> #{str}
|]
-- |
formatLog :: WebLoggerRepo -> GWidget s m ()
formatLog xs = [whamlet|
<h1> output
<table>
<tr>
<td> log
$forall x <- xs
<tr>
<td> #{weblog_content x}
|]
-- concatMap (\x -> weblog_content x ++ "\n\n") (toList xs)
-- |
getListR :: Handler RepHtmlJson
getListR = do
-- setHeader "Access-Control-Allow-Origin" "*"
-- setHeader "Access-Control-Allow-Headers" "X-Requested-With, Content-Type"
liftIO $ putStrLn "getListR called"
acid <- server_acid <$> getYesod
r <- liftIO $ query acid QueryAllLog
-- liftIO $ putStrLn $ show r
defaultLayoutJson (formatLog r) (A.toJSON (Just r))
-- |
postUploadR :: Handler RepHtmlJson
postUploadR = do
liftIO $ putStrLn "postQueueR called"
acid <- server_acid <$> getYesod
wr <- reqWaiRequest <$> getRequest
bs' <- liftIO $ runResourceT (requestBody wr $$ CL.consume)
let bs = S.concat bs'
let parsed = parse json bs
case parsed of
Done _ parsedjson -> do
case (A.fromJSON parsedjson :: A.Result WebLoggerInfo) of
Success minfo -> do
r <- liftIO $ update acid (AddLog minfo)
liftIO $ print (Just r)
liftIO $ print (A.toJSON (Just r))
defaultLayoutJson defhlet (A.toJSON (Just r))
Error err -> do
liftIO $ putStrLn err
defaultLayoutJson defhlet (A.toJSON (Nothing :: Maybe WebLoggerInfo))
Fail _ ctxts err -> do
liftIO $ putStrLn (concat ctxts++err)
defaultLayoutJson defhlet (A.toJSON (Nothing :: Maybe WebLoggerInfo))
Partial _ -> do
liftIO $ putStrLn "partial"
defaultLayoutJson defhlet (A.toJSON (Nothing :: Maybe WebLoggerInfo))
|
wavewave/weblogger-server
|
lib/Application/WebLogger/Server/Yesod.hs
|
Haskell
|
bsd-2-clause
| 3,032
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE UnboxedTuples #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Codec.Compression.Zlib.OutputWindow (
OutputWindow,
emptyWindow,
emitExcess,
finalizeWindow,
addByte,
addChunk,
addOldChunk,
) where
import Control.Monad (foldM)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Short as SBS
import Data.ByteString.Short.Internal (ShortByteString (SBS))
import qualified Data.Primitive as Prim
import qualified Data.Vector.Primitive as V
import qualified Data.Vector.Primitive.Mutable as MV
import GHC.ST (ST (..))
import GHC.Word (Word8 (..))
windowSize :: Int
windowSize = 128 * 1024
data OutputWindow s = OutputWindow
{ owWindow :: {-# UNPACK #-} !(MV.MVector s Word8)
, owNext :: {-# UNPACK #-} !Int
}
emptyWindow :: ST s (OutputWindow s)
emptyWindow = do
window <- MV.new windowSize
return (OutputWindow window 0)
excessChunkSize :: Int
excessChunkSize = 32768
emitExcess :: OutputWindow s -> ST s (Maybe (S.ByteString, OutputWindow s))
emitExcess OutputWindow{owWindow = window, owNext = initialOffset}
| initialOffset < excessChunkSize * 2 = return Nothing
| otherwise = do
toEmit <- V.freeze $ MV.slice 0 excessChunkSize window
let excessLength = initialOffset - excessChunkSize
-- Need move as these can overlap!
MV.move (MV.slice 0 excessLength window) (MV.slice excessChunkSize excessLength window)
let ow' = OutputWindow window excessLength
return (Just (SBS.fromShort $ toByteString toEmit, ow'))
finalizeWindow :: OutputWindow s -> ST s S.ByteString
finalizeWindow ow = do
-- safe as we're doing it at the end
res <- V.unsafeFreeze (MV.slice 0 (owNext ow) (owWindow ow))
pure $ SBS.fromShort $ toByteString res
-- -----------------------------------------------------------------------------
addByte :: OutputWindow s -> Word8 -> ST s (OutputWindow s)
addByte !ow !b = do
let offset = owNext ow
MV.write (owWindow ow) offset b
return ow{owNext = offset + 1}
addChunk :: OutputWindow s -> L.ByteString -> ST s (OutputWindow s)
addChunk !ow !bs = foldM copyChunk ow (L.toChunks bs)
copyChunk :: OutputWindow s -> S.ByteString -> ST s (OutputWindow s)
copyChunk ow sbstr = do
-- safe as we're never going to look at this again
ba <- V.unsafeThaw $ fromByteString $ SBS.toShort sbstr
let offset = owNext ow
len = MV.length ba
MV.copy (MV.slice offset len (owWindow ow)) ba
return ow{owNext = offset + len}
addOldChunk :: OutputWindow s -> Int -> Int -> ST s (OutputWindow s, S.ByteString)
addOldChunk (OutputWindow window next) dist len = do
-- zlib can ask us to copy an "old" chunk that extends past our current offset.
-- The intention is that we then start copying the "new" data we just copied into
-- place. 'copyChunked' handles this for us.
copyChunked (MV.slice next len window) (MV.slice (next - dist) len window) dist
result <- V.freeze $ MV.slice next len window
return (OutputWindow window (next + len), SBS.fromShort $ toByteString result)
{- | A copy function that copies the buffers sequentially in chunks no larger than
the stated size. This allows us to handle the insane zlib behaviour.
-}
copyChunked :: MV.MVector s Word8 -> MV.MVector s Word8 -> Int -> ST s ()
copyChunked dest src chunkSize = go 0 (MV.length src)
where
go _ 0 = pure ()
go copied toCopy = do
let thisChunkSize = min toCopy chunkSize
MV.copy (MV.slice copied thisChunkSize dest) (MV.slice copied thisChunkSize src)
go (copied + thisChunkSize) (toCopy - thisChunkSize)
-- TODO: these are a bit questionable. Maybe we can just pass around Vector Word8 in the client code?
fromByteString :: SBS.ShortByteString -> V.Vector Word8
fromByteString (SBS ba) =
let len = Prim.sizeofByteArray (Prim.ByteArray ba)
sz = Prim.sizeOf (undefined :: Word8)
in V.Vector 0 (len * sz) (Prim.ByteArray ba)
toByteString :: V.Vector Word8 -> SBS.ShortByteString
toByteString (V.Vector offset len ba) =
let sz = Prim.sizeOf (undefined :: Word8)
!(Prim.ByteArray ba') = Prim.cloneByteArray ba (offset * sz) (len * sz)
in SBS ba'
|
GaloisInc/pure-zlib
|
src/Codec/Compression/Zlib/OutputWindow.hs
|
Haskell
|
bsd-3-clause
| 4,249
|
{-# LANGUAGE TupleSections #-}
module Main where
import Data.Vector.Unboxed as V hiding ((++))
import qualified Data.Vector.Unboxed.Mutable as VM
import Data.Word
import Data.Bits
import qualified Data.List as L
import qualified Data.ByteString as B
import qualified Control.Monad.State.Strict as S
import Control.Monad
import Control.Applicative
import Control.Monad.ST
import System.Environment
import Numeric
import BinaryCode (setM, addM, subM, regA, regB, lit, binaryCode)
import CommonTypes
import EmuArgs
main :: IO ()
main = do
args <- emu16Args
when (L.null $ binary args) $
error "No binary file given!"
bs <- B.readFile (binary args)
runDCPU (verbose args) $ dcpuFromByteString bs
runSimpleTest :: IO ()
runSimpleTest =
runDCPU True . dcpuFromList . binaryCode $ do
setM regA (lit 0x1)
addM regA (lit 0x2)
setM regB (lit 0x2)
subM regA regB
runDCPU :: Bool -> DCPUData -> IO ()
runDCPU verbose dcpu = do
dcpu' <- execStep verbose dcpu
when verbose $ print dcpu'
runDCPU verbose dcpu'
execStep :: Bool -> DCPUData -> IO DCPUData
execStep verbose dcpu = do
let (instruc, dcpu') = S.runState readInstruction dcpu
when verbose $ print instruc
return $! S.execState (execInstruction instruc) dcpu'
dcpuFromByteString :: B.ByteString -> DCPUData
dcpuFromByteString binary =
DCPUData {ram = initRam binary, regs = V.replicate numRegs 0,
pc = 0, sp = stackBegin, ov = 0}
where
initRam = V.unfoldrN ramSize (\bs ->
case B.length bs of
l | l >= 2 -> do (loByte, bs' ) <- B.uncons bs
(hiByte, bs'') <- B.uncons bs'
let loWord = toW16 loByte
hiWord = toW16 hiByte
return (loWord .|. (hiWord .<<. 8), bs'')
| l == 1 -> do (loByte, bs') <- B.uncons bs
return (toW16 loByte, bs')
| otherwise -> Just (0, bs))
dcpuFromList :: [Word16] -> DCPUData
dcpuFromList binary =
DCPUData {ram = initRam binary, regs = V.replicate numRegs 0,
pc = 0, sp = stackBegin, ov = 0}
where
initRam = V.unfoldrN ramSize (\ls ->
if L.null ls
then Just (0, ls)
else Just (L.head ls, L.tail ls))
execInstruction :: Instruction -> DCPU ()
execInstruction (BasicInstruction opcode (valA, locA) valB)
| opcode <= XOR = do
let (a, b) = (toW32 valA, toW32 valB)
(res, ovf) = case opcode of
SET -> (b, 0)
ADD -> let r = a+b in (r, r .>>. 16)
SUB -> let r = a-b in (r, r .>>. 16)
MUL -> let r = a*b in (r, r .>>. 16)
DIV -> if b == 0
then (0, 0)
else let r = a `div` b
in (r, (a .<<. 16) `div` b)
MOD -> if b == 0 then (0, 0) else (a `mod` b, 0)
SHL -> let r = a .<<. toInt b in (r, r .>>. 16)
SHR -> let r = a .>>. toInt b in (r, (a .<<. 16) .>>. toInt b)
AND -> (a .&. b, 0)
BOR -> (a .|. b, 0)
XOR -> (a `xor` b, 0)
setValue (toW16 res) locA
S.modify (\dcpu -> dcpu {ov = toW16 ovf})
| opcode == IFE = unless (valA == valB) $ void readInstruction
| opcode == IFN = unless (valA /= valB) $ void readInstruction
| opcode == IFG = unless (valA > valB) $ void readInstruction
| opcode == IFB = unless (valA .&. valB /= 0) $ void readInstruction
| otherwise = error "Unexpected case in execInstruction!"
execInstruction (NonBasicInstruction opcode val) =
case opcode of
JSR -> S.modify (\dcpu ->
let sp' = sp dcpu - 1
in dcpu {ram = set (ram dcpu) sp' (pc dcpu + 1),
sp = sp', pc = val})
readInstruction :: DCPU Instruction
readInstruction = do
word <- readWord
if word .&. 0xf == 0
then NonBasicInstruction (nonBasicOpcode $ valA word) . fst <$> readValue (valB word)
else do a <- readValue $ valA word
b <- fst <$> readValue (valB word)
return $! BasicInstruction (opcode word) a b
where
valA = (.&. 0x3f) . (.>>. 4)
valB = (.&. 0x3f) . (.>>. 10)
readValue :: Word16 -> DCPU (Word16, Location)
readValue word
| word <= 0x07 = do let reg = toEnum $ fromIntegral word
(, Register reg) <$> readRegister reg
| word <= 0x0f = do let reg = toEnum $ fromIntegral (word - 0x08)
addr <- readRegister reg
(, RAM addr) <$> readRam addr
| word <= 0x17 = do let reg = toEnum $ fromIntegral (word - 0x10)
regVal <- readRegister reg
nextWord <- readWord
let addr = nextWord + regVal
(, RAM addr) <$> readRam addr
| word == 0x18 = S.state (\dcpu ->
let sp_ = sp dcpu
in ((get (ram dcpu) sp_, RAM sp_), dcpu {sp = sp_ + 1}))
| word == 0x19 = S.gets (\dcpu ->
let sp_ = sp dcpu in (get (ram dcpu) sp_, RAM sp_))
| word == 0x1a = S.state (\dcpu ->
let sp' = sp dcpu - 1
in ((get (ram dcpu) sp', RAM sp'), dcpu {sp = sp'}))
| word == 0x1b = (, SP) . sp <$> S.get
| word == 0x1c = (, PC) . pc <$> S.get
| word == 0x1d = (, O) . ov <$> S.get
| word == 0x1e = readWord >>= \addr -> (, RAM addr) <$> readRam addr
| word == 0x1f = (, Literal) <$> readWord
| otherwise = return (word - 0x20, Literal)
readWord :: DCPU Word16
readWord = do
dcpu <- S.get
let word = get (ram dcpu) (pc dcpu)
S.put dcpu {pc = pc dcpu + 1}
return $! word
readRegister :: RegName -> DCPU Word16
readRegister reg = S.gets (\dcpu -> get (regs dcpu) (fromEnum reg))
readRam :: Word16 -> DCPU Word16
readRam addr = S.gets (\dcpu -> get (ram dcpu) addr)
data Instruction = BasicInstruction Opcode (Value, Location) Value
| NonBasicInstruction NonBasicOpcode Value
instance Show Instruction where
show (BasicInstruction opcode (valA, locA) valB) =
"(BasicInstruction " ++ show opcode ++ " (" ++ showHex valA "" ++ ", " ++ show locA ++ ") " ++ showHex valB "" ++ ")"
show (NonBasicInstruction opcode val) =
"(NonBasicInstruction " ++ show opcode ++ " " ++ showHex val "" ++ ")"
type Value = Word16
data Location = RAM Word16 | Register RegName | SP | PC | O | Literal
instance Show Location where
show (RAM addr) = "(RAM " ++ showHex addr "" ++ ")"
show (Register name) = "(Register " ++ show name ++ ")"
show SP = "SP"
show PC = "PC"
show O = "O"
show Literal = "Literal"
type DCPU = S.State DCPUData
data DCPUData = DCPUData {
ram :: ! (V.Vector Word16), -- ram
regs :: ! (V.Vector Word16), -- registers
pc :: ! Word16, -- program counter
sp :: ! Word16, -- stack pointer
ov :: ! Word16 -- overflow
}
instance Show DCPUData where
show (DCPUData ram regs pc sp ov) =
"DCPU: regs=" ++ V.foldl' (\str e -> (if str /= "[" then str ++ "," else str) ++ showHex e "") "[" regs ++ "]" ++
", pc=" ++ showHex pc "" ++ ", sp=" ++ showHex sp "" ++ ", ov=" ++ showHex ov ""
showRam f = V.foldl' foldRam ("ram:", 0)
where
foldRam (str, addr) cell =
if f cell
then (str ++ putCell addr cell, addr + 1)
else (str, addr + 1)
putCell addr cell = " [" ++ showHex addr "]=" ++ showHex cell ""
ramSize = 0x10000
videoRam = (0x8000, 0x8400)
numRegs = 8
stackBegin = 0xffff
(.>>.), (.<<.) :: Bits a => a -> Int -> a
(.>>.) = shiftR
(.<<.) = shiftL
setValue :: Word16 -> Location -> DCPU ()
setValue value (RAM addr) = S.modify (\dcpu -> dcpu {ram = set (ram dcpu) addr value})
setValue value (Register reg) = S.modify (\dcpu -> dcpu {regs = set (regs dcpu) (fromEnum reg) value})
setValue value PC = S.modify (\dcpu -> dcpu {pc = value})
setValue value SP = S.modify (\dcpu -> dcpu {sp = value})
setValue value O = S.modify (\dcpu -> dcpu {ov = value})
setValue value Literal = return ()
set :: Integral a => V.Vector Word16 -> a -> Word16 -> V.Vector Word16
set vector index value = runST (setM vector (fromIntegral index) value)
where
setM vec i val = do
mVec <- V.unsafeThaw vec
VM.write mVec i val
V.unsafeFreeze mVec
get :: Integral a => V.Vector Word16 -> a -> Word16
get vector index = vector ! fromIntegral index
toInt :: Integral a => a -> Int
toInt = fromIntegral
toW32 :: Integral a => a -> Word32
toW32 = fromIntegral
toW16 :: Integral a => a -> Word16
toW16 = fromIntegral
|
dan-t/dcpu16
|
Emulator.hs
|
Haskell
|
bsd-3-clause
| 9,008
|
-- UUAGC 0.9.38.6 (./src/SistemaL.ag)
module SistemaL where
{-# LINE 3 "./src/SistemaL.ag" #-}
import Data.List
{-# LINE 9 "./src/SistemaL.hs" #-}
{-# LINE 69 "./src/SistemaL.ag" #-}
addIdentProds prods alfa
= let prods' = map (\(Simbolo e,_) -> e) prods
resto = alfa \\ prods'
iprods = map (\e -> (Simbolo e, [Simbolo e])) resto
in prods ++ iprods
myElem _ [] = False
myElem e1 ((Simbolo e2,_):xs) = if e1 == e2
then True
else myElem e1 xs
{-# LINE 23 "./src/SistemaL.hs" #-}
{-# LINE 125 "./src/SistemaL.ag" #-}
ejemplo1 = SistemaL "Koch" alfaK initK prodK
alfaK = [Simbolo "F", Simbolo "f", Simbolo "+", Simbolo "-"]
initK = [Simbolo "F", Simbolo "a"]
prodK = [ (Simbolo "F", [Simbolo "F", Simbolo "g"])
, (Simbolo "F", [])
]
ejemplo2 = SistemaL "Koch" alfaK2 initK2 prodK2
alfaK2 = [Simbolo "F", Simbolo "f", Simbolo "+", Simbolo "-"]
initK2 = [Simbolo "F", Simbolo "f"]
prodK2 = [ (Simbolo "F", [Simbolo "F", Simbolo "+"])
, (Simbolo "f", [])
]
getNombre (SistemaL nm _ _ _) = nm
testSistemaL :: SistemaL -> Either [String] SistemaL
testSistemaL = sem_SistemaL
{-# LINE 45 "./src/SistemaL.hs" #-}
-- Alfabeto ----------------------------------------------------
type Alfabeto = [Simbolo ]
-- cata
sem_Alfabeto :: Alfabeto ->
T_Alfabeto
sem_Alfabeto list =
(Prelude.foldr sem_Alfabeto_Cons sem_Alfabeto_Nil (Prelude.map sem_Simbolo list) )
-- semantic domain
type T_Alfabeto = ([String]) ->
( ([String]),([String]),Alfabeto )
sem_Alfabeto_Cons :: T_Simbolo ->
T_Alfabeto ->
T_Alfabeto
sem_Alfabeto_Cons hd_ tl_ =
(\ _lhsIalf ->
(let _tlOalf :: ([String])
_lhsOalf :: ([String])
_lhsOerrores :: ([String])
_lhsOself :: Alfabeto
_hdIself :: Simbolo
_hdIsimb :: String
_tlIalf :: ([String])
_tlIerrores :: ([String])
_tlIself :: Alfabeto
_verificar =
({-# LINE 31 "./src/SistemaL.ag" #-}
elem _hdIsimb _lhsIalf
{-# LINE 73 "./src/SistemaL.hs" #-}
)
_tlOalf =
({-# LINE 32 "./src/SistemaL.ag" #-}
if _verificar
then _lhsIalf
else _hdIsimb : _lhsIalf
{-# LINE 80 "./src/SistemaL.hs" #-}
)
_lhsOalf =
({-# LINE 35 "./src/SistemaL.ag" #-}
_tlIalf
{-# LINE 85 "./src/SistemaL.hs" #-}
)
_lhsOerrores =
({-# LINE 93 "./src/SistemaL.ag" #-}
if _verificar
then ("El simbolo: '" ++ _hdIsimb ++ "' esta repetido mas de una ves en el alfabeto.") : _tlIerrores
else _tlIerrores
{-# LINE 92 "./src/SistemaL.hs" #-}
)
_self =
({-# LINE 57 "./src/SistemaL.ag" #-}
(:) _hdIself _tlIself
{-# LINE 97 "./src/SistemaL.hs" #-}
)
_lhsOself =
({-# LINE 57 "./src/SistemaL.ag" #-}
_self
{-# LINE 102 "./src/SistemaL.hs" #-}
)
( _hdIself,_hdIsimb) =
hd_
( _tlIalf,_tlIerrores,_tlIself) =
tl_ _tlOalf
in ( _lhsOalf,_lhsOerrores,_lhsOself)))
sem_Alfabeto_Nil :: T_Alfabeto
sem_Alfabeto_Nil =
(\ _lhsIalf ->
(let _lhsOalf :: ([String])
_lhsOerrores :: ([String])
_lhsOself :: Alfabeto
_lhsOalf =
({-# LINE 36 "./src/SistemaL.ag" #-}
_lhsIalf
{-# LINE 118 "./src/SistemaL.hs" #-}
)
_lhsOerrores =
({-# LINE 96 "./src/SistemaL.ag" #-}
[]
{-# LINE 123 "./src/SistemaL.hs" #-}
)
_self =
({-# LINE 57 "./src/SistemaL.ag" #-}
[]
{-# LINE 128 "./src/SistemaL.hs" #-}
)
_lhsOself =
({-# LINE 57 "./src/SistemaL.ag" #-}
_self
{-# LINE 133 "./src/SistemaL.hs" #-}
)
in ( _lhsOalf,_lhsOerrores,_lhsOself)))
-- Inicio ------------------------------------------------------
type Inicio = [Simbolo ]
-- cata
sem_Inicio :: Inicio ->
T_Inicio
sem_Inicio list =
(Prelude.foldr sem_Inicio_Cons sem_Inicio_Nil (Prelude.map sem_Simbolo list) )
-- semantic domain
type T_Inicio = ([String]) ->
( ([String]),Inicio )
sem_Inicio_Cons :: T_Simbolo ->
T_Inicio ->
T_Inicio
sem_Inicio_Cons hd_ tl_ =
(\ _lhsIalfabeto ->
(let _lhsOerrores :: ([String])
_lhsOself :: Inicio
_tlOalfabeto :: ([String])
_hdIself :: Simbolo
_hdIsimb :: String
_tlIerrores :: ([String])
_tlIself :: Inicio
_lhsOerrores =
({-# LINE 99 "./src/SistemaL.ag" #-}
if elem _hdIsimb _lhsIalfabeto
then _tlIerrores
else ("El simbolo de inicio: '" ++ _hdIsimb ++ "' no se encuentra en el alfabeto.") : _tlIerrores
{-# LINE 163 "./src/SistemaL.hs" #-}
)
_self =
({-# LINE 57 "./src/SistemaL.ag" #-}
(:) _hdIself _tlIself
{-# LINE 168 "./src/SistemaL.hs" #-}
)
_lhsOself =
({-# LINE 57 "./src/SistemaL.ag" #-}
_self
{-# LINE 173 "./src/SistemaL.hs" #-}
)
_tlOalfabeto =
({-# LINE 39 "./src/SistemaL.ag" #-}
_lhsIalfabeto
{-# LINE 178 "./src/SistemaL.hs" #-}
)
( _hdIself,_hdIsimb) =
hd_
( _tlIerrores,_tlIself) =
tl_ _tlOalfabeto
in ( _lhsOerrores,_lhsOself)))
sem_Inicio_Nil :: T_Inicio
sem_Inicio_Nil =
(\ _lhsIalfabeto ->
(let _lhsOerrores :: ([String])
_lhsOself :: Inicio
_lhsOerrores =
({-# LINE 102 "./src/SistemaL.ag" #-}
[]
{-# LINE 193 "./src/SistemaL.hs" #-}
)
_self =
({-# LINE 57 "./src/SistemaL.ag" #-}
[]
{-# LINE 198 "./src/SistemaL.hs" #-}
)
_lhsOself =
({-# LINE 57 "./src/SistemaL.ag" #-}
_self
{-# LINE 203 "./src/SistemaL.hs" #-}
)
in ( _lhsOerrores,_lhsOself)))
-- Produccion --------------------------------------------------
type Produccion = ( Simbolo ,Succesor )
-- cata
sem_Produccion :: Produccion ->
T_Produccion
sem_Produccion ( x1,x2) =
(sem_Produccion_Tuple (sem_Simbolo x1 ) (sem_Succesor x2 ) )
-- semantic domain
type T_Produccion = ([String]) ->
( ([String]),Produccion ,String)
sem_Produccion_Tuple :: T_Simbolo ->
T_Succesor ->
T_Produccion
sem_Produccion_Tuple x1_ x2_ =
(\ _lhsIalfabeto ->
(let _lhsOerrores :: ([String])
_lhsOself :: Produccion
_lhsOsimb :: String
_x2Oalfabeto :: ([String])
_x1Iself :: Simbolo
_x1Isimb :: String
_x2Ierrores :: ([String])
_x2Iself :: Succesor
_lhsOerrores =
({-# LINE 114 "./src/SistemaL.ag" #-}
if elem _x1Isimb _lhsIalfabeto
then _x2Ierrores
else ("El simbolo de la produccion (izq): '" ++ _x1Isimb ++ "' no se encuentra en el alfabeto.") : _x2Ierrores
{-# LINE 234 "./src/SistemaL.hs" #-}
)
_self =
({-# LINE 57 "./src/SistemaL.ag" #-}
(_x1Iself,_x2Iself)
{-# LINE 239 "./src/SistemaL.hs" #-}
)
_lhsOself =
({-# LINE 57 "./src/SistemaL.ag" #-}
_self
{-# LINE 244 "./src/SistemaL.hs" #-}
)
_lhsOsimb =
({-# LINE 45 "./src/SistemaL.ag" #-}
_x1Isimb
{-# LINE 249 "./src/SistemaL.hs" #-}
)
_x2Oalfabeto =
({-# LINE 39 "./src/SistemaL.ag" #-}
_lhsIalfabeto
{-# LINE 254 "./src/SistemaL.hs" #-}
)
( _x1Iself,_x1Isimb) =
x1_
( _x2Ierrores,_x2Iself) =
x2_ _x2Oalfabeto
in ( _lhsOerrores,_lhsOself,_lhsOsimb)))
-- Producciones ------------------------------------------------
type Producciones = [Produccion ]
-- cata
sem_Producciones :: Producciones ->
T_Producciones
sem_Producciones list =
(Prelude.foldr sem_Producciones_Cons sem_Producciones_Nil (Prelude.map sem_Produccion list) )
-- semantic domain
type T_Producciones = ([String]) ->
Producciones ->
( ([String]),Producciones)
sem_Producciones_Cons :: T_Produccion ->
T_Producciones ->
T_Producciones
sem_Producciones_Cons hd_ tl_ =
(\ _lhsIalfabeto
_lhsIprods ->
(let _tlOprods :: Producciones
_lhsOprods :: Producciones
_lhsOerrores :: ([String])
_hdOalfabeto :: ([String])
_tlOalfabeto :: ([String])
_hdIerrores :: ([String])
_hdIself :: Produccion
_hdIsimb :: String
_tlIerrores :: ([String])
_tlIprods :: Producciones
_verificar =
({-# LINE 60 "./src/SistemaL.ag" #-}
myElem _hdIsimb _lhsIprods
{-# LINE 291 "./src/SistemaL.hs" #-}
)
_tlOprods =
({-# LINE 61 "./src/SistemaL.ag" #-}
if _verificar
then _lhsIprods
else _hdIself : _lhsIprods
{-# LINE 298 "./src/SistemaL.hs" #-}
)
_lhsOprods =
({-# LINE 64 "./src/SistemaL.ag" #-}
_tlIprods
{-# LINE 303 "./src/SistemaL.hs" #-}
)
_lhsOerrores =
({-# LINE 105 "./src/SistemaL.ag" #-}
if _verificar
then let error = "La produccion con el simb. izq.:'"
++ _hdIsimb
++ "' esta repetida mas de una ves en la lista de producciones."
in (error : _hdIerrores) ++ _tlIerrores
else _hdIerrores ++ _tlIerrores
{-# LINE 313 "./src/SistemaL.hs" #-}
)
_hdOalfabeto =
({-# LINE 39 "./src/SistemaL.ag" #-}
_lhsIalfabeto
{-# LINE 318 "./src/SistemaL.hs" #-}
)
_tlOalfabeto =
({-# LINE 39 "./src/SistemaL.ag" #-}
_lhsIalfabeto
{-# LINE 323 "./src/SistemaL.hs" #-}
)
( _hdIerrores,_hdIself,_hdIsimb) =
hd_ _hdOalfabeto
( _tlIerrores,_tlIprods) =
tl_ _tlOalfabeto _tlOprods
in ( _lhsOerrores,_lhsOprods)))
sem_Producciones_Nil :: T_Producciones
sem_Producciones_Nil =
(\ _lhsIalfabeto
_lhsIprods ->
(let _lhsOerrores :: ([String])
_lhsOprods :: Producciones
_lhsOerrores =
({-# LINE 111 "./src/SistemaL.ag" #-}
[]
{-# LINE 339 "./src/SistemaL.hs" #-}
)
_lhsOprods =
({-# LINE 58 "./src/SistemaL.ag" #-}
_lhsIprods
{-# LINE 344 "./src/SistemaL.hs" #-}
)
in ( _lhsOerrores,_lhsOprods)))
-- Simbolo -----------------------------------------------------
data Simbolo = Simbolo (String)
deriving ( Eq,Show)
-- cata
sem_Simbolo :: Simbolo ->
T_Simbolo
sem_Simbolo (Simbolo _string ) =
(sem_Simbolo_Simbolo _string )
-- semantic domain
type T_Simbolo = ( Simbolo ,String)
sem_Simbolo_Simbolo :: String ->
T_Simbolo
sem_Simbolo_Simbolo string_ =
(let _lhsOsimb :: String
_lhsOself :: Simbolo
_lhsOsimb =
({-# LINE 47 "./src/SistemaL.ag" #-}
string_
{-# LINE 365 "./src/SistemaL.hs" #-}
)
_self =
({-# LINE 57 "./src/SistemaL.ag" #-}
Simbolo string_
{-# LINE 370 "./src/SistemaL.hs" #-}
)
_lhsOself =
({-# LINE 57 "./src/SistemaL.ag" #-}
_self
{-# LINE 375 "./src/SistemaL.hs" #-}
)
in ( _lhsOself,_lhsOsimb))
-- SistemaL ----------------------------------------------------
data SistemaL = SistemaL (String) (Alfabeto ) (Inicio ) (Producciones )
deriving ( Show)
-- cata
sem_SistemaL :: SistemaL ->
T_SistemaL
sem_SistemaL (SistemaL _nombre _alfabeto _inicio _producciones ) =
(sem_SistemaL_SistemaL _nombre (sem_Alfabeto _alfabeto ) (sem_Inicio _inicio ) (sem_Producciones _producciones ) )
-- semantic domain
type T_SistemaL = ( (Either [String] SistemaL))
sem_SistemaL_SistemaL :: String ->
T_Alfabeto ->
T_Inicio ->
T_Producciones ->
T_SistemaL
sem_SistemaL_SistemaL nombre_ alfabeto_ inicio_ producciones_ =
(let _alfabetoOalf :: ([String])
_inicioOalfabeto :: ([String])
_produccionesOalfabeto :: ([String])
_lhsOresultado :: (Either [String] SistemaL)
_produccionesOprods :: Producciones
_alfabetoIalf :: ([String])
_alfabetoIerrores :: ([String])
_alfabetoIself :: Alfabeto
_inicioIerrores :: ([String])
_inicioIself :: Inicio
_produccionesIerrores :: ([String])
_produccionesIprods :: Producciones
_alfabetoOalf =
({-# LINE 28 "./src/SistemaL.ag" #-}
[]
{-# LINE 409 "./src/SistemaL.hs" #-}
)
_inicioOalfabeto =
({-# LINE 41 "./src/SistemaL.ag" #-}
_alfabetoIalf
{-# LINE 414 "./src/SistemaL.hs" #-}
)
_produccionesOalfabeto =
({-# LINE 42 "./src/SistemaL.ag" #-}
_alfabetoIalf
{-# LINE 419 "./src/SistemaL.hs" #-}
)
_lhsOresultado =
({-# LINE 52 "./src/SistemaL.ag" #-}
if null _errores
then let producciones = addIdentProds _produccionesIprods _alfabetoIalf
in Right (SistemaL nombre_ _alfabetoIself _inicioIself producciones)
else Left _errores
{-# LINE 427 "./src/SistemaL.hs" #-}
)
_produccionesOprods =
({-# LINE 67 "./src/SistemaL.ag" #-}
[]
{-# LINE 432 "./src/SistemaL.hs" #-}
)
_errores =
({-# LINE 85 "./src/SistemaL.ag" #-}
let inicioErr = if null _inicioIself
then "La lista de simbolos de inicio no puede ser vacia" : _inicioIerrores
else _inicioIerrores
errores = map (\err -> nombre_ ++ ": " ++ err) (_alfabetoIerrores ++ inicioErr ++ _produccionesIerrores)
in errores
{-# LINE 441 "./src/SistemaL.hs" #-}
)
( _alfabetoIalf,_alfabetoIerrores,_alfabetoIself) =
alfabeto_ _alfabetoOalf
( _inicioIerrores,_inicioIself) =
inicio_ _inicioOalfabeto
( _produccionesIerrores,_produccionesIprods) =
producciones_ _produccionesOalfabeto _produccionesOprods
in ( _lhsOresultado))
-- Succesor ----------------------------------------------------
type Succesor = [Simbolo ]
-- cata
sem_Succesor :: Succesor ->
T_Succesor
sem_Succesor list =
(Prelude.foldr sem_Succesor_Cons sem_Succesor_Nil (Prelude.map sem_Simbolo list) )
-- semantic domain
type T_Succesor = ([String]) ->
( ([String]),Succesor )
sem_Succesor_Cons :: T_Simbolo ->
T_Succesor ->
T_Succesor
sem_Succesor_Cons hd_ tl_ =
(\ _lhsIalfabeto ->
(let _lhsOerrores :: ([String])
_lhsOself :: Succesor
_tlOalfabeto :: ([String])
_hdIself :: Simbolo
_hdIsimb :: String
_tlIerrores :: ([String])
_tlIself :: Succesor
_lhsOerrores =
({-# LINE 119 "./src/SistemaL.ag" #-}
if elem _hdIsimb _lhsIalfabeto
then _tlIerrores
else ("El simbolo de la produccion (der): '" ++ _hdIsimb ++ "' no se encuentra en el alfabeto.") : _tlIerrores
{-# LINE 477 "./src/SistemaL.hs" #-}
)
_self =
({-# LINE 57 "./src/SistemaL.ag" #-}
(:) _hdIself _tlIself
{-# LINE 482 "./src/SistemaL.hs" #-}
)
_lhsOself =
({-# LINE 57 "./src/SistemaL.ag" #-}
_self
{-# LINE 487 "./src/SistemaL.hs" #-}
)
_tlOalfabeto =
({-# LINE 39 "./src/SistemaL.ag" #-}
_lhsIalfabeto
{-# LINE 492 "./src/SistemaL.hs" #-}
)
( _hdIself,_hdIsimb) =
hd_
( _tlIerrores,_tlIself) =
tl_ _tlOalfabeto
in ( _lhsOerrores,_lhsOself)))
sem_Succesor_Nil :: T_Succesor
sem_Succesor_Nil =
(\ _lhsIalfabeto ->
(let _lhsOerrores :: ([String])
_lhsOself :: Succesor
_lhsOerrores =
({-# LINE 122 "./src/SistemaL.ag" #-}
[]
{-# LINE 507 "./src/SistemaL.hs" #-}
)
_self =
({-# LINE 57 "./src/SistemaL.ag" #-}
[]
{-# LINE 512 "./src/SistemaL.hs" #-}
)
_lhsOself =
({-# LINE 57 "./src/SistemaL.ag" #-}
_self
{-# LINE 517 "./src/SistemaL.hs" #-}
)
in ( _lhsOerrores,_lhsOself)))
|
carliros/lsystem
|
src/SistemaL.hs
|
Haskell
|
bsd-3-clause
| 19,601
|
{-# LANGUAGE ScopedTypeVariables #-}
-- © 2006 Peter Thiemann
{- | Transactional, type-indexed implementation of server-side state.
Glossary
A transactional entity (TE) is a named multi-versioned global variable.
-}
module WASH.CGI.Transaction (
T (), init, create, remove, get, set,
with, Control (..),
TCGI ()
) where
import qualified WASH.CGI.BaseCombinators as B
import qualified WASH.CGI.CGIConfig as Conf
import WASH.CGI.CGIMonad
import WASH.CGI.CGI hiding (head, div, span, map)
import WASH.CGI.TCGI (TCGI)
import qualified WASH.CGI.TransactionUtil as TU
import WASH.CGI.TransactionUtil (Control (..))
import WASH.CGI.LogEntry
import WASH.CGI.MakeTypedName
import WASH.CGI.Types
import qualified WASH.CGI.HTMLWrapper as H hiding (map,head)
import qualified WASH.Utility.Auxiliary as Aux
import qualified WASH.Utility.Locking as L
import qualified WASH.Utility.Unique as Unique
import qualified Data.List as List
import System.Directory
import System.IO
import Control.Exception
import Control.Monad
import Data.Maybe (isNothing)
import Prelude hiding (init)
transactionLock = Conf.transactionDir
-- |Handle of a transactional variable
newtype T a =
T String
deriving (Read, Show)
-- |Attempt to create a new tv @n@ and set its initial value. Returns handle to
-- the variable. If the variable already exists, then just returns the handle.
init :: (Types a, Read a, Show a) => String -> a -> TCGI b (T a)
init name val =
let v = show val
typedName = makeTypedNameFromVal name val
h = T typedName
in
wrapCGI (\ cgistate ->
case inparm cgistate of
[] -> -- first time here
do Aux.assertDirectoryExists (List.init Conf.transactionDir) (return ())
-- must try to read the variable at this point
-- because it may only exist in the log
let out = outparm cgistate
ev <- try (readValue out typedName)
let newparm =
case ev of
Left (_ :: SomeException) ->
-- value did not exist (but don't write it now)
PAR_CRE_TV typedName v
Right (v', cached) ->
-- value did exist (although we have not read its value)
PAR_GET_TV typedName v'
return (h, cgistate { outparm = newparm : out })
PAR_CRE_TV _ _ : rest -> -- created the variable
return (h, cgistate { inparm = rest })
PAR_GET_TV _ _ : rest -> -- touched existing variable
return (h, cgistate { inparm = rest })
le : rest ->
error ("Transaction.init: got log entry "
++ show le ++
". This should not happen")
)
-- |Read transactional variable through a typed handle.
get :: (Read a, Show a) => T a -> TCGI b a
get (T typedName) =
wrapCGI (\ cgistate ->
case inparm cgistate of
[] ->
-- check the log for preceding reads and writes;
-- then fall back to physical read
let out = outparm cgistate in
do (v, cached) <- readValue out typedName
let newparm | cached = PAR_RESULT v
| otherwise = PAR_GET_TV typedName v
return (read v, cgistate { outparm = newparm : out })
PAR_GET_TV _ v : rest ->
return (read v, cgistate { inparm = rest })
PAR_RESULT v : rest ->
return (read v, cgistate { inparm = rest })
_ ->
error "Transaction.get: this should not happen"
)
-- |Write to a transactional variable through typed handle. Only affects the
-- log, no /physical/ write happens. Checks physically for existence of the
-- variable (but tries the log first). Raises exception if it does not exist.
set :: (Read a, Show a) => T a -> a -> TCGI b ()
set (T typedName) val =
let v = show val
in
wrapCGI (\ cgistate ->
case inparm cgistate of
[] ->
do let newparm = PAR_SET_TV typedName v
out = outparm cgistate
readValue out typedName -- must not fail
return ((), cgistate { outparm = newparm : outparm cgistate })
PAR_SET_TV _ _ : rest ->
return ((), cgistate { inparm = rest })
_ ->
error "Transaction.set: this should not happen"
)
-- |Create a fresh transactional variable with an initial value and return its
-- handle. Performs a physical write to ensure that the variable's name is
-- unique. Locks the transaction directory during the write operation.
create :: (Read a, Show a, Types a) => a -> TCGI b (T a)
create val =
let v = show val
obtainUniqueHandle =
do name <- Unique.inventStdKey
let typedName = makeTypedNameFromVal name val
h = T typedName
L.obtainLock transactionLock
conflict <- reallyExists typedName
unless conflict $ reallyWrite typedName v
L.releaseLock transactionLock
if conflict then obtainUniqueHandle else return h
in
do wrapCGI $ \ cgistate ->
case inparm cgistate of
[] ->
do Aux.assertDirectoryExists (List.init Conf.transactionDir) (return ())
h@(T typedName) <- obtainUniqueHandle
return (h, cgistate { outparm = PAR_CRE_TV typedName v : outparm cgistate })
PAR_CRE_TV typedName _ : rest ->
return (T typedName, cgistate { inparm = rest })
_ ->
error "Transaction.create: this should not happen"
-- |Remove a transactional variable. Subsequent read accesses to this variable
-- will make the transaction fail. May throw an exception if the variable is not
-- present.
remove :: (Types a) => T a -> TCGI b ()
remove (T typedName) =
wrapCGI (\ cgistate ->
case inparm cgistate of
[] ->
-- check that the variable exists
-- will raise an exception otherwise
let out = outparm cgistate in
do readValue out typedName
return ((), cgistate { outparm = PAR_REM_TV typedName : out })
PAR_REM_TV _ : rest ->
return ((), cgistate { inparm = rest })
_ ->
error "Transaction.remove: this should not happen"
)
-- | @with@ creates a transactional scope in which transactional variables can
-- be manipulated. Transactions may be nested to an arbitrary depth, although a
-- check with the current state of the world only occurs at the point where the
-- top-level transaction tries to commit.
--
-- @with@ takes three parameters, a default value of type @result@, a
-- continuation, and a body function that maps a @Control@ record to a
-- transactional computation. There are three ways in which a
-- transaction may be completed. First, the transaction may be abandoned
-- explicitly by a call to the @abandon@ function supplied as part of the
-- @Control@ record. In this case, the continuation is invoked on a pre-set
-- failure return value. Second, the transaction body runs to completion but
-- fails to commit. In this case, the continuation is also invoked on the
-- pre-set failure return value. Third, the transaction body runs to completion
-- and commits successfully. In this case, the continuation is invoked, but on
-- the pre-set success value.
-- The @result@-type argument initializes the default return value for both, the
-- success and the failure case. The body function implements the body of the
-- transaction.
--
class CGIMonad cgi => WithMonad cgi where
with :: (Read result, Show result) =>
result
-> (result -> cgi ())
-> (TU.Control (TCGI result) result -> (TCGI result) ())
-> cgi ()
instance WithMonad CGI where
with result onResult fun =
TU.withCGI commitFromLog result onResult fun
instance WithMonad (TCGI x) where
-- !!! needs to be checked !!!
with result onResult fun =
TU.withTCGI (const $ return True) result onResult fun
-- |Read value of a variable first from log prefix. Return value @True@
-- indicates a value from the log, @False@ indicates a value read from file. May
-- raise an exception if the variable has been removed.
readValue :: [PARAMETER] -> String -> IO (String, Bool)
readValue [] n =
do v' <- reallyRead n
return (v', False)
readValue (PAR_SET_TV n' v':rest) n =
if n==n'
then return (v', True) -- has been overwritten
else readValue rest n
readValue (PAR_GET_TV n' v':rest) n =
if n==n'
then return (v', True) -- read before
else readValue rest n
readValue (PAR_CRE_TV n' v':rest) n =
if n==n'
then return (v', True)
else readValue rest n
readValue (PAR_REM_TV n':rest) n =
if n==n'
then fail ("Transactional variable " ++ n ++ " has vanished")
else readValue rest n
readValue (PAR_TRANS stid:rest) n =
do v' <- reallyRead n
return (v', False)
readValue (_:rest) n =
readValue rest n
-- |Descriptor of a transactional variable.
data TV_DESC
= TV_DESC { tv_name :: String
-- ^ variable name
, tv_old :: Maybe (Maybe String)
-- ^ value on first read
-- @Nothing@ if not read
-- @Just Nothing@ if created
-- @Just (Just val)@ first value
, tv_new :: Maybe (Maybe String)
-- ^ value after last write
-- @Nothing@ if not written to
-- @Just Nothing@ if removed
-- @Just (Just val)@ if @val@ was written
}
deriving Show
-- |Obtain list of descriptors of transaction variables from a list of log
-- entries. Each variable has at most one descriptor. Input list is in reverse
-- chronological order, /e.g./, the earliest entries come last.
getDescriptors :: [PARAMETER] -> [TV_DESC]
getDescriptors logEntries =
foldr f [] logEntries
where
f (PAR_GET_TV n v) r = doRead n v r
f (PAR_SET_TV n v) r = doWrite n v r
f (PAR_CRE_TV n v) r = doCreate n v r
f (PAR_REM_TV n) r = doRemove n r
f _ r = r
doCreate n v ds =
TV_DESC {tv_name = n, tv_old = Just Nothing, tv_new = Just (Just v)}
: ds
doRemove n ds =
doProcess g n ds
where
g (TV_DESC { tv_old = Just Nothing } : rest) =
rest
g (tvd : rest) =
tvd { tv_new = Just Nothing } : rest
g [] =
[TV_DESC {tv_name = n, tv_old = Nothing, tv_new = Just Nothing}]
doProcess g n ds =
f ds
where
f [] =
g []
f ds@(d':ds') =
if tv_name d' == n then g ds else d' : f ds'
doRead n v ds =
doProcess h n ds
where
h [] =
[TV_DESC {tv_name = n, tv_old = Just (Just v), tv_new = Nothing }]
h (tvd : rest) =
tvd : rest -- not first read
doWrite n v ds =
doProcess h n ds
where
h [] =
[TV_DESC {tv_name = n, tv_old = Nothing, tv_new = Just (Just v) }]
h (tvd : rest) =
tvd { tv_new = Just (Just v) } : rest -- do write
-- | Get the descriptors and try to commit
commitFromLog :: [PARAMETER] -> IO Bool
commitFromLog =
tryToCommit . getDescriptors
-- |Attempt to commit a list of descriptors by checking for the old values to
-- match and then overwriting with the new values. A read-only transaction
-- always succeeds, even if the values have changed after they have been
-- read. Returns @True@ if commit succeeded.
tryToCommit :: [TV_DESC] -> IO Bool
tryToCommit ds =
if checkOnlyReads ds then return True else
do L.obtainLock transactionLock
oldValuesPreserved <- checkOldValuesPreserved ds
when oldValuesPreserved (writeNewValues ds)
L.releaseLock transactionLock
return oldValuesPreserved
-- |Check if the values of all transactional variable in a list of descriptors
-- match the current values. Called with all variables locked.
checkOldValuesPreserved :: [TV_DESC] -> IO Bool
checkOldValuesPreserved [] =
return True
checkOldValuesPreserved (d:ds) =
do b <- checkOldValuePreserved d
if b then checkOldValuesPreserved ds
else return False
checkOldValuePreserved :: TV_DESC -> IO Bool
checkOldValuePreserved d =
do
let n = tv_name d
varExists <- reallyExists n
case tv_old d of
Nothing -> -- not read, check for presence
return varExists
Just Nothing -> -- created, check that it does *not* exist now
return (not varExists)
Just (Just ov) -> -- read old value @ov@
if varExists
then -- value is still present; check if equal
do cv <- reallyRead n
return (cv == ov)
else -- value has disappeared: fail
return False
-- |Overwrite transactional variables from a list of descriptors with new values.
writeNewValues :: [TV_DESC] -> IO ()
writeNewValues ds =
mapM_ g ds
where
g d =
let n = tv_name d in
case tv_new d of
Nothing -> -- not written
return ()
Just Nothing -> -- removed
reallyRemove n
Just (Just nv) -> -- new value
reallyWrite n nv
-- |Check that no variable has been written to.
checkOnlyReads :: [TV_DESC] -> Bool
checkOnlyReads ds =
and (map wasNotWritten ds)
where
wasNotWritten d =
isNothing (tv_new d)
-- |Physically access current shared value of transactional variable. Internal
-- use only.
reallyRead :: String -> IO String
reallyRead n =
let fileName = Conf.transactionDir ++ n in
Aux.readFileStrictly fileName
-- |Physically overwrite current shared value of transactional variable.
reallyWrite :: String -> String -> IO ()
reallyWrite n v =
let fileName = Conf.transactionDir ++ n in
writeFile fileName v
-- |Physically checks the existence of a transactional variable.
reallyExists :: String -> IO Bool
reallyExists n =
let fileName = Conf.transactionDir ++ n in
doesFileExist fileName
-- |Physically remove transactional variable.
reallyRemove :: String -> IO ()
reallyRemove n =
let fileName = Conf.transactionDir ++ n in
removeFile fileName
|
nh2/WashNGo
|
WASH/CGI/Transaction.hs
|
Haskell
|
bsd-3-clause
| 13,274
|
{-# LANGUAGE TemplateHaskell #-}
module Snap.StarterTH where
------------------------------------------------------------------------------
import qualified Data.Foldable as F
import Data.List
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import System.Directory.Tree
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Convenience types
type FileData = (String, String)
type DirData = FilePath
------------------------------------------------------------------------------
-- Gets all the directorys in a DirTree
getDirs :: [FilePath] -> DirTree a -> [FilePath]
getDirs prefix (Dir n c) = (intercalate "/" (reverse (n:prefix))) : concatMap (getDirs (n:prefix)) c
getDirs _ (File _ _) = []
getDirs _ (Failed _ _) = []
------------------------------------------------------------------------------
-- Reads a directory and returns a tuple of the list of all directories
-- encountered and a list of filenames and content strings.
readTree :: FilePath -> IO ([DirData], [FileData])
readTree dir = do
d <- readDirectory $ dir ++ "/."
let ps = zipPaths $ "" :/ (free d)
fd = F.foldr (:) [] ps
dirs = tail . getDirs [] $ free d
return (dirs, fd)
------------------------------------------------------------------------------
-- Calls readTree and returns it's value in a quasiquote.
dirQ :: FilePath -> Q Exp
dirQ tplDir = do
d <- runIO . readTree $ "project_template/" ++ tplDir
lift d
------------------------------------------------------------------------------
-- Creates a declaration assigning the specified name the value returned by
-- dirQ.
buildData :: String -> FilePath -> Q [Dec]
buildData dirName tplDir = do
let dir = mkName dirName
typeSig <- SigD dir `fmap` [t| ([String], [(String, String)]) |]
v <- valD (varP dir) (normalB $ dirQ tplDir) []
return [typeSig, v]
|
janrain/snap
|
src/Snap/StarterTH.hs
|
Haskell
|
bsd-3-clause
| 2,006
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.GHC
-- Copyright : Isaac Jones 2003-2007
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This is a fairly large module. It contains most of the GHC-specific code for
-- configuring, building and installing packages. It also exports a function
-- for finding out what packages are already installed. Configuring involves
-- finding the @ghc@ and @ghc-pkg@ programs, finding what language extensions
-- this version of ghc supports and returning a 'Compiler' value.
--
-- 'getInstalledPackages' involves calling the @ghc-pkg@ program to find out
-- what packages are installed.
--
-- Building is somewhat complex as there is quite a bit of information to take
-- into account. We have to build libs and programs, possibly for profiling and
-- shared libs. We have to support building libraries that will be usable by
-- GHCi and also ghc's @-split-objs@ feature. We have to compile any C files
-- using ghc. Linking, especially for @split-objs@ is remarkably complex,
-- partly because there tend to be 1,000's of @.o@ files and this can often be
-- more than we can pass to the @ld@ or @ar@ programs in one go.
--
-- Installing for libs and exes involves finding the right files and copying
-- them to the right places. One of the more tricky things about this module is
-- remembering the layout of files in the build directory (which is not
-- explicitly documented) and thus what search dirs are used for various kinds
-- of files.
{- Copyright (c) 2003-2005, Isaac Jones
All rights reserved.
Redistribution and use in source and binary forms, with or without
modiication, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}
module Distribution.Simple.GHC (
configure, getInstalledPackages,
buildLib, buildExe, buildApp,
installLib, installExe,
libAbiHash,
registerPackage,
ghcOptions,
ghcVerbosityOptions,
ghcPackageDbOptions,
ghcLibDir,
) where
import Distribution.PackageDescription as PD
( PackageDescription(..), BuildInfo(..), Executable(..), App(..)
, Library(..), libModules, hcOptions, allExtensions
, ObjcGCMode(..) )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo )
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
( InstalledPackageInfo_(..) )
import Distribution.Simple.CCompiler
( cSourceExtensions )
import Distribution.Simple.PackageIndex (PackageIndex)
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.Simple.LocalBuildInfo
( LocalBuildInfo(..), ComponentLocalBuildInfo(..)
, absoluteInstallDirs )
import Distribution.Simple.InstallDirs hiding ( absoluteInstallDirs )
import Distribution.Simple.BuildPaths
import Distribution.Simple.Utils
import Distribution.Package
( PackageIdentifier, Package(..), PackageName(..) )
import qualified Distribution.ModuleName as ModuleName
import Distribution.Simple.Program
( Program(..), ConfiguredProgram(..), ProgramConfiguration, ProgArg
, ProgramLocation(..), rawSystemProgram, rawSystemProgramConf
, rawSystemProgramStdout, rawSystemProgramStdoutConf
, requireProgramVersion, requireProgram, runProgram, getProgramOutput
, userMaybeSpecifyPath, programPath, lookupProgram, addKnownProgram
, ghcProgram, ghcPkgProgram, hsc2hsProgram
, arProgram, ranlibProgram, ldProgram
, gccProgram, stripProgram, touchProgram, ibtoolProgram )
import qualified Distribution.Simple.Program.HcPkg as HcPkg
import qualified Distribution.Simple.Program.Ar as Ar
import qualified Distribution.Simple.Program.Ld as Ld
import Distribution.Simple.Compiler
( CompilerFlavor(..), CompilerId(..), Compiler(..), compilerVersion
, OptimisationLevel(..), PackageDB(..), PackageDBStack
, Flag, languageToFlags, extensionsToFlags )
import Distribution.Version
( Version(..), anyVersion, orLaterVersion )
import Distribution.System
( OS(..), buildOS )
import Distribution.Verbosity
import Distribution.Text
( display, simpleParse )
import Language.Haskell.Extension (Language(..), Extension(..), KnownExtension(..))
import Control.Monad ( unless, when, liftM )
import Data.Char ( isSpace )
import Data.List
import Data.Maybe ( catMaybes )
import Data.Monoid ( Monoid(..) )
import System.Directory
( removeFile, getDirectoryContents, doesFileExist
, getTemporaryDirectory )
import System.FilePath ( (</>), (<.>), takeExtension,
takeDirectory, replaceExtension, splitExtension )
import System.IO (hClose, hPutStrLn)
import Distribution.Compat.Exception (catchExit, catchIO)
import Distribution.Compat.Filesystem.Posix
( removeDirectoryRecursiveVerbose )
-- -----------------------------------------------------------------------------
-- Configuring
configure :: Verbosity -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration -> IO (Compiler, ProgramConfiguration)
configure verbosity hcPath hcPkgPath conf0 = do
(ghcProg, ghcVersion, conf1) <-
requireProgramVersion verbosity ghcProgram
(orLaterVersion (Version [6,4] []))
(userMaybeSpecifyPath "ghc" hcPath conf0)
-- This is slightly tricky, we have to configure ghc first, then we use the
-- location of ghc to help find ghc-pkg in the case that the user did not
-- specify the location of ghc-pkg directly:
(ghcPkgProg, ghcPkgVersion, conf2) <-
requireProgramVersion verbosity ghcPkgProgram {
programFindLocation = guessGhcPkgFromGhcPath ghcProg
}
anyVersion (userMaybeSpecifyPath "ghc-pkg" hcPkgPath conf1)
when (ghcVersion /= ghcPkgVersion) $ die $
"Version mismatch between ghc and ghc-pkg: "
++ programPath ghcProg ++ " is version " ++ display ghcVersion ++ " "
++ programPath ghcPkgProg ++ " is version " ++ display ghcPkgVersion
-- Likewise we try to find the matching hsc2hs program.
let hsc2hsProgram' = hsc2hsProgram {
programFindLocation = guessHsc2hsFromGhcPath ghcProg
}
conf3 = addKnownProgram hsc2hsProgram' conf2
languages <- getLanguages verbosity ghcProg
extensions <- getExtensions verbosity ghcProg
ghcInfo <- if ghcVersion >= Version [6,7] []
then do xs <- getProgramOutput verbosity ghcProg ["--info"]
case reads xs of
[(i, ss)]
| all isSpace ss ->
return i
_ ->
die "Can't parse --info output of GHC"
else return []
let comp = Compiler {
compilerId = CompilerId GHC ghcVersion,
compilerLanguages = languages,
compilerExtensions = extensions
}
conf4 = configureToolchain ghcProg ghcInfo conf3 -- configure gcc and ld
return (comp, conf4)
-- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find
-- the corresponding tool; e.g. if the tool is ghc-pkg, we try looking
-- for a versioned or unversioned ghc-pkg in the same dir, that is:
--
-- > /usr/local/bin/ghc-pkg-ghc-6.6.1(.exe)
-- > /usr/local/bin/ghc-pkg-6.6.1(.exe)
-- > /usr/local/bin/ghc-pkg(.exe)
--
guessToolFromGhcPath :: FilePath -> ConfiguredProgram -> Verbosity
-> IO (Maybe FilePath)
guessToolFromGhcPath tool ghcProg verbosity
= do let path = programPath ghcProg
dir = takeDirectory path
versionSuffix = takeVersionSuffix (dropExeExtension path)
guessNormal = dir </> tool <.> exeExtension
guessGhcVersioned = dir </> (tool ++ "-ghc" ++ versionSuffix) <.> exeExtension
guessVersioned = dir </> (tool ++ versionSuffix) <.> exeExtension
guesses | null versionSuffix = [guessNormal]
| otherwise = [guessGhcVersioned,
guessVersioned,
guessNormal]
info verbosity $ "looking for tool " ++ show tool ++ " near compiler in " ++ dir
exists <- mapM doesFileExist guesses
case [ file | (file, True) <- zip guesses exists ] of
[] -> return Nothing
(fp:_) -> do info verbosity $ "found " ++ tool ++ " in " ++ fp
return (Just fp)
where takeVersionSuffix :: FilePath -> String
takeVersionSuffix = reverse . takeWhile (`elem ` "0123456789.-") . reverse
dropExeExtension :: FilePath -> FilePath
dropExeExtension filepath =
case splitExtension filepath of
(filepath', extension) | extension == exeExtension -> filepath'
| otherwise -> filepath
-- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a
-- corresponding ghc-pkg, we try looking for both a versioned and unversioned
-- ghc-pkg in the same dir, that is:
--
-- > /usr/local/bin/ghc-pkg-ghc-6.6.1(.exe)
-- > /usr/local/bin/ghc-pkg-6.6.1(.exe)
-- > /usr/local/bin/ghc-pkg(.exe)
--
guessGhcPkgFromGhcPath :: ConfiguredProgram -> Verbosity -> IO (Maybe FilePath)
guessGhcPkgFromGhcPath = guessToolFromGhcPath "ghc-pkg"
-- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a
-- corresponding hsc2hs, we try looking for both a versioned and unversioned
-- hsc2hs in the same dir, that is:
--
-- > /usr/local/bin/hsc2hs-ghc-6.6.1(.exe)
-- > /usr/local/bin/hsc2hs-6.6.1(.exe)
-- > /usr/local/bin/hsc2hs(.exe)
--
guessHsc2hsFromGhcPath :: ConfiguredProgram -> Verbosity -> IO (Maybe FilePath)
guessHsc2hsFromGhcPath = guessToolFromGhcPath "hsc2hs"
-- | Adjust the way we find and configure gcc and ld
--
configureToolchain :: ConfiguredProgram -> [(String, String)]
-> ProgramConfiguration
-> ProgramConfiguration
configureToolchain ghcProg ghcInfo =
addKnownProgram gccProgram {
programFindLocation = findProg gccProgram
[ if ghcVersion >= Version [6,12] []
then mingwBinDir </> "gcc.exe"
else baseDir </> "gcc.exe" ],
programPostConf = configureGcc
}
. addKnownProgram ldProgram {
programFindLocation = findProg ldProgram
[ if ghcVersion >= Version [6,12] []
then mingwBinDir </> "ld.exe"
else libDir </> "ld.exe" ],
programPostConf = configureLd
}
. addKnownProgram arProgram {
programFindLocation = findProg arProgram
[ if ghcVersion >= Version [6,12] []
then mingwBinDir </> "ar.exe"
else libDir </> "ar.exe" ]
}
where
Just ghcVersion = programVersion ghcProg
compilerDir = takeDirectory (programPath ghcProg)
baseDir = takeDirectory compilerDir
mingwBinDir = baseDir </> "mingw" </> "bin"
libDir = baseDir </> "gcc-lib"
includeDir = baseDir </> "include" </> "mingw"
isWindows = case buildOS of Windows -> True; _ -> False
-- on Windows finding and configuring ghc's gcc and ld is a bit special
findProg :: Program -> [FilePath] -> Verbosity -> IO (Maybe FilePath)
findProg prog locations
| isWindows = \verbosity -> look locations verbosity
| otherwise = programFindLocation prog
where
look [] verbosity = do
warn verbosity ("Couldn't find " ++ programName prog ++ " where I expected it. Trying the search path.")
programFindLocation prog verbosity
look (f:fs) verbosity = do
exists <- doesFileExist f
if exists then return (Just f)
else look fs verbosity
ccFlags = getFlags "C compiler flags"
gccLinkerFlags = getFlags "Gcc Linker flags"
ldLinkerFlags = getFlags "Ld Linker flags"
getFlags key = case lookup key ghcInfo of
Nothing -> []
Just flags ->
case reads flags of
[(args, "")] -> args
_ -> [] -- XXX Should should be an error really
configureGcc :: Verbosity -> ConfiguredProgram -> IO [ProgArg]
configureGcc v cp = liftM (++ (ccFlags ++ gccLinkerFlags))
$ configureGcc' v cp
configureGcc' :: Verbosity -> ConfiguredProgram -> IO [ProgArg]
configureGcc'
| isWindows = \_ gccProg -> case programLocation gccProg of
-- if it's found on system then it means we're using the result
-- of programFindLocation above rather than a user-supplied path
-- Pre GHC 6.12, that meant we should add these flags to tell
-- ghc's gcc where it lives and thus where gcc can find its
-- various files:
FoundOnSystem {}
| ghcVersion < Version [6,11] [] ->
return ["-B" ++ libDir, "-I" ++ includeDir]
_ -> return []
| otherwise = \_ _ -> return []
configureLd :: Verbosity -> ConfiguredProgram -> IO [ProgArg]
configureLd v cp = liftM (++ ldLinkerFlags) $ configureLd' v cp
-- we need to find out if ld supports the -x flag
configureLd' :: Verbosity -> ConfiguredProgram -> IO [ProgArg]
configureLd' verbosity ldProg = do
tempDir <- getTemporaryDirectory
ldx <- withTempFile tempDir ".c" $ \testcfile testchnd ->
withTempFile tempDir ".o" $ \testofile testohnd -> do
hPutStrLn testchnd "int foo() {}"
hClose testchnd; hClose testohnd
rawSystemProgram verbosity ghcProg ["-c", testcfile,
"-o", testofile]
withTempFile tempDir ".o" $ \testofile' testohnd' ->
do
hClose testohnd'
_ <- rawSystemProgramStdout verbosity ldProg
["-x", "-r", testofile, "-o", testofile']
return True
`catchIO` (\_ -> return False)
`catchExit` (\_ -> return False)
if ldx
then return ["-x"]
else return []
getLanguages :: Verbosity -> ConfiguredProgram -> IO [(Language, Flag)]
getLanguages _ ghcProg
-- TODO: should be using --supported-languages rather than hard coding
| ghcVersion >= Version [7] [] = return [(Haskell98, "-XHaskell98")
,(Haskell2010, "-XHaskell2010")]
| otherwise = return [(Haskell98, "")]
where
Just ghcVersion = programVersion ghcProg
getExtensions :: Verbosity -> ConfiguredProgram -> IO [(Extension, Flag)]
getExtensions verbosity ghcProg
| ghcVersion >= Version [6,7] [] = do
str <- rawSystemStdout verbosity (programPath ghcProg)
["--supported-languages"]
let extStrs = if ghcVersion >= Version [7] []
then lines str
else -- Older GHCs only gave us either Foo or NoFoo,
-- so we have to work out the other one ourselves
[ extStr''
| extStr <- lines str
, let extStr' = case extStr of
'N' : 'o' : xs -> xs
_ -> "No" ++ extStr
, extStr'' <- [extStr, extStr']
]
let extensions0 = [ (ext, "-X" ++ display ext)
| Just ext <- map simpleParse extStrs ]
extensions1 = if ghcVersion >= Version [6,8] [] &&
ghcVersion < Version [6,10] []
then -- ghc-6.8 introduced RecordPuns however it
-- should have been NamedFieldPuns. We now
-- encourage packages to use NamedFieldPuns
-- so for compatability we fake support for
-- it in ghc-6.8 by making it an alias for
-- the old RecordPuns extension.
(EnableExtension NamedFieldPuns, "-XRecordPuns") :
(DisableExtension NamedFieldPuns, "-XNoRecordPuns") :
extensions0
else extensions0
extensions2 = if ghcVersion < Version [7,1] []
then -- ghc-7.2 split NondecreasingIndentation off
-- into a proper extension. Before that it
-- was always on.
(EnableExtension NondecreasingIndentation, "") :
(DisableExtension NondecreasingIndentation, "") :
extensions1
else extensions1
return extensions2
| otherwise = return oldLanguageExtensions
where
Just ghcVersion = programVersion ghcProg
-- | For GHC 6.6.x and earlier, the mapping from supported extensions to flags
oldLanguageExtensions :: [(Extension, Flag)]
oldLanguageExtensions =
let doFlag (f, (enable, disable)) = [(EnableExtension f, enable),
(DisableExtension f, disable)]
fglasgowExts = ("-fglasgow-exts",
"") -- This is wrong, but we don't want to turn
-- all the extensions off when asked to just
-- turn one off
fFlag flag = ("-f" ++ flag, "-fno-" ++ flag)
in concatMap doFlag
[(OverlappingInstances , fFlag "allow-overlapping-instances")
,(TypeSynonymInstances , fglasgowExts)
,(TemplateHaskell , fFlag "th")
,(ForeignFunctionInterface , fFlag "ffi")
,(MonomorphismRestriction , fFlag "monomorphism-restriction")
,(MonoPatBinds , fFlag "mono-pat-binds")
,(UndecidableInstances , fFlag "allow-undecidable-instances")
,(IncoherentInstances , fFlag "allow-incoherent-instances")
,(Arrows , fFlag "arrows")
,(Generics , fFlag "generics")
,(ImplicitPrelude , fFlag "implicit-prelude")
,(ImplicitParams , fFlag "implicit-params")
,(CPP , ("-cpp", ""{- Wrong -}))
,(BangPatterns , fFlag "bang-patterns")
,(KindSignatures , fglasgowExts)
,(RecursiveDo , fglasgowExts)
,(ParallelListComp , fglasgowExts)
,(MultiParamTypeClasses , fglasgowExts)
,(FunctionalDependencies , fglasgowExts)
,(Rank2Types , fglasgowExts)
,(RankNTypes , fglasgowExts)
,(PolymorphicComponents , fglasgowExts)
,(ExistentialQuantification , fglasgowExts)
,(ScopedTypeVariables , fFlag "scoped-type-variables")
,(FlexibleContexts , fglasgowExts)
,(FlexibleInstances , fglasgowExts)
,(EmptyDataDecls , fglasgowExts)
,(PatternGuards , fglasgowExts)
,(GeneralizedNewtypeDeriving , fglasgowExts)
,(MagicHash , fglasgowExts)
,(UnicodeSyntax , fglasgowExts)
,(PatternSignatures , fglasgowExts)
,(UnliftedFFITypes , fglasgowExts)
,(LiberalTypeSynonyms , fglasgowExts)
,(TypeOperators , fglasgowExts)
,(GADTs , fglasgowExts)
,(RelaxedPolyRec , fglasgowExts)
,(ExtendedDefaultRules , fFlag "extended-default-rules")
,(UnboxedTuples , fglasgowExts)
,(DeriveDataTypeable , fglasgowExts)
,(ConstrainedClassMethods , fglasgowExts)
]
getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration
-> IO PackageIndex
getInstalledPackages verbosity packagedbs conf = do
checkPackageDbStack packagedbs
pkgss <- getInstalledPackages' verbosity packagedbs conf
topDir <- ghcLibDir' verbosity ghcProg
let indexes = [ PackageIndex.fromList (map (substTopDir topDir) pkgs)
| (_, pkgs) <- pkgss ]
return $! hackRtsPackage (mconcat indexes)
where
-- On Windows, various fields have $topdir/foo rather than full
-- paths. We need to substitute the right value in so that when
-- we, for example, call gcc, we have proper paths to give it
Just ghcProg = lookupProgram ghcProgram conf
hackRtsPackage index =
case PackageIndex.lookupPackageName index (PackageName "rts") of
[(_,[rts])]
-> PackageIndex.insert (removeMingwIncludeDir rts) index
_ -> index -- No (or multiple) ghc rts package is registered!!
-- Feh, whatever, the ghc testsuite does some crazy stuff.
ghcLibDir :: Verbosity -> LocalBuildInfo -> IO FilePath
ghcLibDir verbosity lbi =
(reverse . dropWhile isSpace . reverse) `fmap`
rawSystemProgramStdoutConf verbosity ghcProgram (withPrograms lbi) ["--print-libdir"]
ghcLibDir' :: Verbosity -> ConfiguredProgram -> IO FilePath
ghcLibDir' verbosity ghcProg =
(reverse . dropWhile isSpace . reverse) `fmap`
rawSystemProgramStdout verbosity ghcProg ["--print-libdir"]
checkPackageDbStack :: PackageDBStack -> IO ()
checkPackageDbStack (GlobalPackageDB:rest)
| GlobalPackageDB `notElem` rest = return ()
checkPackageDbStack _ =
die $ "GHC.getInstalledPackages: the global package db must be "
++ "specified first and cannot be specified multiple times"
-- GHC < 6.10 put "$topdir/include/mingw" in rts's installDirs. This
-- breaks when you want to use a different gcc, so we need to filter
-- it out.
removeMingwIncludeDir :: InstalledPackageInfo -> InstalledPackageInfo
removeMingwIncludeDir pkg =
let ids = InstalledPackageInfo.includeDirs pkg
ids' = filter (not . ("mingw" `isSuffixOf`)) ids
in pkg { InstalledPackageInfo.includeDirs = ids' }
-- | Get the packages from specific PackageDBs, not cumulative.
--
getInstalledPackages' :: Verbosity -> [PackageDB] -> ProgramConfiguration
-> IO [(PackageDB, [InstalledPackageInfo])]
getInstalledPackages' verbosity packagedbs conf
| ghcVersion >= Version [6,9] [] =
sequence
[ do pkgs <- HcPkg.dump verbosity ghcPkgProg packagedb
return (packagedb, pkgs)
| packagedb <- packagedbs ]
where
Just ghcPkgProg = lookupProgram ghcPkgProgram conf
Just ghcProg = lookupProgram ghcProgram conf
Just ghcVersion = programVersion ghcProg
substTopDir :: FilePath -> InstalledPackageInfo -> InstalledPackageInfo
substTopDir topDir ipo
= ipo {
InstalledPackageInfo.importDirs
= map f (InstalledPackageInfo.importDirs ipo),
InstalledPackageInfo.libraryDirs
= map f (InstalledPackageInfo.libraryDirs ipo),
InstalledPackageInfo.includeDirs
= map f (InstalledPackageInfo.includeDirs ipo),
InstalledPackageInfo.frameworkDirs
= map f (InstalledPackageInfo.frameworkDirs ipo),
InstalledPackageInfo.haddockInterfaces
= map f (InstalledPackageInfo.haddockInterfaces ipo),
InstalledPackageInfo.haddockHTMLs
= map f (InstalledPackageInfo.haddockHTMLs ipo)
}
where f ('$':'t':'o':'p':'d':'i':'r':rest) = topDir ++ rest
f x = x
-- -----------------------------------------------------------------------------
-- Building
-- | Build a library with GHC.
--
buildLib :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildLib verbosity pkg_descr lbi lib clbi = do
let pref = buildDir lbi
pkgid = packageId pkg_descr
runGhcProg = rawSystemProgramConf verbosity ghcProgram (withPrograms lbi)
ifVanillaLib forceVanilla = when (forceVanilla || withVanillaLib lbi)
ifProfLib = when (withProfLib lbi)
ifSharedLib = when (withSharedLib lbi)
ifGHCiLib = when (withGHCiLib lbi && withVanillaLib lbi)
comp = compiler lbi
ghcVersion = compilerVersion comp
libBi <- hackThreadedFlag verbosity
comp (withProfLib lbi) (libBuildInfo lib)
let libTargetDir = pref
forceVanillaLib = EnableExtension TemplateHaskell `elem` allExtensions libBi
-- TH always needs vanilla libs, even when building for profiling
createDirectoryIfMissingVerbose verbosity True libTargetDir
-- TODO: do we need to put hs-boot files into place for mutually recurive modules?
let ghcArgs =
"--make"
: ["-package-name", display pkgid ]
++ constructGHCCmdLine lbi libBi clbi libTargetDir verbosity
++ map display (libModules lib)
ghcArgsProf = ghcArgs
++ ["-prof",
"-hisuf", "p_hi",
"-osuf", "p_o"
]
++ ghcProfOptions libBi
ghcArgsShared = ghcArgs
++ ["-dynamic",
"-hisuf", "dyn_hi",
"-osuf", "dyn_o", "-fPIC"
]
++ ghcSharedOptions libBi
unless (null (libModules lib)) $
do ifVanillaLib forceVanillaLib (runGhcProg ghcArgs)
ifProfLib (runGhcProg ghcArgsProf)
ifSharedLib (runGhcProg ghcArgsShared)
-- build any C sources
foundCSources <- mapM (findFile $ cSourceDirs libBi) $ cSources libBi
unless (null (cSources libBi)) $ do
info verbosity "Building C Sources..."
sequence_ [do let (odir,args) = constructCcCmdLine lbi libBi clbi pref
filename verbosity
False
(withProfLib lbi)
createDirectoryIfMissingVerbose verbosity True odir
runGhcProg args
ifSharedLib (runGhcProg (args ++ ["-fPIC", "-osuf dyn_o"]))
| filename <- foundCSources ]
-- link:
info verbosity "Linking..."
let cObjs = map (`replaceExtension` objExtension) foundCSources
cSharedObjs = map (`replaceExtension` ("dyn_" ++ objExtension))
foundCSources
vanillaLibFilePath = libTargetDir </> mkLibName pkgid
profileLibFilePath = libTargetDir </> mkProfLibName pkgid
sharedLibFilePath = libTargetDir </> mkSharedLibName pkgid
(compilerId (compiler lbi))
ghciLibFilePath = libTargetDir </> mkGHCiLibName pkgid
libInstallPath = libdir $ absoluteInstallDirs pkg_descr lbi NoCopyDest
sharedLibInstallPath = libInstallPath </> mkSharedLibName pkgid
(compilerId (compiler lbi))
stubObjs <- fmap catMaybes $ sequence
[ findFileWithExtension [objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files
, x <- libModules lib ]
stubProfObjs <- fmap catMaybes $ sequence
[ findFileWithExtension ["p_" ++ objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files
, x <- libModules lib ]
stubSharedObjs <- fmap catMaybes $ sequence
[ findFileWithExtension ["dyn_" ++ objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files
, x <- libModules lib ]
hObjs <- getHaskellObjects lib lbi
pref objExtension True
hProfObjs <-
if (withProfLib lbi)
then getHaskellObjects lib lbi
pref ("p_" ++ objExtension) True
else return []
hSharedObjs <-
if (withSharedLib lbi)
then getHaskellObjects lib lbi
pref ("dyn_" ++ objExtension) False
else return []
unless (null hObjs && null cObjs && null stubObjs) $ do
-- first remove library files if they exists
sequence_
[ removeFile libFilePath `catchIO` \_ -> return ()
| libFilePath <- [vanillaLibFilePath, profileLibFilePath
,sharedLibFilePath, ghciLibFilePath] ]
let staticObjectFiles =
hObjs
++ map (pref </>) cObjs
++ stubObjs
profObjectFiles =
hProfObjs
++ map (pref </>) cObjs
++ stubProfObjs
ghciObjFiles =
hObjs
++ map (pref </>) cObjs
++ stubObjs
dynamicObjectFiles =
hSharedObjs
++ map (pref </>) cSharedObjs
++ stubSharedObjs
-- After the relocation lib is created we invoke ghc -shared
-- with the dependencies spelled out as -package arguments
-- and ghc invokes the linker with the proper library paths
ghcSharedLinkArgs =
[ "-no-auto-link-packages",
"-shared",
"-dynamic",
"-o", sharedLibFilePath ]
-- For dynamic libs, Mac OS/X needs to know the install location
-- at build time.
++ (if buildOS == OSX
then ["-dylib-install-name", sharedLibInstallPath]
else [])
++ dynamicObjectFiles
++ ["-package-name", display pkgid ]
++ ghcPackageFlags lbi clbi
++ ["-l"++extraLib | extraLib <- extraLibs libBi]
++ ["-L"++extraLibDir | extraLibDir <- extraLibDirs libBi]
ifVanillaLib False $ do
(arProg, _) <- requireProgram verbosity arProgram (withPrograms lbi)
Ar.createArLibArchive verbosity arProg
vanillaLibFilePath staticObjectFiles
ifProfLib $ do
(arProg, _) <- requireProgram verbosity arProgram (withPrograms lbi)
Ar.createArLibArchive verbosity arProg
profileLibFilePath profObjectFiles
ifGHCiLib $ do
(ldProg, _) <- requireProgram verbosity ldProgram (withPrograms lbi)
Ld.combineObjectFiles verbosity ldProg
ghciLibFilePath ghciObjFiles
ifSharedLib $
runGhcProg ghcSharedLinkArgs
-- | Build an executable with GHC.
--
buildExe :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
buildExe verbosity _pkg_descr lbi
exe@Executable { exeName = exeName', modulePath = modPath } clbi = do
let pref = buildDir lbi
runGhcProg = rawSystemProgramConf verbosity ghcProgram (withPrograms lbi)
exeBi <- hackThreadedFlag verbosity
(compiler lbi) (withProfExe lbi) (buildInfo exe)
-- exeNameReal, the name that GHC really uses (with .exe on Windows)
let exeNameReal = exeName' <.>
(if null $ takeExtension exeName' then exeExtension else "")
let targetDir = pref </> exeName'
let exeDir = targetDir </> (exeName' ++ "-tmp")
createDirectoryIfMissingVerbose verbosity True targetDir
createDirectoryIfMissingVerbose verbosity True exeDir
-- TODO: do we need to put hs-boot files into place for mutually recursive modules?
-- FIX: what about exeName.hi-boot?
-- build executables
srcMainFile <- findFile (exeDir : hsSourceDirs exeBi) modPath
let foreignMain = elem (drop 1 $ takeExtension modPath) cSourceExtensions
hsRootFiles <- do
if not foreignMain
then return [srcMainFile]
else do
maybeFiles <-
sequence [ findFileWithExtension ["hs", "lhs"]
(exeDir : hsSourceDirs exeBi)
(ModuleName.toFilePath x)
| x <- otherModules exeBi ]
return $ catMaybes maybeFiles
foundCSources <- mapM (findFile $ cSourceDirs exeBi) $ cSources exeBi
let cObjs = map (`replaceExtension` objExtension) foundCSources
let binArgs linkExe dynExe profExe =
"--make"
: (if linkExe
then ["-o", targetDir </> exeNameReal]
else ["-c"])
++ constructGHCCmdLine lbi exeBi clbi exeDir verbosity
++ (if linkExe
then [exeDir </> x | x <- cObjs]
else [])
++ hsRootFiles
++ (if foreignMain
then (if linkExe
then [srcMainFile]
else [])
++ ["-no-hs-main"]
else [])
++ ["-optl" ++ opt | opt <- PD.ldOptions exeBi]
++ ["-l"++lib | lib <- extraLibs exeBi]
++ ["-L"++libDir | libDir <- extraLibDirs exeBi]
++ concat [["-framework", f] | f <- PD.frameworks exeBi]
++ (let flagPrefix = if linkExe
then "-optl"
else "-optc"
in case PD.objcGCMode exeBi of
PD.ObjcGCDisabled -> []
PD.ObjcGCOptional -> [flagPrefix ++ "-fobjc-gc"]
PD.ObjcGCMandatory -> [flagPrefix ++ "-fobjc-gc-only"])
++ (if dynExe
then ["-dynamic"]
else [])
++ (if profExe
then ["-prof",
"-hisuf", "p_hi",
"-osuf", "p_o"
] ++ ghcProfOptions exeBi
else [])
-- For building exe's for profiling that use TH we actually
-- have to build twice, once without profiling and the again
-- with profiling. This is because the code that TH needs to
-- run at compile time needs to be the vanilla ABI so it can
-- be loaded up and run by the compiler.
when (withProfExe lbi && EnableExtension TemplateHaskell `elem` allExtensions exeBi)
(runGhcProg (binArgs False (withDynExe lbi) False))
runGhcProg (binArgs False (withDynExe lbi) (withProfExe lbi))
unless (null (cSources exeBi)) $ do
info verbosity "Building C Sources."
sequence_ [do let (odir,args) = constructCcCmdLine lbi exeBi clbi
exeDir filename verbosity
(withDynExe lbi) (withProfExe lbi)
createDirectoryIfMissingVerbose verbosity True odir
runGhcProg args
| filename <- foundCSources]
runGhcProg (binArgs True (withDynExe lbi) (withProfExe lbi))
buildApp :: Verbosity -> PackageDescription -> LocalBuildInfo
-> App -> ComponentLocalBuildInfo -> IO ()
buildApp verbosity _pkg_descr lbi app clbi = do
appBi <- hackThreadedFlag verbosity
(compiler lbi) (withProfExe lbi) (appBuildInfo app)
let prefix = buildDir lbi
appPath = prefix </> (appName app ++ ".app")
contentsPath = appPath </> "Contents"
executableDirectoryPath = contentsPath </> "MacOS"
resourcesPath = contentsPath </> "Resources"
tmpDir = prefix </> (appName app ++ "-tmp")
removeDirectoryRecursiveVerbose verbosity appPath
createDirectoryIfMissingVerbose verbosity True executableDirectoryPath
createDirectoryIfMissingVerbose verbosity True tmpDir
let runGhcProg = rawSystemProgramConf verbosity ghcProgram (withPrograms lbi)
srcMainFile <- findFile (tmpDir : hsSourceDirs appBi) (appModulePath app)
let foreignMain =
elem (drop 1 $ takeExtension $ appModulePath app) cSourceExtensions
hsRootFiles <- do
if not foreignMain
then return [srcMainFile]
else do
maybeFiles <-
sequence [ findFileWithExtension ["hs", "lhs"]
(tmpDir : hsSourceDirs appBi)
(ModuleName.toFilePath x)
| x <- otherModules appBi ]
return $ catMaybes maybeFiles
foundCSources <- mapM (findFile $ cSourceDirs appBi) $ cSources appBi
let cObjs = map (`replaceExtension` objExtension) foundCSources
let binArgs linkExe dynExe profExe =
"--make"
: (if linkExe
then ["-o", executableDirectoryPath </> appName app]
else ["-c"])
++ constructGHCCmdLine lbi appBi clbi tmpDir verbosity
++ (if linkExe
then [tmpDir </> x | x <- cObjs]
else [])
++ hsRootFiles
++ (if foreignMain
then (if linkExe
then [srcMainFile]
else [])
++ ["-no-hs-main"]
else [])
++ ["-optl" ++ opt | opt <- PD.ldOptions appBi]
++ ["-l"++lib | lib <- extraLibs appBi]
++ ["-L"++libDir | libDir <- extraLibDirs appBi]
++ concat [["-framework", f] | f <- PD.frameworks appBi]
++ (let flagPrefix = if linkExe
then "-optl"
else "-optc"
in case PD.objcGCMode appBi of
PD.ObjcGCDisabled -> []
PD.ObjcGCOptional -> [flagPrefix ++ "-fobjc-gc"]
PD.ObjcGCMandatory -> [flagPrefix ++ "-fobjc-gc-only"])
++ (if dynExe
then ["-dynamic"]
else [])
++ (if profExe
then ["-prof",
"-hisuf", "p_hi",
"-osuf", "p_o"
] ++ ghcProfOptions appBi
else [])
-- For building exe's for profiling that use TH we actually
-- have to build twice, once without profiling and the again
-- with profiling. This is because the code that TH needs to
-- run at compile time needs to be the vanilla ABI so it can
-- be loaded up and run by the compiler.
when (withProfExe lbi && EnableExtension TemplateHaskell `elem` allExtensions appBi)
(runGhcProg (binArgs False (withDynExe lbi) False))
runGhcProg (binArgs False (withDynExe lbi) (withProfExe lbi))
unless (null (cSources appBi)) $ do
info verbosity "Building C Sources."
sequence_ [do let (odir,args) = constructCcCmdLine lbi appBi clbi
tmpDir filename verbosity
(withDynExe lbi) (withProfExe lbi)
createDirectoryIfMissingVerbose verbosity True odir
runGhcProg args
| filename <- foundCSources]
runGhcProg (binArgs True (withDynExe lbi) (withProfExe lbi))
(touchConfiguredProgram, _) <-
requireProgram verbosity touchProgram $ withPrograms lbi
(ibtoolConfiguredProgram, _) <-
requireProgram verbosity ibtoolProgram $ withPrograms lbi
createDirectoryIfMissingVerbose verbosity False appPath
writeFileAtomic (appPath </> "PkgInfo") "APPL????"
createDirectoryIfMissingVerbose verbosity False contentsPath
let infoPlistSource = appInfoPlist app
infoPlistDestination = contentsPath </> "Info.plist"
installOrdinaryFile verbosity infoPlistSource infoPlistDestination
createDirectoryIfMissingVerbose verbosity False resourcesPath
let sourceResourcePath relativePath =
case appResourceDirectory app of
Nothing -> relativePath
Just resourceDirectory -> resourceDirectory </> relativePath
mapM_ (\xib -> do
let xibPath = sourceResourcePath xib
nibPath = resourcesPath </> replaceExtension xib ".nib"
runProgram verbosity
ibtoolConfiguredProgram
["--warnings",
"--errors",
"--output-format=human-readable-text",
"--compile",
nibPath,
xibPath])
$ appXIBs app
mapM_ (\resource -> do
let resourceSource = sourceResourcePath resource
resourceDestination = resourcesPath </> resource
installOrdinaryFile verbosity resourceSource resourceDestination)
$ appOtherResources app
runProgram verbosity touchConfiguredProgram [appPath]
-- | Filter the "-threaded" flag when profiling as it does not
-- work with ghc-6.8 and older.
hackThreadedFlag :: Verbosity -> Compiler -> Bool -> BuildInfo -> IO BuildInfo
hackThreadedFlag verbosity comp prof bi
| not mustFilterThreaded = return bi
| otherwise = do
warn verbosity $ "The ghc flag '-threaded' is not compatible with "
++ "profiling in ghc-6.8 and older. It will be disabled."
return bi { options = filterHcOptions (/= "-threaded") (options bi) }
where
mustFilterThreaded = prof && compilerVersion comp < Version [6, 10] []
&& "-threaded" `elem` hcOptions GHC bi
filterHcOptions p hcoptss =
[ (hc, if hc == GHC then filter p opts else opts)
| (hc, opts) <- hcoptss ]
-- when using -split-objs, we need to search for object files in the
-- Module_split directory for each module.
getHaskellObjects :: Library -> LocalBuildInfo
-> FilePath -> String -> Bool -> IO [FilePath]
getHaskellObjects lib lbi pref wanted_obj_ext allow_split_objs
| splitObjs lbi && allow_split_objs = do
let splitSuffix = if compilerVersion (compiler lbi) <
Version [6, 11] []
then "_split"
else "_" ++ wanted_obj_ext ++ "_split"
dirs = [ pref </> (ModuleName.toFilePath x ++ splitSuffix)
| x <- libModules lib ]
objss <- mapM getDirectoryContents dirs
let objs = [ dir </> obj
| (objs',dir) <- zip objss dirs, obj <- objs',
let obj_ext = takeExtension obj,
'.':wanted_obj_ext == obj_ext ]
return objs
| otherwise =
return [ pref </> ModuleName.toFilePath x <.> wanted_obj_ext
| x <- libModules lib ]
-- | Extracts a String representing a hash of the ABI of a built
-- library. It can fail if the library has not yet been built.
--
libAbiHash :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO String
libAbiHash verbosity pkg_descr lbi lib clbi = do
libBi <- hackThreadedFlag verbosity
(compiler lbi) (withProfLib lbi) (libBuildInfo lib)
let
ghcArgs =
"--abi-hash"
: ["-package-name", display (packageId pkg_descr) ]
++ constructGHCCmdLine lbi libBi clbi (buildDir lbi) verbosity
++ map display (exposedModules lib)
--
rawSystemProgramStdoutConf verbosity ghcProgram (withPrograms lbi) ghcArgs
constructGHCCmdLine
:: LocalBuildInfo
-> BuildInfo
-> ComponentLocalBuildInfo
-> FilePath
-> Verbosity
-> [String]
constructGHCCmdLine lbi bi clbi odir verbosity =
ghcVerbosityOptions verbosity
-- Unsupported extensions have already been checked by configure
++ ghcOptions lbi bi clbi odir
ghcVerbosityOptions :: Verbosity -> [String]
ghcVerbosityOptions verbosity
| verbosity >= deafening = ["-v"]
| verbosity >= normal = []
| otherwise = ["-w", "-v0"]
ghcOptions :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> [String]
ghcOptions lbi bi clbi odir
= ["-hide-all-packages"]
++ ["-fbuilding-cabal-package" | ghcVer >= Version [6,11] [] ]
++ ghcPackageDbOptions (withPackageDB lbi)
++ ["-split-objs" | splitObjs lbi ]
++ ["-i"]
++ ["-i" ++ odir]
++ ["-i" ++ l | l <- nub (hsSourceDirs bi)]
++ ["-i" ++ autogenModulesDir lbi]
++ ["-I" ++ autogenModulesDir lbi]
++ ["-I" ++ odir]
++ ["-I" ++ dir | dir <- PD.includeDirs bi]
++ ["-optP" ++ opt | opt <- cppOptions bi]
++ [ "-optP-include", "-optP"++ (autogenModulesDir lbi </> cppHeaderName) ]
++ [ "-#include \"" ++ inc ++ "\"" | ghcVer < Version [6,11] []
, inc <- PD.includes bi ]
++ [ "-odir", odir, "-hidir", odir ]
++ concat [ ["-stubdir", odir] | ghcVer >= Version [6,8] [] ]
++ ghcPackageFlags lbi clbi
++ (case withOptimization lbi of
NoOptimisation -> []
NormalOptimisation -> ["-O"]
MaximumOptimisation -> ["-O2"])
++ (case PD.objcGCMode bi of
PD.ObjcGCDisabled -> []
PD.ObjcGCOptional -> ["-optc-fobjc-gc"]
PD.ObjcGCMandatory -> ["-optc-fobjc-gc-only"])
++ hcOptions GHC bi
++ languageToFlags (compiler lbi) (defaultLanguage bi)
++ extensionsToFlags (compiler lbi) (defaultExtensions bi)
where
ghcVer = compilerVersion (compiler lbi)
ghcPackageFlags :: LocalBuildInfo -> ComponentLocalBuildInfo -> [String]
ghcPackageFlags lbi clbi
| ghcVer >= Version [6,11] []
= concat [ ["-package-id", display ipkgid]
| (ipkgid, _) <- componentPackageDeps clbi ]
| otherwise = concat [ ["-package", display pkgid]
| (_, pkgid) <- componentPackageDeps clbi ]
where
ghcVer = compilerVersion (compiler lbi)
ghcPackageDbOptions :: PackageDBStack -> [String]
ghcPackageDbOptions dbstack = case dbstack of
(GlobalPackageDB:UserPackageDB:dbs) -> concatMap specific dbs
(GlobalPackageDB:dbs) -> "-no-user-package-conf"
: concatMap specific dbs
_ -> ierror
where
specific (SpecificPackageDB db) = [ "-package-conf", db ]
specific _ = ierror
ierror = error ("internal error: unexpected package db stack: " ++ show dbstack)
constructCcCmdLine :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> FilePath -> Verbosity -> Bool -> Bool
->(FilePath,[String])
constructCcCmdLine lbi bi clbi pref filename verbosity dynamic profiling
= let odir | compilerVersion (compiler lbi) >= Version [6,4,1] [] = pref
| otherwise = pref </> takeDirectory filename
-- ghc 6.4.1 fixed a bug in -odir handling
-- for C compilations.
in
(odir,
ghcCcOptions lbi bi clbi odir
++ (if verbosity >= deafening then ["-v"] else [])
++ ["-c",filename]
-- Note: When building with profiling enabled, we pass the -prof
-- option to ghc here when compiling C code, so that the PROFILING
-- macro gets defined. The macro is used in ghc's Rts.h in the
-- definitions of closure layouts (Closures.h).
++ ["-dynamic" | dynamic]
++ ["-prof" | profiling])
ghcCcOptions :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> [String]
ghcCcOptions lbi bi clbi odir
= ["-I" ++ dir | dir <- odir : PD.includeDirs bi]
++ ghcPackageDbOptions (withPackageDB lbi)
++ ghcPackageFlags lbi clbi
++ ["-optc" ++ opt | opt <- PD.ccOptions bi]
++ (case PD.objcGCMode bi of
PD.ObjcGCDisabled -> []
PD.ObjcGCOptional -> ["-optc-fobjc-gc"]
PD.ObjcGCMandatory -> ["-optc-fobjc-gc-only"])
++ (case withOptimization lbi of
NoOptimisation -> []
_ -> ["-optc-O2"])
++ ["-odir", odir]
mkGHCiLibName :: PackageIdentifier -> String
mkGHCiLibName lib = "HS" ++ display lib <.> "o"
-- -----------------------------------------------------------------------------
-- Installing
-- |Install executables for GHC.
installExe :: Verbosity
-> LocalBuildInfo
-> InstallDirs FilePath -- ^Where to copy the files to
-> FilePath -- ^Build location
-> (FilePath, FilePath) -- ^Executable (prefix,suffix)
-> PackageDescription
-> Executable
-> IO ()
installExe verbosity lbi installDirs buildPref (progprefix, progsuffix) _pkg exe = do
let binDir = bindir installDirs
createDirectoryIfMissingVerbose verbosity True binDir
let exeFileName = exeName exe <.> exeExtension
fixedExeBaseName = progprefix ++ exeName exe ++ progsuffix
installBinary dest = do
installExecutableFile verbosity
(buildPref </> exeName exe </> exeFileName)
(dest <.> exeExtension)
stripExe verbosity lbi exeFileName (dest <.> exeExtension)
installBinary (binDir </> fixedExeBaseName)
stripExe :: Verbosity -> LocalBuildInfo -> FilePath -> FilePath -> IO ()
stripExe verbosity lbi name path = when (stripExes lbi) $
case lookupProgram stripProgram (withPrograms lbi) of
Just strip -> rawSystemProgram verbosity strip args
Nothing -> unless (buildOS == Windows) $
-- Don't bother warning on windows, we don't expect them to
-- have the strip program anyway.
warn verbosity $ "Unable to strip executable '" ++ name
++ "' (missing the 'strip' program)"
where
args = path : case buildOS of
OSX -> ["-x"] -- By default, stripping the ghc binary on at least
-- some OS X installations causes:
-- HSbase-3.0.o: unknown symbol `_environ'"
-- The -x flag fixes that.
_ -> []
-- |Install for ghc, .hi, .a and, if --with-ghci given, .o
installLib :: Verbosity
-> LocalBuildInfo
-> FilePath -- ^install location
-> FilePath -- ^install location for dynamic librarys
-> FilePath -- ^Build location
-> PackageDescription
-> Library
-> IO ()
installLib verbosity lbi targetDir dynlibTargetDir builtDir pkg lib = do
-- copy .hi files over:
let copyHelper installFun src dst n = do
createDirectoryIfMissingVerbose verbosity True dst
installFun verbosity (src </> n) (dst </> n)
copy = copyHelper installOrdinaryFile
copyShared = copyHelper installExecutableFile
copyModuleFiles ext =
findModuleFiles [builtDir] [ext] (libModules lib)
>>= installOrdinaryFiles verbosity targetDir
ifVanilla $ copyModuleFiles "hi"
ifProf $ copyModuleFiles "p_hi"
ifShared $ copyModuleFiles "dyn_hi"
-- copy the built library files over:
ifVanilla $ copy builtDir targetDir vanillaLibName
ifProf $ copy builtDir targetDir profileLibName
ifGHCi $ copy builtDir targetDir ghciLibName
ifShared $ copyShared builtDir dynlibTargetDir sharedLibName
-- run ranlib if necessary:
ifVanilla $ updateLibArchive verbosity lbi
(targetDir </> vanillaLibName)
ifProf $ updateLibArchive verbosity lbi
(targetDir </> profileLibName)
where
vanillaLibName = mkLibName pkgid
profileLibName = mkProfLibName pkgid
ghciLibName = mkGHCiLibName pkgid
sharedLibName = mkSharedLibName pkgid (compilerId (compiler lbi))
pkgid = packageId pkg
hasLib = not $ null (libModules lib)
&& null (cSources (libBuildInfo lib))
ifVanilla = when (hasLib && withVanillaLib lbi)
ifProf = when (hasLib && withProfLib lbi)
ifGHCi = when (hasLib && withGHCiLib lbi)
ifShared = when (hasLib && withSharedLib lbi)
-- | On MacOS X we have to call @ranlib@ to regenerate the archive index after
-- copying. This is because the silly MacOS X linker checks that the archive
-- index is not older than the file itself, which means simply
-- copying/installing the file breaks it!!
--
updateLibArchive :: Verbosity -> LocalBuildInfo -> FilePath -> IO ()
updateLibArchive verbosity lbi path
| buildOS == OSX = do
(ranlib, _) <- requireProgram verbosity ranlibProgram (withPrograms lbi)
rawSystemProgram verbosity ranlib [path]
| otherwise = return ()
-- -----------------------------------------------------------------------------
-- Registering
registerPackage
:: Verbosity
-> InstalledPackageInfo
-> PackageDescription
-> LocalBuildInfo
-> Bool
-> PackageDBStack
-> IO ()
registerPackage verbosity installedPkgInfo _pkg lbi _inplace packageDbs = do
let Just ghcPkg = lookupProgram ghcPkgProgram (withPrograms lbi)
HcPkg.reregister verbosity ghcPkg packageDbs (Right installedPkgInfo)
|
IreneKnapp/Faction
|
libfaction/Distribution/Simple/GHC.hs
|
Haskell
|
bsd-3-clause
| 53,821
|
-- | == Single URI Authorization
--
-- There are cases in which limited and short-term access to a
-- protected resource is granted to a third party which does not have
-- access to the shared credentials. For example, displaying a
-- protected image on a web page accessed by anyone. __Hawk__ provides
-- limited support for such URIs in the form of a /bewit/ — a URI
-- query parameter appended to the request URI which contains the
-- necessary credentials to authenticate the request.
--
-- Because of the significant security risks involved in issuing such
-- access, bewit usage is purposely limited only to GET requests and
-- for a finite period of time. Both the client and server can issue
-- bewit credentials, however, the server should not use the same
-- credentials as the client to maintain clear traceability as to who
-- issued which credentials.
--
-- In order to simplify implementation, bewit credentials do not
-- support single-use policy and can be replayed multiple times within
-- the granted access timeframe.
--
-- This module collects the URI authorization functions in a single
-- module, to mirror the @Hawk.uri@ module of the javascript
-- implementation.
module Network.Hawk.URI
( authenticate
, middleware
, getBewit
) where
import Control.Monad.IO.Class (MonadIO)
import Network.Wai (Request)
import Network.Hawk.Types
import Network.Hawk.Server (authenticateBewitRequest, authenticateBewit, CredentialsFunc, AuthReqOpts, AuthOpts, AuthResult, HawkReq)
import Network.Hawk.Middleware (bewitAuth)
import Network.Hawk.Client (getBewit)
-- | See 'Network.Hawk.Server.authenticateBewitRequest'.
authenticateRequest :: MonadIO m => AuthReqOpts -> CredentialsFunc m t
-> Request -> m (AuthResult t)
authenticateRequest = authenticateBewitRequest
-- | See 'Network.Hawk.Server.authenticateBewit'.
authenticate :: MonadIO m => AuthOpts -> CredentialsFunc m t
-> HawkReq -> m (AuthResult t)
authenticate = authenticateBewit
-- | See 'Network.Hawk.Middleware.bewitAuth'.
middleware = bewitAuth
|
rvl/hsoz
|
src/Network/Hawk/URI.hs
|
Haskell
|
bsd-3-clause
| 2,098
|
{-# LANGUAGE RecordWildCards, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, TupleSections #-}
module Aws.SimpleDb.Commands.GetAttributes
where
import Aws.Response
import Aws.Signature
import Aws.SimpleDb.Info
import Aws.SimpleDb.Metadata
import Aws.SimpleDb.Model
import Aws.SimpleDb.Query
import Aws.SimpleDb.Response
import Aws.Transaction
import Aws.Util
import Control.Applicative
import Control.Monad
import Data.Maybe
import Text.XML.Cursor (($//), (&|))
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Text.XML.Cursor as Cu
data GetAttributes
= GetAttributes {
gaItemName :: T.Text
, gaAttributeName :: Maybe T.Text
, gaConsistentRead :: Bool
, gaDomainName :: T.Text
}
deriving (Show)
data GetAttributesResponse
= GetAttributesResponse {
garAttributes :: [Attribute T.Text]
}
deriving (Show)
getAttributes :: T.Text -> T.Text -> GetAttributes
getAttributes item domain = GetAttributes { gaItemName = item, gaAttributeName = Nothing, gaConsistentRead = False, gaDomainName = domain }
instance SignQuery GetAttributes where
type Info GetAttributes = SdbInfo
signQuery GetAttributes{..}
= sdbSignQuery $
[("Action", "GetAttributes"), ("ItemName", T.encodeUtf8 gaItemName), ("DomainName", T.encodeUtf8 gaDomainName)] ++
maybeToList (("AttributeName",) <$> T.encodeUtf8 <$> gaAttributeName) ++
(guard gaConsistentRead >> [("ConsistentRead", awsTrue)])
instance ResponseConsumer r GetAttributesResponse where
type ResponseMetadata GetAttributesResponse = SdbMetadata
responseConsumer _ = sdbResponseConsumer parse
where parse cursor = do
sdbCheckResponseType () "GetAttributesResponse" cursor
attributes <- sequence $ cursor $// Cu.laxElement "Attribute" &| readAttribute
return $ GetAttributesResponse attributes
instance Transaction GetAttributes GetAttributesResponse
|
jgm/aws
|
Aws/SimpleDb/Commands/GetAttributes.hs
|
Haskell
|
bsd-3-clause
| 2,206
|
module HaskQuery (
module HaskQuery.AutoIndex,
Relation,
Cont,
empty,
emptyWithIndex,
reindex,
runQuery,
select,
runQueryM,
executeM,
selectM,
filterM,
selectWithIndex,
selectDynamic,
selectDynamicWithTypeM,
insert,
insertRows,
insertInto,
update,
delete
) where
import qualified Data.IntMap.Lazy
import qualified Data.List
import qualified Control.Monad.Trans.Cont
import qualified Data.Typeable
import qualified Data.Dynamic
import qualified Data.Proxy
import HaskQuery.AutoIndex
data Relation a b = Relation { _relation :: Data.IntMap.Lazy.IntMap a , _lastRowId :: Int, _indices :: UpdatableIndex a b} deriving (Show)
type Cont r a = Control.Monad.Trans.Cont.Cont r a
empty :: Relation a ()
empty = Relation { _relation = Data.IntMap.Lazy.empty, _lastRowId = 0, _indices = emptyIndex }
emptyWithIndex :: UpdatableIndex a c -> Relation a c
emptyWithIndex index = reindex empty index
reindex :: Relation a b -> UpdatableIndex a c -> Relation a c
reindex indexedRelation newIndex =
let originalRelation = _relation indexedRelation
in indexedRelation { _relation = originalRelation, _indices = updateAutoWithInput newIndex $ Insert $ InsertSet {inserted = originalRelation} }
runQuery :: Control.Monad.Trans.Cont.Cont ([a] -> [a]) a -> [a]
runQuery query = (Control.Monad.Trans.Cont.runCont query (\value -> (\list -> value : list))) []
select :: Relation a c -> Control.Monad.Trans.Cont.Cont (b -> b) a
select relation = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> Data.IntMap.Lazy.foldl (\foldSeed value -> continuation value foldSeed) seed (_relation relation)))
filterM :: Monad m => Bool -> Control.Monad.Trans.Cont.Cont (a -> m a) ()
filterM predicate = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> if predicate then (continuation () seed ) else return seed))
runQueryM :: Monad m => Control.Monad.Trans.Cont.Cont ([a] -> m [a]) a -> m [a]
runQueryM query = (Control.Monad.Trans.Cont.runCont query (\value -> (\list -> return (value : list)))) []
selectM :: Monad m => Relation a c -> Control.Monad.Trans.Cont.Cont (b -> m b) a
selectM relation = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> Data.IntMap.Lazy.foldl (\foldSeed value -> foldSeed >>= continuation value) (return seed) (_relation relation)))
executeM :: Monad m => m a -> Control.Monad.Trans.Cont.Cont (b -> m b) a
executeM computation = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> do
value <- computation
result <- continuation value seed
return result))
selectWithIndex :: (c -> indexValue -> Control.Monad.Trans.Cont.Cont (b -> b) Int) -> Relation a c -> indexValue -> Control.Monad.Trans.Cont.Cont (b -> b) a
selectWithIndex indexAccessor relation indexValue = do
rowId <- indexAccessor (readAuto $ _indices relation) indexValue
return $ (_relation relation) Data.IntMap.Lazy.! rowId
selectDynamic :: (Data.Typeable.Typeable a) => Data.Dynamic.Dynamic -> Control.Monad.Trans.Cont.Cont (b->b) a
selectDynamic value = Control.Monad.Trans.Cont.cont (\continuation -> (case Data.Dynamic.fromDynamic value of Just typed -> continuation typed ; Nothing -> id))
selectDynamicWithType :: (Data.Typeable.Typeable a) => Data.Proxy.Proxy a -> Data.Dynamic.Dynamic -> Control.Monad.Trans.Cont.Cont (b->b) a
selectDynamicWithType proxy value = selectDynamic value
selectDynamicWithTypeM :: (Data.Typeable.Typeable a, Monad m) => Data.Proxy.Proxy a -> Data.Dynamic.Dynamic -> Control.Monad.Trans.Cont.Cont (b->m b) a
selectDynamicWithTypeM proxy value = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> (case Data.Dynamic.fromDynamic value of Just typed -> continuation typed seed ; Nothing -> return seed)))
insert :: Relation a b -> a -> Relation a b
insert indexedRelation item =
let newRowId = (_lastRowId indexedRelation) + 1
updatedRelation = Data.IntMap.Lazy.insert newRowId item (_relation indexedRelation)
updatedIndex = updateAutoWithInput (_indices indexedRelation) (Insert $ InsertSet { inserted = Data.IntMap.Lazy.singleton newRowId item})
in
Relation { _relation = updatedRelation, _lastRowId = newRowId, _indices = updatedIndex}
insertRows :: Relation a b -> [a] -> Relation a b
insertRows indexedRelation rows = Data.List.foldl' (insert) indexedRelation rows
insertInto :: Relation a b -> Control.Monad.Trans.Cont.Cont (Relation a b -> Relation a b) a -> Relation a b
insertInto indexedRelation insertContinuation =
Control.Monad.Trans.Cont.runCont insertContinuation (\ row -> (\seedIndexedRelation -> insert seedIndexedRelation row)) indexedRelation
update :: Relation a b-> (a -> Bool) -> (a -> a) -> Relation a b
update indexedRelation predicate updateFunction =
let originalRelation = (_relation indexedRelation)
affectedRows = Data.IntMap.Lazy.filter predicate originalRelation
updateMap = Data.IntMap.Lazy.map (\row -> (row, updateFunction row)) affectedRows
updatedRows = Data.IntMap.Lazy.map (\ (row, updatedRow) -> updatedRow) updateMap
updatedIndex = updateAutoWithInput (_indices indexedRelation) $ Update $ UpdateSet { updated = updateMap }
in
indexedRelation { _relation = updatedRows, _indices = updatedIndex }
delete :: Relation a b -> (a -> Bool) -> Relation a b
delete indexedRelation predicate =
let
originalRelation = (_relation indexedRelation)
affectedRows = Data.IntMap.Lazy.filter predicate originalRelation
updatedRelation = Data.IntMap.Lazy.difference originalRelation affectedRows
updatedIndex = updateAutoWithInput (_indices indexedRelation) $ Delete $ DeleteSet { deleted = affectedRows }
in
indexedRelation { _relation = updatedRelation, _indices = updatedIndex}
|
stevechy/haskellEditor
|
ext-src/HaskQueryPackage/HaskQuery.hs
|
Haskell
|
bsd-3-clause
| 5,788
|
{- *** MOCS-COPYRIGHT-NOTICE-BEGIN ***
-
- This copyright notice is auto-generated by ./add-copyright-notice.
- Additional copyright notices must be added below the last line of this notice.
-
- MoCS (https://lewis.cs.uni-saarland.de/tools/mocs/): "haskell-frontend/Temporal.hs".
- The content of this file is copyright of Saarland University -
- Copyright (C) 2009 Saarland University, Reactive Systems Group, Lars Kuhtz.
-
- This file is part of MoCS (https://lewis.cs.uni-saarland.de/tools/mocs/).
-
- License: three-clause BSD style license.
- The license text can be found in the file LICENSE.
-
- *** MOCS-COPYRIGHT-NOTICE-END *** -}
{-# LANGUAGE FlexibleContexts #-}
{- Logic:
- * Prop
- * WeakReg (weak)
- * StrongReg (strong)
-
- * Negate
- * And
- * Or
-
- * Next (weak)
- * BNext (weak)
- * WNext (strong)
- * WBNext (strong)
-
- * Until (strong) (sugar)
- * Waitfor (weak) (sugar)
- * BUntil (strong)
- * BWaitfor (weak)
-
- * Release (weak) (sugar)
- * SRelease (strong) (sugar)
- * BRelease (weak)
- * SBRelease (strong)
-
- * Globally (weak) (sugar)
- * BGlobally (weak)
- * SBGlobally (strong)
-
- * Eventually (strong) (sugar)
- * BEventually (strong)
- * WBEventually (weak)
-
- * Abort
- * Simplies
-}
module Temporal
( Formula(..)
, mkProp
, mkWeakReg
, mkStrongReg
, mkNegate
, mkAnd
, mkOr
, mkNext
, mkBNext
, mkWNext
, mkWBNext
, mkUntil
, mkWaitfor
, mkBUntil
, mkBWaitfor
, mkRelease
, mkSRelease
, mkBRelease
, mkSBRelease
, mkGlobally
, mkBGlobally
, mkSBGlobally
, mkEventually
, mkBEventually
, mkWBEventually
, mkAbort
, mkSImplies
, mkImplies
, mkEquiv
, formula
, parser
, pushNegations
, simplify
--, unfoldLevelF
--, unfoldF
--, unfoldAllF
--, unfoldBoundedF
, pushNextRec
, allSubf
, allLeaves
, dual
, rec
, toString
, allRegProps
, allRegs
, allProps
, isBounded
)
where
import qualified Text.ParserCombinators.Parsec as P
import Text.ParserCombinators.Parsec.Expr
import Data.Typeable
import Data.List
import PSLLexer
import ToString
import PSLFragment
import Ordinal
-- usualy reg should be defined upon prop as well.
data Formula reg prop
= Prop prop
| WeakReg (reg prop)
| StrongReg (reg prop)
| Negate (Formula reg prop)
| And (Formula reg prop) (Formula reg prop)
| Or (Formula reg prop) (Formula reg prop)
| Next Bound (Formula reg prop)
| WNext Bound (Formula reg prop)
| Until Bound (Formula reg prop) (Formula reg prop)
| Waitfor Bound (Formula reg prop) (Formula reg prop)
| Release Bound (Formula reg prop) (Formula reg prop)
| SRelease Bound (Formula reg prop) (Formula reg prop)
| Globally Bound (Formula reg prop)
| SGlobally Bound (Formula reg prop)
| Eventually Bound (Formula reg prop)
| WEventually Bound (Formula reg prop)
| Abort (Formula reg prop) prop
| SImplies (reg prop) (Formula reg prop)
deriving (Eq, Ord,Show)
instance (Typeable (reg prop), Typeable prop) => Typeable (Formula reg prop) where
typeOf f = mkTyConApp (mkTyCon "Formula") [typeOf f]
instance (PSLFragment (reg prop), PSLFragment prop) => PSLFragment (Formula reg prop) where
horizon = horizon'
dual = dual'
subfmap = rec
subf = subf'
parser = formula
constant = mkProp . constant
simplify = simplify'
constr = constr'
-- horizon
horizon' (Prop p) = horizon p
horizon' (WeakReg r) = horizon r
horizon' (StrongReg r) = horizon r
horizon' (Negate f) = horizon' f
horizon' (And f g) = max (horizon' f) (horizon' g)
horizon' (Or f g) = max (horizon' f) (horizon' g)
horizon' (Next b f) = horizon' f + b
horizon' (WNext b f) = horizon' f + b
horizon' (Until b f g) = max (b + horizon' f) ((b - 1) + horizon' g)
horizon' (Waitfor b f g) = max (b + horizon' f) ((b - 1) + horizon' g)
horizon' (Release b f g) = max (b + horizon' f) (b + horizon' g)
horizon' (SRelease b f g) = max (b + horizon' f) (b + horizon' g)
horizon' (Globally b f) = horizon' f + b
horizon' (SGlobally b f) = horizon' f + b
horizon' (Eventually b f) = horizon' f + b
horizon' (WEventually b f) = horizon' f + b
horizon' (Abort f _) = horizon' f
horizon' (SImplies r f) = (horizon r) + (horizon' f) - 1
-- generator
mkProp e = Prop e
mkWeakReg s = WeakReg s
mkStrongReg b = StrongReg b
mkNegate x = Negate x
mkAnd x y | x < y = And x y
| otherwise = And y x
mkOr x y | x < y = Or x y
| otherwise = Or y x
mkNext x = Next 1 x
mkWNext x = WNext 1 x
mkBNext b x = Next b x
mkWBNext b x = WNext b x
mkUntil x y = Until Infty x y
mkWaitfor x y = Waitfor Infty x y
mkBUntil b x y = Until b x y
mkBWaitfor b x y = Waitfor b x y
mkRelease x y = Release Infty x y
mkSRelease x y = SRelease Infty x y
mkBRelease b x y = Release b x y
mkSBRelease b x y = SRelease b x y
mkGlobally x = Globally Infty x
mkBGlobally b x = Globally b x
mkSBGlobally b x = SGlobally b x
mkEventually x = Eventually Infty x
mkBEventually b x = Eventually b x
mkWBEventually b x = WEventually b x
mkAbort f e = Abort f e
mkSImplies r f = SImplies r f
-- suguar
mkImplies x y = mkOr (mkNegate x) y
mkEquiv x y = mkAnd (mkImplies x y) (mkImplies y x)
-------------------------------------------------------------------------------
-- Note: we maintain arguments of associative operators (and, or) ordered.
-- Alternatively we could have coded this into the instanciation of EQ.
-- The ordered approach is probably more efficient. It Requires, however, that
-- The mk-Constructors are always used to create new Formulas.
-------------------------------------------------------------------------------
-- constr
constr' f = case f of
(Prop _) -> const f
(StrongReg _) -> const f
(WeakReg _) -> const f
(Negate _) -> un mkNegate
(And _ _) -> bin mkAnd
(Or _ _) -> bin mkOr
(Next b _) -> bun mkBNext b
(WNext b _) -> bun mkWBNext b
(Until b _ _) -> bbin mkBUntil b
(Waitfor b _ _) -> bbin mkBWaitfor b
(Release b _ _) -> bbin mkBRelease b
(SRelease b _ _) -> bbin mkSBRelease b
(Globally b _) -> bun mkBGlobally b
(SGlobally b _) -> bun mkSBGlobally b
(Eventually b _) -> bun mkBEventually b
(WEventually b _) -> bun mkWBEventually b
(Abort _ e) -> (\(x:_) -> mkAbort x e)
(SImplies r _) -> (\(x:_) -> mkSImplies r x)
where
un c = \(x:_) -> c x
bun c b = \(x:_) -> c b x
bin c = \(l:r:_) -> c l r
bbin c b = \(l:r:_) -> c b l r
-------------------------------------------------------------------------------
-- show
-- Currently prints out format used by parser
-- TODO set parenthesis only where needed
instance (Show prop, Show (reg prop), ToString (reg prop), ToString prop) => ToString (Formula reg prop) where
toString f = case f of
(Prop e) -> toString e
(StrongReg r) -> un "\\strong" r
(WeakReg r) -> toString r
(Negate f) -> un "\\not" f
(And f g) -> bin "\\and" f g
(Or f g) -> bin "\\or" f g
(Next Infty f) -> un "\\N" f
(WNext Infty f) -> un "\\wN" f
(Next b f) -> bbin "\\BN" b f
(WNext b f) -> bbin "\\wBN" b f
(Until Infty f g) -> bin "\\U" f g
(Waitfor Infty f g) -> bin "\\W" f g
(Until b f g) -> tri "\\BU" b f g
(Waitfor b f g) -> tri "\\BW" b f g
(Release Infty f g) -> bin "\\R" f g
(SRelease Infty f g) -> bin "\\sR" f g
(Release b f g) -> tri "\\BR" b f g
(SRelease b f g) -> tri "\\sBR" b f g
(Globally Infty f) -> un "\\G" f
(Globally b f) -> bbin "\\BG" b f
(SGlobally b f) -> bbin "\\sBG" b f
(Eventually Infty f) -> un "\\F" f
(Eventually b f) -> bbin "\\BF" b f
(WEventually b f) -> bbin "\\wBF" b f
(Abort f e) -> bin "\\abort" f e
(SImplies r f) -> bin "\\simplies" r f
where
un o f = o ++ " " ++ toString f
bin o f g = "(" ++ toString f ++ " " ++ o ++ " " ++ toString g ++ ")"
bbin o b f = o ++ " " ++ p b ++ " " ++ toString f
tri o b f g = "(" ++ toString f ++ " " ++ o ++ " " ++ p b ++ " " ++ toString g ++ ")"
p b = toString b
-------------------------------------------------------------------------------
-- usefull for variable substitution
-- subformulas as list
subf' (Negate f) = [f]
subf' (Or f g) = [f, g]
subf' (And f g) = [f, g]
subf' (Next _ f) = [f]
subf' (WNext _ f) = [f]
subf' (Globally _ f) = [f]
subf' (SGlobally _ f) = [f]
subf' (Eventually _ f) = [f]
subf' (WEventually _ f) = [f]
subf' (Until _ f g) = [f, g]
subf' (Waitfor _ f g) = [f, g]
subf' (Release _ f g) = [f, g]
subf' (SRelease _ f g) = [f, g]
subf' (Abort f _) = [f]
subf' (SImplies _ f) = [f]
subf' _ = []
allRegs :: Formula reg prop -> [Formula reg prop]
allRegs h = case h of
(WeakReg _) -> return h
(StrongReg _) -> return h
_ -> subf' h >>= allRegs
allProps :: Formula reg prop -> [Formula reg prop]
allProps h = case h of
(Prop _) -> return h
_ -> subf' h >>= allProps
allRegProps :: Formula reg prop -> [Formula reg prop]
allRegProps h = case h of
(WeakReg _) -> return h
(StrongReg _) -> return h
(Prop _) -> return h
_ -> subf' h >>= allRegProps
-- Usefull for mutual recursive defintions (see e.g. pushNegations)
rec :: (Ord (reg prop), Ord prop, PSLFragment (Formula reg prop)) =>
(Formula reg prop -> Formula reg prop) -> Formula reg prop -> Formula reg prop
rec a f = if atomic f then f else (constr f) (map a (subf f))
-------------------------------------------------------------------------------
-- Dualities
dual' (Prop f) = mkNegate (mkProp f)
dual' (WeakReg f) = mkNegate (mkWeakReg f)
dual' (StrongReg f) = mkNegate (mkStrongReg f)
dual' (Negate f) = f
dual' (Or f g) = mkAnd (dual f) (dual g)
dual' (And f g) = mkOr (dual f) (dual g)
dual' (Next b f) = mkWBNext b (dual f)
dual' (WNext b f) = mkBNext b (dual f)
dual' (Globally b f) = mkBEventually b (dual f)
dual' (SGlobally b f) = mkWBEventually b (dual f)
dual' (Eventually b f) = mkBGlobally b (dual f)
dual' (WEventually b f) = mkSBGlobally b (dual f)
dual' (Until b f g) = mkBRelease b (dual f) (dual g)
dual' (Waitfor b f g) = mkSBRelease b (dual f) (dual g)
dual' (Release b f g) = mkBUntil b (dual f) (dual g)
dual' (SRelease b f g) = mkBWaitfor b (dual f) (dual g)
dual' (Abort f e) = mkNegate (mkAbort f e)
dual' (SImplies r f) = (mkNegate (StrongReg r)) `mkOr` (r `mkSImplies` (dual f))
-------------------------------------------------------------------------------
-- Push negations to state level
pushNegations (Negate f) = dual f
pushNegations f = rec pushNegations f
-------------------------------------------------------------------------------
-- Push Next-Operators
pushNext h = case h of
(Next b (Negate f)) -> mkNegate $ mkWBNext b f
(WNext b (Negate f)) -> mkNegate $ mkBNext b f
(Next b f) -> rec (mkBNext b) f
(WNext b f) -> rec (mkWBNext b) f
_ -> h
pushNextRec h = bottomUpRec p' h
where
p' h = case h of { (Next b f) -> topDownRec pushNext (mkBNext b f); _ -> h}
-------------------------------------------------------------------------------
-- misc
isBinary f = length (subf f) == 2
isBounded (Next u _) = isFinite u
isBounded (WNext u _) = isFinite u
isBounded (Globally u _) = isFinite u
isBounded (SGlobally u _) = isFinite u
isBounded (Eventually u _) = isFinite u
isBounded (WEventually u _) = isFinite u
isBounded (Until u _ _) = isFinite u
isBounded (Waitfor u _ _) = isFinite u
isBounded (Release u _ _) = isFinite u
isBounded (SRelease u _ _) = isFinite u
isBounded _ = True
allEq [] = True
allEq [_] = True
allEq (a:b:t) = (a == b) && (allEq (b:t))
-------------------------------------------------------------------------------
-- Simplification rules
simplify' f = bottomUpRec (simple5 . simple4 . simple3 . simple2 . simple1) f
simple1 (Abort f e) = mkAbort f e
simple1 (SImplies r f) = mkSImplies r f
simple1 h = if isBinary h && allEq (subf h) then head (subf h) else h
-- (Constants are not part of PSL any more)
simple2 = id
{-
-- Dualities for binary operators
simple3 (Or f g) | isDual f g = mkConst True
| otherwise = mkOr f g
simple3 (And f g) | isDual f g = mkConst False
| otherwise = mkAnd f g
simple3 (BUntil b f g) | isDual f g = mkBUntil b (Const True) g
| otherwise = mkBUntil b f g
simple3 (BRelease b f g) | isDual f g = mkConst True
| otherwise = mkBRelease b f g
simple3 (WBUntil b f g) | isDual f g = mkWBUntil b (Const True) g
| otherwise = mkWBUntil b f g
simple3 (WBRelease b f g) | isDual f g = mkConst True
| otherwise = mkWBRelease b f g
simple3 f = f
-}
simple3 = id
-- Negation
simple4 (Negate f) = dual f
simple4 f = f
-- temporal nesting with equal subformulas
{-
simple5 x = case x of
(f `Until` (g `Until` h)) -> if f == h || f == g then (g `mkUntil` h) else x
((f `Until` g) `Until` h) -> if f == h then (g `mkUntil` f) else
if g == h then (f `mkUntil` g) else x
(BUntil b0 f (BUntil b1 g h)) -> if f == h || f == g then (BUntil (b0+b1) g h) else x
(BUntil b0 (BUntil b1 f g) h) -> if f == h then (BUntil b0 g f) else
if g == h then (BUntil b1 f g) else x
-- TODO weak version
(f `Release` (g `Release` h)) -> if f == h then (h `mkRelease` g) else
if f == g then (g `mkRelease` h) else x
((f `Release` g) `Release` h) -> if f == h || g == h then (f `mkRelease` g) else x
-- TODO bounded version
-- TODO weak version
_ -> x
-}
simple5 = id
--balance (And (And f g) h) =
-- TODO: flatten it into a list (use list-monad), elimiate duplicate subformulas,
-- check for contradictions and rebuild a balanced tree.
-- TODO: add more simplification rules in a more systematic way.
-------------------------------------------------------------------------------
-- Unfold temporal operators
{-
-- unfold top level operator
unfoldF f = unfoldF' unfoldF f
-- unfold f i steps
unfoldLevelF 0 f = f
unfoldLevelF i f = unfoldF' (unfoldLevelF (i-1)) f
-- recursively unfold all operators
unfoldAllF f = bottomUpRec unfoldF f
-- recursively unfold all bounded operators
unfoldBoundedF f = bottomUpRec (\x -> if isBounded x then unfoldF x else x) f
-- Fixpoint characterization
unfoldF' r (BUntil (0,0) f g) = g
unfoldF' r (BUntil (_,0) f g) = error "lower bound must not be greater than upper bound"
unfoldF' r (BUntil (0,u) f g) = g `mkOr` (f `mkAnd` (mkNext (r (mkBUntil (0,u-1) f g))))
unfoldF' r (BUntil (l,u) f g) = mkNext (mkBUntil (l-1,u-1) f g)
unfoldF' r (WBUntil (0,0) f g) = g
unfoldF' r (WBUntil (_,0) f g) = error "lower bound must not be greater than upper bound"
unfoldF' r (WBUntil (0,u) f g) = g `mkOr` (f `mkAnd` (mkWNext (r (mkBUntil (0,u-1) f g))))
unfoldF' r (WBUntil (l,u) f g) = mkWNext (mkWBUntil (l-1,u-1) f g)
unfoldF' r (BRelease (0,0) f g) = g
unfoldF' r (BRelease (_,0) f g) = error "lower bound must not be greater than upper bound"
unfoldF' r (BRelease (0,u) f g) = g `mkAnd` (f `mkOr` (mkNext (r (mkBRelease (0,u-1) f g))))
unfoldF' r (BRelease (l,u) f g) = mkNext (mkBRelease (l-1,u-1) f g)
unfoldF' r (WBRelease (0,0) f g) = g
unfoldF' r (WBRelease (_,0) f g) = error "lower bound must not be greater than upper bound"
unfoldF' r (WBRelease (0,u) f g) = g `mkAnd` (f `mkOr` (mkWNext (r (mkWBRelease (0,u-1) f g))))
unfoldF' r (WBRelease (l,u) f g) = mkWNext (mkWBRelease (l-1,u-1) f g)
-- Causes a blowup in the formula (not in the ciruit!)
unfoldF' r (Abort (BUntil (0,0) f g) e) = ((mkProp e) `mkOr` (g `mkAbort`e))
unfoldF' r (Abort (BUntil (_,0) f g) e) = error "lower bound must not be greater than upper bound"
unfoldF' r (Abort (BUntil (0,u) f g) e) = ((mkProp e) `mkOr` ((g `mkAbort`e) `mkOr` ((f `mkAbort`e) `mkAnd` (mkNext (r ((mkBUntil (0,u-1) f g) `mkAbort` e))))))
unfoldF' r (Abort (BUntil (l,u) f g) e) = ((mkProp e) `mkOr` mkNext (mkAbort (mkBUntil (l-1,u-1) f g) e))
unfoldF' r (Abort (WBUntil (0,0) f g) e) = ((mkProp e) `mkOr` (g `mkAbort`e))
unfoldF' r (Abort (WBUntil (_,0) f g) e) = error "lower bound must not be greater than upper bound"
unfoldF' r (Abort (WBUntil (0,u) f g) e) = ((mkProp e) `mkOr` ((g `mkAbort`e) `mkOr` ((f `mkAbort`e) `mkAnd` (mkWNext (r ((mkBUntil (0,u-1) f g) `mkAbort` e))))))
unfoldF' r (Abort (WBUntil (l,u) f g) e) = ((mkProp e) `mkOr` mkWNext (mkAbort (mkWBUntil (l-1,u-1) f g) e))
unfoldF' r (Abort (BRelease (0,0) f g) e) = ((mkProp e) `mkOr` (g `mkAbort`e))
unfoldF' r (Abort (BRelease (_,0) f g) e) = error "lower bound must not be greater than upper bound"
unfoldF' r (Abort (BRelease (0,u) f g) e) = ((mkProp e) `mkOr` ((g `mkAbort`e) `mkAnd` ((f `mkAbort`e) `mkOr` (mkNext (r ((mkBRelease (0,u-1) f g) `mkAbort` e))))))
unfoldF' r (Abort (BRelease (l,u) f g) e) = ((mkProp e) `mkOr` mkNext (mkAbort (mkBRelease (l-1,u-1) f g) e))
unfoldF' r (Abort (WBRelease (0,0) f g) e) = ((mkProp e) `mkOr` (g `mkAbort`e))
unfoldF' r (Abort (WBRelease (_,0) f g) e) = error "lower bound must not be greater than upper bound"
unfoldF' r (Abort (WBRelease (0,u) f g) e) = ((mkProp e) `mkOr` ((g `mkAbort`e) `mkAnd` ((f `mkAbort`e) `mkOr` (mkWNext (r ((mkWBRelease (0,u-1) f g) `mkAbort` e))))))
unfoldF' r (Abort (WBRelease (l,u) f g) e) = ((mkProp e) `mkOr` mkWNext (mkAbort (mkWBRelease (l-1,u-1) f g) e))
-- There is no unfolding for SImplies :-(
unfoldF' r f = f
-}
-------------------------------------------------------------------------------
-- PSL-Parser
formula :: (PSLFragment (reg prop), PSLFragment prop) => P.Parser (Formula reg prop)
formula = buildExpressionParser table prefixExpr
P.<?> "PSL: formula"
atomicP :: (PSLFragment (reg prop), PSLFragment prop) => P.Parser (Formula reg prop)
atomicP = P.try (parser >>= return . mkWeakReg)
P.<|> (reservedOp "\\strong" >> parser >>= return . mkStrongReg)
P.<|> parens formula
P.<?> "PSL: atomic expression"
-- Note: all prefix operator have highest precedence
-- buildExpressionParser does not allow for nesting of prefixes of same precedence.
-- Moreover it seems that nesting of lower precedence prefix operators in higher precedence
-- prefix operators does not work as well. Seems that I do not understand something there ...
prefixExpr :: (PSLFragment (reg prop), PSLFragment prop) => P.Parser (Formula reg prop)
prefixExpr = P.try atomicP
P.<|> prefix "\\not" mkNegate
P.<|> pPrefix "\\BN" mkBNext
P.<|> pPrefix "\\wBN" mkWBNext
P.<|> prefix "\\N" mkNext
P.<|> prefix "\\wN" mkWNext
P.<|> pPrefix "\\BG" mkBGlobally
P.<|> pPrefix "\\BF" mkBEventually
P.<|> pPrefix "\\sBG" mkSBGlobally
P.<|> pPrefix "\\wBF" mkWBEventually
P.<|> prefix "\\G" mkGlobally
P.<|> prefix "\\F" mkEventually
P.<?> "PSL: prefix expression"
where
prefix name fun = (reservedOp name >> prefixExpr >>= return . fun)
pPrefix name fun = (reservedOp name >> do { b <- bound ; f <- prefixExpr ; return (fun b f) })
table :: (PSLFragment (reg prop), PSLFragment prop) => [[Operator Char () (Formula reg prop)]]
table = [ [binary "\\and" mkAnd AssocLeft]
, [binary "\\or" mkOr AssocLeft]
, [binary "\\implies" mkImplies AssocRight]
, [binary "\\equiv" mkEquiv AssocLeft]
, [pBinary "\\BU" mkBUntil AssocRight, pBinary "\\BR" mkBRelease AssocLeft]
, [pBinary "\\BW" mkBWaitfor AssocRight, pBinary "\\sBR" mkSBRelease AssocLeft]
, [binary "\\U" mkUntil AssocRight, binary "\\R" mkRelease AssocLeft]
, [binary "\\W" mkWaitfor AssocRight, binary "\\sR" mkSRelease AssocLeft]
, [abort]
, [simplies]
]
-- TODO: better move simplies to pslexpr
binary name fun assoc = Infix (reservedOp name >> return fun) assoc
pBinary name fun assoc = Infix (reservedOp name >> bound >>= return . fun) assoc
prefix name fun = Prefix (reservedOp name >> return fun)
-- pPrefix name fun = Prefix (reservedOp name >> bound >>= return . fun)
postfix name fun = Postfix (reservedOp name >> return fun)
abort :: (PSLFragment (reg prop), PSLFragment prop) => Operator Char () (Formula reg prop)
abort = Postfix (reservedOp "\\abort" >> parser >>= return . (flip mkAbort))
simplies :: (PSLFragment (reg prop), PSLFragment prop) => Operator Char () (Formula reg prop)
simplies = Prefix ( P.try $ do { x <- parser; reservedOp "\\simplies"; return (mkSImplies x)} )
-- bounds
-- bound :: P.GenParser Char st a
bound = boundExpr
boundExpr = buildExpressionParser boundTable boundTerm
boundTerm = (parens boundExpr) P.<|> (parseOrdinal)
boundTable :: OperatorTable Char () Ordinal
boundTable = [ [prefix "-" negate, prefix "+" id]
, [postfix "++" (+1)]
, [binary "*" (*) AssocLeft {-, binary "/" (div) AssocLeft-} ]
, [binary "+" (+) AssocLeft, binary "-" (-) AssocLeft]
]
|
larskuhtz/MoCS
|
haskell-frontend/Temporal.hs
|
Haskell
|
bsd-3-clause
| 21,085
|
-- | Physical constants.
module DSMC.Util.Constants
( amu
, avogadro
, boltzmann
, unigas
)
where
-- | Atomic mass unit 1.660538921(73)e-27, inverse to Avogadro's
-- constant.
amu :: Double
amu = 1.6605389217373737e-27
-- | Avogadro constant 6.02214129(27)e23
avogadro :: Double
avogadro = 6.0221412927272727e23
-- | Boltzmann constant 1.3806488(13)e-23
boltzmann :: Double
boltzmann = 1.3806488131313131e-23
-- | Universal gas constant.
unigas :: Double
unigas = boltzmann * avogadro
|
dzhus/dsmc
|
src/DSMC/Util/Constants.hs
|
Haskell
|
bsd-3-clause
| 515
|
{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-missing-signatures #-}
{-# LANGUAGE FlexibleInstances, DeriveFunctor, MultiParamTypeClasses, UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-}
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
-- |
-- | Module : First attempt at approximate mean
-- | Creator: Xiao Ling
-- | Created: 11/29/2015
-- | see : https://github.com/snoyberg/conduit
-- https://gist.github.com/thoughtpolice/3704890
-- http://blog.ezyang.com/2012/01/problem-set-the-codensity-transformation/
-- http://www.janis-voigtlaender.eu/papers/AsymptoticImprovementOfComputationsOverFreeMonads.pdf
-- https://gist.github.com/supki/3776752
-- |
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
module Play1129 where
import System.Random
import Data.List
import Data.Random
import Data.Conduit
import qualified Data.Conduit.List as Cl
import Control.Monad.Identity
import Control.Monad.State
import qualified Test.QuickCheck as T
import Core
import Statistics
{-----------------------------------------------------------------------------
1. make some examples
2. make
3. see if cassava can be put into a conduit
4. output Row type
see : http://stackoverflow.com/questions/2376981/haskell-types-frustrating-a-simple-average-function
------------------------------------------------------------------------------}
{-----------------------------------------------------------------------------
II. Approximate Median try ii
TODO: figure out uniform sampling without knowing length of stream
------------------------------------------------------------------------------}
-- * TODO: make this into an array since we'll be doing (!!) which is O(n) in list
-- * A reservoir is a list, its max allowed size, and its current size
-- * this deign is really bad, cannot gaurantee that currentSize is upToDate with length [a]
-- * dependent types would be good, or we can jsut get rid of current size
-- * or hide it in Core
data Reservoir a = R { run :: [a], size :: Int, currentSize :: Int }
deriving (Show,Functor,Eq)
instance Num a => T.Arbitrary (Reservoir a) where
-- * by construction, an arbitrary reservoir is always 1 item away from full
arbitrary = do
s <- T.arbitrary :: T.Gen (T.Positive Int)
let s' = T.getPositive s
let n = s' - 1 :: Int
return $ R (replicate n 0) s' n
shrink (R xs s n) = (\s' -> let n = max 0 (s' - 1) in (R (replicate n 0) s' n)) <$> T.shrink s
-- * constructor an empty resoivor of max size `s`
reservoir :: Int -> Reservoir a
reservoir s = R [] s 0
-- * check if reservoir is full
full :: Reservoir a -> Bool
full (R xs s n) = n >= s
-- * insert item, note the order
(>+) :: Reservoir a -> a -> Reservoir a
(>+) t@(R xs s n) x | full t = t
| otherwise = R (x:xs) s $ succ n
-- * remove the `i`th item from `r`
-- * if i > size then no item removed
(>-) :: Reservoir a -> Int -> Reservoir a
r@(R xs s n) >- i | i > n = r
| otherwise = undefined -- * really need to use array here
-- * sample an item `x` from the stream with uniform probability place in reservoir
-- * keep a conter `c` of elements seen
sampl :: Counter -> Sink a (StateT (Reservoir a) RVar) [a]
sampl i = do
ma <- await
case ma of
Nothing -> lift get >>= \r -> return $ run r
Just a -> do
lift $ store i a
sampl $ succ i
store :: Counter -> a -> StateT (Reservoir a) RVar ()
store i a = do
r <- get
case full r of
False -> put $ r >+ a
_ -> return ()
where p = (read . show $ size r :: Float)/i
-- * test m/2 - e*m < rank(y) < m/2 + e*m
-- * quickCheck Resoivor
-- * full resoivor is full
prop_fullReso :: Reservoir Int -> T.Property
prop_fullReso r = (T.==>) (size r > 0) $ full (r>+1) == True
---- * inserting into non-full resoivor resutls in additional element
prop_insertNotFull :: Reservoir Int -> T.Property
prop_insertNotFull r = (T.==>) (size r > 0) $ currentSize (r>+1) == currentSize r + 1
-- * inserting into full resoivor leaves it unchanged
prop_insertFull :: Reservoir Int -> T.Property
prop_insertFull r = (T.==>) (size r > 0) $ currentSize (r'>+1) == currentSize r'
where r' = r >+ 1
testReservoir :: IO ()
testReservoir = do
T.quickCheck $ prop_fullReso
T.quickCheck $ prop_insertFull
T.quickCheck $ prop_insertNotFull
{-----------------------------------------------------------------------------
II. Approximate Median Naive
------------------------------------------------------------------------------}
-- * setting problem: can you make this streaming? assuming you know m?
-- * can you do running uniform distribution?
-- * Find approximate eps e-median of list `xs`
-- * Setting: list given before hand for some parameter t
-- * Use : runRVar (naive xs e d) StdRandom
medianNaive :: (Floating a, Ord a) => [a] -> Eps -> Delta -> RVar a
medianNaive xs e d | m <= t = return $ median xs
| otherwise = fmap median $ sampl' xs m t
where
m = length xs
t = round $ 7/(e^2) * log (2/d)
-- * use vector here due to (!!)
-- * sample `t` items from the list `[0..m-1]` *with replacement*
-- * Use : runRVar (sample m t) StdRandom
sampl' :: [a] -> Int -> Int -> RVar [a]
sampl' xs m t | m < 0 || t < 0 = return []
| otherwise = (\is -> [ xs !! i | i <- is]) <$> mis
where mis = fmap sort . replicateM t $ uniform 0 (m-1)
{-----------------------------------------------------------------------------
III. Frequency Moments
------------------------------------------------------------------------------}
{-----------------------------------------------------------------------------
I. Approximate Counting
------------------------------------------------------------------------------}
-- * Run on stream inputs `xs` for t independent trials for `t = 1/eps`,
-- * and `m` times in parralell, for `m = 1/(e^2 * d)`
-- * and take the median
morris :: Eps -> Delta -> [a] -> RVar Counter
morris e d xs = fmap rmedian . (fmap . fmap) rmean -- * take median of the means
$ Cl.sourceList xs $$ count -- * stream to counter
$ replicate m $ replicate t 0 -- * make m counters of length t
where
t = round $ 1/(e^2*d)
m = round $ 1/d
-- * Given an m-long list `xs` of lists (each of which is t-lengthed) of counters,
-- * consume the stream and output result
count :: [[Counter]] -> Sink a RVar [[Counter]]
count xxs = (fmap . fmap . fmap) (\x -> 2^(round x) - 1)
$ Cl.foldM (\xs _ -> incrs xs) xxs
-- * given a list of list of counter `xs` of length `n`,
-- * toss a coin and count
incrs :: [[Counter]] -> RVar [[Counter]]
incrs = sequence . fmap incr where
incr xs = do
hs <- sequence $ (\x -> toss . coin $ 0.5^(round x)) <$> xs
return $ pincr <$> zip hs xs
where pincr (h,x) = if isHead h then (seq () succ x) else seq () x
-- * Naive solution * --
-- * Run Morris alpha on stream inputs `xs`
morrisA :: [a] -> IO Counter
morrisA xs = flip runRVar StdRandom $ Cl.sourceList xs $$ alpha
-- * Run Morris beta on stream inputs `xs` for `t` independent trials and average
morrisB :: Int -> [a] -> IO Counter
morrisB t = fmap rmean . replicateM t . morrisA
-- * Naive morris algorithm
-- * Run on stream inputs `xs` for t independent trials for `t = 1/eps`,
-- * and `m` times in parralell, for `m = 1/(e^2 * d)`
-- * and take the median
-- * Problem : `replicateM n` is O(n) time
morris' :: Eps -> Delta -> [a] -> IO Counter
morris' e d = fmap rmedian . replicateM m . morrisB t
where (t,m) = (round $ 1/(e^2*d), round $ 1/d)
-- * A step in morris Algorithm alpha
alpha :: Sink a RVar Counter
alpha = (\x -> 2^(round x) - 1) <$> Cl.foldM (\x _ -> incr x) 0
-- * Increment a counter `x` with probability 1/2^x
incr :: Counter -> RVar Counter
incr x = do
h <- toss . coin $ 0.5^(round x)
return $ if isHead h then (seq () succ x) else seq () x
rmean, rmedian :: (Floating a, Ord a, RealFrac a) => [a] -> Float
rmean = fromIntegral . round . mean
rmedian = fromIntegral . round . median
---- * Increment a counter `x` with probability 1/2^x
--incr' :: Counter -> RVar Counter
--incr' x = do
-- h <- (\q -> q <= (0.5^(round x) :: Prob)) <$> uniform 0 1
-- return $ if h then (seq () succ x) else seq () x
-- * Test Morris
tMorris :: IO ()
tMorris = undefined
{-----------------------------------------------------------------------------
X. Finger Exercises
type Source m a = ConduitM () a m () -- no meaningful input or return value
type Conduit a m b = ConduitM a b m () -- no meaningful return value
type Sink a m b = ConduitM a Void m b -- no meaningful output value
------------------------------------------------------------------------------}
-- * generator
genRs :: Monad m => Source m Int
genRs = Cl.sourceList rs
-- * conduits
cond :: Monad m => Conduit Int m String
cond = Cl.map show
add1 :: Monad m => Conduit Int m Int
add1 = Cl.map (+1)
add2 :: Monad m => Conduit Int m Int
add2 = do
mx <- await
case mx of
Nothing -> return ()
Just x -> (yield $ x + 2) >> add2
-- * sinks
sink1 :: Sink Int IO ()
sink1 = Cl.mapM_ $ putStrLn . show
sink2 :: Sink String IO ()
sink2 = Cl.mapM_ putStrLn
-- * accumlate the values in a list
sink3 :: Monad m => [Int] -> Sink Int m [Int]
sink3 xs = do
mx <- await
case mx of
Nothing -> return xs
Just x -> sink3 $ xs ++ [x]
-- * accuulate values in a list and increment by 3
add3 :: (Num a, Monad m) => Sink Int m [Int]
add3 = Cl.fold (\xs x -> xs ++ [x+3]) []
-- * some trivial pipes
pp0, pp1, pp2 :: IO ()
pp0 = genRs $$ sink1
pp1 = genRs $$ add1 $= cond $= sink2
pp2 = genRs $$ add2 $= cond $= sink2
-- * map and fold
pp2' :: Identity [Int]
pp2' = genRs $$ add2 $= sink3 []
-- * fold a list
pp3 :: Identity [Int]
pp3 = genRs $$ add3
-- * counts everything
brute :: [a] -> Counter
brute xs = runIdentity $ Cl.sourceList xs $$ Cl.fold (\n _ -> succ n) 0
-- * filter a list
pp4 :: Int -> Identity [Int]
pp4 n = genRs $= Cl.filter (>n) $$ Cl.fold (flip $ (++) . pure) []
-- * map list
pp5 :: Identity [Int]
pp5 = genRs $= Cl.map (+5) $$ sink3 []
-- * test property
tpp2, tpp3, tpp5 :: Bool
tpp2 = runIdentity pp2' == fmap (+2) rs
tpp3 = runIdentity pp3 == fmap (+3) rs
tpp5 = runIdentity pp5 == fmap (+5) rs
-- * test uniformness of list, observe it's relatively uniform
tpp4 :: [Int]
tpp4 = length . runIdentity . pp4 <$> [1..10]
{-----------------------------------------------------------------------------
X. Test Data
------------------------------------------------------------------------------}
-- * random string of choice
rs :: (Enum a, Num a) => [a]
rs = [1..1000]
{-----------------------------------------------------------------------------
Depricated
------------------------------------------------------------------------------}
--morrisA' :: Sink a RVar Counter
--morrisA' = Cl.foldM (\x _ -> incr x) 0
--incr :: MonadRandom m => Counter -> m Counter
--incr x = do
-- h <- toss . coin $ 0.5^x
-- return $ if isHead h then (seq () succ x) else seq () x
--morrisB :: Conduit a (StateT Counter RVar) a
--morrisB = do
-- mi <- await
-- case mi of
-- Nothing -> return ()
-- Just i -> do
-- yield i
-- x <- lift get
-- h <- lift . lift . toss . coin $ 0.5^x
-- let x' = if isHead h then succ x else x
-- lift . put $ seq () x'
-- morrisB
--cap :: Monad m => Sink a m ()
--cap = do
-- mi <- await
-- case mi of
-- Nothing -> return ()
-- _ -> cap
--morrisBs = flip runStateT 0 $ Cl.sourceList [1..10000] $= morrisB $= morrisB $$ cap
-- * Morris Algorithm Beta, repeat step in morris alpha `t` times
--morrisB :: Trials -> Sink a RVar [Counter]
--morrisB t = replicateM t morrisA
--tmorrisB' :: Trials -> [a] -> IO [Counter]
--tmorrisB' t xs = (fmap . fmap) toN . flip runRVar StdRandom $ Cl.sourceList xs $$ morrisB t
|
lingxiao/CIS700
|
depricated/Play1129.hs
|
Haskell
|
bsd-3-clause
| 12,496
|
module Backend.Generic123 (
mpg321Backend
, ogg123Backend
) where
import Backend
import Control.Concurrent
import Control.Monad
import System.IO
import System.Process
(shell,CreateProcess(..),StdStream(..),createProcess,waitForProcess)
-- | A backend for controlling mpg321.
mpg321Backend :: IO Backend
mpg321Backend = generic123Backend "mpg321" "mpg321 -R mp"
-- | A backend for controlling ogg123.
ogg123Backend :: IO Backend
ogg123Backend = generic123Backend "ogg123" "ogg123 -R mp"
-- | A generic backend for audio programs that support an mpg123-like interface.
generic123Backend :: String -> String -> IO Backend
generic123Backend name cmd = do
let process = (shell cmd)
{ std_in = CreatePipe
, std_out = CreatePipe
, std_err = CreatePipe
, close_fds = True
}
(Just inH, Just outH, Just errH, ph) <- createProcess process
hSetBuffering inH NoBuffering
hSetBinaryMode inH False
hSetBinaryMode outH False
hSetBinaryMode errH False
status <- newSampleVar ""
statusTid <- forkIO $ forever $ do
line <- hGetLine outH
unless (null line) (writeSampleVar status line)
let send ws = do
putStrLn ("Sending: " ++ show ws)
hPutStrLn inH (unwords ws)
cleanup = do
send ["QUIT"]
killThread statusTid
hClose inH
hClose outH
hClose errH
_ <- waitForProcess ph
return ()
return Backend
{ backendName = name
, backendLoad = \ path -> send ["LOAD",path]
, backendPause = send ["PAUSE"]
, backendPlay = send ["PAUSE"]
, backendStop = send ["STOP"]
, backendCleanup = cleanup
, backendStatus = readSampleVar status
, backendSetVolume = \ vol -> send ["GAIN",show vol]
}
|
elliottt/din
|
src/Backend/Generic123.hs
|
Haskell
|
bsd-3-clause
| 1,842
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DataKinds #-}
import Test.Tasty.HUnit ((@?=), Assertion, testCase)
import Test.Tasty.TH (defaultMainGenerator)
import Language.Cypher
case_simpleMatchExample :: Assertion
case_simpleMatchExample =
show (simpleMatch (PNode (Just n) [] []) (RetE n ::: HNil)) @?= "MATCH (n) RETURN n"
where
n = EIdent "n"
case_simpleMatchExample2 :: Assertion
case_simpleMatchExample2 =
show ex2 @?= "MATCH (me)-[:KNOWS*1..2]-(remote_friend) RETURN remote_friend.name"
where
ex2 :: Query '[Str]
ex2 = simpleMatch
(PRel left right Nothing (Just range) RelBoth [] ["KNOWS"])
(RetE (EProp remote_friend "name") ::: HNil)
range = Range (Just 1) (Just 2)
remote_friend = EIdent "remote_friend"
me = EIdent "me"
left = PNode (Just me) [] []
right = PNode (Just remote_friend) [] []
main :: IO ()
main = $defaultMainGenerator
|
HaskellDC/neo4j-cypher
|
tests/Language/cypher-test-suite.hs
|
Haskell
|
bsd-3-clause
| 939
|
module Main where
import Data.Ord (comparing)
import qualified Data.Vector.Algorithms.Intro as Intro
import qualified Data.Vector.Storable as VS
import Data.Vector.Storable.Mutable (IOVector)
import Numeric.LinearAlgebra hiding (eig, vector)
import Numeric.LinearAlgebra.Arnoldi
import Test.Hspec
import Test.QuickCheck
main :: IO ()
main = hspec $ do
describe "Numeric.LinearAlgebra.Arnoldi.eig" $ do
it "returns the diagonal of an arbitrary diagonal matrix" $ property $ do
dim <- arbitrary `suchThat` (> 3)
diagonal <- VS.fromList <$> vector dim
let
_matrix = diag diagonal :: Matrix Double
nev = dim - 3
options = Options { which = SR
, number = nev
, maxIterations = Nothing
}
sort = VS.modify Intro.sort
actual = (sort . fst) (eig options dim (multiply _matrix))
expected = (VS.take nev . sort) diagonal
relative = VS.maximum (VS.zipWith (%) expected actual)
pure (counterexample (show (expected, actual)) (relative < 1E-4))
it "returns the diagonal of an arbitrary diagonal matrix" $ property $ do
dim <- arbitrary `suchThat` (> 3)
diagonal <- VS.fromList <$> vector dim
let
_matrix = diag diagonal :: Matrix (Complex Double)
nev = dim - 3
options = Options { which = SR
, number = nev
, maxIterations = Nothing
}
sort = VS.modify (Intro.sortBy (comparing realPart))
actual = (sort . fst) (eig options dim (multiply _matrix))
expected = (VS.take nev . sort) diagonal
relative = VS.maximum (VS.zipWith (%%) expected actual)
pure (counterexample (show (expected, actual)) (relative < 1E-4))
multiply :: Numeric a => Matrix a -> IOVector a -> IOVector a -> IO ()
multiply _matrix dst src = do
x <- VS.freeze src
let y = _matrix #> x
VS.copy dst y
(%) :: Double -> Double -> Double
(%) a b =
let a_plus_b = a + b
in if a_plus_b /= 0
then abs ((a - b) / a_plus_b)
else a - b
(%%) :: Complex Double -> Complex Double -> Double
(%%) a b =
let a_plus_b = a + b
in if a_plus_b /= 0
then magnitude ((a - b) / a_plus_b)
else magnitude (a - b)
|
ttuegel/arpack
|
tests/tests.hs
|
Haskell
|
bsd-3-clause
| 2,306
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE Arrows #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
-- http://blog.jle.im/entry/effectful-recursive-real-world-autos-intro-to-machine
--
-- Auto with on/off behavior and effectful stepping.
module Auto where
import Control.Category.Associative
import Control.Category.Structural
import Control.Category.Monoidal
import Control.Category.Cartesian
import Control.Categorical.Bifunctor.Rules
import Control.Category
import Prelude hiding (id, (.),fst,snd)
import Control.Arrow hiding (first,second,(***),(&&&))
import qualified Control.Arrow as A
import Control.Applicative
import Control.Arrow.CCA
import Control.Arrow.CCA.Optimize
import Control.Category
import Control.Concurrent.Async
import Control.Monad
import Control.Monad.Fix
-- instance Monad Concurrently where
-- return = pure
-- Concurrently a >>= f =
-- Concurrently $ a >>= runConcurrently . f
newtype AutoXIO a b = AutoXIO {runAutoXIO :: AutoX IO a b} deriving (Functor,Applicative,Category,Alternative,ArrowChoice,ArrowLoop)
autoIO :: (a -> IO (Maybe b, AutoX IO a b)) -> AutoXIO a b
autoIO = AutoXIO . AConsX
runAutoIO :: AutoXIO a b -> a -> IO (Maybe b, AutoX IO a b)
runAutoIO = runAutoX . runAutoXIO
runAutoIO_ :: AutoXIO a b -> a -> IO (Maybe b)
runAutoIO_ f a = liftM fst $ (runAutoX . runAutoXIO) f a
instance PFunctor (,) AutoXIO where
first (AutoXIO a) = AutoXIO $ first a
instance QFunctor (,) AutoXIO where
second (AutoXIO a) = AutoXIO $ second a
instance Bifunctor (,) AutoXIO where
(***) = (A.***)
instance Contract (,) AutoXIO where
(&&&) = (A.&&&)
instance Arrow AutoXIO where
arr :: (b -> c) -> AutoXIO b c
arr f = AutoXIO $ AConsX $ \b -> return (Just $ f b,arr f)
first (AutoXIO a) = AutoXIO $ first a
second (AutoXIO a) = AutoXIO $ second a
a1 *** a2 = autoIO $ \(x1, x2) -> do
( (y1,a1') , (y2,a2') ) <- concurrently (runAutoIO a1 x1) (runAutoIO a2 x2)
return (liftA2 (,) y1 y2, a1' *** a2')
a1 &&& a2 = autoIO $ \x -> do
( (y1,a1') , (y2,a2') ) <- concurrently (runAutoIO a1 x) (runAutoIO a2 x)
return (liftA2 (,) y1 y2, a1' &&& a2')
instance ArrowCCA AutoXIO where
delay b = AutoXIO $ delay b
type M AutoXIO = IO
arrM f = AutoXIO $ arrM f
arrIO :: (a -> IO b) -> AutoXIO a b
arrIO action = AutoXIO $ AConsX $ \a -> do
b <- action a
return (Just b,runAutoXIO $ arrIO action)
arrMonad :: Monad m => (a -> m b) -> AutoX m a b
arrMonad action = AConsX $ \a -> do
b <- action a
return (Just b,arrMonad action)
--}
-- | The AutoX type: Auto with on/off behavior and effectful stepping.
newtype AutoX m a b = AConsX { runAutoX :: a -> m (Maybe b, AutoX m a b) }
testAutoM :: Monad m => AutoX m a b -> [a] -> m ([Maybe b], AutoX m a b)
testAutoM a [] = return ([], a)
testAutoM a (x:xs) = do
(y , a' ) <- runAutoX a x
(ys, a'') <- testAutoM a' xs
return (y:ys, a'')
testAutoM_ :: Monad m => AutoX m a b -> [a] -> m [Maybe b]
testAutoM_ a as = liftM fst $ testAutoM a as
{-
newtype AAuto m a b = A {runA :: m a (Maybe b,AAuto m a b)}
instance ArrowChoice m => Category (AAuto m) where
id = A $ arr (\a->(Just a,id))
g . f= A $ proc x -> do
(y, f') <- runA f -< x
(z, g') <- case y of
Just _y -> runA g -< _y
Nothing -> returnA -< (Nothing, g)
returnA -< (z, g' . f')
instance Arrow m => Functor (AAuto m r) where
fmap f a = A $ proc x -> do
(y, a') <- runA a -< x
returnA -< (fmap f y, fmap f a')
instance Arrow m => Applicative (AAuto m r) where
pure y = A $ proc _ -> returnA -< (Just y, pure y)
af <*> ay = A $ proc x -> do
(f, af') <- runA af -< x
(y, ay') <- runA ay -< x
returnA -< (f <*> y, af' <*> ay')
instance ArrowChoice m => Arrow (AAuto m) where
arr f = A $ proc x -> returnA -< (Just (f x), arr f)
first a = A $ proc (x, z) -> do
(y, a') <- runA a -< x
returnA -< (fmap (,z) y , first a')
-}
-- Instances
instance Monad m => Category (AutoX m) where
id = AConsX $ \x -> return (Just x, id)
g . f = AConsX $ \x -> do
(y, f') <- runAutoX f x
(z, g') <- case y of
Just _y -> runAutoX g _y
Nothing -> return (Nothing, g)
return (z, g' . f')
instance Monad m => Functor (AutoX m r) where
fmap f a = AConsX $ \x -> do
(y, a') <- runAutoX a x
return (fmap f y, fmap f a')
instance Monad m => Applicative (AutoX m r) where
pure y = AConsX $ \_ -> return (Just y, pure y)
af <*> ay = AConsX $ \x -> do
(f, af') <- runAutoX af x
(y, ay') <- runAutoX ay x
return (f <*> y, af' <*> ay')
instance MonadFix m => PFunctor (,) (AutoX m) where
first = A.first
instance MonadFix m => Contract (,) (AutoX m) where
(&&&) = (A.&&&)
instance MonadFix m => QFunctor (,) (AutoX m) where
second = A.second
instance MonadFix m => Bifunctor (,) (AutoX m) where
instance MonadFix m => Arrow (AutoX m) where
arr f = AConsX $ \x -> return (Just (f x), arr f)
first a = AConsX $ \(x, z) -> do
(y, a') <- runAutoX a x
return (fmap (,z) y , first a')
second a = AConsX $ \(z, x) -> do
(y, a') <- runAutoX a x
return (fmap (z,) y, second a')
a1 *** a2 = AConsX $ \(x1, x2) -> do
(y1, a1') <- runAutoX a1 x1
(y2, a2') <- runAutoX a2 x2
return (liftA2 (,) y1 y2, a1' *** a2')
a1 &&& a2 = AConsX $ \x -> do
(y1, a1') <- runAutoX a1 x
(y2, a2') <- runAutoX a2 x
return (liftA2 (,) y1 y2, a1' &&& a2')
instance MonadFix m => ArrowChoice (AutoX m) where
left a = AConsX $ \x ->
case x of
Left l -> do
(l', a') <- runAutoX a l
return (fmap Left l', left a')
Right r ->
return (Just (Right r), left a)
instance Monad m => Alternative (AutoX m a) where
empty = AConsX $ \_ -> return (Nothing, empty)
a1 <|> a2 = AConsX $ \x -> do
(y1, a1') <- runAutoX a1 x
(y2, a2') <- runAutoX a2 x
return (y1 <|> y2, a1' <|> a2')
instance MonadFix m => ArrowLoop (AutoX m) where
loop a = AConsX $ \x -> do
rec {(Just (y, d), a') <- runAutoX a (x, d)}
return (Just y, loop a')
instance MonadFix m => ArrowCCA (AutoX m) where -- added 2015 TB
delay b = AConsX $ \a -> return (Just b,delay a)
type M (AutoX m) = m
arrM f = aConsM $ \x -> do
y <- f x
return (y, arrM f)
-- urggghh my head hurt so much trying to write this in a clean way using
-- recursive do notation instead of explicit calls to `mfix` and `fix`.
-- Anyone want to submit a pull request? :)
--
-- instance MonadFix m => ArrowLoop (AutoX m) where
-- | Smart constructors
--
-- aCons: Use as you would use `ACons`, but makes an `AutoX`.
aCons :: Monad m => (a -> (b, AutoX m a b)) -> AutoX m a b
aCons a = AConsX $ \x ->
let (y, aX) = a x
in return (Just y, aX)
-- aConsM: Use as you would use `AConsM`, but makes an `AutoX`.
aConsM :: Monad m => (a -> m (b, AutoX m a b)) -> AutoX m a b
aConsM a = AConsX $ \x -> do
(y, aX) <- a x
return (Just y, aX)
-- aConsOn: Use as you would use `AConsOn`, but makes an `AutoX`.
aConsOn :: Monad m => (a -> (Maybe b, AutoX m a b)) -> AutoX m a b
aConsOn a = AConsX $ \x ->
let (y, aX) = a x
in return (y, aX)
-- | AutoX Test Autos
--
-- summer: Outputs the sum of all inputs so far. Demonstrates the usage of
-- the `aCons` smart constructor.
summer :: (Monad m, Num a) => AutoX m a a
summer = sumFrom 0
where
sumFrom n = aCons $ \input ->
let s = n + input
in ( s , sumFrom s )
-- arrMM: Converts an `a -> m b` into an always-on `AutoX` that just runs
-- the function on the input and outputs the result. Demonstrates the
-- usage of the `aConsM` smart constructor.
arrMM :: Monad m => (a -> m b) -> AutoX m a b
arrMM f = aConsM $ \x -> do
y <- f x
return (y, arrMM f)
-- untilA: Lets all values pass through until the first one that satisfies
-- the predicate. Demonstrates the usage of the `aConsOn` smart
-- constructor.
untilA :: Monad m => (a -> Bool) -> AutoX m a a
untilA p = aConsOn $ \x ->
if p x
then (Just x , untilA p)
else (Nothing, empty )
|
tomberek/rulestesting
|
Auto.hs
|
Haskell
|
bsd-3-clause
| 9,312
|
{-
Copyright 2019 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-|
Functions for generating, reading and writing secrets for use with
local authentication method
-}
module CodeWorld.Auth.Secret
( Secret(..)
, generateSecret
, readSecret
, writeSecret
) where
import Crypto.Random (getRandomBytes)
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString (readFile, writeFile)
import qualified Data.ByteString.Base64 as Base64 (decode, encode)
data Secret = Secret ByteString deriving Eq
-- |Generates a new, random secret
generateSecret ::
IO Secret -- ^ Secret
generateSecret = Secret <$> getRandomBytes 32
-- |Writes a secret to a file
writeSecret ::
FilePath -- ^ File path
-> Secret -- ^ Secret
-> IO () -- ^ Result
writeSecret path (Secret bytes) = ByteString.writeFile path (Base64.encode bytes)
-- |Reads a secret from a file
readSecret ::
FilePath -- ^ File path
-> IO Secret -- ^ Result
readSecret path = do
s <- ByteString.readFile path
case Base64.decode s of
Left e -> error e
Right bytes -> return $ Secret bytes
|
alphalambda/codeworld
|
codeworld-auth/src/CodeWorld/Auth/Secret.hs
|
Haskell
|
apache-2.0
| 1,714
|
<?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="pl-PL">
<title>Authentication Statistics | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/authstats/src/main/javahelp/org/zaproxy/zap/extension/authstats/resources/help_pl_PL/helpset_pl_PL.hs
|
Haskell
|
apache-2.0
| 987
|
--------------------------------------------------------------------------------
-- |
-- Module : HEP.Kinematics.Vector.LorentzTVector
-- Copyright : (c) 2014-2017 Chan Beom Park
-- License : BSD-style
-- Maintainer : Chan Beom Park <cbpark@gmail.com>
-- Stability : experimental
-- Portability : GHC
--
-- (2+1)-dimensional vector.
--
--------------------------------------------------------------------------------
{-# LANGUAGE BangPatterns #-}
module HEP.Kinematics.Vector.LorentzTVector
( -- * Type
LorentzTVector
-- * Function
, setXYM
, setXYT
, invariantMass
) where
import Control.Applicative
import Linear.Metric (Metric (..))
import Linear.V2 (V2 (..))
import Linear.V3 (R1 (..), R2 (..), V3 (..))
import Linear.Vector (Additive (..))
-- | Type for (2+1)-dimensional vector.
newtype LorentzTVector a = LorentzTVector (V3 a) deriving (Eq, Show)
instance Num a => Num (LorentzTVector a) where
(+) = liftA2 (+)
(*) = liftA2 (*)
(-) = liftA2 (-)
negate = fmap negate
abs = fmap abs
signum = fmap signum
fromInteger = pure . fromInteger
instance Functor LorentzTVector where
fmap f (LorentzTVector v3) = LorentzTVector (fmap f v3)
instance Applicative LorentzTVector where
pure a = LorentzTVector (V3 a a a)
LorentzTVector v3 <*> LorentzTVector v3' = LorentzTVector (v3 <*> v3')
instance Additive LorentzTVector where
zero = pure 0
instance Metric LorentzTVector where
(LorentzTVector (V3 t x y)) `dot` (LorentzTVector (V3 t' x' y')) =
t * t' - x * x' - y * y'
instance R1 LorentzTVector where
_x f (LorentzTVector (V3 t x y)) = (\x' -> LorentzTVector (V3 t x' y)) <$> f x
instance R2 LorentzTVector where
_y f (LorentzTVector (V3 t x y)) = LorentzTVector . V3 t x <$> f y
_xy f (LorentzTVector (V3 t x y)) =
(\(V2 x' y') -> LorentzTVector (V3 t x' y')) <$> f (V2 x y)
-- | Makes 'LorentzTVector' out of components based on x, y, t coordinates.
setXYT :: a -> a -> a -> LorentzTVector a
setXYT px py et = LorentzTVector (V3 et px py)
{-# INLINE setXYT #-}
-- | Makes 'LorentzTVector' out of components based on x, y, m coordinates.
setXYM :: Double -> Double -> Double -> LorentzTVector Double
setXYM px py m = let !et = sqrt $ px * px + py * py + m * m
in setXYT px py et
{-# INLINE setXYM #-}
-- | Invariant mass. It would be a transverse mass in (3+1)-dimensional space.
invariantMass :: LorentzTVector Double -> LorentzTVector Double -> Double
invariantMass v v' = norm (v ^+^ v')
{-# INLINE invariantMass #-}
|
cbpark/hep-kinematics
|
src/HEP/Kinematics/Vector/LorentzTVector.hs
|
Haskell
|
bsd-3-clause
| 2,612
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE UndecidableInstances #-}
module Language.Embedded.Concurrent.Backend.C where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Monad.Operational.Higher
import Data.Typeable
import Language.Embedded.Expression
import Language.Embedded.Concurrent.CMD
import Language.Embedded.Imperative.CMD
import Language.Embedded.Backend.C.Expression
import Language.C.Quote.C
import Language.C.Monad
import qualified Language.C.Syntax as C
instance ToIdent ThreadId where
toIdent (TIDComp tid) = C.Id tid
instance ToIdent (Chan t a) where
toIdent (ChanComp c) = C.Id c
threadFun :: ThreadId -> String
threadFun tid = "thread_" ++ show tid
-- | Compile `ThreadCMD`.
-- TODO: sharing for threads with the same body
compThreadCMD :: CompExp exp => ThreadCMD (Param3 CGen exp pred) a -> CGen a
compThreadCMD (ForkWithId body) = do
tid <- TIDComp <$> gensym "t"
let funName = threadFun tid
_ <- inFunctionTy [cty|void*|] funName $ do
addParam [cparam| void* unused |]
body tid
addStm [cstm| return NULL; |]
addSystemInclude "pthread.h"
touchVar tid
addLocal [cdecl| typename pthread_t $id:tid; |]
addStm [cstm| pthread_create(&$id:tid, NULL, $id:funName, NULL); |]
return tid
compThreadCMD (Kill tid) = do
touchVar tid
addStm [cstm| pthread_cancel($id:tid); |]
compThreadCMD (Wait tid) = do
touchVar tid
addStm [cstm| pthread_join($id:tid, NULL); |]
compThreadCMD (Sleep us) = do
us' <- compExp us
addSystemInclude "unistd.h"
addStm [cstm| usleep($us'); |]
-- | Compile `ChanCMD`.
compChanCMD :: (CompExp exp, CompTypeClass ct, ct Bool)
=> ChanCMD (Param3 CGen exp ct) a
-> CGen a
compChanCMD cmd@(NewChan sz) = do
addLocalInclude "chan.h"
sz' <-compChanSize sz
c <- ChanComp <$> gensym "chan"
addGlobal [cedecl| typename chan_t $id:c; |]
addStm [cstm| $id:c = chan_new($sz'); |]
return c
compChanCMD cmd@(WriteOne c (x :: exp a)) = do
x' <- compExp x
v :: Val a <- freshVar (proxyPred cmd)
ok <- freshVar (proxyPred cmd)
addStm [cstm| $id:v = $x'; |]
addStm [cstm| $id:ok = chan_write($id:c, sizeof($id:v), &$id:v); |]
return ok
compChanCMD cmd@(WriteChan c from to (ArrComp arr)) = do
from' <- compExp from
to' <- compExp to
ok <- freshVar (proxyPred cmd)
addStm [cstm| $id:ok = chan_write($id:c, sizeof(*$id:arr)*(($to')-($from')), &$id:arr[$from']); |]
return ok
compChanCMD cmd@(ReadOne c) = do
v <- freshVar (proxyPred cmd)
addStm [cstm| chan_read($id:c, sizeof($id:v), &$id:v); |]
return v
compChanCMD cmd@(ReadChan c from to (ArrComp arr)) = do
ok <- freshVar (proxyPred cmd)
from' <- compExp from
to' <- compExp to
addStm [cstm| chan_read($id:c, sizeof(*$id:arr)*(($to')-($from')), &$id:arr[$from']); |]
addStm [cstm| $id:ok = chan_last_read_ok($id:c); |]
return ok
compChanCMD (CloseChan c) = do
addStm [cstm| chan_close($id:c); |]
compChanCMD cmd@(ReadOK c) = do
var <- freshVar (proxyPred cmd)
addStm [cstm| $id:var = chan_last_read_ok($id:c); |]
return var
compChanSize :: forall exp ct i. (CompExp exp, CompTypeClass ct) => ChanSize exp ct i -> CGen C.Exp
compChanSize (OneSize t sz) = do
t' <- compType (Proxy :: Proxy ct) t
sz' <- compExp sz
return [cexp| $sz' * sizeof($ty:t') |]
compChanSize (TimesSize n sz) = do
n' <- compExp n
sz' <- compChanSize sz
return [cexp| $n' * $sz' |]
compChanSize (PlusSize a b) = do
a' <- compChanSize a
b' <- compChanSize b
return [cexp| $a' + $b' |]
instance CompExp exp => Interp ThreadCMD CGen (Param2 exp pred) where
interp = compThreadCMD
instance (CompExp exp, CompTypeClass ct, ct Bool) => Interp ChanCMD CGen (Param2 exp ct) where
interp = compChanCMD
|
kmate/imperative-edsl
|
src/Language/Embedded/Concurrent/Backend/C.hs
|
Haskell
|
bsd-3-clause
| 3,765
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 2000
FunDeps - functional dependencies
It's better to read it as: "if we know these, then we're going to know these"
-}
{-# LANGUAGE CPP #-}
module Eta.TypeCheck.FunDeps (
FDEq (..),
Equation(..), pprEquation,
improveFromInstEnv, improveFromAnother,
checkInstCoverage, checkFunDeps,
pprFundeps
) where
#include "HsVersions.h"
import Eta.BasicTypes.Name
import Eta.BasicTypes.Var
import Eta.Types.Class
import Eta.Types.Type
import Eta.Types.Unify
import Eta.Types.InstEnv
import Eta.BasicTypes.VarSet
import Eta.BasicTypes.VarEnv
import Eta.Utils.Outputable
import Eta.Main.ErrUtils( Validity(..), allValid )
import Eta.BasicTypes.SrcLoc
import Eta.Utils.Util
import Eta.Utils.FastString
import Data.List ( nubBy )
import Data.Maybe ( isJust )
{-
************************************************************************
* *
\subsection{Generate equations from functional dependencies}
* *
************************************************************************
Each functional dependency with one variable in the RHS is responsible
for generating a single equality. For instance:
class C a b | a -> b
The constraints ([Wanted] C Int Bool) and [Wanted] C Int alpha
FDEq { fd_pos = 1
, fd_ty_left = Bool
, fd_ty_right = alpha }
However notice that a functional dependency may have more than one variable
in the RHS which will create more than one FDEq. Example:
class C a b c | a -> b c
[Wanted] C Int alpha alpha
[Wanted] C Int Bool beta
Will generate:
fd1 = FDEq { fd_pos = 1, fd_ty_left = alpha, fd_ty_right = Bool } and
fd2 = FDEq { fd_pos = 2, fd_ty_left = alpha, fd_ty_right = beta }
We record the paremeter position so that can immediately rewrite a constraint
using the produced FDEqs and remove it from our worklist.
INVARIANT: Corresponding types aren't already equal
That is, there exists at least one non-identity equality in FDEqs.
Assume:
class C a b c | a -> b c
instance C Int x x
And: [Wanted] C Int Bool alpha
We will /match/ the LHS of fundep equations, producing a matching substitution
and create equations for the RHS sides. In our last example we'd have generated:
({x}, [fd1,fd2])
where
fd1 = FDEq 1 Bool x
fd2 = FDEq 2 alpha x
To ``execute'' the equation, make fresh type variable for each tyvar in the set,
instantiate the two types with these fresh variables, and then unify or generate
a new constraint. In the above example we would generate a new unification
variable 'beta' for x and produce the following constraints:
[Wanted] (Bool ~ beta)
[Wanted] (alpha ~ beta)
Notice the subtle difference between the above class declaration and:
class C a b c | a -> b, a -> c
where we would generate:
({x},[fd1]),({x},[fd2])
This means that the template variable would be instantiated to different
unification variables when producing the FD constraints.
Finally, the position parameters will help us rewrite the wanted constraint ``on the spot''
-}
data Equation loc
= FDEqn { fd_qtvs :: [TyVar] -- Instantiate these type and kind vars to fresh unification vars
, fd_eqs :: [FDEq] -- and then make these equal
, fd_pred1, fd_pred2 :: PredType -- The Equation arose from combining these two constraints
, fd_loc :: loc }
data FDEq = FDEq { fd_pos :: Int -- We use '0' for the first position
, fd_ty_left :: Type
, fd_ty_right :: Type }
instance Outputable FDEq where
ppr (FDEq { fd_pos = p, fd_ty_left = tyl, fd_ty_right = tyr })
= parens (int p <> comma <+> ppr tyl <> comma <+> ppr tyr)
{-
Given a bunch of predicates that must hold, such as
C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
improve figures out what extra equations must hold.
For example, if we have
class C a b | a->b where ...
then improve will return
[(t1,t2), (t4,t5)]
NOTA BENE:
* improve does not iterate. It's possible that when we make
t1=t2, for example, that will in turn trigger a new equation.
This would happen if we also had
C t1 t7, C t2 t8
If t1=t2, we also get t7=t8.
improve does *not* do this extra step. It relies on the caller
doing so.
* The equations unify types that are not already equal. So there
is no effect iff the result of improve is empty
-}
instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
-- A simpler version of instFD_WithPos to be used in checking instance coverage etc.
instFD (ls,rs) tvs tys
= (map lookup ls, map lookup rs)
where
env = zipVarEnv tvs tys
lookup tv = lookupVarEnv_NF env tv
instFD_WithPos :: FunDep TyVar -> [TyVar] -> [Type] -> ([Type], [(Int,Type)])
-- Returns a FunDep between the types accompanied along with their
-- position (<=0) in the types argument list.
instFD_WithPos (ls,rs) tvs tys
= (map (snd . lookup) ls, map lookup rs)
where
ind_tys = zip [0..] tys
env = zipVarEnv tvs ind_tys
lookup tv = lookupVarEnv_NF env tv
zipAndComputeFDEqs :: (Type -> Type -> Bool) -- Discard this FDEq if true
-> [Type]
-> [(Int,Type)]
-> [FDEq]
-- Create a list of FDEqs from two lists of types, making sure
-- that the types are not equal.
zipAndComputeFDEqs discard (ty1:tys1) ((i2,ty2):tys2)
| discard ty1 ty2 = zipAndComputeFDEqs discard tys1 tys2
| otherwise = FDEq { fd_pos = i2
, fd_ty_left = ty1
, fd_ty_right = ty2 } : zipAndComputeFDEqs discard tys1 tys2
zipAndComputeFDEqs _ _ _ = []
-- Improve a class constraint from another class constraint
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
improveFromAnother :: PredType -- Template item (usually given, or inert)
-> PredType -- Workitem [that can be improved]
-> [Equation ()]
-- Post: FDEqs always oriented from the other to the workitem
-- Equations have empty quantified variables
improveFromAnother pred1 pred2
| Just (cls1, tys1) <- getClassPredTys_maybe pred1
, Just (cls2, tys2) <- getClassPredTys_maybe pred2
, tys1 `lengthAtLeast` 2 && cls1 == cls2
= [ FDEqn { fd_qtvs = [], fd_eqs = eqs, fd_pred1 = pred1, fd_pred2 = pred2, fd_loc = () }
| let (cls_tvs, cls_fds) = classTvsFds cls1
, fd <- cls_fds
, let (ltys1, rs1) = instFD fd cls_tvs tys1
(ltys2, irs2) = instFD_WithPos fd cls_tvs tys2
, eqTypes ltys1 ltys2 -- The LHSs match
, let eqs = zipAndComputeFDEqs eqType rs1 irs2
, not (null eqs) ]
improveFromAnother _ _ = []
-- Improve a class constraint from instance declarations
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pprEquation :: Equation a -> SDoc
pprEquation (FDEqn { fd_qtvs = qtvs, fd_eqs = pairs })
= vcat [ptext (sLit "forall") <+> braces (pprWithCommas ppr qtvs),
nest 2 (vcat [ ppr t1 <+> ptext (sLit "~") <+> ppr t2 | (FDEq _ t1 t2) <- pairs])]
improveFromInstEnv :: InstEnvs
-> PredType
-> [Equation SrcSpan] -- Needs to be an Equation because
-- of quantified variables
-- Post: Equations oriented from the template (matching instance) to the workitem!
improveFromInstEnv _inst_env pred
| not (isClassPred pred)
= panic "improveFromInstEnv: not a class predicate"
improveFromInstEnv inst_env pred
| Just (cls, tys) <- getClassPredTys_maybe pred
, tys `lengthAtLeast` 2
, let (cls_tvs, cls_fds) = classTvsFds cls
instances = classInstances inst_env cls
rough_tcs = roughMatchTcs tys
= [ FDEqn { fd_qtvs = meta_tvs, fd_eqs = eqs
, fd_pred1 = p_inst, fd_pred2=pred
, fd_loc = getSrcSpan (is_dfun ispec) }
| fd <- cls_fds -- Iterate through the fundeps first,
-- because there often are none!
, let trimmed_tcs = trimRoughMatchTcs cls_tvs fd rough_tcs
-- Trim the rough_tcs based on the head of the fundep.
-- Remember that instanceCantMatch treats both argumnents
-- symmetrically, so it's ok to trim the rough_tcs,
-- rather than trimming each inst_tcs in turn
, ispec <- instances
, (meta_tvs, eqs) <- checkClsFD fd cls_tvs ispec
emptyVarSet tys trimmed_tcs -- NB: orientation
, let p_inst = mkClassPred cls (is_tys ispec)
]
improveFromInstEnv _ _ = []
checkClsFD :: FunDep TyVar -> [TyVar] -- One functional dependency from the class
-> ClsInst -- An instance template
-> TyVarSet -> [Type] -> [Maybe Name] -- Arguments of this (C tys) predicate
-- TyVarSet are extra tyvars that can be instantiated
-> [([TyVar], [FDEq])]
checkClsFD fd clas_tvs
(ClsInst { is_tvs = qtvs, is_tys = tys_inst, is_tcs = rough_tcs_inst })
extra_qtvs tys_actual rough_tcs_actual
-- 'qtvs' are the quantified type variables, the ones which an be instantiated
-- to make the types match. For example, given
-- class C a b | a->b where ...
-- instance C (Maybe x) (Tree x) where ..
--
-- and an Inst of form (C (Maybe t1) t2),
-- then we will call checkClsFD with
--
-- is_qtvs = {x}, is_tys = [Maybe x, Tree x]
-- tys_actual = [Maybe t1, t2]
--
-- We can instantiate x to t1, and then we want to force
-- (Tree x) [t1/x] ~ t2
--
-- This function is also used when matching two Insts (rather than an Inst
-- against an instance decl. In that case, qtvs is empty, and we are doing
-- an equality check
--
-- This function is also used by InstEnv.badFunDeps, which needs to *unify*
-- For the one-sided matching case, the qtvs are just from the template,
-- so we get matching
| instanceCantMatch rough_tcs_inst rough_tcs_actual
= [] -- Filter out ones that can't possibly match,
| otherwise
= ASSERT2( length tys_inst == length tys_actual &&
length tys_inst == length clas_tvs
, ppr tys_inst <+> ppr tys_actual )
case tcUnifyTys bind_fn ltys1 ltys2 of
Nothing -> []
Just subst | isJust (tcUnifyTys bind_fn rtys1' rtys2')
-- Don't include any equations that already hold.
-- Reason: then we know if any actual improvement has happened,
-- in which case we need to iterate the solver
-- In making this check we must taking account of the fact that any
-- qtvs that aren't already instantiated can be instantiated to anything
-- at all
-- NB: We can't do this 'is-useful-equation' check element-wise
-- because of:
-- class C a b c | a -> b c
-- instance C Int x x
-- [Wanted] C Int alpha Int
-- We would get that x -> alpha (isJust) and x -> Int (isJust)
-- so we would produce no FDs, which is clearly wrong.
-> []
| null fdeqs
-> []
| otherwise
-> [(meta_tvs, fdeqs)]
-- We could avoid this substTy stuff by producing the eqn
-- (qtvs, ls1++rs1, ls2++rs2)
-- which will re-do the ls1/ls2 unification when the equation is
-- executed. What we're doing instead is recording the partial
-- work of the ls1/ls2 unification leaving a smaller unification problem
where
rtys1' = map (substTy subst) rtys1
irs2' = map (\(i,x) -> (i,substTy subst x)) irs2
rtys2' = map snd irs2'
fdeqs = zipAndComputeFDEqs (\_ _ -> False) rtys1' irs2'
-- Don't discard anything!
-- We could discard equal types but it's an overkill to call
-- eqType again, since we know for sure that /at least one/
-- equation in there is useful)
meta_tvs = [ setVarType tv (substTy subst (varType tv))
| tv <- qtvs, tv `notElemTvSubst` subst ]
-- meta_tvs are the quantified type variables
-- that have not been substituted out
--
-- Eg. class C a b | a -> b
-- instance C Int [y]
-- Given constraint C Int z
-- we generate the equation
-- ({y}, [y], z)
--
-- But note (a) we get them from the dfun_id, so they are *in order*
-- because the kind variables may be mentioned in the
-- type variabes' kinds
-- (b) we must apply 'subst' to the kinds, in case we have
-- matched out a kind variable, but not a type variable
-- whose kind mentions that kind variable!
-- Trac #6015, #6068
where
qtv_set = mkVarSet qtvs
bind_fn tv | tv `elemVarSet` qtv_set = BindMe
| tv `elemVarSet` extra_qtvs = BindMe
| otherwise = Skolem
(ltys1, rtys1) = instFD fd clas_tvs tys_inst
(ltys2, irs2) = instFD_WithPos fd clas_tvs tys_actual
{-
************************************************************************
* *
The Coverage condition for instance declarations
* *
************************************************************************
Note [Coverage condition]
~~~~~~~~~~~~~~~~~~~~~~~~~
Example
class C a b | a -> b
instance theta => C t1 t2
For the coverage condition, we check
(normal) fv(t2) `subset` fv(t1)
(liberal) fv(t2) `subset` oclose(fv(t1), theta)
The liberal version ensures the self-consistency of the instance, but
it does not guarantee termination. Example:
class Mul a b c | a b -> c where
(.*.) :: a -> b -> c
instance Mul Int Int Int where (.*.) = (*)
instance Mul Int Float Float where x .*. y = fromIntegral x * y
instance Mul a b c => Mul a [b] [c] where x .*. v = map (x.*.) v
In the third instance, it's not the case that fv([c]) `subset` fv(a,[b]).
But it is the case that fv([c]) `subset` oclose( theta, fv(a,[b]) )
But it is a mistake to accept the instance because then this defn:
f = \ b x y -> if b then x .*. [y] else y
makes instance inference go into a loop, because it requires the constraint
Mul a [b] b
-}
checkInstCoverage :: Bool -- Be liberal
-> Class -> [PredType] -> [Type]
-> Validity
-- "be_liberal" flag says whether to use "liberal" coverage of
-- See Note [Coverage Condition] below
--
-- Return values
-- Nothing => no problems
-- Just msg => coverage problem described by msg
checkInstCoverage be_liberal clas theta inst_taus
= allValid (map fundep_ok fds)
where
(tyvars, fds) = classTvsFds clas
fundep_ok fd
| if be_liberal then liberal_ok else conservative_ok
= IsValid
| otherwise
= NotValid msg
where
(ls,rs) = instFD fd tyvars inst_taus
ls_tvs = tyVarsOfTypes ls
rs_tvs = tyVarsOfTypes rs
conservative_ok = rs_tvs `subVarSet` closeOverKinds ls_tvs
liberal_ok = rs_tvs `subVarSet` oclose theta (closeOverKinds ls_tvs)
-- closeOverKinds: see Note [Closing over kinds in coverage]
msg = vcat [ -- text "ls_tvs" <+> ppr ls_tvs
-- , text "closed ls_tvs" <+> ppr (closeOverKinds ls_tvs)
-- , text "theta" <+> ppr theta
-- , text "oclose" <+> ppr (oclose theta (closeOverKinds ls_tvs))
-- , text "rs_tvs" <+> ppr rs_tvs
sep [ ptext (sLit "The")
<+> ppWhen be_liberal (ptext (sLit "liberal"))
<+> ptext (sLit "coverage condition fails in class")
<+> quotes (ppr clas)
, nest 2 $ ptext (sLit "for functional dependency:")
<+> quotes (pprFunDep fd) ]
, sep [ ptext (sLit "Reason: lhs type")<>plural ls <+> pprQuotedList ls
, nest 2 $
(if isSingleton ls
then ptext (sLit "does not")
else ptext (sLit "do not jointly"))
<+> ptext (sLit "determine rhs type")<>plural rs
<+> pprQuotedList rs ]
, ppWhen (not be_liberal && liberal_ok) $
ptext (sLit "Using UndecidableInstances might help") ]
{- Note [Closing over kinds in coverage]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have a fundep (a::k) -> b
Then if 'a' is instantiated to (x y), where x:k2->*, y:k2,
then fixing x really fixes k2 as well, and so k2 should be added to
the lhs tyvars in the fundep check.
Example (Trac #8391), using liberal coverage
data Foo a = ... -- Foo :: forall k. k -> *
class Bar a b | a -> b
instance Bar a (Foo a)
In the instance decl, (a:k) does fix (Foo k a), but only if we notice
that (a:k) fixes k. Trac #10109 is another example.
Here is a more subtle example, from HList-0.4.0.0 (Trac #10564)
class HasFieldM (l :: k) r (v :: Maybe *)
| l r -> v where ...
class HasFieldM1 (b :: Maybe [*]) (l :: k) r v
| b l r -> v where ...
class HMemberM (e1 :: k) (l :: [k]) (r :: Maybe [k])
| e1 l -> r
data Label :: k -> *
type family LabelsOf (a :: [*]) :: *
instance (HMemberM (Label {k} (l::k)) (LabelsOf xs) b,
HasFieldM1 b l (r xs) v)
=> HasFieldM l (r xs) v where
Is the instance OK? Does {l,r,xs} determine v? Well:
* From the instance constraint HMemberM (Label k l) (LabelsOf xs) b,
plus the fundep "| el l -> r" in class HMameberM,
we get {l,k,xs} -> b
* Note the 'k'!! We must call closeOverKinds on the seed set
ls_tvs = {l,r,xs}, BEFORE doing oclose, else the {l,k,xs}->b
fundep won't fire. This was the reason for #10564.
* So starting from seeds {l,r,xs,k} we do oclose to get
first {l,r,xs,k,b}, via the HMemberM constraint, and then
{l,r,xs,k,b,v}, via the HasFieldM1 constraint.
* And that fixes v.
However, we must closeOverKinds whenever augmenting the seed set
in oclose! Consider Trac #10109:
data Succ a -- Succ :: forall k. k -> *
class Add (a :: k1) (b :: k2) (ab :: k3) | a b -> ab
instance (Add a b ab) => Add (Succ {k1} (a :: k1))
b
(Succ {k3} (ab :: k3})
We start with seed set {a:k1,b:k2} and closeOverKinds to {a,k1,b,k2}.
Now use the fundep to extend to {a,k1,b,k2,ab}. But we need to
closeOverKinds *again* now to {a,k1,b,k2,ab,k3}, so that we fix all
the variables free in (Succ {k3} ab).
Bottom line:
* closeOverKinds on initial seeds (in checkInstCoverage)
* and closeOverKinds whenever extending those seeds (in oclose)
Note [The liberal coverage condition]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(oclose preds tvs) closes the set of type variables tvs,
wrt functional dependencies in preds. The result is a superset
of the argument set. For example, if we have
class C a b | a->b where ...
then
oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z}
because if we know x and y then that fixes z.
We also use equality predicates in the predicates; if we have an
assumption `t1 ~ t2`, then we use the fact that if we know `t1` we
also know `t2` and the other way.
eg oclose [C (x,y) z, a ~ x] {a,y} = {a,y,z,x}
oclose is used (only) when checking the coverage condition for
an instance declaration
-}
oclose :: [PredType] -> TyVarSet -> TyVarSet
-- See Note [The liberal coverage condition]
oclose preds fixed_tvs
| null tv_fds = fixed_tvs -- Fast escape hatch for common case.
| otherwise = loop fixed_tvs
where
loop fixed_tvs
| new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
| otherwise = loop new_fixed_tvs
where new_fixed_tvs = foldl extend fixed_tvs tv_fds
extend fixed_tvs (ls,rs)
| ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` closeOverKinds rs
| otherwise = fixed_tvs
-- closeOverKinds: see Note [Closing over kinds in coverage]
tv_fds :: [(TyVarSet,TyVarSet)]
tv_fds = [ (tyVarsOfTypes ls, tyVarsOfTypes rs)
| pred <- preds
, (ls, rs) <- determined pred ]
determined :: PredType -> [([Type],[Type])]
determined pred
= case classifyPredType pred of
ClassPred cls tys ->
do let (cls_tvs, cls_fds) = classTvsFds cls
fd <- cls_fds
return (instFD fd cls_tvs tys)
EqPred NomEq t1 t2 -> [([t1],[t2]), ([t2],[t1])]
TuplePred ts -> concatMap determined ts
_ -> []
{-
************************************************************************
* *
Check that a new instance decl is OK wrt fundeps
* *
************************************************************************
Here is the bad case:
class C a b | a->b where ...
instance C Int Bool where ...
instance C Int Char where ...
The point is that a->b, so Int in the first parameter must uniquely
determine the second. In general, given the same class decl, and given
instance C s1 s2 where ...
instance C t1 t2 where ...
Then the criterion is: if U=unify(s1,t1) then U(s2) = U(t2).
Matters are a little more complicated if there are free variables in
the s2/t2.
class D a b c | a -> b
instance D a b => D [(a,a)] [b] Int
instance D a b => D [a] [b] Bool
The instance decls don't overlap, because the third parameter keeps
them separate. But we want to make sure that given any constraint
D s1 s2 s3
if s1 matches
-}
checkFunDeps :: InstEnvs -> ClsInst
-> Maybe [ClsInst] -- Nothing <=> ok
-- Just dfs <=> conflict with dfs
-- Check whether adding DFunId would break functional-dependency constraints
-- Used only for instance decls defined in the module being compiled
checkFunDeps inst_envs ispec
| null bad_fundeps = Nothing
| otherwise = Just bad_fundeps
where
(ins_tvs, clas, ins_tys) = instanceHead ispec
ins_tv_set = mkVarSet ins_tvs
cls_inst_env = classInstances inst_envs clas
bad_fundeps = badFunDeps cls_inst_env clas ins_tv_set ins_tys
badFunDeps :: [ClsInst] -> Class
-> TyVarSet -> [Type] -- Proposed new instance type
-> [ClsInst]
badFunDeps cls_insts clas ins_tv_set ins_tys
= nubBy eq_inst $
[ ispec | fd <- fds, -- fds is often empty, so do this first!
let trimmed_tcs = trimRoughMatchTcs clas_tvs fd rough_tcs,
ispec <- cls_insts,
notNull (checkClsFD fd clas_tvs ispec ins_tv_set ins_tys trimmed_tcs)
]
where
(clas_tvs, fds) = classTvsFds clas
rough_tcs = roughMatchTcs ins_tys
eq_inst i1 i2 = instanceDFunId i1 == instanceDFunId i2
-- An single instance may appear twice in the un-nubbed conflict list
-- because it may conflict with more than one fundep. E.g.
-- class C a b c | a -> b, a -> c
-- instance C Int Bool Bool
-- instance C Int Char Char
-- The second instance conflicts with the first by *both* fundeps
trimRoughMatchTcs :: [TyVar] -> FunDep TyVar -> [Maybe Name] -> [Maybe Name]
-- Computing rough_tcs for a particular fundep
-- class C a b c | a -> b where ...
-- For each instance .... => C ta tb tc
-- we want to match only on the type ta; so our
-- rough-match thing must similarly be filtered.
-- Hence, we Nothing-ise the tb and tc types right here
trimRoughMatchTcs clas_tvs (ltvs, _) mb_tcs
= zipWith select clas_tvs mb_tcs
where
select clas_tv mb_tc | clas_tv `elem` ltvs = mb_tc
| otherwise = Nothing
|
rahulmutt/ghcvm
|
compiler/Eta/TypeCheck/FunDeps.hs
|
Haskell
|
bsd-3-clause
| 25,305
|
module Settings.Packages.Haddock (haddockPackageArgs) where
import Expression
haddockPackageArgs :: Args
haddockPackageArgs = package haddock ?
builder GhcCabal ? pure ["--flag", "in-ghc-tree"]
|
bgamari/shaking-up-ghc
|
src/Settings/Packages/Haddock.hs
|
Haskell
|
bsd-3-clause
| 200
|
-- | Basic types used by this library.
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Brick.Types
( Location(..)
, locL
, TerminalLocation(..)
, CursorLocation(..)
, cursorLocationL
, cursorLocationNameL
, HandleEvent(..)
, Name(..)
, suffixLenses
)
where
import Control.Lens
import Data.String
import Data.Monoid (Monoid(..))
import Graphics.Vty (Event)
import Brick.Types.TH
-- | A terminal screen location.
data Location = Location { loc :: (Int, Int)
-- ^ (Column, Row)
}
deriving Show
suffixLenses ''Location
instance Field1 Location Location Int Int where
_1 = locL._1
instance Field2 Location Location Int Int where
_2 = locL._2
-- | The class of types that behave like terminal locations.
class TerminalLocation a where
-- | Get the column out of the value
columnL :: Lens' a Int
column :: a -> Int
-- | Get the row out of the value
rowL :: Lens' a Int
row :: a -> Int
instance TerminalLocation Location where
columnL = _1
column (Location t) = fst t
rowL = _2
row (Location t) = snd t
-- | Names of things. Used to name cursor locations, widgets, and
-- viewports.
newtype Name = Name String
deriving (Eq, Show, Ord)
instance IsString Name where
fromString = Name
-- | The origin (upper-left corner).
origin :: Location
origin = Location (0, 0)
instance Monoid Location where
mempty = origin
mappend (Location (w1, h1)) (Location (w2, h2)) = Location (w1+w2, h1+h2)
-- | A cursor location. These are returned by the rendering process.
data CursorLocation =
CursorLocation { cursorLocation :: !Location
-- ^ The location
, cursorLocationName :: !(Maybe Name)
-- ^ The name of the widget associated with the location
}
deriving Show
suffixLenses ''CursorLocation
instance TerminalLocation CursorLocation where
columnL = cursorLocationL._1
column = column . cursorLocation
rowL = cursorLocationL._2
row = row . cursorLocation
-- | The class of types that provide some basic event-handling.
class HandleEvent a where
-- | Handle a Vty event
handleEvent :: Event -> a -> a
|
FranklinChen/brick
|
src/Brick/Types.hs
|
Haskell
|
bsd-3-clause
| 2,308
|
module Manual where
import System.IO(openFile,hClose,IOMode(..),hPutStr,stdout)
import Data.Char(isAlpha,isDigit)
-- Parts of the manual are generated automatically from the
-- sources, by generating LaTex files by observing the
-- data structures of the Omega sources
import LangEval(vals)
import Syntax(metaHaskellOps)
import Infer(typeConstrEnv0,modes_and_doc,predefined)
import Commands(commands)
import RankN(Sigma,disp0,Exhibit(..),PolyKind(..))
import Version(version,buildtime)
-----------------------------------------
-- LaTex-Like macros
figure h body caption label =
do { hPutStr h "\\begin{figure}[t]\n"
; body
; hPutStr h ("\\caption{"++caption++"}\\label{"++label++"}\n")
; hPutStr h "\\hrule\n"
; hPutStr h "\\end{figure}\n"
}
figure2 h body caption label =
do { hPutStr h "\\begin{figure}[t]\n"
; hPutStr h "\\begin{multicols}{2}\n"
; body
; hPutStr h "\\end{multicols}\n"
; hPutStr h ("\\caption{"++caption++"}\\label{"++label++"}\n")
; hPutStr h "\\hrule\n"
; hPutStr h "\\end{figure}\n"
}
verbatim h body =
do { hPutStr h "{\\small\n\\begin{verbatim}\n"
; hPutStr h body
; hPutStr h "\\end{verbatim}}\n"
}
itemize f h items =
do { hPutStr h "\\begin{itemize}\n"
; mapM (\ x -> hPutStr h "\\item\n" >> f x >> hPutStr h "\n") items
; hPutStr h "\\end{itemize}\n"
}
---------------------------------------------------------------------
-------------------------------------------------------------------
-- Printing out tables for the manual
vals' = map (\(name,maker) -> (name,maker name)) vals
infixOperators = (concat (map f metaHaskellOps))
where f x = case lookup x vals' of
Nothing -> []
Just (_,y) -> [(x,showSigma y)]
main2 = makeManual "d:/Omega/doc"
makeManual :: String -> IO()
makeManual dir = go
where kindfile = dir ++ "/kinds.tex"
prefixfile = dir ++ "/infix.tex"
comfile = dir ++ "/commands.tex"
modefile = dir ++ "/modes.tex"
prefile = dir ++ "/predef.tex"
versionfile = dir ++ "/version.tex"
licenseSrc = "../LICENSE.txt"
licensefile = dir ++ "/license.tex"
go = do { putStrLn "Writing tables for Manual"
; h <- openFile kindfile WriteMode
; predefinedTypes h
; hClose h
; h <- openFile prefixfile WriteMode
; prefixOp h
; hClose h
; h <- openFile comfile WriteMode
; command h
; hClose h
; h <- openFile modefile WriteMode
; modes h
; hClose h
; h <- openFile prefile WriteMode
; verbatim h predefined
; hClose h
; h <- openFile versionfile WriteMode
; hPutStr h (version++"\\\\"++buildtime++"\\\\")
; hClose h
; h <- openFile licensefile WriteMode
; s <- readFile licenseSrc
; verbatim h s
; hClose h
}
------------------------------------------------------
-- helper function
showSigma:: Sigma -> String
showSigma s = scan (snd(exhibit disp0 s))
showpoly (K lvs s) = showSigma s
scan ('f':'o':'r':'a':'l':'l':xs) = dropWhile g (dropWhile f xs)
where f c = c /= '.'
g c = c `elem` ". "
scan xs = xs
f ("unsafeCast",_) = ""
f ("undefined",_) = ""
f (x,(y,z)) = (g x ++ " :: " ++ showSigma z ++ "\n")
hf (x,y,z) = (g x ++ " :: " ++ showpoly z ++ "\n")
hg (x,y) = "("++x++") :: " ++ y ++ "\n"
g [] = []
g "[]" = "[]"
g (s@(c:cs)) | isAlpha c = s -- normal names
| c == '(' = s
| True = "("++s++")" -- infix operators
predefinedTypes h =
do { figure2 h
(verbatim h
("\nType :: Kind \n\n"++(concat (map hf typeConstrEnv0))))
"Predefined types and their kinds."
"types"
; figure2 h
(verbatim h
("\nValue :: Type \n\n"++(concat (map f vals'))))
"Predefined functions and values."
"values"
}
prefixOp h =
figure2 h
(verbatim h
("\nOperator :: Type \n\n"++(concat (map hg infixOperators))))
"The fixed set of infix operators and their types."
"infix"
command h =
figure h (verbatim h commands)
"Legal inputs to the command line interpreter."
"commands"
modes h = itemize f h modes_and_doc
where f (name,init,doc) = hPutStr h line
where line = "{\\tt "++under name++"}. Initial value = {\\tt "++show init++"}. "++doc++"\n"
under [] = []
under ('_' : xs) = "\\_"++under xs
under (x:xs) = x: under xs
|
cartazio/omega
|
src/Manual.hs
|
Haskell
|
bsd-3-clause
| 4,733
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.