code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Nat where
import Prelude hiding ((+))
data Nat = Zero | Succ Nat deriving (Eq,Show)
(+) :: Nat -> Nat -> Nat
Zero + n = n
(Succ m) + n = Succ (m + n)
toNat :: Integer -> Nat
toNat 0 = Zero
toNat n = Succ (toNat (pred n))
fromNat :: Nat -> Integer
fromNat Zero = 0
fromNat (Succ n) = succ (fromNat n) | conal/hermit | examples/fib-stream/Nat.hs | bsd-2-clause | 315 | 0 | 9 | 77 | 171 | 91 | 80 | 12 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveGeneric #-}
module RWPAS.Actor
( sentinelActor
, Actor()
, ActorID
, ActorAppearance(..)
-- * Appearance, position, AI
, appearance
, position
, actorName
, ai
-- * Hit points
, hurt
, actorHitPoints
, emptyHitPoints
, hitPointsCritical
, hitPointsHealthy
, HasHitPoints(..)
, HitPoints()
, isDeadByHitPoints )
where
import Control.Lens
import Data.Data
import Data.SafeCopy
import Data.Text ( Text )
import GHC.Generics
import RWPAS.SafeCopyOrphanInstances()
import {-# SOURCE #-} RWPAS.Control
import {-# SOURCE #-} RWPAS.Control.Types
import Linear.V2
data Actor = Actor
{ _position :: !ActorPosition
, _appearance :: !ActorAppearance
, _ai :: !AI
, _actorName :: !Text
, _actorHitPoints :: !(Maybe HitPoints) }
deriving ( Eq, Ord, Show, Typeable, Generic )
data ActorAppearance
= PlayerCharacter
| BeastFrog
deriving ( Eq, Ord, Show, Read, Typeable, Data, Generic, Enum )
type ActorID = Int
type ActorPosition = V2 Int
data HitPoints = HitPoints
{ _hp :: !Int
, _maxHp :: !Int }
deriving ( Eq, Ord, Show, Read, Typeable, Data, Generic )
makeLenses ''Actor
makeClassy ''HitPoints
deriveSafeCopy 0 'base ''Actor
deriveSafeCopy 0 'base ''ActorAppearance
deriveSafeCopy 0 'base ''HitPoints
class HasActor a where
actor :: Lens' a Actor
instance HasActor Actor where
actor = lens id (\_ new -> new)
-- | Sentinel actor. Not meant to be used as-is, take it and modify it to be a
-- proper actor.
sentinelActor :: Text -> Actor
sentinelActor name = Actor
{ _position = V2 0 0
, _appearance = PlayerCharacter
, _ai = sentinelAI
, _actorName = name
, _actorHitPoints = Nothing }
isDeadByHitPoints :: HasHitPoints a => a -> Bool
isDeadByHitPoints thing =
thing^.hitPoints.hp <= 0 ||
thing^.hitPoints.maxHp <= 0
emptyHitPoints :: HitPoints
emptyHitPoints = HitPoints
{ _hp = 0
, _maxHp = 0 }
hurt :: Int -> Actor -> Actor
hurt points actor = case actor^.actorHitPoints of
Nothing -> actor
Just hitp -> actor & actorHitPoints .~ (Just $ hitp & hp -~ points)
hitPointsCritical :: HasHitPoints a => a -> Bool
hitPointsCritical thing =
thing^.hitPoints.hp <= (thing^.hitPoints.maxHp `div` 3)
hitPointsHealthy :: HasHitPoints a => a -> Bool
hitPointsHealthy thing =
thing^.hitPoints.hp >= (thing^.hitPoints.maxHp `div` 3 +
thing^.hitPoints.maxHp `div` 3)
| Noeda/rwpas | src/RWPAS/Actor.hs | mit | 2,485 | 0 | 12 | 511 | 731 | 406 | 325 | -1 | -1 |
module Nifty.BEB where
import Nifty.Message
import Control.Exception
import Network.Socket hiding (send)
import Network.Socket.ByteString (sendAll)
import qualified Data.ByteString as L
broadcastOnce :: (L.ByteString, L.ByteString) -- (message content, history)
-> Char
-> [Socket]
-> IO ()
broadcastOnce m pId eSockets = do
broadcastOneMessage (assembleMessage m) eSockets
where
assembleMessage (c, h) =
serializeForwardedMessage c pId h
broadcastOneMessage ::
L.ByteString
-> [Socket]
-> IO ()
broadcastOneMessage m sos = do
-- putStrLn $ "Sending message " ++ (show m) ++ " to all"
mapM_ (\s -> (sendWithError s m) `catch` hndl) sos
sendWithError ::
Socket
-> L.ByteString
-> IO ()
sendWithError sock msg = do sendAll sock msg
hndl :: IOError -> IO ()
hndl _ =
-- putStrLn $ "Error sending on socket; some processes are down? " ++( show e)
return () | adizere/nifty-urb | src/Nifty/BEB.hs | mit | 1,017 | 0 | 12 | 294 | 261 | 140 | 121 | 28 | 1 |
-- Unsafe functions
-- ref: https://wiki.haskell.org/Unsafe_functions
unsafePerformIO :: IO a -> a
unsafeInterleaveIO :: IO a -> IO a
unsafeInterleaveST :: ST s a -> ST s a
unsafeIOToST :: IO a -> ST s a
unsafeIOToSTM :: IO a -> STM a
unsafeFreeze, unsafeThaw
unsafeCoerce# :: a -> b
seq :: a -> b -> b
-- Unsafe functions can break type safety (unsafeCoerce#, unsafePerformIO), interfere with lazy IO (unsafeInterleaveIO), or break parametricity (seq). Their use (except in the case of seq) would require some kind of assurance on the part of the programmer that what they're doing is safe.
-- "unsafe" is also a keyword which can be used in a foreign import declaration. (FFI)
| Airtnp/Freshman_Simple_Haskell_Lib | Idioms/Unsafe-functions.hs | mit | 687 | 1 | 6 | 125 | 108 | 56 | 52 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Algebra.Graph.Test.Graph
-- Copyright : (c) Andrey Mokhov 2016-2022
-- License : MIT (see the file LICENSE)
-- Maintainer : andrey.mokhov@gmail.com
-- Stability : experimental
--
-- Testsuite for "Algebra.Graph" and polymorphic functions defined in
-- "Algebra.Graph.HigherKinded.Class".
-----------------------------------------------------------------------------
module Algebra.Graph.Test.Graph (
-- * Testsuite
testGraph
) where
import Data.Either
import Algebra.Graph
import Algebra.Graph.Test
import Algebra.Graph.Test.API (toIntAPI, graphAPI)
import Algebra.Graph.Test.Generic
import Algebra.Graph.ToGraph (reachable)
import qualified Data.Graph as KL
tPoly :: Testsuite Graph Ord
tPoly = ("Graph.", graphAPI)
t :: TestsuiteInt Graph
t = fmap toIntAPI tPoly
type G = Graph Int
testGraph :: IO ()
testGraph = do
putStrLn "\n============ Graph ============"
test "Axioms of graphs" (axioms @G)
test "Theorems of graphs" (theorems @G)
testBasicPrimitives t
testIsSubgraphOf t
testToGraph t
testSize t
testGraphFamilies t
testTransformations t
testInduceJust tPoly
----------------------------------------------------------------
-- Generic relational composition tests, plus an additional one
testCompose t
test "size (compose x y) <= edgeCount x + edgeCount y + 1" $ \(x :: G) y ->
size (compose x y) <= edgeCount x + edgeCount y + 1
----------------------------------------------------------------
putStrLn "\n============ Graph.(===) ============"
test " x === x == True" $ \(x :: G) ->
(x === x) == True
test " x === x + empty == False" $ \(x :: G) ->
(x === x + empty)== False
test "x + y === x + y == True" $ \(x :: G) y ->
(x + y === x + y) == True
test "1 + 2 === 2 + 1 == False" $
(1 + 2 === 2 + (1 :: G)) == False
test "x + y === x * y == False" $ \(x :: G) y ->
(x + y === x * y) == False
testMesh tPoly
testTorus tPoly
testDeBruijn tPoly
testSplitVertex t
testBind t
testSimplify t
testBox tPoly
putStrLn "\n============ Graph.sparsify ============"
test "sort . reachable x == sort . rights . reachable (Right x) . sparsify" $ \x (y :: G) ->
(sort . reachable x) y == (sort . rights . reachable (Right x) . sparsify) y
test "vertexCount (sparsify x) <= vertexCount x + size x + 1" $ \(x :: G) ->
vertexCount (sparsify x) <= vertexCount x + size x + 1
test "edgeCount (sparsify x) <= 3 * size x" $ \(x :: G) ->
edgeCount (sparsify x) <= 3 * size x
test "size (sparsify x) <= 3 * size x" $ \(x :: G) ->
size (sparsify x) <= 3 * size x
putStrLn "\n============ Graph.sparsifyKL ============"
test "sort . reachable k == sort . filter (<= n) . flip reachable k . sparsifyKL n" $ \(Positive n) -> do
let pairs = (,) <$> choose (1, n) <*> choose (1, n)
k <- choose (1, n)
es <- listOf pairs
let x = vertices [1..n] `overlay` edges es
return $ (sort . reachable k) x == (sort . filter (<= n) . flip KL.reachable k . sparsifyKL n) x
test "length (vertices $ sparsifyKL n x) <= vertexCount x + size x + 1" $ \(Positive n) -> do
let pairs = (,) <$> choose (1, n) <*> choose (1, n)
es <- listOf pairs
let x = vertices [1..n] `overlay` edges es
return $ length (KL.vertices $ sparsifyKL n x) <= vertexCount x + size x + 1
test "length (edges $ sparsifyKL n x) <= 3 * size x" $ \(Positive n) -> do
let pairs = (,) <$> choose (1, n) <*> choose (1, n)
es <- listOf pairs
let x = vertices [1..n] `overlay` edges es
return $ length (KL.edges $ sparsifyKL n x) <= 3 * size x
putStrLn "\n============ Graph.context ============"
test "context (const False) x == Nothing" $ \x ->
context (const False) (x :: G) == Nothing
test "context (== 1) (edge 1 2) == Just (Context [ ] [2 ])" $
context (== 1) (edge 1 2 :: G) == Just (Context [ ] [2 ])
test "context (== 2) (edge 1 2) == Just (Context [1 ] [ ])" $
context (== 2) (edge 1 2 :: G) == Just (Context [1 ] [ ])
test "context (const True ) (edge 1 2) == Just (Context [1 ] [2 ])" $
context (const True ) (edge 1 2 :: G) == Just (Context [1 ] [2 ])
test "context (== 4) (3 * 1 * 4 * 1 * 5) == Just (Context [3,1] [1,5])" $
context (== 4) (3 * 1 * 4 * 1 * 5 :: G) == Just (Context [3,1] [1,5])
putStrLn "\n============ Graph.buildg ============"
test "buildg (\\e _ _ _ -> e) == empty" $
buildg (\e _ _ _ -> e) == (empty :: G)
test "buildg (\\_ v _ _ -> v x) == vertex x" $ \(x :: Int) ->
buildg (\_ v _ _ -> v x) == vertex x
test "buildg (\\e v o c -> o (foldg e v o c x) (foldg e v o c y)) == overlay x y" $ \(x :: G) y ->
buildg (\e v o c -> o (foldg e v o c x) (foldg e v o c y)) == overlay x y
test "buildg (\\e v o c -> c (foldg e v o c x) (foldg e v o c y)) == connect x y" $ \(x :: G) y ->
buildg (\e v o c -> c (foldg e v o c x) (foldg e v o c y)) == connect x y
test "buildg (\\e v o _ -> foldr o e (map v xs)) == vertices xs" $ \(xs :: [Int]) ->
buildg (\e v o _ -> foldr o e (map v xs)) == vertices xs
test "buildg (\\e v o c -> foldg e v o (flip c) g) == transpose g" $ \(g :: G) ->
buildg (\e v o c -> foldg e v o (flip c) g) == transpose g
| snowleopard/alga | test/Algebra/Graph/Test/Graph.hs | mit | 6,109 | 0 | 18 | 2,107 | 1,824 | 901 | 923 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Config.Internal.RabbitMQ
( RabbitMQConfig (..)
, readRabbitMQConfig
) where
import Data.Text (Text, pack)
import System.Environment (getEnv)
data RabbitMQConfig =
RabbitMQConfig { getHost :: Text
, getPath :: Text
, getUser :: Text
, getPass :: Text
, getExchangeName :: Text
} deriving (Show, Read, Eq)
readRabbitMQConfig :: IO RabbitMQConfig
readRabbitMQConfig =
RabbitMQConfig
<$> getEnvAsText "FC_RABBITMQ_HOST"
<*> getEnvAsText "FC_RABBITMQ_PATH"
<*> getEnvAsText "FC_RABBITMQ_USER"
<*> getEnvAsText "FC_RABBITMQ_PASS"
<*> getEnvAsText "FC_RABBITMQ_EXCHANGE_NAME"
getEnvAsText :: String -> IO Text
getEnvAsText varName = pack <$> (getEnv varName)
| gust/feature-creature | legacy/lib/Config/Internal/RabbitMQ.hs | mit | 808 | 0 | 10 | 198 | 175 | 98 | 77 | 23 | 1 |
import Text.Parsec
import Text.Parsec.String
import Data.Maybe (fromJust)
value :: Char -> Int
value c = fromJust . lookup c $ [
('I', 1),
('V', 5),
('X', 10),
('L', 50),
('C', 100),
('D', 500),
('M', 1000)]
single :: Char -> Parser Int
single c = do
x <- many (char c)
return $ length x * value c
pair :: Char -> Char -> Parser Int
pair small big = do
string $ small:big:""
return $ value big - value small
roman :: Parser Int
roman = do
m <- single 'M'
d <- single 'D'
c <- try (pair 'C' 'M') <|> try (pair 'C' 'D') <|> (single 'C')
l <- single 'L'
x <- try (pair 'X' 'C') <|> try (pair 'X' 'L') <|> (single 'X')
v <- single 'V'
i <- try (pair 'I' 'X') <|> try (pair 'I' 'V') <|> (single 'I')
eof
return $ m + d + c + l + x + v + i
main = do
print $ parse roman "fail" "XVII"
print $ parse roman "fail" "IV"
print $ parse roman "fail" "IX"
print $ parse roman "fail" "MMCDXLVI"
| Russell91/roman | 09.hs | mit | 981 | 0 | 13 | 289 | 501 | 246 | 255 | 36 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RankNTypes, GADTs #-}
-- This module requires GHC 8 to compile.
module Lang where
import Common
import DataDynamic
-- | This module defines a simple untyped language using the Dynamic module.
-- =======================================================================================
-- Simple untyped language.
data Exp where
Lam :: String -> Exp -> Exp -- ^ Function abstraction as \x . e
(:@) :: Exp -> Exp -> Exp -- ^ Function application (e1 e2)
Bin :: BinOp -> Exp -> Exp -> Exp -- ^ Binary operator.
Uni :: UniOp -> Exp -> Exp
Lit :: forall t. (LangType t) => t -> Exp -- ^ literal.
Var :: String -> Exp -- ^ Variable.
If :: Exp -> Exp -> Exp -> Exp -- ^ Conditional branching.
Nill :: Exp -- ^ lists.
-- Notice we can use Haskell's let and where syntax to define expressions.
-- Useful for debugging and simple viewing.
instance Show Exp where
show (Lam str e) = "(Lam " ++ str ++ " " ++ show e ++ ")"
show (e1 :@ e2) = "(" ++ show e1 ++ " @ " ++ show e2 ++ ")"
show (Bin op e1 e2) = "(" ++ show op ++ " " ++ show e1 ++ " " ++ show e2 ++ ")"
show (Uni op e) = "(" ++ show op ++ " " ++ show e ++ ")"
show (Lit x) = "Lit " ++ show x
show (Var x) = "(Var " ++ x ++ ")"
show (If e1 e2 e3) = "(If " ++ show e1 ++ " " ++ show e2 ++ " " ++ show e3 ++ ")"
show Nill = "[]"
-- No alpha equivalance here :/
instance Eq Exp where
Lam s e == Lam s' e' = s == s' && e == e'
e1 :@ e2 == e1' :@ e2' = e1 == e1' && e2 == e2'
Bin op e1 e2 == Bin op' e1' e2' = op == op' && e1 == e1' && e2 == e2'
Uni op e == Uni op' e' = op == op' && e == e'
-- There has to be a better way to do this?
Lit x == Lit x' = toDynamic x == toDynamic x'
Var s == Var s' = s == s'
If e1 e2 e3 == If e1' e2' e3' = e1 == e1' && e2 == e2' && e3 == e3'
Nill == Nill = True
_ == _ = False
-- =======================================================================================
| plclub/cis670-16fa | projects/DynamicLang/src/Lang.hs | mit | 2,007 | 0 | 12 | 537 | 680 | 341 | 339 | -1 | -1 |
module Minibas.Util (
totalScore
, quarterUrls
, buildScoreData
, buildGameData
, buildGameData'
) where
import Import
import Control.Lens ((^.))
import qualified Data.List as L (foldl, sortOn, (!!))
import qualified Data.Map as M (Map, lookup)
import Data.Maybe (fromJust)
import Data.Time.LocalTime (utcToLocalZonedTime)
import Jabara.Persist.Util (toMap, toRecord)
import Jabara.Util (listToListMap)
import Jabara.Yesod.Util (getResourcePath)
totalScore :: [Entity Score] -> (Int, Int)
totalScore = L.foldl (\(a,b) (Entity _ score) ->
let as = score^.scoreTeamAPoint
bs = score^.scoreTeamBPoint
in (a+as,b+bs)
) (0,0)
quarterUrls :: (MonadHandler m, HandlerSite m ~ App) => GameId -> m [Text]
quarterUrls gameId = do
firstUrl <- getResourcePath $ GameScoreFirstR gameId
secondUrl <- getResourcePath $ GameScoreSecondR gameId
thirdUrl <- getResourcePath $ GameScoreThirdR gameId
fourthUrl <- getResourcePath $ GameScoreFourthR gameId
extraUrl <- getResourcePath $ GameScoreExtraR gameId
pure [firstUrl, secondUrl, thirdUrl, fourthUrl, extraUrl]
buildScoreData :: (MonadHandler m, HandlerSite m ~ App) =>
GameId -> Entity Score -> m ScoreData
buildScoreData gameId (Entity key score) = do
urls <- quarterUrls gameId
url <- do
let idx = fromEnum $ score^.scoreQuarter
pure (urls L.!! idx)
pure $ ScoreData {
_scoreDataId = key
, _scoreDataGame = gameId
, _scoreDataQuarter = score^.scoreQuarter
, _scoreDataTeamAPoint = score^.scoreTeamAPoint
, _scoreDataTeamBPoint = score^.scoreTeamBPoint
, _scoreDataLock = score^.scoreLock
, _scoreDataUrlBase = url
}
buildGameData :: (MonadHandler m, HandlerSite m ~ App) =>
[Entity League]
-> [Entity Team]
-> [Entity Score]
-> Entity Game
-> m GameData
buildGameData leagues teams scores game = buildGameData'
(toMap leagues)
(toMap teams)
(listToListMap (_scoreGame.toRecord) scores)
game
buildGameData' :: (MonadHandler m, HandlerSite m ~ App) =>
M.Map LeagueId League
-> M.Map TeamId Team
-> M.Map GameId [Entity Score]
-> Entity Game
-> m GameData
buildGameData' leagueMap teamMap scoreMap (Entity gameId game) = do
urlBase <- getResourcePath $ GameR gameId
urlEdit <- getResourcePath $ GameUiR gameId
let scores = L.sortOn (_scoreQuarter.toRecord)
$ fromJust $ M.lookup gameId scoreMap
total = totalScore scores
league = getFromMap (game^.gameLeague) leagueMap
teamA = getFromMap (game^.gameTeamA) teamMap
teamB = getFromMap (game^.gameTeamB) teamMap
scores' <- mapM (buildScoreData gameId) scores
date <- liftIO $ utcToLocalZonedTime $ game^.gameDate
pure $ GameData {
_gameDataId = gameId
, _gameDataName = game^.gameName
, _gameDataPlace = game^.gamePlace
, _gameDataLeague = league
, _gameDataLeagueName = (toRecord league)^.leagueName
, _gameDataTeamA = teamA
, _gameDataTeamAName = (toRecord teamA)^.teamName
, _gameDataTeamBName = (toRecord teamB)^.teamName
, _gameDataTeamB = teamB
, _gameDataTeamAScore = fst total
, _gameDataTeamBScore = snd total
, _gameDataUrlBase = urlBase
, _gameDataUrlEdit = urlEdit
, _gameDataDate = date
, _gameDataScoreList = scores'
}
where
getFromMap :: PersistEntity r => Key r -> Map (Key r) r -> Entity r
getFromMap key entityMap = Entity key $ fromJust $ M.lookup key entityMap
| jabaraster/minibas-web | Minibas/Util.hs | mit | 4,054 | 0 | 14 | 1,316 | 1,116 | 590 | 526 | 90 | 1 |
{-# Language TemplateHaskell #-}
module Labyrinth.Move where
import Control.Lens hiding (Action)
import Labyrinth.Map
data MoveDirection = Towards Direction | Next
deriving (Eq)
type ActionCondition = String
data Action = Go { _amdirection :: MoveDirection }
| Shoot { _asdirection :: Direction }
| Grenade { _agdirection :: Direction }
| Surrender
| Conditional { _acif :: ActionCondition
, _acthen :: [Action]
, _acelse :: [Action]
}
deriving (Eq)
makeLenses ''Action
goTowards :: Direction -> Action
goTowards = Go . Towards
data QueryType = BulletCount
| GrenadeCount
| PlayerHealth
| TreasureCarried
deriving (Eq)
data Move = Move { _mactions :: [Action] }
| ChoosePosition { _mcposition :: Position }
| ReorderCell { _mrposition :: Position }
| Query { _mqueries :: [QueryType] }
| Say { _msstext :: String }
deriving (Eq)
makeLenses ''Move
data CellTypeResult = LandR
| ArmoryR
| HospitalR
| PitR
| RiverR
| RiverDeltaR
deriving (Eq)
ctResult :: CellType -> CellTypeResult
ctResult Land = LandR
ctResult Armory = ArmoryR
ctResult Hospital = HospitalR
ctResult (Pit _) = PitR
ctResult (River _) = RiverR
ctResult RiverDelta = RiverDeltaR
data TreasureResult = TurnedToAshesR
| TrueTreasureR
deriving (Eq)
data CellEvents = CellEvents { _foundBullets :: Int
, _foundGrenades :: Int
, _foundTreasures :: Int
, _transportedTo :: Maybe CellTypeResult
} deriving (Eq)
makeLenses ''CellEvents
noEvents :: CellEvents
noEvents = CellEvents { _foundBullets = 0
, _foundGrenades = 0
, _foundTreasures = 0
, _transportedTo = Nothing
}
data GoResult = Went { _onto :: CellTypeResult
, _wevents :: CellEvents
}
| WentOutside { _treasureResult :: Maybe TreasureResult
}
| HitWall { _hitr :: CellEvents
}
| LostOutside
| InvalidMovement
deriving (Eq)
makeLenses ''GoResult
data ShootResult = ShootOK
| Scream
| NoBullets
| Forbidden
deriving (Eq, Show)
data GrenadeResult = GrenadeOK
| NoGrenades
deriving (Eq, Show)
data ChoosePositionResult = ChosenOK
| ChooseAgain
deriving (Eq)
data ReorderCellResult = ReorderOK { _ronto :: CellTypeResult
, _revents :: CellEvents
}
| ReorderForbidden {}
deriving (Eq)
makeLenses ''ReorderCellResult
data QueryResult = BulletCountR { _qrbullets :: Int }
| GrenadeCountR { _qrgrenades :: Int }
| HealthR { _qrhealth :: Health }
| TreasureCarriedR { _qrtreasure :: Bool }
deriving (Eq)
makeLenses ''QueryResult
data StartResult = StartR { _splayer :: PlayerId
, _scell :: CellTypeResult
, _sevents :: CellEvents
} deriving (Eq)
makeLenses ''StartResult
data ActionResult = GoR GoResult
| ShootR ShootResult
| GrenadeR GrenadeResult
| Surrendered
| WoundedAlert PlayerId Health
| ChoosePositionR ChoosePositionResult
| ReorderCellR ReorderCellResult
| QueryR QueryResult
| GameStarted [StartResult]
| Draw
| WrongTurn
| InvalidMove
deriving (Eq)
data MoveResult = MoveRes [ActionResult]
deriving (Eq)
| koterpillar/labyrinth | src/Labyrinth/Move.hs | mit | 4,391 | 1 | 9 | 1,986 | 821 | 482 | 339 | 108 | 1 |
module Monad where
import Control.Monad.Except (ExceptT, runExceptT)
import Control.Monad.Reader (ReaderT, runReaderT)
import Text.Parsec (ParseError)
import Config.Types
-- | The base monad
type Sparker = ExceptT SparkError (ReaderT SparkConfig IO)
runSparker :: SparkConfig -> Sparker a -> IO (Either SparkError a)
runSparker conf func = runReaderT (runExceptT func) conf
data SparkError = ParseError ParseError
| PreCompileError [PreCompileError]
| CompileError CompileError
| DeployError DeployError
| UnpredictedError String
deriving (Show, Eq)
type CompileError = String
type PreCompileError = String
type DeployError = String
| badi/super-user-spark | src/Monad.hs | mit | 757 | 0 | 9 | 204 | 176 | 101 | 75 | 17 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module DarkSky.Client
( getForecast
, httpRequest
) where
import DarkSky.Request
import DarkSky.Response (Response)
import Data.ByteString.Char8 (pack)
import Network.HTTP.Simple as HTTP
getForecast :: DarkSky.Request.Request -> IO DarkSky.Response.Response
getForecast request = getResponseBody <$> httpJSON (httpRequest request)
httpRequest :: DarkSky.Request.Request -> HTTP.Request
httpRequest r =
setRequestQueryString queryParameters .
setRequestPath (pack $ path r) .
setRequestHost "api.darksky.net" . setRequestPort 443 . setRequestSecure True $
defaultRequest
where
queryParameters = convert <$> parameters r
convert (key', value') = (pack key', Just $ pack value')
| peterstuart/dark-sky | src/DarkSky/Client.hs | mit | 739 | 0 | 13 | 110 | 199 | 107 | 92 | 18 | 1 |
{------------------------------------------------------------------------------
uPuppet: Main program
------------------------------------------------------------------------------}
import UPuppet.Errors
import UPuppet.Options
import UPuppet.CState
import UPuppet.AST
import UPuppet.Catalog
import UPuppet.Parser
import UPuppet.Eval
import UPuppet.ShowAST
import UPuppet.ShowCatalog
import UPuppet.ShowJSON
import System.Environment (getArgs)
import System.IO (hPutStr, stderr)
import System.Exit (exitWith, ExitCode(..), exitSuccess)
{------------------------------------------------------------------------------
main program
------------------------------------------------------------------------------}
main = do
-- command line args
(opts, files) <- getArgs >>= parseOptions
-- process each file on the command line
status <- mapM (compileAndSave opts) files
-- return failure if any of the compilations fails
if (and status) then exitSuccess else exitWith (ExitFailure 1)
{------------------------------------------------------------------------------
parse/evaluate/render source from file
------------------------------------------------------------------------------}
compile :: CState -> IO (Either Errors String)
compile st = do
-- parse
src <- readFile $ srcPath (sOpts st)
astOrError <- parsePuppet st src
case astOrError of
Right ast -> evaluate st ast
Left errs -> return $ Left errs
where
-- evaluate
evaluate :: CState -> AST -> IO (Either Errors String)
evaluate st ast = case (format (sOpts st)) of
AST_FORMAT -> return $ Right $ showAST st ast
otherwise -> do
catalogOrError <- evalPuppet st ast
case catalogOrError of
Right catalog -> render st catalog
Left errs -> return $ Left errs
-- render
render :: CState -> Catalog -> IO (Either Errors String)
render st catalog = case (format $ sOpts st) of
CATALOG_FORMAT -> return $ Right $ showCatalog st catalog
JSON_FORMAT -> return $ Right $ showJSON st catalog
otherwise -> error "unsupported output format"
{------------------------------------------------------------------------------
compile and save to file (or report errors)
------------------------------------------------------------------------------}
compileAndSave :: Opts -> String -> IO (Bool)
compileAndSave opts path = do
let opts' = opts { srcPath=path }
let st = newState opts'
resultOrError <- compile st
case resultOrError of
Left errs -> do
hPutStr stderr $ showErrors errs
return False
Right result -> do
let dstPath = outputPath opts'
if (dstPath == "-") then putStrLn result else writeFile dstPath (result++"\n")
return True
| dcspaul/uPuppet | Src/uPuppet.hs | mit | 2,694 | 0 | 16 | 434 | 651 | 324 | 327 | 50 | 6 |
module Control.Monad.Classes.Zoom where
import Control.Applicative
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Base
import Control.Monad.IO.Class
import Control.Monad.Trans.Control
import Control.Monad.Classes.Core
import Control.Monad.Classes.Effects
import Control.Monad.Classes.Reader
import Control.Monad.Classes.State
import Control.Monad.Classes.Writer
import Control.Monad.Classes.Proxied
import Data.Functor.Identity
import Data.Monoid
newtype ZoomT big small m a = ZoomT (Proxied (VLLens big small) m a)
deriving (Functor, Applicative, Alternative, Monad, MonadPlus, MonadTrans, MonadBase b, MonadIO)
newtype VLLens big small = VLLens (forall f . Functor f => (small -> f small) -> big -> f big)
vlGet :: VLLens b a -> b -> a
vlGet (VLLens l) s = getConst (l Const s)
vlSet :: VLLens b a -> a -> b -> b
vlSet (VLLens l) v s = runIdentity (l (\_ -> Identity v) s)
-- N.B. applies function eagerly
vlMod' :: VLLens b a -> (a -> a) -> b -> b
vlMod' (VLLens l) f s = runIdentity (l (\x -> Identity $! f x) s)
runZoom
:: forall big small m a .
(forall f. Functor f => (small -> f small) -> big -> f big)
-> ZoomT big small m a
-> m a
runZoom l a =
reify (VLLens l) $ \px ->
case a of ZoomT (Proxied f) -> f px
type instance CanDo (ZoomT big small m) eff = ZoomCanDo small eff
type family ZoomCanDo s eff where
ZoomCanDo s (EffState s) = 'True
ZoomCanDo s (EffReader s) = 'True
ZoomCanDo s (EffWriter s) = 'True
ZoomCanDo s eff = 'False
instance MonadReader big m => MonadReaderN 'Zero small (ZoomT big small m)
where
askN _ = ZoomT $ Proxied $ \px -> vlGet (reflect px) `liftM` ask
instance MonadState big m => MonadStateN 'Zero small (ZoomT big small m)
where
stateN _ f = ZoomT $ Proxied $ \px ->
let l = reflect px in
state $ \s ->
case f (vlGet l s) of
(a, t') -> (a, vlSet l t' s)
instance (MonadState big m, Monoid small) => MonadWriterN 'Zero small (ZoomT big small m)
where
tellN _ w = ZoomT $ Proxied $ \px ->
let l = reflect px in
state $ \s ->
let s' = vlMod' l (<> w) s
in s' `seq` ((), s')
instance MonadTransControl (ZoomT big small) where
type StT (ZoomT big small) a = a
liftWith = defaultLiftWith ZoomT (\(ZoomT a) -> a)
restoreT = defaultRestoreT ZoomT
instance MonadBaseControl b m => MonadBaseControl b (ZoomT big small m) where
type StM (ZoomT big small m) a = StM m a
liftBaseWith = defaultLiftBaseWith
restoreM = defaultRestoreM
| feuerbach/monad-classes | Control/Monad/Classes/Zoom.hs | mit | 2,504 | 0 | 17 | 536 | 1,055 | 561 | 494 | -1 | -1 |
module Problem6 ( isPalindrome ) where
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome str = (reverse str) == str | chanind/haskell-99-problems | Problem6.hs | mit | 117 | 0 | 7 | 21 | 48 | 27 | 21 | 3 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.CSSFontFaceRule
(js_getStyle, getStyle, CSSFontFaceRule, castToCSSFontFaceRule,
gTypeCSSFontFaceRule)
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 (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
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.Enums
foreign import javascript unsafe "$1[\"style\"]" js_getStyle ::
JSRef CSSFontFaceRule -> IO (JSRef CSSStyleDeclaration)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/CSSFontFaceRule.style Mozilla CSSFontFaceRule.style documentation>
getStyle ::
(MonadIO m) => CSSFontFaceRule -> m (Maybe CSSStyleDeclaration)
getStyle self
= liftIO ((js_getStyle (unCSSFontFaceRule self)) >>= fromJSRef) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/CSSFontFaceRule.hs | mit | 1,396 | 6 | 11 | 165 | 377 | 238 | 139 | 24 | 1 |
{-|
A module which implements the translation from pepa models to timed
system equations.
The model should have already been transformed into canonical form,
and in particular sequential derivatives should all be named.
Although actually maybe I can get rid of the whole process
concentrations database by simply not removing the process arrays
before we get here? Ach actually no I don't think we can.
-}
module Language.Pepa.Ode.TimedSystemEquation
( TimedSystemEqn ( .. )
, TimedSystem
, ConcentrationDB
, toTimedSystem
, apparentTSErate
, formatTimedSystem
, formatTimedEquation
, NVFcomp ( .. )
, getNvfIdentifier
, formatNumericalForm
, TSEcptExpression ( .. )
, formatTseCompExpr
)
where
{- Standard Library Modules Imported -}
import Prelude hiding
( lookup )
import Data.List
( union
, nub
, partition
)
import Data.Map
( Map
, empty
, lookup
)
import Data.Maybe
( fromMaybe )
{- Non-Standard Library Modules Imported -}
{- Local Library Modules Imported -}
import Language.Pepa.Utils
( mkCSlist )
import Language.Pepa.Print
( HumanPrint ( .. ) )
import Language.Pepa.Syntax
( ParsedModel ( .. )
, ParsedComponentId
, ParsedComponent ( .. )
, ParsedAction
, ParsedRate
, RateSpec
)
import Language.Pepa.PepaUtils
( isPepaActionEnabled )
import Language.Pepa.Analysis.Analysis
( possibleSuccessors )
import Language.Pepa.ApparentRates
( summedPepaRate )
{- End of Module Imports -}
type TimedSystem = ([ RateSpec ], ConcentrationDB, TimedSystemEqn)
{-| The data type for the main system equation of a pepa model translated
into a timed system equation.
-}
data TimedSystemEqn =
TSECooperation TimedSystemEqn [ ParsedAction ] TimedSystemEqn
| TSEHide TimedSystemEqn [ ParsedAction ]
| TSENumVerForm [ NVFcomp ] [ ParsedAction ]
{-| The numerical vector form of a component is used to count the number
of the sequential derivatives of the process @S@ in the cooperation
@S <L> S <L> S <L> S ... <L> S <L> S@
-}
data NVFcomp = NVFcomp CompCount ParsedComponentId
type CompCount = Int
data TSEcptExpression =
TSEmin TSEcptExpression TSEcptExpression
| TSEsum TSEcptExpression TSEcptExpression
| TSEproduct TSEcptExpression TSEcptExpression
| TSEatom ParsedComponentId ParsedRate
| TSEcpt ParsedComponentId -- used when simplifying min(c1*r1, c2*r2)
| TSErate ParsedRate
| TSEind TSEcptIndicator
| TSEzero
-- Indicator function on cs list of component types I((\sum_{c\in cs} c) > 0)
-- TSEindC is the complement of the indicator function
type TSEiInvIndElem = ( ParsedComponentId, ParsedRate )
-- Not exactly sure what this is for?
data TSEcptIndicator =
TSEiInd [ ParsedComponentId ]
| TSEiIndC [ ParsedComponentId ]
| TSEiInverseInd [ TSEiInvIndElem ]
deriving Show
instance Show TSEcptExpression where
show (TSEmin t1 t2) = concat ["min", " (", show t1, ", ", show t2, ")"]
show (TSEsum t1 t2) = concat [show t1, " + ", show t2]
show (TSEproduct t1 t2) = concat [show t1, " * ", show t2]
show (TSEatom c r) = (show c)++"*"++(show r)
show (TSEcpt c) = (show c)
show (TSErate r) = show r
show (TSEind i) = "I( "++(show i)++" )"
show TSEzero = "TSEzero"
instance Eq TSEcptExpression where
(==) TSEzero TSEzero = True
(==) _ _ = False
instance Ord TSEcptExpression where
min = TSEmin
instance Num TSEcptExpression where
(+) = TSEsum
(*) = TSEproduct
signum _ = error "TSEcptExpression.signum: not defined"
abs _ = error "TSEcptExpression.abs: not defined"
fromInteger 0 = TSEzero
fromInteger _ = error "TSEcptExpression.fromInteger: only defined for 0"
{-| A bit of a temporary 'toTimedSystem' obviously this should return
something more sensible for the rate specifications and for
the concentration data base.
-}
toTimedSystem :: ParsedModel -> TimedSystem
toTimedSystem model@(ParsedModel rDefs _pDefs mainComp) =
( rDefs
, concentrations
, translateComposition mainComp model concentrations
)
where
concentrations = empty
{-| translates a composition into a timed system equation -}
-- A small point here, we should really check if it is a simple
-- cooperation between the same two components ie @ P <L> P @
-- and in such a case we can return a 'NVFcomp'
translateComposition :: ParsedComponent -> ParsedModel -> ConcentrationDB
-> TimedSystemEqn
translateComposition (IdProcess ident) model cDb =
translateComponent ident model cDb
translateComposition (Cooperation left actions right) model cDb =
TSECooperation tLeft actions tRight
where
tLeft = translateComposition left model cDb
tRight = translateComposition right model cDb
translateComposition (ProcessArray _ident _size _mActions) _model _cDb =
error "Not yet implemented process arrays in TimedSystemEquations"
translateComposition (Hiding _ident _actions) _model _cDb =
error "Not yet implemented hiding in TimedSystemEquations"
translateComposition (ComponentSum _ _) _model _cDb =
error "There should be no component sums in the main composition"
translateComposition (PrefixComponent _ _) _model _cDb =
error "There should be no prefix components in the main composition"
{-| translates a component into a timed system equation -}
translateComponent :: ParsedComponentId -> ParsedModel -> ConcentrationDB
-> TimedSystemEqn
translateComponent ident model concentrations =
TSENumVerForm nvfcomps [] -- The action set is empty
where
nvfcomps = mkHeadNVFC ident : (map mkTailNVFC derivatives)
-- Actually holds derivatives minus the component itself, since
-- we this is added at the head above.
derivatives = nub (filter (ident /=) $ sequentialDerivatives ident model )
-- makes an nvfc, with the given concentration, however the given
-- concentration may be overridden by what is in the concentration
-- database.
mkNVFC :: CompCount -> ParsedComponentId -> NVFcomp
mkNVFC i p = NVFcomp (fromMaybe i $ lookup p concentrations) p
-- So now making the head or any of the tail components is
-- just the above but for the head component the default concentration
-- is 1 and for the others it is 0.
-- Actually I'm thinking it should *always* be zero, basically for the
-- tail components they shouldn't be a process array.
mkTailNVFC :: ParsedComponentId -> NVFcomp
mkTailNVFC = mkNVFC 0
mkHeadNVFC :: ParsedComponentId -> NVFcomp
mkHeadNVFC = mkNVFC 1
{-| Return the Component name of a Numerical Vector Component -}
getNvfIdentifier :: NVFcomp -> ParsedComponentId
getNvfIdentifier (NVFcomp _count ident) = ident
{-
I should note that perhaps all this getting the sequential derivatives
should be in the 'Language.Pepa.Analysis.Analysis' module somewhere.
-}
{-| We require a mapping from process identifiers to concentrations -}
type ConcentrationDB = Map ParsedComponentId Int
{-| We will require a pepa database mapping process identifiers
to their process definitions
-}
type ProcessDataBase = Map ParsedComponentId ParsedComponent
{-| We wish to return a list of sequential derivatives of a component
these therefore can be stored in a mapping.
-}
type DerivativeDataBase = Map ParsedComponentId [ ParsedComponentId ]
{-| Given a process data base and a process identifier we return all the derivatives
of the given process identifier.
-}
sequentialDerivatives :: ParsedComponentId -> ParsedModel
-> [ ParsedComponentId ]
sequentialDerivatives ident model =
getDeriv [ident] []
where
-- Use breadth first search to find the derivatives of the given components
-- the first argument is a todo list, that is components we have yet to visit
-- and the second argument is seen list, that is, we've already seen this
-- component and it's either been done or on the todo list.
getDeriv :: [ ParsedComponentId ] -> [ ParsedComponentId ]
-> [ ParsedComponentId ]
getDeriv [] visited = visited
getDeriv (first : rest) visited
| elem first visited = getDeriv rest visited
| otherwise = getDeriv stillToVisit nowVisited
where
stillToVisit = union rest reachable
nowVisited = first : visited
-- reachable with just one transition
reachable = possibleSuccessors first model
{-|
@r_a(P)@ function from eqn (5) of Bradley-Hillston 2006
NOTE: this function uses
'Language.Pepa.ApparentRates.summedPepaRate'
and I think it should use
'Language.Pepa.ApparentRates.apparentPepaRate'
but the code that was given to me did not and hence I am not.
-}
apparentTSErate :: ParsedAction -> TimedSystemEqn
-> ParsedModel -> TSEcptExpression
apparentTSErate a (TSECooperation t1 ls t2) model
| elem a ls =
min (apparentTSErate a t1 model) (apparentTSErate a t2 model)
| otherwise =
(apparentTSErate a t1 model) + (apparentTSErate a t2 model)
apparentTSErate a (TSEHide t ls) model
| elem a ls = 0
| otherwise = apparentTSErate a t model
apparentTSErate a (TSENumVerForm cs ls) model
| elem a ls =
(TSEind $ TSEiIndC $ map getNvfIdentifier cnes)
* minimum [ TSEind $ TSEiInverseInd inverseElems ]
| otherwise =
sum $ map mkAtom cs
where
inverseElems = map mkInvElem ces
mkInvElem :: NVFcomp -> TSEiInvIndElem
mkInvElem c = ( ident, summedPepaRate a ident model )
where ident = getNvfIdentifier c
-- ces: list of NVF components enabling a
-- cnes: list of NVF components not enabling a
(ces, cnes) = partition partitionFun cs
partitionFun :: NVFcomp -> Bool
partitionFun c = isPepaActionEnabled a (getNvfIdentifier c) model
mkAtom :: NVFcomp -> TSEcptExpression
mkAtom c = TSEatom ident (summedPepaRate a ident model)
where ident = getNvfIdentifier c
{-| The printing of a timed system -}
formatTimedSystem :: TimedSystem -> String
formatTimedSystem (_rates, _concentrations, timedEqn) =
formatTimedEquation timedEqn
formatTimedEquation :: TimedSystemEqn -> String
formatTimedEquation (TSECooperation left actions right) =
unlines [ formatTimedEquation left
, concat [ "<", mkCSlist $ map hprint actions, ">" ]
, formatTimedEquation right
]
formatTimedEquation( TSEHide left actions) =
unwords [ formatTimedEquation left
, "/{"
, mkCSlist $ map hprint actions
, "}"
]
formatTimedEquation (TSENumVerForm nForms actions) =
concat [ "("
, mkCSlist $ map formatNumericalForm nForms
, ")"
, "<"
, mkCSlist $ map hprint actions
, ">"
]
formatTseCompExpr :: TSEcptExpression -> String
formatTseCompExpr (TSEmin t1 t2) =
unwords [ "min"
, "("
, formatTseCompExpr t1
, ","
, formatTseCompExpr t2
, ")"
]
formatTseCompExpr (TSEsum t1 t2) =
unwords [ formatTseCompExpr t1
, "+"
, formatTseCompExpr t2
]
formatTseCompExpr (TSEproduct t1 t2) =
unwords [formatTseCompExpr t1
, "*"
, formatTseCompExpr t2
]
formatTseCompExpr (TSEcpt c) =
hprint c
formatTseCompExpr (TSEatom c r) =
concat [ hprint c
, "*"
, hprint r
]
formatTseCompExpr (TSErate r) =
hprint r
formatTseCompExpr (TSEind i) =
unwords [ "I("
, show i
, ")"
]
formatTseCompExpr (TSEzero) = "0"
{-| The formatting of a component in numerical vector form -}
formatNumericalForm :: NVFcomp -> String
formatNumericalForm ( NVFcomp i ident) =
concat [ "("
, show i
, ","
, hprint ident
, ")"
] | allanderek/ipclib | Language/Pepa/Ode/TimedSystemEquation.hs | gpl-2.0 | 12,226 | 0 | 11 | 3,178 | 2,215 | 1,191 | 1,024 | 219 | 2 |
module Controllers.Game.Model.ServerPlayer (ServerPlayer(ServerPlayer),
name,
identifier,
makeNewPlayer,
makeGameStatePlayers,
makeNewPlayerId) where
import Data.Text
import Prelude
import Network.Mail.Mime
import Control.Applicative
import System.Random
import qualified Wordify.Rules.Player as G
data ServerPlayer = ServerPlayer {name :: Text, identifier :: Text}
makeNewPlayer :: Text -> Text -> ServerPlayer
makeNewPlayer playerName gameId = ServerPlayer playerName gameId
makeNewPlayerId :: StdGen -> (Text, StdGen)
makeNewPlayerId generator =
let (result, newGen) = randomString 8 generator
in (pack result, newGen)
makeGameStatePlayers :: Int -> Either Text (G.Player, G.Player, Maybe (G.Player, Maybe G.Player))
makeGameStatePlayers numPlayers
| numPlayers == 2 = Right (G.makePlayer "player1", G.makePlayer "player2", Nothing)
| numPlayers == 3 = Right (G.makePlayer "player1", G.makePlayer "player2", Just ((G.makePlayer "player3"), Nothing))
| numPlayers == 4 = Right (G.makePlayer "player1", G.makePlayer "player2", Just ((G.makePlayer "player3"), Just (G.makePlayer "player4")))
| otherwise = Left "Invalid number of players"
| Happy0/liscrabble | src/Controllers/Game/Model/ServerPlayer.hs | gpl-2.0 | 1,474 | 0 | 13 | 466 | 379 | 204 | 175 | 27 | 1 |
module Roller.CLI (
CLI(..)
, withOpts
) where
import Options.Applicative
import Control.Applicative
type CLI a = Bool -> Int -> [String] -> a
withOpts :: CLI a -> IO a
withOpts f = execParser . info (helper <*> handleOpts) $ infoMod
where
handleOpts =
f <$> switch ( long "verbose"
<> short 'v'
<> help "List out each roll")
<*> option auto ( long "nrolls"
<> value 1
<> short 'n'
<> help "Number of times to roll the expression")
<*> some (argument str (metavar "EXPR.." <> help "Dice expressions"))
infoMod = fullDesc <> progDesc "Roll some dice"
| PiotrJustyna/roller | Roller/CLI.hs | gpl-2.0 | 657 | 0 | 14 | 205 | 201 | 102 | 99 | 18 | 1 |
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-}
module CoreTypes where
import Control.Concurrent
import Data.Word
import qualified Data.Map as Map
import Data.Sequence(Seq, empty)
import Data.Time
import Network
import Data.Function
import Data.ByteString.Char8 as B
import Data.Unique
import Control.Exception
import Data.Typeable
import Data.TConfig
-----------------------
import RoomsAndClients
type ClientChan = Chan [B.ByteString]
data ClientInfo =
ClientInfo
{
clUID :: Unique,
sendChan :: ClientChan,
clientSocket :: Socket,
host :: B.ByteString,
connectTime :: UTCTime,
nick :: B.ByteString,
webPassword :: B.ByteString,
logonPassed :: Bool,
clientProto :: !Word16,
roomID :: RoomIndex,
pingsQueue :: !Word,
isMaster :: Bool,
isReady :: !Bool,
isAdministrator :: Bool,
clientClan :: Maybe B.ByteString,
teamsInGame :: Word
}
instance Eq ClientInfo where
(==) = (==) `on` clientSocket
data HedgehogInfo =
HedgehogInfo B.ByteString B.ByteString
data TeamInfo =
TeamInfo
{
teamownerId :: ClientIndex,
teamowner :: B.ByteString,
teamname :: B.ByteString,
teamcolor :: B.ByteString,
teamgrave :: B.ByteString,
teamfort :: B.ByteString,
teamvoicepack :: B.ByteString,
teamflag :: B.ByteString,
difficulty :: Int,
hhnum :: Int,
hedgehogs :: [HedgehogInfo]
}
data RoomInfo =
RoomInfo
{
masterID :: ClientIndex,
name :: B.ByteString,
password :: B.ByteString,
roomProto :: Word16,
teams :: [TeamInfo],
gameinprogress :: Bool,
playersIn :: !Int,
readyPlayers :: !Int,
isRestrictedJoins :: Bool,
isRestrictedTeams :: Bool,
roundMsgs :: Seq B.ByteString,
leftTeams :: [B.ByteString],
teamsAtStart :: [TeamInfo],
mapParams :: Map.Map B.ByteString B.ByteString,
params :: Map.Map B.ByteString [B.ByteString]
}
newRoom :: RoomInfo
newRoom =
RoomInfo
(error "No room master defined")
""
""
0
[]
False
0
0
False
False
Data.Sequence.empty
[]
[]
(
Map.fromList $ Prelude.zipWith (,)
["MAP", "MAPGEN", "MAZE_SIZE", "SEED", "TEMPLATE"]
["+rnd+", "0", "0", "seed", "0"]
)
(Map.singleton "SCHEME" ["Default"])
data StatisticsInfo =
StatisticsInfo
{
playersNumber :: Int,
roomsNumber :: Int
}
data ServerInfo =
ServerInfo
{
isDedicated :: Bool,
serverMessage :: B.ByteString,
serverMessageForOldVersions :: B.ByteString,
latestReleaseVersion :: Word16,
earliestCompatibleVersion :: Word16,
listenPort :: PortNumber,
nextRoomID :: Int,
dbHost :: B.ByteString,
dbName :: B.ByteString,
dbLogin :: B.ByteString,
dbPassword :: B.ByteString,
bans :: [BanInfo],
restartPending :: Bool,
coreChan :: Chan CoreMessage,
dbQueries :: Chan DBQuery,
serverConfig :: Maybe Conf
}
newServerInfo :: Chan CoreMessage -> Chan DBQuery -> Maybe Conf -> ServerInfo
newServerInfo =
ServerInfo
True
"<h2><p align=center><a href=\"http://www.hedgewars.org/\">http://www.hedgewars.org/</a></p></h2>"
"<font color=yellow><h3 align=center>Hedgewars 0.9.16 is out! Please update.</h3><p align=center><a href=http://hedgewars.org/download.html>Download page here</a></font>"
39
31 -- 0.9.13
46631
0
""
""
""
""
[]
False
data AccountInfo =
HasAccount B.ByteString Bool
| Guest
| Admin
deriving (Show, Read)
data DBQuery =
CheckAccount ClientIndex Int B.ByteString B.ByteString
| ClearCache
| SendStats Int Int
deriving (Show, Read)
data CoreMessage =
Accept ClientInfo
| ClientMessage (ClientIndex, [B.ByteString])
| ClientAccountInfo ClientIndex Int AccountInfo
| TimerAction Int
| Remove ClientIndex
type MRnC = MRoomsAndClients RoomInfo ClientInfo
type IRnC = IRoomsAndClients RoomInfo ClientInfo
data Notice =
NickAlreadyInUse
| AdminLeft
deriving Enum
data ShutdownException =
ShutdownException
| RestartException
deriving (Show, Typeable)
instance Exception ShutdownException
data ShutdownThreadException = ShutdownThreadException String
deriving Typeable
instance Show ShutdownThreadException where
show (ShutdownThreadException s) = s
instance Exception ShutdownThreadException
data BanInfo =
BanByIP B.ByteString B.ByteString UTCTime
| BanByNick B.ByteString B.ByteString UTCTime
deriving (Show, Read)
| jeffchao/hedgewars-accessible | gameServer/CoreTypes.hs | gpl-2.0 | 4,924 | 0 | 11 | 1,433 | 1,080 | 637 | 443 | 173 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Types where
import Control.Lens
import Data.Time
import Data.Typeable
--main type in app
data Item = Item {
_typo :: String, --typo represents type of consumption/income
_description :: String,
_price :: Int,
_time :: UTCTime --time and date of creation
} deriving (Typeable,Eq)
data ItemList = ItemList [Item] deriving Typeable
makeLenses ''Item
| deynekalex/Money-Haskell-Project- | src/Types.hs | gpl-2.0 | 483 | 0 | 8 | 152 | 90 | 55 | 35 | 13 | 0 |
module Main ( main )
where
import Prelude hiding ( catch )
import System.IO ( hPrint, stderr )
import System.Exit ( exitWith, ExitCode(ExitFailure) )
import System.Environment ( getProgName )
import Control.Exception ( catch )
import Control.Applicative ( (<$>) )
import Data.Version ( showVersion )
-- this one is autogenerated by cabal
import Paths_hylores ( version )
import HyLoRes.FrontEnd.CommandLine ( getCmdLineParams, showHelp, usage )
import HyLoRes.Main ( runWithParams )
import HyLoRes.Core.Worker.Base ( Result(SAT, UNSAT, INTERRUPTED) )
-- This function, replaces the lambda function that as 2nd arg of catch
-- Need it for ghc >=7
teste :: IOError -> IO a
teste e = do hPrint stderr (show e)
exit r_RUNTIME_ERROR
where r_RUNTIME_ERROR = 13
--main :: IO
main = do r <- runCmdLineVersion
`catch` teste
--
case r of
Nothing -> exit r_DID_NOT_RUN
Just (SAT _) -> exit r_SAT
Just UNSAT -> exit r_UNSAT
Just INTERRUPTED -> exit r_TIMEOUT
--
where r_SAT = 1
r_UNSAT = 2
r_TIMEOUT = 3
r_DID_NOT_RUN = 10
r_RUNTIME_ERROR = 13
exit :: Int -> IO a
exit = exitWith . ExitFailure
runCmdLineVersion :: IO (Maybe Result)
runCmdLineVersion =
do p_clp <- getCmdLineParams
case p_clp of
Left err -> do putStrLn header
putStrLn err
hylores <- getProgName
putStrLn $ "Try `" ++ hylores ++ " --help' " ++
"for more information"
return Nothing
--
Right clp -> if showHelp clp
then do putStrLn header
hylores <- getProgName
putStrLn $ usage (hylores ++ " [OPTIONS]")
putStrLn gpl_tag
return Nothing
--
else Just <$> runWithParams clp
header :: String
header = unlines ["HyLoRes " ++ showVersion version,
"C. Areces, D.Gorin and J. Heguiabehere. (c) 2002-2007."]
gpl_tag :: String
gpl_tag = unlines [
"This program is distributed in the hope that it will be useful,",
"but WITHOUT ANY WARRANTY; without even the implied warranty of",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"GNU General Public License for more details."]
| nevrenato/HyLoRes_Source | src/hylores.hs | gpl-2.0 | 2,591 | 0 | 16 | 967 | 529 | 283 | 246 | 56 | 4 |
-- | WRONG Echo implementation using transactional variables.
module EchoTVarWrong (mkEchoTVarWrong) where
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TVar (TVar, newTVarIO, readTVarIO,
writeTVar)
import Echo (Echo, input, output, reset)
newtype EchoTVar = EchoTVar
{ _buf :: TVar (Maybe String) }
deriving Eq
-- | Create a new EchoTVar.
mkEchoTVarWrong :: IO EchoTVar
mkEchoTVarWrong = EchoTVar <$> newTVarIO Nothing
instance Echo EchoTVar where
-- | Input a string. Returns 'True' iff the buffer was empty and the given
-- string was added to it.
input (EchoTVar mBuf) str = do
res <- readTVarIO mBuf
case res of
Nothing -> atomically $ writeTVar mBuf (Just str) >> return True
Just _ -> return False
-- | Output the buffer contents.
output (EchoTVar mBuf) = do
res <- readTVarIO mBuf
atomically $ writeTVar mBuf Nothing
return res
-- | Reset the environment
reset (EchoTVar mBuf) = atomically $ writeTVar mBuf Nothing
| capitanbatata/sandbox | hedgehog-sm-echo/src/EchoTVarWrong.hs | gpl-3.0 | 1,163 | 0 | 15 | 359 | 255 | 135 | 120 | 21 | 1 |
module Tests.GADTFirstOrder where
import QFeldspar.MyPrelude
import QFeldspar.Expression.GADTFirstOrder
import QFeldspar.Variable.Typed
import QFeldspar.Conversion
import QFeldspar.Expression.Conversions.Evaluation.GADTFirstOrder ()
import qualified QFeldspar.Expression.GADTValue as FGV
import QFeldspar.Environment.Typed
import QFeldspar.Type.GADT hiding (Int)
dbl :: Exp '[Word32 -> Word32 -> Word32] '[] (Word32 -> Word32)
dbl = -- Abs (App (App (Var (Suc Zro)) (Var Zro)) (Var Zro))
Abs (Prm Zro (Ext (Var Zro) (Ext (Var Zro) Emp)))
compose :: (Type ta , Type tb , Type tc) =>
Exp s g ((tb -> tc) -> ((ta -> tb) -> (ta -> tc)))
compose = Abs (Abs (Abs
(App (Var (Suc (Suc Zro)))
(App (Var (Suc Zro)) (Var Zro)))))
four :: Exp '[Word32 -> Word32 -> Word32] '[] Word32
four = App (App (App compose dbl) dbl) (Int 1)
test :: Bool
test = case runNamM (cnv (four
, (Ext (FGV.Exp (+) :: FGV.Exp (Word32 -> Word32 -> Word32)) Emp, Emp :: Env FGV.Exp '[])))
of
Rgt (FGV.Exp x) -> x == 4
Lft _ -> False
| shayan-najd/QFeldspar | Tests/GADTFirstOrder.hs | gpl-3.0 | 1,102 | 0 | 17 | 262 | 461 | 250 | 211 | -1 | -1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Run.Eggs.SequenceEater
(
SequenceEater,
makeSequenceEater,
sequenceEat,
) where
import Data.List
data SequenceEater a =
SequenceEater
{
eaterIdeal :: [a],
eaterCurrent :: [a],
eaterNexts :: [a]
}
makeSequenceEater :: [a] -> SequenceEater a
makeSequenceEater ideal =
SequenceEater
{
eaterIdeal = ideal,
eaterCurrent = [],
eaterNexts = ideal
}
sequenceEat :: Eq a => SequenceEater a -> a -> (SequenceEater a, Bool)
sequenceEat eater a =
let ideal = eaterIdeal eater
current = eaterCurrent eater
nexts = eaterNexts eater
in case nexts of
[] ->
let (current', nexts') = findIdeal ideal $ tail $ current ++ [a]
eater' = eater { eaterCurrent = current',
eaterNexts = ideal }
in (eater', True)
(n:ns) -> if a == n
then case ns of
[] ->
let (current', nexts') = findIdeal ideal $ tail $ current ++ [a]
eater' = eater { eaterCurrent = current',
eaterNexts = ideal }
in (eater', True)
ns ->
let current' = current ++ [a]
eater' = eater { eaterCurrent = current',
eaterNexts = ns }
in (eater', False)
else
let (current', nexts') = findIdeal ideal $ tail $ current ++ [a]
eater' = eater { eaterCurrent = current',
eaterNexts = nexts' }
in (eater', False)
findIdeal :: Eq a => [a] -> [a] -> ([a], [a])
findIdeal ideal seq =
helper ideal $ tails seq
where
helper ideal (s:ss) =
case maybeNexts ideal s of
Just ns -> (s, ns)
Nothing -> helper ideal ss
helper ideal [] =
([], ideal)
maybeNexts :: Eq a => [a] -> [a] -> Maybe [a]
maybeNexts (i:is) (a:as) =
if i == a then maybeNexts is as
else Nothing
maybeNexts is [] =
Just is
maybeNexts [] as =
Nothing
| karamellpelle/grid | source/Game/Run/Eggs/SequenceEater.hs | gpl-3.0 | 3,161 | 0 | 21 | 1,275 | 710 | 397 | 313 | 61 | 4 |
{-# LANGUAGE QuasiQuotes, OverloadedStrings #-}
module PythonSpec (spec) where
import Test.Hspec
import Language.Mulang.Ast
import Language.Mulang.Ast.Operator
import Language.Mulang.Parsers.Python
import Data.Text (Text, unpack)
import NeatInterpolation (text)
import Control.Exception (evaluate)
run :: Text -> Expression
run = py . unpack
spec :: Spec
spec = do
describe "parse" $ do
it "parses numbers" $ do
py "1" `shouldBe` MuNumber 1
it "parses booleans" $ do
py "True" `shouldBe` MuBool True
py "False" `shouldBe` MuBool False
it "parses booleans in version2" $ do
py2 "True" `shouldBe` MuBool True
py2 "False" `shouldBe` MuBool False
it "parses strings" $ do
py "\"some string\"" `shouldBe` MuString "some string"
it "parses strings sequences" $ do
py "\"hello\" \"world\"" `shouldBe` MuString "helloworld"
it "parses multi-line strings" $ do
run [text|"""some
string"""|] `shouldBe` MuString "some\nstring"
it "parses lists" $ do
py "[1,2,3]" `shouldBe` MuList [MuNumber 1, MuNumber 2, MuNumber 3]
it "parses dictionaries" $ do
py "{}" `shouldBe` MuDict None
py "{'foo': 1}" `shouldBe` MuDict (Arrow (MuString "foo") (MuNumber 1))
py "{'foo': 1, 'bar': 2}" `shouldBe` MuDict (Sequence [Arrow (MuString "foo") (MuNumber 1), Arrow (MuString "bar") (MuNumber 2)])
it "parses sets as lists" $ do
py "{1,2,3}" `shouldBe` MuList [MuNumber 1, MuNumber 2, MuNumber 3]
it "parses assignment" $ do
py "one = 1" `shouldBe` Assignment "one" (MuNumber 1.0)
it "allows parentheses" $ do
py "(123)" `shouldBe` MuNumber 123
it "parses references" $ do
py "x" `shouldBe` (Reference "x")
it "parses application" $ do
py "f(2)" `shouldBe` (Application (Reference "f") [MuNumber 2])
it "parses message sending" $ do
py "o.f(2)" `shouldBe` (Send (Reference "o") (Reference "f") [(MuNumber 2)])
it "parses assign-operators" $ do
py "x += 8" `shouldBe` (Assignment "x" (Application (Primitive Plus) [Reference "x",MuNumber 8.0]))
it "parses binary operators" $ do
py "x + y" `shouldBe` (Application (Primitive Plus) [Reference "x",Reference "y"])
it "parses sequences" $ do
py "1;2;3" `shouldBe` Sequence [MuNumber 1, MuNumber 2, MuNumber 3]
it "parses unary operators" $ do
py "not True" `shouldBe` (Application (Primitive Negation) [MuBool True])
it "parses classes" $ do
py "class Something: pass" `shouldBe` Class "Something" Nothing None
it "parses classes with methods" $ do
py "class Something:\n def __init__(self): pass\n def foo(self, x): return x" `shouldBe` (
Class "Something" Nothing (Sequence [
(SimpleMethod "__init__" [VariablePattern "self"] None),
(SimpleMethod "foo" [VariablePattern "self", VariablePattern "x"] (Return (Reference "x")))
]))
it "doesn't parse methods without self" $ do
py "class Something:\n def bar(): return None\n" `shouldBe` (
Class "Something" Nothing (SimpleFunction "bar" [] (Return MuNil)))
it "doesn't parse methods pseudo-methods outside a class" $ do
py "def bar(self): return None\n" `shouldBe` (SimpleFunction "bar" [VariablePattern "self"] (Return MuNil))
it "parses inheritance" $ do
py "class DerivedClassName(BaseClassName): pass" `shouldBe` Class "DerivedClassName" (Just "BaseClassName") None
it "parses if, elif and else" $ do
run [text|if True: 1
elif False: 2
else: 3|] `shouldBe` If (MuBool True) (MuNumber 1) (If (MuBool False) (MuNumber 2) (MuNumber 3))
it "parses functions" $ do
py "def foo(): return 1" `shouldBe` SimpleFunction "foo" [] (Return (MuNumber 1.0))
it "parses procedures" $ do
py "def foo(param): print(param)" `shouldBe` SimpleProcedure "foo" [VariablePattern "param"] (Print (Reference "param"))
it "parses whiles" $ do
py "while True: pass" `shouldBe` While (MuBool True) None
it "parses fors" $ do
py "for x in range(0, 3): pass" `shouldBe` For [Generator (TuplePattern [VariablePattern "x"]) (Application (Reference "range") [MuNumber 0, MuNumber 3])] None
it "parses tries" $ do
run [text|
try:
1
except IOError as e:
2
except ValueError:
3
except:
4|] `shouldBe` Try (MuNumber 1) [
(AsPattern "e" (TypePattern "IOError"), MuNumber 2),
(TypePattern "ValueError", MuNumber 3),
(WildcardPattern, MuNumber 4)] None
it "parses raise expressions" $ do
py "raise" `shouldBe` Raise None
it "parses raise expressions with exception" $ do
py "raise Exception('something')" `shouldBe` Raise (Application (Reference "Exception") [MuString "something"])
it "parses raise expressions with exception in version2 format" $ do
py2 "raise Exception('something')" `shouldBe` Raise (Application (Reference "Exception") [MuString "something"])
py2 "raise Exception, 'something'" `shouldBe` Raise (Application (Reference "Exception") [MuString "something"])
py2 "raise Exception" `shouldBe` Raise (Reference "Exception")
it "parses raise expressions with exception in version3 format" $ do
py3 "raise Exception('something')" `shouldBe` Raise (Application (Reference "Exception") [MuString "something"])
evaluate (py3 "raise Exception, 'something'") `shouldThrow` anyErrorCall
py3 "raise Exception" `shouldBe` Raise (Reference "Exception")
it "parses lambdas" $ do
py "lambda x: 1" `shouldBe` Lambda [VariablePattern "x"] (MuNumber 1)
it "parses tuples" $ do
py "(1, \"something\")" `shouldBe` MuTuple [MuNumber 1, MuString "something"]
it "parses yields" $ do
py "yield 1" `shouldBe` Yield (MuNumber 1)
it "parses field access" $ do
py "x.y" `shouldBe` (FieldReference (Reference "x") "y")
it "parses field assignment" $ do
py "x.y = 2" `shouldBe` (FieldAssignment (Reference "x") "y" (MuNumber 2))
it "parses test groups" $ do
run [text|
class TestGroup(unittest.TestCase):
def test_something():
self.assertTrue(True)
|] `shouldBe` TestGroup (MuString "TestGroup")
(Test (MuString "test_something")
(Assert False $ Truth (MuBool True)))
| mumuki/mulang | spec/PythonSpec.hs | gpl-3.0 | 6,471 | 0 | 24 | 1,563 | 1,987 | 959 | 1,028 | 113 | 1 |
{- This file is part of PhoneDirectory.
Copyright (C) 2009 Michael Steele
PhoneDirectory is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PhoneDirectory is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PhoneDirectory. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE OverloadedStrings #-}
module GUI
( mainWindow
) where
import Control.Applicative
import Control.Monad as M
import Data.Char
import qualified Data.Function as F (on)
import Data.List
import Data.Time
import Control.Monad.IO.Class
import Control.Monad.Trans.Error
import qualified Data.Aeson as A
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Graphics.UI.WX as WX
import Graphics.UI.WXCore hiding (Document)
import System.FilePath
import qualified Text.CSV.ByteString as CSV
import ContactInfo as CI
import Document
import Export
import GUIConstants
import Name as N
import qualified Organization as O
import PageProperties (mkPageProperties, PageProperties)
import PageSetupGUI
import Priority
type WXError a = ErrorT String IO a
-- |The application only exports to .pdf. I could see other formats like
-- .html being useful to.
exportTypesSelection :: [(String, [String])]
exportTypesSelection = [ ("PDF", ["*.pdf"])
, ("Comma-Separated-Value", ["*.csv"])]
-- |The application only exports to .pdf. I could see other formats like
-- .html being useful to.
importTypesSelection :: [(String, [String])]
importTypesSelection = [ ("Comma-Separated-Value", ["*.csv"])]
-- |This is the format to be saved in. It's a Shame that the Haskell YAML
-- library was made available a week after I settled on this.
openSaveTypesSelection :: [(String, [String])]
openSaveTypesSelection = [("Phone Directory (*.pdir)", ["*.pdir"])]
-- |When you first start the application this is the filename chosen to save
-- to.
defaultFile :: String
defaultFile = "untitled.pdir"
-- |Text blurb that goes in the about box.
aboutTxt :: Text
aboutTxt =
"PhoneDirectory 0.7\n\
\Copyright (C) 2009 Michael Steele\n\n\
\This program comes with ABSOLUTELY NO WARRANTY; for\n\
\details go to http://github.com/mikesteele81/Phone-Directory/.\n\n\
\This is free software, and you are welcome to\n\
\redistribute it under certain conditions; read the\n\
\included license file for details."
-- |Build the main window and start the event loop.
mainWindow :: Maybe String -> IO ()
mainWindow filename = do
file <- varCreate defaultFile
modified <- varCreate False
properties <- varCreate mkPageProperties
f <- frame []
pRight <- panel f []
mFile <- menuPane []
iNew <- menuItem mFile []
iOpen <- menuItem mFile []
iSave <- menuItem mFile []
iSaveAs <- menuItem mFile []
menuLine mFile
iPage <- menuItem mFile []
iImport <- menuItem mFile []
iExport <- menuItem mFile []
menuLine mFile
iQuit <- menuQuit mFile []
mHelp <- menuHelp []
iAbout <- menuAbout mHelp []
lFirst <- staticText pRight
[ text := "First Name:"
, tooltip := "Enter the contact's first name. If the contact \
\only goes by a single name, enter it either \
\here or in the last name field."]
eFirst <- entry pRight []
lLast <- staticText pRight
[ text := "Last Name:"
, tooltip := "Enter the contact's last name. If the contact \
\only goes by a single name, enter it either \
\here or in the first name field."]
eLast <- entry pRight []
lPhone <- staticText pRight
[ text := "Phone Number:"
, tooltip := "Enter thecontact's phone number."]
ePhone <- entry pRight []
lPriority <- staticText pRight
[ text := "Priority:"
, tooltip := "Low values will sort before contacts with \
\higher values."]
ePriority <- spinCtrl pRight (fromEnum (minBound :: Priority))
(fromEnum (maxBound :: Priority)) []
tc <- treeCtrl f []
-- Use to determine scaling based on a standard 96dpi view.
Size xDpi yDpi <- bracket (clientDCCreate f) clientDCDelete
dcGetPPI
let
onTreeEvent (TreeSelChanged itm' itm) | treeItemIsOk itm' =
trapError $ do
-- Delete non-root nodes without a name
root <- liftIO $ treeCtrlGetRootItem tc
M.when (root /= itm && treeItemIsOk itm) $ do
ci <- right2CI
M.when (T.null . CI.renderWith lastFirst $ ci)
(liftIO $ treeCtrlDelete tc itm)
if root == itm' then clearDisableDetails
else treeItem2CI tc itm' >>= updateDetails
liftIO propagateEvent
onTreeEvent (TreeKeyDown _ (EventKey k _ _)) = do
-- TreeKeyDown's item member doesn't hold anything.
itm <- treeCtrlGetSelection tc
root <- treeCtrlGetRootItem tc
case k of
KeyInsert -> do
itmP <- treeCtrlGetParent tc itm
-- We only want the heirarchy 2 deep
let p = if root == itmP || root == itm then itm else itmP
itm' <- treeCtrlAppendItem tc p "<New Item>" 0 0 objectNull
treeCtrlSetItemClientData tc itm' (return ())
(ContactInfo (mkPriority 1) (mkName "" "") "")
setModified True
treeCtrlSelectItem tc itm'
windowSetFocus eFirst
KeyDelete -> unless (root == itm) $ do
n <- treeCtrlGetNextSibling tc itm
p <- treeCtrlGetPrevSibling tc itm
u <- treeCtrlGetParent tc itm
treeCtrlDelete tc itm
if treeItemIsOk n
then treeCtrlSelectItem tc n
else if treeItemIsOk p
then treeCtrlSelectItem tc p
else if treeItemIsOk u
then treeCtrlSelectItem tc u
else treeCtrlSelectItem tc root
setModified True
_ -> return ()
propagateEvent
onTreeEvent _ = propagateEvent
setModified m = varSet modified m >> updateTitle
updateTitle = do
fn <- varGet file
m <- varGet modified
set f [WX.text := title m fn]
checkConfirmUnsaved :: WXError () -> WXError ()
checkConfirmUnsaved op = do
m <- liftIO $ varGet modified
if m
then do
confirmed <- liftIO $ confirmDialog f caption msg False
M.when confirmed op
else op
where
caption = "Unsaved Changes"
msg = "You have unsaved changes. Are you sure you want to continue?"
right2CI :: WXError ContactInfo
right2CI = liftIO $ do
firstName <- get eFirst WX.text
lastName <- get eLast WX.text
phone <- get ePhone WX.text
priority <- get ePriority WX.selection
return ContactInfo
{ cName = mkName (T.pack firstName) (T.pack lastName)
, cPhone = T.pack phone
, cPriority = mkPriority priority }
updateDetails :: ContactInfo -> WXError ()
updateDetails ci = liftIO $ do
set eFirst [ enabled := True, WX.text := T.unpack . N.given $ n]
set eLast [ enabled := True, WX.text := maybe "" T.unpack $ N.sur n]
set ePhone [ enabled := True, WX.text := T.unpack (cPhone ci) ]
set ePriority [ enabled := True, WX.selection := fromEnum $ cPriority ci ]
where n = cName ci
clearDisableDetails :: WXError ()
clearDisableDetails = liftIO $ do
set eFirst [ enabled := False, WX.text := "" ]
set eLast [ enabled := False, WX.text := "" ]
set ePhone [ enabled := False, WX.text := "" ]
set ePriority [ enabled := False, WX.text := "" ]
trapError :: WXError a -> IO ()
trapError x = do
e <- runErrorT x
either (errorDialog f "error") (const $ return ()) e
handleFocus :: Bool -> WXError ()
-- lost focus
handleFocus False = do
itm <- liftIO $ treeCtrlGetSelection tc
ci <- treeItem2CI tc itm
ci' <- right2CI
M.when (ci /= ci') $ do
updateNode tc itm ci'
liftIO $ setModified True
handleFocus _ = return ()
commitStringInput :: TextCtrl a -> Bool -> WXError ()
commitStringInput ctrl hasFocus = do
liftIO $ set ctrl [WX.text :~ unpad]
handleFocus hasFocus
commitPriorityInput :: SpinCtrl a -> Bool -> WXError ()
commitPriorityInput ctrl hasFocus = do
liftIO $ set ctrl [ selection :~ fromEnum . mkPriority ]
handleFocus hasFocus
new :: WXError ()
new = do
-- this prevents events from firing.
clearDisableDetails
populateTree tc mkDocument
liftIO $ do
varSet file defaultFile
setModified False
windowSetFocus tc
importFile :: FilePath -> WXError ()
importFile fp = do
doc <- importCSV fp
-- this prevents events from firing.
clearDisableDetails
populateTree tc doc
liftIO $ do
--importing doesn't imply that you can 'save' to the same file.
varSet file defaultFile
--importing implies that the source had incomplete information.
setModified True
varSet properties (pageProperties doc)
open :: FilePath -> WXError ()
open fp = do
doc <- loadDoc fp
-- this prevents events from firing.
clearDisableDetails
populateTree tc doc
liftIO $ do
varSet file fp
setModified False
varSet properties (pageProperties doc)
save :: FilePath -> WXError ()
save fp = do
props <- liftIO $ varGet properties
props2Doc <- tree2Doc tc
let
doc = props2Doc props
doc' = sortDoc lastFirst doc
saveDoc fp doc'
M.when (doc /= doc') $ do
clearDisableDetails
populateTree tc doc'
liftIO $ varSet file fp
liftIO $ setModified False
set mFile [ WX.text := "&File"]
set iNew [ WX.text := "&New"
, on command := trapError $ checkConfirmUnsaved new
]
set iOpen
[ WX.text := "&Open..."
, on command := trapError $ checkConfirmUnsaved $ do
name <- liftIO $ fileOpenDialog f True True "Open phone directory"
openSaveTypesSelection "" ""
maybe (return ()) open name
]
set iSave [ WX.text := "&Save"
, on command := trapError $ liftIO (varGet file) >>= save
]
set iSaveAs
[ WX.text := "Save &As..."
, on command := trapError $ do
name <- liftIO $ fileSaveDialog f True True "Save phone directory"
openSaveTypesSelection "" ""
maybe (return ()) save name
]
set iPage
[ WX.text := "Page Setup..."
, on command := trapError $ do
prop <- liftIO $ varGet properties
prop' <- liftIO $ PageSetupGUI.pageSetupDialog f prop
maybe (return ()) (\p -> unless (prop == p) . liftIO $ do
varSet properties p
setModified True) prop'
return ()
]
set iImport
[ WX.text := "&Import..."
, on command := trapError $ checkConfirmUnsaved $ do
name <- liftIO $ fileOpenDialog f True True "Import phone directory"
importTypesSelection "" ""
maybe (return ()) importFile name
]
set iExport
[ WX.text := "Ex&port..."
, on command := do
name <- fileSaveDialog f True True "Export phone directory"
exportTypesSelection "" ""
case name of
Just name' -> trapError $ do
props <- liftIO $ varGet properties
op <- tree2Doc tc
let ext = drop (length name' - 3) (map toLower name')
if ext == "pdf"
then generate name' (op props)
else M.when (ext == "csv") . liftIO $ S.writeFile name'
(T.encodeUtf8 . printCSV . toCSVRecords $ op props)
Nothing -> return ()
]
-- The 'closing' event handler checks for unsaved changes.
set iQuit [ on command := close f ]
set iAbout [ on command := infoDialog f "About Phone Directory" (T.unpack aboutTxt) ]
set eFirst [ processEnter := True
, on command := trapError $ commitStringInput eFirst False
, on focus := trapError . commitStringInput eFirst
]
set eLast [ processEnter := True
, on command := trapError $ commitStringInput eLast False
, on focus := trapError . commitStringInput eLast
]
set ePhone [ processEnter := True
, on command := trapError $ commitStringInput ePhone False
, on focus := trapError . commitStringInput ePhone
]
set ePriority [ on select := trapError $ commitPriorityInput ePriority False
, on focus := trapError . commitPriorityInput ePriority
]
set tc [ on treeEvent := onTreeEvent ]
set pRight [ layout := column (ctrlPadding yDpi)
. map (column (lblPadding yDpi) . map WX.hfill)
$ [ [widget lFirst, widget eFirst]
, [widget lLast, widget eLast]
, [widget lPhone, widget ePhone]
, [widget lPriority, widget ePriority]
]
]
-- f must have its layout defined last. Otherwise things don't layout
-- properly until the main application window is resized.
set f [ on closing := trapError . checkConfirmUnsaved . liftIO
$ void (windowDestroy f)
, menuBar := [mFile, mHelp]
, picture := T.unpack "data/images/pdirectory.ico"
, layout := margin (winPadding xDpi) $ WX.fill
$ row (ctrlPadding xDpi)
[ WX.fill $ widget tc, WX.fill $ widget pRight ]
, clientSize := sz (scale 640 xDpi) (scale 480 yDpi)
]
--name has already been set. make a new one in case opening a file fails.
trapError new
windowSetFocus tc
case filename of
Nothing -> return ()
Just fn -> trapError $ open fn
-- |Scrap and rebuild the heirarchical tree. Once this is done, expand it and
-- select the first non-root node.
populateTree :: TreeCtrl a -> Document -> WXError ()
populateTree tc doc =
liftIO $ do
treeCtrlDeleteAllItems tc
root <- treeCtrlAddRoot tc "Organizations" 0 0 objectNull
mapM_ (populateOrg root) $ dOrganizations doc
--Select root first. That way if there are no child nodes at least
--something gets selected.
if null (dOrganizations doc)
then treeCtrlSelectItem tc root
else do
treeCtrlExpand tc root
treeCtrlGetNextVisible tc root >>= treeCtrlSelectItem tc
where
addItem p itm = do
tc' <- treeCtrlAppendItem tc p
(T.unpack . CI.renderWith lastFirst $ itm) 0 0 objectNull
treeCtrlSetItemClientData tc tc' (return ()) itm
return tc'
populateOrg p org = do
orgTc <- addItem p $ O.oInfo org
mapM_ (addItem orgTc) $ O.oContacts org
-- |Set the supplied frame's title bar based on the supplied file.
title
:: Bool -- ^Modifications?
-> FilePath -- ^File name
-> String
title m = (if m then ("* " ++) else id) . (++ " - Phone Directory") . takeBaseName
-- |Create a Document object based on the tree heirarchy.
tree2Doc :: TreeCtrl a -> WXError (PageProperties -> Document)
tree2Doc tc = do
root <- liftIO $ treeCtrlGetRootItem tc
orgs <- liftIO $ treeCtrlWithChildren tc root $ \itm ->
runErrorT $ do
orgCI <- treeItem2CI tc itm
contacts <- liftIO $ treeCtrlWithChildren tc itm
$ runErrorT . treeItem2CI tc
either throwError return $ O.Organization orgCI <$> sequence contacts
(year, month, day) <- liftIO $ liftM
(toGregorian . localDay . zonedTimeToLocalTime) getZonedTime
either throwError return $ Document
(show month ++ "/" ++ show day ++ "/" ++ show year)
<$> sequence orgs
-- |Create a ContactInfo by pulling it from the tree heirarchy. This is the
-- only place where 'unsafeTreeCtrlGetItemClientData' should be called.
treeItem2CI :: TreeCtrl a -> TreeItem -> WXError ContactInfo
treeItem2CI tc itm = do
-- If this fails, it will probably raise a segmentation fault.
ci <- liftIO $ unsafeTreeCtrlGetItemClientData tc itm
maybe (throwError "Tree node does not contain contact information") return ci
-- |Save the supplied document to a file.
saveDoc :: FilePath -> Document -> WXError ()
saveDoc fp doc =
(liftIO . L.writeFile fp . A.encode $ doc)
`catchError` (throwError . msg)
where
msg x = "Failed to save directory to " ++ fp ++ ": " ++ x
-- |Attempt to load a document from the supplied file.
loadDoc :: FilePath -> WXError Document
loadDoc fp = ( do
s <- liftIO $ L.readFile fp
maybe (throwError msg) return $ A.decode s
) `catchError` (throwError . (\e -> msg ++ ": " ++ e))
where
msg = "Failed to load " ++ fp
-- |Attempt to load a document from the supplied file.
importCSV :: FilePath -> WXError Document
importCSV fp = ( do
bs <- liftIO . S.readFile $ fp
maybe (throwError "Error Parsing CSV file.") go $ CSV.parseCSV bs
) `catchError` (throwError . msg)
where
go csv = do
orgs <- either (throwError . T.unpack) return (O.fromCSV csv)
return $ mkDocument {dOrganizations = O.mergeOrgs orgs}
msg x = "Failed to load " ++ fp ++ ": " ++ x
unpad :: String -> String
unpad s = case tail . groupBy ((==) `F.on` isSpace) . (" " ++) . (++ " ") $ s of
[] -> []
s' -> join . init $ s'
-- | update left side to match what's entered on right
updateNode :: TreeCtrl a
-> TreeItem
-> ContactInfo
-> WXError ()
updateNode tc itm ci = liftIO $ do
-- Never update the root node.
root <- treeCtrlGetRootItem tc
M.when (root /= itm && treeItemIsOk itm) $ do
treeCtrlSetItemClientData tc itm (return ()) ci
treeCtrlSetItemText tc itm
(T.unpack . CI.renderWith N.lastFirst $ ci)
-- | Given an object of type CSV, generate a CSV formatted
-- string. Always uses escaped fields.
printCSV :: CSV.CSV -> Text
printCSV records = unlines (printRecord `map` records) `T.append` "\n"
where printRecord = T.concat . intersperse "," . map printField
printField f = "\"" `T.append` T.concatMap escape (T.decodeUtf8 f)
`T.append` "\""
escape '"' = "\"\""
escape x = T.singleton x
unlines = T.concat . intersperse "\n"
| mikesteele81/Phone-Directory | src/GUI.hs | gpl-3.0 | 19,744 | 0 | 25 | 6,303 | 5,066 | 2,471 | 2,595 | -1 | -1 |
module Hadolint.Formatter.Codacy
( printResults,
formatResult,
)
where
import qualified Control.Foldl as Foldl
import Data.Aeson hiding (Result)
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Sequence (Seq)
import qualified Data.Text as Text
import Hadolint.Formatter.Format (Result (..), errorPosition)
import Hadolint.Rule (CheckFailure (..), RuleCode (..))
import Text.Megaparsec (TraversableStream)
import Text.Megaparsec.Error
import Text.Megaparsec.Pos (sourceLine, sourceName, unPos)
import Text.Megaparsec.Stream (VisualStream)
data Issue = Issue
{ filename :: Text.Text,
msg :: Text.Text,
patternId :: Text.Text,
line :: Int
}
instance ToJSON Issue where
toJSON Issue {..} =
object ["filename" .= filename, "patternId" .= patternId, "message" .= msg, "line" .= line]
errorToIssue :: (VisualStream s, TraversableStream s, ShowErrorComponent e) => ParseErrorBundle s e -> Issue
errorToIssue err =
Issue
{ filename = Text.pack $ sourceName pos,
patternId = "DL1000",
msg = Text.pack $ errorBundlePretty err,
line = linenumber
}
where
pos = errorPosition err
linenumber = unPos (sourceLine pos)
checkToIssue :: Text.Text -> CheckFailure -> Issue
checkToIssue filename CheckFailure {..} =
Issue
{ filename = filename,
patternId = unRuleCode code,
msg = message,
line = line
}
formatResult :: (VisualStream s, TraversableStream s, ShowErrorComponent e) => Result s e -> Seq Issue
formatResult (Result filename errors checks) = allIssues
where
allIssues = errorMessages <> checkMessages
errorMessages = fmap errorToIssue errors
checkMessages = fmap (checkToIssue filename) checks
printResults ::
(Foldable f, VisualStream s, TraversableStream s, ShowErrorComponent e) =>
f (Result s e) ->
IO ()
printResults results = mapM_ output flattened
where
flattened = Foldl.fold (Foldl.premap formatResult Foldl.mconcat) results
output value = B.putStrLn (encode value)
| lukasmartinelli/hadolint | src/Hadolint/Formatter/Codacy.hs | gpl-3.0 | 2,010 | 0 | 10 | 378 | 612 | 344 | 268 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CognitoIdentity.UnlinkDeveloperIdentity
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Unlinks a 'DeveloperUserIdentifier' from an existing identity. Unlinked
-- developer users will be considered new identities next time they are seen.
-- If, for a given Cognito identity, you remove all federated identities as well
-- as the developer user identifier, the Cognito identity becomes inaccessible.
--
-- <http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_UnlinkDeveloperIdentity.html>
module Network.AWS.CognitoIdentity.UnlinkDeveloperIdentity
(
-- * Request
UnlinkDeveloperIdentity
-- ** Request constructor
, unlinkDeveloperIdentity
-- ** Request lenses
, udiDeveloperProviderName
, udiDeveloperUserIdentifier
, udiIdentityId
, udiIdentityPoolId
-- * Response
, UnlinkDeveloperIdentityResponse
-- ** Response constructor
, unlinkDeveloperIdentityResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.CognitoIdentity.Types
import qualified GHC.Exts
data UnlinkDeveloperIdentity = UnlinkDeveloperIdentity
{ _udiDeveloperProviderName :: Text
, _udiDeveloperUserIdentifier :: Text
, _udiIdentityId :: Text
, _udiIdentityPoolId :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'UnlinkDeveloperIdentity' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'udiDeveloperProviderName' @::@ 'Text'
--
-- * 'udiDeveloperUserIdentifier' @::@ 'Text'
--
-- * 'udiIdentityId' @::@ 'Text'
--
-- * 'udiIdentityPoolId' @::@ 'Text'
--
unlinkDeveloperIdentity :: Text -- ^ 'udiIdentityId'
-> Text -- ^ 'udiIdentityPoolId'
-> Text -- ^ 'udiDeveloperProviderName'
-> Text -- ^ 'udiDeveloperUserIdentifier'
-> UnlinkDeveloperIdentity
unlinkDeveloperIdentity p1 p2 p3 p4 = UnlinkDeveloperIdentity
{ _udiIdentityId = p1
, _udiIdentityPoolId = p2
, _udiDeveloperProviderName = p3
, _udiDeveloperUserIdentifier = p4
}
-- | The "domain" by which Cognito will refer to your users.
udiDeveloperProviderName :: Lens' UnlinkDeveloperIdentity Text
udiDeveloperProviderName =
lens _udiDeveloperProviderName
(\s a -> s { _udiDeveloperProviderName = a })
-- | A unique ID used by your backend authentication process to identify a user.
udiDeveloperUserIdentifier :: Lens' UnlinkDeveloperIdentity Text
udiDeveloperUserIdentifier =
lens _udiDeveloperUserIdentifier
(\s a -> s { _udiDeveloperUserIdentifier = a })
-- | A unique identifier in the format REGION:GUID.
udiIdentityId :: Lens' UnlinkDeveloperIdentity Text
udiIdentityId = lens _udiIdentityId (\s a -> s { _udiIdentityId = a })
-- | An identity pool ID in the format REGION:GUID.
udiIdentityPoolId :: Lens' UnlinkDeveloperIdentity Text
udiIdentityPoolId =
lens _udiIdentityPoolId (\s a -> s { _udiIdentityPoolId = a })
data UnlinkDeveloperIdentityResponse = UnlinkDeveloperIdentityResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'UnlinkDeveloperIdentityResponse' constructor.
unlinkDeveloperIdentityResponse :: UnlinkDeveloperIdentityResponse
unlinkDeveloperIdentityResponse = UnlinkDeveloperIdentityResponse
instance ToPath UnlinkDeveloperIdentity where
toPath = const "/"
instance ToQuery UnlinkDeveloperIdentity where
toQuery = const mempty
instance ToHeaders UnlinkDeveloperIdentity
instance ToJSON UnlinkDeveloperIdentity where
toJSON UnlinkDeveloperIdentity{..} = object
[ "IdentityId" .= _udiIdentityId
, "IdentityPoolId" .= _udiIdentityPoolId
, "DeveloperProviderName" .= _udiDeveloperProviderName
, "DeveloperUserIdentifier" .= _udiDeveloperUserIdentifier
]
instance AWSRequest UnlinkDeveloperIdentity where
type Sv UnlinkDeveloperIdentity = CognitoIdentity
type Rs UnlinkDeveloperIdentity = UnlinkDeveloperIdentityResponse
request = post "UnlinkDeveloperIdentity"
response = nullResponse UnlinkDeveloperIdentityResponse
| dysinger/amazonka | amazonka-cognito-identity/gen/Network/AWS/CognitoIdentity/UnlinkDeveloperIdentity.hs | mpl-2.0 | 5,104 | 0 | 9 | 1,086 | 552 | 335 | 217 | 73 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EC2.ImportVolume
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Creates an import volume task using metadata from the specified disk image.
-- After importing the image, you then upload it using the 'ec2-import-volume'
-- command in the Amazon EC2 command-line interface (CLI) tools. For more
-- information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UploadingYourInstancesandVolumes.html Using the Command Line Tools to Import Your Virtual Machineto Amazon EC2> in the /Amazon Elastic Compute Cloud User Guide for Linux/.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ImportVolume.html>
module Network.AWS.EC2.ImportVolume
(
-- * Request
ImportVolume
-- ** Request constructor
, importVolume
-- ** Request lenses
, ivAvailabilityZone
, ivDescription
, ivDryRun
, ivImage
, ivVolume
-- * Response
, ImportVolumeResponse
-- ** Response constructor
, importVolumeResponse
-- ** Response lenses
, ivrConversionTask
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data ImportVolume = ImportVolume
{ _ivAvailabilityZone :: Text
, _ivDescription :: Maybe Text
, _ivDryRun :: Maybe Bool
, _ivImage :: DiskImageDetail
, _ivVolume :: VolumeDetail
} deriving (Eq, Read, Show)
-- | 'ImportVolume' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ivAvailabilityZone' @::@ 'Text'
--
-- * 'ivDescription' @::@ 'Maybe' 'Text'
--
-- * 'ivDryRun' @::@ 'Maybe' 'Bool'
--
-- * 'ivImage' @::@ 'DiskImageDetail'
--
-- * 'ivVolume' @::@ 'VolumeDetail'
--
importVolume :: Text -- ^ 'ivAvailabilityZone'
-> DiskImageDetail -- ^ 'ivImage'
-> VolumeDetail -- ^ 'ivVolume'
-> ImportVolume
importVolume p1 p2 p3 = ImportVolume
{ _ivAvailabilityZone = p1
, _ivImage = p2
, _ivVolume = p3
, _ivDryRun = Nothing
, _ivDescription = Nothing
}
-- | The Availability Zone for the resulting Amazon EBS volume.
ivAvailabilityZone :: Lens' ImportVolume Text
ivAvailabilityZone =
lens _ivAvailabilityZone (\s a -> s { _ivAvailabilityZone = a })
-- | An optional description for the volume being imported.
ivDescription :: Lens' ImportVolume (Maybe Text)
ivDescription = lens _ivDescription (\s a -> s { _ivDescription = a })
ivDryRun :: Lens' ImportVolume (Maybe Bool)
ivDryRun = lens _ivDryRun (\s a -> s { _ivDryRun = a })
ivImage :: Lens' ImportVolume DiskImageDetail
ivImage = lens _ivImage (\s a -> s { _ivImage = a })
ivVolume :: Lens' ImportVolume VolumeDetail
ivVolume = lens _ivVolume (\s a -> s { _ivVolume = a })
newtype ImportVolumeResponse = ImportVolumeResponse
{ _ivrConversionTask :: Maybe ConversionTask
} deriving (Eq, Read, Show)
-- | 'ImportVolumeResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ivrConversionTask' @::@ 'Maybe' 'ConversionTask'
--
importVolumeResponse :: ImportVolumeResponse
importVolumeResponse = ImportVolumeResponse
{ _ivrConversionTask = Nothing
}
ivrConversionTask :: Lens' ImportVolumeResponse (Maybe ConversionTask)
ivrConversionTask =
lens _ivrConversionTask (\s a -> s { _ivrConversionTask = a })
instance ToPath ImportVolume where
toPath = const "/"
instance ToQuery ImportVolume where
toQuery ImportVolume{..} = mconcat
[ "AvailabilityZone" =? _ivAvailabilityZone
, "Description" =? _ivDescription
, "DryRun" =? _ivDryRun
, "Image" =? _ivImage
, "Volume" =? _ivVolume
]
instance ToHeaders ImportVolume
instance AWSRequest ImportVolume where
type Sv ImportVolume = EC2
type Rs ImportVolume = ImportVolumeResponse
request = post "ImportVolume"
response = xmlResponse
instance FromXML ImportVolumeResponse where
parseXML x = ImportVolumeResponse
<$> x .@? "conversionTask"
| kim/amazonka | amazonka-ec2/gen/Network/AWS/EC2/ImportVolume.hs | mpl-2.0 | 5,049 | 0 | 9 | 1,177 | 686 | 414 | 272 | 81 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Logging.Projects.Sinks.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets a sink.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.projects.sinks.get@.
module Network.Google.Resource.Logging.Projects.Sinks.Get
(
-- * REST Resource
ProjectsSinksGetResource
-- * Creating a Request
, projectsSinksGet
, ProjectsSinksGet
-- * Request Lenses
, psgXgafv
, psgUploadProtocol
, psgAccessToken
, psgUploadType
, psgSinkName
, psgCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.projects.sinks.get@ method which the
-- 'ProjectsSinksGet' request conforms to.
type ProjectsSinksGetResource =
"v2" :>
Capture "sinkName" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] LogSink
-- | Gets a sink.
--
-- /See:/ 'projectsSinksGet' smart constructor.
data ProjectsSinksGet =
ProjectsSinksGet'
{ _psgXgafv :: !(Maybe Xgafv)
, _psgUploadProtocol :: !(Maybe Text)
, _psgAccessToken :: !(Maybe Text)
, _psgUploadType :: !(Maybe Text)
, _psgSinkName :: !Text
, _psgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsSinksGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'psgXgafv'
--
-- * 'psgUploadProtocol'
--
-- * 'psgAccessToken'
--
-- * 'psgUploadType'
--
-- * 'psgSinkName'
--
-- * 'psgCallback'
projectsSinksGet
:: Text -- ^ 'psgSinkName'
-> ProjectsSinksGet
projectsSinksGet pPsgSinkName_ =
ProjectsSinksGet'
{ _psgXgafv = Nothing
, _psgUploadProtocol = Nothing
, _psgAccessToken = Nothing
, _psgUploadType = Nothing
, _psgSinkName = pPsgSinkName_
, _psgCallback = Nothing
}
-- | V1 error format.
psgXgafv :: Lens' ProjectsSinksGet (Maybe Xgafv)
psgXgafv = lens _psgXgafv (\ s a -> s{_psgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
psgUploadProtocol :: Lens' ProjectsSinksGet (Maybe Text)
psgUploadProtocol
= lens _psgUploadProtocol
(\ s a -> s{_psgUploadProtocol = a})
-- | OAuth access token.
psgAccessToken :: Lens' ProjectsSinksGet (Maybe Text)
psgAccessToken
= lens _psgAccessToken
(\ s a -> s{_psgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
psgUploadType :: Lens' ProjectsSinksGet (Maybe Text)
psgUploadType
= lens _psgUploadType
(\ s a -> s{_psgUploadType = a})
-- | Required. The resource name of the sink:
-- \"projects\/[PROJECT_ID]\/sinks\/[SINK_ID]\"
-- \"organizations\/[ORGANIZATION_ID]\/sinks\/[SINK_ID]\"
-- \"billingAccounts\/[BILLING_ACCOUNT_ID]\/sinks\/[SINK_ID]\"
-- \"folders\/[FOLDER_ID]\/sinks\/[SINK_ID]\" Example:
-- \"projects\/my-project-id\/sinks\/my-sink-id\".
psgSinkName :: Lens' ProjectsSinksGet Text
psgSinkName
= lens _psgSinkName (\ s a -> s{_psgSinkName = a})
-- | JSONP
psgCallback :: Lens' ProjectsSinksGet (Maybe Text)
psgCallback
= lens _psgCallback (\ s a -> s{_psgCallback = a})
instance GoogleRequest ProjectsSinksGet where
type Rs ProjectsSinksGet = LogSink
type Scopes ProjectsSinksGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/logging.admin",
"https://www.googleapis.com/auth/logging.read"]
requestClient ProjectsSinksGet'{..}
= go _psgSinkName _psgXgafv _psgUploadProtocol
_psgAccessToken
_psgUploadType
_psgCallback
(Just AltJSON)
loggingService
where go
= buildClient
(Proxy :: Proxy ProjectsSinksGetResource)
mempty
| brendanhay/gogol | gogol-logging/gen/Network/Google/Resource/Logging/Projects/Sinks/Get.hs | mpl-2.0 | 4,861 | 0 | 15 | 1,080 | 709 | 417 | 292 | 104 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.DirectConnect.DescribeConnections
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Displays all connections in this region.
--
-- If a connection ID is provided, the call returns only that particular
-- connection.
--
-- <http://docs.aws.amazon.com/directconnect/latest/APIReference/API_DescribeConnections.html>
module Network.AWS.DirectConnect.DescribeConnections
(
-- * Request
DescribeConnections
-- ** Request constructor
, describeConnections
-- ** Request lenses
, dc1ConnectionId
-- * Response
, DescribeConnectionsResponse
-- ** Response constructor
, describeConnectionsResponse
-- ** Response lenses
, dcrConnections
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.DirectConnect.Types
import qualified GHC.Exts
newtype DescribeConnections = DescribeConnections
{ _dc1ConnectionId :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'DescribeConnections' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dc1ConnectionId' @::@ 'Maybe' 'Text'
--
describeConnections :: DescribeConnections
describeConnections = DescribeConnections
{ _dc1ConnectionId = Nothing
}
dc1ConnectionId :: Lens' DescribeConnections (Maybe Text)
dc1ConnectionId = lens _dc1ConnectionId (\s a -> s { _dc1ConnectionId = a })
newtype DescribeConnectionsResponse = DescribeConnectionsResponse
{ _dcrConnections :: List "connections" Connection
} deriving (Eq, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList DescribeConnectionsResponse where
type Item DescribeConnectionsResponse = Connection
fromList = DescribeConnectionsResponse . GHC.Exts.fromList
toList = GHC.Exts.toList . _dcrConnections
-- | 'DescribeConnectionsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dcrConnections' @::@ ['Connection']
--
describeConnectionsResponse :: DescribeConnectionsResponse
describeConnectionsResponse = DescribeConnectionsResponse
{ _dcrConnections = mempty
}
-- | A list of connections.
dcrConnections :: Lens' DescribeConnectionsResponse [Connection]
dcrConnections = lens _dcrConnections (\s a -> s { _dcrConnections = a }) . _List
instance ToPath DescribeConnections where
toPath = const "/"
instance ToQuery DescribeConnections where
toQuery = const mempty
instance ToHeaders DescribeConnections
instance ToJSON DescribeConnections where
toJSON DescribeConnections{..} = object
[ "connectionId" .= _dc1ConnectionId
]
instance AWSRequest DescribeConnections where
type Sv DescribeConnections = DirectConnect
type Rs DescribeConnections = DescribeConnectionsResponse
request = post "DescribeConnections"
response = jsonResponse
instance FromJSON DescribeConnectionsResponse where
parseJSON = withObject "DescribeConnectionsResponse" $ \o -> DescribeConnectionsResponse
<$> o .:? "connections" .!= mempty
| dysinger/amazonka | amazonka-directconnect/gen/Network/AWS/DirectConnect/DescribeConnections.hs | mpl-2.0 | 3,959 | 0 | 10 | 769 | 496 | 299 | 197 | 58 | 1 |
{-
Copyright (C) 2010, 2011, 2012 Jeroen Ketema and Jakob Grue Simonsen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
-- This module defines some reductions that can be tried with the confluence
-- algorithm.
module ConfluenceExamples (
cRed1a, cRed1b, cRed1c,
cRed2a, cRed2b,
cRed3a, cRed3b,
cRed4a, cRed4b,
confluence
) where
import RuleAndSystem
import Reduction
import Omega
import Confluence
import ExampleTermsAndSubstitutions
import ExampleRulesAndSystems
import Prelude
-- The next three reductions start in f^omega. Interesting combinations to try
-- are:
--
-- fst $ confluence system_a_f_x (cRed1a, cRed1b)
-- snd $ confluence system_a_f_x (cRed1a, cRed1b)
-- finalTerm $ fst $ confluence system_a_f_x (cRed1b, cRed1c)
-- finalTerm $ snd $ confluence system_a_f_x (cRed1b, cRed1c)
--
-- f^omega -> g(f^omega) -> g^2(f^omega) -> .. -> g^n(f^omega) -> ...
--
red1a :: OmegaReduction Sigma Var System_a_f_x
red1a = RCons (constructSequence terms) (constructSequence steps)
where terms = rewriteSteps f_omega steps
steps = zip ps rs
ps = iterate (\p -> 1 : p) []
rs = repeat rule_f_x_to_g_x
cRed1a :: CReduction Sigma Var System_a_f_x
cRed1a = CRCons red1a (constructModulus phi)
where phi n = n + 1
--
-- f^omega -> g(f^\omega) -> (gf)(g(f^\omega)) -> ... -> (gf)^n(f^\omega) -> ...
--
red1b :: OmegaReduction Sigma Var System_a_f_x
red1b = RCons (constructSequence terms) (constructSequence steps)
where terms = rewriteSteps f_omega steps
steps = zip ps rs
ps = iterate (\p -> 1 : 1 : p) []
rs = repeat rule_f_x_to_g_x
cRed1b :: CReduction Sigma Var System_a_f_x
cRed1b = CRCons red1b (constructModulus phi)
where phi m = m + 1
--
-- f^omega -> (fg)(f^\omega) -> (fg)^2(f^\omega))) -> ...
-- -> (fg)^n(f^\omega) -> ...
--
red1c :: OmegaReduction Sigma Var System_a_f_x
red1c = RCons (constructSequence terms) (constructSequence steps)
where terms = rewriteSteps f_omega steps
steps = zip ps rs
ps = iterate (\p -> 1 : 1 : p) [1]
rs = repeat rule_f_x_to_g_x
cRed1c :: CReduction Sigma Var System_a_f_x
cRed1c = CRCons red1c (constructModulus phi)
where phi m = m
-- The next two finite reductions start in f(a). These reductions demonstrate
-- that the confluence algorithm also applies in the finite case. The two
-- obvious combinations are:
--
-- fst $ confluence system_a_b_f_x (cRed2a, cRed2b)
-- snd $ confluence system_a_b_f_x (cRed2a, cRed2b)
--
-- f(a) -> h(a, f(a)) -> h(a, h(a, f(a))) -> h(a, h(a, h(a, f(a))))
--
red2a :: OmegaReduction Sigma Var System_a_b_f_x
red2a = RCons (constructSequence terms) (constructSequence steps)
where terms = rewriteSteps f_a steps
steps = zip ps rs
ps = [[], [2], [2,2]]
rs = [rule_f_x_to_h_x_f_x, rule_f_x_to_h_x_f_x, rule_f_x_to_h_x_f_x]
cRed2a :: CReduction Sigma Var System_a_b_f_x
cRed2a = CRCons red2a (constructModulus phi)
where phi m = min 3 (m + 1)
--
-- f(a) -> f(b) -> f(c)
--
red2b :: OmegaReduction Sigma Var System_a_b_f_x
red2b = RCons (constructSequence terms) (constructSequence steps)
where terms = rewriteSteps f_a steps
steps = zip ps rs
ps = [[1], [1]]
rs = [rule_a_to_b, rule_b_to_c]
cRed2b :: CReduction Sigma Var System_a_b_f_x
cRed2b = CRCons red2b (constructModulus phi)
where phi m = if m == 0 then 0 else 2
-- The next two reductions test for an edge case where the top-most function
-- symbol is not touched in either reduction. The two
-- obvious combinations are:
--
-- fst $ confluence system_a_b_f_x (cRed3a, cRed3b)
-- snd $ confluence system_a_b_f_x (cRed3a, cRed3b)
--
-- f(f(a)) -> f(f(b))
--
red3a :: OmegaReduction Sigma Var System_a_b_f_x
red3a = RCons (constructSequence terms) (constructSequence steps)
where terms = rewriteSteps f_f_a steps
steps = zip ps rs
ps = [[1, 1]]
rs = [rule_a_to_b]
cRed3a :: CReduction Sigma Var System_a_b_f_x
cRed3a = CRCons red3a (constructModulus phi)
where phi m = if m `elem` [0, 1] then 0 else 1
--
-- f(f(a)) -> f(g(a))
--
red3b :: OmegaReduction Sigma Var System_a_b_f_x
red3b = RCons (constructSequence terms) (constructSequence steps)
where terms = rewriteSteps f_f_a steps
steps = zip ps rs
ps = [[1]]
rs = [rule_f_x_to_g_x]
cRed3b :: CReduction Sigma Var System_a_b_f_x
cRed3b = CRCons red3b (constructModulus phi)
where phi n = if n == 0 then 0 else 1
-- The next two reductions start in a. These reductions demonstrate that the
-- confluence algorithm can deal with rules that have infinite right-hand
-- sides. The obvious (although not very informative) combinations are:
--
-- finalTerm $ fst $ confluence system_a_f_x_omega (cRed4a, cRed4b)
-- finalTerm $ snd $ confluence system_a_f_x_omega (cRed4a, cRed4b)
--
-- a -> f(a) -> f^2(a) -> ... -> f^n(a) -> ...
--
red4a :: OmegaReduction Sigma Var System_a_f_x_omega
red4a = RCons (constructSequence terms) (constructSequence steps)
where terms = rewriteSteps a steps
steps = zip ps rs
ps = iterate (\p -> 1 : p) []
rs = repeat rule_a_to_f_a
cRed4a :: CReduction Sigma Var System_a_f_x_omega
cRed4a = CRCons red4a (constructModulus phi)
where phi m = m + 1
--
-- a -> f(a) -> s = h(a, s)
--
red4b :: OmegaReduction Sigma Var System_a_f_x_omega
red4b = RCons (constructSequence terms) (constructSequence steps)
where terms = rewriteSteps a steps
steps = zip ps rs
ps = [[], []]
rs = [rule_a_to_f_a, rule_f_x_to_h_x_omega]
cRed4b :: CReduction Sigma Var System_a_f_x_omega
cRed4b = CRCons red4b (constructModulus phi)
where phi _ = 2
| jeroenk/iTRSsImplemented | ConfluenceExamples.hs | agpl-3.0 | 6,389 | 0 | 11 | 1,425 | 1,298 | 714 | 584 | 94 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Bantam.Service.Webship (
module X
, ResourceDenied (..)
, Resource
, inconceivable
, serverError
, lookupAccept
, lookupContentType
, redirect
, forbidden
, forbiddenB
, notFound
, halt
, resourceToWaiT
) where
import Bantam.Service.Path
import Bantam.Service.View
import Control.Monad.Trans.Class (lift)
import Data.ByteString (ByteString)
import Data.List (lookup)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
import Network.Wai (Application, Request (..), Response, responseLBS)
import Network.Wai as X (requestMethod)
import Network.HTTP.Media
import qualified Network.HTTP.Types as HTTP
import P
import qualified Prelude as Unsafe (error)
import System.IO (IO)
import Webship.Path (Path)
import Webship.Wai (ResponseBody (..), toWaiResponse)
import X.Control.Monad.Trans.Either (EitherT, hoistEither, runEitherT)
data ResourceDenied =
UnsupportedAcceptType ByteString
| UnsupportedContentType ByteString
| Forbidden
| NotFound
type Resource m = Request -> EitherT ResourceDenied m Response
inconceivable :: a
inconceivable =
Unsafe.error "The impossible happened"
lookupAccept :: Request -> NonEmpty (MediaType, a) -> Either ResourceDenied a
lookupAccept req known =
case lookup HTTP.hAccept $ requestHeaders req of
Nothing ->
Right . snd $ NE.head known
Just t ->
maybeToRight (UnsupportedAcceptType t) . mapAcceptMedia (NE.toList known) $ t
lookupContentType :: Request -> NonEmpty (MediaType, a) -> Either ResourceDenied a
lookupContentType req known =
case lookup HTTP.hContentType $ requestHeaders req of
Nothing ->
Right . snd $ NE.head known
Just t ->
maybeToRight (UnsupportedContentType t) . mapContentMedia (NE.toList known) $ t
forbiddenB :: Monad m => m Bool -> EitherT ResourceDenied m ()
forbiddenB =
forbidden . bind (return . bool Nothing (Just ()))
forbidden :: Monad m => m (Maybe a) -> EitherT ResourceDenied m a
forbidden =
bind (hoistEither . maybeToRight Forbidden) . lift
notFound :: Monad m => m (Maybe a) -> EitherT ResourceDenied m a
notFound =
bind (hoistEither . maybeToRight NotFound) . lift
redirect :: Path a -> a -> Response
redirect p a =
responseLBS HTTP.status302 [(HTTP.hLocation, encodedPath p a)] ""
halt :: HTTP.Status -> ResponseBody -> Response
halt s b =
toWaiResponse s [] b
resourceToWaiT :: Functor m => (Request -> m Response -> IO Response) -> Resource m -> Application
resourceToWaiT run fs req respond = do
bind respond . run req $ do
flip fmap (runEitherT $ fs req) $ \x -> case x of
Left e -> case e of
UnsupportedAcceptType _ ->
halt HTTP.status406 $ serverError "Not acceptable"
UnsupportedContentType _ ->
halt HTTP.status415 $ serverError "Unsupport content-type"
Forbidden ->
halt HTTP.status403 $ serverError "Permission denied"
NotFound ->
halt HTTP.status404 $ serverError "Page not found"
Right r ->
r
| charleso/bantam | bantam-service/src/Bantam/Service/Webship.hs | unlicense | 3,238 | 0 | 20 | 764 | 969 | 513 | 456 | 86 | 5 |
{-# LANGUAGE PackageImports #-}
import "tomato" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, settingsPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
main :: IO ()
main = do
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings defaultSettings
{ settingsPort = port
} app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "dist/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
| twopoint718/tomato | devel.hs | bsd-2-clause | 700 | 0 | 10 | 123 | 187 | 101 | 86 | 23 | 2 |
{-# LANGUAGE Arrows #-}
module OSM.XML (parseXMLFile)
where
import Data.Int (Int64)
import Text.XML.HXT.Core
import qualified OSM
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
tagElementToKeyValue :: ArrowXml t => t XmlTree (OSM.TagKey, T.Text)
tagElementToKeyValue = proc el -> do
key <- getAttrValue "k" -< el
value <- getAttrValue "v" -< el
returnA -< (OSM.TagKey (T.pack key), T.pack value)
topLevelTag :: ArrowXml t => String -> t XmlTree XmlTree
topLevelTag tag = getChildren >>> hasName "osm" /> hasName tag
getOSMTags :: ArrowXml t => t XmlTree OSM.Tags
getOSMTags = listA (getChildren >>> hasName "tag" >>> tagElementToKeyValue)
>>> arr Map.fromList
getOSMID :: ArrowXml a => a XmlTree Int64
getOSMID = getAttrValue "id" >>> arr read
getOSMNode :: ArrowXml t => t XmlTree (OSM.Node ())
getOSMNode = topLevelTag "node" >>>
proc x -> do
nodeId <- getOSMID -< x
tags <- getOSMTags -< x
latS <- getAttrValue "lat" -< x
lonS <- getAttrValue "lon" -< x
let lat = read latS
let lon = read lonS
returnA -< OSM.node (OSM.NodeID nodeId) tags
(OSM.Coordinates { OSM.latitude = lat, OSM.longitude = lon })
getOSMWayNodes :: ArrowXml t => t XmlTree [OSM.NodeID]
getOSMWayNodes = listA $ getChildren >>> hasName "nd" >>> getAttrValue "ref" >>> arr read >>> arr OSM.NodeID
getOSMWay :: ArrowXml t => t XmlTree (OSM.Way ())
getOSMWay = topLevelTag "way" >>>
proc x -> do
wayId <- getOSMID -< x
tags <- getOSMTags -< x
nodes <- getOSMWayNodes -< x
returnA -< OSM.way (OSM.WayID wayId) tags nodes
elementIdByType :: String -> Int64 -> OSM.ElementID
elementIdByType "node" i = OSM.ElementNodeID (OSM.NodeID i)
elementIdByType "way" i = OSM.ElementWayID (OSM.WayID i)
elementIdByType "relation" i = OSM.ElementRelationID (OSM.RelationID i)
elementIdByType t _ = error $ "Invalid type " ++ t
getOSMRelationMembers :: ArrowXml t => t XmlTree [OSM.RelationMember]
getOSMRelationMembers = listA $ getChildren >>> hasName "member" >>>
proc x -> do
elIdS <- getAttrValue "ref" -< x
typeS <- getAttrValue "type" -< x
role <- getAttrValue "role" -< x
let elId = read elIdS
let elementId = elementIdByType typeS elId
returnA -< OSM.RelationMember elementId (OSM.RelationRole (T.pack role))
getOSMRelation :: ArrowXml t => t XmlTree (OSM.Relation ())
getOSMRelation = topLevelTag "relation" >>>
proc x -> do
relationId <- getOSMID -< x
tags <- getOSMTags -< x
members <- getOSMRelationMembers -< x
returnA -< OSM.relation (OSM.RelationID relationId) tags members
listToMap :: (Ord i) => [OSM.Element i p v] -> Map.Map i (OSM.Element i p v)
listToMap list = Map.fromList $ map (\o -> (OSM.id o, o)) list
getOSMEverything :: ArrowXml t => t XmlTree (OSM.Dataset ())
getOSMEverything = proc x -> do
nodes <- listA getOSMNode -< x
ways <- listA getOSMWay -< x
relations <- listA getOSMRelation -< x
let nodesMap = listToMap nodes
let waysMap = listToMap ways
let relationsMap = listToMap relations
returnA -< OSM.Dataset nodesMap waysMap relationsMap
parseXMLFile :: String -> IO (OSM.Dataset ())
parseXMLFile filename = do
results <- runX (readDocument [] filename >>> getOSMEverything)
return (case results of [result] -> result
_ -> error "No result")
| kolen/ptwatch | src/OSM/XML.hs | bsd-2-clause | 3,325 | 6 | 15 | 663 | 1,261 | 607 | 654 | 76 | 2 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE FlexibleContexts #-}
module Main where
import qualified QuickCheck
import Opaleye (Column, Nullable, Query, QueryArr, (.==), (.>))
import qualified Opaleye as O
import qualified Database.PostgreSQL.Simple as PGS
import qualified Data.Profunctor.Product.Default as D
import qualified Data.Profunctor.Product as PP
import qualified Data.Profunctor as P
import qualified Data.Ord as Ord
import qualified Data.List as L
import Data.Monoid ((<>))
import qualified Data.String as String
import qualified System.Exit as Exit
import qualified System.Environment as Environment
import qualified Control.Applicative as A
import qualified Control.Arrow as Arr
import Control.Arrow ((&&&), (***), (<<<), (>>>))
import GHC.Int (Int64)
-- { Set your test database info here. Then invoke the 'main'
-- function to run the tests, or just use 'cabal test'. The test
-- database must already exist and the test user must have
-- permissions to modify it.
connectInfo :: PGS.ConnectInfo
connectInfo = PGS.ConnectInfo { PGS.connectHost = "localhost"
, PGS.connectPort = 25433
, PGS.connectUser = "tom"
, PGS.connectPassword = "tom"
, PGS.connectDatabase = "opaleye_test" }
connectInfoTravis :: PGS.ConnectInfo
connectInfoTravis = PGS.ConnectInfo { PGS.connectHost = "localhost"
, PGS.connectPort = 5432
, PGS.connectUser = "postgres"
, PGS.connectPassword = ""
, PGS.connectDatabase = "opaleye_test" }
-- }
{-
Status
======
The tests here are very superficial and pretty much the bare mininmum
that needs to be tested.
Future
======
The overall approach to testing should probably go as follows.
1. Test all individual units of functionality by running them on a
table and checking that they produce the expected result. This type
of testing is amenable to the QuickCheck approach if we reimplement
the individual units of functionality in Haskell.
2. Test that "the denotation is an arrow morphism" is correct. I
think in combination with 1. this is all that will be required to
demonstrate that the library is correct.
"The denotation is an arrow morphism" means that for each arrow
operation, the denotation preserves the operation. If we have
f :: QueryArr wiresa wiresb
then [f] should be something like
[f] :: a -> IO [b]
f as = runQuery (toValues as >>> f)
For example, take the operation >>>. We need to check that
[f >>> g] = [f] >>> [g]
for all f and g, where [] means the denotation. We would also want
to check that
[id] = id
and
[first f] = first [f]
I think checking these operations is sufficient because all the
other QueryArr operations are implemented in terms of them.
(Here I'm taking a slight liberty as `a -> IO [b]` is not directly
an arrow, but it could be made one straightforwardly. (For the laws
to be satisfied, perhaps we have to assume that the IO actions
commute.))
I don't think this type of testing is amenable to QuickCheck. It
seems we have to check the properties for arbitrary arrows indexed by
arbitrary types. I don't think QuickCheck supports this sort of
randomised testing.
Note
----
This seems to be equivalent to just reimplementing Opaleye in
Haskell-side terms and comparing the results of queries run in both
ways.
-}
twoIntTable :: String
-> O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4)
twoIntTable n = O.Table n (PP.p2 (O.required "column1", O.required "column2"))
table1 :: O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4)
table1 = twoIntTable "table1"
table1F :: O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4)
table1F = fmap (\(col1, col2) -> (col1 + col2, col1 - col2)) table1
-- This is implicitly testing our ability to handle upper case letters in table names.
table2 :: O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4)
table2 = twoIntTable "TABLE2"
table3 :: O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4)
table3 = twoIntTable "table3"
table4 :: O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4)
table4 = twoIntTable "table4"
table5 :: O.Table (Maybe (Column O.PGInt4), Maybe (Column O.PGInt4))
(Column O.PGInt4, Column O.PGInt4)
table5 = O.TableWithSchema "public" "table5" (PP.p2 (O.optional "column1", O.optional "column2"))
table6 :: O.Table (Column O.PGText, Column O.PGText) (Column O.PGText, Column O.PGText)
table6 = O.Table "table6" (PP.p2 (O.required "column1", O.required "column2"))
tableKeywordColNames :: O.Table (Column O.PGInt4, Column O.PGInt4)
(Column O.PGInt4, Column O.PGInt4)
tableKeywordColNames = O.Table "keywordtable" (PP.p2 (O.required "column", O.required "where"))
table1Q :: Query (Column O.PGInt4, Column O.PGInt4)
table1Q = O.queryTable table1
table2Q :: Query (Column O.PGInt4, Column O.PGInt4)
table2Q = O.queryTable table2
table3Q :: Query (Column O.PGInt4, Column O.PGInt4)
table3Q = O.queryTable table3
table6Q :: Query (Column O.PGText, Column O.PGText)
table6Q = O.queryTable table6
table1dataG :: Num a => [(a, a)]
table1dataG = [ (1, 100)
, (1, 100)
, (1, 200)
, (2, 300) ]
table1data :: [(Int, Int)]
table1data = table1dataG
table1columndata :: [(Column O.PGInt4, Column O.PGInt4)]
table1columndata = table1dataG
table2dataG :: Num a => [(a, a)]
table2dataG = [ (1, 100)
, (3, 400) ]
table2data :: [(Int, Int)]
table2data = table2dataG
table2columndata :: [(Column O.PGInt4, Column O.PGInt4)]
table2columndata = table2dataG
table3dataG :: Num a => [(a, a)]
table3dataG = [ (1, 50) ]
table3data :: [(Int, Int)]
table3data = table3dataG
table3columndata :: [(Column O.PGInt4, Column O.PGInt4)]
table3columndata = table3dataG
table4dataG :: Num a => [(a, a)]
table4dataG = [ (1, 10)
, (2, 20) ]
table4data :: [(Int, Int)]
table4data = table4dataG
table4columndata :: [(Column O.PGInt4, Column O.PGInt4)]
table4columndata = table4dataG
table6data :: [(String, String)]
table6data = [("xy", "a"), ("z", "a"), ("more text", "a")]
table6columndata :: [(Column O.PGText, Column O.PGText)]
table6columndata = map (\(column1, column2) -> (O.pgString column1, O.pgString column2)) table6data
-- We have to quote the table names here because upper case letters in
-- table names are treated as lower case unless the name is quoted!
dropAndCreateTable :: String -> (String, [String]) -> PGS.Query
dropAndCreateTable columnType (t, cols) = String.fromString drop_
where drop_ = "DROP TABLE IF EXISTS \"public\".\"" ++ t ++ "\";"
++ "CREATE TABLE \"public\".\"" ++ t ++ "\""
++ " (" ++ commas cols ++ ");"
integer c = ("\"" ++ c ++ "\"" ++ " " ++ columnType)
commas = L.intercalate "," . map integer
dropAndCreateTableInt :: (String, [String]) -> PGS.Query
dropAndCreateTableInt = dropAndCreateTable "integer"
dropAndCreateTableText :: (String, [String]) -> PGS.Query
dropAndCreateTableText = dropAndCreateTable "text"
-- We have to quote the table names here because upper case letters in
-- table names are treated as lower case unless the name is quoted!
dropAndCreateTableSerial :: (String, [String]) -> PGS.Query
dropAndCreateTableSerial (t, cols) = String.fromString drop_
where drop_ = "DROP TABLE IF EXISTS \"public\".\"" ++ t ++ "\";"
++ "CREATE TABLE \"public\".\"" ++ t ++ "\""
++ " (" ++ commas cols ++ ");"
integer c = ("\"" ++ c ++ "\"" ++ " SERIAL")
commas = L.intercalate "," . map integer
type Table_ = (String, [String])
-- This should ideally be derived from the table definition above
columns2 :: String -> Table_
columns2 t = (t, ["column1", "column2"])
-- This should ideally be derived from the table definition above
tables :: [Table_]
tables = map columns2 ["table1", "TABLE2", "table3", "table4"]
++ [("keywordtable", ["column", "where"])]
serialTables :: [Table_]
serialTables = map columns2 ["table5"]
dropAndCreateDB :: PGS.Connection -> IO ()
dropAndCreateDB conn = do
mapM_ execute tables
_ <- executeTextTable
mapM_ executeSerial serialTables
where execute = PGS.execute_ conn . dropAndCreateTableInt
executeTextTable = (PGS.execute_ conn . dropAndCreateTableText . columns2) "table6"
executeSerial = PGS.execute_ conn . dropAndCreateTableSerial
type Test = PGS.Connection -> IO Bool
testG :: D.Default O.QueryRunner wires haskells =>
Query wires
-> ([haskells] -> b)
-> PGS.Connection
-> IO b
testG q p conn = do
result <- O.runQuery conn q
return (p result)
testSelect :: Test
testSelect = testG table1Q
(\r -> L.sort table1data == L.sort r)
testProduct :: Test
testProduct = testG query
(\r -> L.sort (A.liftA2 (,) table1data table2data) == L.sort r)
where query = table1Q &&& table2Q
testRestrict :: Test
testRestrict = testG query
(\r -> filter ((== 1) . fst) (L.sort table1data) == L.sort r)
where query = proc () -> do
t <- table1Q -< ()
O.restrict -< fst t .== 1
Arr.returnA -< t
testNum :: Test
testNum = testG query expected
where query :: Query (Column O.PGInt4)
query = proc () -> do
t <- table1Q -< ()
Arr.returnA -< op t
expected = \r -> L.sort (map op table1data) == L.sort r
op :: Num a => (a, a) -> a
op (x, y) = abs (x - 5) * signum (x - 4) * (y * y + 1)
testDiv :: Test
testDiv = testG query expected
where query :: Query (Column O.PGFloat8)
query = proc () -> do
t <- Arr.arr (O.doubleOfInt *** O.doubleOfInt) <<< table1Q -< ()
Arr.returnA -< op t
expected r = L.sort (map (op . toDoubles) table1data) == L.sort r
op :: Fractional a => (a, a) -> a
-- Choosing 0.5 here as it should be exactly representable in
-- floating point
op (x, y) = y / x * 0.5
toDoubles :: (Int, Int) -> (Double, Double)
toDoubles = fromIntegral *** fromIntegral
-- TODO: need to implement and test case_ returning tuples
testCase :: Test
testCase = testG q (== expected)
where q :: Query (Column O.PGInt4)
q = table1Q >>> proc (i, j) -> do
Arr.returnA -< O.case_ [(j .== 100, 12), (i .== 1, 21)] 33
expected :: [Int]
expected = [12, 12, 21, 33]
testDistinct :: Test
testDistinct = testG (O.distinct table1Q)
(\r -> L.sort (L.nub table1data) == L.sort r)
-- FIXME: the unsafeCoerceColumn is currently needed because the type
-- changes required for aggregation are not currently dealt with by
-- Opaleye.
aggregateCoerceFIXME :: QueryArr (Column O.PGInt4) (Column O.PGInt8)
aggregateCoerceFIXME = Arr.arr aggregateCoerceFIXME'
aggregateCoerceFIXME' :: Column a -> Column O.PGInt8
aggregateCoerceFIXME' = O.unsafeCoerceColumn
testAggregate :: Test
testAggregate = testG (Arr.second aggregateCoerceFIXME
<<< O.aggregate (PP.p2 (O.groupBy, O.sum))
table1Q)
(\r -> [(1, 400) :: (Int, Int64), (2, 300)] == L.sort r)
testAggregateFunction :: Test
testAggregateFunction = testG (Arr.second aggregateCoerceFIXME
<<< O.aggregate (PP.p2 (O.groupBy, O.sum))
(fmap (\(x, y) -> (x + 1, y)) table1Q))
(\r -> [(2, 400) :: (Int, Int64), (3, 300)] == L.sort r)
testAggregateProfunctor :: Test
testAggregateProfunctor = testG q expected
where q = O.aggregate (PP.p2 (O.groupBy, countsum)) table1Q
expected r = [(1, 1200) :: (Int, Int64), (2, 300)] == L.sort r
countsum = P.dimap (\x -> (x,x))
(\(x, y) -> aggregateCoerceFIXME' x * y)
(PP.p2 (O.sum, O.count))
testStringArrayAggregate :: Test
testStringArrayAggregate = testG q expected
where q = O.aggregate (PP.p2 (O.arrayAgg, O.min)) table6Q
expected r = [(map fst table6data, minimum (map snd table6data))] == r
testStringAggregate :: Test
testStringAggregate = testG q expected
where q = O.aggregate (PP.p2 ((O.stringAgg . O.pgString) "_", O.groupBy)) table6Q
expected r = [(
(foldl1 (\x y -> x ++ "_" ++ y) . map fst) table6data ,
head (map snd table6data))] == r
testOrderByG :: O.Order (Column O.PGInt4, Column O.PGInt4)
-> ((Int, Int) -> (Int, Int) -> Ordering)
-> Test
testOrderByG orderQ order = testG (O.orderBy orderQ table1Q)
(L.sortBy order table1data ==)
testOrderBy :: Test
testOrderBy = testOrderByG (O.desc snd)
(flip (Ord.comparing snd))
testOrderBy2 :: Test
testOrderBy2 = testOrderByG (O.desc fst <> O.asc snd)
(flip (Ord.comparing fst) <> Ord.comparing snd)
testOrderBySame :: Test
testOrderBySame = testOrderByG (O.desc fst <> O.asc fst)
(flip (Ord.comparing fst) <> Ord.comparing fst)
testLOG :: (Query (Column O.PGInt4, Column O.PGInt4) -> Query (Column O.PGInt4, Column O.PGInt4))
-> ([(Int, Int)] -> [(Int, Int)]) -> Test
testLOG olQ ol = testG (olQ (orderQ table1Q))
(ol (order table1data) ==)
where orderQ = O.orderBy (O.desc snd)
order = L.sortBy (flip (Ord.comparing snd))
testLimit :: Test
testLimit = testLOG (O.limit 2) (take 2)
testOffset :: Test
testOffset = testLOG (O.offset 2) (drop 2)
testLimitOffset :: Test
testLimitOffset = testLOG (O.limit 2 . O.offset 2) (take 2 . drop 2)
testOffsetLimit :: Test
testOffsetLimit = testLOG (O.offset 2 . O.limit 2) (drop 2 . take 2)
testDistinctAndAggregate :: Test
testDistinctAndAggregate = testG q expected
where q = O.distinct table1Q
&&& (Arr.second aggregateCoerceFIXME
<<< O.aggregate (PP.p2 (O.groupBy, O.sum)) table1Q)
expected r = L.sort r == L.sort expectedResult
expectedResult = A.liftA2 (,) (L.nub table1data)
[(1 :: Int, 400 :: Int64), (2, 300)]
one :: Query (Column O.PGInt4)
one = Arr.arr (const (1 :: Column O.PGInt4))
-- The point of the "double" tests is to ensure that we do not
-- introduce name clashes in the operations which create new column names
testDoubleG :: (Eq haskells, D.Default O.QueryRunner columns haskells) =>
(QueryArr () (Column O.PGInt4) -> QueryArr () columns) -> [haskells]
-> Test
testDoubleG q expected1 = testG (q one &&& q one) (== expected2)
where expected2 = A.liftA2 (,) expected1 expected1
testDoubleDistinct :: Test
testDoubleDistinct = testDoubleG O.distinct [1 :: Int]
testDoubleAggregate :: Test
testDoubleAggregate = testDoubleG (O.aggregate O.count) [1 :: Int64]
testDoubleLeftJoin :: Test
testDoubleLeftJoin = testDoubleG lj [(1 :: Int, Just (1 :: Int))]
where lj :: Query (Column O.PGInt4)
-> Query (Column O.PGInt4, Column (Nullable O.PGInt4))
lj q = O.leftJoin q q (uncurry (.==))
testDoubleValues :: Test
testDoubleValues = testDoubleG v [1 :: Int]
where v :: Query (Column O.PGInt4) -> Query (Column O.PGInt4)
v _ = O.values [1]
testDoubleUnionAll :: Test
testDoubleUnionAll = testDoubleG u [1 :: Int, 1]
where u q = q `O.unionAll` q
aLeftJoin :: Query ((Column O.PGInt4, Column O.PGInt4),
(Column (Nullable O.PGInt4), Column (Nullable O.PGInt4)))
aLeftJoin = O.leftJoin table1Q table3Q (\(l, r) -> fst l .== fst r)
testLeftJoin :: Test
testLeftJoin = testG aLeftJoin (== expected)
where expected :: [((Int, Int), (Maybe Int, Maybe Int))]
expected = [ ((1, 100), (Just 1, Just 50))
, ((1, 100), (Just 1, Just 50))
, ((1, 200), (Just 1, Just 50))
, ((2, 300), (Nothing, Nothing)) ]
testLeftJoinNullable :: Test
testLeftJoinNullable = testG q (== expected)
where q :: Query ((Column O.PGInt4, Column O.PGInt4),
((Column (Nullable O.PGInt4), Column (Nullable O.PGInt4)),
(Column (Nullable O.PGInt4),
Column (Nullable O.PGInt4))))
q = O.leftJoin table3Q aLeftJoin cond
cond (x, y) = fst x .== fst (fst y)
expected :: [((Int, Int), ((Maybe Int, Maybe Int), (Maybe Int, Maybe Int)))]
expected = [ ((1, 50), ((Just 1, Just 100), (Just 1, Just 50)))
, ((1, 50), ((Just 1, Just 100), (Just 1, Just 50)))
, ((1, 50), ((Just 1, Just 200), (Just 1, Just 50))) ]
testThreeWayProduct :: Test
testThreeWayProduct = testG q (== expected)
where q = A.liftA3 (,,) table1Q table2Q table3Q
expected = A.liftA3 (,,) table1data table2data table3data
testValues :: Test
testValues = testG (O.values values) (values' ==)
where values :: [(Column O.PGInt4, Column O.PGInt4)]
values = [ (1, 10)
, (2, 100) ]
values' :: [(Int, Int)]
values' = [ (1, 10)
, (2, 100) ]
{- FIXME: does not yet work
testValuesDouble :: Test
testValuesDouble = testG (O.values values) (values' ==)
where values :: [(Column O.PGInt4, Column O.PGFloat8)]
values = [ (1, 10.0)
, (2, 100.0) ]
values' :: [(Int, Double)]
values' = [ (1, 10.0)
, (2, 100.0) ]
-}
testValuesEmpty :: Test
testValuesEmpty = testG (O.values values) (values' ==)
where values :: [Column O.PGInt4]
values = []
values' :: [Int]
values' = []
testUnionAll :: Test
testUnionAll = testG (table1Q `O.unionAll` table2Q)
(\r -> L.sort (table1data ++ table2data) == L.sort r)
testTableFunctor :: Test
testTableFunctor = testG (O.queryTable table1F) (result ==)
where result = fmap (\(col1, col2) -> (col1 + col2, col1 - col2)) table1data
-- TODO: This is getting too complicated
testUpdate :: Test
testUpdate conn = do
_ <- O.runUpdate conn table4 update cond
result <- runQueryTable4
if result /= expected
then return False
else do
_ <- O.runDelete conn table4 condD
resultD <- runQueryTable4
if resultD /= expectedD
then return False
else do
returned <- O.runInsertReturning conn table4 insertT returning
_ <- O.runInsertMany conn table4 insertTMany
resultI <- runQueryTable4
return ((resultI == expectedI) && (returned == expectedR))
where update (x, y) = (x + y, x - y)
cond (_, y) = y .> 15
condD (x, _) = x .> 20
expected :: [(Int, Int)]
expected = [ (1, 10)
, (22, -18)]
expectedD :: [(Int, Int)]
expectedD = [(1, 10)]
runQueryTable4 = O.runQuery conn (O.queryTable table4)
insertT :: (Column O.PGInt4, Column O.PGInt4)
insertT = (1, 2)
insertTMany :: [(Column O.PGInt4, Column O.PGInt4)]
insertTMany = [(20, 30), (40, 50)]
expectedI :: [(Int, Int)]
expectedI = [(1, 10), (1, 2), (20, 30), (40, 50)]
returning (x, y) = x - y
expectedR :: [Int]
expectedR = [-1]
testKeywordColNames :: Test
testKeywordColNames conn = do
let q :: IO [(Int, Int)]
q = O.runQuery conn (O.queryTable tableKeywordColNames)
_ <- q
return True
testInsertSerial :: Test
testInsertSerial conn = do
_ <- O.runInsert conn table5 (Just 10, Just 20)
_ <- O.runInsert conn table5 (Just 30, Nothing)
_ <- O.runInsert conn table5 (Nothing, Nothing)
_ <- O.runInsert conn table5 (Nothing, Just 40)
resultI <- O.runQuery conn (O.queryTable table5)
return (resultI == expected)
where expected :: [(Int, Int)]
expected = [ (10, 20)
, (30, 1)
, (1, 2)
, (2, 40) ]
allTests :: [Test]
allTests = [testSelect, testProduct, testRestrict, testNum, testDiv, testCase,
testDistinct, testAggregate, testAggregateFunction,
testAggregateProfunctor, testStringAggregate,
testOrderBy, testOrderBy2, testOrderBySame, testLimit, testOffset,
testLimitOffset, testOffsetLimit, testDistinctAndAggregate,
testDoubleDistinct, testDoubleAggregate, testDoubleLeftJoin,
testDoubleValues, testDoubleUnionAll,
testLeftJoin, testLeftJoinNullable, testThreeWayProduct, testValues,
testValuesEmpty, testUnionAll, testTableFunctor, testUpdate,
testKeywordColNames, testInsertSerial
]
-- Environment.getEnv throws an exception on missing environment variable!
getEnv :: String -> IO (Maybe String)
getEnv var = do
environment <- Environment.getEnvironment
return (lookup var environment)
-- Using an envvar is unpleasant, but it will do for now.
travis :: IO Bool
travis = do
travis' <- getEnv "TRAVIS"
return (case travis' of
Nothing -> False
Just "yes" -> True
Just _ -> False)
main :: IO ()
main = do
travis' <- travis
let connectInfo' = if travis' then connectInfoTravis else connectInfo
conn <- PGS.connect connectInfo'
dropAndCreateDB conn
let insert (writeable, columndata) =
mapM_ (O.runInsert conn writeable) columndata
mapM_ insert [ (table1, table1columndata)
, (table2, table2columndata)
, (table3, table3columndata)
, (table4, table4columndata) ]
insert (table6, table6columndata)
-- Need to run quickcheck after table data has been inserted
QuickCheck.run conn
results <- mapM ($ conn) allTests
print results
let passed = and results
putStrLn (if passed then "All passed" else "Failure")
Exit.exitWith (if passed then Exit.ExitSuccess
else Exit.ExitFailure 1)
| benkolera/haskell-opaleye | Test/Test.hs | bsd-3-clause | 22,190 | 4 | 17 | 5,742 | 6,930 | 3,778 | 3,152 | 412 | 4 |
{-# LANGUAGE CPP, ScopedTypeVariables, NoImplicitPrelude #-}
-- | Compatibility module to work around differences in the
-- types of functions between pandoc < 2.0 and pandoc >= 2.0.
module Text.CSL.Compat.Pandoc (
writeMarkdown,
writePlain,
writeNative,
writeHtmlString,
readNative,
readHtml,
readMarkdown,
readLaTeX,
fetchItem,
pipeProcess ) where
import Prelude
import qualified Control.Exception as E
import System.Exit (ExitCode)
import Data.ByteString.Lazy as BL
import Data.ByteString as B
import Data.Text (Text)
import Text.Pandoc (Extension (..), Pandoc, ReaderOptions(..), WrapOption(..),
WriterOptions(..), def, pandocExtensions)
import qualified Text.Pandoc as Pandoc
import qualified Text.Pandoc.Process
import qualified Data.Text as T
import Text.Pandoc.MIME (MimeType)
import Text.Pandoc.Error (PandocError)
import Text.Pandoc.Class (runPure, runIO)
import qualified Text.Pandoc.Class (fetchItem)
import Control.Monad.Except (runExceptT, lift)
import Text.Pandoc.Extensions (extensionsFromList, disableExtension)
readHtml :: Text -> Pandoc
readHtml = either mempty id . runPure . Pandoc.readHtml
def{ readerExtensions = extensionsFromList [Ext_native_divs,
Ext_native_spans, Ext_raw_html, Ext_smart] }
readMarkdown :: Text -> Pandoc
readMarkdown = either mempty id . runPure . Pandoc.readMarkdown
def{ readerExtensions = pandocExtensions, readerStandalone = True }
readLaTeX :: Text -> Pandoc
readLaTeX = either mempty id . runPure . Pandoc.readLaTeX
def{ readerExtensions = extensionsFromList [Ext_raw_tex, Ext_smart] }
readNative :: Text -> Pandoc
readNative = either mempty id . runPure . Pandoc.readNative def
writeMarkdown, writePlain, writeNative, writeHtmlString :: Pandoc -> Text
writeMarkdown = either mempty id . runPure . Pandoc.writeMarkdown
def{ writerExtensions = disableExtension Ext_smart $
disableExtension Ext_bracketed_spans $
disableExtension Ext_raw_attribute $
pandocExtensions,
writerWrapText = WrapNone }
writePlain = either mempty id . runPure . Pandoc.writePlain def
writeNative = either mempty id . runPure . Pandoc.writeNative def{ writerTemplate = Just mempty }
writeHtmlString = either mempty id . runPure . Pandoc.writeHtml4String
def{ writerExtensions = extensionsFromList
[Ext_native_divs, Ext_native_spans, Ext_raw_html],
writerWrapText = WrapPreserve }
pipeProcess :: Maybe [(String, String)] -> FilePath -> [String]
-> BL.ByteString -> IO (ExitCode,BL.ByteString)
pipeProcess = Text.Pandoc.Process.pipeProcess
fetchItem :: String
-> IO (Either E.SomeException (B.ByteString, Maybe MimeType))
fetchItem s = do
res <- runIO $ runExceptT $ lift $ Text.Pandoc.Class.fetchItem $ T.pack s
return $ case res of
Left e -> Left (E.toException e)
Right (Left (e :: PandocError)) -> Left (E.toException e)
Right (Right r) -> Right r
| jgm/pandoc-citeproc | compat/Text/CSL/Compat/Pandoc.hs | bsd-3-clause | 3,016 | 0 | 15 | 580 | 806 | 457 | 349 | 65 | 3 |
module Main where
import System.IO
import System.Environment
import System.Exit
import Config
import Store
import Twitter
main :: IO ()
main = do
config <- getConfig
articles <- unpostedArticles def
let keys = twKeys
(cfg_consumer_key config)
(cfg_consumer_secret config)
(cfg_access_token config)
(cfg_access_token_secret config)
mapM_ (post keys) articles
where
getConfig :: IO Config
getConfig = getArgs >>= eachCase
eachCase args
| n == 1 = loadConfig $ args !! 0
| otherwise = do
hPutStrLn stderr "Usage: ndpost config_file"
exitFailure
where
n = length args
| yunomu/nicodicbot | src/NdPost.hs | bsd-3-clause | 687 | 0 | 12 | 205 | 191 | 94 | 97 | 25 | 1 |
module Codegen.Monad
(
) where
import Control.Monad.Trans.Class
import Control.Monad.Writer
import LLVM.General.AST
import Core.Unique
newtype GeneratorT m a = GeneratorT { runGeneratorT' :: WriterT [Definition] m a }
deriving (Functor, Applicative, Monad)
class MonadGenerator m where
newDefinition :: Definition -> m ()
instance MonadGenerator (GeneratorT m) where
newDefinition = GeneratorT . tell . pure
instance MonadTrans GeneratorT where
lift = GeneratorT
runGeneratorT :: UniqueT m a -> m a
runGeneratorT = flip evalStateT 0 . runUniqueT'
instance MonadUnique m => MonadUnique (StateT s m) where
uid = lift uid
instance MonadUnique m => MonadUnique (ReaderT s m) where
uid = lift uid
instance MonadUnique m => MonadUnique (WriterT s m) where
uid = lift uid
instance MonadUnique m => MonadUnique (ExceptT e m) where
uid = lift uid
type Generator = UniqueT (Writer [Definition])
| abbradar/dnohs | src/Codegen/Monad.hs | bsd-3-clause | 944 | 0 | 9 | 192 | 309 | 163 | 146 | 25 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Data.Text.ExtraTest (test_tests) where
import Elm.Utils ((|>))
import Test.Tasty
import Test.Tasty.HUnit
import Data.Text.Extra
test_tests :: TestTree
test_tests =
testGroup "Data.Text.ExtraTest"
[ testCase "when there is no span of the given character" $
longestSpanOf '*' "stars exist only where you believe"
|> assertEqual "" NoSpan
, testCase "when the given character is present" $
longestSpanOf '*' "it's here -> * <-"
|> assertEqual "" (Span 1)
, testCase "only counts the longest span" $
longestSpanOf '*' "it's here -> ** <-, not here: *"
|> assertEqual "" (Span 2)
]
| avh4/elm-format | avh4-lib/test/Data/Text/ExtraTest.hs | bsd-3-clause | 704 | 0 | 10 | 178 | 141 | 75 | 66 | 18 | 1 |
module Main where
import Tkhs
import Parser
import System.Environment
import System.IO.UTF8 as U
import qualified Zipper
import Data.Maybe
main :: IO ()
main = getArgs >>= U.readFile . headOrUsage
>>= either (error . show)
(runP presentation . fromJust . Zipper.fromList . (++[T ["[End of Slide]"]]))
. parseSlides
headOrUsage :: [String] -> String
headOrUsage ls | null ls = error "Usage: tkhs [presentation]"
| otherwise = head ls
| nonowarn/tkhs | src/Main.hs | bsd-3-clause | 518 | 0 | 13 | 152 | 154 | 83 | 71 | 15 | 1 |
module Util.HTML.Attributes where
import Util.HTML
action, align, alt, autocomplete, background, border, charset, checked, _class, cols, colspan, content, enctype, for, height, href, http_equiv, _id, maxlength, method, name, placeholder, role, rows, rowspan, selected, size, src, style, tabindex, target, title, _type, value, width :: String -> Attribute
action = makeAttr "action"
align = makeAttr "align"
alt = makeAttr "alt"
autocomplete = makeAttr "autocomplete"
background = makeAttr "background"
border = makeAttr "border"
charset = makeAttr "charset"
checked = makeAttr "checked"
_class = makeAttr "class"
cols = makeAttr "cols"
colspan = makeAttr "colspan"
content = makeAttr "content"
enctype = makeAttr "enctype"
for = makeAttr "for"
height = makeAttr "height"
href = makeAttr "href"
http_equiv = makeAttr "http-equiv"
_id = makeAttr "id"
maxlength = makeAttr "maxlength"
method = makeAttr "method"
name = makeAttr "name"
placeholder = makeAttr "placeholder"
role = makeAttr "role"
rows = makeAttr "rows"
rowspan = makeAttr "rowspan"
selected = makeAttr "selected"
size = makeAttr "size"
src = makeAttr "src"
style = makeAttr "style"
tabindex = makeAttr "tabindex"
target = makeAttr "target"
title = makeAttr "title"
_type = makeAttr "type"
value = makeAttr "value"
width = makeAttr "width"
| johanneshilden/liquid-epsilon | Util/HTML/Attributes.hs | bsd-3-clause | 1,642 | 0 | 5 | 525 | 369 | 221 | 148 | 38 | 1 |
module Main where
import System.Console.GetOpt
import System.Environment
import qualified TextUI as TUI
data Flag = Help
| Text TUI.Config
options :: [OptDescr Flag]
options =
[ Option ['?','h'] ["help"] (NoArg Help)
"Help message."
, Option ['t'] ["text"] (OptArg textConfig "uc")
"Use text user interface with options: u(nicode), c(olors)."
]
textConfig :: Maybe String -> Flag
textConfig Nothing = Text $ TUI.Config { TUI.colors = False,
TUI.unicode = False }
textConfig (Just opts) =
let
unicode = elem 'u' opts
colors = elem 'c' opts
in Text $ TUI.Config { TUI.colors = colors, TUI.unicode = unicode }
doOptions :: [Flag] -> IO ()
doOptions [] = TUI.newGame $ TUI.Config { TUI.colors = False,
TUI.unicode = False }
doOptions [Help] = putStrLn $ usage
doOptions [Text config] = TUI.newGame config
doOptions _ = do
putStrLn $ "There must be exactly one option specified."
putStrLn $ usage
usage :: String
usage = usageInfo "Usage: FreeCell [options]" options
main :: IO ()
main = do
args <- getArgs
case getOpt Permute options args of
(o, [], []) -> doOptions o
(_, n, []) -> do
putStrLn $ concat $ map ("Unknown option: " ++) n
putStrLn $ usage
(_, _, errs) -> do
putStrLn $ concat errs ++ usage
--let config = TUI.Config { TUI.colors = True, TUI.unicode = True }
--TextUI.newGame config
| sakhnik/FreeCell | Main.hs | bsd-3-clause | 1,539 | 0 | 14 | 466 | 469 | 251 | 218 | 40 | 3 |
-- Copyright (c) 2011, Colin Hill
-- | Implementation of ridged multi-fractal noise.
--
-- Example of use:
--
-- @
--main = putStrLn (\"Noise value at (1, 2, 3): \" ++ show x)
-- where seed = 1
-- octaves = 5
-- scale = 0.005
-- frequency = 1
-- lacunarity = 2
-- ridgedNoise = ridged seed octaves scale frequency lacunarity
-- x = noiseValue ridgedNoise (1, 2, 3)
-- @
module Numeric.Noise.Ridged (
Ridged,
ridged,
noiseValue
) where
import Numeric.Noise
import Data.Bits ((.&.))
import Data.Vector.Unboxed (Vector, fromList, (!))
-- | A ridged multi-fractal noise function.
data Ridged = Ridged Seed Int Double Double Double (Vector Double)
-- | Constructs a ridged multi-fractal noise function given a seed, number of octaves, scale,
-- frequency, and lacunarity.
ridged :: Seed -> Int -> Double -> Double -> Double -> Ridged
ridged seed octs scale freq lac = ridgedNoise
where specWeights = computeSpecWeights octs lac
ridgedNoise = Ridged seed octs scale freq lac specWeights
instance Noise Ridged where
noiseValue ridgedNoise xyz = clamp noise (-1) 1
where Ridged _ octs scale freq _ _ = ridgedNoise
xyz' = pmap (* (scale * freq)) xyz
noise = ridgedNoiseValue ridgedNoise octs 1 xyz' * 1.25 - 1
-- | Computes the noise value for a ridged multi-fractal noise function given the octave number,
-- the weight, and the point.
ridgedNoiseValue :: Ridged -> Int -> Double -> Point -> Double
ridgedNoiseValue _ 0 _ _ = 0
ridgedNoiseValue ridgedNoise oct weight xyz = noise + noise'
where Ridged seed octs _ _ lac specWeights = ridgedNoise
oct' = oct - 1
xyz' = pmap (* lac) xyz
seed' = (seed + (octs - oct)) .&. 0x7fffffff
signal = (offset - abs (coherentNoise seed' xyz)) * weight * weight
weight' = clamp (signal * gain) 0 1
noise = signal * (specWeights ! (octs - oct))
noise' = ridgedNoiseValue ridgedNoise oct' weight' xyz'
gain = 2
offset = 1
-- | Computes the spectral weight for each oct given the number of octs and the lac.
computeSpecWeights :: Int -> Double -> Vector Double
computeSpecWeights octs lac = fromList (computeSpecWeights' octs lac 1)
-- | Helper for 'computeSpecWeights'.
computeSpecWeights' :: Int -> Double -> Double -> [Double]
computeSpecWeights' 0 _ _ = []
computeSpecWeights' oct lac freq = weight : weights
where freq' = freq * lac
oct' = oct - 1
weight = freq ** (-1)
weights = computeSpecWeights' oct' lac freq'
| colinhect/hsnoise | src/Numeric/Noise/Ridged.hs | bsd-3-clause | 2,686 | 0 | 13 | 752 | 618 | 340 | 278 | 39 | 1 |
import Debug.Trace
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Text.Unidecode
main :: IO ()
main = hspec spec
spec = describe "unidecode" $ do
it "doesn't hurt ascii text" $ do
unidecode 'a' `shouldBe` "a"
it "doesn't crash" $ property $
\x -> unidecode x == unidecode x
it "strips out non-ASCII text" $ do
concatMap unidecode "五十音順" `shouldBe` ""
| mwotton/unidecode | test/Spec.hs | bsd-3-clause | 463 | 0 | 12 | 134 | 132 | 65 | 67 | 14 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiWayIf #-}
module Game.Monsters.MGladiator where
import Control.Lens (use, preuse, ix, (^.), (.=), (%=), zoom, (&), (.~), (%~))
import Control.Monad (when, unless, liftM, void)
import Data.Bits ((.&.), (.|.))
import Data.Maybe (isJust)
import Linear (V3(..), normalize, norm, _z)
import qualified Data.Vector as V
import {-# SOURCE #-} Game.GameImportT
import Game.LevelLocalsT
import Game.GameLocalsT
import Game.CVarT
import Game.SpawnTempT
import Game.EntityStateT
import Game.EdictT
import Game.MMoveT
import Game.GClientT
import Game.MoveInfoT
import Game.ClientPersistantT
import Game.ClientRespawnT
import Game.MonsterInfoT
import Game.PlayerStateT
import Types
import QuakeRef
import QuakeState
import CVarVariables
import Game.Adapters
import qualified Constants
import qualified Game.GameAI as GameAI
import qualified Game.GameMisc as GameMisc
import qualified Game.GameUtil as GameUtil
import qualified Game.Monster as Monster
import qualified Game.Monsters.MFlash as MFlash
import qualified Util.Lib as Lib
import qualified Util.Math3D as Math3D
modelScale :: Float
modelScale = 1.0
frameStand1 :: Int
frameStand1 = 0
frameStand7 :: Int
frameStand7 = 6
frameWalk1 :: Int
frameWalk1 = 7
frameWalk16 :: Int
frameWalk16 = 22
frameRun1 :: Int
frameRun1 = 23
frameRun6 :: Int
frameRun6 = 28
frameMelee1 :: Int
frameMelee1 = 29
frameMelee17 :: Int
frameMelee17 = 45
frameAttack1 :: Int
frameAttack1 = 46
frameAttack9 :: Int
frameAttack9 = 54
framePain1 :: Int
framePain1 = 55
framePain6 :: Int
framePain6 = 60
frameDeath1 :: Int
frameDeath1 = 61
frameDeath22 :: Int
frameDeath22 = 82
framePainUp1 :: Int
framePainUp1 = 83
framePainUp7 :: Int
framePainUp7 = 89
gladiatorIdle :: EntThink
gladiatorIdle =
GenericEntThink "gladiator_idle" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundIdle <- use $ mGladiatorGlobals.mGladiatorSoundIdle
sound (Just selfRef) Constants.chanVoice soundIdle 1 Constants.attnIdle 0
return True
gladiatorSight :: EntInteract
gladiatorSight =
GenericEntInteract "gladiator_sight" $ \selfRef _ -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundSight <- use $ mGladiatorGlobals.mGladiatorSoundSight
sound (Just selfRef) Constants.chanVoice soundSight 1 Constants.attnNorm 0
return True
gladiatorSearch :: EntThink
gladiatorSearch =
GenericEntThink "gladiator_search" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundSearch <- use $ mGladiatorGlobals.mGladiatorSoundSearch
sound (Just selfRef) Constants.chanVoice soundSearch 1 Constants.attnNorm 0
return True
gladiatorCleaverSwing :: EntThink
gladiatorCleaverSwing =
GenericEntThink "gladiator_cleaver_swing" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundCleaverSwing <- use $ mGladiatorGlobals.mGladiatorSoundCleaverSwing
sound (Just selfRef) Constants.chanWeapon soundCleaverSwing 1 Constants.attnNorm 0
return True
gladiatorFramesStand :: V.Vector MFrameT
gladiatorFramesStand =
V.fromList [ MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
]
gladiatorMoveStand :: MMoveT
gladiatorMoveStand = MMoveT "gladiatorMoveStand" frameStand1 frameStand7 gladiatorFramesStand Nothing
gladiatorStand :: EntThink
gladiatorStand =
GenericEntThink "gladiator_stand" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just gladiatorMoveStand)
return True
gladiatorFramesWalk :: V.Vector MFrameT
gladiatorFramesWalk =
V.fromList [ MFrameT (Just GameAI.aiWalk) 15 Nothing
, MFrameT (Just GameAI.aiWalk) 7 Nothing
, MFrameT (Just GameAI.aiWalk) 6 Nothing
, MFrameT (Just GameAI.aiWalk) 5 Nothing
, MFrameT (Just GameAI.aiWalk) 2 Nothing
, MFrameT (Just GameAI.aiWalk) 0 Nothing
, MFrameT (Just GameAI.aiWalk) 2 Nothing
, MFrameT (Just GameAI.aiWalk) 8 Nothing
, MFrameT (Just GameAI.aiWalk) 12 Nothing
, MFrameT (Just GameAI.aiWalk) 8 Nothing
, MFrameT (Just GameAI.aiWalk) 5 Nothing
, MFrameT (Just GameAI.aiWalk) 5 Nothing
, MFrameT (Just GameAI.aiWalk) 2 Nothing
, MFrameT (Just GameAI.aiWalk) 2 Nothing
, MFrameT (Just GameAI.aiWalk) 1 Nothing
, MFrameT (Just GameAI.aiWalk) 8 Nothing
]
gladiatorMoveWalk :: MMoveT
gladiatorMoveWalk = MMoveT "gladiatorMoveWalk" frameWalk1 frameWalk16 gladiatorFramesWalk Nothing
gladiatorWalk :: EntThink
gladiatorWalk =
GenericEntThink "gladiator_walk" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just gladiatorMoveWalk)
return True
gladiatorFramesRun :: V.Vector MFrameT
gladiatorFramesRun =
V.fromList [ MFrameT (Just GameAI.aiRun) 23 Nothing
, MFrameT (Just GameAI.aiRun) 14 Nothing
, MFrameT (Just GameAI.aiRun) 14 Nothing
, MFrameT (Just GameAI.aiRun) 21 Nothing
, MFrameT (Just GameAI.aiRun) 12 Nothing
, MFrameT (Just GameAI.aiRun) 13 Nothing
]
gladiatorMoveRun :: MMoveT
gladiatorMoveRun = MMoveT "gladiatorMoveRun" frameRun1 frameRun6 gladiatorFramesRun Nothing
gladiatorRun :: EntThink
gladiatorRun =
GenericEntThink "gladiator_run" $ \selfRef -> do
self <- readRef selfRef
let action = if (self^.eMonsterInfo.miAIFlags) .&. Constants.aiStandGround /= 0
then gladiatorMoveStand
else gladiatorMoveRun
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just action)
return True
gladiatorMelee :: EntThink
gladiatorMelee =
GenericEntThink "GladiatorMelee" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just gladiatorMoveAttackMelee)
return True
gladiatorFramesAttackMelee :: V.Vector MFrameT
gladiatorFramesAttackMelee =
V.fromList [ MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just gladiatorCleaverSwing)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just gladiatorMelee)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just gladiatorCleaverSwing)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just gladiatorMelee)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
]
gladiatorMoveAttackMelee :: MMoveT
gladiatorMoveAttackMelee = MMoveT "gladiatorMoveAttackMelee" frameMelee1 frameMelee17 gladiatorFramesAttackMelee (Just gladiatorRun)
gladiatorAttackMelee :: EntThink
gladiatorAttackMelee =
GenericEntThink "gladiator_melee" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just gladiatorMoveAttackMelee)
return True
gladiatorGun :: EntThink
gladiatorGun =
GenericEntThink "GladiatorGun" $ \selfRef -> do
self <- readRef selfRef
let (Just forward, Just right, _) = Math3D.angleVectors (self^.eEntityState.esAngles) True True False
start = Math3D.projectSource (self^.eEntityState.esOrigin) (MFlash.monsterFlashOffset V.! Constants.mz2GladiatorRailgun1) forward right
-- calc direction to where we targeted
dir = normalize ((self^.ePos1) - start)
Monster.monsterFireRailgun selfRef start dir 50 100 Constants.mz2GladiatorRailgun1
return True
gladiatorFramesAttackGun :: V.Vector MFrameT
gladiatorFramesAttackGun =
V.fromList [ MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just gladiatorGun)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
]
gladiatorMoveAttackGun :: MMoveT
gladiatorMoveAttackGun = MMoveT "gladiatorMoveAttackGun" frameAttack1 frameAttack9 gladiatorFramesAttackGun (Just gladiatorRun)
gladiatorAttack :: EntThink
gladiatorAttack =
GenericEntThink "gladiator_attack" $ \selfRef -> do
self <- readRef selfRef
let Just enemyRef = self^.eEnemy
enemy <- readRef enemyRef
-- a small safe zone
let v = (self^.eEntityState.esOrigin) - (enemy^.eEntityState.esOrigin)
range = norm v
if range <= fromIntegral Constants.meleeDistance + 32
then
return True
else do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundGun <- use $ mGladiatorGlobals.mGladiatorSoundGun
sound (Just selfRef) Constants.chanWeapon soundGun 1 Constants.attnNorm 0
let V3 a b c = enemy^.eEntityState.esOrigin
pos1 = V3 a b (c + fromIntegral (enemy^.eViewHeight))
modifyRef selfRef (\v -> v & ePos1 .~ pos1
& eMonsterInfo.miCurrentMove .~ Just gladiatorMoveAttackGun)
return True
gladiatorFramesPain :: V.Vector MFrameT
gladiatorFramesPain =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
gladiatorMovePain :: MMoveT
gladiatorMovePain = MMoveT "gladiatorMovePain" framePain1 framePain6 gladiatorFramesPain (Just gladiatorRun)
gladiatorFramesPainAir :: V.Vector MFrameT
gladiatorFramesPainAir =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
gladiatorMovePainAir :: MMoveT
gladiatorMovePainAir = MMoveT "gladiatorMovePainAir" framePainUp1 framePainUp7 gladiatorFramesPainAir (Just gladiatorRun)
gladiatorPain :: EntPain
gladiatorPain =
GenericEntPain "gladiator_pain" $ \selfRef _ _ _ -> do
self <- readRef selfRef
when ((self^.eHealth) < (self^.eMaxHealth) `div` 2) $
modifyRef selfRef (\v -> v & eEntityState.esSkinNum .~ 1)
levelTime <- use $ gameBaseGlobals.gbLevel.llTime
if levelTime < (self^.ePainDebounceTime)
then do
when (isJust (self^.eMonsterInfo.miCurrentMove)) $ do
let Just currentMove = self^.eMonsterInfo.miCurrentMove
when ((self^.eVelocity._z) > 100 && (currentMove^.mmId) == "gladiatorMovePain") $
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just gladiatorMovePainAir)
else do
modifyRef selfRef (\v -> v & ePainDebounceTime .~ levelTime + 3)
r <- Lib.randomF
soundPain <- if r < 0.5
then use $ mGladiatorGlobals.mGladiatorSoundPain1
else use $ mGladiatorGlobals.mGladiatorSoundPain2
sound <- use $ gameBaseGlobals.gbGameImport.giSound
sound (Just selfRef) Constants.chanVoice soundPain 1 Constants.attnNorm 0
skillValue <- liftM (^.cvValue) skillCVar
unless (skillValue == 3) $ do -- no pain anims in nightmare
let currentMove = if (self^.eVelocity._z) > 100
then gladiatorMovePainAir
else gladiatorMovePain
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just currentMove)
gladiatorDead :: EntThink
gladiatorDead =
GenericEntThink "gladiator_dead" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMins .~ V3 (-16) (-16) (-24)
& eMaxs .~ V3 16 16 (-8)
& eMoveType .~ Constants.moveTypeToss
& eSvFlags %~ (.|. Constants.svfDeadMonster)
& eNextThink .~ 0)
linkEntity <- use $ gameBaseGlobals.gbGameImport.giLinkEntity
linkEntity selfRef
return True
gladiatorFramesDeath :: V.Vector MFrameT
gladiatorFramesDeath =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
gladiatorMoveDeath :: MMoveT
gladiatorMoveDeath = MMoveT "gladiatorMoveDeath" frameDeath1 frameDeath22 gladiatorFramesDeath (Just gladiatorDead)
gladiatorDie :: EntDie
gladiatorDie =
GenericEntDie "gladiator_die" $ \selfRef _ _ damage _ -> do
self <- readRef selfRef
gameImport <- use $ gameBaseGlobals.gbGameImport
let soundIndex = gameImport^.giSoundIndex
sound = gameImport^.giSound
if | (self^.eHealth) <= (self^.eGibHealth) -> do -- check for gib
soundIdx <- soundIndex (Just "misc/udeath.wav")
sound (Just selfRef) Constants.chanVoice soundIdx 1 Constants.attnNorm 0
GameMisc.throwGib selfRef "models/objects/gibs/bone/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/bone/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwHead selfRef "models/objects/gibs/head2/tris.md2" damage Constants.gibOrganic
modifyRef selfRef (\v -> v & eDeadFlag .~ Constants.deadDead)
| (self^.eDeadFlag) == Constants.deadDead ->
return ()
| otherwise -> do -- regular death
soundDie <- use $ mGladiatorGlobals.mGladiatorSoundDie
sound (Just selfRef) Constants.chanVoice soundDie 1 Constants.attnNorm 0
modifyRef selfRef (\v -> v & eDeadFlag .~ Constants.deadDead
& eTakeDamage .~ Constants.damageYes
& eMonsterInfo.miCurrentMove .~ Just gladiatorMoveDeath)
{-
- QUAKED monster_gladiator (1 .5 0) (-32 -32 -24) (32 32 64) Ambush
- Trigger_Spawn Sight
-}
spMonsterGladiator :: Ref EdictT -> Quake ()
spMonsterGladiator selfRef = do
deathmatchValue <- liftM (^.cvValue) deathmatchCVar
if deathmatchValue /= 0
then
GameUtil.freeEdict selfRef
else do
gameImport <- use $ gameBaseGlobals.gbGameImport
let soundIndex = gameImport^.giSoundIndex
modelIndex = gameImport^.giModelIndex
linkEntity = gameImport^.giLinkEntity
soundIndex (Just "gladiator/pain.wav") >>= (mGladiatorGlobals.mGladiatorSoundPain1 .=)
soundIndex (Just "gladiator/gldpain2.wav") >>= (mGladiatorGlobals.mGladiatorSoundPain2 .=)
soundIndex (Just "gladiator/glddeth2.wav") >>= (mGladiatorGlobals.mGladiatorSoundDie .=)
soundIndex (Just "gladiator/railgun.wav") >>= (mGladiatorGlobals.mGladiatorSoundGun .=)
soundIndex (Just "gladiator/melee1.wav") >>= (mGladiatorGlobals.mGladiatorSoundCleaverSwing .=)
soundIndex (Just "gladiator/melee2.wav") >>= (mGladiatorGlobals.mGladiatorSoundCleaverHit .=)
soundIndex (Just "gladiator/melee3.wav") >>= (mGladiatorGlobals.mGladiatorSoundCleaverMiss .=)
soundIndex (Just "gladiator/gldidle1.wav") >>= (mGladiatorGlobals.mGladiatorSoundIdle .=)
soundIndex (Just "gladiator/gldsrch1.wav") >>= (mGladiatorGlobals.mGladiatorSoundSearch .=)
soundIndex (Just "gladiator/sight.wav") >>= (mGladiatorGlobals.mGladiatorSoundSight .=)
modelIdx <- modelIndex (Just "models/monsters/gladiatr/tris.md2")
modifyRef selfRef (\v -> v & eMoveType .~ Constants.moveTypeStep
& eSolid .~ Constants.solidBbox
& eEntityState.esModelIndex .~ modelIdx
& eMins .~ V3 (-32) (-32) (-24)
& eMaxs .~ V3 32 32 64
& eHealth .~ 400
& eGibHealth .~ (-175)
& eMass .~ 400
& ePain .~ Just gladiatorPain
& eDie .~ Just gladiatorDie
& eMonsterInfo.miStand .~ Just gladiatorStand
& eMonsterInfo.miWalk .~ Just gladiatorWalk
& eMonsterInfo.miRun .~ Just gladiatorRun
& eMonsterInfo.miDodge .~ Nothing
& eMonsterInfo.miAttack .~ Just gladiatorAttack
& eMonsterInfo.miMelee .~ Just gladiatorAttackMelee
& eMonsterInfo.miSight .~ Just gladiatorSight
& eMonsterInfo.miIdle .~ Just gladiatorIdle
& eMonsterInfo.miSearch .~ Just gladiatorSearch)
linkEntity selfRef
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just gladiatorMoveStand
& eMonsterInfo.miScale .~ modelScale)
void $ think GameAI.walkMonsterStart selfRef
| ksaveljev/hake-2 | src/Game/Monsters/MGladiator.hs | bsd-3-clause | 19,821 | 0 | 50 | 5,390 | 5,223 | 2,649 | 2,574 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Graphics.Blank.DeviceContext where
import Control.Concurrent.STM
import Data.Set (Set)
import Data.Text.Lazy (Text, toStrict)
import Graphics.Blank.Events
import Graphics.Blank.JavaScript
import Graphics.Blank.Instr
import Prelude.Compat
-- import TextShow (Builder, toText)
--import qualified Web.Scotty.Comet as KC
import Network.JavaScript as JS
-- | 'DeviceContext' is the abstract handle into a specific 2D context inside a browser.
-- Note that the JavaScript API concepts of
-- @<https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D CanvasRenderingContext2D>@ and
-- @<https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement HTMLCanvasElement>@
-- are conflated in @blank-canvas@. Therefore, there is no
-- @<https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext getContext()>@ method;
-- rather, @getContext()@ is implied (when using 'send').
data DeviceContext = DeviceContext
{ theComet :: JS.Engine -- ^ The mechanisms for sending commands
, eventQueue :: EventQueue -- ^ A single (typed) event queue
, ctx_width :: !Int
, ctx_height :: !Int
, ctx_devicePixelRatio :: !Double
, localFiles :: TVar (Set Text) -- ^ approved local files
, weakRemoteMonad :: Bool -- ^ use a weak remote monad for debugging
}
instance Image DeviceContext where
jsImage = jsImage . deviceCanvasContext
width = fromIntegral . ctx_width
height = fromIntegral . ctx_height
deviceCanvasContext :: DeviceContext -> CanvasContext
deviceCanvasContext cxt = CanvasContext Nothing (ctx_width cxt) (ctx_height cxt)
-- | 'devicePixelRatio' returns the device's pixel ratio as used. Typically, the
-- browser ignores @devicePixelRatio@ in the canvas, which can make fine details
-- and text look fuzzy. Using the query @?hd@ on the URL, @blank-canvas@ attempts
-- to use the native @devicePixelRatio@, and if successful, 'devicePixelRatio' will
-- return a number other than 1. You can think of 'devicePixelRatio' as the line
-- width to use to make lines look one pixel wide.
devicePixelRatio :: DeviceContext -> Double
devicePixelRatio = ctx_devicePixelRatio
-- | Internal command to send a message to the canvas.
sendToCanvas :: DeviceContext -> Instr -> IO ()
sendToCanvas cxt cmds = do
print "sendToCanvas"
-- KC.send (theComet cxt) . toStrict . toLazyText $ surround "syncToFrame(function(){" "});" <> cmds
-- | Wait for any event. Blocks.
wait :: DeviceContext -> IO Event
wait c = atomically $ readTChan (eventQueue c)
-- | 'flush' all the current events, returning them all to the user. Never blocks.
flush :: DeviceContext -> IO [Event]
flush cxt = atomically $ loop
where loop = do
b <- isEmptyTChan (eventQueue cxt)
if b then return [] else do
e <- readTChan (eventQueue cxt)
es <- loop
return (e : es)
| ku-fpg/blank-canvas | Graphics/Blank/DeviceContext.hs | bsd-3-clause | 3,158 | 0 | 15 | 721 | 411 | 233 | 178 | 46 | 2 |
{-# LANGUAGE RecordWildCards #-}
module Day7 where
import Data.List
import Data.List.Split
data IP = IP
{ supernet :: [String]
, hypernet :: [String]
}
input :: IO String
input = readFile "day7"
parse :: String -> IP
parse s = IP (map head parts) (concatMap tail parts)
where
parts = chunksOf 2 $ splitOneOf "[]" s
load :: String -> [IP]
load = map parse . lines
isAbba :: String -> Bool
isAbba [a, b, c, d] = a == d && b == c && a /= b
hasAbba :: String -> Bool
hasAbba = any isAbba . map (take 4) . drop 4 . reverse . tails
hasTls :: IP -> Bool
hasTls IP{..} = any hasAbba supernet && not (any hasAbba hypernet)
solve1 :: [IP] -> Int
solve1 = length . filter hasTls
isAba :: String -> Bool
isAba [a, b, c] = a == c && a /= b
findAbas :: String -> [String]
findAbas = filter isAba . map (take 3) . drop 3 . reverse . tails
toBab :: String -> String
toBab [a, b, _] = [b, a, b]
hasSsl :: IP -> Bool
hasSsl IP{..} = not . null $ intersect abas babs
where
abas = concatMap findAbas supernet
babs = concatMap (map toBab . findAbas) hypernet
solve2 :: [IP] -> Int
solve2 = length . filter hasSsl
| mbernat/aoc16-haskell | src/Day7.hs | bsd-3-clause | 1,137 | 0 | 11 | 271 | 514 | 273 | 241 | 34 | 1 |
module Interpret
( interpret
)
where
import Ast
import Control.Monad.Trans.State
import Data.Map (Map)
import qualified Data.Map as M
import Control.Monad
import Control.Monad.IO.Class
import Control.Arrow (first)
interpret :: Program -> IO (Maybe String)
interpret p =
let ftab = buildFunctionTable p
in case M.lookup "main" ftab of
Nothing -> return $ Just "function \"main\" is not defined"
Just main -> do
result <- evalStateT (runEvalLisp (call main [])) (ftab, ftab)
case result of
Left e -> return $ Just e
_ -> return Nothing
----
type SymTab = Map String Value
type FunTab = SymTab
data Value = IntVal Integer
| BoolVal Bool
| ArrayVal [Value]
| LambdaVal [Identifier] [Expr]
instance Show Value where
show (IntVal a) = show a
show (BoolVal a) = show a
show (ArrayVal a) = "[" ++ unwords (map show a) ++ "]"
show (LambdaVal params body) =
show $ Lambda params body
instance Num Value where
(IntVal a) + (IntVal b) = IntVal $ a + b
_ + _ = error "Type error: Should have been caught by the type checker"
(IntVal a) - (IntVal b) = IntVal $ a - b
_ - _ = error "Type error: Should have been caught by the type checker"
(IntVal a) * (IntVal b) = IntVal $ a * b
_ * _ = error "Type error: Should have been caught by the type checker"
abs (IntVal a) = IntVal $ abs a
abs _ = error "Type error: Should have been caught by the type checker"
signum (IntVal a) = IntVal $ signum a
signum _ = error "Type error: Should have been caught by the type checker"
fromInteger = IntVal . fromInteger
instance Ord Value where
compare (IntVal a) (IntVal b) = compare a b
compare (BoolVal a) (BoolVal b) = compare a b
compare _ _ = error "Type error: Should have been caught by the type checker"
instance Eq Value where
(==) (IntVal a) (IntVal b) = a == b
(==) (BoolVal a) (BoolVal b) = a == b
(==) _ _ = error "Type error: Should have been caught by the type checker"
evalExprs :: [Expr] -> StateT (SymTab, FunTab) IO (Either String Value)
evalExprs [] = return $ Left "No expressions to evaluate"
evalExprs [e] = runEvalLisp $ eval e
evalExprs (e : es) = do
e' <- runEvalLisp $ eval e
case e' of
Left err' -> return $ Left err'
Right _ -> evalExprs es
bindArgs :: (Monad a) => [(Identifier, Value)] -> StateT (SymTab, FunTab) a ()
bindArgs [] = return ()
bindArgs ((p, a) : rest) = do
update $ first $ M.insert p a
bindArgs rest
update :: Monad m => (a -> a) -> StateT a m ()
update f = do
s <- get
let s' = f s
put s'
eval :: Expr -> EvalLisp Value
eval (IntLit a) = return $ IntVal a
eval (Ref a) = EvalLisp $ do
(vtab, ftab) <- get
runEvalLisp $ case M.lookup a vtab of
Just x -> EvalLisp $ return $ Right x
Nothing -> case M.lookup a ftab of
Just x -> EvalLisp $ return $ Right x
Nothing -> err $ a ++ " is undefined"
eval (Plus a b) = (+) <$> eval a <*> eval b
eval (Minus a b) = (-) <$> eval a <*> eval b
eval (Times a b) = (*) <$> eval a <*> eval b
eval (Greater a b) = ((BoolVal .) . (>)) <$> eval a <*> eval b
eval (GreaterEq a b) = ((BoolVal .) . (>=)) <$> eval a <*> eval b
eval (Less a b) = ((BoolVal .) . (<)) <$> eval a <*> eval b
eval (LessEq a b) = ((BoolVal .) . (<=)) <$> eval a <*> eval b
eval (Eq a b) = ((BoolVal .) . (==)) <$> eval a <*> eval b
eval (NotEq a b) = ((BoolVal .) . (/=)) <$> eval a <*> eval b
eval (And a b) = boolValAnd <$> eval a <*> eval b
eval (Or a b) = boolValOr <$> eval a <*> eval b
eval (Not a) = boolValNot <$> eval a
eval (If cond thenB elseB) = do
cond' <- eval cond
case cond' of
(BoolVal True) -> eval thenB
_ -> eval elseB
eval (Call e params) = do
e' <- eval e
params' <- mapM eval params
call e' params'
eval (Lambda args body) = return $ LambdaVal args body
eval (Array elements) = do
x <- mapM eval elements
return $ ArrayVal x
eval (Print a) = do
a' <- eval a
liftIO $ print a'
return a'
eval (Let [] body) = EvalLisp $ evalExprs body
eval (Let ((i, e) : bindings) body) = do
v <- eval e
EvalLisp $ do
update $ first $ M.insert i v
runEvalLisp $ eval (Let bindings body)
call :: Value -> [Value] -> EvalLisp Value
call (LambdaVal params _) args | length params /= length args = err "Wrong number of arguments"
call (LambdaVal params body) args = EvalLisp $ do
prev@(_, funs) <- get
put (M.empty, funs)
bindArgs $ zip params args
result <- evalExprs body
put prev
return result
call (ArrayVal vals) [IntVal n] = case vals `safeIdx` fromIntegral n of
Nothing -> err "Array index failure"
Just x -> return x
call (ArrayVal _) _ = err "Wrong number of arguments to array"
call i _ = err $ show i ++ " is not a function"
safeIdx :: [a] -> Int -> Maybe a
safeIdx [] _ = Nothing
safeIdx (x : _) 0 = Just x
safeIdx (_ : rest) n = safeIdx rest (n - 1)
boolValNot :: Value -> Value
boolValNot (BoolVal a) = BoolVal $ not a
boolValNot _ = error "Type error: Should have been caught by the type checker"
boolValAnd :: Value -> Value -> Value
boolValAnd (BoolVal a) (BoolVal b) = BoolVal $ a && b
boolValAnd _ _ = error "Type error: Should have been caught by the type checker"
boolValOr :: Value -> Value -> Value
boolValOr (BoolVal a) (BoolVal b) = BoolVal $ a || b
boolValOr _ _ = error "Type error: Should have been caught by the type checker"
buildFunctionTable :: [Function] -> SymTab
buildFunctionTable = M.fromList . map (\f -> (funName f, LambdaVal (funArgs f) (funBody f)))
-- | EvalLisp helper type
newtype EvalLisp a = EvalLisp { runEvalLisp :: StateT (SymTab, FunTab) IO (Either String a) }
instance Functor EvalLisp where
fmap f (EvalLisp x) = EvalLisp $ do
x' <- x
return $ do
x'' <- x'
return $ f x''
instance Applicative EvalLisp where
pure = EvalLisp . pure . Right
(EvalLisp f) <*> (EvalLisp x) = EvalLisp $ do
f' <- f
x' <- x
return $ do
f'' <- f'
x'' <- x'
return $ f'' x''
err :: String -> EvalLisp a
err = EvalLisp . return . Left
instance Monad EvalLisp where
return = pure
(EvalLisp x) >>= f = EvalLisp $ do
x' <- x
case x' of
Left e -> return $ Left e
Right x'' -> runEvalLisp $ f x''
instance MonadIO EvalLisp where
liftIO x = EvalLisp $ do
x' <- liftIO x
return $ Right x'
| davidpdrsn/alisp | src/Interpret.hs | bsd-3-clause | 6,671 | 0 | 18 | 1,946 | 2,785 | 1,372 | 1,413 | 171 | 4 |
------------------------------------------------------------------------
-- |
-- Module : Data.CSV.BatchAverage
-- Copyright : (c) Amy de Buitléir 2014
-- License : BSD-style
-- Maintainer : amy@nualeargais.ie
-- Stability : experimental
-- Portability : portable
--
-- Groups the records of a CSV into fixed-size batches, calculates
-- the average of each column in a batch, and prints the averages.
-- The last batch may be smaller than the others, depending on the batch
-- size.
------------------------------------------------------------------------
import Data.List
import Data.List.Split
import Factory.Math.Statistics (getMean)
import System.Environment(getArgs)
fromCSV :: String -> ([String], [[Double]])
fromCSV xss = extractValues . tokenise $ xss
toCSVLine :: Show a => [a] -> String
toCSVLine = intercalate "," . map show
tokenise :: String -> [[String]]
tokenise = map (splitOn ",") . lines
extractValues :: [[String]] -> ([String], [[Double]])
extractValues xss = (headings, values)
where (headings:xs) = xss
values = map (map read) xs
mapColumns :: ([Double] -> Double) -> [[Double]] -> [Double]
mapColumns f xss = map f . transpose $ xss
main :: IO ()
main = do
args <- getArgs
let n = read . head $ args
(hs,xss) <- fmap fromCSV getContents
putStrLn . intercalate "," $ hs
let yss = map (mapColumns getMean) . chunksOf n $ xss
mapM_ putStrLn . map toCSVLine $ yss
| mhwombat/amy-csv | src/Data/CSV/BatchAverage.hs | bsd-3-clause | 1,433 | 0 | 14 | 258 | 399 | 218 | 181 | 24 | 1 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Ivory.ModelCheck.CVC4 where
import qualified Data.ByteString.Char8 as B
import Data.Int
import Data.List (intersperse)
import Data.Monoid
import Data.String
import Data.Word
import Prelude hiding (exp)
import Ivory.Language.Syntax.Concrete.Location
import Ivory.Language.Syntax.Concrete.Pretty
--------------------------------------------------------------------------------
type Var = String
type Func = String
--------------------------------------------------------------------------------
-- Concrete syntax
class Concrete a where
concrete :: a -> B.ByteString
instance Concrete B.ByteString where
concrete = id
instance Concrete String where
concrete = B.pack
instance Concrete SrcLoc where
concrete = concrete . prettyPrint . pretty
data ConcreteList = forall a. Concrete a => CL a
-- Specialization
clBS :: B.ByteString -> ConcreteList
clBS = CL
--------------------------------------------------------------------------------
-- Statements
data Statement = TypeDecl String [(Var, Type)]
| VarDecl Var Type
| Assert (Located Expr)
| Query (Located Expr)
-- Arbitrary statement constructed by-hand.
| forall a . Concrete a => Statement a
instance Concrete Statement where
concrete (TypeDecl ty [])
= statement [CL ty, clBS ":", clBS "TYPE"]
concrete (TypeDecl ty fs)
= statement [CL ty, clBS ":", clBS "TYPE", clBS "= [#", fieldList fs, clBS "#]"]
concrete (VarDecl v ty) = statement [CL v, clBS ":", CL ty]
concrete (Assert (Located loc exp))
= statement [clBS "ASSERT", CL exp, clBS ";\t %", CL loc]
concrete (Query (Located loc exp))
= statement [clBS "QUERY", CL exp, clBS ";\t %", CL loc]
concrete (Statement a) = statement [CL a]
statement :: [ConcreteList] -> B.ByteString
statement as =
let unList (CL a) = concrete a in
let toks = B.unwords (map unList as) in
B.snoc toks ';'
fieldList :: [(Var,Type)] -> ConcreteList
fieldList fs = clBS $ B.intercalate ", "
[concrete v <> " : " <> concrete t | (v,t) <- fs]
typeDecl :: String -> [(Var,Type)] -> Statement
typeDecl = TypeDecl
varDecl :: Var -> Type -> Statement
varDecl = VarDecl
assert :: Located Expr -> Statement
assert = Assert
query :: Located Expr -> Statement
query = Query
--------------------------------------------------------------------------------
-- Expressions and literals
instance Concrete Float where
concrete = concrete . show
instance Concrete Double where
concrete = concrete . show
instance Concrete Integer where
concrete = concrete . show
instance Concrete Int where
concrete = concrete . show
data Type = Void
| Integer
| Real
| Char
| Bool
| Struct String
| Array Type
| Opaque
deriving (Show, Read, Eq)
instance Concrete Type where
concrete Bool = "BOOLEAN"
concrete Real = "REAL"
concrete Integer = "INT"
concrete (Array t) = "ARRAY INT OF " <> concrete t
concrete (Struct name) = B.pack name
concrete _ = "INT" -- error $ "unexpected type: " ++ show t
data Expr = Var Var
-- Boolean expressions
| T
| F
| Not Expr
| And Expr Expr
| Or Expr Expr
| Impl Expr Expr
| Equiv Expr Expr
| Eq Expr Expr
| Le Expr Expr
| Leq Expr Expr
| Ge Expr Expr
| Geq Expr Expr
-- Numeric expressions
| forall a . (Show a, Concrete a, Num a) => NumLit a
| Add Expr Expr
| Sub Expr Expr
| Mod Expr Integer -- CVC4 can handle mod-by-constant
| Call Func [Expr]
| Store Expr Expr
| StoreMany Expr [(Expr,Expr)]
| Field Expr Expr
| Index Expr Expr
-- Store (Index 4 (Field "bFoo" "var0")) 5
-- var0 WITH .bFoo[4] := 5
-- Index 5 (Index 1) "var0")
-- var0[1][5]
deriving instance Show Expr
substExpr :: [(Var, Expr)] -> Expr -> Expr
substExpr su = go
where
go (Var v) = case lookup v su of
Nothing -> Var v
Just e -> e
go (Not e) = Not (go e)
go (And x y) = And (go x) (go y)
go (Or x y) = Or (go x) (go y)
go (Impl x y) = Impl (go x) (go y)
go (Equiv x y) = Equiv (go x) (go y)
go (Eq x y) = Eq (go x) (go y)
go (Le x y) = Le (go x) (go y)
go (Leq x y) = Leq (go x) (go y)
go (Ge x y) = Ge (go x) (go y)
go (Geq x y) = Geq (go x) (go y)
go (Add x y) = Add (go x) (go y)
go (Sub x y) = Sub (go x) (go y)
go (Mod x y) = Mod (go x) y
go (Call f es) = Call f (map go es)
go (Store s e) = Store (go s) (go e)
go (StoreMany a ies) = StoreMany (go a) (map (\(i,e) -> (go i, go e)) ies)
go (Field f e) = Field (go f) (go e)
go (Index i e) = Index (go i) (go e)
go e = e
leaf :: Expr -> Bool
leaf exp =
case exp of
(Var _) -> True
T -> True
F -> True
(NumLit _) -> True
_ -> False
parens :: Expr -> B.ByteString
parens exp =
if leaf exp
then concrete exp
else '(' `B.cons` (concrete exp `B.snoc` ')')
instance Concrete Expr where
concrete (Var v) = concrete v
concrete T = "TRUE"
concrete F = "FALSE"
concrete (Not e) = B.unwords ["NOT", parens e]
concrete (And e0 e1) = B.unwords [parens e0, "AND", parens e1]
concrete (Or e0 e1) = B.unwords [parens e0, "OR" , parens e1]
concrete (Impl e0 e1) = B.unwords [parens e0, "=>" , parens e1]
concrete (Equiv e0 e1) = B.unwords [parens e0, "<=>", parens e1]
concrete (Eq e0 e1) = B.unwords [parens e0, "=" , parens e1]
concrete (Le e0 e1) = B.unwords [parens e0, "<" , parens e1]
concrete (Leq e0 e1) = B.unwords [parens e0, "<=" , parens e1]
concrete (Ge e0 e1) = B.unwords [parens e0, ">" , parens e1]
concrete (Geq e0 e1) = B.unwords [parens e0, ">=" , parens e1]
concrete (NumLit n) = concrete n
concrete (Add e0 e1) = B.unwords [parens e0, "+", parens e1]
concrete (Sub e0 e1) = B.unwords [parens e0, "-", parens e1]
concrete (Mod e x) = B.unwords [parens e, "MOD", concrete x]
concrete (Call f args) = concrete f
`B.append` ('(' `B.cons` (args' `B.snoc` ')'))
where
args' = B.unwords $ intersperse "," (map concrete args)
concrete (Store s e) = v <> " WITH " <> f <> " := " <> concrete e
where
(v,f) = B.break (`elem` (".[" :: String)) (concrete s)
-- concrete (Store a i e) = concrete a <> " WITH "
-- <> B.concat (map concrete i)
-- <> " := " <> concrete e
concrete (StoreMany a ies)
= concrete a <> " WITH " <>
B.intercalate ", " [ f <> " := " <> concrete e
| (i,e) <- ies
, let f = B.dropWhile (not . (`elem` (".[" :: String)))
(concrete i)
]
concrete (Field f e) = concrete e <> "." <> concrete f
concrete (Index i e) = concrete e <> "[" <> concrete i <> "]"
-- concrete (Select e ss) = concrete e <> B.concat (map concrete ss)
-- concrete (Load a i) = concrete a <> "[" <> concrete i <> "]"
-- instance Concrete Selector where
-- concrete (Field f) = "." <> concrete f
-- concrete (Index i) = "[" <> concrete i <> "]"
var :: Var -> Expr
var = Var
true :: Expr
true = T
false :: Expr
false = F
not' :: Expr -> Expr
not' = Not
(.&&) :: Expr -> Expr -> Expr
(.&&) = And
(.||) :: Expr -> Expr -> Expr
(.||) = Or
(.=>) :: Expr -> Expr -> Expr
(.=>) T e = e
(.=>) x y = Impl x y
(.<=>) :: Expr -> Expr -> Expr
(.<=>) = Equiv
(.==) :: Expr -> Expr -> Expr
(.==) = Eq
(.<) :: Expr -> Expr -> Expr
(.<) = Le
(.<=) :: Expr -> Expr -> Expr
(.<=) = Leq
(.>) :: Expr -> Expr -> Expr
(.>) = Ge
(.>=) :: Expr -> Expr -> Expr
(.>=) = Geq
(.+) :: Expr -> Expr -> Expr
(.+) = Add
(.-) :: Expr -> Expr -> Expr
(.-) = Sub
(.%) :: Expr -> Integer -> Expr
(.%) = Mod
lit :: (Show a, Concrete a, Num a) => a -> Expr
lit = NumLit
intLit :: Integer -> Expr
intLit = lit
realLit :: Double -> Expr
realLit = lit
call :: Func -> [Expr] -> Expr
call = Call
store :: Expr -> Expr -> Expr
store = Store
storeMany :: Expr -> [(Expr,Expr)] -> Expr
storeMany = StoreMany
field :: Expr -> Expr -> Expr
field = Field
index :: Expr -> Expr -> Expr
index = Index
--------------------------------------------------------------------------------
-- CVC4 Lib
----------------------------------------
-- Bounded int types
boundedFunc :: forall a . (Show a, Integral a, Bounded a)
=> Func -> a -> Statement
boundedFunc f _sz = Statement $ B.unwords
[ B.pack f, ":", "INT", "->", "BOOLEAN"
, "=", "LAMBDA", "(x:INT)", ":"
, exp (toInt minBound) (toInt maxBound)
]
where
toInt a = fromIntegral (a :: a)
x = var "x"
exp l h = concrete $ (intLit l .<= x) .&& (x .<= intLit h)
word8, word16, word32, word64, int8, int16, int32, int64 :: Func
word8 = "word8"
word16 = "word16"
word32 = "word32"
word64 = "word64"
int8 = "int8"
int16 = "int16"
int32 = "int32"
int64 = "int64"
word8Bound :: Statement
word8Bound = boundedFunc word8 (0 :: Word8)
word16Bound :: Statement
word16Bound = boundedFunc word16 (0 :: Word16)
word32Bound :: Statement
word32Bound = boundedFunc word32 (0 :: Word32)
word64Bound :: Statement
word64Bound = boundedFunc word64 (0 :: Word64)
int8Bound :: Statement
int8Bound = boundedFunc int8 (0 :: Int8)
int16Bound :: Statement
int16Bound = boundedFunc int16 (0 :: Int16)
int32Bound :: Statement
int32Bound = boundedFunc int32 (0 :: Int32)
int64Bound :: Statement
int64Bound = boundedFunc int64 (0 :: Int64)
----------------------------------------
-- Mod
modAbs :: Func
modAbs = "mod"
-- | Abstraction: a % b (C semantics) implies
--
-- ( ((a >= 0) && (a % b >= 0) && (a % b < b) && (a % b <= a))
-- || ((a < 0) && (a % b <= 0) && (a % b > b) && (a % b >= a)))
--
-- a % b is abstracted with a fresh var v.
modFunc :: Statement
modFunc = Statement $ B.unwords
[ B.pack modAbs, ":", "(INT, INT)", "->", "INT" ]
modExp :: Expr -> Expr -> Expr -> Expr
modExp v a b
= ((a .>= z) .&& (v .>= z) .&& (v .< b) .&& (v .<= a))
.|| ((a .< z) .&& (v .<= z) .&& (v .> b) .&& (v .>= a))
where
z = intLit 0
----------------------------------------
-- Mul
mulAbs :: Func
mulAbs = "mul"
mulFunc :: Statement
mulFunc = Statement $ B.unwords
[ B.pack mulAbs, ":", "(INT, INT)", "->", "INT" ]
mulExp :: Expr -> Expr -> Expr -> Expr
mulExp v a b
= (((a .== z) .|| (b .== z)) .=> (v .== z))
.&& ((a .== o) .=> (v .== b))
.&& ((b .== o) .=> (v .== a))
.&& (((a .> o) .&& (b .> o)) .=> ((v .> a) .&& (v .> b)))
where
z = intLit 0
o = intLit 1
----------------------------------------
-- Div
divAbs :: Func
divAbs = "div"
divFunc :: Statement
divFunc = Statement $ B.unwords
[ B.pack divAbs, ":", "(INT, INT)", "->", "INT" ]
divExp :: Expr -> Expr -> Expr -> Expr
divExp v a b
= ((b .== o) .=> (v .== a))
.&& ((a .== z) .=> (v .== z))
.&& (((a .>= o) .&& (b .> o)) .=> ((v .>= z) .&& (v .< a)))
where
z = intLit 0
o = intLit 1
cvc4Lib :: [Statement]
cvc4Lib =
[ word8Bound, word16Bound, word32Bound, word64Bound
, int8Bound, int16Bound, int32Bound, int64Bound
, modFunc, mulFunc, divFunc
]
--------------------------------------------------------------------------------
-- Testing
foo :: Statement
foo = assert . noLoc $ (intLit 3 .== var "x") .&& (var "x" .< intLit 4)
| Hodapp87/ivory | ivory-model-check/src/Ivory/ModelCheck/CVC4.hs | bsd-3-clause | 11,945 | 0 | 17 | 3,411 | 4,411 | 2,394 | 2,017 | 300 | 21 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
module DirectoryServer where
import Control.Monad.Trans.Except
import Control.Monad.Trans.Resource
import Control.Monad.IO.Class
import Data.Aeson
import Data.Aeson.TH
import Data.Bson.Generic
import GHC.Generics
import Network.Wai hiding(Response)
import Network.Wai.Handler.Warp
import Network.Wai.Logger
import Servant
import Servant.API
import Servant.Client
import System.IO
import System.Directory
import System.Environment (getArgs, getProgName, lookupEnv)
import System.Log.Formatter
import System.Log.Handler (setFormatter)
import System.Log.Handler.Simple
import System.Log.Handler.Syslog
import System.Log.Logger
import Data.Bson.Generic
import qualified Data.List as DL
import Data.Maybe (catMaybes)
import Data.Text (pack, unpack)
import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Time.Format (defaultTimeLocale, formatTime)
import Database.MongoDB
import Control.Monad (when)
import Network.HTTP.Client (newManager, defaultManagerSettings)
manager = newManager defaultManagerSettings
data File = File {
fileName :: FilePath,
fileContent :: String
} deriving (Eq, Show, Generic)
instance ToJSON File
instance FromJSON File
data Response = Response{
response :: String
} deriving (Eq, Show, Generic)
instance ToJSON Response
instance FromJSON Response
data FileServer = FileServer{
id :: String,
fsaddress :: String,
fsport :: String
} deriving (Eq, Show, Generic)
instance ToJSON FileServer
instance FromJSON FileServer
instance ToBSON FileServer
instance FromBSON FileServer
data FileMapping = FileMapping{
fmfileName :: String,
fmaddress :: String,
fmport :: String
} deriving (Eq, Show, Generic)
instance ToJSON FileServer
instance FromJSON FileServer
instance ToBSON FileServer
instance FromBSON FileServer
type ApiHandler = ExceptT ServantErr IO
serverport :: String
serverport = "7008"
serverhost :: String
serverhost = "localhost"
type DirectoryApi =
"join" :> ReqBody '[JSON] FileServer :> Post '[JSON] Response :<|>
"open" :> Capture "fileName" String :> Get '[JSON] File :<|>
"close" :> ReqBody '[JSON] File :> Post '[JSON] Response
type FileApi =
"files" :> Get '[JSON] [FilePath] :<|>
"download" :> Capture "fileName" String :> Get '[JSON] File :<|>
"upload" :> ReqBody '[JSON] File :> Post '[JSON] Response -- :<|>
fileApi :: Proxy FileApi
fileApi = Proxy
files:: ClientM [FilePath]
download :: String -> ClientM File
upload :: File -> ClientM Response
files :<|> download :<|> upload = client fileApi
getFilesQuery :: ClientM[FilePath]
getFilesQuery = do
get_files <- files
return(get_files)
downloadQuery :: String -> ClientM File
downloadQuery fname = do
get_download <- download (fname)
return(get_download)
directoryApi :: Proxy DirectoryApi
directoryApi = Proxy
server :: Server DirectoryApi
server =
fsJoin :<|>
DirectoryServer.openFile :<|>
closeFile
directoryApp :: Application
directoryApp = serve directoryApi server
mkApp :: IO()
mkApp = do
run (read (serverport) ::Int) directoryApp
storefs:: FileServer -> Bool
storefs fs@(FileServer key _ _) = liftIO $ do
warnLog $ "Storing file under key " ++ key ++ "."
withMongoDbConnection $ upsert (select ["id" =: key] "FILESERVER_RECORD") $ toBSON fs
return True
storefm :: FileMapping -> Bool
storefm fm@(FileMapping key _ _) = liftIO $ do
warnLog $ "Storing file under key " ++ key ++ "."
withMongoDbConnection $ upsert (select ["id" =: key] "FILEMAPPING_RECORD") $ toBSON fm
return True
getStoreFm :: FileServer -> Bool
getStoreFm fs = do
manager <- newManager defaultManagerSettings
res <- runClientM getFilesQuery (ClientEnv manager (BaseUrl Http (fsaddress fs) (read(fsport fs)) ""))
case res of
Left err -> putStrLn $ "Error: " ++ show err
Right response -> map (storefm (fsaddress fs) (fsport fs)) response
return True
fsJoin :: FileServer -> ApiHandler Response
fsJoin fs = do
bool <- storefs fs
bool2 <- getStoreFm fs
return (Response "Success")
searchFileMappings :: String -> Maybe FileMapping
searchFileMappings key = liftIO $ do
warnLog $ "Searching for value for key: " ++ key
withMongoDbConnection $ do
docs <- find (select ["fmfileName" =: key] "FILEMAPPING_RECORD") >>= drainCursor
file <- head $ DL.map (\ b -> fromBSON b :: Maybe FileMapping) docs
return file
openFileQuery :: String -> FileMapping -> File
openFileQuery key fm = do
manager <- newManager defaultManagerSettings
res <- runClientM (downloadQuery key) (ClientEnv manager (BaseUrl Http (fmaddress fm) (read(fmport fm)) ""))
case res of
Left err -> putStrLn $ "Error: " ++ show err
Right response -> return response
openFile :: String -> ApiHandler File
openFile key = do
fm <- searchFileMappings key
case fm of
Nothing -> putStrLn $ "Error: " ++ "File not found"
Just filemapping -> do
file <- openFileQuery key filemapping
return file
-- | Logging stuff
iso8601 :: UTCTime -> String
iso8601 = formatTime defaultTimeLocale "%FT%T%q%z"
-- global loggin functions
debugLog, warnLog, errorLog :: String -> IO ()
debugLog = doLog debugM
warnLog = doLog warningM
errorLog = doLog errorM
noticeLog = doLog noticeM
doLog f s = getProgName >>= \ p -> do
t <- getCurrentTime
f p $ (iso8601 t) ++ " " ++ s
withLogging act = withStdoutLogger $ \aplogger -> do
lname <- getProgName
llevel <- logLevel
updateGlobalLogger lname
(setLevel $ case llevel of
"WARNING" -> WARNING
"ERROR" -> ERROR
_ -> DEBUG)
act aplogger
-- | Mongodb helpers...
-- | helper to open connection to mongo database and run action
-- generally run as follows:
-- withMongoDbConnection $ do ...
--
withMongoDbConnection :: Action IO a -> IO a
withMongoDbConnection act = do
ip <- mongoDbIp
port <- mongoDbPort
database <- mongoDbDatabase
pipe <- connect (host ip)
ret <- runResourceT $ liftIO $ access pipe master (pack database) act
Database.MongoDB.close pipe
return ret
-- | helper method to ensure we force extraction of all results
-- note how it is defined recursively - meaning that draincursor' calls itself.
-- the purpose is to iterate through all documents returned if the connection is
-- returning the documents in batch mode, meaning in batches of retruned results with more
-- to come on each call. The function recurses until there are no results left, building an
-- array of returned [Document]
drainCursor :: Cursor -> Action IO [Document]
drainCursor cur = drainCursor' cur []
where
drainCursor' cur res = do
batch <- nextBatch cur
if null batch
then return res
else drainCursor' cur (res ++ batch)
-- | Environment variable functions, that return the environment variable if set, or
-- default values if not set.
-- | The IP address of the mongoDB database that devnostics-rest uses to store and access data
mongoDbIp :: IO String
mongoDbIp = defEnv "MONGODB_IP" Prelude.id "database" True
-- | The port number of the mongoDB database that devnostics-rest uses to store and access data
mongoDbPort :: IO Integer
mongoDbPort = defEnv "MONGODB_PORT" read 27017 False -- 27017 is the default mongodb port
-- | The name of the mongoDB database that devnostics-rest uses to store and access data
mongoDbDatabase :: IO String
mongoDbDatabase = defEnv "MONGODB_DATABASE" Prelude.id "USEHASKELLDB" True
-- | Determines log reporting level. Set to "DEBUG", "WARNING" or "ERROR" as preferred. Loggin is
-- provided by the hslogger library.
logLevel :: IO String
logLevel = defEnv "LOG_LEVEL" Prelude.id "DEBUG" True
-- | Helper function to simplify the setting of environment variables
-- function that looks up environment variable and returns the result of running funtion fn over it
-- or if the environment variable does not exist, returns the value def. The function will optionally log a
-- warning based on Boolean tag
defEnv :: Show a
=> String -- Environment Variable name
-> (String -> a) -- function to process variable string (set as 'id' if not needed)
-> a -- default value to use if environment variable is not set
-> Bool -- True if we should warn if environment variable is not set
-> IO a
defEnv env fn def doWarn = lookupEnv env >>= \ e -> case e of
Just s -> return $ fn s
Nothing -> do
when doWarn (doLog warningM $ "Environment variable: " ++ env ++
" is not set. Defaulting to " ++ (show def))
return def
| Garygunn94/DFS | DirectoryServer/.stack-work/intero/intero16528ftM.hs | bsd-3-clause | 9,535 | 40 | 18 | 2,385 | 2,282 | 1,181 | 1,101 | 210 | 3 |
{-# LANGUAGE OverloadedStrings #-}
-- |
module Main where
import Cache
import Commands
import qualified System.Process as P
import Options.Applicative
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Shelly (shelly, Sh, fromText, FilePath)
import Data.Monoid (mconcat)
import Prelude hiding (FilePath)
main :: IO ()
main = execParser hscacheInfo >>= shelly . hscache
hscache :: Options -> Sh ()
hscache (Options ghc (Freeze args)) = freeze ghc args
hscache (Options _ (AddSource dirs)) = addSourceCmd dirs
hscache (Options _ Build) = build
hscache (Options _ Install) = install
hscache (Options _ (Exec args)) = exec args
hscache (Options _ Repl) = repl
hscache (Options _ Shell) = nix_shell
hscacheInfo :: ParserInfo Options
hscacheInfo = info (helper <*> optionsParser)
(fullDesc
<> progDesc "Fast sandboxed Haskell builds. Sandboxed builds of Haskell packages, using Cabal's dependency solver. Cache built packages indexed by all their transitive dependencies."
<> header "hscache - fast sandboxed Haskell builds")
data Options = Options
GHC -- ^ GHC version, as Nix attribute
Command
data Command
= Freeze [T.Text]
| AddSource [FilePath]
| Build
| Install
| Exec [T.Text]
| Repl
| Shell
optionsParser :: Parser Options
optionsParser = Options <$> ghcParser <*> commandParser
commandParser :: Parser Command
commandParser =
subparser $ mconcat
[ command "freeze" $
info (Freeze <$> many (argument text (metavar "CONSTRAINTS..."))) $
progDesc "Pick versions for all dependencies."
, command "add-source" $
info (AddSource <$> some (argument filepath (metavar "DIRS..."))) $
progDesc "Make one or more local package available."
, command "build" $
info (pure Build) $
progDesc "compile all configured components"
, command "install" $
info (pure Install) $
progDesc "install executables on user path"
, command "exec" $
info (Exec <$> some (argument text (metavar "COMMANDS..."))) $
progDesc "Give a command access to the sandbox package repository."
, command "repl" $
info (pure Repl) $
progDesc "Open GHCi with access to sandbox packages."
, command "shell" $
(info (pure Shell) $
progDesc "Launch a sub-shell with access to sandbox packages.")
]
ghcParser :: Parser GHC
ghcParser = GHC . T.pack <$> strOption (
short 'w'
<> long "with-ghc"
<> long "with-compiler"
<> help "Nix attr for the GHC version: eg, ghc7101"
<> metavar "GHC"
<> showDefault
<> value "ghc784"
)
filepath :: ReadM FilePath
filepath = fromText . T.pack <$> str
text :: ReadM T.Text
text = T.pack <$> str
| bergey/hscache | src/Main.hs | bsd-3-clause | 2,821 | 0 | 17 | 704 | 752 | 388 | 364 | 76 | 1 |
module Problem37 where
import Prime
main :: IO ()
main = print . sum . take 11 . filter truncablePrime $ [11 ..]
truncablePrime :: Int -> Bool
truncablePrime n
| n < 10 = isPrimeNaive n
| otherwise = isPrimeNaive n && leftTruncablePrime n && rightTruncablePrime n
leftTruncablePrime :: Int -> Bool
leftTruncablePrime n
| n < 10 = isPrimeNaive n
| otherwise = isPrimeNaive n && (leftTruncablePrime . read . tail . show $ n)
rightTruncablePrime :: Int -> Bool
rightTruncablePrime n
| n < 10 = isPrimeNaive n
| otherwise = isPrimeNaive n && rightTruncablePrime (n `div` 10)
| adityagupta1089/Project-Euler-Haskell | src/problems/Problem37.hs | bsd-3-clause | 609 | 0 | 11 | 139 | 227 | 110 | 117 | 16 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Control.Monad (mzero)
import Data.Aeson
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Data.Char (chr)
import qualified Data.Map as M
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Network.HTTP.Conduit hiding (Request, queryString)
import Network.HTTP.Types (Query, status200)
import Network.Wai
import Network.Wai.Handler.Warp (run)
import URI.ByteString.QQ
import URI.ByteString (serializeURIRef')
import Keys (fitbitKey)
import Network.OAuth.OAuth2
------------------------------------------------------------------------------
data FitbitUser = FitbitUser
{ userId :: Text
, userName :: Text
, userAge :: Int
} deriving (Show, Eq)
instance FromJSON FitbitUser where
parseJSON (Object o) =
FitbitUser
<$> ((o .: "user") >>= (.: "encodedId"))
<*> ((o .: "user") >>= (.: "fullName"))
<*> ((o .: "user") >>= (.: "age"))
parseJSON _ = mzero
instance ToJSON FitbitUser where
toJSON (FitbitUser fid name age) =
object [ "id" .= fid
, "name" .= name
, "age" .= age
]
------------------------------------------------------------------------------
main :: IO ()
main = do
print $ serializeURIRef' $ appendQueryParams [("state", state), ("scope", "profile")] $ authorizationUrl fitbitKey
putStrLn "visit the url to continue"
run 9988 application
state :: B.ByteString
state = "testFitbitApi"
application :: Application
application request respond = do
response <- handleRequest requestPath request
respond $ responseLBS status200 [("Content-Type", "text/plain")] response
where
requestPath = T.intercalate "/" $ pathInfo request
handleRequest :: Text -> Request -> IO BL.ByteString
handleRequest "favicon.ico" _ = return ""
handleRequest _ request = do
mgr <- newManager tlsManagerSettings
token <- getApiToken mgr $ getApiCode request
print token
user <- getApiUser mgr (accessToken token)
print user
return $ encode user
getApiCode :: Request -> ExchangeToken
getApiCode request =
case M.lookup "code" queryMap of
Just code -> ExchangeToken $ T.decodeUtf8 $ code
Nothing -> error "request doesn't include code"
where
queryMap = convertQueryToMap $ queryString request
getApiToken :: Manager -> ExchangeToken -> IO (OAuth2Token)
getApiToken mgr code = do
result <- doJSONPostRequest mgr fitbitKey url $ body ++ [("state", state)]
case result of
Right token -> return token
Left e -> error $ lazyBSToString e
where
(url, body) = accessTokenUrl fitbitKey code
getApiUser :: Manager -> AccessToken -> IO (FitbitUser)
getApiUser mgr token = do
result <- authGetJSON mgr token [uri|https://api.fitbit.com/1/user/-/profile.json|]
case result of
Right user -> return user
Left e -> error $ lazyBSToString e
convertQueryToMap :: Query -> M.Map B.ByteString B.ByteString
convertQueryToMap query =
M.fromList $ map normalize query
where
normalize (k, Just v) = (k, v)
normalize (k, Nothing) = (k, B.empty)
lazyBSToString :: BL.ByteString -> String
lazyBSToString s = map (chr . fromIntegral) (BL.unpack s)
| reactormonk/hoauth2 | example/Fitbit/test.hs | bsd-3-clause | 3,662 | 0 | 12 | 969 | 994 | 531 | 463 | 85 | 2 |
{-# LANGUAGE BangPatterns, ScopedTypeVariables, RecordWildCards #-}
-- |
-- Module : AI.HNN.Recurrent.Network
-- Copyright : (c) 2012 Gatlin Johnson
-- License : LGPL
-- Maintainer : rokenrol@gmail.com
-- Stability : experimental
-- Portability : GHC
--
-- An implementation of recurrent neural networks in pure Haskell.
--
-- A network is an adjacency matrix of connection weights, the number of
-- neurons, the number of inputs, and the threshold values for each neuron.
--
-- E.g.,
--
-- > module Main where
-- >
-- > import AI.HNN.Recurrent.Network
-- >
-- > main = do
-- > let numNeurons = 3
-- > numInputs = 1
-- > thresholds = replicate numNeurons 0.5
-- > inputs = [[0.38], [0.75]]
-- > adj = [ 0.0, 0.0, 0.0,
-- > 0.9, 0.8, 0.0,
-- > 0.0, 0.1, 0.0 ]
-- > n <- createNetwork numNeurons numInputs adj thresholds :: IO (Network Double)
-- > output <- evalNet n inputs sigmoid
-- > putStrLn $ "Output: " ++ (show output)
--
-- This creates a network with three neurons (one of which is an input), an
-- arbitrary connection / weight matrix, and arbitrary thresholds for each neuron.
-- Then, we evaluate the network with an arbitrary input.
--
-- For the purposes of this library, the outputs returned are the values of all
-- the neurons except the inputs. Conceptually, in a recurrent net *any*
-- non-input neuron can be treated as an output, so we let you decide which
-- ones matter.
module AI.HNN.Recurrent.Network (
-- * Network type
Network, createNetwork,
weights, size, nInputs, thresh,
-- * Evaluation functions
computeStep, evalNet,
-- * Misc
sigmoid
) where
import System.Random.MWC
import Control.Monad
import Numeric.LinearAlgebra hiding (i)
import Foreign.Storable as F
-- | Our recurrent neural network
data Network a = Network
{ weights :: !(Matrix a)
, size :: {-# UNPACK #-} !Int
, nInputs :: {-# UNPACK #-} !Int
, thresh :: !(Vector a)
} deriving Show
-- | Creates a network with an adjacency matrix of your choosing, specified as
-- an unboxed vector. You also must supply a vector of threshold values.
createNetwork :: (Variate a, Fractional a, Storable a) =>
Int -- ^ number of total neurons neurons (input and otherwise)
-> Int -- ^ number of inputs
-> [a] -- ^ flat weight matrix
-> [a] -- ^ threshold (bias) values for each neuron
-> IO (Network a) -- ^ a new network
createNetwork n m matrix thresh = return $!
Network ( (n><n) matrix ) n m (n |> thresh)
-- | Evaluates a network with the specified function and list of inputs
-- precisely one time step. This is used by `evalNet` which is probably a
-- more convenient interface for client applications.
computeStep :: (Variate a, Num a, F.Storable a, Product a) =>
Network a -- ^ Network to evaluate input
-> Vector a -- ^ vector of pre-existing state
-> (a -> a) -- ^ activation function
-> Vector a -- ^ list of inputs
-> Vector a -- ^ new state vector
computeStep (Network{..}) state activation input =
mapVector activation $! zipVectorWith (-) (weights <> prefixed) thresh
where
prefixed = Numeric.LinearAlgebra.vjoin
[ input, (subVector nInputs (size-nInputs) state) ]
{-# INLINE prefixed #-}
-- | Iterates over a list of input vectors in sequence and computes one time
-- step for each.
evalNet :: (Num a, Variate a, Fractional a, Product a) =>
Network a -- ^ Network to evaluate inputs
-> [[a]] -- ^ list of input lists
-> (a -> a) -- ^ activation function
-> IO (Vector a) -- ^ output state vector
evalNet n@(Network{..}) inputs activation = do
s <- foldM (\x -> computeStepM n x activation) state inputsV
return $! subVector nInputs (size-nInputs) s
where
state = fromList $ replicate size 0.0
{-# INLINE state #-}
computeStepM _ s a i = return $ computeStep n s a i
{-# INLINE computeStepM #-}
inputsV = map (fromList) inputs
{-# INLINE inputsV #-}
-- | It's a simple, differentiable sigmoid function.
sigmoid :: Floating a => a -> a
sigmoid !x = 1 / (1 + exp (-x))
{-# INLINE sigmoid #-}
| fffej/hnn | AI/HNN/Recurrent/Network.hs | bsd-3-clause | 4,375 | 0 | 12 | 1,185 | 690 | 402 | 288 | 56 | 1 |
{-
foo
bar
a) foo
foo
b) bar
bar
baa
-}
{-
foo
bar
* @foo
* @bar
baa
-}
{-
foo
bar
> foo
> bar
baa
-}
| itchyny/vim-haskell-indent | test/comment/list.out.hs | mit | 126 | 0 | 2 | 53 | 5 | 4 | 1 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- Module: Gpg.EditKey
--
-- Edit keys with Gpg's interactive mode
module Gpg.EditKey where
import Control.Monad
import qualified Control.Exception as Ex
import Control.Applicative
import qualified Data.Text.Encoding as Text
import Control.Monad.Trans.Free
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.IORef
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import System.Posix
import Foreign.Ptr
import Control.Monad.Trans
import System.IO
import Bindings
import Gpg.Basic
fdWrite' :: Fd -> ByteString -> IO ByteCount
fdWrite' fd bs = BS.useAsCStringLen bs $ \(ptr, len) ->
fdWriteBuf fd (castPtr ptr) (fromIntegral len)
runEditAction :: Ctx -> Key -> GpgM () -> IO ByteString
runEditAction ctx key action = do
ref <- newIORef action
editKey ctx key $ cb ref
where
cb :: IORef (GpgM ()) -> EditCallback
cb _ StatusGotIt "" fd = fdWrite' fd "\n" >> return noError
cb ref sc ln fd@(Fd fdInt) = do
GpgM st <- readIORef ref
go =<< runFreeT st
where
go (Pure ()) = return $ Error ErrUser1 ErrSourceUser1 ""
go (Free (GpgError e)) = Ex.throwIO (MethodError e)
go (Free (Send txt cont)) = do
writeIORef ref (GpgM cont)
case (fdInt, txt) of
(-1, "") -> return noError
(-1, _) -> return $ Error ErrUser2 ErrSourceUser1 ""
_ -> fdWrite' fd (Text.encodeUtf8 txt <> "\n")
>> return noError
go (Free (GetState f)) = go =<< runFreeT (f sc ln)
data RevocationReason = NoReason
| Compromised
| Superseeded
| NoLongerUsed
deriving (Eq, Show, Enum)
-- | Revoke a key
revoke :: Ctx -> Key -> RevocationReason -> Text -> IO ByteString
revoke ctx key reason reasonText = runEditAction ctx key $ do
expectAndSend (StatusGetLine, "keyedit.prompt") "revkey"
expectAndSend (StatusGetBool, "keyedit.revoke.subkey.okay") "y"
let reasonCode = Text.pack . show $ fromEnum reason
expectAndSend (StatusGetLine, "ask_revocation_reason.code") reasonCode
forM_ (Text.lines reasonText) $ \line -> do
expect StatusGetLine "ask_revocation_reason.text"
send line
expectAndSend (StatusGetLine, "ask_revocation_reason.text") ""
expectAndSend (StatusGetBool, "ask_revocation_reason.okay") "y"
getPassphrase
quit
liftIO . print =<< getState
return ()
| Philonous/pontarius-gpg | src/Gpg/EditKey.hs | mit | 2,786 | 0 | 19 | 787 | 800 | 413 | 387 | 64 | 7 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
module Qi.Program.SQS.Lang where
import Control.Monad.Freer
import Data.Aeson (FromJSON, ToJSON)
import qualified Data.ByteString.Lazy as LBS
import Network.AWS.SQS
import Protolude
import Qi.AWS.SQS
import Qi.Config.AWS.SQS
import Qi.Config.Identifier
import Qi.Core.Curry
import Qi.Program.Gen.Lang
data SqsEff r where
SendSqsMessage
:: ToJSON a
=> SqsQueueId
-> a
-> SqsEff ()
ReceiveSqsMessage
:: FromJSON a
=> SqsQueueId
-> SqsEff [(a, ReceiptHandle)]
DeleteSqsMessage
:: SqsQueueId
-> ReceiptHandle
-> SqsEff ()
sendSqsMessage
:: (Member SqsEff effs, ToJSON a)
=> SqsQueueId
-> a
-> Eff effs ()
sendSqsMessage = send .: SendSqsMessage
receiveSqsMessage
:: (Member SqsEff effs, FromJSON a)
=> SqsQueueId
-> Eff effs [(a, ReceiptHandle)] -- the json body and the receipt handle
receiveSqsMessage = send . ReceiveSqsMessage
deleteSqsMessage
:: (Member SqsEff effs)
=> SqsQueueId
-> ReceiptHandle
-> Eff effs ()
deleteSqsMessage = send .: DeleteSqsMessage
| ababkin/qmuli | library/Qi/Program/SQS/Lang.hs | mit | 1,453 | 0 | 9 | 384 | 298 | 175 | 123 | 51 | 1 |
-- | Specification for Pos.Chain.Ssc.GodTossing.Toss.Pure
module Test.Pos.Ssc.Toss.PureSpec
( spec
) where
import Universum
import qualified Crypto.Random as Rand
import Data.Default (def)
import Test.Hspec (Spec, describe)
import Test.Hspec.QuickCheck (modifyMaxSuccess, prop)
import Test.QuickCheck (Arbitrary (..), Gen, Property, forAll, listOf,
suchThat, (===))
import Test.QuickCheck.Arbitrary.Generic (genericArbitrary,
genericShrink)
import Pos.Chain.Ssc (InnerSharesMap, Opening, SignedCommitment,
VssCertificate (..))
import qualified Pos.Chain.Ssc as Toss
import Pos.Core (EpochOrSlot, StakeholderId, addressHash)
import Test.Pos.Core.Arbitrary ()
import Test.Pos.Infra.Arbitrary.Ssc ()
spec :: Spec
spec = describe "Toss" $ do
let smaller n = modifyMaxSuccess (const n)
describe "PureToss" $ smaller 30 $ do
prop "Adding and deleting a signed commitment in the 'PureToss' monad is the\
\ same as doing nothing"
putDelCommitment
prop "Adding and deleting an opening in the 'PureToss' monad is the same as doing\
\ nothing"
putDelOpening
prop "Adding and deleting a share in the 'PureToss' monad is the same as doing\
\ nothing"
putDelShare
data TossAction
= PutCommitment SignedCommitment
| PutOpening StakeholderId Opening
| PutShares StakeholderId InnerSharesMap
| PutCertificate VssCertificate
| ResetCO
| ResetShares
| DelCommitment StakeholderId
| DelOpening StakeholderId
| DelShares StakeholderId
| SetEpochOrSlot EpochOrSlot
deriving (Show, Eq, Generic)
instance Arbitrary TossAction where
arbitrary = genericArbitrary
shrink = genericShrink
actionToMonad :: Toss.MonadToss m => TossAction -> m ()
actionToMonad (PutCommitment sc) = Toss.putCommitment sc
actionToMonad (PutOpening sid o) = Toss.putOpening sid o
actionToMonad (PutShares sid ism) = Toss.putShares sid ism
actionToMonad (PutCertificate v) = Toss.putCertificate v
actionToMonad ResetCO = Toss.resetCO
actionToMonad ResetShares = Toss.resetShares
actionToMonad (DelCommitment sid) = Toss.delCommitment sid
actionToMonad (DelOpening sid) = Toss.delOpening sid
actionToMonad (DelShares sid) = Toss.delShares sid
actionToMonad (SetEpochOrSlot eos) = Toss.setEpochOrSlot eos
emptyTossSt :: Toss.SscGlobalState
emptyTossSt = def
perform :: [TossAction] -> Toss.PureToss ()
perform = mapM_ actionToMonad
-- | Type synonym used for convenience. This quintuple is used to pass the randomness
-- needed to run 'PureToss' actions to the testing property.
type TossTestInfo = (Word64, Word64, Word64, Word64, Word64)
-- | Operational equivalence operator in the 'PureToss' monad. To be used when
-- equivalence between two sequences of actions in 'PureToss' is to be tested/proved.
(==^)
:: [TossAction]
-> [TossAction]
-> Gen TossAction
-> TossTestInfo
-> Property
t1 ==^ t2 = \prefixGen ttInfo ->
forAll ((listOf prefixGen) :: Gen [TossAction]) $ \prefix ->
forAll (arbitrary :: Gen [TossAction]) $ \suffix ->
let applyAction x =
view _2 .
fst . Rand.withDRG (Rand.drgNewTest ttInfo) .
Toss.runPureToss emptyTossSt $ (perform $ prefix ++ x ++ suffix)
in applyAction t1 === applyAction t2
{- A note on the following tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The reason these tests have to pass a custom generator for the prefix of the action list
to '(==^)' is that in each case, there is a particular sequence of actions for which
the property does not hold. Using one of the following tests as an example:
Let 'o, o´ :: Opening' such that 'o /= o´'. This sequence of actions
in the 'PureToss' monad:
[PutOpening sid o´, PutOpening sid o, DelOpening sid]
is not, in operational semantics terms, equal to the sequence
[PutOpening sid o´]
It is instead equivalent to
[]
Because these actions are performed from left to right, performing an insertion with the
same key several times without deleting it in between those insertions means only the
last insertion actually matters for these tests.
As such, prefixes with an insertion with the same key as the action being tested in the
property will cause it to fail.
-}
putDelCommitment :: SignedCommitment -> TossTestInfo -> Property
putDelCommitment sc =
let actionPrefixGen = arbitrary `suchThat` (\case
PutCommitment sc' -> sc ^. _1 /= sc'^. _1
_ -> True)
in ([PutCommitment sc, DelCommitment $ addressHash $ sc ^. _1] ==^ []) actionPrefixGen
putDelOpening
:: StakeholderId
-> Opening
-> TossTestInfo
-> Property
putDelOpening sid o =
let actionPrefixGen = arbitrary `suchThat` (\case
PutOpening sid' _ -> sid /= sid'
_ -> True)
in ([PutOpening sid o, DelOpening sid] ==^ []) actionPrefixGen
putDelShare
:: StakeholderId
-> InnerSharesMap
-> TossTestInfo
-> Property
putDelShare sid ism =
let actionPrefixGen = arbitrary `suchThat` (\case
PutShares sid' _ -> sid' /= sid
_ -> True)
in ([PutShares sid ism, DelShares sid] ==^ []) actionPrefixGen
| input-output-hk/pos-haskell-prototype | lib/test/Test/Pos/Ssc/Toss/PureSpec.hs | mit | 5,450 | 0 | 20 | 1,358 | 1,091 | 586 | 505 | -1 | -1 |
--ProbabFP.hs
--Author: Chad Myles
--Date: 9/26/16
module Probab (
Dist,
unit,
uniformDist,
weightedDist,
toList,
mergeEqual,
possibilities,
probabilityOf,
adjoin,
distFil,
transform,
combine,
duplicate
) where
import Data.List
data Dist a = Dist [(a, Float)]
deriving( Show)
instance Functor Dist where
fmap f (Dist xs) = Dist (map (\(x,p) -> (f x, p)) xs)
--TODO: make sure sum of Floats = 1 and none are negative
--
-- Public Interface
--
unit :: a -> Dist a
uniformDist :: [a] -> Dist a
weightedDist :: [(a, Float)] -> Dist a
toList :: Dist a -> [(a, Float)]
mergeEqual :: Eq a => Dist a -> Dist a
possibilities :: Eq a => Dist a -> [a]
probabilityOf :: Eq a => Dist a -> (a -> Bool) -> Float
adjoin :: (a -> Dist b) -> Dist a -> Dist (a,b)
distFil :: (a -> Bool) -> Dist a -> Dist a
transform :: (a -> Dist b) -> Dist a-> Dist b
combine :: Dist a -> Dist b -> Dist (a, b)
duplicate :: Integral a => a -> Dist b -> Dist [b]
--
-- Implementation of Public Interface
--
--unit :: a -> Dist a
unit x = Dist [(x,1.0)]
--uniformDist :: [a] -> Dist a
uniformDist xs = Dist (map (\ x -> (x, (1.0 / len))) xs)
where len = fromIntegral (length xs)
--weightedDist :: [(a, Float)] -> Dist a
weightedDist xs = Dist xs
--toList :: Dist a -> [(a, Float)]
toList (Dist valList ) = valList
--mergeEqual :: Eq a => [(a, Float)] -> [(a, Float)]
mergeEqual xs =
let distinct = possibilities xs
in weightedDist (map (\y -> (y, (foldl (\acc (b,c) ->if (b == y)
then (acc + c)
else acc) 0.0 (toList xs)))) distinct)
--possibilites :: Eq a => Dist a -> [a]
possibilities xs =
let firsts = map (\(a,b) -> a) (toList xs)
in nub firsts
--probabilityOf :: Eq a => [(a, Float)] -> a -> Float
probabilityOf xs f =
foldl (\acc (a, b) -> if (f a)
then (acc + b)
else (acc)) 0.0 (toList (mergeEqual xs))
--adjoin :: (a -> Dist b) -> Dist a -> Dist (a,b)
adjoin f (Dist xs) =
let wrapped = map (\(k, p) ->
let (Dist res) = f k
in map (\(k',p') -> ((k,k'), p*p'))
res)
xs
in Dist (concat wrapped)
--distFil :: (a -> Bool) -> Dist a -> Dist a
distFil f xs =
let intermed = filter (\ x -> f (fst x)) (toList xs)
in weightedDist (map (\ (x,y) -> (x, y * (1.0 / totalProb(intermed)))) intermed)
--transform :: (a -> Dist b) -> Dist a -> Dist b
transform f xs =
--create ([(b, Float)], Float) list
let intermed = (map (\(a, b) -> ((toList (f a)), b)) (toList xs))
in weightedDist (concat (map (\(a, b) -> (map (\(c,d) -> (c, b*d)) a)) intermed))
--combine :: Dist a -> Dist b -> Dist (a, b)
combine xs ys = weightedDist (concat (map (\ x -> map (\ y -> ((fst x, fst y), snd x * snd y)) (toList ys)) (toList xs)))
--duplicate :: Dist a -> Int -> Dist [a]
duplicate num xs = if (num == 1)
then weightedDist (map (\(a,b) -> ([a], b)) (toList xs))
else weightedDist (map (\((a,b),c) -> (a:b,c)) (toList (combine xs (duplicate (num-1) xs))))
--
-- Private functions
--
totalProb :: [(a,Float)] -> Float
totalProb xs = foldl (\acc (a,b) -> acc + b) 0.0 xs
| seabornloyalis/probabilistic-haskell | ProbabFP.hs | mit | 3,417 | 0 | 19 | 1,080 | 1,382 | 755 | 627 | 67 | 2 |
-- Functional and recursive function
let fib x = if x < 1 then 0 else (if x < 3 then 1 else (fib(x - 1) + fib(x - 2)))
| MarkWaldron/Challenges | Maths/01-Fibonacci-Sequence/solutions/askl56-fibonacci.hs | gpl-2.0 | 121 | 1 | 14 | 32 | 67 | 36 | 31 | -1 | -1 |
{- |
Module : $Header$
Description : printing Isabelle entities
Copyright : (c) University of Cambridge, Cambridge, England
adaption (c) Till Mossakowski, Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable
Printing functions for Isabelle logic.
-}
module Isabelle.IsaPrint
( showBaseSig
, printIsaTheory
, getAxioms
, printNamedSen
, printTerm
) where
import Isabelle.IsaSign
import Isabelle.IsaConsts
import Isabelle.Translate
import Common.AS_Annotation
import qualified Data.Map as Map
import qualified Data.Set as Set
import Common.Doc hiding (bar)
import Common.DocUtils
import Common.Utils (number)
import Data.Char
import Data.List
import Data.Maybe (isNothing, catMaybes)
printIsaTheory :: String -> Sign -> [Named Sentence] -> Doc
printIsaTheory tn sign sens = let
b = baseSig sign
bs = showBaseSig b
ld = "$HETS_ISABELLE_LIB/"
mlFileUse = text mlFileS <+> doubleQuotes (text $ ld ++ "prelude.ML")
in text theoryS <+> text tn
$+$ text importsS <+> fsep (case b of
Custom_thy -> []
_ -> if case b of
Main_thy -> False
HOLCF_thy -> False
Custom_thy -> True
_ -> True then [doubleQuotes $ text $ ld ++ bs] else [text bs]
++ map (doubleQuotes . text) (imports sign))
$+$ text beginS
$++$ mlFileUse
$++$ printTheoryBody sign sens
$++$ text endS
printTheoryBody :: Sign -> [Named Sentence] -> Doc
printTheoryBody sig sens =
let (sens', recFuns) = findTypesForRecFuns sens (constTab sig)
sig' = sig { constTab =
Map.filterWithKey (\ k _ -> notElem (new k) recFuns) (constTab sig) }
in callSetup "initialize" (brackets $ sepByCommas
$ map (text . show . Quote . senAttr)
$ filter (\ s -> not (isConstDef s || isRecDef s || isInstance s)
&& senAttr s /= "") sens')
$++$ printSign sig'
$++$ printNamedSentences sens'
$++$ printMonSign sig'
findTypesForRecFuns :: [Named Sentence] -> ConstTab
-> ([Named Sentence], [String])
findTypesForRecFuns ns ctab =
let (sens, recFuns') = unzip $ map (\ sen ->
let (sen', recFns') =
case sentence sen of
RecDef kw cName cType tm ->
(case Map.toList $
Map.filterWithKey (\ k _ -> new k == new cName) ctab of
(_, t) : _ ->
case cType of
Nothing ->
RecDef kw cName (Just t) tm
Just t' ->
if t /= t' then error "recFun: two types given"
else sentence sen
[] -> sentence sen
, Just cName)
_ -> (sentence sen, Nothing)
in (sen {sentence = sen'}, recFns')) ns
in (sens, map new $ catMaybes recFuns')
printNamedSentences :: [Named Sentence] -> Doc
printNamedSentences sens = case sens of
[] -> empty
s : r
| isIsaAxiom s ->
let (axs, rest) = span isAxiom sens in
(if null axs then empty else text axiomatizationS $+$ text whereS)
$+$ vcat (intersperse (text andS) $ map printNamedSen axs)
$++$ vcat (map ( \ a -> text declareS <+> text (senAttr a)
<+> brackets (text simpS))
$ filter ( \ a -> case sentence a of
b@Sentence {} -> isSimp b && senAttr a /= ""
_ -> False) axs)
$++$ printNamedSentences rest
| isConstDef s ->
let (defs_, rest) = span isConstDef sens in
text defsS $+$ vsep (map printNamedSen defs_)
$++$ printNamedSentences rest
| otherwise ->
printNamedSen s $++$ (case senAttr s of
n | n == "" || isRecDef s -> empty
| otherwise -> callSetup "record" (text $ show $ Quote n))
$++$ printNamedSentences r
callSetup :: String -> Doc -> Doc
callSetup fun args =
text "setup" <+> doubleQuotes (fsep [text ("Header." ++ fun), args])
data QuotedString = Quote String
instance Show QuotedString where
show (Quote s) = init . tail . show $ show s
getAxioms :: [Named Sentence] -> ([Named Sentence], [Named Sentence])
getAxioms = partition isIsaAxiom
isIsaAxiom :: Named Sentence -> Bool
isIsaAxiom s = case sentence s of
Sentence {} -> isAxiom s
_ -> False
isInstance :: Named Sentence -> Bool
isInstance s = case sentence s of
Instance {} -> True
_ -> False
isConstDef :: Named Sentence -> Bool
isConstDef s = case sentence s of
ConstDef {} -> True
_ -> False
isRecDef :: Named Sentence -> Bool
isRecDef s = case sentence s of
RecDef {} -> True
_ -> False
-- --------------------- Printing functions -----------------------------
showBaseSig :: BaseSig -> String
showBaseSig = takeWhile (/= '_') . show
printClass :: IsaClass -> Doc
printClass (IsaClass x) = text x
printSort :: Sort -> Doc
printSort = printSortAux False
printSortAux :: Bool -> Sort -> Doc
printSortAux b l = case l of
[c] -> printClass c
_ -> (if b then doubleQuotes else id)
. braces . hcat . punctuate comma $ map printClass l
data SynFlag = Quoted | Unquoted | Null
doubleColon :: Doc
doubleColon = text "::"
isaEquals :: Doc
isaEquals = text "=="
bar :: [Doc] -> [Doc]
bar = punctuate $ space <> text "|"
printType :: Typ -> Doc
printType = printTyp Unquoted
printTyp :: SynFlag -> Typ -> Doc
printTyp a = fst . printTypeAux a
printTypeAux :: SynFlag -> Typ -> (Doc, Int)
printTypeAux a t = case t of
TFree v s -> (let
d = text $ if isPrefixOf "\'" v || isPrefixOf "?\'" v
then v else '\'' : v
c = printSort s
in if null s then d else case a of
Quoted -> d <> doubleColon <> if null
$ tail s then c else doubleQuotes c
Unquoted -> d <> doubleColon <> c
Null -> d, 1000)
TVar iv s -> printTypeAux a $ TFree (unindexed iv) s
Type name _ args -> case args of
[t1, t2] | elem name [prodS, sProdS, funS, cFunS, lFunS, sSumS] ->
printTypeOp a name t1 t2
_ -> ((case args of
[] -> empty
[arg] -> let (d, i) = printTypeAux a arg in
if i < 1000 then parens d else d
_ -> parens $ hsep $ punctuate comma $
map (fst . printTypeAux a) args)
<+> text name, 1000)
printTypeOp :: SynFlag -> TName -> Typ -> Typ -> (Doc, Int)
printTypeOp x name r1 r2 =
let (d1, i1) = printTypeAux x r1
(d2, i2) = printTypeAux x r2
(l, r) = Map.findWithDefault (0 :: Int, 0 :: Int)
name $ Map.fromList
[ (funS, (1, 0))
, (cFunS, (1, 0))
, (lFunS, (1, 0))
, (sSumS, (11, 10))
, (prodS, (21, 20))
, (sProdS, (21, 20))
, (lProdS, (21, 20))
]
d3 = if i1 < l then parens d1 else d1
d4 = if i2 < r then parens d2 else d2
in (d3 <+> text name <+> d4, r)
andDocs :: [Doc] -> Doc
andDocs = vcat . prepPunctuate (text andS <> space)
-- | printing a named sentence
printNamedSen :: Named Sentence -> Doc
printNamedSen ns =
let s = sentence ns
lab = senAttr ns
b = isAxiom ns
d = printSentence s
in case s of
TypeDef {} -> d
RecDef {} -> d
Lemmas {} -> d
Instance {} -> d
Locale {} -> d
Class {} -> d
Datatypes _ -> d
Consts _ -> d
TypeSynonym {} -> d
Axioms _ -> d
Lemma {} -> d
Definition {} -> d
Fun {} -> d
Instantiation {} -> d
InstanceProof {} -> d
InstanceArity {} -> d
InstanceSubclass {} -> d
Subclass {} -> d
Typedef {} -> d
Defs {} -> d
Fixrec {} -> d
Domains {} -> d
Primrec {} -> d
_ -> let dd = doubleQuotes d in
if isRefute s then text lemmaS <+> text lab <+> colon
<+> dd $+$ text refuteS
else if null lab then dd else fsep [ (case s of
ConstDef {} -> text $ lab ++ "_def"
Sentence {} ->
(if b then empty else text theoremS)
<+> text lab <+> (if b then text "[rule_format]" else
if isSimp s then text "[simp]" else empty)
_ -> error "printNamedSen") <+> colon, dd] $+$ case s of
Sentence {} -> if b then empty else case thmProof s of
Nothing -> text oopsS
Just prf -> pretty prf
_ -> empty
-- | sentence printing
printSentence :: Sentence -> Doc
printSentence s = case s of
TypeDef nt td pr -> text typedefS
<+> printType nt
<+> equals
<+> doubleQuotes (printSetDecl td)
$+$ pretty pr
RecDef kw cName cType xs ->
let preparedEq = map (doubleQuotes . printTerm) xs
preparedEqWithBars =
map (<+> text barS) (init preparedEq) ++ [last preparedEq]
tp = case cType of
Just t -> doubleColon <+> doubleQuotes (printType t)
Nothing -> empty
kw' = case kw of
Just str -> text str
Nothing -> text primrecS
in kw' <+> text (new cName) <+> tp <+> printAlt cName <+> text whereS $+$
vcat preparedEqWithBars
Instance { tName = t, arityArgs = args, arityRes = res, definitions = defs_,
instProof = prf } ->
text instantiationS <+> text t <> doubleColon <> (case args of
[] -> empty
_ -> parens $ hsep $ punctuate comma $ map (printSortAux True) args)
<+> printSortAux True res $+$ text beginS $++$ printDefs defs_ $++$
text instanceS <+> pretty prf $+$ text endS
where printDefs :: [(String, Term)] -> Doc
printDefs defs' = vcat (map printDef defs')
printDef :: (String, Term) -> Doc
printDef (name, def) =
text definitionS <+>
printNamedSen (makeNamed name (ConstDef def))
Sentence { isRefuteAux = b, metaTerm = t } -> printPlainMetaTerm (not b) t
ConstDef t -> printTerm t
Lemmas name lemmas -> if null lemmas
then empty {- only have this lemmas if we have some in
the list -}
else text lemmasS <+> text name <+>
equals <+> sep (map text lemmas)
l@(Locale {}) ->
let h = text "locale" <+> text (show $ localeName l)
parents = Data.List.intersperse (text "+") $
map (text . show) (localeParents l)
(fxs, ass) = printContext $ localeContext l
in printFixesAssumes h parents ass fxs
$+$ printBody (localeBody l)
c@(Class {}) ->
let h = text "class" <+> text (show $ className c)
parents = Data.List.intersperse (text "+") $
map (text . show) (classParents c)
(fxs, ass) = printContext (classContext c)
in printFixesAssumes h parents ass fxs
$+$ printBody (classBody c)
(Datatypes dts) -> if null dts then empty
else text "datatype" <+>
andDocs (map (\ d ->
let vars = map printType $ datatypeTVars d
name = text $ show $ datatypeName d
pretty_cs c =
let cname = case c of
DatatypeNoConstructor {} -> ""
_ -> show $ constructorName c
cname' = if any isSpace cname
then doubleQuotes (text cname)
else text cname
tps = map (doubleQuotes . printType) $
constructorArgs c
in hsep (cname' : tps)
cs = map pretty_cs $ datatypeConstructors d
in hsep vars <+> name <+> text "=" <+>
fsep (bar cs)) dts)
Domains ds -> if null ds then empty
else text "domain" <+>
andDocs (map (\ d ->
let vars = map printType $ domainTVars d
name = text $ show $ domainName d
pretty_cs c =
let cname = text $ show $ domainConstructorName c
args' = map (\ arg ->
(if domainConstructorArgLazy arg
then text "lazy" else empty) <+>
(case domainConstructorArgSel arg of
Just sel -> text (show sel) <+> text "::"
Nothing -> empty) <+> (doubleQuotes . printType)
(domainConstructorArgType arg)) $
domainConstructorArgs c
args = map parens args'
in hsep $ cname : args
cs = map pretty_cs $ domainConstructors d
in hsep vars <+> name <+> text "=" <+>
fsep (bar cs)) ds)
Consts cs -> if null cs then empty
else vsep $ text "consts" :
map (\ (n, _, t) -> text n <+> text "::" <+>
doubleQuotes (printType t)) cs
TypeSynonym n _ vs tp -> hsep $ [text "type_synonym",
text $ show n, text "="] ++ map text vs
++ [doubleQuotes . printType $ tp]
Axioms axs -> if null axs then empty
else vsep $ text "axioms" :
map (\ a -> text (show $ axiomName a) <+>
(if axiomArgs a /= ""
then brackets (text $ axiomArgs a)
else empty) <+> text ":" <+>
doubleQuotes (printTerm $ axiomTerm a)) axs
l@(Lemma {}) ->
let (fxs, ass) = printContext $ lemmaContext l
in text "lemma" <+> (case lemmaTarget l of
Just t -> braces (text "in" <+> text (show t))
Nothing -> empty) <+>
(case (null fxs, null ass, lemmaProps l) of
(True, True, [sh]) -> printProps sh
_ -> vsep (fxs ++ ass ++
[text "shows" <+> andDocs
(map printProps (lemmaProps l))]))
$+$ (case lemmaProof l of
Just p -> text p
Nothing -> empty)
d@(Definition {}) -> fsep [text "definition" <+>
(case definitionTarget d of
Just t -> braces (text "in" <+> text (show t))
Nothing -> empty) <+>
(text (show $ definitionName d) <+> text "::" <+>
doubleQuotes (printType $ definitionType d)), text "where" <+>
doubleQuotes (text (show $ definitionName d) <+> hsep (map printTerm (
definitionVars d)) <+> text "=" <+> printTerm (definitionTerm d))]
f@(Fun {}) -> text "fun" <+> (case funTarget f of
Just t -> braces (text "in" <+> text (show t))
Nothing -> empty) <+> (if funDomintros f then braces (text "domintros")
else empty) <+> vcat (intersperse (text andS) $
map (\ (name, mx, tp, _) -> text name <+> text "::" <+>
doubleQuotes (printType tp) <+> case mx of
Just (Mixfix _ _ s' _) -> doubleQuotes (text s')
_ -> empty) (funEquations f)) <+> text "where" $+$
(let eqs = concatMap (\ (name, _, _, e) -> map (\ e' -> (name, e')) e)
(funEquations f)
eqs' = map (\ (n, (vs, t)) -> doubleQuotes (text n <+>
hsep (map printTerm vs) <+>
text "=" <+> printTerm t)) eqs
in fsep $ bar eqs')
i@(Instantiation {}) -> fsep $ (text "instantiation" <+> text
(instantiationType i) <+> text "::" <+> printArity (instantiationArity i)) :
[printBody (instantiationBody i)]
InstanceProof prf -> text "instance" $+$ text prf
i@(InstanceArity {}) -> text "instance" <+>
hcat (intersperse (text "and") $ map text $ instanceTypes i) <+>
printArity (instanceArity i) $+$ text (instanceProof i)
i@(InstanceSubclass {}) -> text "instance" <+> text (instanceClass i) <+>
text (instanceRel i) <+> text (instanceClass1 i) $+$ text (instanceProof i)
c@(Subclass {}) -> text "subclass" <+> (case subclassTarget c of
Just t -> braces (text "in" <+> text (show t))
Nothing -> empty) <+> text (subclassClass c)
<+> text (subclassProof c)
t@(Typedef {}) -> text "typedef" <+> (case typedefVars t of
[] -> empty
[v] -> printVarWithSort v
vs -> parens $ hsep $ punctuate comma $
map printVarWithSort vs) <+>
text (show $ typedefName t) <+> text "=" <+>
doubleQuotes (printTerm $ typedefTerm t) <+>
(case typedefMorphisms t of
Just (m1, m2) -> text "morphisms" <+> text (show m1)
<+> text (show m2)
Nothing -> empty) $+$ text (typedefProof t)
d@(Defs {}) -> fsep $ (text "defs" <+> (if defsUnchecked d
then text "unchecked"
else empty) <+>
(if defsOverloaded d
then text "overloaded"
else empty))
: map (\ eq' ->
text (show (defEquationName eq')) <+> text ":" <+> doubleQuotes (
text (defEquationConst eq') <+> text "==" <+>
printTerm (defEquationTerm eq')) <+> if null (defEquationArgs eq')
then empty else brackets (text $ defEquationArgs eq')) (defsEquations d)
Fixrec fs ->
let h = map (\ (name, _, tp, _) -> text name <+> text "::" <+>
(doubleQuotes . printType) tp) fs
pretty_fixreceq name eq' =
let unchecked = if fixrecEquationUnchecked eq' then
text "(unchecked)" else empty
premises = fixrecEquationPremises eq'
p s' = punctuate $ space <> text s'
patterns = map (parens . printTerm) $ fixrecEquationPatterns eq'
tm = printTerm $ fixrecEquationTerm eq'
in unchecked <+> doubleQuotes (printTermWithPremises premises
(hsep (p "\\<cdot>" (text name : patterns)) <+> text "=" <+> tm))
body = concatMap (\ (name, _, _, eqs) -> map (pretty_fixreceq name) eqs)
fs
in text "fixrec" <+> andDocs h <+> text "where" $+$ fsep (bar body)
Primrec t eqs ->
let h = map (\ (name, _, tp, _) -> text name <+> text "::" <+>
(doubleQuotes . printType) tp) eqs
pretty_primrec name (vs, tm) = doubleQuotes (text name
<+> hsep (map printTerm vs) <+> text "=" <+> printTerm tm)
body = concatMap (\ (name, _, _, tms) ->
map (pretty_primrec name) tms) eqs
in text "primrec" <+> (case t of
Just t' -> braces (text "in" <+> text (show t'))
Nothing -> empty) <+> andDocs h <+> text "where"
$+$ fsep (bar body)
printTermWithPremises :: [Term] -> Doc -> Doc
printTermWithPremises ps t =
let p s = punctuate $ space <> text s
in fsep $ p "\\<Longrightarrow>" (map printTerm ps ++ [t])
printArity :: (Sort, [Sort]) -> Doc
printArity (sort', sorts) = parens (hsep $ punctuate comma $
map (printSortAux True) sorts) <+> printSort sort'
printVarWithSort :: (String, Sort) -> Doc
printVarWithSort (name, []) = text name
printVarWithSort (name, sort') = text name <+> printSortAux True sort'
printBody :: [Sentence] -> Doc
printBody sens = fsep $ if null sens then []
else [text "begin"] ++ map printSentence sens ++ [text "end"]
printContext :: Ctxt -> ([Doc], [Doc])
printContext ctxt =
let fixes' = map (\ (n, _, tp) -> if n == "" then empty else text n
<+> text "::" <+> (doubleQuotes . printTyp Null) tp)
(fixes ctxt)
assumes' = map (\ (n, tm) -> if n == "" then empty else text n <+> text ":"
<+> (doubleQuotes . printTerm) tm)
(assumes ctxt)
in (fixes', assumes')
printProps :: Props -> Doc
printProps (Props {propsName = n, propsArgs = a, props = p}) =
printMaybe (text . show) n <+> printMaybe text a
<+> (if isNothing n && isNothing a
then empty else text ":") <+>
vcat (map printProp p)
printProp :: Prop -> Doc
printProp (Prop {prop = t, propPats = ts}) =
let t' = doubleQuotes $ printTerm t
ts' = hsep $ map (\ p -> text "is" <+> (doubleQuotes . printTerm) p) ts
in t' <+> if null ts then empty
else parens ts'
printSetDecl :: SetDecl -> Doc
printSetDecl setdecl =
case setdecl of
SubSet v t f -> braces $ printTerm v <> doubleColon <> printType t <> dot
<+> printTerm f
FixedSet elems -> braces $ sepByCommas $ map printTerm elems
printPlainMetaTerm :: Bool -> MetaTerm -> Doc
printPlainMetaTerm b mt = case mt of
Term t -> printPlainTerm b t
Conditional conds t -> sep
[ text premiseOpenS
<+> fsep (punctuate semi $ map printTerm conds)
<+> text premiseCloseS
, text metaImplS <+> printTerm t ]
-- | print plain term
printTerm :: Term -> Doc
printTerm = printPlainTerm True
printPlainTerm :: Bool -> Term -> Doc
printPlainTerm b = fst . printTrm b
-- | print parens but leave a space if doc starts or ends with a bar
parensForTerm :: Doc -> Doc
parensForTerm d =
let s = show d
b = '|'
in parens $ if null s then d
else (if head s == b then (space <>) else id)
((if last s == b then (<> space) else id) d)
printParenTerm :: Bool -> Int -> Term -> Doc
printParenTerm b i t = case printTrm b t of
(d, j) -> if j < i then parensForTerm d else d
flatTuplex :: [Term] -> Continuity -> [Term]
flatTuplex cs c = case cs of
[] -> cs
_ -> case last cs of
Tuplex rs@(_ : _ : _) d | d == c -> init cs ++ flatTuplex rs d
_ -> cs
printMixfixAppl :: Bool -> Continuity -> Term -> [Term] -> (Doc, Int)
printMixfixAppl b c f args = case f of
Const (VName n (Just (AltSyntax s is i))) (Hide {}) ->
if length is == length args &&
(b || n == cNot || isPrefixOf "op " n) then
(fsep $ replaceUnderlines s
$ zipWith (printParenTerm b) is args, i)
else printApp b c f args
Const vn _ | new vn `elem` [allS, exS, ex1S] -> case args of
[Abs v t _] -> (fsep [text (new vn) <+> printPlainTerm False v
<> dot
, printPlainTerm b t], lowPrio)
_ -> printApp b c f args
App g a d | c == d -> printMixfixAppl b c g (a : args)
_ -> printApp b c f args
-- | print the term using the alternative syntax (if True)
printTrm :: Bool -> Term -> (Doc, Int)
printTrm b trm = case trm of
Const vn ty -> let
dvn = text $ new vn
nvn = case ty of
Hide {} -> dvn
Disp w _ _ -> parens $ dvn <+> doubleColon <+> printType w
in case altSyn vn of
Nothing -> (nvn, maxPrio)
Just (AltSyntax s is i) -> if b && null is then
(fsep $ replaceUnderlines s [], i) else (nvn, maxPrio)
Free vn -> (text $ new vn, maxPrio)
Abs v t c -> (text (case c of
NotCont -> "%"
IsCont _ -> "Lam") <+> printPlainTerm False v <> dot
<+> printPlainTerm b t, lowPrio)
If i t e c -> let d = fsep [printPlainTerm b i,
text (case c of
NotCont -> "then"
IsCont _ -> "THEN")
<+> printPlainTerm b t,
text (case c of
NotCont -> "else"
IsCont _ -> "ELSE")
<+> printPlainTerm b e]
in case c of
NotCont -> (text "if" <+> d, lowPrio)
IsCont _ -> (text "IF" <+> d <+> text "FI", maxPrio)
Case e ps -> (text "case" <+> printPlainTerm b e <+> text "of"
$+$ vcat (bar $ map (\ (p, t) ->
fsep [ printPlainTerm b p <+> text "=>"
, printParenTerm b (lowPrio + 1) t]) ps), lowPrio)
Let es i -> (fsep [text "let" <+>
vcat (punctuate semi $
map (\ (p, t) -> fsep [ printPlainTerm b p <+> equals
, printPlainTerm b t]) es)
, text "in" <+> printPlainTerm b i], lowPrio)
IsaEq t1 t2 ->
(fsep [ printParenTerm b (isaEqPrio + 1) t1 <+> isaEquals
, printParenTerm b isaEqPrio t2], isaEqPrio)
Tuplex cs c -> case c of
NotCont -> (parensForTerm
$ sepByCommas (map (printPlainTerm b)
$ flatTuplex cs c)
, maxPrio)
IsCont _ -> case cs of
[] -> error "IsaPrint, printTrm"
[a] -> printTrm b a
a : aa -> printTrm b $ App (App
lpairTerm a $ IsCont False)
(Tuplex aa c) (IsCont False)
App f a c -> printMixfixAppl b c f [a]
Set setdecl -> (printSetDecl setdecl, lowPrio)
printApp :: Bool -> Continuity -> Term -> [Term] -> (Doc, Int)
printApp b c t l = case l of
[] -> printTrm b t
_ -> printDocApp b c (printParenTerm b (maxPrio - 1) t) l
printDocApp :: Bool -> Continuity -> Doc -> [Term] -> (Doc, Int)
printDocApp b c d l =
( fsep $ (case c of
NotCont -> id
IsCont True -> punctuate $ text " $$"
IsCont False -> punctuate $ text " $")
$ d : map (printParenTerm b maxPrio) l
, maxPrio - 1)
replaceUnderlines :: String -> [Doc] -> [Doc]
replaceUnderlines str l = case str of
"" -> []
'\'' : r@(q : s) -> if q `elem` "_/'()"
then consDocBarSep (text [q]) $ replaceUnderlines s l
else consDocBarSep (text "'") $ replaceUnderlines r l
'_' : r -> case l of
h : t -> consDocBarSep h $ replaceUnderlines r t
_ -> error "replaceUnderlines"
'/' : ' ' : r -> empty : replaceUnderlines r l
q : r -> if q `elem` "()/" then replaceUnderlines r l
else consDocBarSep (text [q]) $ replaceUnderlines r l
consDocBarSep :: Doc -> [Doc] -> [Doc]
consDocBarSep d r = case r of
[] -> [d]
h : t -> let
b = '|'
hs = show h
ds = show d
hhs = head hs
lds = last ds
in if null hs || null ds then (d <> h) : t else
if hhs == b && lds == '(' || last ds == b && hhs == ')'
then (d <+> h) : t
else (d <> h) : t
-- end of term printing
printLocales :: Locales -> Doc
printLocales = vsep . map printLocale . orderLDecs . Map.toList
printDefinitions :: Defs -> Doc
printDefinitions = vsep . map printDefinition . Map.toList
printFunctions :: Funs -> Doc
printFunctions = vsep . map printFunction . Map.toList
printFixesAssumes :: Doc -> [Doc] -> [Doc] -> [Doc] -> Doc
printFixesAssumes h p' a f = vcat
[ h <+> (if null $ p' ++ a ++ f then empty else text "=") <+> hsep p'
<+> if null p' || null a && null f then empty else text "+"
, if null f then empty else text "fixes" <+> andDocs f
, if null a then empty else text "assumes" <+> andDocs a
]
printDefinition :: (String, Def) -> Doc
printDefinition (n, (tp, vs, tm)) = text "definition" <+> text n <+> text "::"
$+$ (doubleQuotes . printTyp Null) tp <+> text "where"
$+$ doubleQuotes (text n <+> hsep (map (text . fst) vs)
<+> text "\\<equiv>" <+> printTerm tm)
printFunction :: (String, FunDef) -> Doc
printFunction (n, (tp, def_eqs)) = text "fun" <+> text n <+> text "::"
$+$ (doubleQuotes . printTyp Null) tp <+> text "where"
$+$ (vcat . punctuate (text "|"))
(map (\ (pats, tm) -> doubleQuotes $ text n
<+> hsep (map printTerm pats) <+> text "="
<+> printTerm tm) def_eqs)
printLocale :: (String, LocaleDecl) -> Doc
printLocale (n, (parents, in_ax, ex_ax, params)) =
let p' = Data.List.intersperse (text "+") $ map text parents
a = map (\ (s, t) -> text s <+> text ":"
<+> (doubleQuotes . printTerm) t) in_ax
f = map (\ (s, t, alt) -> text s <+> text "::"
<+> (doubleQuotes . printTyp Null) t
<+> (case alt of
Just (AltSyntax s' [i1, i2] i) -> parens (
text (if i1 == i2 then "infix "
else if i1 < i2 then "infixr "
else "infixl ") <+> doubleQuotes (text s')
<+> text (show i))
_ -> empty
)) params
in vcat [
printFixesAssumes (text "locale" <+> text n) p' a f,
vcat (map (\ (s, t) -> text ("theorem (in " ++ n ++ ")")
<+> text s <+> text ":"
<+> (doubleQuotes . printTerm) t
<+> text "apply(auto)"
<+> text "done") ex_ax)]
printClassrel :: Classrel -> Doc
printClassrel = vsep . map printClassR . orderCDecs . Map.toList
printClassR :: (IsaClass, ClassDecl) -> Doc
printClassR (y, (parents, assumptions, fxs)) =
let a = map (\ (s, t) -> text s <+> text ":"
<+> (doubleQuotes . printTerm) t) assumptions
f = map (\ (s, t) -> text s <+> text "::"
<+> (doubleQuotes . printTyp Null) t) fxs
parents' = filter (\ (IsaClass s) -> notElem s
["HOL.type_class", "HOL.type", "type", "type_class"]) parents
p' = Data.List.intersperse (text "+") $ map printClass parents'
in printFixesAssumes (text "class" <+> printClass y) p' a f
orderCDecs :: [(IsaClass, ClassDecl)] -> [(IsaClass, ClassDecl)]
orderCDecs =
topSort crord
where
crord (_, (cs, _, _)) (c, _) = elem c cs
orderLDecs :: [(String, LocaleDecl)] -> [(String, LocaleDecl)]
orderLDecs =
topSort crord
where
crord (_, (cs, _, _, _)) (c, _) = elem c cs
printMonArities :: String -> Arities -> Doc
printMonArities tn = vcat . map ( \ (t, cl) ->
vcat $ map (printThMorp tn t) cl) . Map.toList
printThMorp :: String -> TName -> (IsaClass, [(Typ, Sort)]) -> Doc
printThMorp tn t xs = case xs of
(IsaClass "Monad", _) ->
if isSuffixOf "_mh" tn || isSuffixOf "_mhc" tn
then printMInstance tn t
else error "IsaPrint, printInstance: monads not supported"
_ -> empty
printMInstance :: String -> TName -> Doc
printMInstance tn t = let nM = text (t ++ "_tm")
nM2 = text (t ++ "_tm2")
in prnThymorph nM "MonadType" tn t [("MonadType.M", "'a")] []
$+$ text "t_instantiate MonadOps mapping" <+> nM
$+$ text "renames:" <+>
brackMapList (\ x -> t ++ "_" ++ x)
[("MonadOpEta.eta", "eta"), ("MonadOpBind.bind", "bind")]
$+$ text "without_syntax"
$++$ text "defs "
$+$ text (t ++ "_eta_def:") <+> doubleQuotes
(text (t ++ "_eta") <+> isaEquals <+> text ("return_" ++ t))
$+$ text (t ++ "_bind_def:") <+> doubleQuotes
(text (t ++ "_bind") <+> isaEquals <+> text ("mbind_" ++ t))
$++$ lunitLemma t
$+$ runitLemma t
$+$ assocLemma t
$+$ etaInjLemma t
$++$ prnThymorph nM2 "MonadAxms" tn t [("MonadType.M", "'a")]
[("MonadOpEta.eta", t ++ "_eta"),
("MonadOpBind.bind", t ++ "_bind")]
$+$ text "t_instantiate Monad mapping" <+> nM2
$+$ text "renames:" <+>
brackMapList (\ x -> t ++ "_" ++ x)
[("Monad.kapp", "kapp"),
("Monad.lift", "lift"),
("Monad.lift", "lift"),
("Monad.mapF", "mapF"),
("Monad.bind'", "mbbind"),
("Monad.joinM", "joinM"),
("Monad.kapp2", "kapp2"),
("Monad.kapp3", "kapp3"),
("Monad.lift2", "lift2"),
("Monad.lift3", "lift3")]
$+$ text "without_syntax"
$++$ text " "
where
lunitLemma w = text lemmaS <+> text (w ++ "_lunit:")
<+> doubleQuotes (text (w ++ "_bind")
<+> parens (text (w ++ "_eta x"))
<+> parens (text $ "t::'a => 'b " ++ w)
<+> equals <+> text "t x")
$+$ text "sorry "
runitLemma w = text lemmaS <+> text (w ++ "_runit:")
<+> doubleQuotes (text (w ++ "_bind")
<+> parens (text $ "t::'a " ++ w) <+> text (w ++ "_eta")
<+> equals <+> text "t")
$+$ text "sorry "
assocLemma w = text lemmaS <+> text (w ++ "_assoc:")
<+> doubleQuotes (text (w ++ "_bind")
<+> parens (text (w ++ "_bind")
<+> parens (text $ "s::'a " ++ w) <+> text "t") <+> text "u"
<+> equals <+> text (w ++ "_bind s")
<+> parens (text "%x." <+>
text (w ++ "_bind") <+> text "(t x) u"))
$+$ text "sorry "
etaInjLemma w = text lemmaS <+> text (w ++ "_eta_inj:")
<+> doubleQuotes (parens (text $ w ++ "_eta::'a => 'a " ++ w)
<+> text "x"
<+> equals <+> text (w ++ "_eta y")
<+> text "==>" <+> text "x = y")
$+$ text "sorry "
prnThymorph :: Doc -> String -> String -> TName -> [(String, String)]
-> [(String, String)] -> Doc
prnThymorph nm xn tn t ts ws = let qual s = tn ++ "." ++ s in
text "thymorph" <+> nm <+> colon <+>
text xn <+> cfun <+> text tn
$+$ text " maps" <+> brackets
(hcat [ parens $ doubleQuotes (text b <+> text a) <+> mapsto
<+> doubleQuotes (text b <+> text (qual t))
| (a, b) <- ts])
$+$ brackMapList qual ws
brackMapList :: (String -> String) -> [(String, String)] -> Doc
brackMapList f ws = brackets $ hsep $ punctuate comma
[ parens $ doubleQuotes (text a) <+> mapsto <+> doubleQuotes (text $ f b)
| (a, b) <- ws]
-- filter out types that are given in the domain table
printTypeDecls :: BaseSig -> DomainTab -> Arities -> Doc
printTypeDecls bs odt ars =
let dt = Map.fromList $ map (\ (t, _) -> (typeId t, [])) $ concat odt
in vcat $ map (printTycon bs) $ Map.toList $ Map.difference ars dt
printTycon :: BaseSig -> (TName, [(IsaClass, [(Typ, Sort)])]) -> Doc
printTycon bs (t, arity') = case arity' of
[] -> error "IsaPrint.printTycon"
(_, rs) : _ ->
if Set.member t
$ Map.findWithDefault (error "Isabelle.printTycon") bs
$ preTypes isaPrelude
then empty else
text typedeclS <+>
(if null rs then empty else
parens $ hsep $ punctuate comma
$ map (text . ("'a" ++) . show . snd) $ number rs) <+> text t
-- | show alternative syntax (computed by comorphisms)
printAlt :: VName -> Doc
printAlt (VName _ altV) = case altV of
Nothing -> empty
Just (AltSyntax s is i) -> parens $ doubleQuotes (text s)
<+> if null is then empty else text (show is) <+>
if i == maxPrio then empty else text (show i)
instance Pretty Sign where
pretty = printSign
-- | a dummy constant table with wrong types
constructors :: DomainTab -> ConstTab
constructors = Map.fromList . map (\ v -> (v, noTypeT))
. concatMap (map fst . snd) . concat
printMonSign :: Sign -> Doc
printMonSign sig = let ars = arities $ tsig sig
in
printMonArities (theoryName sig) ars
printSign :: Sign -> Doc
printSign sig = let dt = ordDoms $ domainTab sig
ars = arities $ tsig sig
in
printAbbrs (abbrs $ tsig sig) $++$
printTypeDecls (baseSig sig) dt ars $++$
printDefinitions (defs $ tsig sig) $++$
printFunctions (funs $ tsig sig) $++$
printLocales (locales $ tsig sig) $++$
printClassrel (classrel $ tsig sig) $++$
printDomainDefs dt $++$
printConstTab (Map.difference (constTab sig)
$ constructors dt) $++$
(if showLemmas sig
then showCaseLemmata dt else empty)
where
printAbbrs tab = if Map.null tab then empty else text typesS
$+$ vcat (map printAbbr $ Map.toList tab)
printAbbr (n, (vs, t)) = case vs of
[] -> empty
[x] -> text ('\'' : x)
_ -> parens $ hsep $ punctuate comma $
map (text . ('\'' :)) vs
<+> text n <+> equals <+> doubleQuotes (printType t)
printConstTab tab = if Map.null tab then empty else text constsS
$+$ vcat (map printConst $ Map.toList tab)
printConst (vn, t) = text (new vn) <+> doubleColon <+>
doubleQuotes (printType t) <+> printAlt vn
isDomain = case baseSig sig of
HOLCF_thy -> True
HsHOLCF_thy -> True
MHsHOLCF_thy -> True
_ -> False
printDomainDefs dtDefs = vcat $ map printDomainDef dtDefs
printDomainDef dts = if null dts then empty else
text (if isDomain then domainS else datatypeS)
<+> andDocs (map printDomain dts)
printDomain (t, ops) =
printTyp (if isDomain then Quoted else Null) t <+> equals <+>
fsep (bar $ map printDOp ops)
printDOp (vn, args) = let opname = new vn in
text (if any isSpace opname then show opname else opname)
<+> hsep (map (printDOpArg opname) $ number args)
<+> printAlt vn
printDOpArg o (a, i) = let
d = case a of
TFree _ _ -> printTyp Null a
_ -> doubleQuotes $ printTyp Null a
in if isDomain then
parens $ text "lazy" <+>
text (o ++ "_" ++ show i) <> doubleColon <> d
else d
showCaseLemmata dtDefs = text (concatMap showCaseLemmata1 dtDefs)
showCaseLemmata1 = concatMap showCaseLemma
showCaseLemma (_, []) = ""
showCaseLemma (tyCons, c : cns) =
let cs = "case caseVar of" ++ sp
sc b = showCons b c ++ concatMap ((" | " ++) . showCons b) cns
clSome = sc True
cl = sc False
showCons b (VName {new = cName}, args) =
let pat = cName ++ concatMap ((sp ++) . showArg) args
++ sp ++ "=>" ++ sp
term = showCaseTerm cName args
in
pat ++ if b then "Some" ++ sp ++ lb ++ term ++ rb ++ "\n"
else term ++ "\n"
showCaseTerm name args = case name of
"" -> sa
n : _ -> toLower n : sa
where sa = concatMap ((sp ++) . showArg) args
showArg (TFree [] _) = "varName"
showArg (TFree (n : ns) _) = toLower n : ns
showArg (TVar v s) = showArg (TFree (unindexed v) s)
showArg (Type [] _ _) = "varName"
showArg (Type m@(n : ns) _ s) =
if elem m ["typeAppl", "fun", "*"]
then concatMap showArg s
else toLower n : ns
showName (TFree v _) = v
showName (TVar v _) = unindexed v
showName (Type n _ _) = n
proof' = "apply (case_tac caseVar)\napply (auto)\ndone\n"
in
lemmaS ++ sp ++ "case_" ++ showName tyCons ++ "_SomeProm" ++ sp
++ "[simp]:\"" ++ sp ++ lb ++ cs ++ clSome ++ rb ++ sp
++ "=\n" ++ "Some" ++ sp ++ lb ++ cs ++ cl ++ rb ++ "\"\n"
++ proof'
instance Pretty Sentence where
pretty = printSentence
sp :: String
sp = " "
rb :: String
rb = ")"
lb :: String
lb = "("
-- Pretty printing of proofs
instance Pretty IsaProof where
pretty = printIsaProof
printIsaProof :: IsaProof -> Doc
printIsaProof (IsaProof p e) = fsep $ map pretty p ++ [pretty e]
instance Pretty ProofCommand where
pretty = printProofCommand
printProofCommand :: ProofCommand -> Doc
printProofCommand pc =
case pc of
Apply pms plus ->
let plusDoc = if plus then text "+" else empty
in text applyS <+> parens
(sepByCommas $ map pretty pms) <> plusDoc
Using ls -> text usingS <+> fsep (map text ls)
Back -> text backS
Defer x -> text deferS <+> pretty x
Prefer x -> text preferS <+> pretty x
Refute -> text refuteS
instance Pretty ProofEnd where
pretty = printProofEnd
printProofEnd :: ProofEnd -> Doc
printProofEnd pe =
case pe of
By pm -> text byS <+> parens (pretty pm)
DotDot -> text dotDot
Done -> text doneS
Oops -> text oopsS
Sorry -> text sorryS
instance Pretty Modifier where
pretty = printModifier
printModifier :: Modifier -> Doc
printModifier m =
case m of
No_asm -> text "no_asm"
No_asm_simp -> text "no_asm_simp"
No_asm_use -> text "no_asm_use"
instance Pretty ProofMethod where
pretty = printProofMethod
printProofMethod :: ProofMethod -> Doc
printProofMethod pm =
case pm of
Auto -> text autoS
Simp -> text simpS
AutoSimpAdd m names -> let modDoc = case m of
Just mod' -> parens $ pretty mod'
Nothing -> empty
in fsep $ [text autoS, text simpS, modDoc,
text "add:"] ++ map text names
SimpAdd m names -> let modDoc = case m of
Just mod' -> parens $ pretty mod'
Nothing -> empty
in fsep $ [text simpS, modDoc, text "add:"] ++
map text names
Induct var -> text inductS <+> doubleQuotes (printTerm var)
CaseTac t -> text caseTacS <+> doubleQuotes (printTerm t)
SubgoalTac t -> text subgoalTacS <+> doubleQuotes (printTerm t)
Insert ts -> fsep (text insertS : map text ts)
Other s -> text s
| keithodulaigh/Hets | Isabelle/IsaPrint.hs | gpl-2.0 | 41,894 | 1,387 | 27 | 14,867 | 14,680 | 7,636 | 7,044 | 927 | 54 |
module Main where
import System.Console.Haskeline
import Expr
import TypeCheck
import Translation
import Syntax
import Parser
-- import Predef
-- Note: 1. datatypes first, then record
-- 2. first `desugar` to get rid of record, second desugar to get rid of let expression
main :: IO ()
main = runInputT defaultSettings (loop [] [])
where
loop :: BEnv -> Env -> InputT IO ()
loop benv env =
do
minput <- getInputLine "pts> "
case minput of
Nothing -> return ()
Just "" -> loop benv env
Just ":q" -> return ()
Just cmds -> dispatch benv env cmds
dispatch :: BEnv -> Env -> String -> InputT IO ()
dispatch benv env cmds =
let e@(cmd:progm) = words cmds
in case cmd of
":clr" -> do
outputStrLn "Environment cleaned up!"
loop [] [] -- initalBEnv initalEnv
":env" -> do
outputStrLn $ "Typing environment: " ++ show env
outputStrLn $ "Binding environment: " ++ show (map fst benv)
loop benv env
":add" -> delegate progm "Command parse error - :add name type" $
\name xs -> do
outputStrLn "Added!"
loop benv (extend name (head xs) env)
":let" -> delegate progm "Command parse error - :let name expr" $
\name xs -> do
outputStrLn "Added new term!"
loop ((name, head xs) : benv) env
":e" -> processCMD progm $
\xs -> do
if length xs == 1
then case trans env (desugar . head $ xs) >>= \(_, transE) -> eval (desugar transE) of
Left err -> outputStrLn err
Right e' -> outputStrLn ("\n--- Evaluation result ---\n\n" ++ show e' ++ "\n")
else outputStrLn "Command parser error - need one expression!"
loop benv env
-- ":eq" -> processCMD progm $
-- \xs -> do
-- if length xs == 2
-- then outputStrLn . show $ equate benv (head xs) (xs !! 1)
-- else outputStrLn "Command parser error - need two expressions!"
-- loop benv env
":t" -> processCMD progm $
\xs -> do
if length xs == 1
then case trans env (desugar . head $ xs) >>= \(_, transE) -> tcheck env (desugar transE) of
Left err -> outputStrLn err
Right typ -> outputStrLn ("\n--- Typing result ---\n\n" ++ show typ ++ "\n")
else outputStrLn "Command parser error - need one expression!"
loop benv env
-- ":teq" -> processCMD progm $
-- \xs -> do
-- if length xs == 2
-- then case tcheck env . repFreeVar benv . head $ xs of
-- Left err -> outputStrLn err
-- Right typ -> outputStrLn . show $ equate benv typ (xs !! 1)
-- else outputStrLn "Command parser error - need two expressions!"
-- loop benv env
":trans" ->
processCMD progm $
\xs -> do
if length xs == 1
then case trans env . desugar . head $ xs of
Left err -> outputStrLn err
Right (_, transE) -> outputStrLn ("\n--- Translation result ---\n\n" ++ show transE ++ "\n")
else outputStrLn "Command parser error - need one expression!"
loop benv env
_ -> processCMD e $
\xs -> do
outputStrLn ("\n--- Pretty printing ---\n\n" ++ concatMap show xs ++ "\n")
loop benv env
where
processCMD expr func =
case parseExpr . unwords $ expr of
Left err -> do
outputStrLn err
loop benv env
Right (Progm xs) -> func xs
delegate progm errMsg func =
if length progm >= 2
then let (name:typ) = progm
in processCMD typ $
\xs -> if length xs == 1
then func name xs
else do
outputStrLn "Command parser error - need one expression!"
loop benv env
else do
outputStrLn errMsg
loop benv env
| bixuanzju/full-version | src/Main.hs | gpl-3.0 | 4,269 | 0 | 24 | 1,702 | 1,011 | 488 | 523 | 84 | 20 |
-- | Handler for comments on Wiki pages. Section comments are relative to /p/#handle/w/#target/c/#comment
module Handler.Wiki.Comment where
import Import
import Handler.Comment as Com
import Handler.Project (checkProjectCommentActionPermission)
import Model.Comment
import Model.Comment.ActionPermissions
import Model.Comment.HandlerInfo
import Model.Comment.Mods
import Model.Comment.Sql
import Model.User
import Widgets.Preview
import Data.Default (def)
import Data.Tree (Forest, Tree)
import qualified Data.Tree as Tree
import Text.Cassius (cassiusFile)
--------------------------------------------------------------------------------
-- Utility functions
-- | Convenience method for all pages that accept a project handle, target, and comment id
-- as URL parameters. Makes sure that the comment is indeed on the page. Redirects if the
-- comment was rethreaded. 404's if the comment doesn't exist. 403 if permission denied.
checkCommentPage :: Text -> Language -> Text -> CommentId -> Handler (Maybe (Entity User), Entity Project, Entity WikiPage, Comment)
checkCommentPage project_handle language target comment_id = do
muser <- maybeAuth
(project, page, comment) <- checkCommentPage' (entityKey <$> muser) project_handle language target comment_id
return (muser, project, page, comment)
-- | Like checkCommentPage, but authentication is required.
checkCommentPageRequireAuth :: Text -> Language -> Text -> CommentId -> Handler (Entity User, Entity Project, Entity WikiPage, Comment)
checkCommentPageRequireAuth project_handle language target comment_id = do
user@(Entity user_id _) <- requireAuth
(project, page, comment) <- checkCommentPage' (Just user_id) project_handle language target comment_id
return (user, project, page, comment)
-- | Abstract checkCommentPage and checkCommentPageRequireAuth. You shouldn't
-- use this function directly.
checkCommentPage' :: Maybe UserId -> Text -> Language -> Text -> CommentId -> Handler (Entity Project, Entity WikiPage, Comment)
checkCommentPage' muser_id project_handle language target comment_id = do
redirectIfRethreaded comment_id
(project, wiki_page, ecomment) <- runYDB $ do
project@(Entity project_id _) <- getBy404 $ UniqueProjectHandle project_handle
Entity _ wiki_target <- getBy404 $ UniqueWikiTarget (entityKey project) language target
let wiki_page_id = wikiTargetPage wiki_target
wiki_page <- get404 wiki_page_id
let has_permission = exprCommentProjectPermissionFilter muser_id (val project_id)
ecomment <- fetchCommentDB comment_id has_permission
return (project, Entity wiki_page_id wiki_page, ecomment)
case ecomment of
Left CommentNotFound -> notFound
Left CommentPermissionDenied -> permissionDenied "You don't have permission to view this comment."
Right comment ->
if commentDiscussion comment /= wikiPageDiscussion (entityVal wiki_page)
then notFound
else return (project, wiki_page, comment)
makeWikiPageCommentForestWidget
:: Maybe (Entity User)
-> ProjectId
-> Text
-> Language
-> Text
-> [Entity Comment]
-> CommentMods
-> Handler MaxDepth
-> Bool
-> Widget
-> Handler (Widget, Forest (Entity Comment))
makeWikiPageCommentForestWidget
muser
project_id
project_handle
language
target
comments =
makeCommentForestWidget
(wikiPageCommentHandlerInfo muser project_id project_handle language target)
comments
muser
makeWikiPageCommentTreeWidget
:: Maybe (Entity User)
-> ProjectId
-> Text
-> Language
-> Text
-> Entity Comment
-> CommentMods
-> Handler MaxDepth
-> Bool
-> Widget
-> Handler (Widget, Tree (Entity Comment))
makeWikiPageCommentTreeWidget mviewer project_id project_handle language target comment mods maxDepth is_preview widget_under_root_comment = do
(widget, [tree]) <- makeWikiPageCommentForestWidget mviewer project_id project_handle language target [comment] mods maxDepth is_preview widget_under_root_comment
return (widget, tree)
makeWikiPageCommentActionWidget
:: MakeCommentActionWidget
-> Text
-> Language
-> Text
-> CommentId
-> CommentMods
-> Handler MaxDepth
-> Handler (Widget, Tree (Entity Comment))
makeWikiPageCommentActionWidget make_comment_action_widget project_handle language target comment_id mods get_max_depth = do
(user, Entity project_id _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
make_comment_action_widget
(Entity comment_id comment)
user
(wikiPageCommentHandlerInfo (Just user) project_id project_handle language target)
mods
get_max_depth
False
wikiDiscussionPage :: Text -> Language -> Text -> Widget -> Widget
wikiDiscussionPage project_handle language target widget = do
$(widgetFile "wiki_discussion_wrapper")
toWidget $(cassiusFile "templates/comment.cassius")
--------------------------------------------------------------------------------
-- /
getWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getWikiCommentR project_handle language target comment_id = do
(muser, Entity project_id _, _, comment) <- checkCommentPage project_handle language target comment_id
(widget, comment_tree) <-
makeWikiPageCommentTreeWidget
muser
project_id
project_handle
language
target
(Entity comment_id comment)
def
getMaxDepth
False
mempty
case muser of
Nothing -> return ()
Just (Entity user_id _) ->
runDB (userMaybeViewProjectCommentsDB user_id project_id (map entityKey (Tree.flatten comment_tree)))
defaultLayout (wikiDiscussionPage project_handle language target widget)
--------------------------------------------------------------------------------
-- /claim
getClaimWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getClaimWikiCommentR project_handle language target comment_id = do
(widget, _) <-
makeWikiPageCommentActionWidget
makeClaimCommentWidget
project_handle
language
target
comment_id
def
getMaxDepth
defaultLayout (wikiDiscussionPage project_handle language target widget)
postClaimWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
postClaimWikiCommentR project_handle language target comment_id = do
(user, Entity project_id _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
checkProjectCommentActionPermission can_claim user project_handle (Entity comment_id comment)
postClaimComment
user
comment_id
comment
(wikiPageCommentHandlerInfo (Just user) project_id project_handle language target)
>>= \case
Nothing -> redirect (WikiCommentR project_handle language target comment_id)
Just (widget, form) -> defaultLayout $ previewWidget form "claim" (wikiDiscussionPage project_handle language target widget)
--------------------------------------------------------------------------------
-- /approve
getApproveWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getApproveWikiCommentR project_handle language target comment_id = do
(widget, _) <-
makeWikiPageCommentActionWidget
makeApproveCommentWidget
project_handle
language
target
comment_id
def
getMaxDepth
defaultLayout (wikiDiscussionPage project_handle language target widget)
postApproveWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
postApproveWikiCommentR project_handle language target comment_id = do
(user@(Entity user_id _), _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
checkProjectCommentActionPermission can_approve user project_handle (Entity comment_id comment)
postApproveComment user_id comment_id comment
redirect (WikiCommentR project_handle language target comment_id)
--------------------------------------------------------------------------------
-- /close
getCloseWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getCloseWikiCommentR project_handle language target comment_id = do
(widget, _) <-
makeWikiPageCommentActionWidget
makeCloseCommentWidget
project_handle
language
target
comment_id
def
getMaxDepth
defaultLayout (wikiDiscussionPage project_handle language target widget)
postCloseWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
postCloseWikiCommentR project_handle language target comment_id = do
(user, Entity project_id _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
checkProjectCommentActionPermission can_close user project_handle (Entity comment_id comment)
postCloseComment
user
comment_id
comment
(wikiPageCommentHandlerInfo (Just user) project_id project_handle language target)
>>= \case
Nothing -> redirect (WikiCommentR project_handle language target comment_id)
Just (widget, form) -> defaultLayout $ previewWidget form "close" (wikiDiscussionPage project_handle language target widget)
--------------------------------------------------------------------------------
-- /delete
getDeleteWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getDeleteWikiCommentR project_handle language target comment_id = do
(widget, _) <-
makeWikiPageCommentActionWidget
makeDeleteCommentWidget
project_handle
language
target
comment_id
def
getMaxDepth
defaultLayout (wikiDiscussionPage project_handle language target widget)
postDeleteWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
postDeleteWikiCommentR project_handle language target comment_id = do
(user, _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
checkProjectCommentActionPermission can_delete user project_handle (Entity comment_id comment)
was_deleted <- postDeleteComment comment_id
if was_deleted
then redirect (WikiDiscussionR project_handle language target)
else redirect (WikiCommentR project_handle language target comment_id)
--------------------------------------------------------------------------------
-- /edit
getEditWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getEditWikiCommentR project_handle language target comment_id = do
(widget, _) <-
makeWikiPageCommentActionWidget
makeEditCommentWidget
project_handle
language
target
comment_id
def
getMaxDepth
defaultLayout (wikiDiscussionPage project_handle language target widget)
postEditWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
postEditWikiCommentR project_handle language target comment_id = do
(user, Entity project_id _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
checkProjectCommentActionPermission can_edit user project_handle (Entity comment_id comment)
postEditComment
user
(Entity comment_id comment)
(wikiPageCommentHandlerInfo (Just user) project_id project_handle language target)
>>= \case
Nothing -> redirect (WikiCommentR project_handle language target comment_id) -- Edit made.
Just (widget, form) -> defaultLayout $ previewWidget form "post" (wikiDiscussionPage project_handle language target widget)
--------------------------------------------------------------------------------
-- /flag
getFlagWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getFlagWikiCommentR project_handle language target comment_id = do
(widget, _) <-
makeWikiPageCommentActionWidget
makeFlagCommentWidget
project_handle
language
target
comment_id
def
getMaxDepth
defaultLayout (wikiDiscussionPage project_handle language target widget)
postFlagWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
postFlagWikiCommentR project_handle language target comment_id = do
(user, Entity project_id _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
checkProjectCommentActionPermission can_flag user project_handle (Entity comment_id comment)
postFlagComment
user
(Entity comment_id comment)
(wikiPageCommentHandlerInfo (Just user) project_id project_handle language target)
>>= \case
Nothing -> redirect (WikiDiscussionR project_handle language target)
Just (widget, form) -> defaultLayout $ previewWidget form "flag" (wikiDiscussionPage project_handle language target widget)
--------------------------------------------------------------------------------
-- /reply
getReplyWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getReplyWikiCommentR project_handle language target comment_id = do
(widget, _) <-
makeWikiPageCommentActionWidget
makeReplyCommentWidget
project_handle
language
target
comment_id
def
getMaxDepth
defaultLayout (wikiDiscussionPage project_handle language target widget)
postReplyWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
postReplyWikiCommentR project_handle language target parent_id = do
(user, _, Entity _ page, parent) <- checkCommentPageRequireAuth project_handle language target parent_id
checkProjectCommentActionPermission can_reply user project_handle (Entity parent_id parent)
postNewComment
(Just parent_id)
user
(wikiPageDiscussion page)
(makeProjectCommentActionPermissionsMap (Just user) project_handle def)
>>= \case
ConfirmedPost (Left err) -> do
alertDanger err
redirect $ ReplyWikiCommentR
project_handle language target parent_id
ConfirmedPost (Right _)->
redirect $ WikiCommentR project_handle language target parent_id
Com.Preview (widget, form) ->
defaultLayout $ previewWidget form "post" $
wikiDiscussionPage project_handle language target widget
--------------------------------------------------------------------------------
-- /rethread
getRethreadWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getRethreadWikiCommentR project_handle language target comment_id = do
(widget, _) <-
makeWikiPageCommentActionWidget
makeRethreadCommentWidget
project_handle
language
target
comment_id
def
getMaxDepth
defaultLayout (wikiDiscussionPage project_handle language target widget)
postRethreadWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
postRethreadWikiCommentR project_handle language target comment_id = do
(user@(Entity user_id _), _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
checkProjectCommentActionPermission can_rethread user project_handle (Entity comment_id comment)
postRethreadComment user_id comment_id comment
--------------------------------------------------------------------------------
-- /retract
getRetractWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getRetractWikiCommentR project_handle language target comment_id = do
(widget, _) <-
makeWikiPageCommentActionWidget
makeRetractCommentWidget
project_handle
language
target
comment_id
def
getMaxDepth
defaultLayout (wikiDiscussionPage project_handle language target widget)
postRetractWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
postRetractWikiCommentR project_handle language target comment_id = do
(user, Entity project_id _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
checkProjectCommentActionPermission can_retract user project_handle (Entity comment_id comment)
postRetractComment
user
comment_id
comment
(wikiPageCommentHandlerInfo (Just user) project_id project_handle language target)
>>= \case
Nothing -> redirect (WikiCommentR project_handle language target comment_id)
Just (widget, form) -> defaultLayout $ previewWidget form "retract" (wikiDiscussionPage project_handle language target widget)
--------------------------------------------------------------------------------
-- /tags
getWikiCommentTagsR :: Text -> Language -> Text -> CommentId -> Handler Html
getWikiCommentTagsR _ _ _ = getCommentTags
--------------------------------------------------------------------------------
-- /tag/#TagId
getWikiCommentTagR :: Text -> Language -> Text -> CommentId -> TagId -> Handler Html
getWikiCommentTagR _ _ _ = getCommentTagR
postWikiCommentTagR :: Text -> Language -> Text -> CommentId -> TagId -> Handler ()
postWikiCommentTagR _ _ _ = postCommentTagR
--------------------------------------------------------------------------------
-- /tag/apply, /tag/create
postWikiCommentApplyTagR, postWikiCommentCreateTagR :: Text -> Language -> Text -> CommentId -> Handler Html
postWikiCommentApplyTagR = applyOrCreate postCommentApplyTag
postWikiCommentCreateTagR = applyOrCreate postCommentCreateTag
applyOrCreate :: (CommentId -> Handler ()) -> Text -> Language -> Text -> CommentId -> Handler Html
applyOrCreate action project_handle language target comment_id = do
action comment_id
redirect (WikiCommentR project_handle language target comment_id)
--------------------------------------------------------------------------------
-- /tag/new
getWikiCommentAddTagR :: Text -> Language -> Text -> CommentId -> Handler Html
getWikiCommentAddTagR project_handle language target comment_id = do
(user@(Entity user_id _), Entity project_id _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
checkProjectCommentActionPermission can_add_tag user project_handle (Entity comment_id comment)
getProjectCommentAddTag comment_id project_id user_id
--------------------------------------------------------------------------------
-- /unclaim
getUnclaimWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getUnclaimWikiCommentR project_handle language target comment_id = do
(widget, _) <-
makeWikiPageCommentActionWidget
makeUnclaimCommentWidget
project_handle
language
target
comment_id
def
getMaxDepth
defaultLayout (wikiDiscussionPage project_handle language target widget)
postUnclaimWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
postUnclaimWikiCommentR project_handle language target comment_id = do
(user, Entity project_id _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
checkProjectCommentActionPermission can_unclaim user project_handle (Entity comment_id comment)
postUnclaimComment
user
comment_id
comment
(wikiPageCommentHandlerInfo (Just user) project_id project_handle language target)
>>= \case
Nothing -> redirect (WikiCommentR project_handle language target comment_id)
Just (widget, form) -> defaultLayout $ previewWidget form "unclaim" (wikiDiscussionPage project_handle language target widget)
--------------------------------------------------------------------------------
-- /watch
getWatchWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getWatchWikiCommentR project_handle language target comment_id = do
(widget, _) <-
makeWikiPageCommentActionWidget
makeWatchCommentWidget
project_handle
language
target
comment_id
def
getMaxDepth
defaultLayout (wikiDiscussionPage project_handle language target widget)
postWatchWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
postWatchWikiCommentR project_handle language target comment_id = do
(viewer@(Entity viewer_id _), _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
checkProjectCommentActionPermission can_watch viewer project_handle (Entity comment_id comment)
postWatchComment viewer_id comment_id
redirect (WikiCommentR project_handle language target comment_id)
--------------------------------------------------------------------------------
-- /unwatch
getUnwatchWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getUnwatchWikiCommentR project_handle language target comment_id = do
(widget, _) <-
makeWikiPageCommentActionWidget
makeUnwatchCommentWidget
project_handle
language
target
comment_id
def
getMaxDepth
defaultLayout (wikiDiscussionPage project_handle language target widget)
postUnwatchWikiCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
postUnwatchWikiCommentR project_handle language target comment_id = do
(viewer@(Entity viewer_id _), _, _, comment) <- checkCommentPageRequireAuth project_handle language target comment_id
checkProjectCommentActionPermission can_unwatch viewer project_handle (Entity comment_id comment)
postUnwatchComment viewer_id comment_id
redirect (WikiCommentR project_handle language target comment_id)
--------------------------------------------------------------------------------
-- DEPRECATED
-- This is just because we used to have "/comment/#" with that longer URL,
-- and this keeps any permalinks from breaking
getOldDiscussCommentR :: Text -> Language -> Text -> CommentId -> Handler Html
getOldDiscussCommentR project_handle language target comment_id = redirect $ WikiCommentR project_handle language target comment_id
| chreekat/snowdrift | Handler/Wiki/Comment.hs | agpl-3.0 | 22,938 | 0 | 19 | 4,877 | 4,779 | 2,381 | 2,398 | -1 | -1 |
module Main where
main :: IO ()
main = putStrLn "Hello, World!"
| nixdog/helloworld | haskell.hs | apache-2.0 | 69 | 0 | 6 | 17 | 22 | 12 | 10 | 3 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude, AutoDeriveTypeable, MagicHash,
ExistentialQuantification #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.Exception
-- Copyright : (c) The University of Glasgow, 2009
-- License : see libraries/base/LICENSE
--
-- Maintainer : libraries@haskell.org
-- Stability : internal
-- Portability : non-portable
--
-- IO-related Exception types and functions
--
-----------------------------------------------------------------------------
module GHC.IO.Exception (
BlockedIndefinitelyOnMVar(..), blockedIndefinitelyOnMVar,
BlockedIndefinitelyOnSTM(..), blockedIndefinitelyOnSTM,
Deadlock(..),
AllocationLimitExceeded(..), allocationLimitExceeded,
AssertionFailed(..),
SomeAsyncException(..),
asyncExceptionToException, asyncExceptionFromException,
AsyncException(..), stackOverflow, heapOverflow,
ArrayException(..),
ExitCode(..),
ioException,
ioError,
IOError,
IOException(..),
IOErrorType(..),
userError,
assertError,
unsupportedOperation,
untangle,
) where
import GHC.Base
import GHC.List
import GHC.IO
import GHC.Show
import GHC.Read
import GHC.Exception
import GHC.IO.Handle.Types
import Foreign.C.Types
import Data.Typeable ( Typeable, cast )
-- ------------------------------------------------------------------------
-- Exception datatypes and operations
-- |The thread is blocked on an @MVar@, but there are no other references
-- to the @MVar@ so it can't ever continue.
data BlockedIndefinitelyOnMVar = BlockedIndefinitelyOnMVar
deriving Typeable
instance Exception BlockedIndefinitelyOnMVar
instance Show BlockedIndefinitelyOnMVar where
showsPrec _ BlockedIndefinitelyOnMVar = showString "thread blocked indefinitely in an MVar operation"
blockedIndefinitelyOnMVar :: SomeException -- for the RTS
blockedIndefinitelyOnMVar = toException BlockedIndefinitelyOnMVar
-----
-- |The thread is waiting to retry an STM transaction, but there are no
-- other references to any @TVar@s involved, so it can't ever continue.
data BlockedIndefinitelyOnSTM = BlockedIndefinitelyOnSTM
deriving Typeable
instance Exception BlockedIndefinitelyOnSTM
instance Show BlockedIndefinitelyOnSTM where
showsPrec _ BlockedIndefinitelyOnSTM = showString "thread blocked indefinitely in an STM transaction"
blockedIndefinitelyOnSTM :: SomeException -- for the RTS
blockedIndefinitelyOnSTM = toException BlockedIndefinitelyOnSTM
-----
-- |There are no runnable threads, so the program is deadlocked.
-- The @Deadlock@ exception is raised in the main thread only.
data Deadlock = Deadlock
deriving Typeable
instance Exception Deadlock
instance Show Deadlock where
showsPrec _ Deadlock = showString "<<deadlock>>"
-----
-- |This thread has exceeded its allocation limit. See
-- 'GHC.Conc.setAllocationCounter' and
-- 'GHC.Conc.enableAllocationLimit'.
--
-- @since 4.8.0.0
data AllocationLimitExceeded = AllocationLimitExceeded
deriving Typeable
instance Exception AllocationLimitExceeded
instance Show AllocationLimitExceeded where
showsPrec _ AllocationLimitExceeded =
showString "allocation limit exceeded"
allocationLimitExceeded :: SomeException -- for the RTS
allocationLimitExceeded = toException AllocationLimitExceeded
-----
-- |'assert' was applied to 'False'.
data AssertionFailed = AssertionFailed String
deriving Typeable
instance Exception AssertionFailed
instance Show AssertionFailed where
showsPrec _ (AssertionFailed err) = showString err
-----
-- |Superclass for asynchronous exceptions.
--
-- @since 4.7.0.0
data SomeAsyncException = forall e . Exception e => SomeAsyncException e
deriving Typeable
instance Show SomeAsyncException where
show (SomeAsyncException e) = show e
instance Exception SomeAsyncException
-- |@since 4.7.0.0
asyncExceptionToException :: Exception e => e -> SomeException
asyncExceptionToException = toException . SomeAsyncException
-- |@since 4.7.0.0
asyncExceptionFromException :: Exception e => SomeException -> Maybe e
asyncExceptionFromException x = do
SomeAsyncException a <- fromException x
cast a
-- |Asynchronous exceptions.
data AsyncException
= StackOverflow
-- ^The current thread\'s stack exceeded its limit.
-- Since an exception has been raised, the thread\'s stack
-- will certainly be below its limit again, but the
-- programmer should take remedial action
-- immediately.
| HeapOverflow
-- ^The program\'s heap is reaching its limit, and
-- the program should take action to reduce the amount of
-- live data it has. Notes:
--
-- * It is undefined which thread receives this exception.
--
-- * GHC currently does not throw 'HeapOverflow' exceptions.
| ThreadKilled
-- ^This exception is raised by another thread
-- calling 'Control.Concurrent.killThread', or by the system
-- if it needs to terminate the thread for some
-- reason.
| UserInterrupt
-- ^This exception is raised by default in the main thread of
-- the program when the user requests to terminate the program
-- via the usual mechanism(s) (e.g. Control-C in the console).
deriving (Eq, Ord, Typeable)
instance Exception AsyncException where
toException = asyncExceptionToException
fromException = asyncExceptionFromException
-- | Exceptions generated by array operations
data ArrayException
= IndexOutOfBounds String
-- ^An attempt was made to index an array outside
-- its declared bounds.
| UndefinedElement String
-- ^An attempt was made to evaluate an element of an
-- array that had not been initialized.
deriving (Eq, Ord, Typeable)
instance Exception ArrayException
-- for the RTS
stackOverflow, heapOverflow :: SomeException
stackOverflow = toException StackOverflow
heapOverflow = toException HeapOverflow
instance Show AsyncException where
showsPrec _ StackOverflow = showString "stack overflow"
showsPrec _ HeapOverflow = showString "heap overflow"
showsPrec _ ThreadKilled = showString "thread killed"
showsPrec _ UserInterrupt = showString "user interrupt"
instance Show ArrayException where
showsPrec _ (IndexOutOfBounds s)
= showString "array index out of range"
. (if not (null s) then showString ": " . showString s
else id)
showsPrec _ (UndefinedElement s)
= showString "undefined array element"
. (if not (null s) then showString ": " . showString s
else id)
-- -----------------------------------------------------------------------------
-- The ExitCode type
-- We need it here because it is used in ExitException in the
-- Exception datatype (above).
-- | Defines the exit codes that a program can return.
data ExitCode
= ExitSuccess -- ^ indicates successful termination;
| ExitFailure Int
-- ^ indicates program failure with an exit code.
-- The exact interpretation of the code is
-- operating-system dependent. In particular, some values
-- may be prohibited (e.g. 0 on a POSIX-compliant system).
deriving (Eq, Ord, Read, Show, Typeable)
instance Exception ExitCode
ioException :: IOException -> IO a
ioException err = throwIO err
-- | Raise an 'IOError' in the 'IO' monad.
ioError :: IOError -> IO a
ioError = ioException
-- ---------------------------------------------------------------------------
-- IOError type
-- | The Haskell 2010 type for exceptions in the 'IO' monad.
-- Any I\/O operation may raise an 'IOError' instead of returning a result.
-- For a more general type of exception, including also those that arise
-- in pure code, see "Control.Exception.Exception".
--
-- In Haskell 2010, this is an opaque type.
type IOError = IOException
-- |Exceptions that occur in the @IO@ monad.
-- An @IOException@ records a more specific error type, a descriptive
-- string and maybe the handle that was used when the error was
-- flagged.
data IOException
= IOError {
ioe_handle :: Maybe Handle, -- the handle used by the action flagging
-- the error.
ioe_type :: IOErrorType, -- what it was.
ioe_location :: String, -- location.
ioe_description :: String, -- error type specific information.
ioe_errno :: Maybe CInt, -- errno leading to this error, if any.
ioe_filename :: Maybe FilePath -- filename the error is related to.
}
deriving Typeable
instance Exception IOException
instance Eq IOException where
(IOError h1 e1 loc1 str1 en1 fn1) == (IOError h2 e2 loc2 str2 en2 fn2) =
e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && en1==en2 && fn1==fn2
-- | An abstract type that contains a value for each variant of 'IOError'.
data IOErrorType
-- Haskell 2010:
= AlreadyExists
| NoSuchThing
| ResourceBusy
| ResourceExhausted
| EOF
| IllegalOperation
| PermissionDenied
| UserError
-- GHC only:
| UnsatisfiedConstraints
| SystemError
| ProtocolError
| OtherError
| InvalidArgument
| InappropriateType
| HardwareFault
| UnsupportedOperation
| TimeExpired
| ResourceVanished
| Interrupted
instance Eq IOErrorType where
x == y = isTrue# (getTag x ==# getTag y)
instance Show IOErrorType where
showsPrec _ e =
showString $
case e of
AlreadyExists -> "already exists"
NoSuchThing -> "does not exist"
ResourceBusy -> "resource busy"
ResourceExhausted -> "resource exhausted"
EOF -> "end of file"
IllegalOperation -> "illegal operation"
PermissionDenied -> "permission denied"
UserError -> "user error"
HardwareFault -> "hardware fault"
InappropriateType -> "inappropriate type"
Interrupted -> "interrupted"
InvalidArgument -> "invalid argument"
OtherError -> "failed"
ProtocolError -> "protocol error"
ResourceVanished -> "resource vanished"
SystemError -> "system error"
TimeExpired -> "timeout"
UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
UnsupportedOperation -> "unsupported operation"
-- | Construct an 'IOError' value with a string describing the error.
-- The 'fail' method of the 'IO' instance of the 'Monad' class raises a
-- 'userError', thus:
--
-- > instance Monad IO where
-- > ...
-- > fail s = ioError (userError s)
--
userError :: String -> IOError
userError str = IOError Nothing UserError "" str Nothing Nothing
-- ---------------------------------------------------------------------------
-- Showing IOErrors
instance Show IOException where
showsPrec p (IOError hdl iot loc s _ fn) =
(case fn of
Nothing -> case hdl of
Nothing -> id
Just h -> showsPrec p h . showString ": "
Just name -> showString name . showString ": ") .
(case loc of
"" -> id
_ -> showString loc . showString ": ") .
showsPrec p iot .
(case s of
"" -> id
_ -> showString " (" . showString s . showString ")")
-- Note the use of "lazy". This means that
-- assert False (throw e)
-- will throw the assertion failure rather than e. See trac #5561.
assertError :: Addr# -> Bool -> a -> a
assertError str predicate v
| predicate = lazy v
| otherwise = throw (AssertionFailed (untangle str "Assertion failed"))
unsupportedOperation :: IOError
unsupportedOperation =
(IOError Nothing UnsupportedOperation ""
"Operation is not supported" Nothing Nothing)
{-
(untangle coded message) expects "coded" to be of the form
"location|details"
It prints
location message details
-}
untangle :: Addr# -> String -> String
untangle coded message
= location
++ ": "
++ message
++ details
++ "\n"
where
coded_str = unpackCStringUtf8# coded
(location, details)
= case (span not_bar coded_str) of { (loc, rest) ->
case rest of
('|':det) -> (loc, ' ' : det)
_ -> (loc, "")
}
not_bar c = c /= '|'
| green-haskell/ghc | libraries/base/GHC/IO/Exception.hs | bsd-3-clause | 12,430 | 0 | 17 | 2,768 | 1,869 | 1,043 | 826 | 214 | 2 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash, ImplicitParams #-}
{-# LANGUAGE RankNTypes, PolyKinds, DataKinds #-}
{-# OPTIONS_HADDOCK not-home #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Err
-- Copyright : (c) The University of Glasgow, 1994-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC extensions)
--
-- The "GHC.Err" module defines the code for the wired-in error functions,
-- which have a special type in the compiler (with \"open tyvars\").
--
-- We cannot define these functions in a module where they might be used
-- (e.g., "GHC.Base"), because the magical wired-in type will get confused
-- with what the typechecker figures out.
--
-----------------------------------------------------------------------------
module GHC.Err( absentErr, error, errorWithoutStackTrace, undefined ) where
import GHC.Types (Char, RuntimeRep)
import GHC.Stack.Types
import GHC.Prim
import GHC.Integer () -- Make sure Integer and Natural are compiled first
import GHC.Natural () -- because GHC depends on it in a wired-in way
-- so the build system doesn't see the dependency.
-- See Note [Depend on GHC.Integer] and
-- Note [Depend on GHC.Natural] in GHC.Base.
import {-# SOURCE #-} GHC.Exception
( errorCallWithCallStackException
, errorCallException )
-- | 'error' stops execution and displays an error message.
error :: forall (r :: RuntimeRep). forall (a :: TYPE r).
HasCallStack => [Char] -> a
error s = raise# (errorCallWithCallStackException s ?callStack)
-- Bleh, we should be using 'GHC.Stack.callStack' instead of
-- '?callStack' here, but 'GHC.Stack.callStack' depends on
-- 'GHC.Stack.popCallStack', which is partial and depends on
-- 'error'.. Do as I say, not as I do.
-- | A variant of 'error' that does not produce a stack trace.
--
-- @since 4.9.0.0
errorWithoutStackTrace :: forall (r :: RuntimeRep). forall (a :: TYPE r).
[Char] -> a
errorWithoutStackTrace s = raise# (errorCallException s)
-- Note [Errors in base]
-- ~~~~~~~~~~~~~~~~~~~~~
-- As of base-4.9.0.0, `error` produces a stack trace alongside the
-- error message using the HasCallStack machinery. This provides
-- a partial stack trace, containing the call-site of each function
-- with a HasCallStack constraint.
--
-- In base, however, the only functions that have such constraints are
-- error and undefined, so the stack traces from partial functions in
-- base will never contain a call-site in user code. Instead we'll
-- usually just get the actual call to error. Base functions already
-- have a good habit of providing detailed error messages, including the
-- name of the offending partial function, so the partial stack-trace
-- does not provide any extra information, just noise. Thus, we export
-- the callstack-aware error, but within base we use the
-- errorWithoutStackTrace variant for more hygienic error messages.
-- | A special case of 'error'.
-- It is expected that compilers will recognize this and insert error
-- messages which are more appropriate to the context in which 'undefined'
-- appears.
undefined :: forall (r :: RuntimeRep). forall (a :: TYPE r).
HasCallStack => a
undefined = error "Prelude.undefined"
-- | Used for compiler-generated error message;
-- encoding saves bytes of string junk.
absentErr :: a
absentErr = errorWithoutStackTrace "Oops! The program has entered an `absent' argument!\n"
| sdiehl/ghc | libraries/base/GHC/Err.hs | bsd-3-clause | 3,686 | 0 | 9 | 716 | 302 | 198 | 104 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.RDS.CreateOptionGroup
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Creates a new option group. You can create up to 20 option groups.
--
-- <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateOptionGroup.html>
module Network.AWS.RDS.CreateOptionGroup
(
-- * Request
CreateOptionGroup
-- ** Request constructor
, createOptionGroup
-- ** Request lenses
, cogEngineName
, cogMajorEngineVersion
, cogOptionGroupDescription
, cogOptionGroupName
, cogTags
-- * Response
, CreateOptionGroupResponse
-- ** Response constructor
, createOptionGroupResponse
-- ** Response lenses
, cogr1OptionGroup
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.RDS.Types
import qualified GHC.Exts
data CreateOptionGroup = CreateOptionGroup
{ _cogEngineName :: Text
, _cogMajorEngineVersion :: Text
, _cogOptionGroupDescription :: Text
, _cogOptionGroupName :: Text
, _cogTags :: List "member" Tag
} deriving (Eq, Read, Show)
-- | 'CreateOptionGroup' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cogEngineName' @::@ 'Text'
--
-- * 'cogMajorEngineVersion' @::@ 'Text'
--
-- * 'cogOptionGroupDescription' @::@ 'Text'
--
-- * 'cogOptionGroupName' @::@ 'Text'
--
-- * 'cogTags' @::@ ['Tag']
--
createOptionGroup :: Text -- ^ 'cogOptionGroupName'
-> Text -- ^ 'cogEngineName'
-> Text -- ^ 'cogMajorEngineVersion'
-> Text -- ^ 'cogOptionGroupDescription'
-> CreateOptionGroup
createOptionGroup p1 p2 p3 p4 = CreateOptionGroup
{ _cogOptionGroupName = p1
, _cogEngineName = p2
, _cogMajorEngineVersion = p3
, _cogOptionGroupDescription = p4
, _cogTags = mempty
}
-- | Specifies the name of the engine that this option group should be associated
-- with.
cogEngineName :: Lens' CreateOptionGroup Text
cogEngineName = lens _cogEngineName (\s a -> s { _cogEngineName = a })
-- | Specifies the major version of the engine that this option group should be
-- associated with.
cogMajorEngineVersion :: Lens' CreateOptionGroup Text
cogMajorEngineVersion =
lens _cogMajorEngineVersion (\s a -> s { _cogMajorEngineVersion = a })
-- | The description of the option group.
cogOptionGroupDescription :: Lens' CreateOptionGroup Text
cogOptionGroupDescription =
lens _cogOptionGroupDescription
(\s a -> s { _cogOptionGroupDescription = a })
-- | Specifies the name of the option group to be created.
--
-- Constraints:
--
-- Must be 1 to 255 alphanumeric characters or hyphens First character must be
-- a letter Cannot end with a hyphen or contain two consecutive hyphens Example:
-- 'myoptiongroup'
cogOptionGroupName :: Lens' CreateOptionGroup Text
cogOptionGroupName =
lens _cogOptionGroupName (\s a -> s { _cogOptionGroupName = a })
cogTags :: Lens' CreateOptionGroup [Tag]
cogTags = lens _cogTags (\s a -> s { _cogTags = a }) . _List
newtype CreateOptionGroupResponse = CreateOptionGroupResponse
{ _cogr1OptionGroup :: Maybe OptionGroup
} deriving (Eq, Read, Show)
-- | 'CreateOptionGroupResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cogr1OptionGroup' @::@ 'Maybe' 'OptionGroup'
--
createOptionGroupResponse :: CreateOptionGroupResponse
createOptionGroupResponse = CreateOptionGroupResponse
{ _cogr1OptionGroup = Nothing
}
cogr1OptionGroup :: Lens' CreateOptionGroupResponse (Maybe OptionGroup)
cogr1OptionGroup = lens _cogr1OptionGroup (\s a -> s { _cogr1OptionGroup = a })
instance ToPath CreateOptionGroup where
toPath = const "/"
instance ToQuery CreateOptionGroup where
toQuery CreateOptionGroup{..} = mconcat
[ "EngineName" =? _cogEngineName
, "MajorEngineVersion" =? _cogMajorEngineVersion
, "OptionGroupDescription" =? _cogOptionGroupDescription
, "OptionGroupName" =? _cogOptionGroupName
, "Tags" =? _cogTags
]
instance ToHeaders CreateOptionGroup
instance AWSRequest CreateOptionGroup where
type Sv CreateOptionGroup = RDS
type Rs CreateOptionGroup = CreateOptionGroupResponse
request = post "CreateOptionGroup"
response = xmlResponse
instance FromXML CreateOptionGroupResponse where
parseXML = withElement "CreateOptionGroupResult" $ \x -> CreateOptionGroupResponse
<$> x .@? "OptionGroup"
| romanb/amazonka | amazonka-rds/gen/Network/AWS/RDS/CreateOptionGroup.hs | mpl-2.0 | 5,530 | 0 | 10 | 1,265 | 703 | 428 | 275 | 84 | 1 |
{-# OPTIONS_GHC -funbox-strict-fields #-}
module RestyScript.Emitter.Stats (
Stats,
emit,
emitJSON
) where
import RestyScript.AST
import Text.JSON
data Stats = Stats {
modelList :: ![String], funcList :: ![String],
selectedMax :: !Int, joinedMax :: !Int,
comparedCount :: !Int, queryCount :: !Int }
deriving (Ord, Eq, Show)
instance JSON Stats where
showJSON st =
JSObject $ toJSObject [
("modelList", showList $ modelList st),
("funcList", showList $ funcList st),
("selectedMax", showJSON $ selectedMax st),
("joinedMax", showJSON $ joinedMax st),
("comparedCount", showJSON $ comparedCount st),
("queryCount", showJSON $ queryCount st)]
where showList = JSArray . map showJSON
readJSON = undefined
si = Stats {
modelList = [], funcList = [],
selectedMax = 0, joinedMax = 0,
comparedCount = 0, queryCount = 0 }
findModel :: RSVal -> Stats -> Stats
findModel (Model (Symbol n)) st = st { modelList = [n] }
findModel (Model (Variable _ n)) st = st { modelList = ['$':n] }
findModel _ st = st
findFunc :: RSVal -> Stats -> Stats
findFunc (FuncCall (Symbol func) _) st = st { funcList = func : (funcList st) }
findFunc (FuncCall (Variable _ func) _) st = st { funcList = ('$':func) : (funcList st) }
findFunc _ st = st
findSelected :: RSVal -> Stats -> Stats
findSelected (Select lst) st = st { selectedMax = length lst }
findSelected _ st = st
findJoined :: RSVal -> Stats -> Stats
findJoined (From lst) st = st { joinedMax = length lst }
findJoined _ st = st
findQuery :: RSVal -> Stats -> Stats
findQuery (Query _) st = st { queryCount = 1 }
findQuery _ st = st
findCompared :: RSVal -> Stats -> Stats
findCompared (Compare _ _ _) st = st { comparedCount = 1 }
findCompared _ st = st
visit :: RSVal -> Stats
visit node = foldr (\f st -> f node st) si
[findModel, findFunc,
findSelected, findJoined, findCompared, findQuery]
merge :: Stats -> Stats -> Stats
merge a b = Stats {
modelList = (modelList a) ++ (modelList b),
funcList = (funcList a) ++ (funcList b),
selectedMax = max (selectedMax a) (selectedMax b),
joinedMax = max (joinedMax a) (joinedMax b),
comparedCount = comparedCount a + comparedCount b,
queryCount = queryCount a + queryCount b }
emit :: RSVal -> Stats
emit = traverse visit merge
emitJSON :: RSVal -> String
emitJSON = encode . emit
| beni55/old-openresty | haskell/src/RestyScript/Emitter/Stats.hs | bsd-3-clause | 2,506 | 0 | 11 | 643 | 936 | 510 | 426 | 75 | 1 |
{- $Id: AFRPTestsSwitch.hs,v 1.2 2003/11/10 21:28:58 antony Exp $
******************************************************************************
* A F R P *
* *
* Module: AFRPTestsSwitch *
* Purpose: Test cases for switch *
* Authors: Antony Courtney and Henrik Nilsson *
* *
* Copyright (c) Yale University, 2003 *
* *
******************************************************************************
-}
module AFRPTestsSwitch (switch_tr, switch_trs) where
import FRP.Yampa
import FRP.Yampa.EventS
import FRP.Yampa.Internals (Event(NoEvent, Event))
import AFRPTestsCommon
------------------------------------------------------------------------------
-- Test cases for switch and dSwitch
------------------------------------------------------------------------------
switch_inp1 = deltaEncode 1.0 $
[1.0, 1.0, 1.0,
2.0,
3.0, 3.0,
4.0, 4.0, 4.0,
5.0,
6.0, 6.0,
7.0, 7.0, 7.0,
8.0]
++ repeat 9.0
switch_t0 = take 18 $
embed (switch switch_t0a $ \x ->
switch (switch_t0b x) $ \x ->
switch (switch_t0c x) $ \x ->
switch (switch_t0c x) $ \x ->
switch (switch_t0d x) $ \x ->
switch (switch_t0e x) $ \x ->
switch (switch_t0e x) $
switch_t0final)
switch_inp1
switch_t0a :: SF Double (Double, Event Int)
switch_t0a = localTime
>>> arr dup
>>> second (arr (>= 3.0) >>> edge >>> arr (`tag` 17))
switch_t0b :: Int -> SF Double (Double, Event Int)
switch_t0b x = localTime
>>> arr dup
>>> second (arr (>= 3.0) >>> edge >>> arr (`tag` (23 + x)))
-- This should raise an event IMMEDIATELY: no time should pass.
switch_t0c :: Num b => b -> SF a (a, Event b)
switch_t0c x = arr dup >>> second (now (x + 1))
switch_t0d x = (arr (+ (fromIntegral x))) &&& (arr (>= 7.0) >>> edge)
-- This should raise an event IMMEDIATELY: no time should pass.
switch_t0e :: b -> SF a (a, Event a)
switch_t0e _ = arr dup >>> second snap
switch_t0final :: Double -> SF Double Double
switch_t0final x = arr (+x)
switch_t0r =
[0.0, 1.0, 2.0, -- switch_t0a
0.0, 1.0, 2.0, -- switch_t0b
46.0, 46.0, 46.0, 47.0, 48.0, 48.0, -- switch_t0d
14.0, 14.0, 14.0, 15.0, 16.0, 16.0 -- switch_t0final
]
switch_t1 = take 32 $ embed (switch_t1rec 42.0) switch_inp1
-- Outputs current input, local time, and the value of the initializing
-- argument until some time has passed (determined by integrating a constant),
-- at which point an event occurs.
switch_t1a :: Double -> SF Double ((Double,Double,Double), Event ())
switch_t1a x = (arr dup >>> second localTime >>> arr (\(a,t) -> (a,t,x)))
&&& (constant 0.5
>>> integral
>>> (arr (>= (2.0 :: Double)) -- Used to work with no sig.
>>> edge))
-- This should raise an event IMMEDIATELY: no time should pass.
switch_t1b :: b -> SF a ((Double,Double,Double), Event a)
switch_t1b _ = constant (-999.0,-999.0,-999.0) &&& snap
switch_t1rec :: Double -> SF Double (Double,Double,Double)
switch_t1rec x =
switch (switch_t1a x) $ \x ->
switch (switch_t1b x) $ \x ->
switch (switch_t1b x) $
switch_t1rec
switch_t1r =
[(1.0,0.0,42.0), (1.0,1.0,42.0), (1.0,2.0,42.0), (2.0,3.0,42.0),
(3.0,0.0,3.0), (3.0,1.0,3.0), (4.0,2.0,3.0), (4.0,3.0,3.0),
(4.0,0.0,4.0), (5.0,1.0,4.0), (6.0,2.0,4.0), (6.0,3.0,4.0),
(7.0,0.0,7.0), (7.0,1.0,7.0), (7.0,2.0,7.0), (8.0,3.0,7.0),
(9.0,0.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0),
(9.0,0.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0),
(9.0,0.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0),
(9.0,0.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0)]
switch_t2 = take 18 $
embed (dSwitch switch_t0a $ \x ->
dSwitch (switch_t0b x) $ \x ->
dSwitch (switch_t0c x) $ \x ->
dSwitch (switch_t0c x) $ \x ->
dSwitch (switch_t0d x) $ \x ->
dSwitch (switch_t0e x) $ \x ->
dSwitch (switch_t0e x) $
switch_t0final)
switch_inp1
switch_t2r =
[0.0, 1.0, 2.0, -- switch_t0a
3.0, 1.0, 2.0, -- switch_t0b
3.0, 46.0, 46.0, 47.0, 48.0, 48.0, -- switch_t0d
49.0, 14.0, 14.0, 15.0, 16.0, 16.0 -- switch_t0final
]
switch_t3 = take 32 $ embed (switch_t3rec 42.0) switch_inp1
switch_t3rec :: Double -> SF Double (Double,Double,Double)
switch_t3rec x =
dSwitch (switch_t1a x) $ \x ->
dSwitch (switch_t1b x) $ \x ->
dSwitch (switch_t1b x) $
switch_t3rec
switch_t3r =
[(1.0,0.0,42.0), (1.0,1.0,42.0), (1.0,2.0,42.0), (2.0,3.0,42.0),
(3.0,4.0,42.0), (3.0,1.0,3.0), (4.0,2.0,3.0), (4.0,3.0,3.0),
(4.0,4.0,3.0), (5.0,1.0,4.0), (6.0,2.0,4.0), (6.0,3.0,4.0),
(7.0,4.0,4.0), (7.0,1.0,7.0), (7.0,2.0,7.0), (8.0,3.0,7.0),
(9.0,4.0,7.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0),
(9.0,4.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0),
(9.0,4.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0),
(9.0,4.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0)]
-- The correct strictness properties of dSwitch are crucial here.
-- switch does not work.
switch_t4 = take 25 $
embed (loop $
dSwitch switch_t4a $ \_ ->
dSwitch switch_t4a $ \_ ->
dSwitch switch_t4a $ \_ ->
switch_t4final
)
(deltaEncode 1.0 (repeat ()))
switch_t4a :: SF (a, Double) ((Double, Double), Event ())
switch_t4a = (constant 1.0 >>> integral >>> arr dup)
&&& (arr (\ (_, x) -> x >= 5.0) >>> edge)
switch_t4final :: SF (a, Double) (Double, Double)
switch_t4final = constant 0.1 >>> integral >>> arr dup
switch_t4r =
[0.0, 1.0, 2.0, 3.0, 4.0, -- switch_t4a
5.0, 1.0, 2.0, 3.0, 4.0, -- switch_t4a
5.0, 1.0, 2.0, 3.0, 4.0, -- switch_t4a
5.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 -- switch_t4final
]
impulseIntegral2 :: VectorSpace a s => SF (a, Event a) a
impulseIntegral2 =
switch (first integral >>> arr (\(a, ea) -> (a, fmap (^+^ a) ea)))
impulseIntegral2'
where
impulseIntegral2' :: VectorSpace a s => a -> SF (a, Event a) a
impulseIntegral2' a =
switch ((integral >>> arr (^+^ a)) *** notYet
>>> arr (\(a, ea) -> (a, fmap (^+^ a) ea)))
impulseIntegral2'
switch_t5 :: [Double]
switch_t5 = take 50 $ embed impulseIntegral2
(deltaEncode 0.1 (zip (repeat 1.0) evSeq))
where
evSeq = replicate 9 NoEvent ++ [Event 10.0]
++ replicate 9 NoEvent ++ [Event (-10.0)]
++ evSeq
switch_t5r =
[ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 10.9,
11.0, 11.1, 11.2, 11.3, 11.4, 11.5, 11.6, 11.7, 11.8, 1.9,
2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 12.9,
13.0, 13.1, 13.2, 13.3, 13.4, 13.5, 13.6, 13.7, 13.8, 3.9,
4.0, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 14.9]
switch_trs =
[ switch_t0 ~= switch_t0r,
switch_t1 ~= switch_t1r,
switch_t2 ~= switch_t2r,
switch_t3 ~= switch_t3r,
switch_t4 ~= switch_t4r,
switch_t5 ~= switch_t5r
]
switch_tr = and switch_trs
| meimisaki/Yampa | tests/AFRPTestsSwitch.hs | bsd-3-clause | 7,509 | 30 | 23 | 2,115 | 2,814 | 1,654 | 1,160 | 146 | 1 |
-------------------------------------------------------------------------
--
-- QCStoreTest.hs
--
-- QuickCheck tests for stores. --
-- (c) Addison-Wesley, 1996-2011.
--
-------------------------------------------------------------------------
module QCStoreTest where
import StoreTest
import Test.QuickCheck
prop_Update1 :: Char -> Integer -> Store -> Bool
prop_Update1 ch int st =
value (update st ch int) ch == int
prop_Update2 :: Char -> Char -> Integer -> Store -> Bool
prop_Update2 ch1 ch2 int st =
ch1 == ch2 || value (update st ch2 int) ch1 == value st ch1
prop_Initial :: Char -> Bool
prop_Initial ch =
value initial ch == 0
| c089/haskell-craft3e | Chapter16/QCStoreTest.hs | mit | 707 | 0 | 9 | 163 | 161 | 86 | 75 | 12 | 1 |
{-# LANGUAGE PatternGuards, CPP, ForeignFunctionInterface #-}
-----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2004-2009.
--
-- Package management tool
--
-----------------------------------------------------------------------------
module HastePkg708 (main) where
import Distribution.InstalledPackageInfo.Binary()
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.ModuleName hiding (main)
import Distribution.InstalledPackageInfo
import Distribution.Compat.ReadP
import Distribution.ParseUtils
import Distribution.Package hiding (depends)
import Distribution.Text
import Distribution.Version
import System.FilePath as FilePath
import qualified System.FilePath.Posix as FilePath.Posix
import System.Process
import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing,
getModificationTime )
import Text.Printf
import Prelude
import System.Console.GetOpt
import qualified Control.Exception as Exception
import Data.Maybe
import Data.Char ( isSpace, toLower )
import Data.Ord (comparing)
import Control.Applicative (Applicative(..))
import Control.Monad
import System.Directory ( doesDirectoryExist, getDirectoryContents,
doesFileExist, renameFile, removeFile,
getCurrentDirectory )
import System.Exit ( exitWith, ExitCode(..) )
import System.Environment ( getArgs, getProgName, getEnv )
import System.IO
import System.IO.Error
import Data.List
import Control.Concurrent
import qualified Data.ByteString.Lazy as B
import qualified Data.Binary as Bin
import qualified Data.Binary.Get as Bin
-- Haste-specific
import Haste.Environment
import Haste.Version
import System.Info (os)
import qualified Control.Shell as Sh
#if defined(mingw32_HOST_OS)
-- mingw32 needs these for getExecDir
import Foreign
import Foreign.C
#endif
#ifdef mingw32_HOST_OS
import GHC.ConsoleHandler
#else
import System.Posix hiding (fdToHandle)
#endif
#if defined(GLOB)
import qualified System.Info(os)
#endif
#if !defined(mingw32_HOST_OS) && !defined(BOOTSTRAPPING)
import System.Console.Terminfo as Terminfo
#endif
#ifdef mingw32_HOST_OS
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# else
# error Unknown mingw32 arch
# endif
#endif
-- -----------------------------------------------------------------------------
-- Entry point
main :: IO ()
main = do
args <- getArgs
case args of
["relocate", pkg] -> do
Sh.shell (relocate packages pkg) >> exitWith ExitSuccess
_ ->
return ()
case getOpt Permute (flags ++ deprecFlags) args of
(cli,_,[]) | FlagHelp `elem` cli -> do
prog <- getProgramName
bye (usageInfo (usageHeader prog) flags)
(cli,_,[]) | FlagVersion `elem` cli ->
bye ourCopyright
(cli,_,[]) | FlagNumericVersion `elem` cli ->
bye $ showVersion hasteVersion ++ "\n"
(cli,_,[]) | FlagNumericGhcVersion `elem` cli ->
bye $ showVersion ghcVersion ++ "\n"
(cli,nonopts,[]) ->
case getVerbosity Normal cli of
Right v -> runit v cli nonopts
Left err -> die err
(_,_,errors) -> do
prog <- getProgramName
die (concat errors ++ shortUsage prog)
where
packages = ["--global-package-db=" ++ pkgSysDir,
"--package-db=" ++ pkgSysDir,
"--package-db=" ++ pkgUserDir]
-- -----------------------------------------------------------------------------
-- Command-line syntax
data Flag
= FlagUser
| FlagGlobal
| FlagHelp
| FlagVersion
| FlagNumericVersion
| FlagNumericGhcVersion
| FlagConfig FilePath
| FlagGlobalConfig FilePath
| FlagForce
| FlagForceFiles
| FlagAutoGHCiLibs
| FlagExpandEnvVars
| FlagExpandPkgroot
| FlagNoExpandPkgroot
| FlagSimpleOutput
| FlagNamesOnly
| FlagIgnoreCase
| FlagNoUserDb
| FlagVerbosity (Maybe String)
deriving Eq
flags :: [OptDescr Flag]
flags = [
Option [] ["user"] (NoArg FlagUser)
"use the current user's package database",
Option [] ["global"] (NoArg FlagGlobal)
"use the global package database",
Option ['f'] ["package-db"] (ReqArg FlagConfig "FILE/DIR")
"use the specified package database",
Option [] ["package-conf"] (ReqArg FlagConfig "FILE/DIR")
"use the specified package database (DEPRECATED)",
Option [] ["global-package-db"] (ReqArg FlagGlobalConfig "DIR")
"location of the global package database",
Option [] ["no-user-package-db"] (NoArg FlagNoUserDb)
"never read the user package database",
Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
"never read the user package database (DEPRECATED)",
Option [] ["force"] (NoArg FlagForce)
"ignore missing dependencies, directories, and libraries",
Option [] ["force-files"] (NoArg FlagForceFiles)
"ignore missing directories and libraries only",
Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
"automatically build libs for GHCi (with register)",
Option [] ["expand-env-vars"] (NoArg FlagExpandEnvVars)
"expand environment variables (${name}-style) in input package descriptions",
Option [] ["expand-pkgroot"] (NoArg FlagExpandPkgroot)
"expand ${pkgroot}-relative paths to absolute in output package descriptions",
Option [] ["no-expand-pkgroot"] (NoArg FlagNoExpandPkgroot)
"preserve ${pkgroot}-relative paths in output package descriptions",
Option ['?'] ["help"] (NoArg FlagHelp)
"display this help and exit",
Option ['V'] ["version"] (NoArg FlagVersion)
"output version information and exit",
Option [] ["numeric-version"] (NoArg FlagNumericVersion)
"output version number and exit",
Option [] ["numeric-ghc-version"] (NoArg FlagNumericGhcVersion)
"output GHC version number and exit",
Option [] ["simple-output"] (NoArg FlagSimpleOutput)
"print output in easy-to-parse format for some commands",
Option [] ["names-only"] (NoArg FlagNamesOnly)
"only print package names, not versions; can only be used with list --simple-output",
Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
"ignore case for substring matching",
Option ['v'] ["verbose"] (OptArg FlagVerbosity "Verbosity")
"verbosity level (0-2, default 1)"
]
data Verbosity = Silent | Normal | Verbose
deriving (Show, Eq, Ord)
getVerbosity :: Verbosity -> [Flag] -> Either String Verbosity
getVerbosity v [] = Right v
getVerbosity _ (FlagVerbosity Nothing : fs) = getVerbosity Verbose fs
getVerbosity _ (FlagVerbosity (Just "0") : fs) = getVerbosity Silent fs
getVerbosity _ (FlagVerbosity (Just "1") : fs) = getVerbosity Normal fs
getVerbosity _ (FlagVerbosity (Just "2") : fs) = getVerbosity Verbose fs
getVerbosity _ (FlagVerbosity v : _) = Left ("Bad verbosity: " ++ show v)
getVerbosity v (_ : fs) = getVerbosity v fs
deprecFlags :: [OptDescr Flag]
deprecFlags = [
-- put deprecated flags here
]
ourCopyright :: String
ourCopyright = "Haste package manager version " ++ showVersion hasteVersion ++ "\n"
shortUsage :: String -> String
shortUsage prog = "For usage information see '" ++ prog ++ " --help'."
usageHeader :: String -> String
usageHeader prog = substProg prog $
"Usage:\n" ++
" $p init {path}\n" ++
" Create and initialise a package database at the location {path}.\n" ++
" Packages can be registered in the new database using the register\n" ++
" command with --package-db={path}. To use the new database with GHC,\n" ++
" use GHC's -package-db flag.\n" ++
"\n" ++
" $p register {filename | -}\n" ++
" Register the package using the specified installed package\n" ++
" description. The syntax for the latter is given in the $p\n" ++
" documentation. The input file should be encoded in UTF-8.\n" ++
"\n" ++
" $p update {filename | -}\n" ++
" Register the package, overwriting any other package with the\n" ++
" same name. The input file should be encoded in UTF-8.\n" ++
"\n" ++
" $p unregister {pkg-id}\n" ++
" Unregister the specified package.\n" ++
"\n" ++
" $p expose {pkg-id}\n" ++
" Expose the specified package.\n" ++
"\n" ++
" $p hide {pkg-id}\n" ++
" Hide the specified package.\n" ++
"\n" ++
" $p trust {pkg-id}\n" ++
" Trust the specified package.\n" ++
"\n" ++
" $p distrust {pkg-id}\n" ++
" Distrust the specified package.\n" ++
"\n" ++
" $p list [pkg]\n" ++
" List registered packages in the global database, and also the\n" ++
" user database if --user is given. If a package name is given\n" ++
" all the registered versions will be listed in ascending order.\n" ++
" Accepts the --simple-output flag.\n" ++
"\n" ++
" $p dot\n" ++
" Generate a graph of the package dependencies in a form suitable\n" ++
" for input for the graphviz tools. For example, to generate a PDF" ++
" of the dependency graph: ghc-pkg dot | tred | dot -Tpdf >pkgs.pdf" ++
"\n" ++
" $p find-module {module}\n" ++
" List registered packages exposing module {module} in the global\n" ++
" database, and also the user database if --user is given.\n" ++
" All the registered versions will be listed in ascending order.\n" ++
" Accepts the --simple-output flag.\n" ++
"\n" ++
" $p latest {pkg-id}\n" ++
" Prints the highest registered version of a package.\n" ++
"\n" ++
" $p check\n" ++
" Check the consistency of package dependencies and list broken packages.\n" ++
" Accepts the --simple-output flag.\n" ++
"\n" ++
" $p describe {pkg}\n" ++
" Give the registered description for the specified package. The\n" ++
" description is returned in precisely the syntax required by $p\n" ++
" register.\n" ++
"\n" ++
" $p field {pkg} {field}\n" ++
" Extract the specified field of the package description for the\n" ++
" specified package. Accepts comma-separated multiple fields.\n" ++
"\n" ++
" $p dump\n" ++
" Dump the registered description for every package. This is like\n" ++
" \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
" by tools that parse the results, rather than humans. The output is\n" ++
" always encoded in UTF-8, regardless of the current locale.\n" ++
"\n" ++
" $p recache\n" ++
" Regenerate the package database cache. This command should only be\n" ++
" necessary if you added a package to the database by dropping a file\n" ++
" into the database directory manually. By default, the global DB\n" ++
" is recached; to recache a different DB use --user or --package-db\n" ++
" as appropriate.\n" ++
"\n" ++
" Substring matching is supported for {module} in find-module and\n" ++
" for {pkg} in list, describe, and field, where a '*' indicates\n" ++
" open substring ends (prefix*, *suffix, *infix*).\n" ++
"\n" ++
" When asked to modify a database (register, unregister, update,\n"++
" hide, expose, and also check), ghc-pkg modifies the global database by\n"++
" default. Specifying --user causes it to act on the user database,\n"++
" or --package-db can be used to act on another database\n"++
" entirely. When multiple of these options are given, the rightmost\n"++
" one is used as the database to act upon.\n"++
"\n"++
" Commands that query the package database (list, tree, latest, describe,\n"++
" field) operate on the list of databases specified by the flags\n"++
" --user, --global, and --package-db. If none of these flags are\n"++
" given, the default is --global --user.\n"++
"\n" ++
" The following optional flags are also accepted:\n"
substProg :: String -> String -> String
substProg _ [] = []
substProg prog ('$':'p':xs) = prog ++ substProg prog xs
substProg prog (c:xs) = c : substProg prog xs
-- -----------------------------------------------------------------------------
-- Do the business
data Force = NoForce | ForceFiles | ForceAll | CannotForce
deriving (Eq,Ord)
data PackageArg = Id PackageIdentifier | Substring String (String->Bool)
runit :: Verbosity -> [Flag] -> [String] -> IO ()
runit verbosity cli nonopts = do
installSignalHandlers -- catch ^C and clean up
prog <- getProgramName
let
force
| FlagForce `elem` cli = ForceAll
| FlagForceFiles `elem` cli = ForceFiles
| otherwise = NoForce
auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
expand_env_vars= FlagExpandEnvVars `elem` cli
mexpand_pkgroot= foldl' accumExpandPkgroot Nothing cli
where accumExpandPkgroot _ FlagExpandPkgroot = Just True
accumExpandPkgroot _ FlagNoExpandPkgroot = Just False
accumExpandPkgroot x _ = x
splitFields fields = unfoldr splitComma (',':fields)
where splitComma "" = Nothing
splitComma fs = Just $ break (==',') (tail fs)
substringCheck :: String -> Maybe (String -> Bool)
substringCheck "" = Nothing
substringCheck "*" = Just (const True)
substringCheck [_] = Nothing
substringCheck (h:t) =
case (h, init t, last t) of
('*',s,'*') -> Just (isInfixOf (f s) . f)
('*',_, _ ) -> Just (isSuffixOf (f t) . f)
( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
_ -> Nothing
where f | FlagIgnoreCase `elem` cli = map toLower
| otherwise = id
#if defined(GLOB)
glob x | System.Info.os=="mingw32" = do
-- glob echoes its argument, after win32 filename globbing
(_,o,_,_) <- runInteractiveCommand ("glob "++x)
txt <- hGetContents o
return (read txt)
glob x | otherwise = return [x]
#endif
--
-- first, parse the command
case nonopts of
#if defined(GLOB)
-- dummy command to demonstrate usage and permit testing
-- without messing things up; use glob to selectively enable
-- windows filename globbing for file parameters
-- register, update, FlagGlobalConfig, FlagConfig; others?
["glob", filename] -> do
print filename
glob filename >>= print
#endif
["init", filename] ->
initPackageDB filename verbosity cli
["register", filename] ->
registerPackage filename verbosity cli
auto_ghci_libs expand_env_vars False force
["update", filename] ->
registerPackage filename verbosity cli
auto_ghci_libs expand_env_vars True force
["unregister", pkgid_str] -> do
pkgid <- readGlobPkgId pkgid_str
unregisterPackage pkgid verbosity cli force
["expose", pkgid_str] -> do
pkgid <- readGlobPkgId pkgid_str
exposePackage pkgid verbosity cli force
["hide", pkgid_str] -> do
pkgid <- readGlobPkgId pkgid_str
hidePackage pkgid verbosity cli force
["trust", pkgid_str] -> do
pkgid <- readGlobPkgId pkgid_str
trustPackage pkgid verbosity cli force
["distrust", pkgid_str] -> do
pkgid <- readGlobPkgId pkgid_str
distrustPackage pkgid verbosity cli force
["list"] -> do
listPackages verbosity cli Nothing Nothing
["list", pkgid_str] ->
case substringCheck pkgid_str of
Nothing -> do pkgid <- readGlobPkgId pkgid_str
listPackages verbosity cli (Just (Id pkgid)) Nothing
Just m -> listPackages verbosity cli (Just (Substring pkgid_str m)) Nothing
["dot"] -> do
showPackageDot verbosity cli
["find-module", moduleName] -> do
let match = maybe (==moduleName) id (substringCheck moduleName)
listPackages verbosity cli Nothing (Just match)
["latest", pkgid_str] -> do
pkgid <- readGlobPkgId pkgid_str
latestPackage verbosity cli pkgid
["describe", pkgid_str] -> do
pkgarg <- case substringCheck pkgid_str of
Nothing -> liftM Id (readGlobPkgId pkgid_str)
Just m -> return (Substring pkgid_str m)
describePackage verbosity cli pkgarg (fromMaybe False mexpand_pkgroot)
["field", pkgid_str, fields] -> do
pkgarg <- case substringCheck pkgid_str of
Nothing -> liftM Id (readGlobPkgId pkgid_str)
Just m -> return (Substring pkgid_str m)
describeField verbosity cli pkgarg
(splitFields fields) (fromMaybe True mexpand_pkgroot)
["check"] -> do
checkConsistency verbosity cli
["dump"] -> do
dumpPackages verbosity cli (fromMaybe False mexpand_pkgroot)
["recache"] -> do
recache verbosity cli
[] -> do
die ("missing command\n" ++ shortUsage prog)
(_cmd:_) -> do
die ("command-line syntax error\n" ++ shortUsage prog)
parseCheck :: ReadP a a -> String -> String -> IO a
parseCheck parser str what =
case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
[x] -> return x
_ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
readGlobPkgId :: String -> IO PackageIdentifier
readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
parseGlobPackageId :: ReadP r PackageIdentifier
parseGlobPackageId =
parse
+++
(do n <- parse
_ <- string "-*"
return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
-- globVersion means "all versions"
globVersion :: Version
globVersion = Version{ versionBranch=[], versionTags=["*"] }
-- -----------------------------------------------------------------------------
-- Package databases
-- Some commands operate on a single database:
-- register, unregister, expose, hide, trust, distrust
-- however these commands also check the union of the available databases
-- in order to check consistency. For example, register will check that
-- dependencies exist before registering a package.
--
-- Some commands operate on multiple databases, with overlapping semantics:
-- list, describe, field
data PackageDB
= PackageDB {
location, locationAbsolute :: !FilePath,
-- We need both possibly-relative and definately-absolute package
-- db locations. This is because the relative location is used as
-- an identifier for the db, so it is important we do not modify it.
-- On the other hand we need the absolute path in a few places
-- particularly in relation to the ${pkgroot} stuff.
packages :: [InstalledPackageInfo]
}
type PackageDBStack = [PackageDB]
-- A stack of package databases. Convention: head is the topmost
-- in the stack.
allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
allPackagesInStack = concatMap packages
getPkgDatabases :: Verbosity
-> Bool -- we are modifying, not reading
-> Bool -- read caches, if available
-> Bool -- expand vars, like ${pkgroot} and $topdir
-> [Flag]
-> IO (PackageDBStack,
-- the real package DB stack: [global,user] ++
-- DBs specified on the command line with -f.
Maybe FilePath,
-- which one to modify, if any
PackageDBStack)
-- the package DBs specified on the command
-- line, or [global,user] otherwise. This
-- is used as the list of package DBs for
-- commands that just read the DB, such as 'list'.
getPkgDatabases verbosity modify use_cache expand_vars my_flags = do
-- first we determine the location of the global package config. On Windows,
-- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
-- location is passed to the binary using the --global-package-db flag by the
-- wrapper script.
let err_msg = "missing --global-package-db option, location of global package database unknown\n"
global_conf <-
case [ f | FlagGlobalConfig f <- my_flags ] of
[] -> do mb_dir <- getLibDir
case mb_dir of
Nothing -> die err_msg
Just dir -> do
r <- lookForPackageDBIn dir
case r of
Nothing -> die ("Can't find package database in " ++ dir)
Just path -> return path
fs -> return (last fs)
-- The value of the $topdir variable used in some package descriptions
-- Note that the way we calculate this is slightly different to how it
-- is done in ghc itself. We rely on the convention that the global
-- package db lives in ghc's libdir.
top_dir <- absolutePath (takeDirectory global_conf)
let no_user_db = FlagNoUserDb `elem` my_flags
mb_user_conf <-
if no_user_db then return Nothing else do
r <- lookForPackageDBIn hasteUserDir
case r of
Nothing -> return (Just (pkgUserDir, False))
Just f -> return (Just (f, True))
-- If the user database doesn't exist, and this command isn't a
-- "modify" command, then we won't attempt to create or use it.
let sys_databases
| Just (user_conf,user_exists) <- mb_user_conf,
modify || user_exists = [user_conf, global_conf]
| otherwise = [global_conf]
e_pkg_path <- tryIO (System.Environment.getEnv "HASTE_PACKAGE_PATH")
let env_stack =
case e_pkg_path of
Left _ -> sys_databases
Right path
| last cs == "" -> init cs ++ sys_databases
| otherwise -> cs
where cs = parseSearchPath path
-- The "global" database is always the one at the bottom of the stack.
-- This is the database we modify by default.
virt_global_conf = last env_stack
let db_flags = [ f | Just f <- map is_db_flag my_flags ]
where is_db_flag FlagUser
| Just (user_conf, _user_exists) <- mb_user_conf
= Just user_conf
is_db_flag FlagGlobal = Just virt_global_conf
is_db_flag (FlagConfig f) = Just f
is_db_flag _ = Nothing
let flag_db_names | null db_flags = env_stack
| otherwise = reverse (nub db_flags)
-- For a "modify" command, treat all the databases as
-- a stack, where we are modifying the top one, but it
-- can refer to packages in databases further down the
-- stack.
-- -f flags on the command line add to the database
-- stack, unless any of them are present in the stack
-- already.
let final_stack = filter (`notElem` env_stack)
[ f | FlagConfig f <- reverse my_flags ]
++ env_stack
-- the database we actually modify is the one mentioned
-- rightmost on the command-line.
let to_modify
| not modify = Nothing
| null db_flags = Just virt_global_conf
| otherwise = Just (last db_flags)
db_stack <- sequence
[ do db <- readParseDatabase verbosity mb_user_conf use_cache db_path
if expand_vars then return (mungePackageDBPaths top_dir db)
else return db
| db_path <- final_stack ]
let flag_db_stack = [ db | db_name <- flag_db_names,
db <- db_stack, location db == db_name ]
return (db_stack, to_modify, flag_db_stack)
lookForPackageDBIn :: FilePath -> IO (Maybe FilePath)
lookForPackageDBIn dir = do
let path_dir = dir </> "package.conf.d"
exists_dir <- doesDirectoryExist path_dir
if exists_dir then return (Just path_dir) else do
let path_file = dir </> "package.conf"
exists_file <- doesFileExist path_file
if exists_file then return (Just path_file) else return Nothing
readParseDatabase :: Verbosity
-> Maybe (FilePath,Bool)
-> Bool -- use cache
-> FilePath
-> IO PackageDB
readParseDatabase verbosity mb_user_conf use_cache path
-- the user database (only) is allowed to be non-existent
| Just (user_conf,False) <- mb_user_conf, path == user_conf
= mkPackageDB []
| otherwise
= do e <- tryIO $ getDirectoryContents path
case e of
Left _ -> do
pkgs <- parseMultiPackageConf verbosity path
mkPackageDB pkgs
Right fs
| not use_cache -> ignore_cache (const $ return ())
| otherwise -> do
let cache = path </> cachefilename
tdir <- getModificationTime path
e_tcache <- tryIO $ getModificationTime cache
case e_tcache of
Left ex -> do
when (verbosity > Normal) $
warn ("warning: cannot read cache file " ++ cache ++ ": " ++ show ex)
ignore_cache (const $ return ())
Right tcache -> do
let compareTimestampToCache file =
when (verbosity >= Verbose) $ do
tFile <- getModificationTime file
compareTimestampToCache' file tFile
compareTimestampToCache' file tFile = do
let rel = case tcache `compare` tFile of
LT -> " (NEWER than cache)"
GT -> " (older than cache)"
EQ -> " (same as cache)"
warn ("Timestamp " ++ show tFile
++ " for " ++ file ++ rel)
when (verbosity >= Verbose) $ do
warn ("Timestamp " ++ show tcache ++ " for " ++ cache)
compareTimestampToCache' path tdir
if tcache >= tdir
then do
when (verbosity > Normal) $
infoLn ("using cache: " ++ cache)
pkgs <- myReadBinPackageDB cache
let pkgs' = map convertPackageInfoIn pkgs
mkPackageDB pkgs'
else do
when (verbosity >= Normal) $ do
warn ("WARNING: cache is out of date: "
++ cache)
warn "Use 'ghc-pkg recache' to fix."
ignore_cache compareTimestampToCache
where
ignore_cache :: (FilePath -> IO ()) -> IO PackageDB
ignore_cache checkTime = do
let confs = filter (".conf" `isSuffixOf`) fs
doFile f = do checkTime f
parseSingletonPackageConf verbosity f
pkgs <- mapM doFile $ map (path </>) confs
mkPackageDB pkgs
where
mkPackageDB pkgs = do
path_abs <- absolutePath path
return PackageDB {
location = path,
locationAbsolute = path_abs,
packages = pkgs
}
-- read the package.cache file strictly, to work around a problem with
-- bytestring 0.9.0.x (fixed in 0.9.1.x) where the file wasn't closed
-- after it has been completely read, leading to a sharing violation
-- later.
myReadBinPackageDB :: FilePath -> IO [InstalledPackageInfoString]
myReadBinPackageDB filepath = do
h <- openBinaryFile filepath ReadMode
sz <- hFileSize h
b <- B.hGet h (fromIntegral sz)
hClose h
return $ Bin.runGet Bin.get b
parseMultiPackageConf :: Verbosity -> FilePath -> IO [InstalledPackageInfo]
parseMultiPackageConf verbosity file = do
when (verbosity > Normal) $ infoLn ("reading package database: " ++ file)
str <- readUTF8File file
let pkgs = map convertPackageInfoIn $ read str
Exception.evaluate pkgs
`catchError` \e->
die ("error while parsing " ++ file ++ ": " ++ show e)
parseSingletonPackageConf :: Verbosity -> FilePath -> IO InstalledPackageInfo
parseSingletonPackageConf verbosity file = do
when (verbosity > Normal) $ infoLn ("reading package config: " ++ file)
readUTF8File file >>= fmap fst . parsePackageInfo
cachefilename :: FilePath
cachefilename = "package.cache"
mungePackageDBPaths :: FilePath -> PackageDB -> PackageDB
mungePackageDBPaths top_dir db@PackageDB { packages = pkgs } =
db { packages = map (mungePackagePaths top_dir pkgroot) pkgs }
where
pkgroot = takeDirectory (locationAbsolute db)
-- It so happens that for both styles of package db ("package.conf"
-- files and "package.conf.d" dirs) the pkgroot is the parent directory
-- ${pkgroot}/package.conf or ${pkgroot}/package.conf.d/
-- TODO: This code is duplicated in compiler/main/Packages.lhs
mungePackagePaths :: FilePath -> FilePath
-> InstalledPackageInfo -> InstalledPackageInfo
-- Perform path/URL variable substitution as per the Cabal ${pkgroot} spec
-- (http://www.haskell.org/pipermail/libraries/2009-May/011772.html)
-- Paths/URLs can be relative to ${pkgroot} or ${pkgrooturl}.
-- The "pkgroot" is the directory containing the package database.
--
-- Also perform a similar substitution for the older GHC-specific
-- "$topdir" variable. The "topdir" is the location of the ghc
-- installation (obtained from the -B option).
mungePackagePaths top_dir pkgroot pkg =
pkg {
importDirs = munge_paths (importDirs pkg),
includeDirs = munge_paths (includeDirs pkg),
libraryDirs = munge_paths (libraryDirs pkg),
frameworkDirs = munge_paths (frameworkDirs pkg),
haddockInterfaces = munge_paths (haddockInterfaces pkg),
-- haddock-html is allowed to be either a URL or a file
haddockHTMLs = munge_paths (munge_urls (haddockHTMLs pkg))
}
where
munge_paths = map munge_path
munge_urls = map munge_url
munge_path p
| Just p' <- stripVarPrefix "${pkgroot}" p = pkgroot ++ p'
| Just p' <- stripVarPrefix "$topdir" p = top_dir ++ p'
| otherwise = p
munge_url p
| Just p' <- stripVarPrefix "${pkgrooturl}" p = toUrlPath pkgroot p'
| Just p' <- stripVarPrefix "$httptopdir" p = toUrlPath top_dir p'
| otherwise = p
toUrlPath r p = "file:///"
-- URLs always use posix style '/' separators:
++ FilePath.Posix.joinPath
(r : -- We need to drop a leading "/" or "\\"
-- if there is one:
dropWhile (all isPathSeparator)
(FilePath.splitDirectories p))
-- We could drop the separator here, and then use </> above. However,
-- by leaving it in and using ++ we keep the same path separator
-- rather than letting FilePath change it to use \ as the separator
stripVarPrefix var path = case stripPrefix var path of
Just [] -> Just []
Just cs@(c : _) | isPathSeparator c -> Just cs
_ -> Nothing
-- -----------------------------------------------------------------------------
-- Creating a new package DB
initPackageDB :: FilePath -> Verbosity -> [Flag] -> IO ()
initPackageDB filename verbosity _flags = do
let eexist = die ("cannot create: " ++ filename ++ " already exists")
b1 <- doesFileExist filename
when b1 eexist
b2 <- doesDirectoryExist filename
when b2 eexist
filename_abs <- absolutePath filename
changeDB verbosity [] PackageDB {
location = filename, locationAbsolute = filename_abs,
packages = []
}
-- -----------------------------------------------------------------------------
-- Registering
registerPackage :: FilePath
-> Verbosity
-> [Flag]
-> Bool -- auto_ghci_libs
-> Bool -- expand_env_vars
-> Bool -- update
-> Force
-> IO ()
registerPackage input verbosity my_flags auto_ghci_libs expand_env_vars update force = do
(db_stack, Just to_modify, _flag_dbs) <-
getPkgDatabases verbosity True True False{-expand vars-} my_flags
let
db_to_operate_on = my_head "register" $
filter ((== to_modify).location) db_stack
--
when (auto_ghci_libs && verbosity >= Silent) $
warn "Warning: --auto-ghci-libs is deprecated and will be removed in GHC 7.4"
--
s <-
case input of
"-" -> do
when (verbosity >= Normal) $
info "Reading package info from stdin ... "
-- fix the encoding to UTF-8, since this is an interchange format
hSetEncoding stdin utf8
getContents
f -> do
when (verbosity >= Normal) $
info ("Reading package info from " ++ show f ++ " ... ")
readUTF8File f
expanded <- if expand_env_vars then expandEnvVars s force
else return s
(pkg, ws) <- parsePackageInfo expanded
when (verbosity >= Normal) $
infoLn "done."
-- report any warnings from the parse phase
_ <- reportValidateErrors [] ws
(display (sourcePackageId pkg) ++ ": Warning: ") Nothing
-- validate the expanded pkg, but register the unexpanded
pkgroot <- absolutePath (takeDirectory to_modify)
let top_dir = takeDirectory (location (last db_stack))
pkg_expanded = mungePackagePaths top_dir pkgroot pkg
let truncated_stack = dropWhile ((/= to_modify).location) db_stack
-- truncate the stack for validation, because we don't allow
-- packages lower in the stack to refer to those higher up.
validatePackageConfig pkg_expanded verbosity truncated_stack auto_ghci_libs update force
let
removes = [ RemovePackage p
| p <- packages db_to_operate_on,
sourcePackageId p == sourcePackageId pkg ]
--
changeDB verbosity (removes ++ [AddPackage pkg]) db_to_operate_on
parsePackageInfo
:: String
-> IO (InstalledPackageInfo, [ValidateWarning])
parsePackageInfo str =
case parseInstalledPackageInfo str of
ParseOk warnings ok -> return (ok, ws)
where
ws = [ msg | PWarning msg <- warnings
, not ("Unrecognized field pkgroot" `isPrefixOf` msg) ]
ParseFailed err -> case locatedErrorMsg err of
(Nothing, s) -> die s
(Just l, s) -> die (show l ++ ": " ++ s)
-- -----------------------------------------------------------------------------
-- Making changes to a package database
data DBOp = RemovePackage InstalledPackageInfo
| AddPackage InstalledPackageInfo
| ModifyPackage InstalledPackageInfo
changeDB :: Verbosity -> [DBOp] -> PackageDB -> IO ()
changeDB verbosity cmds db = do
let db' = updateInternalDB db cmds
isfile <- doesFileExist (location db)
if isfile
then writeNewConfig verbosity (location db') (packages db')
else do
createDirectoryIfMissing True (location db)
changeDBDir verbosity cmds db'
updateInternalDB :: PackageDB -> [DBOp] -> PackageDB
updateInternalDB db cmds = db{ packages = foldl do_cmd (packages db) cmds }
where
do_cmd pkgs (RemovePackage p) =
filter ((/= installedPackageId p) . installedPackageId) pkgs
do_cmd pkgs (AddPackage p) = p : pkgs
do_cmd pkgs (ModifyPackage p) =
do_cmd (do_cmd pkgs (RemovePackage p)) (AddPackage p)
changeDBDir :: Verbosity -> [DBOp] -> PackageDB -> IO ()
changeDBDir verbosity cmds db = do
mapM_ do_cmd cmds
updateDBCache verbosity db
where
do_cmd (RemovePackage p) = do
let file = location db </> display (installedPackageId p) <.> "conf"
when (verbosity > Normal) $ infoLn ("removing " ++ file)
removeFileSafe file
do_cmd (AddPackage p) = do
let file = location db </> display (installedPackageId p) <.> "conf"
when (verbosity > Normal) $ infoLn ("writing " ++ file)
writeFileUtf8Atomic file (showInstalledPackageInfo p)
do_cmd (ModifyPackage p) =
do_cmd (AddPackage p)
updateDBCache :: Verbosity -> PackageDB -> IO ()
updateDBCache verbosity db = do
let filename = location db </> cachefilename
when (verbosity > Normal) $
infoLn ("writing cache " ++ filename)
writeBinaryFileAtomic filename (map convertPackageInfoOut (packages db))
`catchIO` \e ->
if isPermissionError e
then die (filename ++ ": you don't have permission to modify this file")
else ioError e
#ifndef mingw32_HOST_OS
status <- getFileStatus filename
setFileTimes (location db) (accessTime status) (modificationTime status)
#endif
-- -----------------------------------------------------------------------------
-- Exposing, Hiding, Trusting, Distrusting, Unregistering are all similar
exposePackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO ()
exposePackage = modifyPackage (\p -> ModifyPackage p{exposed=True})
hidePackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO ()
hidePackage = modifyPackage (\p -> ModifyPackage p{exposed=False})
trustPackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO ()
trustPackage = modifyPackage (\p -> ModifyPackage p{trusted=True})
distrustPackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO ()
distrustPackage = modifyPackage (\p -> ModifyPackage p{trusted=False})
unregisterPackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO ()
unregisterPackage = modifyPackage RemovePackage
modifyPackage
:: (InstalledPackageInfo -> DBOp)
-> PackageIdentifier
-> Verbosity
-> [Flag]
-> Force
-> IO ()
modifyPackage fn pkgid verbosity my_flags force = do
(db_stack, Just _to_modify, _flag_dbs) <-
getPkgDatabases verbosity True{-modify-} True{-use cache-} False{-expand vars-} my_flags
(db, ps) <- fmap head $ findPackagesByDB db_stack (Id pkgid)
let
db_name = location db
pkgs = packages db
pids = map sourcePackageId ps
cmds = [ fn pkg | pkg <- pkgs, sourcePackageId pkg `elem` pids ]
new_db = updateInternalDB db cmds
old_broken = brokenPackages (allPackagesInStack db_stack)
rest_of_stack = filter ((/= db_name) . location) db_stack
new_stack = new_db : rest_of_stack
new_broken = map sourcePackageId (brokenPackages (allPackagesInStack new_stack))
newly_broken = filter (`notElem` map sourcePackageId old_broken) new_broken
--
when (not (null newly_broken)) $
dieOrForceAll force ("unregistering " ++ display pkgid ++
" would break the following packages: "
++ unwords (map display newly_broken))
changeDB verbosity cmds db
recache :: Verbosity -> [Flag] -> IO ()
recache verbosity my_flags = do
(db_stack, Just to_modify, _flag_dbs) <-
getPkgDatabases verbosity True{-modify-} False{-no cache-} False{-expand vars-} my_flags
let
db_to_operate_on = my_head "recache" $
filter ((== to_modify).location) db_stack
--
changeDB verbosity [] db_to_operate_on
-- -----------------------------------------------------------------------------
-- Listing packages
listPackages :: Verbosity -> [Flag] -> Maybe PackageArg
-> Maybe (String->Bool)
-> IO ()
listPackages verbosity my_flags mPackageName mModuleName = do
let simple_output = FlagSimpleOutput `elem` my_flags
(db_stack, _, flag_db_stack) <-
getPkgDatabases verbosity False True{-use cache-} False{-expand vars-} my_flags
let db_stack_filtered -- if a package is given, filter out all other packages
| Just this <- mPackageName =
[ db{ packages = filter (this `matchesPkg`) (packages db) }
| db <- flag_db_stack ]
| Just match <- mModuleName = -- packages which expose mModuleName
[ db{ packages = filter (match `exposedInPkg`) (packages db) }
| db <- flag_db_stack ]
| otherwise = flag_db_stack
db_stack_sorted
= [ db{ packages = sort_pkgs (packages db) }
| db <- db_stack_filtered ]
where sort_pkgs = sortBy cmpPkgIds
cmpPkgIds pkg1 pkg2 =
case pkgName p1 `compare` pkgName p2 of
LT -> LT
GT -> GT
EQ -> pkgVersion p1 `compare` pkgVersion p2
where (p1,p2) = (sourcePackageId pkg1, sourcePackageId pkg2)
stack = reverse db_stack_sorted
match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
pkg_map = allPackagesInStack db_stack
broken = map sourcePackageId (brokenPackages pkg_map)
show_normal PackageDB{ location = db_name, packages = pkg_confs } =
do hPutStrLn stdout (db_name ++ ":")
if null pp_pkgs
then hPutStrLn stdout " (no packages)"
else hPutStrLn stdout $ unlines (map (" " ++) pp_pkgs)
where
-- Sort using instance Ord PackageId
pp_pkgs = map pp_pkg . sortBy (comparing installedPackageId) $ pkg_confs
pp_pkg p
| sourcePackageId p `elem` broken = printf "{%s}" doc
| exposed p = doc
| otherwise = printf "(%s)" doc
where doc | verbosity >= Verbose = printf "%s (%s)" pkg ipid
| otherwise = pkg
where
InstalledPackageId ipid = installedPackageId p
pkg = display (sourcePackageId p)
show_simple = simplePackageList my_flags . allPackagesInStack
when (not (null broken) && not simple_output && verbosity /= Silent) $ do
prog <- getProgramName
warn ("WARNING: there are broken packages. Run '" ++ prog ++ " check' for more details.")
if simple_output then show_simple stack else do
#if defined(mingw32_HOST_OS) || defined(BOOTSTRAPPING)
mapM_ show_normal stack
#else
let
show_colour withF db =
mconcat $ map (<#> termText "\n") $
(termText (location db) :
map (termText " " <#>) (map pp_pkg (packages db)))
where
pp_pkg p
| sourcePackageId p `elem` broken = withF Red doc
| exposed p = doc
| otherwise = withF Blue doc
where doc | verbosity >= Verbose
= termText (printf "%s (%s)" pkg ipid)
| otherwise
= termText pkg
where
InstalledPackageId ipid = installedPackageId p
pkg = display (sourcePackageId p)
is_tty <- hIsTerminalDevice stdout
if not is_tty
then mapM_ show_normal stack
else do tty <- Terminfo.setupTermFromEnv
case Terminfo.getCapability tty withForegroundColor of
Nothing -> mapM_ show_normal stack
Just w -> runTermOutput tty $ mconcat $
map (show_colour w) stack
#endif
simplePackageList :: [Flag] -> [InstalledPackageInfo] -> IO ()
simplePackageList my_flags pkgs = do
let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
else display
-- Sort using instance Ord PackageId
strs = map showPkg $ sort $ map sourcePackageId pkgs
when (not (null pkgs)) $
hPutStrLn stdout $ concat $ intersperse " " strs
showPackageDot :: Verbosity -> [Flag] -> IO ()
showPackageDot verbosity myflags = do
(_, _, flag_db_stack) <-
getPkgDatabases verbosity False True{-use cache-} False{-expand vars-} myflags
let all_pkgs = allPackagesInStack flag_db_stack
ipix = PackageIndex.fromList all_pkgs
putStrLn "digraph {"
let quote s = '"':s ++ "\""
mapM_ putStrLn [ quote from ++ " -> " ++ quote to
| p <- all_pkgs,
let from = display (sourcePackageId p),
depid <- depends p,
Just dep <- [PackageIndex.lookupInstalledPackageId ipix depid],
let to = display (sourcePackageId dep)
]
putStrLn "}"
-- -----------------------------------------------------------------------------
-- Prints the highest (hidden or exposed) version of a package
latestPackage :: Verbosity -> [Flag] -> PackageIdentifier -> IO ()
latestPackage verbosity my_flags pkgid = do
(_, _, flag_db_stack) <-
getPkgDatabases verbosity False True{-use cache-} False{-expand vars-} my_flags
ps <- findPackages flag_db_stack (Id pkgid)
case ps of
[] -> die "no matches"
_ -> show_pkg . maximum . map sourcePackageId $ ps
where
show_pkg pid = hPutStrLn stdout (display pid)
-- -----------------------------------------------------------------------------
-- Describe
describePackage :: Verbosity -> [Flag] -> PackageArg -> Bool -> IO ()
describePackage verbosity my_flags pkgarg expand_pkgroot = do
(_, _, flag_db_stack) <-
getPkgDatabases verbosity False True{-use cache-} expand_pkgroot my_flags
dbs <- findPackagesByDB flag_db_stack pkgarg
doDump expand_pkgroot [ (pkg, locationAbsolute db)
| (db, pkgs) <- dbs, pkg <- pkgs ]
dumpPackages :: Verbosity -> [Flag] -> Bool -> IO ()
dumpPackages verbosity my_flags expand_pkgroot = do
(_, _, flag_db_stack) <-
getPkgDatabases verbosity False True{-use cache-} expand_pkgroot my_flags
doDump expand_pkgroot [ (pkg, locationAbsolute db)
| db <- flag_db_stack, pkg <- packages db ]
doDump :: Bool -> [(InstalledPackageInfo, FilePath)] -> IO ()
doDump expand_pkgroot pkgs = do
-- fix the encoding to UTF-8, since this is an interchange format
hSetEncoding stdout utf8
putStrLn $
intercalate "---\n"
[ if expand_pkgroot
then showInstalledPackageInfo pkg
else showInstalledPackageInfo pkg ++ pkgrootField
| (pkg, pkgloc) <- pkgs
, let pkgroot = takeDirectory pkgloc
pkgrootField = "pkgroot: " ++ show pkgroot ++ "\n" ]
-- PackageId is can have globVersion for the version
findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
findPackages db_stack pkgarg
= fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
findPackagesByDB :: PackageDBStack -> PackageArg
-> IO [(PackageDB, [InstalledPackageInfo])]
findPackagesByDB db_stack pkgarg
= case [ (db, matched)
| db <- db_stack,
let matched = filter (pkgarg `matchesPkg`) (packages db),
not (null matched) ] of
[] -> die ("cannot find package " ++ pkg_msg pkgarg)
ps -> return ps
where
pkg_msg (Id pkgid) = display pkgid
pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
matches :: PackageIdentifier -> PackageIdentifier -> Bool
pid `matches` pid'
= (pkgName pid == pkgName pid')
&& (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
realVersion :: PackageIdentifier -> Bool
realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
-- when versionBranch == [], this is a glob
matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
(Id pid) `matchesPkg` pkg = pid `matches` sourcePackageId pkg
(Substring _ m) `matchesPkg` pkg = m (display (sourcePackageId pkg))
-- -----------------------------------------------------------------------------
-- Field
describeField :: Verbosity -> [Flag] -> PackageArg -> [String] -> Bool -> IO ()
describeField verbosity my_flags pkgarg fields expand_pkgroot = do
(_, _, flag_db_stack) <-
getPkgDatabases verbosity False True{-use cache-} expand_pkgroot my_flags
fns <- mapM toField fields
ps <- findPackages flag_db_stack pkgarg
mapM_ (selectFields fns) ps
where showFun = if FlagSimpleOutput `elem` my_flags
then showSimpleInstalledPackageInfoField
else showInstalledPackageInfoField
toField f = case showFun f of
Nothing -> die ("unknown field: " ++ f)
Just fn -> return fn
selectFields fns pinfo = mapM_ (\fn->putStrLn (fn pinfo)) fns
-- -----------------------------------------------------------------------------
-- Check: Check consistency of installed packages
checkConsistency :: Verbosity -> [Flag] -> IO ()
checkConsistency verbosity my_flags = do
(db_stack, _, _) <-
getPkgDatabases verbosity True True{-use cache-} True{-expand vars-} my_flags
-- check behaves like modify for the purposes of deciding which
-- databases to use, because ordering is important.
let simple_output = FlagSimpleOutput `elem` my_flags
let pkgs = allPackagesInStack db_stack
checkPackage p = do
(_,es,ws) <- runValidate $ checkPackageConfig p verbosity db_stack False True
if null es
then do when (not simple_output) $ do
_ <- reportValidateErrors [] ws "" Nothing
return ()
return []
else do
when (not simple_output) $ do
reportError ("There are problems in package " ++ display (sourcePackageId p) ++ ":")
_ <- reportValidateErrors es ws " " Nothing
return ()
return [p]
broken_pkgs <- concat `fmap` mapM checkPackage pkgs
let filterOut pkgs1 pkgs2 = filter not_in pkgs2
where not_in p = sourcePackageId p `notElem` all_ps
all_ps = map sourcePackageId pkgs1
let not_broken_pkgs = filterOut broken_pkgs pkgs
(_, trans_broken_pkgs) = closure [] not_broken_pkgs
all_broken_pkgs = broken_pkgs ++ trans_broken_pkgs
when (not (null all_broken_pkgs)) $ do
if simple_output
then simplePackageList my_flags all_broken_pkgs
else do
reportError ("\nThe following packages are broken, either because they have a problem\n"++
"listed above, or because they depend on a broken package.")
mapM_ (hPutStrLn stderr . display . sourcePackageId) all_broken_pkgs
when (not (null all_broken_pkgs)) $ exitWith (ExitFailure 1)
closure :: [InstalledPackageInfo] -> [InstalledPackageInfo]
-> ([InstalledPackageInfo], [InstalledPackageInfo])
closure pkgs db_stack = go pkgs db_stack
where
go avail not_avail =
case partition (depsAvailable avail) not_avail of
([], not_avail') -> (avail, not_avail')
(new_avail, not_avail') -> go (new_avail ++ avail) not_avail'
depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
-> Bool
depsAvailable pkgs_ok pkg = null dangling
where dangling = filter (`notElem` pids) (depends pkg)
pids = map installedPackageId pkgs_ok
-- we want mutually recursive groups of package to show up
-- as broken. (#1750)
brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
brokenPackages pkgs = snd (closure [] pkgs)
-- -----------------------------------------------------------------------------
-- Manipulating package.conf files
type InstalledPackageInfoString = InstalledPackageInfo_ String
convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString
convertPackageInfoOut
(pkgconf@(InstalledPackageInfo { exposedModules = e,
hiddenModules = h })) =
pkgconf{ exposedModules = map display e,
hiddenModules = map display h }
convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo
convertPackageInfoIn
(pkgconf@(InstalledPackageInfo { exposedModules = e,
hiddenModules = h })) =
pkgconf{ exposedModules = map convert e,
hiddenModules = map convert h }
where convert = fromJust . simpleParse
writeNewConfig :: Verbosity -> FilePath -> [InstalledPackageInfo] -> IO ()
writeNewConfig verbosity filename ipis = do
when (verbosity >= Normal) $
info "Writing new package config file... "
createDirectoryIfMissing True $ takeDirectory filename
let shown = concat $ intersperse ",\n "
$ map (show . convertPackageInfoOut) ipis
fileContents = "[" ++ shown ++ "\n]"
writeFileUtf8Atomic filename fileContents
`catchIO` \e ->
if isPermissionError e
then die (filename ++ ": you don't have permission to modify this file")
else ioError e
when (verbosity >= Normal) $
infoLn "done."
-----------------------------------------------------------------------------
-- Sanity-check a new package config, and automatically build GHCi libs
-- if requested.
type ValidateError = (Force,String)
type ValidateWarning = String
newtype Validate a = V { runValidate :: IO (a, [ValidateError],[ValidateWarning]) }
instance Functor Validate where
fmap = liftM
instance Applicative Validate where
pure = return
(<*>) = ap
instance Monad Validate where
return a = V $ return (a, [], [])
m >>= k = V $ do
(a, es, ws) <- runValidate m
(b, es', ws') <- runValidate (k a)
return (b,es++es',ws++ws')
verror :: Force -> String -> Validate ()
verror f s = V (return ((),[(f,s)],[]))
vwarn :: String -> Validate ()
vwarn s = V (return ((),[],["Warning: " ++ s]))
liftIO :: IO a -> Validate a
liftIO k = V (k >>= \a -> return (a,[],[]))
-- returns False if we should die
reportValidateErrors :: [ValidateError] -> [ValidateWarning]
-> String -> Maybe Force -> IO Bool
reportValidateErrors es ws prefix mb_force = do
mapM_ (warn . (prefix++)) ws
oks <- mapM report es
return (and oks)
where
report (f,s)
| Just force <- mb_force
= if (force >= f)
then do reportError (prefix ++ s ++ " (ignoring)")
return True
else if f < CannotForce
then do reportError (prefix ++ s ++ " (use --force to override)")
return False
else do reportError err
return False
| otherwise = do reportError err
return False
where
err = prefix ++ s
validatePackageConfig :: InstalledPackageInfo
-> Verbosity
-> PackageDBStack
-> Bool -- auto-ghc-libs
-> Bool -- update, or check
-> Force
-> IO ()
validatePackageConfig pkg verbosity db_stack auto_ghci_libs update force = do
(_,es,ws) <- runValidate $ checkPackageConfig pkg verbosity db_stack auto_ghci_libs update
ok <- reportValidateErrors es ws (display (sourcePackageId pkg) ++ ": ") (Just force)
when (not ok) $ exitWith (ExitFailure 1)
checkPackageConfig :: InstalledPackageInfo
-> Verbosity
-> PackageDBStack
-> Bool -- auto-ghc-libs
-> Bool -- update, or check
-> Validate ()
checkPackageConfig pkg verbosity db_stack auto_ghci_libs update = do
checkInstalledPackageId pkg db_stack update
checkPackageId pkg
checkDuplicates db_stack pkg update
mapM_ (checkDep db_stack) (depends pkg)
checkDuplicateDepends (depends pkg)
mapM_ (checkDir False "import-dirs") (importDirs pkg)
mapM_ (checkDir True "library-dirs") (libraryDirs pkg)
mapM_ (checkDir True "include-dirs") (includeDirs pkg)
mapM_ (checkDir True "framework-dirs") (frameworkDirs pkg)
mapM_ (checkFile True "haddock-interfaces") (haddockInterfaces pkg)
mapM_ (checkDirURL True "haddock-html") (haddockHTMLs pkg)
checkModules pkg
-- TODO: move jsmod directory structure into single jslib file?
-- mapM_ (checkHSLib verbosity (libraryDirs pkg) auto_ghci_libs) (hsLibraries pkg)
-- ToDo: check these somehow?
-- extra_libraries :: [String],
-- c_includes :: [String],
checkInstalledPackageId :: InstalledPackageInfo -> PackageDBStack -> Bool
-> Validate ()
checkInstalledPackageId ipi db_stack update = do
let ipid@(InstalledPackageId str) = installedPackageId ipi
when (null str) $ verror CannotForce "missing id field"
let dups = [ p | p <- allPackagesInStack db_stack,
installedPackageId p == ipid ]
when (not update && not (null dups)) $
verror CannotForce $
"package(s) with this id already exist: " ++
unwords (map (display.packageId) dups)
-- When the package name and version are put together, sometimes we can
-- end up with a package id that cannot be parsed. This will lead to
-- difficulties when the user wants to refer to the package later, so
-- we check that the package id can be parsed properly here.
checkPackageId :: InstalledPackageInfo -> Validate ()
checkPackageId ipi =
let str = display (sourcePackageId ipi) in
case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
[_] -> return ()
[] -> verror CannotForce ("invalid package identifier: " ++ str)
_ -> verror CannotForce ("ambiguous package identifier: " ++ str)
checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Validate ()
checkDuplicates db_stack pkg update = do
let
pkgid = sourcePackageId pkg
pkgs = packages (head db_stack)
--
-- Check whether this package id already exists in this DB
--
when (not update && (pkgid `elem` map sourcePackageId pkgs)) $
verror CannotForce $
"package " ++ display pkgid ++ " is already installed"
let
uncasep = map toLower . display
dups = filter ((== uncasep pkgid) . uncasep) (map sourcePackageId pkgs)
when (not update && not (null dups)) $ verror ForceAll $
"Package names may be treated case-insensitively in the future.\n"++
"Package " ++ display pkgid ++
" overlaps with: " ++ unwords (map display dups)
checkDir, checkFile, checkDirURL :: Bool -> String -> FilePath -> Validate ()
checkDir = checkPath False True
checkFile = checkPath False False
checkDirURL = checkPath True True
checkPath :: Bool -> Bool -> Bool -> String -> FilePath -> Validate ()
checkPath url_ok is_dir warn_only thisfield d
| url_ok && ("http://" `isPrefixOf` d
|| "https://" `isPrefixOf` d) = return ()
| url_ok
, Just d' <- stripPrefix "file://" d
= checkPath False is_dir warn_only thisfield d'
-- Note: we don't check for $topdir/${pkgroot} here. We rely on these
-- variables having been expanded already, see mungePackagePaths.
| isRelative d = verror ForceFiles $
thisfield ++ ": " ++ d ++ " is a relative path which "
++ "makes no sense (as there is nothing for it to be "
++ "relative to). You can make paths relative to the "
++ "package database itself by using ${pkgroot}."
-- relative paths don't make any sense; #4134
| otherwise = do
there <- liftIO $ if is_dir then doesDirectoryExist d else doesFileExist d
when (not there) $
let msg = thisfield ++ ": " ++ d ++ " doesn't exist or isn't a "
++ if is_dir then "directory" else "file"
in
if warn_only
then vwarn msg
else verror ForceFiles msg
checkDep :: PackageDBStack -> InstalledPackageId -> Validate ()
checkDep db_stack pkgid
| pkgid `elem` pkgids = return ()
| otherwise = verror ForceAll ("dependency \"" ++ display pkgid
++ "\" doesn't exist")
where
all_pkgs = allPackagesInStack db_stack
pkgids = map installedPackageId all_pkgs
checkDuplicateDepends :: [InstalledPackageId] -> Validate ()
checkDuplicateDepends deps
| null dups = return ()
| otherwise = verror ForceAll ("package has duplicate dependencies: " ++
unwords (map display dups))
where
dups = [ p | (p:_:_) <- group (sort deps) ]
checkHSLib :: Verbosity -> [String] -> Bool -> String -> Validate ()
checkHSLib verbosity dirs auto_ghci_libs lib = do
let batch_lib_file = "lib" ++ lib ++ ".a"
filenames = ["lib" ++ lib ++ ".a",
"lib" ++ lib ++ ".p_a",
"lib" ++ lib ++ "-ghc" ++ showVersion ghcVersion ++ ".so",
"lib" ++ lib ++ "-ghc" ++ showVersion ghcVersion ++ ".dylib",
lib ++ "-ghc" ++ showVersion ghcVersion ++ ".dll"]
m <- liftIO $ doesFileExistOnPath filenames dirs
case m of
Nothing -> verror ForceFiles ("cannot find any of " ++ show filenames ++
" on library path")
Just dir -> liftIO $ checkGHCiLib verbosity dir batch_lib_file lib auto_ghci_libs
doesFileExistOnPath :: [FilePath] -> [FilePath] -> IO (Maybe FilePath)
doesFileExistOnPath filenames paths = go fullFilenames
where fullFilenames = [ (path, path </> filename)
| filename <- filenames
, path <- paths ]
go [] = return Nothing
go ((p, fp) : xs) = do b <- doesFileExist fp
if b then return (Just p) else go xs
checkModules :: InstalledPackageInfo -> Validate ()
checkModules pkg = do
mapM_ findModule (exposedModules pkg ++ hiddenModules pkg)
where
findModule modl =
-- there's no interface file for GHC.Prim
unless (modl == fromString "GHC.Prim") $ do
let files = [ toFilePath modl <.> extension
| extension <- ["hi", "p_hi", "dyn_hi" ] ]
m <- liftIO $ doesFileExistOnPath files (importDirs pkg)
when (isNothing m) $
verror ForceFiles ("cannot find any of " ++ show files)
checkGHCiLib :: Verbosity -> String -> String -> String -> Bool -> IO ()
checkGHCiLib verbosity batch_lib_dir batch_lib_file lib auto_build
| auto_build = autoBuildGHCiLib verbosity batch_lib_dir batch_lib_file ghci_lib_file
| otherwise = return ()
where
ghci_lib_file = lib <.> "o"
-- automatically build the GHCi version of a batch lib,
-- using ld --whole-archive.
autoBuildGHCiLib :: Verbosity -> String -> String -> String -> IO ()
autoBuildGHCiLib verbosity dir batch_file ghci_file = do
let ghci_lib_file = dir ++ '/':ghci_file
batch_lib_file = dir ++ '/':batch_file
when (verbosity >= Normal) $
info ("building GHCi library " ++ ghci_lib_file ++ "...")
#if defined(darwin_HOST_OS)
r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
#elif defined(mingw32_HOST_OS)
execDir <- getLibDir
r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
#else
r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
#endif
when (r /= ExitSuccess) $ exitWith r
when (verbosity >= Normal) $
infoLn (" done.")
-- -----------------------------------------------------------------------------
-- Searching for modules
#if not_yet
findModules :: [FilePath] -> IO [String]
findModules paths =
mms <- mapM searchDir paths
return (concat mms)
searchDir path prefix = do
fs <- getDirectoryEntries path `catchIO` \_ -> return []
searchEntries path prefix fs
searchEntries path prefix [] = return []
searchEntries path prefix (f:fs)
| looks_like_a_module = do
ms <- searchEntries path prefix fs
return (prefix `joinModule` f : ms)
| looks_like_a_component = do
ms <- searchDir (path </> f) (prefix `joinModule` f)
ms' <- searchEntries path prefix fs
return (ms ++ ms')
| otherwise
searchEntries path prefix fs
where
(base,suffix) = splitFileExt f
looks_like_a_module =
suffix `elem` haskell_suffixes &&
all okInModuleName base
looks_like_a_component =
null suffix && all okInModuleName base
okInModuleName c
#endif
-- ---------------------------------------------------------------------------
-- expanding environment variables in the package configuration
expandEnvVars :: String -> Force -> IO String
expandEnvVars str0 force = go str0 ""
where
go "" acc = return $! reverse acc
go ('$':'{':str) acc | (var, '}':rest) <- break close str
= do value <- lookupEnvVar var
go rest (reverse value ++ acc)
where close c = c == '}' || c == '\n' -- don't span newlines
go (c:str) acc
= go str (c:acc)
lookupEnvVar :: String -> IO String
lookupEnvVar "pkgroot" = return "${pkgroot}" -- these two are special,
lookupEnvVar "pkgrooturl" = return "${pkgrooturl}" -- we don't expand them
lookupEnvVar nm =
catchIO (System.Environment.getEnv nm)
(\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
show nm)
return "")
-----------------------------------------------------------------------------
getProgramName :: IO String
getProgramName = liftM (`withoutSuffix` ".bin") getProgName
where str `withoutSuffix` suff
| suff `isSuffixOf` str = take (length str - length suff) str
| otherwise = str
bye :: String -> IO a
bye s = putStr s >> exitWith ExitSuccess
die :: String -> IO a
die = dieWith 1
dieWith :: Int -> String -> IO a
dieWith ec s = do
prog <- getProgramName
reportError (prog ++ ": " ++ s)
exitWith (ExitFailure ec)
dieOrForceAll :: Force -> String -> IO ()
dieOrForceAll ForceAll s = ignoreError s
dieOrForceAll _other s = dieForcible s
warn :: String -> IO ()
warn = reportError
-- send info messages to stdout
infoLn :: String -> IO ()
infoLn = putStrLn
info :: String -> IO ()
info = putStr
ignoreError :: String -> IO ()
ignoreError s = reportError (s ++ " (ignoring)")
reportError :: String -> IO ()
reportError s = do hFlush stdout; hPutStrLn stderr s
dieForcible :: String -> IO ()
dieForcible s = die (s ++ " (use --force to override)")
my_head :: String -> [a] -> a
my_head s [] = error s
my_head _ (x : _) = x
getLibDir :: IO (Maybe String)
getLibDir = return $ Just hasteSysDir
-----------------------------------------
-- Adapted from ghc/compiler/utils/Panic
installSignalHandlers :: IO ()
installSignalHandlers = do
threadid <- myThreadId
let
interrupt = Exception.throwTo threadid
(Exception.ErrorCall "interrupted")
--
#if !defined(mingw32_HOST_OS)
_ <- installHandler sigQUIT (Catch interrupt) Nothing
_ <- installHandler sigINT (Catch interrupt) Nothing
return ()
#else
-- GHC 6.3+ has support for console events on Windows
-- NOTE: running GHCi under a bash shell for some reason requires
-- you to press Ctrl-Break rather than Ctrl-C to provoke
-- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
-- why --SDM 17/12/2004
let sig_handler ControlC = interrupt
sig_handler Break = interrupt
sig_handler _ = return ()
_ <- installHandler (Catch sig_handler)
return ()
#endif
#if mingw32_HOST_OS || mingw32_TARGET_OS
throwIOIO :: Exception.IOException -> IO a
throwIOIO = Exception.throwIO
#endif
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
catchError :: IO a -> (String -> IO a) -> IO a
catchError io handler = io `Exception.catch` handler'
where handler' (Exception.ErrorCall err) = handler err
tryIO :: IO a -> IO (Either Exception.IOException a)
tryIO = Exception.try
writeBinaryFileAtomic :: Bin.Binary a => FilePath -> a -> IO ()
writeBinaryFileAtomic targetFile obj =
withFileAtomic targetFile $ \h -> do
hSetBinaryMode h True
B.hPutStr h (Bin.encode obj)
writeFileUtf8Atomic :: FilePath -> String -> IO ()
writeFileUtf8Atomic targetFile content =
withFileAtomic targetFile $ \h -> do
hSetEncoding h utf8
hPutStr h content
-- copied from Cabal's Distribution.Simple.Utils, except that we want
-- to use text files here, rather than binary files.
withFileAtomic :: FilePath -> (Handle -> IO ()) -> IO ()
withFileAtomic targetFile write_content = do
(newFile, newHandle) <- openNewFile targetDir template
do write_content newHandle
hClose newHandle
#if mingw32_HOST_OS || mingw32_TARGET_OS
renameFile newFile targetFile
-- If the targetFile exists then renameFile will fail
`catchIO` \err -> do
exists <- doesFileExist targetFile
if exists
then do removeFileSafe targetFile
-- Big fat hairy race condition
renameFile newFile targetFile
-- If the removeFile succeeds and the renameFile fails
-- then we've lost the atomic property.
else throwIOIO err
#else
renameFile newFile targetFile
#endif
`Exception.onException` do hClose newHandle
removeFileSafe newFile
where
template = targetName <.> "tmp"
targetDir | null targetDir_ = "."
| otherwise = targetDir_
--TODO: remove this when takeDirectory/splitFileName is fixed
-- to always return a valid dir
(targetDir_,targetName) = splitFileName targetFile
openNewFile :: FilePath -> String -> IO (FilePath, Handle)
openNewFile dir template = do
-- this was added to System.IO in 6.12.1
-- we must use this version because the version below opens the file
-- in binary mode.
openTempFileWithDefaultPermissions dir template
-- | The function splits the given string to substrings
-- using 'isSearchPathSeparator'.
parseSearchPath :: String -> [FilePath]
parseSearchPath path = split path
where
split :: String -> [String]
split s =
case rest' of
[] -> [chunk]
_:rest -> chunk : split rest
where
chunk =
case chunk' of
#ifdef mingw32_HOST_OS
('\"':xs@(_:_)) | last xs == '\"' -> init xs
#endif
_ -> chunk'
(chunk', rest') = break isSearchPathSeparator s
readUTF8File :: FilePath -> IO String
readUTF8File file = do
h <- openFile file ReadMode
-- fix the encoding to UTF-8
hSetEncoding h utf8
hGetContents h
-- removeFileSave doesn't throw an exceptions, if the file is already deleted
removeFileSafe :: FilePath -> IO ()
removeFileSafe fn =
removeFile fn `catchIO` \ e ->
when (not $ isDoesNotExistError e) $ ioError e
absolutePath :: FilePath -> IO FilePath
absolutePath path = return . normalise . (</> path) =<< getCurrentDirectory
-- | Only global packages may be marked as relocatable!
-- May break horribly for general use, only reliable for Haste base packages.
relocate :: [String] -> String -> Sh.Shell ()
relocate packages pkg = do
pi <- Sh.run hastePkgBinary (packages ++ ["describe", pkg]) ""
Sh.run_ hastePkgBinary (packages ++ ["update", "-", "--force", "--global"])
(reloc pi)
where
reloc = unlines . map fixPath . lines
fixPath s
| isKey "library-dirs: " s = prefix s "library-dirs" importDir
| isKey "import-dirs: " s = prefix s "import-dirs" importDir
| isKey "haddock-interfaces: " s = prefix s "haddock-interfaces" importDir
| isKey "haddock-html: " s = prefix s "haddock-html" importDir
| isKey "include-dirs: " s = "include-dirs: " ++ includeDir
| otherwise = s
prefix s pfx path = pfx ++ ": " ++ path </> stripPrefix s
stripPrefix = joinPath . dropWhile (not . isKey pkg) . splitPath
isKey _ "" =
False
isKey key str =
and $ zipWith (==) key str
importDir = "${pkgroot}"
includeDir = "${pkgroot}" </> "include"
| szatkus/haste-compiler | utils/haste-pkg/HastePkg708.hs | bsd-3-clause | 72,226 | 3 | 99 | 19,836 | 16,870 | 8,506 | 8,364 | 1,280 | 32 |
{-# LANGUAGE TemplateHaskell, TypeFamilies, PolyKinds #-}
module T9692 where
import Data.Kind (Type)
import Language.Haskell.TH hiding (Type)
import Language.Haskell.TH.Syntax hiding (Type)
import Language.Haskell.TH.Ppr
import System.IO
class C a where
data F a (b :: k) :: Type
instance C Int where
data F Int x = FInt x
$( do info <- qReify (mkName "F")
runIO $ putStrLn $ pprint info
runIO $ hFlush stdout
return [])
| sdiehl/ghc | testsuite/tests/th/T9692.hs | bsd-3-clause | 460 | 0 | 12 | 105 | 153 | 83 | 70 | -1 | -1 |
#!/usr/bin/env runhaskell
{-|
This Haskell script prints a random quote from my quote
collection in `data/finished.yaml`.
I email myself quotes every few days with a cron job piping
the output of this to a command-line mailing program (mutt).
Appropriate packages can be installed with `cabal`.
Brandon Amos
http://bamos.github.io
2015/04/24
-}
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
import Data.Aeson -- For parsing YAML with FromJSON.
import Data.Maybe (catMaybes, fromJust)
import Data.Random (sample)
import Data.Random.Extras (choice) -- From `random-extras` package.
import Data.Yaml (decode) -- From `yaml` package.
import GHC.Generics
import qualified Data.ByteString.Char8 as BS
data Quote =
Quote {
-- String for Roman numerals.
-- Warning: Integer page numbers cause silent
-- parsing errors.
page :: String
,content :: String}
deriving (Show,Generic,FromJSON)
data Book =
Book {author :: String
,title :: String
,finished :: String
,rating :: Int
,quotes :: Maybe [Quote]
,notes :: Maybe [String]}
deriving (Show,Generic,FromJSON)
-- Produce a formatted string for a quote.
getQuote :: Book -> Quote -> String
getQuote book quote = concat [show $ content quote
,"\n\nFrom page "
,page quote
," of "
,show $ title book
," by "
,author book]
-- Format all of the quotes of a book.
getQuotes :: Book -> Maybe [String]
getQuotes book = (map $ getQuote book) <$> quotes book
getAllQuotes :: [Book] -> [String]
getAllQuotes books = concat . catMaybes . map getQuotes $ books
main = do
yamlData <- BS.readFile "data/finished.yaml"
let mBooks = Data.Yaml.decode yamlData :: Maybe [Book]
case mBooks of
Just books -> putStrLn =<< randomQuote
where randomQuote = sample $ choice quotes
quotes = getAllQuotes $ books
Nothing -> putStrLn "Unable to parse YAML document."
| BIPOC-Books/BIPOC-Books.github.io | scripts/random-quote.hs | mit | 2,086 | 18 | 13 | 578 | 428 | 235 | 193 | 41 | 2 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude, DeriveDataTypeable, MagicHash #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.Exception
-- Copyright : (c) The University of Glasgow, 2009
-- License : see libraries/base/LICENSE
--
-- Maintainer : libraries@haskell.org
-- Stability : internal
-- Portability : non-portable
--
-- IO-related Exception types and functions
--
-----------------------------------------------------------------------------
module GHC.IO.Exception (
BlockedIndefinitelyOnMVar(..), blockedIndefinitelyOnMVar,
BlockedIndefinitelyOnSTM(..), blockedIndefinitelyOnSTM,
Deadlock(..),
AssertionFailed(..),
AsyncException(..), stackOverflow, heapOverflow,
ArrayException(..),
ExitCode(..),
ioException,
ioError,
IOError,
IOException(..),
IOErrorType(..),
userError,
assertError,
unsupportedOperation,
untangle,
) where
import GHC.Base
import GHC.List
import GHC.IO
import GHC.Show
import GHC.Read
import GHC.Exception
import Data.Maybe
import GHC.IO.Handle.Types
import Foreign.C.Types
import Data.Typeable ( Typeable )
-- ------------------------------------------------------------------------
-- Exception datatypes and operations
-- |The thread is blocked on an @MVar@, but there are no other references
-- to the @MVar@ so it can't ever continue.
data BlockedIndefinitelyOnMVar = BlockedIndefinitelyOnMVar
deriving Typeable
instance Exception BlockedIndefinitelyOnMVar
instance Show BlockedIndefinitelyOnMVar where
showsPrec _ BlockedIndefinitelyOnMVar = showString "thread blocked indefinitely in an MVar operation"
blockedIndefinitelyOnMVar :: SomeException -- for the RTS
blockedIndefinitelyOnMVar = toException BlockedIndefinitelyOnMVar
-----
-- |The thread is waiting to retry an STM transaction, but there are no
-- other references to any @TVar@s involved, so it can't ever continue.
data BlockedIndefinitelyOnSTM = BlockedIndefinitelyOnSTM
deriving Typeable
instance Exception BlockedIndefinitelyOnSTM
instance Show BlockedIndefinitelyOnSTM where
showsPrec _ BlockedIndefinitelyOnSTM = showString "thread blocked indefinitely in an STM transaction"
blockedIndefinitelyOnSTM :: SomeException -- for the RTS
blockedIndefinitelyOnSTM = toException BlockedIndefinitelyOnSTM
-----
-- |There are no runnable threads, so the program is deadlocked.
-- The @Deadlock@ exception is raised in the main thread only.
data Deadlock = Deadlock
deriving Typeable
instance Exception Deadlock
instance Show Deadlock where
showsPrec _ Deadlock = showString "<<deadlock>>"
-----
-- |'assert' was applied to 'False'.
data AssertionFailed = AssertionFailed String
deriving Typeable
instance Exception AssertionFailed
instance Show AssertionFailed where
showsPrec _ (AssertionFailed err) = showString err
-----
-- |Asynchronous exceptions.
data AsyncException
= StackOverflow
-- ^The current thread\'s stack exceeded its limit.
-- Since an exception has been raised, the thread\'s stack
-- will certainly be below its limit again, but the
-- programmer should take remedial action
-- immediately.
| HeapOverflow
-- ^The program\'s heap is reaching its limit, and
-- the program should take action to reduce the amount of
-- live data it has. Notes:
--
-- * It is undefined which thread receives this exception.
--
-- * GHC currently does not throw 'HeapOverflow' exceptions.
| ThreadKilled
-- ^This exception is raised by another thread
-- calling 'Control.Concurrent.killThread', or by the system
-- if it needs to terminate the thread for some
-- reason.
| UserInterrupt
-- ^This exception is raised by default in the main thread of
-- the program when the user requests to terminate the program
-- via the usual mechanism(s) (e.g. Control-C in the console).
deriving (Eq, Ord, Typeable)
instance Exception AsyncException
-- | Exceptions generated by array operations
data ArrayException
= IndexOutOfBounds String
-- ^An attempt was made to index an array outside
-- its declared bounds.
| UndefinedElement String
-- ^An attempt was made to evaluate an element of an
-- array that had not been initialized.
deriving (Eq, Ord, Typeable)
instance Exception ArrayException
stackOverflow, heapOverflow :: SomeException -- for the RTS
stackOverflow = toException StackOverflow
heapOverflow = toException HeapOverflow
instance Show AsyncException where
showsPrec _ StackOverflow = showString "stack overflow"
showsPrec _ HeapOverflow = showString "heap overflow"
showsPrec _ ThreadKilled = showString "thread killed"
showsPrec _ UserInterrupt = showString "user interrupt"
instance Show ArrayException where
showsPrec _ (IndexOutOfBounds s)
= showString "array index out of range"
. (if not (null s) then showString ": " . showString s
else id)
showsPrec _ (UndefinedElement s)
= showString "undefined array element"
. (if not (null s) then showString ": " . showString s
else id)
-- -----------------------------------------------------------------------------
-- The ExitCode type
-- We need it here because it is used in ExitException in the
-- Exception datatype (above).
-- | Defines the exit codes that a program can return.
data ExitCode
= ExitSuccess -- ^ indicates successful termination;
| ExitFailure Int
-- ^ indicates program failure with an exit code.
-- The exact interpretation of the code is
-- operating-system dependent. In particular, some values
-- may be prohibited (e.g. 0 on a POSIX-compliant system).
deriving (Eq, Ord, Read, Show, Typeable)
instance Exception ExitCode
ioException :: IOException -> IO a
ioException err = throwIO err
-- | Raise an 'IOError' in the 'IO' monad.
ioError :: IOError -> IO a
ioError = ioException
-- ---------------------------------------------------------------------------
-- IOError type
-- | The Haskell 98 type for exceptions in the 'IO' monad.
-- Any I\/O operation may raise an 'IOError' instead of returning a result.
-- For a more general type of exception, including also those that arise
-- in pure code, see "Control.Exception.Exception".
--
-- In Haskell 98, this is an opaque type.
type IOError = IOException
-- |Exceptions that occur in the @IO@ monad.
-- An @IOException@ records a more specific error type, a descriptive
-- string and maybe the handle that was used when the error was
-- flagged.
data IOException
= IOError {
ioe_handle :: Maybe Handle, -- the handle used by the action flagging
-- the error.
ioe_type :: IOErrorType, -- what it was.
ioe_location :: String, -- location.
ioe_description :: String, -- error type specific information.
ioe_errno :: Maybe CInt, -- errno leading to this error, if any.
ioe_filename :: Maybe FilePath -- filename the error is related to.
}
deriving Typeable
instance Exception IOException
instance Eq IOException where
(IOError h1 e1 loc1 str1 en1 fn1) == (IOError h2 e2 loc2 str2 en2 fn2) =
e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && en1==en2 && fn1==fn2
-- | An abstract type that contains a value for each variant of 'IOError'.
data IOErrorType
-- Haskell 98:
= AlreadyExists
| NoSuchThing
| ResourceBusy
| ResourceExhausted
| EOF
| IllegalOperation
| PermissionDenied
| UserError
-- GHC only:
| UnsatisfiedConstraints
| SystemError
| ProtocolError
| OtherError
| InvalidArgument
| InappropriateType
| HardwareFault
| UnsupportedOperation
| TimeExpired
| ResourceVanished
| Interrupted
instance Eq IOErrorType where
x == y = isTrue# (getTag x ==# getTag y)
instance Show IOErrorType where
showsPrec _ e =
showString $
case e of
AlreadyExists -> "already exists"
NoSuchThing -> "does not exist"
ResourceBusy -> "resource busy"
ResourceExhausted -> "resource exhausted"
EOF -> "end of file"
IllegalOperation -> "illegal operation"
PermissionDenied -> "permission denied"
UserError -> "user error"
HardwareFault -> "hardware fault"
InappropriateType -> "inappropriate type"
Interrupted -> "interrupted"
InvalidArgument -> "invalid argument"
OtherError -> "failed"
ProtocolError -> "protocol error"
ResourceVanished -> "resource vanished"
SystemError -> "system error"
TimeExpired -> "timeout"
UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
UnsupportedOperation -> "unsupported operation"
-- | Construct an 'IOError' value with a string describing the error.
-- The 'fail' method of the 'IO' instance of the 'Monad' class raises a
-- 'userError', thus:
--
-- > instance Monad IO where
-- > ...
-- > fail s = ioError (userError s)
--
userError :: String -> IOError
userError str = IOError Nothing UserError "" str Nothing Nothing
-- ---------------------------------------------------------------------------
-- Showing IOErrors
instance Show IOException where
showsPrec p (IOError hdl iot loc s _ fn) =
(case fn of
Nothing -> case hdl of
Nothing -> id
Just h -> showsPrec p h . showString ": "
Just name -> showString name . showString ": ") .
(case loc of
"" -> id
_ -> showString loc . showString ": ") .
showsPrec p iot .
(case s of
"" -> id
_ -> showString " (" . showString s . showString ")")
-- Note the use of "lazy". This means that
-- assert False (throw e)
-- will throw the assertion failure rather than e. See trac #5561.
assertError :: Addr# -> Bool -> a -> a
assertError str predicate v
| predicate = lazy v
| otherwise = throw (AssertionFailed (untangle str "Assertion failed"))
unsupportedOperation :: IOError
unsupportedOperation =
(IOError Nothing UnsupportedOperation ""
"Operation is not supported" Nothing Nothing)
{-
(untangle coded message) expects "coded" to be of the form
"location|details"
It prints
location message details
-}
untangle :: Addr# -> String -> String
untangle coded message
= location
++ ": "
++ message
++ details
++ "\n"
where
coded_str = unpackCStringUtf8# coded
(location, details)
= case (span not_bar coded_str) of { (loc, rest) ->
case rest of
('|':det) -> (loc, ' ' : det)
_ -> (loc, "")
}
not_bar c = c /= '|'
| beni55/haste-compiler | libraries/ghc-7.8/base/GHC/IO/Exception.hs | bsd-3-clause | 11,036 | 0 | 17 | 2,580 | 1,647 | 922 | 725 | 190 | 2 |
{-# LANGUAGE GADTs #-}
module CmmSink (
cmmSink
) where
import Cmm
import CmmOpt
import BlockId
import CmmLive
import CmmUtils
import Hoopl
import CodeGen.Platform
import Platform (isARM, platformArch)
import DynFlags
import UniqFM
import PprCmm ()
import Data.List (partition)
import qualified Data.Set as Set
import Data.Maybe
-- -----------------------------------------------------------------------------
-- Sinking and inlining
-- This is an optimisation pass that
-- (a) moves assignments closer to their uses, to reduce register pressure
-- (b) pushes assignments into a single branch of a conditional if possible
-- (c) inlines assignments to registers that are mentioned only once
-- (d) discards dead assignments
--
-- This tightens up lots of register-heavy code. It is particularly
-- helpful in the Cmm generated by the Stg->Cmm code generator, in
-- which every function starts with a copyIn sequence like:
--
-- x1 = R1
-- x2 = Sp[8]
-- x3 = Sp[16]
-- if (Sp - 32 < SpLim) then L1 else L2
--
-- we really want to push the x1..x3 assignments into the L2 branch.
--
-- Algorithm:
--
-- * Start by doing liveness analysis.
--
-- * Keep a list of assignments A; earlier ones may refer to later ones.
-- Currently we only sink assignments to local registers, because we don't
-- have liveness information about global registers.
--
-- * Walk forwards through the graph, look at each node N:
--
-- * If it is a dead assignment, i.e. assignment to a register that is
-- not used after N, discard it.
--
-- * Try to inline based on current list of assignments
-- * If any assignments in A (1) occur only once in N, and (2) are
-- not live after N, inline the assignment and remove it
-- from A.
--
-- * If an assignment in A is cheap (RHS is local register), then
-- inline the assignment and keep it in A in case it is used afterwards.
--
-- * Otherwise don't inline.
--
-- * If N is assignment to a local register pick up the assignment
-- and add it to A.
--
-- * If N is not an assignment to a local register:
-- * remove any assignments from A that conflict with N, and
-- place them before N in the current block. We call this
-- "dropping" the assignments.
--
-- * An assignment conflicts with N if it:
-- - assigns to a register mentioned in N
-- - mentions a register assigned by N
-- - reads from memory written by N
-- * do this recursively, dropping dependent assignments
--
-- * At an exit node:
-- * drop any assignments that are live on more than one successor
-- and are not trivial
-- * if any successor has more than one predecessor (a join-point),
-- drop everything live in that successor. Since we only propagate
-- assignments that are not dead at the successor, we will therefore
-- eliminate all assignments dead at this point. Thus analysis of a
-- join-point will always begin with an empty list of assignments.
--
--
-- As a result of above algorithm, sinking deletes some dead assignments
-- (transitively, even). This isn't as good as removeDeadAssignments,
-- but it's much cheaper.
-- -----------------------------------------------------------------------------
-- things that we aren't optimising very well yet.
--
-- -----------
-- (1) From GHC's FastString.hashStr:
--
-- s2ay:
-- if ((_s2an::I64 == _s2ao::I64) >= 1) goto c2gn; else goto c2gp;
-- c2gn:
-- R1 = _s2au::I64;
-- call (I64[Sp])(R1) args: 8, res: 0, upd: 8;
-- c2gp:
-- _s2cO::I64 = %MO_S_Rem_W64(%MO_UU_Conv_W8_W64(I8[_s2aq::I64 + (_s2an::I64 << 0)]) + _s2au::I64 * 128,
-- 4091);
-- _s2an::I64 = _s2an::I64 + 1;
-- _s2au::I64 = _s2cO::I64;
-- goto s2ay;
--
-- a nice loop, but we didn't eliminate the silly assignment at the end.
-- See Note [dependent assignments], which would probably fix this.
-- This is #8336 on Trac.
--
-- -----------
-- (2) From stg_atomically_frame in PrimOps.cmm
--
-- We have a diamond control flow:
--
-- x = ...
-- |
-- / \
-- A B
-- \ /
-- |
-- use of x
--
-- Now x won't be sunk down to its use, because we won't push it into
-- both branches of the conditional. We certainly do have to check
-- that we can sink it past all the code in both A and B, but having
-- discovered that, we could sink it to its use.
--
-- -----------------------------------------------------------------------------
type Assignment = (LocalReg, CmmExpr, AbsMem)
-- Assignment caches AbsMem, an abstraction of the memory read by
-- the RHS of the assignment.
type Assignments = [Assignment]
-- A sequence of assignements; kept in *reverse* order
-- So the list [ x=e1, y=e2 ] means the sequence of assignments
-- y = e2
-- x = e1
cmmSink :: DynFlags -> CmmGraph -> CmmGraph
cmmSink dflags graph = ofBlockList (g_entry graph) $ sink mapEmpty $ blocks
where
liveness = cmmLocalLiveness dflags graph
getLive l = mapFindWithDefault Set.empty l liveness
blocks = postorderDfs graph
join_pts = findJoinPoints blocks
sink :: BlockEnv Assignments -> [CmmBlock] -> [CmmBlock]
sink _ [] = []
sink sunk (b:bs) =
-- pprTrace "sink" (ppr lbl) $
blockJoin first final_middle final_last : sink sunk' bs
where
lbl = entryLabel b
(first, middle, last) = blockSplit b
succs = successors last
-- Annotate the middle nodes with the registers live *after*
-- the node. This will help us decide whether we can inline
-- an assignment in the current node or not.
live = Set.unions (map getLive succs)
live_middle = gen_kill dflags last live
ann_middles = annotate dflags live_middle (blockToList middle)
-- Now sink and inline in this block
(middle', assigs) = walk dflags ann_middles (mapFindWithDefault [] lbl sunk)
fold_last = constantFoldNode dflags last
(final_last, assigs') = tryToInline dflags live fold_last assigs
-- We cannot sink into join points (successors with more than
-- one predecessor), so identify the join points and the set
-- of registers live in them.
(joins, nonjoins) = partition (`mapMember` join_pts) succs
live_in_joins = Set.unions (map getLive joins)
-- We do not want to sink an assignment into multiple branches,
-- so identify the set of registers live in multiple successors.
-- This is made more complicated because when we sink an assignment
-- into one branch, this might change the set of registers that are
-- now live in multiple branches.
init_live_sets = map getLive nonjoins
live_in_multi live_sets r =
case filter (Set.member r) live_sets of
(_one:_two:_) -> True
_ -> False
-- Now, drop any assignments that we will not sink any further.
(dropped_last, assigs'') = dropAssignments dflags drop_if init_live_sets assigs'
drop_if a@(r,rhs,_) live_sets = (should_drop, live_sets')
where
should_drop = conflicts dflags a final_last
|| not (isTrivial dflags rhs) && live_in_multi live_sets r
|| r `Set.member` live_in_joins
live_sets' | should_drop = live_sets
| otherwise = map upd live_sets
upd set | r `Set.member` set = set `Set.union` live_rhs
| otherwise = set
live_rhs = foldRegsUsed dflags extendRegSet emptyRegSet rhs
final_middle = foldl blockSnoc middle' dropped_last
sunk' = mapUnion sunk $
mapFromList [ (l, filterAssignments dflags (getLive l) assigs'')
| l <- succs ]
{- TODO: enable this later, when we have some good tests in place to
measure the effect and tune it.
-- small: an expression we don't mind duplicating
isSmall :: CmmExpr -> Bool
isSmall (CmmReg (CmmLocal _)) = True --
isSmall (CmmLit _) = True
isSmall (CmmMachOp (MO_Add _) [x,y]) = isTrivial x && isTrivial y
isSmall (CmmRegOff (CmmLocal _) _) = True
isSmall _ = False
-}
--
-- We allow duplication of trivial expressions: registers (both local and
-- global) and literals.
--
isTrivial :: DynFlags -> CmmExpr -> Bool
isTrivial _ (CmmReg (CmmLocal _)) = True
isTrivial dflags (CmmReg (CmmGlobal r)) = -- see Note [Inline GlobalRegs?]
if isARM (platformArch (targetPlatform dflags))
then True -- CodeGen.Platform.ARM does not have globalRegMaybe
else isJust (globalRegMaybe (targetPlatform dflags) r)
-- GlobalRegs that are loads from BaseReg are not trivial
isTrivial _ (CmmLit _) = True
isTrivial _ _ = False
--
-- annotate each node with the set of registers live *after* the node
--
annotate :: DynFlags -> LocalRegSet -> [CmmNode O O] -> [(LocalRegSet, CmmNode O O)]
annotate dflags live nodes = snd $ foldr ann (live,[]) nodes
where ann n (live,nodes) = (gen_kill dflags n live, (live,n) : nodes)
--
-- Find the blocks that have multiple successors (join points)
--
findJoinPoints :: [CmmBlock] -> BlockEnv Int
findJoinPoints blocks = mapFilter (>1) succ_counts
where
all_succs = concatMap successors blocks
succ_counts :: BlockEnv Int
succ_counts = foldr (\l -> mapInsertWith (+) l 1) mapEmpty all_succs
--
-- filter the list of assignments to remove any assignments that
-- are not live in a continuation.
--
filterAssignments :: DynFlags -> LocalRegSet -> Assignments -> Assignments
filterAssignments dflags live assigs = reverse (go assigs [])
where go [] kept = kept
go (a@(r,_,_):as) kept | needed = go as (a:kept)
| otherwise = go as kept
where
needed = r `Set.member` live
|| any (conflicts dflags a) (map toNode kept)
-- Note that we must keep assignments that are
-- referred to by other assignments we have
-- already kept.
-- -----------------------------------------------------------------------------
-- Walk through the nodes of a block, sinking and inlining assignments
-- as we go.
--
-- On input we pass in a:
-- * list of nodes in the block
-- * a list of assignments that appeared *before* this block and
-- that are being sunk.
--
-- On output we get:
-- * a new block
-- * a list of assignments that will be placed *after* that block.
--
walk :: DynFlags
-> [(LocalRegSet, CmmNode O O)] -- nodes of the block, annotated with
-- the set of registers live *after*
-- this node.
-> Assignments -- The current list of
-- assignments we are sinking.
-- Earlier assignments may refer
-- to later ones.
-> ( Block CmmNode O O -- The new block
, Assignments -- Assignments to sink further
)
walk dflags nodes assigs = go nodes emptyBlock assigs
where
go [] block as = (block, as)
go ((live,node):ns) block as
| shouldDiscard node live = go ns block as
-- discard dead assignment
| Just a <- shouldSink dflags node2 = go ns block (a : as1)
| otherwise = go ns block' as'
where
node1 = constantFoldNode dflags node
(node2, as1) = tryToInline dflags live node1 as
(dropped, as') = dropAssignmentsSimple dflags
(\a -> conflicts dflags a node2) as1
block' = foldl blockSnoc block dropped `blockSnoc` node2
--
-- Heuristic to decide whether to pick up and sink an assignment
-- Currently we pick up all assignments to local registers. It might
-- be profitable to sink assignments to global regs too, but the
-- liveness analysis doesn't track those (yet) so we can't.
--
shouldSink :: DynFlags -> CmmNode e x -> Maybe Assignment
shouldSink dflags (CmmAssign (CmmLocal r) e) | no_local_regs = Just (r, e, exprMem dflags e)
where no_local_regs = True -- foldRegsUsed (\_ _ -> False) True e
shouldSink _ _other = Nothing
--
-- discard dead assignments. This doesn't do as good a job as
-- removeDeadAsssignments, because it would need multiple passes
-- to get all the dead code, but it catches the common case of
-- superfluous reloads from the stack that the stack allocator
-- leaves behind.
--
-- Also we catch "r = r" here. You might think it would fall
-- out of inlining, but the inliner will see that r is live
-- after the instruction and choose not to inline r in the rhs.
--
shouldDiscard :: CmmNode e x -> LocalRegSet -> Bool
shouldDiscard node live
= case node of
CmmAssign r (CmmReg r') | r == r' -> True
CmmAssign (CmmLocal r) _ -> not (r `Set.member` live)
_otherwise -> False
toNode :: Assignment -> CmmNode O O
toNode (r,rhs,_) = CmmAssign (CmmLocal r) rhs
dropAssignmentsSimple :: DynFlags -> (Assignment -> Bool) -> Assignments
-> ([CmmNode O O], Assignments)
dropAssignmentsSimple dflags f = dropAssignments dflags (\a _ -> (f a, ())) ()
dropAssignments :: DynFlags -> (Assignment -> s -> (Bool, s)) -> s -> Assignments
-> ([CmmNode O O], Assignments)
dropAssignments dflags should_drop state assigs
= (dropped, reverse kept)
where
(dropped,kept) = go state assigs [] []
go _ [] dropped kept = (dropped, kept)
go state (assig : rest) dropped kept
| conflict = go state' rest (toNode assig : dropped) kept
| otherwise = go state' rest dropped (assig:kept)
where
(dropit, state') = should_drop assig state
conflict = dropit || any (conflicts dflags assig) dropped
-- -----------------------------------------------------------------------------
-- Try to inline assignments into a node.
tryToInline
:: DynFlags
-> LocalRegSet -- set of registers live after this
-- node. We cannot inline anything
-- that is live after the node, unless
-- it is small enough to duplicate.
-> CmmNode O x -- The node to inline into
-> Assignments -- Assignments to inline
-> (
CmmNode O x -- New node
, Assignments -- Remaining assignments
)
tryToInline dflags live node assigs = go usages node [] assigs
where
usages :: UniqFM Int -- Maps each LocalReg to a count of how often it is used
usages = foldLocalRegsUsed dflags addUsage emptyUFM node
go _usages node _skipped [] = (node, [])
go usages node skipped (a@(l,rhs,_) : rest)
| cannot_inline = dont_inline
| occurs_none = discard -- Note [discard during inlining]
| occurs_once = inline_and_discard
| isTrivial dflags rhs = inline_and_keep
| otherwise = dont_inline
where
inline_and_discard = go usages' inl_node skipped rest
where usages' = foldLocalRegsUsed dflags addUsage usages rhs
discard = go usages node skipped rest
dont_inline = keep node -- don't inline the assignment, keep it
inline_and_keep = keep inl_node -- inline the assignment, keep it
keep node' = (final_node, a : rest')
where (final_node, rest') = go usages' node' (l:skipped) rest
usages' = foldLocalRegsUsed dflags (\m r -> addToUFM m r 2)
usages rhs
-- we must not inline anything that is mentioned in the RHS
-- of a binding that we have already skipped, so we set the
-- usages of the regs on the RHS to 2.
cannot_inline = skipped `regsUsedIn` rhs -- Note [dependent assignments]
|| l `elem` skipped
|| not (okToInline dflags rhs node)
l_usages = lookupUFM usages l
l_live = l `elemRegSet` live
occurs_once = not l_live && l_usages == Just 1
occurs_none = not l_live && l_usages == Nothing
inl_node = mapExpDeep inline node
-- mapExpDeep is where the inlining actually takes place!
where inline (CmmReg (CmmLocal l')) | l == l' = rhs
inline (CmmRegOff (CmmLocal l') off) | l == l'
= cmmOffset dflags rhs off
-- re-constant fold after inlining
inline (CmmMachOp op args) = cmmMachOpFold dflags op args
inline other = other
-- Note [dependent assignments]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- If our assignment list looks like
--
-- [ y = e, x = ... y ... ]
--
-- We cannot inline x. Remember this list is really in reverse order,
-- so it means x = ... y ...; y = e
--
-- Hence if we inline x, the outer assignment to y will capture the
-- reference in x's right hand side.
--
-- In this case we should rename the y in x's right-hand side,
-- i.e. change the list to [ y = e, x = ... y1 ..., y1 = y ]
-- Now we can go ahead and inline x.
--
-- For now we do nothing, because this would require putting
-- everything inside UniqSM.
--
-- One more variant of this (#7366):
--
-- [ y = e, y = z ]
--
-- If we don't want to inline y = e, because y is used many times, we
-- might still be tempted to inline y = z (because we always inline
-- trivial rhs's). But of course we can't, because y is equal to e,
-- not z.
-- Note [discard during inlining]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Opportunities to discard assignments sometimes appear after we've
-- done some inlining. Here's an example:
--
-- x = R1;
-- y = P64[x + 7];
-- z = P64[x + 15];
-- /* z is dead */
-- R1 = y & (-8);
--
-- The x assignment is trivial, so we inline it in the RHS of y, and
-- keep both x and y. z gets dropped because it is dead, then we
-- inline y, and we have a dead assignment to x. If we don't notice
-- that x is dead in tryToInline, we end up retaining it.
addUsage :: UniqFM Int -> LocalReg -> UniqFM Int
addUsage m r = addToUFM_C (+) m r 1
regsUsedIn :: [LocalReg] -> CmmExpr -> Bool
regsUsedIn [] _ = False
regsUsedIn ls e = wrapRecExpf f e False
where f (CmmReg (CmmLocal l)) _ | l `elem` ls = True
f (CmmRegOff (CmmLocal l) _) _ | l `elem` ls = True
f _ z = z
-- we don't inline into CmmUnsafeForeignCall if the expression refers
-- to global registers. This is a HACK to avoid global registers
-- clashing with C argument-passing registers, really the back-end
-- ought to be able to handle it properly, but currently neither PprC
-- nor the NCG can do it. See Note [Register parameter passing]
-- See also StgCmmForeign:load_args_into_temps.
okToInline :: DynFlags -> CmmExpr -> CmmNode e x -> Bool
okToInline dflags expr node@(CmmUnsafeForeignCall{}) =
not (globalRegistersConflict dflags expr node)
okToInline _ _ _ = True
-- -----------------------------------------------------------------------------
-- | @conflicts (r,e) node@ is @False@ if and only if the assignment
-- @r = e@ can be safely commuted past statement @node@.
conflicts :: DynFlags -> Assignment -> CmmNode O x -> Bool
conflicts dflags (r, rhs, addr) node
-- (1) node defines registers used by rhs of assignment. This catches
-- assignments and all three kinds of calls. See Note [Sinking and calls]
| globalRegistersConflict dflags rhs node = True
| localRegistersConflict dflags rhs node = True
-- (2) node uses register defined by assignment
| foldRegsUsed dflags (\b r' -> r == r' || b) False node = True
-- (3) a store to an address conflicts with a read of the same memory
| CmmStore addr' e <- node
, memConflicts addr (loadAddr dflags addr' (cmmExprWidth dflags e)) = True
-- (4) an assignment to Hp/Sp conflicts with a heap/stack read respectively
| HeapMem <- addr, CmmAssign (CmmGlobal Hp) _ <- node = True
| StackMem <- addr, CmmAssign (CmmGlobal Sp) _ <- node = True
| SpMem{} <- addr, CmmAssign (CmmGlobal Sp) _ <- node = True
-- (5) foreign calls clobber heap: see Note [Foreign calls clobber heap]
| CmmUnsafeForeignCall{} <- node, memConflicts addr AnyMem = True
-- (6) native calls clobber any memory
| CmmCall{} <- node, memConflicts addr AnyMem = True
-- (7) otherwise, no conflict
| otherwise = False
-- Returns True if node defines any global registers that are used in the
-- Cmm expression
globalRegistersConflict :: DynFlags -> CmmExpr -> CmmNode e x -> Bool
globalRegistersConflict dflags expr node =
foldRegsDefd dflags (\b r -> b || regUsedIn dflags (CmmGlobal r) expr)
False node
-- Returns True if node defines any local registers that are used in the
-- Cmm expression
localRegistersConflict :: DynFlags -> CmmExpr -> CmmNode e x -> Bool
localRegistersConflict dflags expr node =
foldRegsDefd dflags (\b r -> b || regUsedIn dflags (CmmLocal r) expr)
False node
-- Note [Sinking and calls]
-- ~~~~~~~~~~~~~~~~~~~~~~~~
--
-- We have three kinds of calls: normal (CmmCall), safe foreign (CmmForeignCall)
-- and unsafe foreign (CmmUnsafeForeignCall). We perform sinking pass after
-- stack layout (see Note [Sinking after stack layout]) which leads to two
-- invariants related to calls:
--
-- a) during stack layout phase all safe foreign calls are turned into
-- unsafe foreign calls (see Note [Lower safe foreign calls]). This
-- means that we will never encounter CmmForeignCall node when running
-- sinking after stack layout
--
-- b) stack layout saves all variables live across a call on the stack
-- just before making a call (remember we are not sinking assignments to
-- stack):
--
-- L1:
-- x = R1
-- P64[Sp - 16] = L2
-- P64[Sp - 8] = x
-- Sp = Sp - 16
-- call f() returns L2
-- L2:
--
-- We will attempt to sink { x = R1 } but we will detect conflict with
-- { P64[Sp - 8] = x } and hence we will drop { x = R1 } without even
-- checking whether it conflicts with { call f() }. In this way we will
-- never need to check any assignment conflicts with CmmCall. Remember
-- that we still need to check for potential memory conflicts.
--
-- So the result is that we only need to worry about CmmUnsafeForeignCall nodes
-- when checking conflicts (see Note [Unsafe foreign calls clobber caller-save registers]).
-- This assumption holds only when we do sinking after stack layout. If we run
-- it before stack layout we need to check for possible conflicts with all three
-- kinds of calls. Our `conflicts` function does that by using a generic
-- foldRegsDefd and foldRegsUsed functions defined in DefinerOfRegs and
-- UserOfRegs typeclasses.
--
-- An abstraction of memory read or written.
data AbsMem
= NoMem -- no memory accessed
| AnyMem -- arbitrary memory
| HeapMem -- definitely heap memory
| StackMem -- definitely stack memory
| SpMem -- <size>[Sp+n]
{-# UNPACK #-} !Int
{-# UNPACK #-} !Int
-- Having SpMem is important because it lets us float loads from Sp
-- past stores to Sp as long as they don't overlap, and this helps to
-- unravel some long sequences of
-- x1 = [Sp + 8]
-- x2 = [Sp + 16]
-- ...
-- [Sp + 8] = xi
-- [Sp + 16] = xj
--
-- Note that SpMem is invalidated if Sp is changed, but the definition
-- of 'conflicts' above handles that.
-- ToDo: this won't currently fix the following commonly occurring code:
-- x1 = [R1 + 8]
-- x2 = [R1 + 16]
-- ..
-- [Hp - 8] = x1
-- [Hp - 16] = x2
-- ..
-- because [R1 + 8] and [Hp - 8] are both HeapMem. We know that
-- assignments to [Hp + n] do not conflict with any other heap memory,
-- but this is tricky to nail down. What if we had
--
-- x = Hp + n
-- [x] = ...
--
-- the store to [x] should be "new heap", not "old heap".
-- Furthermore, you could imagine that if we started inlining
-- functions in Cmm then there might well be reads of heap memory
-- that was written in the same basic block. To take advantage of
-- non-aliasing of heap memory we will have to be more clever.
-- Note [Foreign calls clobber heap]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- It is tempting to say that foreign calls clobber only
-- non-heap/stack memory, but unfortunately we break this invariant in
-- the RTS. For example, in stg_catch_retry_frame we call
-- stmCommitNestedTransaction() which modifies the contents of the
-- TRec it is passed (this actually caused incorrect code to be
-- generated).
--
-- Since the invariant is true for the majority of foreign calls,
-- perhaps we ought to have a special annotation for calls that can
-- modify heap/stack memory. For now we just use the conservative
-- definition here.
--
-- Some CallishMachOp imply a memory barrier e.g. AtomicRMW and
-- therefore we should never float any memory operations across one of
-- these calls.
bothMems :: AbsMem -> AbsMem -> AbsMem
bothMems NoMem x = x
bothMems x NoMem = x
bothMems HeapMem HeapMem = HeapMem
bothMems StackMem StackMem = StackMem
bothMems (SpMem o1 w1) (SpMem o2 w2)
| o1 == o2 = SpMem o1 (max w1 w2)
| otherwise = StackMem
bothMems SpMem{} StackMem = StackMem
bothMems StackMem SpMem{} = StackMem
bothMems _ _ = AnyMem
memConflicts :: AbsMem -> AbsMem -> Bool
memConflicts NoMem _ = False
memConflicts _ NoMem = False
memConflicts HeapMem StackMem = False
memConflicts StackMem HeapMem = False
memConflicts SpMem{} HeapMem = False
memConflicts HeapMem SpMem{} = False
memConflicts (SpMem o1 w1) (SpMem o2 w2)
| o1 < o2 = o1 + w1 > o2
| otherwise = o2 + w2 > o1
memConflicts _ _ = True
exprMem :: DynFlags -> CmmExpr -> AbsMem
exprMem dflags (CmmLoad addr w) = bothMems (loadAddr dflags addr (typeWidth w)) (exprMem dflags addr)
exprMem dflags (CmmMachOp _ es) = foldr bothMems NoMem (map (exprMem dflags) es)
exprMem _ _ = NoMem
loadAddr :: DynFlags -> CmmExpr -> Width -> AbsMem
loadAddr dflags e w =
case e of
CmmReg r -> regAddr dflags r 0 w
CmmRegOff r i -> regAddr dflags r i w
_other | regUsedIn dflags (CmmGlobal Sp) e -> StackMem
| otherwise -> AnyMem
regAddr :: DynFlags -> CmmReg -> Int -> Width -> AbsMem
regAddr _ (CmmGlobal Sp) i w = SpMem i (widthInBytes w)
regAddr _ (CmmGlobal Hp) _ _ = HeapMem
regAddr _ (CmmGlobal CurrentTSO) _ _ = HeapMem -- important for PrimOps
regAddr dflags r _ _ | isGcPtrType (cmmRegType dflags r) = HeapMem -- yay! GCPtr pays for itself
regAddr _ _ _ _ = AnyMem
{-
Note [Inline GlobalRegs?]
Should we freely inline GlobalRegs?
Actually it doesn't make a huge amount of difference either way, so we
*do* currently treat GlobalRegs as "trivial" and inline them
everywhere, but for what it's worth, here is what I discovered when I
(SimonM) looked into this:
Common sense says we should not inline GlobalRegs, because when we
have
x = R1
the register allocator will coalesce this assignment, generating no
code, and simply record the fact that x is bound to $rbx (or
whatever). Furthermore, if we were to sink this assignment, then the
range of code over which R1 is live increases, and the range of code
over which x is live decreases. All things being equal, it is better
for x to be live than R1, because R1 is a fixed register whereas x can
live in any register. So we should neither sink nor inline 'x = R1'.
However, not inlining GlobalRegs can have surprising
consequences. e.g. (cgrun020)
c3EN:
_s3DB::P64 = R1;
_c3ES::P64 = _s3DB::P64 & 7;
if (_c3ES::P64 >= 2) goto c3EU; else goto c3EV;
c3EU:
_s3DD::P64 = P64[_s3DB::P64 + 6];
_s3DE::P64 = P64[_s3DB::P64 + 14];
I64[Sp - 8] = c3F0;
R1 = _s3DE::P64;
P64[Sp] = _s3DD::P64;
inlining the GlobalReg gives:
c3EN:
if (R1 & 7 >= 2) goto c3EU; else goto c3EV;
c3EU:
I64[Sp - 8] = c3F0;
_s3DD::P64 = P64[R1 + 6];
R1 = P64[R1 + 14];
P64[Sp] = _s3DD::P64;
but if we don't inline the GlobalReg, instead we get:
_s3DB::P64 = R1;
if (_s3DB::P64 & 7 >= 2) goto c3EU; else goto c3EV;
c3EU:
I64[Sp - 8] = c3F0;
R1 = P64[_s3DB::P64 + 14];
P64[Sp] = P64[_s3DB::P64 + 6];
This looks better - we managed to inline _s3DD - but in fact it
generates an extra reg-reg move:
.Lc3EU:
movq $c3F0_info,-8(%rbp)
movq %rbx,%rax
movq 14(%rbx),%rbx
movq 6(%rax),%rax
movq %rax,(%rbp)
because _s3DB is now live across the R1 assignment, we lost the
benefit of coalescing.
Who is at fault here? Perhaps if we knew that _s3DB was an alias for
R1, then we would not sink a reference to _s3DB past the R1
assignment. Or perhaps we *should* do that - we might gain by sinking
it, despite losing the coalescing opportunity.
Sometimes not inlining global registers wins by virtue of the rule
about not inlining into arguments of a foreign call, e.g. (T7163) this
is what happens when we inlined F1:
_s3L2::F32 = F1;
_c3O3::F32 = %MO_F_Mul_W32(F1, 10.0 :: W32);
(_s3L7::F32) = call "ccall" arg hints: [] result hints: [] rintFloat(_c3O3::F32);
but if we don't inline F1:
(_s3L7::F32) = call "ccall" arg hints: [] result hints: [] rintFloat(%MO_F_Mul_W32(_s3L2::F32,
10.0 :: W32));
-}
| urbanslug/ghc | compiler/cmm/CmmSink.hs | bsd-3-clause | 29,851 | 0 | 17 | 7,980 | 4,292 | 2,363 | 1,929 | 244 | 5 |
module Models.Task where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger (NoLoggingT, runNoLoggingT)
import Control.Monad.Trans.Resource (ResourceT, runResourceT)
import Data.Text (Text)
import Data.Time (UTCTime)
import Database.Persist (Entity, Key, SelectOpt(LimitTo), (=.), deleteWhere, selectList)
import Database.Persist.Sql (SqlBackend, ToBackendKey, delete, insert, toSqlKey, update)
import Database.Persist.Sqlite (SqlPersistT, runSqlConn, withSqliteConn)
import Database.Persist.TH (mkMigrate, mkPersist, persistLowerCase, share, sqlSettings)
import Database.Persist.Types (PersistValue(PersistInt64))
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Task
title String
content Text
createdAt UTCTime
done Bool
deriving Show
|]
runDb :: SqlPersistT (ResourceT (NoLoggingT IO)) a -> IO a
runDb query = runNoLoggingT . runResourceT . withSqliteConn "dev.sqlite3" . runSqlConn $ query
readTasks :: IO [Entity Task]
readTasks = (runDb $ selectList [] [LimitTo 10])
saveTask :: MonadIO m => String -> Text -> UTCTime -> m (Key Task)
saveTask title content time = liftIO $ runDb $ insert $ Task title content time False
toKey :: ToBackendKey SqlBackend a => Integer -> Key a
toKey i = toSqlKey $ fromIntegral (i :: Integer)
markTaskAsDone :: MonadIO m => Integer -> UTCTime -> m ()
markTaskAsDone id_ time = liftIO $ runDb $ update (toKey id_ :: TaskId) [TaskDone =. True]
deleteTask :: MonadIO m => Integer -> m ()
deleteTask id_ = liftIO $ runDb $ delete (toKey id_ :: TaskId)
| quephird/todo.hs | src/Models/Task.hs | mit | 1,563 | 0 | 11 | 232 | 522 | 288 | 234 | -1 | -1 |
module Logic.Data.Units where
import Logic.Types
import qualified Data.Map as Map
import Control.Lens
unitsBase :: Map.Map UnitType UnitData
unitsBase = Map.fromList [
(UnitType 1, marine)
]
marine = UnitData {
_maxHp = 50,
_attackValue = 8,
_attackSpeed = 0.5,
_movementSpeed = 0.5
} | HarvestGame/logic-prototype | src/Logic/Data/Units.hs | mit | 331 | 0 | 8 | 88 | 90 | 55 | 35 | 12 | 1 |
--
--
--
------------------
-- Exercise 13.24.
------------------
--
--
--
module E'13'24 where
| pascal-knodel/haskell-craft | Chapter 13/E'13'24.hs | mit | 106 | 0 | 2 | 24 | 13 | 12 | 1 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Copyright 2014-2015 Anchor Systems, Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the 3-clause BSD licence.
--
-- /Description/
-- This module defines the Result type and how it's presented.
--
module Borel.Types.Result
( -- * Query results
Result
, ResponseItem(..)
, respResource, respResourceID, respVal
, mkItem
-- * Convenient
, uomVal
) where
import Control.Applicative
import Control.Lens hiding ((.=))
import Control.Monad
import Data.Aeson hiding (Result)
import Data.Csv (FromRecord, ToRecord, parseRecord, record,
toField, toRecord, (.!))
import Data.Text (Text)
import qualified Data.Vector as V
import Data.Word
import Ceilometer.Tags
import Vaultaire.Types
import Borel.Error
import Borel.Types.Metric
import Borel.Types.UOM
type Result = (Metric, Word64)
type Val = (UOM, Word64)
data ResponseItem = ResponseItem
{ _respResource :: Text
, _respResourceID :: Text
, _respVal :: Val }
deriving (Eq, Show, Read)
makeLenses ''ResponseItem
instance FromJSON ResponseItem where
parseJSON (Object x)
= ResponseItem
<$> x .: "resource"
<*> x .: "resource-id"
<*> ((,) <$> x .: "uom"
<*> x .: "quantity")
parseJSON _ = mzero
instance ToJSON ResponseItem where
toJSON (ResponseItem n i (u,x))
= object [ "resource" .= n
, "resource-id" .= i
, "uom" .= u
, "quantity" .= x ]
instance FromRecord ResponseItem where
parseRecord v
| V.length v == 4 = ResponseItem
<$> v .! 0
<*> v .! 1
<*> ((,) <$> v .! 2
<*> v .! 3)
| otherwise = mzero
instance ToRecord ResponseItem where
toRecord (ResponseItem n i (u,v))
= record [ toField n
, toField i
, toField u
, toField v ]
mkItem :: SourceDict -> Result -> ResponseItem
mkItem sd (metric, quantity)
= let name = pretty metric
uid = stopBorelError $ lookupSD keyResourceID sd
in ResponseItem name uid (uom metric, quantity)
-- Some convenient traversals
uomVal :: Lens' ResponseItem Val
uomVal f (ResponseItem x y v)
= ResponseItem x y <$> f v
| anchor/borel | lib/Borel/Types/Result.hs | mit | 2,690 | 0 | 13 | 905 | 628 | 354 | 274 | 67 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{- |
Module : Orville.PostgreSQL.Expr.Where.ValueExpression
Copyright : Flipstone Technology Partners 2016-2021
License : MIT
-}
module Orville.PostgreSQL.Internal.Expr.ValueExpression
( ValueExpression,
columnReference,
valueExpression,
rowValueConstructor,
)
where
import qualified Data.List.NonEmpty as NE
import Orville.PostgreSQL.Internal.Expr.Name (ColumnName)
import qualified Orville.PostgreSQL.Internal.RawSql as RawSql
import Orville.PostgreSQL.Internal.SqlValue (SqlValue)
newtype ValueExpression = ValueExpression RawSql.RawSql
deriving (RawSql.SqlExpression)
columnReference :: ColumnName -> ValueExpression
columnReference = ValueExpression . RawSql.toRawSql
valueExpression :: SqlValue -> ValueExpression
valueExpression = ValueExpression . RawSql.parameter
rowValueConstructor :: NE.NonEmpty ValueExpression -> ValueExpression
rowValueConstructor elements =
ValueExpression $
RawSql.leftParen
<> RawSql.intercalate RawSql.comma elements
<> RawSql.rightParen
| flipstone/orville | orville-postgresql-libpq/src/Orville/PostgreSQL/Internal/Expr/ValueExpression.hs | mit | 1,066 | 0 | 8 | 137 | 176 | 107 | 69 | 22 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module: Network.SIP.Parser.ResponseLine
-- Description: Response line parser.
-- Copyright: Copyright (c) 2015-2016 Jan Sipr
-- License: MIT
module Network.SIP.Parser.ResponseLine
( firstLineParser
)
where
import Control.Applicative ((<*))
import Control.Monad ((>>=), return, fail)
import Data.Attoparsec.ByteString.Char8 (char, decimal)
import Data.Attoparsec.ByteString (Parser, takeByteString)
import Data.Bool ((&&), otherwise)
import Data.Function (($), (.))
import Data.Functor (fmap)
import Data.List (lookup)
import Data.Maybe (maybe)
import Data.Monoid ((<>))
import Data.Ord ((<), (>=))
import Data.Text.Encoding (decodeUtf8)
import Data.Tuple (fst, snd)
import Text.Show (show)
import Network.SIP.Parser.SipVersion (sipVersionParser)
import Network.SIP.Type.Message (MessageType(Response))
import Network.SIP.Type.ResponseStatus
( ResponseCode(Unknown)
, Status(Status)
, UnknownResponseCode
( Unknown_1xx
, Unknown_2xx
, Unknown_3xx
, Unknown_4xx
, Unknown_5xx
, Unknown_6xx
)
, responseStatusMap
)
firstLineParser :: Parser MessageType
firstLineParser = do
_ <- sipVersionParser <* char ' '
code <- (decimal <* char ' ') >>= typeStatusCode
statusMsg <- fmap decodeUtf8 takeByteString
return . Response $ Status code statusMsg
where
typeStatusCode c =
maybe (unknownStatusCode c) return $ lookup c $ fmap (\x -> (fst $ snd x, fst x)) responseStatusMap
unknownStatusCode c
| c >= 100 && c < 200 = return $ Unknown Unknown_1xx
| c < 300 = return $ Unknown Unknown_2xx
| c < 400 = return $ Unknown Unknown_3xx
| c < 500 = return $ Unknown Unknown_4xx
| c < 600 = return $ Unknown Unknown_5xx
| c < 700 = return $ Unknown Unknown_6xx
| otherwise =
fail $ "Status code must be bettwen <100 - 699>, but this one is: "
<> show c
| Siprj/ragnarok | src/Network/SIP/Parser/ResponseLine.hs | mit | 2,017 | 0 | 13 | 456 | 565 | 322 | 243 | 49 | 1 |
-- Copyright (C) 2014 Google Inc. All rights reserved.
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may not
-- use this file except in compliance with the License. You may obtain a copy
-- of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations
-- under the License.
module Gemstone.Maths where
-- | Modified Moving Average.
mma :: Fractional a => a -> a -> a
mma new old = (19 * old + new) / 20
| MostAwesomeDude/gemstone | Gemstone/Maths.hs | mit | 739 | 0 | 8 | 129 | 65 | 41 | 24 | 3 | 1 |
a = fmap (+1) $ read "[1]" :: [Int]
b = (fmap . fmap) (++ "lol") (Just ["Hi,","Hello"])
-- same as (*2) . (\x -> x - 2)
c = fmap (*2) (\x -> x - 2)
d = fmap ((return '1'++) . show) (\x -> [x,1..3])
e :: IO Integer
e = let ioi = readIO "1" :: IO Integer
--changed = fmap read $ fmap ("123"++) $ fmap show ioi
changed = fmap (read . ("123"++) . show) ioi
in fmap (*3) changed
| JustinUnger/haskell-book | ch16/functor-ex1.hs | mit | 399 | 3 | 13 | 110 | 211 | 110 | 101 | 8 | 1 |
{--
Copyright (c) 2012 Gorka Suárez García
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--}
-- ***************************************************************
-- Primes example application
-- Make: ghc -main-is Primes Primes.hs
-- ***************************************************************
module Primes (main) where
squareRoot :: (Integral a) => a -> a
squareRoot x = truncate $ sqrt $ fromIntegral x
multipleOf :: (Integral a) => a -> a -> Bool
multipleOf a b = (mod a b) == 0
isPrime :: (Integral a) => a -> Bool
isPrime 2 = True
isPrime n = not $ or [multipleOf n x | x <- 2:[3,5..upperLimit]]
where upperLimit = squareRoot n + 1
primeTest n = do putStrLn (show n ++ " is prime?")
putStrLn (show $ isPrime n)
main = primeTest 1234567891 | gorkinovich/Haskell | Others/Primes.hs | mit | 1,751 | 0 | 11 | 305 | 226 | 118 | 108 | 12 | 1 |
{-# htermination (compareChar :: Char -> Char -> Ordering) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Char = Char MyInt ;
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
data Ordering = LT | EQ | GT ;
primCmpNat :: Nat -> Nat -> Ordering;
primCmpNat Zero Zero = EQ;
primCmpNat Zero (Succ y) = LT;
primCmpNat (Succ x) Zero = GT;
primCmpNat (Succ x) (Succ y) = primCmpNat x y;
primCmpInt :: MyInt -> MyInt -> Ordering;
primCmpInt (Pos Zero) (Pos Zero) = EQ;
primCmpInt (Pos Zero) (Neg Zero) = EQ;
primCmpInt (Neg Zero) (Pos Zero) = EQ;
primCmpInt (Neg Zero) (Neg Zero) = EQ;
primCmpInt (Pos x) (Pos y) = primCmpNat x y;
primCmpInt (Pos x) (Neg y) = GT;
primCmpInt (Neg x) (Pos y) = LT;
primCmpInt (Neg x) (Neg y) = primCmpNat y x;
primCmpChar :: Char -> Char -> Ordering;
primCmpChar (Char x) (Char y) = primCmpInt x y;
compareChar :: Char -> Char -> Ordering
compareChar = primCmpChar;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/compare_4.hs | mit | 993 | 0 | 8 | 223 | 445 | 241 | 204 | 25 | 1 |
module SSH.Key
( KeyBox
, PublicKey(..)
, PrivateKey(..)
, parseKey
, serialiseKey
, publicKeys
, privateKeys
, putPublicKey
) where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (unless, replicateM)
import Data.Binary.Get (Get, getWord32be, getByteString, getRemainingLazyByteString)
import Data.Binary.Put (Put, putWord32be, putByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Char8 as BC
import Data.ByteString.Lazy (toStrict)
import Data.Monoid ((<>))
import SSH.Types (getWord32be', getString, putString, runStrictGet, runStrictPut)
data KeyBox = KeyBox
{ ciphername :: B.ByteString
, _kdfname :: B.ByteString
, _kdfoptions :: B.ByteString
, keycount :: Int
, boxPublicKeys :: B.ByteString
, boxPrivateKeys :: B.ByteString
} deriving (Show)
auth_magic :: B.ByteString
auth_magic = "openssh-key-v1\000"
expected_padding :: B.ByteString
expected_padding = BC.pack ['\001'..'\377']
armor_start :: B.ByteString
armor_start = "-----BEGIN OPENSSH PRIVATE KEY-----"
armor_end :: B.ByteString
armor_end = "-----END OPENSSH PRIVATE KEY-----"
data PublicKey = Ed25519PublicKey
{ publicKeyData :: B.ByteString }
deriving (Show)
data PrivateKey = Ed25519PrivateKey
{ publicKey :: PublicKey
, privateKeyData :: B.ByteString
, privateKeyComment :: B.ByteString
}
deriving (Show)
dearmorPrivateKey :: B.ByteString -> Either String B.ByteString
dearmorPrivateKey =
B64.decode
. B.concat
. takeWhile (/= armor_end)
. drop 1
. dropWhile (/= armor_start)
. BC.lines
armorPrivateKey :: B.ByteString -> B.ByteString
armorPrivateKey k =
armor_start <> "\n"
<> B64.joinWith "\n" 70 (B64.encode k)
<> armor_end <> "\n"
getKeyBox :: Get KeyBox
getKeyBox = do
magic <- getByteString (B.length auth_magic)
unless (magic == auth_magic) (fail "Magic does not match")
cn <- getString
unless (cn == "none") (fail "Unsupported cipher")
kn <- getString
unless (kn == "none") (fail "Unsupported kdf")
ko <- getString
unless (ko == "") (fail "Invalid kdf options")
count <- getWord32be'
publicData <- getString
privateData <- getString
return $ KeyBox cn kn ko count publicData privateData
putKeyBox :: PrivateKey -> Put
putKeyBox key = do
putByteString auth_magic
putString "none"
putString "none"
putString ""
putWord32be 1
putPublicKeys [publicKey key]
putPrivateKeys [key]
publicKeys :: KeyBox -> [PublicKey]
publicKeys box = flip runStrictGet (boxPublicKeys box) $
replicateM (keycount box) $ do
keyType <- getString
case keyType of
"ssh-ed25519" -> Ed25519PublicKey <$> getString
_ -> fail "Unsupported key type"
putPublicKeys :: [PublicKey] -> Put
putPublicKeys = putString . runStrictPut . mapM_ putPublicKey
putPublicKey :: PublicKey -> Put
putPublicKey (Ed25519PublicKey k) = do
putString "ssh-ed25519"
putString k
getPrivateKey :: Get PrivateKey
getPrivateKey = do
keyType <- getString
case keyType of
"ssh-ed25519" -> Ed25519PrivateKey
<$> (Ed25519PublicKey <$> getString)
<*> getString
<*> getString
_ -> fail "Unsupported key type"
putPrivateKey :: PrivateKey -> Put
putPrivateKey (Ed25519PrivateKey pk k c) = do
putString "ssh-ed25519"
putString (publicKeyData pk)
putString k
putString c
getPrivateKeys :: Int -> Get [PrivateKey]
getPrivateKeys count = do
checkint1 <- getWord32be
checkint2 <- getWord32be
unless (checkint1 == checkint2) (fail "Decryption failed")
keys <- replicateM count getPrivateKey
padding <- toStrict <$> getRemainingLazyByteString
unless (B.take (B.length padding) expected_padding == padding) (fail "Incorrect padding")
return keys
putPrivateKeys :: [PrivateKey] -> Put
putPrivateKeys keys = putString . pad 8 . runStrictPut $ do
putWord32be 0
putWord32be 0
mapM_ putPrivateKey keys
where pad a s | B.length s `rem` a == 0 = s
| otherwise = s <> B.take (a - B.length s `rem` a) expected_padding
privateKeys :: KeyBox -> [PrivateKey]
privateKeys box | ciphername box == "none" =
runStrictGet (getPrivateKeys $ keycount box) (boxPrivateKeys box)
| otherwise = error "Unsupported encryption type"
parseKey :: BC.ByteString -> Either String KeyBox
parseKey = fmap (runStrictGet getKeyBox) . dearmorPrivateKey
serialiseKey :: PrivateKey -> B.ByteString
serialiseKey = armorPrivateKey . runStrictPut . putKeyBox
| mithrandi/ssh-key-generator | SSH/Key.hs | mit | 4,843 | 0 | 14 | 1,187 | 1,358 | 701 | 657 | 131 | 2 |
-- | Traversing mutable vectors.
module Data.Vector.Generic.Mutable.Loops where
import Control.Monad.Primitive
import Data.Vector.Generic.Mutable as MG
type Loop m v a = v (PrimState m) a -> (a -> m ()) -> m ()
type ILoop m v a = v (PrimState m) a -> (Int -> a -> m ()) -> m ()
{-# INLINE iForM_ #-}
iForM_ :: (MG.MVector v a, PrimMonad m) => ILoop m v a
iForM_ v f = for' 0 (MG.length v) $ \i -> MG.unsafeRead v i >>= f i
{-# INLINE forM_ #-}
forM_ :: (MG.MVector v a, PrimMonad m) => Loop m v a
forM_ v = iForM_ v . const
-- @forM_ [0 .. n-1]@ somehow runs out of memory
for' i n f | i == n = return ()
for' i n f = f i >> for' (i+1) n f
| Lysxia/twentyseven | src/Data/Vector/Generic/Mutable/Loops.hs | mit | 645 | 0 | 11 | 146 | 305 | 161 | 144 | 13 | 1 |
module Main ( main ) where
import OpenGLRenderer
import Utils
import Utils.GL
import Tiles
import Tiles.Renderer
import TestTiles as TT
import TestRenderer
import Data.Map (fromList)
import Data.IORef
import Graphics.UI.GLUT hiding (Point)
player1 = Owner "1" "xxPLAYERxx"
player2 = Owner "2" "__player__"
coords :: [TileId]
coords = [Point x y | x <- [0, 5], y <- [0, 1]]
--coords = do
-- x <- [0, 1]
-- y <- [0, 1]
-- return $ Coordinate x y
--coords = [0, 1] >>= (
-- \x -> [0, 1] >>= (
-- \y ->
-- return $ Coordinate x y
-- )
-- )
tls :: [TT.Tile]
tls = [
Tile (Point 0 0) Sea (Nothing, Storm) []
, Tile (Point 0 1) Sea (Nothing, Storm) []
, Tile (Point 1 0) Sea (Nothing, Rain) []
, Tile (Point 1 1) Sea (Nothing, Storm) []
, Tile (Point 2 0) Sea (Nothing, Rain) []
, Tile (Point 2 1) Sea (Nothing, Storm) []
, Tile (Point 3 0) Sea (Nothing, Rain) []
, Tile (Point 3 1) Plain (Just player1, Cloudy) []
, Tile (Point 4 0) Hill (Just player2, Rain) []
, Tile (Point 4 1) Mountain (Nothing, Sunny) []
]
neighbours :: Neighbours TileId
neighbours = fromList $ map f tls
where f = \(Tile id _ _ _) -> (id, filter (id /=) coords)
type World = TT.Map
world :: World
world = Tiles.Map (mkTiles tls) Main.neighbours
reshaped :: ReshapeCallback --Mutator World
reshaped size = do putStrLn $ "viewport"
viewport $= (mkPosition 0 0, mkSize 400 400) -- size
postRedisplay Nothing
mkPosition :: Int -> Int -> Position
mkPosition x y = Position (glInt x) (glInt y)
mkSize :: Int -> Int -> Size
mkSize w h = Size (glInt w) (glInt h)
keyCallbacks :: Maybe (Window -> IORef(Camera Int) -> KeyboardCallback)
keyCallbacks = Just $ \w -> \cRef -> \key pos -> case key of '\ESC' -> do destroyWindow w
_ -> return () --putStrLn $ "key " ++ show key
keySpecialCallbacks :: Maybe (Window -> IORef(Camera Int) -> SpecialCallback)
keySpecialCallbacks = Just $ \w -> \cRef -> \key pos -> case key of KeyUp -> moveCamera cRef Main.Up
KeyRight -> moveCamera cRef Main.Right
KeyDown -> moveCamera cRef Main.Down
KeyLeft -> moveCamera cRef Main.Left
_ -> return ()
initialCamera = Rect { topLeft = Point 0 0
, bottomRight = Point 5 5
}
data Direction = Left | Right | Up | Down deriving Show
moveCamera :: IORef (Camera Int) -> Direction -> IO()
moveCamera cameraRef dir = do camera <- readIORef cameraRef
putStrLn $ "dir = " ++ show dir
let updCamera fx fy = Rect ptT ptB
where ffx g = fx . x . g $ camera
ffy g = fy . y . g $ camera
ptT = Point (ffx topLeft) (ffy topLeft)
ptB = Point (ffx bottomRight) (ffy bottomRight)
let id x = x
let minus1 x = x - 1
let plus1 x = x + 1
let nCamera = case dir of Main.Left -> updCamera minus1 id
Main.Right -> updCamera plus1 id
Main.Up -> updCamera id plus1
Main.Down -> updCamera id minus1
writeIORef cameraRef nCamera
postRedisplay Nothing
cameraVar :: IO( IORef (Camera Int) )
cameraVar = newIORef initialCamera
render :: IORef (Camera Int) -> Renderer World
render cameraRef = do renderMap before after cameraRef
where before = do clear [ColorBuffer]
loadIdentity
color $ rgb2GLcolor 255 255 255
renderPrimitive Quads $ tileQuad (1 :: GLfloat)
after = flush
callbacks = Callbacks{ callReshape = Nothing
, callKey = keyCallbacks
, callSpecKey = keySpecialCallbacks
}
main :: IO()
main = run cameraVar render Nothing callbacks world
| fehu/hgt | tiles-test/src/Main.hs | mit | 4,728 | 0 | 14 | 2,082 | 1,383 | 717 | 666 | 84 | 5 |
{-
-- LoGoff system
-}
module Logoff where
import Datatypes
import Data.Maybe
{------------------------------------------------------------------------------}
-- Axiom block
{------------------------------------------------------------------------------}
-- isAx verifies if a sequent is an Ax-type axiom
isAx :: Sequent -> Bool
isAx (RFocus (IStruct (P (Positive i))) (P (Positive o))) =
o == i
isAx _ = False
-- isCoAx verifies if a sequent is a CoAx-type axiom
isCoAx :: Sequent -> Bool
isCoAx (LFocus (N (Negative i)) (OStruct (N (Negative o)))) =
o == i
isCoAx _ = False
{------------------------------------------------------------------------------}
-- Focusing block
-- Note that if the functions can't treat the given sequent, they return it
{------------------------------------------------------------------------------}
-- Defocus right (or top-down focus right)
defocusR :: Sequent -> Sequent
defocusR (RFocus i (P o)) = Neutral i (OStruct (P o))
defocusR s = s
-- Inverse defocus right (top-down focus right)
idefocusR :: Sequent -> Sequent
idefocusR (Neutral i (OStruct (P o))) = RFocus i (P o)
idefocusR s = s
-- Defocus left (or top-down focus left)
defocusL :: Sequent -> Sequent
defocusL (LFocus (N i) o) = Neutral (IStruct (N i)) o
defocusL s = s
-- Inverse defocus left (top-down focus left)
idefocusL :: Sequent -> Sequent
idefocusL (Neutral (IStruct (N i)) o) = LFocus (N i) o
idefocusL s = s
-- Focus right (or top-down defocus right)
focusR :: Sequent -> Sequent
focusR (Neutral i (OStruct (N o))) = RFocus i (N o)
focusR s = s
-- Inverse focus right (top-down defocus right)
ifocusR :: Sequent -> Sequent
ifocusR (RFocus i (N o)) = Neutral i (OStruct (N o))
ifocusR s = s
-- Focus left (or top-down defocus left)
focusL :: Sequent -> Sequent
focusL (Neutral (IStruct (P i)) o) = LFocus (P i) o
focusL s = s
-- Inverse focus left (top-down defocus left)
ifocusL :: Sequent -> Sequent
ifocusL (LFocus (P i) o) = Neutral (IStruct (P i)) o
ifocusL s = s
{------------------------------------------------------------------------------}
-- Monotonicity block
-- Note that if the functions can't treat the given sequent, they return the
-- left one
{------------------------------------------------------------------------------}
-- Tensor - introduces tensor
monoTensor :: Sequent -> Sequent -> Sequent
monoTensor (RFocus xi xo) (RFocus yi yo) =
RFocus (STensor xi yi) (P (Tensor xo yo))
monoTensor l r = l
-- Sum - introduces sum
monoSum :: Sequent -> Sequent -> Sequent
monoSum (LFocus xi xo) (LFocus yi yo) = LFocus (N (Sum xi yi)) (SSum xo yo)
monoSum l r = l
-- Left division - introduces LDiv
monoLDiv :: Sequent -> Sequent -> Sequent
monoLDiv (RFocus xi xo) (LFocus yi yo) = LFocus (N (LDiv xo yi)) (SLDiv xi yo)
monoLDiv l r = l
-- Right division - introduces RDiv
monoRDiv :: Sequent -> Sequent -> Sequent
monoRDiv (LFocus yi yo) (RFocus xi xo) = LFocus (N (RDiv yi xo)) (SRDiv yo xi)
monoRDiv l r = l
-- Left difference - introduces LDiff
monoLDiff :: Sequent -> Sequent -> Sequent
monoLDiff (LFocus yi yo) (RFocus xi xo) =
RFocus (SLDiff yo xi) (P (LDiff yi xo))
monoLDiff l r = l
-- Right difference - introduces RDiff
monoRDiff :: Sequent -> Sequent -> Sequent
monoRDiff (RFocus xi xo) (LFocus yi yo) =
RFocus (SRDiff xi yo) (P (RDiff xo yi))
monoRDiff l r = l
{------------------------------------------------------------------------------}
-- Inverse monotonicity block
-- Note that if the functions can't treat the given sequent, they return it
{------------------------------------------------------------------------------}
-- Tensor - removes tensor
iMonoTensor :: Sequent -> (Sequent, Sequent)
iMonoTensor (RFocus (STensor xi yi) (P (Tensor xo yo))) =
(RFocus xi xo, RFocus yi yo)
iMonoTensor s = (s,s)
-- Sum - removes sum
iMonoSum :: Sequent -> (Sequent, Sequent)
iMonoSum (LFocus (N (Sum xi yi)) (SSum xo yo)) =
(LFocus xi xo, LFocus yi yo)
iMonoSum s = (s,s)
-- Left division - removes LDiv
iMonoLDiv :: Sequent -> (Sequent, Sequent)
iMonoLDiv (LFocus (N (LDiv xo yi)) (SLDiv xi yo)) =
(RFocus xi xo, LFocus yi yo)
iMonoLDiv s = (s,s)
-- Right division - removes RDiv
iMonoRDiv :: Sequent -> (Sequent, Sequent)
iMonoRDiv (LFocus (N (RDiv yi xo)) (SRDiv yo xi)) =
(LFocus yi yo, RFocus xi xo)
iMonoRDiv s = (s,s)
-- Left difference - removes LDiff
iMonoLDiff :: Sequent -> (Sequent, Sequent)
iMonoLDiff (RFocus (SLDiff yo xi) (P (LDiff yi xo))) =
(LFocus yi yo, RFocus xi xo)
iMonoLDiff s = (s,s)
-- Right difference - removes RDiff
iMonoRDiff :: Sequent -> (Sequent, Sequent)
iMonoRDiff (RFocus (SRDiff xi yo) (P (RDiff xo yi))) =
(RFocus xi xo, LFocus yi yo)
iMonoRDiff s = (s,s)
{------------------------------------------------------------------------------}
-- Residuation block
-- Note that if the functions can't treat the given sequent, they return it
{------------------------------------------------------------------------------}
-- residuate1 - Downwards R1 rule
residuate1 :: Int -> Sequent -> Sequent
residuate1 1 (Neutral x (SRDiv z y)) = Neutral (STensor x y) z
residuate1 2 (Neutral (STensor x y) z) = Neutral y (SLDiv x z)
residuate1 _ s = s
-- residuate1i - Upwards (inverted) R1 rule
residuate1i :: Int -> Sequent -> Sequent
residuate1i 2 (Neutral y (SLDiv x z)) = Neutral (STensor x y) z
residuate1i 1 (Neutral (STensor x y) z) = Neutral x (SRDiv z y)
residuate1i _ s = s
-- residuate2 - Downwards R2 rule
residuate2 :: Int -> Sequent -> Sequent
residuate2 1 (Neutral (SLDiff y z) x) = Neutral z (SSum y x)
residuate2 2 (Neutral z (SSum y x)) = Neutral (SRDiff z x) y
residuate2 _ s = s
-- residuate2i - Upwards (inverted) R2 rule
residuate2i :: Int -> Sequent -> Sequent
residuate2i 2 (Neutral (SRDiff z x) y) = Neutral z (SSum y x)
residuate2i 1 (Neutral z (SSum y x)) = Neutral (SLDiff y z) x
residuate2i _ s = s
{------------------------------------------------------------------------------}
-- Rewrite block
-- Note that if the functions can't treat the given sequent, they return it
{------------------------------------------------------------------------------}
-- rewriteL - rewrites tensor, left and right difference (structure to logical)
rewriteL :: Sequent -> Sequent
rewriteL (Neutral (STensor (IStruct x) (IStruct y)) o) =
Neutral (IStruct (P (Tensor x y))) o
rewriteL (Neutral (SRDiff (IStruct x) (OStruct y)) o) =
Neutral (IStruct (P (RDiff x y))) o
rewriteL (Neutral (SLDiff (OStruct x) (IStruct y)) o) =
Neutral (IStruct (P (LDiff x y))) o
rewriteL s = s
-- rewriteR - rewrites sum, left and right division (structure to logical)
rewriteR :: Sequent -> Sequent
rewriteR (Neutral i (SSum (OStruct x) (OStruct y))) =
Neutral i (OStruct (N (Sum x y)))
rewriteR (Neutral i (SRDiv (OStruct x) (IStruct y))) =
Neutral i (OStruct (N (RDiv x y)))
rewriteR (Neutral i (SLDiv (IStruct x) (OStruct y))) =
Neutral i (OStruct (N (LDiv x y)))
rewriteR s = s
-- rewriteLi - rewrites tensor, left and right difference (logical to structure)
rewriteLi :: Sequent -> Sequent
rewriteLi (Neutral (IStruct (P (Tensor x y))) o) =
Neutral (STensor (IStruct x) (IStruct y)) o
rewriteLi (Neutral (IStruct (P (RDiff x y))) o) =
Neutral (SRDiff (IStruct x) (OStruct y)) o
rewriteLi (Neutral (IStruct (P (LDiff x y))) o) =
Neutral (SLDiff (OStruct x) (IStruct y)) o
rewriteLi s = s
-- rewriteRi - rewrites sum, left and right division (logical to structure)
rewriteRi :: Sequent -> Sequent
rewriteRi (Neutral i (OStruct (N (Sum x y)))) =
Neutral i (SSum (OStruct x) (OStruct y))
rewriteRi (Neutral i (OStruct (N (RDiv x y)))) =
Neutral i (SRDiv (OStruct x) (IStruct y))
rewriteRi (Neutral i (OStruct (N (LDiv x y)))) =
Neutral i (SLDiv (IStruct x) (OStruct y))
rewriteRi s = s
{------------------------------------------------------------------------------}
-- Top-Down solver block
{------------------------------------------------------------------------------}
-- tdSolve - Master Top-Down solver
-- Also, yay maybe monad
tdSolve :: Sequent -> Maybe ProofTree
tdSolve s
| isAx s = Just (Ax s)
| isCoAx s = Just (CoAx s)
| otherwise = case tdSolveRewrite s of
Nothing -> case tdSolveMono s of
Nothing -> case tdSolveFocus s of
Nothing -> case tdSolveRes tdSolveResHelperList s of
Nothing -> Nothing
pt -> pt
pt -> pt
pt -> pt
pt -> pt
-- tdSolveHelperSpecial - master-solver following a residuation step to prevent
-- residuation looping
tdSolveHelperSpecial :: Residuation -> Sequent -> Maybe ProofTree
tdSolveHelperSpecial res s
| isAx s = Just (Ax s)
| isCoAx s = Just (CoAx s)
| otherwise = case tdSolveRewrite s of
Nothing -> case tdSolveMono s of
Nothing -> case tdSolveFocus s of
Nothing -> case tdSolveRes (tdSolveResHelperPermit res) s of
Nothing -> Nothing
pt -> pt
pt -> pt
pt -> pt
pt -> pt
-- tdSolveRewrite - solves rewriting
tdSolveRewrite :: Sequent -> Maybe ProofTree
tdSolveRewrite s = let
list = [(rewriteLi, RewriteL), (rewriteRi, RewriteR)]
complist = map (\(f,o) -> (f s, o)) list
res = dropWhile (\(ns, _) -> s == ns) complist in
case res of
((ns, o):_) -> case tdSolve ns of
(Just pt) -> Just (Unary s o pt)
otherwise -> Nothing
[] -> Nothing
-- tdSolveFocus - solves focusing
tdSolveFocus :: Sequent -> Maybe ProofTree
tdSolveFocus s = let
list = [(idefocusR, DeFocusR), (idefocusL, DeFocusL), (ifocusR, FocusR),
(ifocusL, FocusL)]
complist = map (\(f,o) -> (f s, o)) list
res = dropWhile (\(ns, _) -> s == ns) complist in
case res of
((ns, o):_) -> case tdSolve ns of
(Just pt) -> Just (Unary s o pt)
otherwise -> Nothing
[] -> Nothing
-- tdSolveMono - solves inverse monotonicity
tdSolveMono :: Sequent -> Maybe ProofTree
tdSolveMono s = let
list = [(iMonoTensor, MonoTensor), (iMonoSum, MonoSum), (iMonoLDiv, MonoLDiv),
(iMonoRDiv, MonoRDiv), (iMonoLDiff, MonoLDiff), (iMonoRDiff, MonoRDiff)]
complist = map (\(f,o) -> (f s, o)) list
res = dropWhile (\((ns,_), _) -> s == ns) complist in
case res of
(((ns1, ns2), o):_) -> case tdSolve ns1 of
(Just pt1) -> case tdSolve ns2 of
(Just pt2) -> Just (Binary s o pt1 pt2)
otherwise -> Nothing
otherwise -> Nothing
[] -> Nothing
-- tdSolveRes - solves residuation
tdSolveRes :: [(Sequent -> Sequent, Residuation)] -> Sequent -> Maybe ProofTree
tdSolveRes permit s = let
complist = map (\(f, o) -> (f s, o)) permit
residuations = [(ns, o) | (ns,o) <- complist, ns /= s] in
case tdSolveResHelperOptions residuations of
Nothing -> Nothing
(Just (pt, res)) -> Just (Unary s (Res res) pt)
-- tdSolveResHelperOptions - solves residuation, handles the actual branching
tdSolveResHelperOptions :: [(Sequent, Residuation)] ->
Maybe (ProofTree, Residuation)
tdSolveResHelperOptions [] = Nothing
tdSolveResHelperOptions ((s, res):xs) =
case tdSolveHelperSpecial (tdSolveResHelperGetInverse res) s of
Nothing -> tdSolveResHelperOptions xs
(Just pt) -> Just (pt, res)
-- tdSolveResHelperPermit - calculates new permit-list
tdSolveResHelperPermit :: Residuation -> [(Sequent -> Sequent, Residuation)]
tdSolveResHelperPermit res = filter (\(f, r) -> r /= res) tdSolveResHelperList
-- tdSolveResHelperGetInverse
tdSolveResHelperGetInverse :: Residuation -> Residuation
tdSolveResHelperGetInverse (Res1 i) = Res1i i
tdSolveResHelperGetInverse (Res1i i) = Res1 i
tdSolveResHelperGetInverse (Res2 i) = Res2i i
tdSolveResHelperGetInverse (Res2i i) = Res2 i
-- tdSolveResHelperList - list of functions and operation mappings
tdSolveResHelperList :: [(Sequent -> Sequent, Residuation)]
tdSolveResHelperList = [(f i,o i) | (f,o) <- [(residuate1, Res1),
(residuate2, Res2), (residuate1i, Res1i), (residuate2i, Res2i)], i <- [1,2]]
{------------------------------------------------------------------------------}
-- Bottom-up solver block
{------------------------------------------------------------------------------}
-- buSolve - master bottom-up solver
-- First argument is the target string/type pair. Second is the master Lexicon
buSolve :: LexItem -> Lexicon -> Maybe ProofTree
buSolve (ts, tt) le = let
le' = buDeriveLexicon (words ts) le
pps = buPartial le' in
case buCombine pps of
(Just (ps, pt)) -> case buCoerce tt pt of
(Just pt) -> let
s = buExtractSequent pt
s' = focusR s in
if s' /= s
then Just (Unary s' FocusR pt)
else Nothing
Nothing -> Nothing
Nothing -> Nothing
-- buDeriveLexicon - Builds the relevant Lexicon for the given target
buDeriveLexicon :: [String] -> Lexicon -> Lexicon
buDeriveLexicon [] _ = []
buDeriveLexicon (w:ws) ls = case buDeriveLexiconHelper w ls of
[] -> []
(l:_) -> l : buDeriveLexicon ws ls
-- buDeriveLexiconHelper - Runs the lexicon for each word
buDeriveLexiconHelper :: String -> Lexicon -> Lexicon
buDeriveLexiconHelper "" _ = []
buDeriveLexiconHelper _ [] = []
buDeriveLexiconHelper w (l@(s,_):ls)
| w == s = [l]
| otherwise = buDeriveLexiconHelper w ls
-- buPartial - Generates partial proof trees for the derived lexicon
buPartial :: Lexicon -> [PartialProof]
buPartial [] = []
buPartial ((s,t):ls) = case tdSolve (buInsertionSequent t) of
(Just pt) -> (s,pt) : buPartial ls
Nothing -> []
-- buInsertionSequent - Generates the "insertion sequent"; the point where a
-- lexical term enters the proof tree
buInsertionSequent :: Formula -> Sequent
buInsertionSequent f = rewriteRi (Neutral (IStruct f) (OStruct f))
-- buCombine - Combines the partial proofs to build a whole proof tree
buCombine :: [PartialProof] -> Maybe PartialProof
buCombine [] = Nothing
buCombine [x] = Just x
buCombine (l:r:xs) = case buCombinePair l r of
(Just p) -> buCombine (p:xs)
Nothing -> let
p = buCombine (r:xs)
in case p of
(Just p) -> buCombine (l:[p])
Nothing -> Nothing
-- buCombinePair - Attempts to combine a pair of partial proofs
buCombinePair :: PartialProof -> PartialProof -> Maybe PartialProof
buCombinePair (ls, lt) (rs, rt) = if buHasInsertion lt || buHasInsertion rt
then case buCombinePairEval lt rt of
(Just pt) -> Just (ls ++ " " ++ rs, pt)
Nothing -> case buCombinePairEval rt lt of
(Just pt) -> Just (ls ++ " " ++ rs, pt)
Nothing -> Nothing
else Nothing
-- buCombinePairEval - Tries to attach the right tree to the left tree
buCombinePairEval :: ProofTree -> ProofTree -> Maybe ProofTree
buCombinePairEval lt rt = let
ts = buCombineHelperGetType lt
in case buCombinePairCoerce ts rt of
(Just (pt, t)) -> case buCombinePairStitch t lt pt of
(Just pt) -> Just (buRehash pt)
Nothing -> Nothing
Nothing -> Nothing
-- buCombinePairCoerce - Tries to coerce all insertion sequent types
buCombinePairCoerce :: [Formula] -> ProofTree -> Maybe (ProofTree, Formula)
buCombinePairCoerce [] _ = Nothing
buCombinePairCoerce (t:ts) pt = case buCoerce t pt of
(Just pt) -> Just (pt, t)
Nothing -> buCombinePairCoerce ts pt
-- buCombinePairStitch - Stitches the right tree into the left where the right
-- left tree has an insertion sequent of the given type
buCombinePairStitch :: Formula -> ProofTree -> ProofTree -> Maybe ProofTree
buCombinePairStitch t (Unary x o (Unary s DeFocusL lt)) rt = if
buHelperExtractType s == Just t
then Just (Unary x o rt)
else case buCombinePairStitch t lt rt of
(Just pt) -> Just (Unary x o (Unary s DeFocusL pt))
Nothing -> Nothing
buCombinePairStitch t (Unary x o (Unary s DeFocusR lt)) rt = if
buHelperExtractType s == Just t
then Just (Unary x o rt)
else case buCombinePairStitch t lt rt of
(Just pt) -> Just (Unary x o (Unary s DeFocusR pt))
Nothing -> Nothing
buCombinePairStitch t (Unary x o pt) rt = case buCombinePairStitch t pt rt of
(Just pt) -> Just (Unary x o pt)
Nothing -> Nothing
buCombinePairStitch t (Binary x o pt1 pt2) rt = case
buCombinePairStitch t pt1 rt of
(Just pt) -> Just (Binary x o pt pt2)
Nothing -> case buCombinePairStitch t pt2 rt of
(Just pt) -> Just (Binary x o pt1 pt)
Nothing -> Nothing
buCombinePairStitch _ _ _ = Nothing
-- buCombineHelperGetType - Gets the desired type of all insertion sequents
buCombineHelperGetType :: ProofTree -> [Formula]
buCombineHelperGetType (Unary _ _ (Unary s DeFocusL pt)) = case
buHelperExtractType s of
(Just t) -> t : buCombineHelperGetType pt
Nothing -> buCombineHelperGetType pt
buCombineHelperGetType (Unary _ _ (Unary s DeFocusR pt)) = case
buHelperExtractType s of
(Just t) -> t : buCombineHelperGetType pt
Nothing -> buCombineHelperGetType pt
buCombineHelperGetType (Unary _ _ pt) = buCombineHelperGetType pt
buCombineHelperGetType (Binary _ _ pt1 pt2) = case
buCombineHelperGetType pt1 of
[] -> case buCombineHelperGetType pt2 of
[] -> []
l -> l
l -> l
buCombineHelperGetType _ = []
-- buHelperExtractType -- Extracts the type from the sequent
buHelperExtractType :: Sequent -> Maybe Formula
buHelperExtractType (Neutral _ (OStruct f)) = Just f
buHelperExtractType _ = Nothing
-- buHasInsertion - Recursively searches a proof tree for insertion sequents
buHasInsertion :: ProofTree -> Bool
buHasInsertion (Ax _) = False
buHasInsertion (CoAx _) = False
buHasInsertion (Unary _ _ (Unary _ DeFocusL _)) = True
buHasInsertion (Unary _ _ (Unary _ DeFocusR _)) = True
buHasInsertion (Unary _ _ pt) = buHasInsertion pt
buHasInsertion (Binary _ _ pt1 pt2) = buHasInsertion pt1 || buHasInsertion pt2
-- buCoerce - Attempts to force a proof tree to match a given type
buCoerce :: Formula -> ProofTree -> Maybe ProofTree
buCoerce t pt@(Unary s _ _) = case buCoerceTrivial t pt of
(Just pt) -> Just pt
otherwise -> let
complist = map (\(f, o) -> (f s, o)) tdSolveResHelperList
residuations = [(ns, o) | (ns,o) <- complist, ns /= s] in
case buCoerceEval t residuations of
(Just (s, res)) -> Just (Unary s (Res res) pt)
Nothing -> Nothing
-- buCoerceTrivial - Tests if coercion is needed
buCoerceTrivial :: Formula -> ProofTree -> Maybe ProofTree
buCoerceTrivial t pt@(Unary s _ _) = case buHelperExtractType s of
(Just f) -> if f == t
then Just pt
else Nothing
otherwise -> Nothing
-- buCoerceEval - Evaluates a list of residuations
buCoerceEval :: Formula -> [(Sequent, Residuation)] ->
Maybe (Sequent, Residuation)
buCoerceEval _ [] = Nothing
buCoerceEval t ((s, res):xs) = case buHelperExtractType s of
(Just f) -> if f == t
then Just (s, res)
else buCoerceEval t xs
otherwise -> Nothing
-- buRehash - Recursively rebuilds a proof tree to match combined trees
buRehash :: ProofTree -> ProofTree
buRehash pt = case pt of
Ax {} -> pt
CoAx {} -> pt
Unary {} -> buRehashUnary pt
Binary {} -> buRehashBinary pt
-- buExtractSequent - Extracts the sequent from a proof-tree step
buExtractSequent :: ProofTree -> Sequent
buExtractSequent (Ax s) = s
buExtractSequent (CoAx s) = s
buExtractSequent (Unary s _ _) = s
buExtractSequent (Binary s _ _ _) = s
-- buRehashUnary - Rehashes unary steps in proof trees
buRehashUnary :: ProofTree -> ProofTree
buRehashUnary (Unary _ o pt) = let
pt' = buRehash pt
s = buExtractSequent pt' in
Unary (buRehashUnaryEval s o) o pt'
-- buRehashUnaryEval - Evaluates new unary sequents
buRehashUnaryEval :: Sequent -> Operation -> Sequent
buRehashUnaryEval s o = case o of
DeFocusL -> defocusL s
DeFocusR -> defocusR s
FocusL -> focusL s
FocusR -> focusR s
RewriteL -> rewriteL s
RewriteR -> rewriteR s
(Res r) -> case r of
(Res1 i) -> residuate1 i s
(Res1i i) -> residuate1i i s
(Res2 i) -> residuate2 i s
(Res2i i) -> residuate2i i s
-- buRehashBinary - Rehashes binary steps in proof trees
buRehashBinary :: ProofTree -> ProofTree
buRehashBinary (Binary _ o pt1 pt2) = let
pt1' = buRehash pt1
pt2' = buRehash pt2
l = buExtractSequent pt1'
r = buExtractSequent pt2' in
Binary (buRehashBinaryEval l r o) o pt1' pt2'
-- buRehashBinaryEval - Evaluates new binary sequents
buRehashBinaryEval :: Sequent -> Sequent -> Operation -> Sequent
buRehashBinaryEval l r o = case o of
MonoTensor -> monoTensor l r
MonoLDiff -> monoLDiff l r
MonoRDiff -> monoRDiff l r
MonoSum -> monoSum l r
MonoLDiv -> monoLDiv l r
MonoRDiv -> monoRDiv l r
| DrSLDR/logoff | src/Logoff.hs | mit | 20,224 | 0 | 18 | 3,879 | 7,070 | 3,635 | 3,435 | 392 | 10 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingaction.html
module Stratosphere.ResourceProperties.EMRInstanceGroupConfigScalingAction where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.EMRInstanceGroupConfigSimpleScalingPolicyConfiguration
-- | Full data type definition for EMRInstanceGroupConfigScalingAction. See
-- 'emrInstanceGroupConfigScalingAction' for a more convenient constructor.
data EMRInstanceGroupConfigScalingAction =
EMRInstanceGroupConfigScalingAction
{ _eMRInstanceGroupConfigScalingActionMarket :: Maybe (Val Text)
, _eMRInstanceGroupConfigScalingActionSimpleScalingPolicyConfiguration :: EMRInstanceGroupConfigSimpleScalingPolicyConfiguration
} deriving (Show, Eq)
instance ToJSON EMRInstanceGroupConfigScalingAction where
toJSON EMRInstanceGroupConfigScalingAction{..} =
object $
catMaybes
[ fmap (("Market",) . toJSON) _eMRInstanceGroupConfigScalingActionMarket
, (Just . ("SimpleScalingPolicyConfiguration",) . toJSON) _eMRInstanceGroupConfigScalingActionSimpleScalingPolicyConfiguration
]
-- | Constructor for 'EMRInstanceGroupConfigScalingAction' containing required
-- fields as arguments.
emrInstanceGroupConfigScalingAction
:: EMRInstanceGroupConfigSimpleScalingPolicyConfiguration -- ^ 'emrigcsaSimpleScalingPolicyConfiguration'
-> EMRInstanceGroupConfigScalingAction
emrInstanceGroupConfigScalingAction simpleScalingPolicyConfigurationarg =
EMRInstanceGroupConfigScalingAction
{ _eMRInstanceGroupConfigScalingActionMarket = Nothing
, _eMRInstanceGroupConfigScalingActionSimpleScalingPolicyConfiguration = simpleScalingPolicyConfigurationarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingaction.html#cfn-elasticmapreduce-instancegroupconfig-scalingaction-market
emrigcsaMarket :: Lens' EMRInstanceGroupConfigScalingAction (Maybe (Val Text))
emrigcsaMarket = lens _eMRInstanceGroupConfigScalingActionMarket (\s a -> s { _eMRInstanceGroupConfigScalingActionMarket = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingaction.html#cfn-elasticmapreduce-instancegroupconfig-scalingaction-simplescalingpolicyconfiguration
emrigcsaSimpleScalingPolicyConfiguration :: Lens' EMRInstanceGroupConfigScalingAction EMRInstanceGroupConfigSimpleScalingPolicyConfiguration
emrigcsaSimpleScalingPolicyConfiguration = lens _eMRInstanceGroupConfigScalingActionSimpleScalingPolicyConfiguration (\s a -> s { _eMRInstanceGroupConfigScalingActionSimpleScalingPolicyConfiguration = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/EMRInstanceGroupConfigScalingAction.hs | mit | 2,841 | 0 | 13 | 210 | 259 | 150 | 109 | 29 | 1 |
-- | Defines an internal representation of Haskell data\/newtype definitions
-- that correspond to the XML DTD types, and provides pretty-printers to
-- convert these types into the 'Doc' type of "Text.PrettyPrint.HughesPJ".
module DtdToHaskell.TypeDef
( -- * Internal representation of types
TypeDef(..)
, Constructors
, AttrFields
, StructType(..)
-- * Pretty-print a TypeDef
, ppTypeDef
, ppHName
, ppXName
, ppAName
-- * Name mangling
, Name(..)
, name, name_, name_a, name_ac, name_f, mangle, manglef
) where
import Data.Char (isLower, isUpper, toLower, toUpper, isDigit)
import Data.List (intersperse)
import Text.PrettyPrint.HughesPJ
---- Internal representation for typedefs ----
-- | Need to keep both the XML and Haskell versions of a name.
data Name = Name { xName :: String -- ^ original XML name
, hName :: String -- ^ mangled Haskell name
}
deriving Eq
data TypeDef =
DataDef Bool Name AttrFields Constructors -- ^ Bool for main\/aux.
| EnumDef Name [Name]
deriving Eq
type Constructors = [(Name,[StructType])]
type AttrFields = [(Name, StructType)]
data StructType =
Maybe StructType
| Defaultable StructType String -- ^ String holds default value.
| List StructType
| List1 StructType -- ^ Non-empty lists.
| Tuple [StructType]
| OneOf [StructType]
| Any -- ^ XML's contentspec allows ANY
| String
| Defined Name
deriving Eq
-- used for converting StructType (roughly) back to an XML content model
instance Show StructType where
showsPrec p (Maybe s) = showsPrec (p+1) s . showChar '?'
showsPrec _ (Defaultable s _) = shows s
showsPrec p (List s) = showsPrec (p+1) s . showChar '*'
showsPrec p (List1 s) = showsPrec (p+1) s . showChar '+'
showsPrec _ (Tuple ss) = showChar '('
. foldr1 (.) (intersperse (showChar ',')
(map shows ss))
. showChar ')'
showsPrec _ (OneOf ss) = showChar '('
. foldr1 (.) (intersperse (showChar '|')
(map shows ss))
. showChar ')'
showsPrec _ (Any) = showString "ANY"
showsPrec _ (String) = showString "#PCDATA"
showsPrec _ (Defined (Name n _)) = showString n
---- Pretty-printing typedefs ----
ppTypeDef :: TypeDef -> Doc
-- no attrs, no constructors
ppTypeDef (DataDef _ n [] []) =
let nme = ppHName n in
text "data" <+> nme <+> text "=" <+> nme <+> derives
-- no attrs, single constructor
ppTypeDef (DataDef _ n [] [c@(_,[_])]) =
text "newtype" <+> ppHName n <+> text "=" <+> ppC c <+> derives
-- no attrs, multiple constrs
ppTypeDef (DataDef _ n [] cs) =
text "data" <+> ppHName n <+>
( text "=" <+> ppC (head cs) $$
vcat (map (\c-> text "|" <+> ppC c) (tail cs)) $$
derives )
-- nonzero attrs, no constructors
ppTypeDef (DataDef _ n fs []) =
let nme = ppHName n in
text "data" <+> nme <+> text "=" <+> nme $$
nest 4 ( text "{" <+> ppF (head fs) $$
vcat (map (\f-> text "," <+> ppF f) (tail fs)) $$
text "}" <+> derives )
-- nonzero attrs, one or more constrs
ppTypeDef (DataDef _ n fs cs) =
let attr = ppAName n in
text "data" <+> ppHName n <+>
( text "=" <+> ppAC attr (head cs) $$
vcat (map (\c-> text "|" <+> ppAC attr c) (tail cs)) $$
derives ) $$
text "data" <+> attr <+> text "=" <+> attr $$
nest 4 ( text "{" <+> ppF (head fs) $$
vcat (map (\f-> text "," <+> ppF f) (tail fs)) $$
text "}" <+> derives )
-- enumerations (of attribute values)
ppTypeDef (EnumDef n es) =
text "data" <+> ppHName n <+>
( text "=" <+>
fsep (intersperse (text " | ") (map ppHName es))
$$ derives )
ppST :: StructType -> Doc
ppST (Defaultable st _) = parens (text "Defaultable" <+> ppST st)
ppST (Maybe st) = parens (text "Maybe" <+> ppST st)
ppST (List st) = text "[" <> ppST st <> text "]"
ppST (List1 st) = parens (text "List1" <+> ppST st)
ppST (Tuple sts) = parens (commaList (map ppST sts))
ppST (OneOf sts) = parens (text "OneOf" <> text (show (length sts)) <+>
hsep (map ppST sts))
ppST String = text "String"
ppST Any = text "ANYContent"
ppST (Defined n) = ppHName n
-- constructor and components
ppC :: (Name,[StructType]) -> Doc
ppC (n,sts) = ppHName n <+> fsep (map ppST sts)
-- attribute (fieldname and type)
ppF :: (Name,StructType) -> Doc
ppF (n,st) = ppHName n <+> text "::" <+> ppST st
-- constructor and components with initial attr-type
ppAC :: Doc -> (Name,[StructType]) -> Doc
ppAC atype (n,sts) = ppHName n <+> fsep (atype: map ppST sts)
-- | Pretty print Haskell name.
ppHName :: Name -> Doc
ppHName (Name _ s) = text s
-- | Pretty print XML name.
ppXName :: Name -> Doc
ppXName (Name s _) = text s
-- | Pretty print Haskell attributes name.
ppAName :: Name -> Doc
ppAName (Name _ s) = text s <> text "_Attrs"
derives :: Doc
derives = text "deriving" <+> parens (commaList (map text ["Eq","Show"]))
---- Some operations on Names ----
-- | Make a type name valid in both XML and Haskell.
name :: String -> Name
name n = Name { xName = n
, hName = mangle n }
-- | Append an underscore to the Haskell version of the name.
name_ :: String -> Name
name_ n = Name { xName = n
, hName = mangle n ++ "_" }
-- | Prefix an attribute enumeration type name with its containing element
-- name.
name_a :: String -> String -> Name
name_a e n = Name { xName = n
, hName = mangle e ++ "_" ++ map decolonify n }
-- | Prefix an attribute enumeration constructor with its element-tag name,
-- and its enumeration type name.
name_ac :: String -> String -> String -> Name
name_ac e t n = Name { xName = n
, hName = mangle e ++ "_" ++ map decolonify t
++ "_" ++ map decolonify n }
-- | Prefix a field name with its enclosing element name.
name_f :: String -> String -> Name
name_f e n = Name { xName = n
, hName = manglef e ++ mangle n }
---- obsolete
-- elementname_at :: String -> Name
-- elementname_at n = Name n (mangle n ++ "_Attrs")
-- | Convert an XML name to a Haskell conid.
mangle :: String -> String
mangle (n:ns)
| isLower n = notPrelude (toUpper n: map decolonify ns)
| isDigit n = 'I': n: map decolonify ns
| otherwise = notPrelude (n: map decolonify ns)
-- | Ensure a generated name does not conflict with a standard haskell one.
notPrelude :: String -> String
notPrelude "Bool" = "ABool"
notPrelude "Bounded" = "ABounded"
notPrelude "Char" = "AChar"
notPrelude "Double" = "ADouble"
notPrelude "Either" = "AEither"
notPrelude "Enum" = "AEnum"
notPrelude "Eq" = "AEq"
notPrelude "FilePath"= "AFilePath"
notPrelude "Float" = "AFloat"
notPrelude "Floating"= "AFloating"
notPrelude "Fractional"= "AFractional"
notPrelude "Functor" = "AFunctor"
notPrelude "IO" = "AIO"
notPrelude "IOError" = "AIOError"
notPrelude "Int" = "AInt"
notPrelude "Integer" = "AInteger"
notPrelude "Integral"= "AIntegral"
notPrelude "List1" = "AList1" -- part of HaXml
notPrelude "Maybe" = "AMaybe"
notPrelude "Monad" = "AMonad"
notPrelude "Num" = "ANum"
notPrelude "Ord" = "AOrd"
notPrelude "Ordering"= "AOrdering"
notPrelude "Rational"= "ARational"
notPrelude "Read" = "ARead"
notPrelude "ReadS" = "AReadS"
notPrelude "Real" = "AReal"
notPrelude "RealFloat" = "ARealFloat"
notPrelude "RealFrac"= "ARealFrac"
notPrelude "Show" = "AShow"
notPrelude "ShowS" = "AShowS"
notPrelude "String" = "AString"
notPrelude n = n
-- | Convert an XML name to a Haskell varid.
manglef :: String -> String
manglef (n:ns)
| isUpper n = toLower n: map decolonify ns
| isDigit n = '_': n: map decolonify ns
| otherwise = n: map decolonify ns
-- | Convert colon to prime, hyphen to underscore.
decolonify :: Char -> Char
decolonify ':' = '\'' -- TODO: turn namespaces into qualified identifiers
decolonify '-' = '_'
decolonify '.' = '_'
decolonify c = c
commaList :: [Doc] -> Doc
commaList = hcat . intersperse comma
| nevrenato/Hets_Fork | utils/DtdToHaskell-src/pre-1.22/TypeDef.hs | gpl-2.0 | 8,527 | 0 | 22 | 2,437 | 2,566 | 1,321 | 1,245 | 175 | 1 |
-- -*- mode: haskell -*-
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module Control.Schule.Typ where
import Control.Types ( UNr, Name )
import Autolib.Reader
import Autolib.ToDoc
import Data.Typeable
-- | das sollte exactly das sein, was auch in DB-tabelle steht
data Schule =
Schule { unr :: UNr
, name :: Name
, mail_suffix :: Name
-- ^ Studenten werden nur akzeptiert,
-- wenn email so endet
}
deriving ( Typeable )
$(derives [makeReader, makeToDoc] [''Schule])
| Erdwolf/autotool-bonn | src/Control/Schule/Typ.hs | gpl-2.0 | 547 | 4 | 9 | 146 | 101 | 62 | 39 | 12 | 0 |
{- |
Module : $Header$
Description : OWL Morphisms
Copyright : (c) Dominik Luecke, 2008, Felix Gabriel Mance, 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : f.mance@jacobs-university.de
Stability : provisional
Portability : portable
Morphisms for OWL
-}
module OWL2.Morphism where
import OWL2.AS
import OWL2.MS
import OWL2.Sign
import OWL2.ManchesterPrint ()
import OWL2.StaticAnalysis
import OWL2.Symbols
import OWL2.Function
import Common.DocUtils
import Common.Doc
import Common.Result
import Common.Utils (composeMap)
import Common.Lib.State (execState)
import Common.Lib.MapSet (setToMap)
import Control.Monad
import Data.Maybe
import qualified Data.Map as Map
import qualified Data.Set as Set
data OWLMorphism = OWLMorphism
{ osource :: Sign
, otarget :: Sign
, mmaps :: MorphMap
, pmap :: StringMap
} deriving (Show, Eq, Ord)
inclOWLMorphism :: Sign -> Sign -> OWLMorphism
inclOWLMorphism s t = OWLMorphism
{ osource = s
, otarget = t
, pmap = Map.empty
, mmaps = Map.empty }
isOWLInclusion :: OWLMorphism -> Bool
isOWLInclusion m = Map.null (pmap m)
&& Map.null (mmaps m) && isSubSign (osource m) (otarget m)
symMap :: MorphMap -> Map.Map Entity Entity
symMap = Map.mapWithKey (\ (Entity ty _) -> Entity ty)
inducedElems :: MorphMap -> [Entity]
inducedElems = Map.elems . symMap
inducedSign :: MorphMap -> StringMap -> Sign -> Sign
inducedSign m t s =
let new = execState (do
mapM_ (modEntity Set.delete) $ Map.keys m
mapM_ (modEntity Set.insert) $ inducedElems m) s
in function Rename (StringMap t) new
inducedPref :: String -> String -> Sign -> (MorphMap, StringMap)
-> (MorphMap, StringMap)
inducedPref v u sig (m, t) =
let pm = prefixMap sig
in if Set.member v $ Map.keysSet pm
then if u == v then (m, t) else (m, Map.insert v u t)
else error $ "unknown symbol: " ++ showDoc v "\n" ++ shows sig ""
inducedFromMor :: Map.Map RawSymb RawSymb -> Sign -> Result OWLMorphism
inducedFromMor rm sig = do
let syms = symOf sig
(mm, tm) <- foldM (\ (m, t) p -> case p of
(ASymbol s@(Entity _ v), ASymbol (Entity _ u)) ->
if Set.member s syms
then return $ if u == v then (m, t) else (Map.insert s u m, t)
else fail $ "unknown symbol: " ++ showDoc s "\n" ++ shows sig ""
(AnUri v, AnUri u) -> case filter (`Set.member` syms)
$ map (`Entity` v) entityTypes of
[] -> let v2 = showQU v
u2 = showQU u
in return $ inducedPref v2 u2 sig (m, t)
l -> return $ if u == v then (m, t) else
(foldr (`Map.insert` u) m l, t)
(APrefix v, APrefix u) -> return $ inducedPref v u sig (m, t)
_ -> error "OWL2.Morphism.inducedFromMor") (Map.empty, Map.empty)
$ Map.toList rm
return OWLMorphism
{ osource = sig
, otarget = inducedSign mm tm sig
, pmap = tm
, mmaps = mm }
symMapOf :: OWLMorphism -> Map.Map Entity Entity
symMapOf mor = Map.union (symMap $ mmaps mor) $ setToMap $ symOf $ osource mor
instance Pretty OWLMorphism where
pretty m = let
s = osource m
srcD = specBraces $ space <> pretty s
t = otarget m
in if isOWLInclusion m then
if isSubSign t s then
fsep [text "identity morphism over", srcD]
else fsep
[ text "inclusion morphism of"
, srcD
, text "extended with"
, pretty $ Set.difference (symOf t) $ symOf s ]
else fsep
[ pretty $ mmaps m
, pretty $ pmap m
, colon <+> srcD, mapsto <+> specBraces (space <> pretty t) ]
legalMor :: OWLMorphism -> Result ()
legalMor m = let mm = mmaps m in unless
(Set.isSubsetOf (Map.keysSet mm) (symOf $ osource m)
&& Set.isSubsetOf (Set.fromList $ inducedElems mm) (symOf $ otarget m))
$ fail "illegal OWL2 morphism"
composeMor :: OWLMorphism -> OWLMorphism -> Result OWLMorphism
composeMor m1 m2 =
let nm = Set.fold (\ s@(Entity ty u) -> let
t = getIri ty u $ mmaps m1
r = getIri ty t $ mmaps m2
in if r == u then id else Map.insert s r) Map.empty
. symOf $ osource m1
in return m1
{ otarget = otarget m2
, pmap = composeMap (prefixMap $ osource m1) (pmap m1) $ pmap m2
, mmaps = nm }
cogeneratedSign :: Set.Set Entity -> Sign -> Result OWLMorphism
cogeneratedSign s sign =
let sig2 = execState (mapM_ (modEntity Set.delete) $ Set.toList s) sign
in if isSubSign sig2 sign then return $ inclOWLMorphism sig2 sign else
fail "non OWL2 subsignatures for (co)generatedSign"
generatedSign :: Set.Set Entity -> Sign -> Result OWLMorphism
generatedSign s sign = cogeneratedSign (Set.difference (symOf sign) s) sign
matchesSym :: Entity -> RawSymb -> Bool
matchesSym e@(Entity _ u) r = case r of
ASymbol s -> s == e
AnUri s -> s == u || namePrefix u == localPart s && null (namePrefix s)
APrefix p -> p == namePrefix u
statSymbItems :: [SymbItems] -> [RawSymb]
statSymbItems = concatMap
$ \ (SymbItems m us) -> case m of
AnyEntity -> map AnUri us
EntityType ty -> map (ASymbol . Entity ty) us
Prefix -> map (APrefix . showQN) us
statSymbMapItems :: [SymbMapItems] -> Result (Map.Map RawSymb RawSymb)
statSymbMapItems =
foldM (\ m (s, t) -> case Map.lookup s m of
Nothing -> return $ Map.insert s t m
Just u -> case (u, t) of
(AnUri su, ASymbol (Entity _ tu)) | su == tu ->
return $ Map.insert s t m
(ASymbol (Entity _ su), AnUri tu) | su == tu -> return m
(AnUri su, APrefix tu) | showQU su == tu ->
return $ Map.insert s t m
(APrefix su, AnUri tu) | su == showQU tu -> return m
_ -> if u == t then return m else
fail $ "differently mapped symbol: " ++ showDoc s "\nmapped to "
++ showDoc u " and " ++ showDoc t "")
Map.empty
. concatMap (\ (SymbMapItems m us) ->
let ps = map (\ (u, v) -> (u, fromMaybe u v)) us in
case m of
AnyEntity -> map (\ (s, t) -> (AnUri s, AnUri t)) ps
EntityType ty ->
let mS = ASymbol . Entity ty
in map (\ (s, t) -> (mS s, mS t)) ps
Prefix ->
map (\ (s, t) -> (APrefix (showQU s), APrefix $ showQU t)) ps)
mapSen :: OWLMorphism -> Axiom -> Result Axiom
mapSen m a = do
let new = function Rename (MorphMap $ mmaps m) a
return $ function Rename (StringMap $ pmap m) new
| nevrenato/Hets_Fork | OWL2/Morphism.hs | gpl-2.0 | 6,510 | 0 | 22 | 1,836 | 2,531 | 1,293 | 1,238 | 154 | 9 |
-- |Article writer.
-- Writes articles in the format described at <http://www.gilith.com/research/opentheory/article.html>.
module OpenTheory.Write (Loggable,WM,WriteState,logRawLn,logThm,evalWM) where
import Data.Map (Map)
import Data.Set (Set)
import qualified Data.Set as Set (toAscList)
import qualified Data.Map as Map (toAscList,lookup,size,insert,empty)
import Control.Monad.State (StateT,get,put,liftIO,evalStateT)
import Control.Monad.Reader (ReaderT,lift,ask,runReaderT)
import System.IO (Handle,hPutStrLn)
import qualified Data.List as List (map)
import Prelude hiding (log,map)
import OpenTheory.Name (Name(Name))
import OpenTheory.Type (Type(..),TypeOp(TypeOp))
import OpenTheory.Term (Term(..),Var(Var),Const(Const))
import OpenTheory.Proof (Proof(..),hyp,concl)
import OpenTheory.Object (Object(..))
-- |Article-writing state: a map for tracking objects saved in the virtual machine's dictionary.
type WriteState = Map Object Int
-- |Monad for article writing.
-- Includes the article-writing state and the handle on the destination for article commands.
type WM = StateT WriteState (ReaderT Handle IO)
evalWMState :: WM a -> Handle -> WriteState -> IO a
evalWMState m h s = flip runReaderT h $ evalStateT m s
initialState :: WriteState
initialState = Map.empty
-- |Run an article-writing action on the supplied destination.
-- The article-writing state starts empty.
evalWM :: WM a -> Handle -> IO a
evalWM m h = evalWMState m h initialState
-- |An object is @Loggable@ if it can be represented as a virtual machine object and constructed using article commands.
class Loggable a where
-- |Representation as an @Object@.
key :: a -> Object
-- |Generate commands for construction.
log :: a -> WM ()
-- |Write a newline-terminated string.
logRawLn :: String -> WM ()
logRawLn s = lift ask >>= liftIO . flip hPutStrLn s
logCommand :: String -> WM ()
logCommand = logRawLn
logNum :: Int -> WM ()
logNum = logCommand . show
-- |Make a function for writing an commands to build an object also write commands to save the object (keeping track in the article-writing state), and refer to existing objects in the dictionary if possible rather than rebuilding them.
hc :: Loggable a => (a -> WM ()) -> a -> WM ()
hc logA a = do
m0 <- get
case Map.lookup (key a) m0 of
Just k -> do
logNum k
logCommand "ref"
Nothing -> do
logA a
m <- get
let k = Map.size m
logNum k
logCommand "def"
put (Map.insert (key a) k m)
instance Loggable a => Loggable [a] where
key = OList . (List.map key)
log = hc l where
l [] = logCommand "nil"
l (x:xs) = do
log x
log xs
logCommand "cons"
instance Loggable a => Loggable (Set a) where
key = key . Set.toAscList
log = log . Set.toAscList
instance (Loggable a, Loggable b) => Loggable (a,b) where
key (a,b) = OPair (key a, key b)
log = hc l where
l (a,b) = do
log a
log b
logCommand "nil"
logCommand "cons"
logCommand "cons"
instance (Loggable k, Loggable v) => Loggable (Map k v) where
key = key . Map.toAscList
log = log . Map.toAscList
instance Loggable Name where
key = OName
log = hc l where
l (Name (ns,n)) =
logRawLn $ showChar '\"' $
shows ns $ shows n $
showChar '\"' ""
instance Loggable TypeOp where
key = OTypeOp
log = hc l where
l (TypeOp t) = do
log t
logCommand "typeOp"
instance Loggable Type where
key = OType
log = hc l where
l (OpType op args) = do
log op
log args
logCommand "opType"
l (VarType n) = do
log n
logCommand "varType"
instance Loggable Var where
key = OVar
log = hc l where
l (Var (n,ty)) = do
log n
log ty
logCommand "var"
instance Loggable Const where
key = OConst
log = hc l where
l (Const c) = do
log c
logCommand "const"
instance Loggable Term where
key = OTerm
log = hc l where
l (AbsTerm v t) = do
log v
log t
logCommand "absTerm"
l (AppTerm f x) = do
log f
log x
logCommand "appTerm"
l (ConstTerm c ty) = do
log c
log ty
logCommand "constTerm"
l (VarTerm v) = do
log v
logCommand "varTerm"
instance Loggable Proof where
key = OThm
log = hc l where
l (Assume tm) = do
log tm
logCommand "assume"
l (Refl tm) = do
log tm
logCommand "refl"
l (Axiom hs tm) = do
log hs
log tm
logCommand "axiom"
l (EqMp th1 th2) = do
log th1
log th2
logCommand "eqMp"
l (AppThm th1 th2) = do
log th1
log th2
logCommand "appThm"
l (AbsThm v th) = do
log v
log th
logCommand "absThm"
l (BetaConv tm) = do
log tm
logCommand "betaConv"
l (Subst sigma th) = do
log sigma
log th
logCommand "subst"
l (DeductAntisym th1 th2) = do
log th1
log th2
logCommand "deductAntisym"
-- |Write commands to build a theorem object from a @Proof@ and mark it as one of the article's exports.
logThm :: Proof -> WM ()
logThm th = do
log th
log (hyp th)
log (concl th)
logCommand "thm"
| xrchz/ot | OpenTheory/Write.hs | gpl-3.0 | 5,196 | 0 | 16 | 1,387 | 1,806 | 890 | 916 | 165 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
module Bamboo.Type.Config where
import Bamboo.Helper.PreludeEnv
import Bamboo.Type.Common
import Bamboo.Type.Extension
import Bamboo.Type.Reader
import Bamboo.Type.StaticWidget (StaticWidget)
import Bamboo.Type.Theme (ThemeConfig)
import Data.Default
data ConfigData =
BlogTitle
| BlogSubtitle
| HostName
| AuthorEmail
| PerPage
| Navigation
| Sidebar
| Footer
| Favicon
| AnalyticsAccountId
| Extensions
| Theme
| PostDateFormat
| CommentDateFormat
| UrlDateFormat
| UrlDateMatcher
| UrlTitleSubs
| UrlDateTitleSeperator
| Cut
| SummaryForRoot
| SummaryForTag
| SummaryForRss
| PicturePrefix
| NumberOfLatestPosts
| UseCache
| BambooUrl
| Js
| Css
deriving (Show)
data Config = Config
{
blog_title :: String
, blog_subtitle :: String
, host_name :: String
, author_email :: String
, per_page :: Int
, navigation :: [String]
, bamboo_url :: String
, default_reader :: Reader
, sidebar :: [StaticWidget]
, footer :: Maybe StaticWidget
, favicon :: String
-- extensions
, analytics_account_id :: String
, extensions :: [Extension]
-- theme
, theme_config :: ThemeConfig
-- custom
, post_date_format :: String
, comment_date_format :: String
, url_date_format :: String
, url_date_matcher :: String
, url_title_subs :: Assoc
, url_date_title_seperator :: String
-- summary
, cut :: String
, summary_for_root :: Bool
, summary_for_tag :: Bool
, summary_for_rss :: Bool
-- album
, picture_prefix :: String
-- latest
, number_of_latest_posts :: Int
-- count
, count_meta :: String
-- cache
, use_cache :: Bool
-- dir structure
, db_id :: String
, flat_id :: String
, post_id :: String
, config_id :: String
, tag_id :: String
, comment_id :: String
, sidebar_id :: String
, theme_id :: String
, config_file_id :: String
, album_id :: String
, image_id :: String
, public_id :: String
, static_id :: String
, topic_id :: String
, thumb_id :: String
, stat_id :: String
, cache_id :: String
}
deriving (Show)
instance Default Config where
def = Config
{
blog_title = def
, blog_subtitle = def
, host_name = def
, author_email = def
, per_page = 7
, navigation = def
, bamboo_url = bamboo_url_current
, default_reader = def
, sidebar = def
, footer = def
, favicon = def
, analytics_account_id = def
, extensions = [Comment, Search, Analytics]
, theme_config = def
, post_date_format = "%y-%m-%d"
, comment_date_format = "%y-%m-%d %T"
, url_date_format = "%y-%m-%d"
, url_date_matcher = "\\d{2}-\\d{2}-\\d{2}"
, url_title_subs = def
, url_date_title_seperator = " "
, cut = "✂-----"
, summary_for_root = True
, summary_for_tag = True
, summary_for_rss = False
, picture_prefix = "\\d+-"
, number_of_latest_posts = 15
, count_meta = "count.meta"
, use_cache = True
, db_id = "db"
, flat_id = "."
, post_id = "blog"
, config_id = "config"
, tag_id = "tag"
, comment_id = "comment"
, sidebar_id = "sidebar"
, theme_id = "theme"
, config_file_id = "site.txt"
, album_id = "album"
, image_id = "images"
, public_id = "public"
, static_id = "static"
, topic_id = "forum/post"
, thumb_id = "thumb"
, stat_id = "stat"
, cache_id = "cache"
}
where
bamboo_url_current = "http://github.com/nfjinjing/bamboo/tree/master"
| nfjinjing/bamboo | src/Bamboo/Type/Config.hs | gpl-3.0 | 5,088 | 0 | 9 | 2,437 | 762 | 504 | 258 | 134 | 0 |
import Bench
import Bench.Triangulations
import Criterion.Main
main :: IO ()
main = defaultMain
[ bench "it" (nf qVertexSolBench trs) ]
| DanielSchuessler/hstri | bench.hs | gpl-3.0 | 151 | 1 | 9 | 35 | 51 | 25 | 26 | 6 | 1 |
-- Identify for the server
module Handlers.Identify
( handler
) where
import Network.Socket
import Request
defaultIdent = "ShrubBot"
defaultNick = "ShrubBot"
defaultRealName = "Mr. Shrubbery"
identify :: EventHandler
identify (Just sender, _, ["AUTH", "*** Checking Ident"]) botState = do
putStrLn "Identifying with server and setting nick"
send socket (formatRequest (Nothing, "USER", [defaultIdent, defaultNick, "*", defaultRealName]))
send socket (formatRequest (Nothing, "NICK", [defaultNick]))
return (botState {botNick = defaultNick, botIdent = defaultIdent, botRealName = defaultRealName, botIdentified = True})
where socket = botSocket botState
identify _ botState = return botState
handler = identify
| UndeadMastodon/ShrubBot | Handlers/Identify.hs | gpl-3.0 | 736 | 0 | 11 | 115 | 198 | 112 | 86 | 16 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.