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
-------------------------------------------------------------------------- -- -- -- NfaTypes.hs -- -- -- -- The type of NFAs, defined using the Set library of sets. -- -- -- -- (c) Simon Thompson, 1995, 2000 -- -- -- -------------------------------------------------------------------------- -------------------------------------------------------------------------- -- -- -- Type definitions. -- -- -- -- States are of arbitrary type, though we will usually represent -- -- them as numbers, or as sets of numbers, when we form a dfa -- -- from an nfa, for example. -- -- -- -- Strings are lists of characters. -- -- -- -- Moves are either on a character (Move) or are epsilon moves -- -- (Emove). -- -- -- -- An NFA has four components -- -- the set of its states -- -- the set of its moves -- -- the start state -- -- the set of terminal states -- -- -- -------------------------------------------------------------------------- module NfaTypes where import Sets data Move a = Move a Char a | Emove a a deriving (Eq,Ord,Show) data Nfa a = NFA (Set a) (Set (Move a)) a (Set a) deriving (Eq,Show)
SonomaStatist/CS454_NFA
haskellDFA/RegExp/NfaTypes.hs
unlicense
1,255
4
10
332
127
83
44
6
0
-- Copyright (c) 2014-2015 Jonathan M. Lange <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoImplicitPrelude #-} module Haverer.Engine ( MonadEngine(..) , playGame ) where import BasicPrelude hiding (round) import Control.Monad.Random (MonadRandom) import Data.Maybe (fromJust) import Haverer.Action (Play) import Haverer.Deck (Card) import qualified Haverer.Game as Game import qualified Haverer.Round as Round import Haverer.PlayerSet (PlayerSet) class Monad m => MonadEngine m playerId where badPlay :: Round.BadAction playerId -> m () badPlay _ = return () -- XXX: We're passing PlayerSet around everywhere just so we can have it -- here. choosePlay :: PlayerSet playerId -> playerId -> Card -> Card -> m (Card, Play playerId) gameStarted :: Game.Game playerId -> m () gameStarted _ = return () gameOver :: Game.Outcome playerId -> m () gameOver _ = return () roundStarted :: Game.Game playerId -> Round.Round playerId -> m () roundStarted _ _ = return () roundOver :: Round.Victory playerId -> m () roundOver _ = return () handStarted :: Round.Round playerId -> m () handStarted _ = return () handOver :: Round.Result playerId -> m () handOver _ = return () playGame :: (Ord playerId, Show playerId, MonadRandom m, MonadEngine m playerId) => PlayerSet playerId -> m (Game.Outcome playerId) playGame players = do let game = Game.makeGame players gameStarted game outcome <- playGame' game gameOver outcome return outcome playGame' :: (Show playerId, Ord playerId, MonadRandom m, MonadEngine m playerId) => Game.Game playerId -> m (Game.Outcome playerId) playGame' game = do round <- Game.newRound game roundStarted game round outcome <- playRound (Game.players game) round roundOver outcome case Game.playersWon game (Round.getWinners outcome) of Left o -> return o Right game' -> playGame' game' playRound :: (Show playerId, Ord playerId, MonadEngine m playerId) => PlayerSet playerId -> Round.Round playerId -> m (Round.Victory playerId) playRound players round = do result <- playHand players round case result of Just round' -> playRound players round' Nothing -> return $ fromJust $ Round.victory round playHand :: (Show playerId, Ord playerId, MonadEngine m playerId) => PlayerSet playerId -> Round.Round playerId -> m (Maybe (Round.Round playerId)) playHand players r = case Round.currentTurn r of Nothing -> return Nothing Just (player, (dealt, hand)) -> do handStarted r (event, round') <- getPlay players r player dealt hand handOver event return $ Just round' getPlay :: (Ord playerId, Show playerId, MonadEngine m playerId) => PlayerSet playerId -> Round.Round playerId -> playerId -> Card -> Card -> m (Round.Result playerId, Round.Round playerId) getPlay players round player dealt hand = do result <- case Round.playTurn round of Left r -> return r Right handlePlay -> do (card, play) <- choosePlay players player dealt hand return $ handlePlay card play case result of Left err -> do badPlay err getPlay players round player dealt hand Right (event, round') -> return (event, round')
jml/haverer
lib/Haverer/Engine.hs
apache-2.0
3,791
0
14
756
1,151
565
586
72
3
module Tiling.A320097Spec (main, spec) where import Test.Hspec import Tiling.A320097 (a320097) main :: IO () main = hspec spec spec :: Spec spec = describe "A320097" $ it "correctly computes the first 5 elements" $ take 5 (map a320097 [1..]) `shouldBe` expectedValue where expectedValue = [1, 15, 463, 16372, 583199]
peterokagey/haskellOEIS
test/Tiling/A320097Spec.hs
apache-2.0
331
0
10
63
115
65
50
10
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE MultiWayIf #-} module Client.CLEnts where import Control.Lens (use, (^.), (.=), Traversal', preuse, ix, Lens', (+=), (-=)) import Control.Monad (when, liftM, unless) import Data.Bits (shiftL, shiftR, (.&.), (.|.), complement) import Data.Char (toLower) import Data.Int (Int16) import Data.IORef (IORef, newIORef, readIORef) import Data.Maybe (fromJust, isNothing) import Linear (V3(..), V4(..), _x, _y, _z, _w) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import qualified Data.Vector as V import qualified Data.Vector.Unboxed as UV import Game.CVarT import Game.PMoveT import QCommon.SizeBufT import Render.Renderer import Client.RefExportT import Client.ClientStateT import Client.ClientStaticT import Game.EntityStateT import Client.CEntityT import Game.PlayerStateT import Client.FrameT import Client.ClientInfoT import Game.PMoveStateT import Types import QuakeState import CVarVariables import qualified Constants import qualified Client.CLFX as CLFX import qualified Client.CLNewFX as CLNewFX import {-# SOURCE #-} qualified Client.CLParse as CLParse import qualified Client.CLPred as CLPred import qualified Client.CLTEnt as CLTEnt import {-# SOURCE #-} qualified Client.SCR as SCR import {-# SOURCE #-} qualified Client.V as ClientV import {-# SOURCE #-} qualified QCommon.Com as Com import {-# SOURCE #-} qualified QCommon.FS as FS import qualified QCommon.MSG as MSG import qualified Util.Lib as Lib import qualified Util.Math3D as Math3D bfgLightRamp :: UV.Vector Int bfgLightRamp = UV.fromList [ 300, 400, 600, 300, 150, 75 ] {- - =============== CL_AddEntities - - Emits all entities, particles, and lights to the refresh =============== -} addEntities :: Quake () addEntities = do cl' <- use $ globals.gCl cls' <- use $ globals.gCls showClampValue <- liftM (^.cvValue) clShowClampCVar when ((cls'^.csState) == Constants.caActive) $ do if | (cl'^.csTime) > (cl'^.csFrame.fServerTime) -> do when (showClampValue /= 0) $ Com.printf ("high clamp " `B.append` BC.pack (show ((cl'^.csTime) - (cl'^.csFrame.fServerTime))) `B.append` "\n") -- IMPROVE? globals.gCl.csTime .= (cl'^.csFrame.fServerTime) globals.gCl.csLerpFrac .= 1 | (cl'^.csTime) < (cl'^.csFrame.fServerTime) - 100 -> do when (showClampValue /= 0) $ Com.printf ("low clamp " `B.append` BC.pack (show ((cl'^.csFrame.fServerTime) - 100 - (cl'^.csTime))) `B.append` "\n") -- IMPROVE? globals.gCl.csTime .= (cl'^.csFrame.fServerTime) - 100 globals.gCl.csLerpFrac .= 0 | otherwise -> do globals.gCl.csLerpFrac .= 1 - fromIntegral ((cl'^.csFrame.fServerTime) - (cl'^.csTime)) * 0.01 timeDemoValue <- liftM (^.cvValue) clTimeDemoCVar when (timeDemoValue /= 0) $ do globals.gCl.csLerpFrac .= 1 -- is ok.. CL_AddPacketEntities (cl.frame); CL_AddTEnts (); -- CL_AddParticles (); CL_AddDLights (); CL_AddLightStyles (); calcViewValues -- PMM - moved this here so the heat beam has the right values for -- the vieworg, and can lock the beam to the gun use (globals.gCl.csFrame) >>= \f -> addPacketEntities f CLTEnt.addTEnts CLFX.addParticles CLFX.addDLights CLFX.addLightStyles {- - ================= CL_ParseEntityBits - - Returns the entity number and the header bits ================= -} parseEntityBits :: [Int] -> Quake (Int, [Int]) parseEntityBits bits = do total <- MSG.readByte (globals.gNetMessage) total' <- if total .&. Constants.uMoreBits1 /= 0 then do b <- MSG.readByte (globals.gNetMessage) return (total .|. (b `shiftL` 8)) else return total total'' <- if total' .&. Constants.uMoreBits2 /= 0 then do b <- MSG.readByte (globals.gNetMessage) return (total' .|. (b `shiftL` 16)) else return total' total''' <- if total'' .&. Constants.uMoreBits3 /= 0 then do b <- MSG.readByte (globals.gNetMessage) return (total'' .|. (b `shiftL` 24)) else return total'' number <- if total''' .&. Constants.uNumber16 /= 0 then MSG.readShort (globals.gNetMessage) else MSG.readByte (globals.gNetMessage) -- io (print "YEYEYE") -- io (print total''') -- io (print number) return (number, total''' : tail bits) {- - ================== CL_ParseDelta - - Can go from either a baseline or a previous packet_entity - ================== -} parseDelta :: EntityStateT -> Traversal' QuakeState EntityStateT -> Int -> Int -> Quake () parseDelta from to number bits = do modelIndex <- if bits .&. Constants.uModel /= 0 then MSG.readByte (globals.gNetMessage) else return (from^.esModelIndex) modelIndex2 <- if bits .&. Constants.uModel2 /= 0 then MSG.readByte (globals.gNetMessage) else return (from^.esModelIndex2) modelIndex3 <- if bits .&. Constants.uModel3 /= 0 then MSG.readByte (globals.gNetMessage) else return (from^.esModelIndex3) modelIndex4 <- if bits .&. Constants.uModel4 /= 0 then MSG.readByte (globals.gNetMessage) else return (from^.esModelIndex4) frame <- if bits .&. Constants.uFrame8 /= 0 then MSG.readByte (globals.gNetMessage) else return (from^.esFrame) frame' <- if bits .&. Constants.uFrame16 /= 0 then MSG.readShort (globals.gNetMessage) else return frame skinNum <- if | bits .&. Constants.uSkin8 /= 0 && bits .&. Constants.uSkin16 /= 0 -> MSG.readLong (globals.gNetMessage) | bits .&. Constants.uSkin8 /= 0 -> MSG.readByte (globals.gNetMessage) | bits .&. Constants.uSkin16 /= 0 -> MSG.readShort (globals.gNetMessage) | otherwise -> return (from^.esSkinNum) effects <- if | bits .&. (Constants.uEffects8 .|. Constants.uEffects16) == (Constants.uEffects8 .|. Constants.uEffects16) -> MSG.readLong (globals.gNetMessage) | bits .&. Constants.uEffects8 /= 0 -> MSG.readByte (globals.gNetMessage) | bits .&. Constants.uEffects16 /= 0 -> MSG.readShort (globals.gNetMessage) | otherwise -> return (from^.esEffects) renderFx <- if | bits .&. (Constants.uRenderFx8 .|. Constants.uRenderFx16) == (Constants.uRenderFx8 .|. Constants.uRenderFx16) -> MSG.readLong (globals.gNetMessage) | bits .&. Constants.uRenderFx8 /= 0 -> MSG.readByte (globals.gNetMessage) | bits .&. Constants.uRenderFx16 /= 0 -> MSG.readShort (globals.gNetMessage) | otherwise -> return (from^.esRenderFx) originX <- if bits .&. Constants.uOrigin1 /= 0 then MSG.readCoord (globals.gNetMessage) else return (from^.esOrigin._x) originY <- if bits .&. Constants.uOrigin2 /= 0 then MSG.readCoord (globals.gNetMessage) else return (from^.esOrigin._y) originZ <- if bits .&. Constants.uOrigin3 /= 0 then MSG.readCoord (globals.gNetMessage) else return (from^.esOrigin._z) anglesX <- if bits .&. Constants.uAngle1 /= 0 then MSG.readAngle (globals.gNetMessage) else return (from^.esAngles._x) anglesY <- if bits .&. Constants.uAngle2 /= 0 then MSG.readAngle (globals.gNetMessage) else return (from^.esAngles._y) anglesZ <- if bits .&. Constants.uAngle3 /= 0 then MSG.readAngle (globals.gNetMessage) else return (from^.esAngles._z) oldOrigin <- if bits .&. Constants.uOldOrigin /= 0 then MSG.readPos (globals.gNetMessage) else return (from^.esOrigin) sound <- if bits .&. Constants.uSound /= 0 then MSG.readByte (globals.gNetMessage) else return (from^.esSound) event <- if bits .&. Constants.uEvent /= 0 then MSG.readByte (globals.gNetMessage) else return 0 solid <- if bits .&. Constants.uSolid /= 0 then MSG.readShort (globals.gNetMessage) else return (from^.esSolid) to .= from { _esNumber = number , _esModelIndex = modelIndex , _esModelIndex2 = modelIndex2 , _esModelIndex3 = modelIndex3 , _esModelIndex4 = modelIndex4 , _esFrame = frame' , _esSkinNum = skinNum , _esEffects = effects , _esRenderFx = renderFx , _esOrigin = V3 originX originY originZ , _esAngles = V3 anglesX anglesY anglesZ , _esOldOrigin = oldOrigin , _esSound = sound , _esEvent = event , _esSolid = solid } --io (print "parseDelta: ENTITYENTITY") --io (print number) --io (print modelIndex) --io (print modelIndex2) --io (print modelIndex3) --io (print modelIndex4) --io (print frame') --io (print skinNum) --io (print effects) --io (print renderFx) --io (print originX) --io (print originY) --io (print originZ) --io (print anglesX) --io (print anglesY) --io (print anglesZ) --io (print oldOrigin) --io (print sound) --io (print event) --io (print solid) parseFrame :: Quake () parseFrame = do globals.gCl.csFrame .= newFrameT serverFrame <- MSG.readLong (globals.gNetMessage) globals.gCl.csFrame.fServerFrame .= serverFrame deltaFrame <- MSG.readLong (globals.gNetMessage) globals.gCl.csFrame.fDeltaFrame .= deltaFrame let serverTime = serverFrame * 100 globals.gCl.csFrame.fServerTime .= serverTime -- io (print "SERVER FRAME") -- io (print serverFrame) -- io (print "DELTA FRAME") -- io (print deltaFrame) -- BIG HACK to let old demos continue to work serverProtocol <- use $ globals.gCls.csServerProtocol when (serverProtocol /= 26) $ do surpressCount <- MSG.readByte (globals.gNetMessage) globals.gCl.csSurpressCount .= surpressCount showNetValue <- liftM (^.cvValue) clShowNetCVar when (showNetValue == 3) $ Com.printf (" frame:" `B.append` BC.pack (show serverFrame) `B.append` " delta:" `B.append` BC.pack (show deltaFrame) `B.append` "\n") -- IMPROVE? -- If the frame is delta compressed from data that we -- no longer have available, we must suck up the rest of -- the frame, but not use it, then ask for a non-compressed -- message old <- if deltaFrame <= 0 then do globals.gCl.csFrame.fValid .= True -- uncompressed frame globals.gCls.csDemoWaiting .= False -- we can start recording now return Nothing else do let idx = deltaFrame .&. Constants.updateMask Just old <- preuse $ globals.gCl.csFrames.ix idx unless (old^.fValid) $ -- should never happen Com.printf "Delta from invalid frame (not supposed to happen!).\n" parseEntities <- use $ globals.gCl.csParseEntities if | (old^.fServerFrame) /= deltaFrame -> -- The frame is too old, so we can't reconstruct it properly. Com.printf "Delta frame too old.\n" | parseEntities - (old^.fParseEntities) > Constants.maxParseEntities - 128 -> Com.printf "Delta parse_entities too old.\n" | otherwise -> globals.gCl.csFrame.fValid .= True -- valid delta parse return (Just old) -- clamp time use (globals.gCl.csTime) >>= \time -> if | time > serverTime -> globals.gCl.csTime .= serverTime | time < serverTime - 100 -> globals.gCl.csTime .= serverTime - 100 | otherwise -> return () -- read areabits len <- MSG.readByte (globals.gNetMessage) MSG.readData (globals.gNetMessage) (globals.gCl.csFrame.fAreaBits) len -- read playerinfo cmd <- MSG.readByte (globals.gNetMessage) CLParse.showNet (CLParse.svcStrings V.! cmd) when (cmd /= Constants.svcPlayerInfo) $ Com.comError Constants.errDrop "CL_ParseFrame: not playerinfo" parsePlayerState old (globals.gCl.csFrame) -- read packet entities cmd' <- MSG.readByte (globals.gNetMessage) CLParse.showNet (CLParse.svcStrings V.! cmd') when (cmd' /= Constants.svcPacketEntities) $ Com.comError Constants.errDrop "CL_ParseFrame: not packetentities" parsePacketEntities old (globals.gCl.csFrame) -- save the frame off in the backup array for later delta comparisons frame <- use $ globals.gCl.csFrame let idx = serverFrame .&. Constants.updateMask globals.gCl.csFrames.ix idx .= frame when (frame^.fValid) $ do -- getting a valid frame message ends the connection process clientStatic <- use $ globals.gCls clientState <- use $ globals.gCl when ((clientStatic^.csState) /= Constants.caActive) $ do globals.gCls.csState .= Constants.caActive globals.gCl.csForceRefDef .= True -- io $ print "PARSE FRAME" -- io $ print (frame^.fPlayerState.psViewAngles) globals.gCl.csPredictedOrigin .= fmap ((* 0.125) . fromIntegral) (frame^.fPlayerState.psPMoveState.pmsOrigin) globals.gCl.csPredictedAngles .= (frame^.fPlayerState.psViewAngles) when ((clientStatic^.csDisableServerCount) /= (clientState^.csServerCount) && (clientState^.csRefreshPrepped)) $ SCR.endLoadingPlaque -- get rid of loading plaque globals.gCl.csSoundPrepped .= True -- can start mixing ambient sounds -- fire entity events fireEntityEvents frame CLPred.checkPredictionError parsePlayerState :: Maybe FrameT -> Lens' QuakeState FrameT -> Quake () parsePlayerState oldFrame newFrameLens = do let state = case oldFrame of Nothing -> newPlayerStateT Just frame -> frame^.fPlayerState flags <- MSG.readShort (globals.gNetMessage) -- parse the pmove_state_t pmType <- if flags .&. Constants.psMType /= 0 then MSG.readByte (globals.gNetMessage) else return (state^.psPMoveState.pmsPMType) origin <- if flags .&. Constants.psMOrigin /= 0 then do x <- MSG.readShort (globals.gNetMessage) y <- MSG.readShort (globals.gNetMessage) z <- MSG.readShort (globals.gNetMessage) return $ fmap fromIntegral (V3 x y z) else return (state^.psPMoveState.pmsOrigin) velocity <- if flags .&. Constants.psMVelocity /= 0 then do x <- MSG.readShort (globals.gNetMessage) y <- MSG.readShort (globals.gNetMessage) z <- MSG.readShort (globals.gNetMessage) return $ fmap fromIntegral (V3 x y z) else return (state^.psPMoveState.pmsVelocity) pmTime <- if flags .&. Constants.psMTime /= 0 then liftM fromIntegral $ MSG.readByte (globals.gNetMessage) else return (state^.psPMoveState.pmsPMTime) pmFlags <- if flags .&. Constants.psMFlags /= 0 then liftM fromIntegral $ MSG.readByte (globals.gNetMessage) else return (state^.psPMoveState.pmsPMFlags) gravity <- if flags .&. Constants.psMGravity /= 0 then liftM fromIntegral $ MSG.readShort (globals.gNetMessage) else return (state^.psPMoveState.pmsGravity) deltaAngles <- if flags .&. Constants.psMDeltaAngles /= 0 then do x <- MSG.readShort (globals.gNetMessage) y <- MSG.readShort (globals.gNetMessage) z <- MSG.readShort (globals.gNetMessage) return $ fmap fromIntegral (V3 x y z) else return (state^.psPMoveState.pmsDeltaAngles) attractLoop <- use $ globals.gCl.csAttractLoop let pmType' = if attractLoop then Constants.pmFreeze -- demo playback else pmType -- parse the rest of the player_state_t viewOffset <- if flags .&. Constants.psViewOffset /= 0 then do x <- MSG.readChar (globals.gNetMessage) y <- MSG.readChar (globals.gNetMessage) z <- MSG.readChar (globals.gNetMessage) return $ fmap ((* 0.25) . fromIntegral) (V3 x y z) else return (state^.psViewOffset) viewAngles <- if flags .&. Constants.psViewAngles /= 0 then do x <- MSG.readAngle16 (globals.gNetMessage) y <- MSG.readAngle16 (globals.gNetMessage) z <- MSG.readAngle16 (globals.gNetMessage) return (V3 x y z) else return (state^.psViewAngles) kickAngles <- if flags .&. Constants.psKickAngles /= 0 then do x <- MSG.readChar (globals.gNetMessage) y <- MSG.readChar (globals.gNetMessage) z <- MSG.readChar (globals.gNetMessage) return $ fmap ((* 0.25) . fromIntegral) (V3 x y z) else return (state^.psKickAngles) gunIndex <- if flags .&. Constants.psWeaponIndex /= 0 then MSG.readByte (globals.gNetMessage) else return (state^.psGunIndex) (gunFrame, gunOffset, gunAngles) <- if flags .&. Constants.psWeaponFrame /= 0 then do gunFrame <- MSG.readByte (globals.gNetMessage) x <- MSG.readChar (globals.gNetMessage) y <- MSG.readChar (globals.gNetMessage) z <- MSG.readChar (globals.gNetMessage) x' <- MSG.readChar (globals.gNetMessage) y' <- MSG.readChar (globals.gNetMessage) z' <- MSG.readChar (globals.gNetMessage) return (gunFrame, fmap ((* 0.25) . fromIntegral) (V3 x y z), fmap ((* 0.25) . fromIntegral) (V3 x' y' z')) else return (state^.psGunFrame, state^.psGunOffset, state^.psGunAngles) blend <- if flags .&. Constants.psBlend /= 0 then do x <- MSG.readByte (globals.gNetMessage) y <- MSG.readByte (globals.gNetMessage) z <- MSG.readByte (globals.gNetMessage) w <- MSG.readByte (globals.gNetMessage) return $ fmap ((/ 255) . fromIntegral) (V4 x y z w) else return (state^.psBlend) fov <- if flags .&. Constants.psFov /= 0 then liftM fromIntegral $ MSG.readByte (globals.gNetMessage) else return (state^.psFOV) rdFlags <- if flags .&. Constants.psRdFlags /= 0 then MSG.readByte (globals.gNetMessage) else return (state^.psRDFlags) -- parse stats statbits <- MSG.readLong (globals.gNetMessage) updates <- readStats statbits 0 Constants.maxStats [] newFrameLens.fPlayerState .= PlayerStateT { _psPMoveState = PMoveStateT { _pmsPMType = pmType , _pmsOrigin = origin , _pmsVelocity = velocity , _pmsPMFlags = pmFlags , _pmsPMTime = pmTime , _pmsGravity = gravity , _pmsDeltaAngles = deltaAngles } , _psViewAngles = viewAngles , _psViewOffset = viewOffset , _psKickAngles = kickAngles , _psGunAngles = gunAngles , _psGunOffset = gunOffset , _psGunIndex = gunIndex , _psGunFrame = gunFrame , _psBlend = blend , _psFOV = fov , _psRDFlags = rdFlags , _psStats = (state^.psStats) UV.// updates } where readStats :: Int -> Int -> Int -> [(Int, Int16)] -> Quake [(Int, Int16)] readStats statbits idx maxIdx acc | idx >= maxIdx = return acc | otherwise = do if statbits .&. (1 `shiftL` idx) /= 0 then do v <- MSG.readShort (globals.gNetMessage) readStats statbits (idx + 1) maxIdx ((idx, fromIntegral v) : acc) else readStats statbits (idx + 1) maxIdx acc {- - ================== CL_ParsePacketEntities ================== - - An svc_packetentities has just been parsed, deal with the rest of the - data stream. -} parsePacketEntities :: Maybe FrameT -> Lens' QuakeState FrameT -> Quake () parsePacketEntities oldFrame newFrameLens = do use (globals.gCl.csParseEntities) >>= \parseEntities -> do newFrameLens.fParseEntities .= parseEntities newFrameLens.fNumEntities .= 0 -- delta from the entities present in oldframe parseEntities <- use $ globals.gClParseEntities let (oldNum, oldState) = case oldFrame of Nothing -> (99999, Nothing) Just frame -> let idx = (frame^.fParseEntities) .&. (Constants.maxParseEntities - 1) oldState = parseEntities V.! idx in (oldState^.esNumber, Just oldState) parse oldNum oldState 0 0 where parse :: Int -> Maybe EntityStateT -> Int -> Int -> Quake () parse oldNum oldState oldIndex bits = do (newNum, iw) <- parseEntityBits [bits] let bits' = head iw when (newNum >= Constants.maxEdicts) $ Com.comError Constants.errDrop ("CL_ParsePacketEntities: bad number:" `B.append` (BC.pack $ show newNum)) -- IMPROVE? use (globals.gNetMessage) >>= \netMsg -> when ((netMsg^.sbReadCount) > (netMsg^.sbCurSize)) $ Com.comError Constants.errDrop "CL_ParsePacketEntities: end of message" showNetValue <- liftM (^.cvValue) clShowNetCVar --io (print $ "BITS = " ++ show bits') --io (print $ "NEW NUM = " ++ show newNum) --io (print $ "OLD NUM = " ++ show oldNum) if newNum == 0 then -- any remaining entities in the old frame are copied over copyRemainingEntities showNetValue oldNum oldState oldIndex else do -- one or more entities from the old packet are unchanged (oldIndex', oldNum', oldState') <- deltaEntityPackets showNetValue oldNum newNum oldState oldIndex (oldIndex'', oldNum'', oldState'') <- if | bits' .&. Constants.uRemove /= 0 -> do -- the entity present in oldframe is not in the current frame when (showNetValue == 3) $ Com.printf (" remove: " `B.append` BC.pack (show newNum) `B.append` "\n") -- IMPROVE ? when (oldNum' /= newNum) $ Com.printf "U_REMOVE: oldnum != newnum\n" let Just oldFrame' = oldFrame if (oldIndex' + 1) >= oldFrame'^.fNumEntities then return (oldIndex' + 1, 99999, oldState') else do let idx = ((oldFrame'^.fParseEntities) + oldIndex' + 1) .&. (Constants.maxParseEntities - 1) Just oldState'' <- preuse $ globals.gClParseEntities.ix idx return (oldIndex' + 1, oldState''^.esNumber, Just oldState'') | oldNum' == newNum -> do -- delta from previous state when (showNetValue == 3) $ Com.printf (" delta: " `B.append` BC.pack (show newNum) `B.append` "\n") -- IMPROVE ? deltaEntity newFrameLens newNum (fromJust oldState') bits' let Just oldFrame' = oldFrame if (oldIndex' + 1) >= oldFrame'^.fNumEntities then return (oldIndex' + 1, 99999, oldState') else do let idx = ((oldFrame'^.fParseEntities) + oldIndex' + 1) .&. (Constants.maxParseEntities - 1) Just oldState'' <- preuse $ globals.gClParseEntities.ix idx return (oldIndex' + 1, oldState''^.esNumber, Just oldState'') | oldNum' > newNum -> do -- delta from baseline when (showNetValue == 3) $ Com.printf (" baseline: " `B.append` BC.pack (show newNum) `B.append` "\n") -- IMPROVE ? Just baseline <- preuse $ globals.gClEntities.ix newNum.ceBaseline deltaEntity newFrameLens newNum baseline bits' return (oldIndex', oldNum', oldState') parse oldNum'' oldState'' oldIndex'' bits' deltaEntityPackets :: Float -> Int -> Int -> Maybe EntityStateT -> Int -> Quake (Int, Int, Maybe EntityStateT) deltaEntityPackets showNetValue oldNum newNum oldState oldIndex | oldNum >= newNum = return (oldIndex, oldNum, oldState) | otherwise = do when (showNetValue == 3) $ Com.printf (" unchanged: " `B.append` BC.pack (show oldNum) `B.append` "\n") -- IMPROVE ? let Just oldFrame' = oldFrame deltaEntity newFrameLens oldNum (fromJust oldState) 0 if (oldIndex + 1) >= (oldFrame'^.fNumEntities) then deltaEntityPackets showNetValue 99999 newNum oldState (oldIndex + 1) else do let idx = ((oldFrame'^.fParseEntities) + (oldIndex + 1)) .&. (Constants.maxParseEntities - 1) Just oldState' <- preuse $ globals.gClParseEntities.ix idx deltaEntityPackets showNetValue (oldState'^.esNumber) newNum (Just oldState') (oldIndex + 1) copyRemainingEntities :: Float -> Int -> Maybe EntityStateT -> Int -> Quake () copyRemainingEntities showNetValue oldNum oldState oldIndex | oldNum == 99999 = return () | otherwise = do -- one or more entities from the old packet are unchanged when (showNetValue == 3) $ Com.printf (" unchanged: " `B.append` BC.pack (show oldNum) `B.append` "\n") -- IMPROVE? deltaEntity newFrameLens oldNum (fromJust oldState) 0 let Just oldFrame' = oldFrame if oldIndex + 1 >= oldFrame'^.fNumEntities then copyRemainingEntities showNetValue 99999 oldState (oldIndex + 1) else do let idx = ((oldFrame'^.fParseEntities) + oldIndex + 1) .&. (Constants.maxParseEntities - 1) Just oldState' <- preuse $ globals.gClParseEntities.ix idx copyRemainingEntities showNetValue (oldState'^.esNumber) (Just oldState') (oldIndex + 1) fireEntityEvents :: FrameT -> Quake () fireEntityEvents frame = do parseEntities <- use $ globals.gClParseEntities goThrouhEntities parseEntities 0 (frame^.fNumEntities) where goThrouhEntities :: V.Vector EntityStateT -> Int -> Int -> Quake () goThrouhEntities parseEntities pnum maxPnum | pnum >= maxPnum = return () | otherwise = do let num = ((frame^.fParseEntities) + pnum) .&. (Constants.maxParseEntities - 1) s1 = parseEntities V.! num when ((s1^.esEvent) /= 0) $ CLFX.entityEvent s1 -- EF_TELEPORTER acts like an event, but is not cleared each frame when ((s1^.esEffects) .&. Constants.efTeleporter /= 0) $ CLFX.teleporterParticles s1 goThrouhEntities parseEntities (pnum + 1) maxPnum {- - ================== CL_DeltaEntity ================== - - Parses deltas from the given base and adds the resulting entity to the - current frame -} deltaEntity :: Traversal' QuakeState FrameT -> Int -> EntityStateT -> Int -> Quake () deltaEntity frameLens newNum old bits = do parseEntities <- use $ globals.gCl.csParseEntities let idx = parseEntities .&. (Constants.maxParseEntities - 1) globals.gCl.csParseEntities += 1 frameLens.fNumEntities += 1 --io (print "DELTA ENTITY") --io (print ("number = " ++ show newNum)) --io (print ("old number = " ++ show (old^.esNumber))) --io (print ("modelindex = " ++ show (old^.esModelIndex))) parseDelta old (globals.gClParseEntities.ix idx) newNum bits Just state <- preuse $ globals.gClParseEntities.ix idx preuse (globals.gClEntities.ix newNum) >>= \(Just ent) -> when ((state^.esModelIndex) /= (ent^.ceCurrent.esModelIndex) || (state^.esModelIndex2) /= (ent^.ceCurrent.esModelIndex2) || (state^.esModelIndex3) /= (ent^.ceCurrent.esModelIndex3) || (state^.esModelIndex4) /= (ent^.ceCurrent.esModelIndex4) || abs((state^.esOrigin._x) - (ent^.ceCurrent.esOrigin._x)) > 512 || abs((state^.esOrigin._y) - (ent^.ceCurrent.esOrigin._y)) > 512 || abs((state^.esOrigin._z) - (ent^.ceCurrent.esOrigin._z)) > 512 || (state^.esEvent) == Constants.evPlayerTeleport || (state^.esEvent) == Constants.evOtherTeleport) $ globals.gClEntities.ix newNum.ceServerFrame .= -99 Just ent <- preuse $ globals.gClEntities.ix newNum serverFrame <- use $ globals.gCl.csFrame.fServerFrame if (ent^.ceServerFrame) /= serverFrame - 1 then do -- wasn't in last update, so initialize some things globals.gClEntities.ix newNum.ceTrailCount .= 1024 -- for diminishing rocket / grenade trails -- duplicate the current state so lerping doesn't hurt anything globals.gClEntities.ix newNum.cePrev .= state if (state^.esEvent) == Constants.evOtherTeleport then do globals.gClEntities.ix newNum.cePrev.esOrigin .= (state^.esOrigin) globals.gClEntities.ix newNum.ceLerpOrigin .= (state^.esOrigin) else do globals.gClEntities.ix newNum.cePrev.esOrigin .= (state^.esOldOrigin) globals.gClEntities.ix newNum.ceLerpOrigin .= (state^.esOldOrigin) else -- shuffle the last state to previous Copy ! globals.gClEntities.ix newNum.cePrev .= (ent^.ceCurrent) globals.gClEntities.ix newNum.ceServerFrame .= serverFrame -- Copy ! globals.gClEntities.ix newNum.ceCurrent .= state {- - =============== CL_CalcViewValues =============== - - Sets cl.refdef view values -} calcViewValues :: Quake () calcViewValues = do -- find the previous frame to interpolate from cl' <- use $ globals.gCl let ps = cl'^.csFrame.fPlayerState i = ((cl'^.csFrame.fServerFrame) - 1) .&. Constants.updateMask oldFrame = (cl'^.csFrames) V.! i oldFrame' = if (oldFrame^.fServerFrame) /= (cl'^.csFrame.fServerFrame) - 1 || not (oldFrame^.fValid) then cl'^.csFrame -- previous frame was dropped or invalid else oldFrame ops = oldFrame'^.fPlayerState -- see if the player entity was teleported this frame ops' = if abs ((ops^.psPMoveState.pmsOrigin._x) - (ps^.psPMoveState.pmsOrigin._x)) > 256 * 8 || abs ((ops^.psPMoveState.pmsOrigin._y) - (ps^.psPMoveState.pmsOrigin._y)) > 256 * 8 || abs ((ops^.psPMoveState.pmsOrigin._z) - (ps^.psPMoveState.pmsOrigin._z)) > 256 * 8 then ps -- don't interpolate else ops lerp = cl'^.csLerpFrac -- calculate the origin predictValue <- liftM (^.cvValue) clPredictCVar if predictValue /= 0 && (cl'^.csFrame.fPlayerState.psPMoveState.pmsPMFlags) .&. pmfNoPrediction == 0 -- use predicted values then do let backlerp = 1 - lerp globals.gCl.csRefDef.rdViewOrg .= (cl'^.csPredictedOrigin) + (ops'^.psViewOffset) + (fmap (* (cl'^.csLerpFrac)) ((ps^.psViewOffset) - (ops'^.psViewOffset))) - (fmap (* backlerp) (cl'^.csPredictionError)) -- smooth out stair climbing realTime <- use $ globals.gCls.csRealTime let delta = (realTime - (cl'^.csPredictedStepTime)) when (delta < 100) $ globals.gCl.csRefDef.rdViewOrg._z -= (cl'^.csPredictedStep) * fromIntegral (100 - delta) * 0.01 else do -- juse use interpolated values let v = (fmap ((* 0.125) . fromIntegral) (ps^.psPMoveState.pmsOrigin)) + (ps^.psViewOffset) - ((fmap ((* 0.125) . fromIntegral) (ops'^.psPMoveState.pmsOrigin)) + (ops'^.psViewOffset)) globals.gCl.csRefDef.rdViewOrg .= (fmap ((* 0.125) . fromIntegral) (ops'^.psPMoveState.pmsOrigin)) + (ops'^.psViewOffset) + (fmap (* lerp) v) -- if not running a demo or on a locked frame, add the local angle -- movement if (cl'^.csFrame.fPlayerState.psPMoveState.pmsPMType) < Constants.pmDead then do -- io $ print "USE PREDICTED VALUES" -- io $ print (cl'^.csPredictedAngles) globals.gCl.csRefDef.rdViewAngles .= (cl'^.csPredictedAngles) -- use predicted values else do -- io $ print "USE INTERPOLATED VALUES" -- io $ print ("ops.viewangles = " ++ show (ops'^.psViewAngles)) -- io $ print ("ps.viewangles = " ++ show (ps^.psViewAngles)) -- io $ print ("lerp = " ++ show lerp) globals.gCl.csRefDef.rdViewAngles .= Math3D.lerpAngles (ops'^.psViewAngles) (ps^.psViewAngles) lerp -- just use interpolated values globals.gCl.csRefDef.rdViewAngles += Math3D.lerpAngles (ops'^.psKickAngles) (ps^.psKickAngles) lerp rd <- use $ globals.gCl.csRefDef let (Just f, Just r, Just u) = Math3D.angleVectors (rd^.rdViewAngles) True True True globals.gCl.csVForward .= f globals.gCl.csVRight .= r globals.gCl.csVUp .= u -- interpolate field of view globals.gCl.csRefDef.rdFovX .= (ops'^.psFOV) + lerp * ((ps^.psFOV) - (ops'^.psFOV)) -- don't interpolate blend color globals.gCl.csRefDef.rdBlend .= (ps^.psBlend) -- add the weapon addViewWeapon ps ops' addViewWeapon :: PlayerStateT -> PlayerStateT -> Quake () addViewWeapon ps ops = do clGunValue <- liftM (^.cvValue) clGunCVar -- allow the gun to be completely removed -- don't draw gun if in wide angle view unless (clGunValue == 0 || (ps^.psFOV) > 90) $ do gunModel' <- use $ globals.gGunModel model <- case gunModel' of Nothing -> preuse (globals.gCl.csModelDraw.ix (ps^.psGunIndex)) >>= \(Just m) -> return m Just m -> return gunModel' -- development tool case model of Nothing -> return () Just _ -> do -- set up gun position cl' <- use $ globals.gCl let origin = (cl'^.csRefDef.rdViewOrg) + (ops^.psGunOffset) + (fmap (* (cl'^.csLerpFrac)) ((ps^.psGunOffset) - (ops^.psGunOffset))) angles = (cl'^.csRefDef.rdViewAngles) + (Math3D.lerpAngles (ops^.psGunAngles) (ps^.psGunAngles) (cl'^.csLerpFrac)) gunFrame' <- use $ globals.gGunFrame let (frame, oldFrame) = if gunFrame' /= 0 then (gunFrame', gunFrame') -- development tool else if (ps^.psGunFrame) == 0 then (0, 0) -- just changed weapons, don't lerp from old else (ps^.psGunFrame, ops^.psGunFrame) gunRef <- io $ newIORef newEntityT { _eModel = model , _eAngles = angles , _eOrigin = origin , _eFrame = frame , _eOldOrigin = origin , _eOldFrame = oldFrame , _eBackLerp = 1 - (cl'^.csLerpFrac) , _enFlags = Constants.rfMinLight .|. Constants.rfDepthHack .|. Constants.rfWeaponModel } ClientV.addEntity gunRef addPacketEntities :: FrameT -> Quake () addPacketEntities frame = do cl' <- use $ globals.gCl -- bonus items rotate at a fixed rate let autoRotate = Math3D.angleMod (fromIntegral (cl'^.csTime) / 10) -- brush models can auto animate their frames autoAnim = 2 * (cl'^.csTime) `div` 1000 addEntity autoRotate autoAnim newEntityT 0 (frame^.fNumEntities) where addEntity :: Float -> Int -> EntityT -> Int -> Int -> Quake () addEntity autoRotate autoAnim ent pNum maxPNum | pNum >= maxPNum = return () | otherwise = do Just s1 <- preuse $ globals.gClParseEntities.ix (((frame^.fParseEntities) + pNum) .&. (Constants.maxParseEntities - 1)) Just cent <- preuse $ globals.gClEntities.ix (s1^.esNumber) cl' <- use $ globals.gCl let entFrame = setFrame autoAnim s1 (cl'^.csTime) (effects, renderfx) = calcEffectsAndRenderFx s1 entOldFrame = cent^.cePrev.esFrame entBackLerp = 1 - (cl'^.csLerpFrac) (entOrigin, entOldOrigin) = calcOrigin cent renderfx (cl'^.csLerpFrac) (entAlpha, entSkinNum, entSkin, entModel) <- tweakBeamsColor cl' s1 ent renderfx -- only used for black hole model right now, FIXME: do better let entAlpha' = if renderfx == Constants.rfTranslucent then 0.7 else entAlpha -- render effects (fullbright, translucent, etc) entFlags = if effects .&. Constants.efColorShell /= 0 then 0 -- renderfx go on color shell entity else renderfx entAngles <- calcAngles cl' s1 entOrigin cent autoRotate effects if | (s1^.esNumber) == (cl'^.csPlayerNum) + 1 -> do if | effects .&. Constants.efFlag1 /= 0 -> ClientV.addLight entOrigin 225 1.0 0.1 0.1 | effects .&. Constants.efFlag2 /= 0 -> ClientV.addLight entOrigin 225 0.1 0.1 1.0 | effects .&. Constants.efTagTrail /= 0 -> ClientV.addLight entOrigin 225 1.0 1.0 0.0 | effects .&. Constants.efTrackerTrail /= 0 -> ClientV.addLight entOrigin 225 (-1) (-1) (-1) | otherwise -> return () let ent' = ent { _eFrame = entFrame , _eOldFrame = entOldFrame , _eBackLerp = entBackLerp , _eOrigin = entOrigin , _eOldOrigin = entOldOrigin , _eAlpha = entAlpha' , _eSkinNum = entSkinNum , _eModel = entModel , _eSkin = entSkin , _enFlags = entFlags .|. Constants.rfViewerModel -- only draw from mirrors , _eAngles = entAngles } addEntity autoRotate autoAnim ent' (pNum + 1) maxPNum | (s1^.esModelIndex) == 0 -> do let ent' = ent { _eFrame = entFrame , _eOldFrame = entOldFrame , _eBackLerp = entBackLerp , _eOrigin = entOrigin , _eOldOrigin = entOldOrigin , _eAlpha = entAlpha' , _eSkinNum = entSkinNum , _eModel = entModel , _eSkin = entSkin , _enFlags = entFlags , _eAngles = entAngles } addEntity autoRotate autoAnim ent' (pNum + 1) maxPNum | otherwise -> do let (entFlags', entAlpha'') = updateFlagsAndAlpha entFlags entAlpha' effects let ent' = ent { _eFrame = entFrame , _eOldFrame = entOldFrame , _eBackLerp = entBackLerp , _eOrigin = entOrigin , _eOldOrigin = entOldOrigin , _eAlpha = entAlpha'' , _eSkinNum = entSkinNum , _eModel = entModel , _eSkin = entSkin , _enFlags = entFlags' , _eAngles = entAngles } -- add to refresh list entRef <- io $ newIORef ent' ClientV.addEntity entRef -- color shells generate a separate entity for the main model checkColorShells ent' effects renderfx >>= checkModelIndex2 s1 >>= checkModelIndex3 s1 >>= checkModelIndex4 s1 >>= checkPowerScreen effects >>= addAutomaticParticleTrails effects s1 >>= copyOrigin s1 >>= \v -> addEntity autoRotate autoAnim v (pNum + 1) maxPNum setFrame :: Int -> EntityStateT -> Int -> Int setFrame autoAnim s1 time = let effects = s1^.esEffects in if | effects .&. Constants.efAnim01 /= 0 -> autoAnim .&. 1 | effects .&. Constants.efAnim23 /= 0 -> 2 + (autoAnim .&. 1) | effects .&. Constants.efAnimAll /= 0 -> autoAnim | effects .&. Constants.efAnimAllFast /= 0 -> time `div` 100 | otherwise -> s1^.esFrame calcEffectsAndRenderFx :: EntityStateT -> (Int, Int) calcEffectsAndRenderFx s1 = let effects = s1^.esEffects renderfx = s1^.esRenderFx (effects', renderfx') = if effects .&. Constants.efPent /= 0 then ((effects .&. (complement Constants.efPent)) .|. Constants.efColorShell, renderfx .|. Constants.rfShellRed) else (effects, renderfx) (effects'', renderfx'') = if effects' .&. Constants.efQuad /= 0 then ((effects' .&. (complement Constants.efQuad)) .|. Constants.efColorShell, renderfx' .|. Constants.rfShellBlue) else (effects', renderfx') (effects''', renderfx''') = if effects'' .&. Constants.efDouble /= 0 then ((effects'' .&. (complement Constants.efDouble)) .|. Constants.efColorShell, renderfx'' .|. Constants.rfShellDouble) else (effects'', renderfx'') result = if effects''' .&. Constants.efHalfDamage /= 0 then ((effects''' .&. (complement Constants.efHalfDamage)) .|. Constants.efColorShell, renderfx''' .|. Constants.rfShellHalfDam) else (effects''', renderfx''') in result calcOrigin :: CEntityT -> Int -> Float -> (V3 Float, V3 Float) calcOrigin cent renderfx lerpFrac = if renderfx .&. (Constants.rfFrameLerp .|. Constants.rfBeam) /= 0 then -- step origin discretely, because the frames -- do the animation properly (cent^.ceCurrent.esOrigin, cent^.ceCurrent.esOldOrigin) else -- interpolate origin let v = (cent^.cePrev.esOrigin) + (fmap (* lerpFrac) ((cent^.ceCurrent.esOrigin) - (cent^.cePrev.esOrigin))) in (v, v) tweakBeamsColor :: ClientStateT -> EntityStateT -> EntityT -> Int -> Quake (Float, Int, Maybe (IORef ImageT), Maybe (IORef ModelT)) tweakBeamsColor cl' s1 ent renderfx = do if renderfx .&. Constants.rfBeam /= 0 -- the four beam colors are encoded in 32 bits of skinnum (hack) then do r <- liftM (`mod` 4) Lib.rand return (0.3, ((s1^.esSkinNum) `shiftR` (fromIntegral r * 8)) .&. 0xFF, ent^.eSkin, Nothing) else do -- set skin if (s1^.esModelIndex) == 255 -- use custom player skin then do let skinNum = 0 ci = (cl'^.csClientInfo) V.! ((s1^.esSkinNum) .&. 0xFF) (skin, model) = if isNothing (ci^.ciSkin) || isNothing (ci^.ciModel) then (cl'^.csBaseClientInfo.ciSkin, cl'^.csBaseClientInfo.ciModel) else (ci^.ciSkin, ci^.ciModel) (skin', model') <- if renderfx .&. Constants.rfUseDisguise /= 0 then do Just renderer <- use $ globals.gRenderer let registerSkin = renderer^.rRefExport.reRegisterSkin registerModel = renderer^.rRefExport.reRegisterModel image <- io $ readIORef (fromJust skin) if | "players/male" `BC.isPrefixOf` (image^.iName) -> do s <- registerSkin "players/male/disguise.pcx" m <- registerModel "players/male/tris.md2" return (s, m) | "players/female" `BC.isPrefixOf` (image^.iName) -> do s <- registerSkin "players/female/disguise.pcx" m <- registerModel "players/female/tris.md2" return (s, m) | "players/cyborg" `BC.isPrefixOf` (image^.iName) -> do s <- registerSkin "players/cyborg/disguise.pcx" m <- registerModel "players/cyborg/tris.md2" return (s, m) | otherwise -> return (skin, model) else return (skin, model) return (ent^.eAlpha, skinNum, skin', model') else do return (ent^.eAlpha, s1^.esSkinNum, Nothing, (cl'^.csModelDraw) V.! (s1^.esModelIndex)) calcAngles :: ClientStateT -> EntityStateT -> V3 Float -> CEntityT -> Float -> Int -> Quake (V3 Float) calcAngles cl' s1 entOrigin cent autoRotate effects = do if | effects .&. Constants.efRotate /= 0 -> -- some bonus items return (V3 0 autoRotate 0) -- RAFAEL | effects .&. Constants.efSpinningLights /= 0 -> do let result = V3 0 (Math3D.angleMod (fromIntegral (cl'^.csTime) / 2) + (s1^.esAngles._y)) 180 (Just forward, _, _) = Math3D.angleVectors result True False False start = entOrigin + fmap (* 64) forward ClientV.addLight start 100 1 0 0 return result -- interpolate angles | otherwise -> return (Math3D.lerpAngles (cent^.cePrev.esAngles) (cent^.ceCurrent.esAngles) (cl'^.csLerpFrac)) updateFlagsAndAlpha :: Int -> Float -> Int -> (Int, Float) updateFlagsAndAlpha entFlags entAlpha effects = let (f, a) = if effects .&. Constants.efBFG /= 0 then (entFlags .|. Constants.rfTranslucent, 0.3) else (entFlags, entAlpha) (f', a') = if effects .&. Constants.efPlasma /= 0 then (f .|. Constants.rfTranslucent, 0.6) else (f, a) result = if effects .&. Constants.efSphereTrans /= 0 then if effects .&. Constants.efTrackerTrail /= 0 then (f' .|. Constants.rfTranslucent, 0.6) else (f' .|. Constants.rfTranslucent, 0.3) else (f', a') in result checkColorShells :: EntityT -> Int -> Int -> Quake EntityT checkColorShells ent effects renderfx = do when (effects .&. Constants.efColorShell /= 0) $ do {- - PMM - at this point, all of the shells have been handled if - we're in the rogue pack, set up the custom mixing, otherwise - just keep going if(Developer_searchpath(2) == 2) { all of the - solo colors are fine. we need to catch any of the - combinations that look bad (double & half) and turn them into - the appropriate color, and make double/quad something special -} renderfx' <- if renderfx .&. Constants.rfShellHalfDam /= 0 then do v <- FS.developerSearchPath 2 -- ditch the half damage shell if any of -- red, blue, or double are on return $ if v == 2 && renderfx .&. (Constants.rfShellRed .|. Constants.rfShellBlue .|. Constants.rfShellDouble) /= 0 then renderfx .&. (complement Constants.rfShellHalfDam) else renderfx else return renderfx renderfx'' <- if renderfx' .&. Constants.rfShellDouble /= 0 then do v <- FS.developerSearchPath 2 if v == 2 then do -- lose the yellow shell if we have a red, blue, or green shell let r = if renderfx' .&. (Constants.rfShellRed .|. Constants.rfShellBlue .|. Constants.rfShellGreen) /= 0 then renderfx' .&. (complement Constants.rfShellDouble) else renderfx' -- if we have a red shell, turn it to purple by adding blue r' = if | r .&. Constants.rfShellRed /= 0 -> r .|. Constants.rfShellBlue -- if we have a blue shell (and not a red shell), turn it to cyan by adding green | r .&. Constants.rfShellBlue /= 0 -> -- go to green if it's on already, otherwise do cyan (flash green) if r .&. Constants.rfShellGreen /= 0 then r .&. (complement Constants.rfShellBlue) else r .|. Constants.rfShellGreen | otherwise -> r return r' else return renderfx' else return renderfx' entRef <- io $ newIORef ent { _enFlags = renderfx'' .|. Constants.rfTranslucent , _eAlpha = 0.3 } ClientV.addEntity entRef return ent { _eSkin = Nothing -- never use a custom skin on others , _eSkinNum = 0 , _enFlags = 0 , _eAlpha = 0 } checkModelIndex2 :: EntityStateT -> EntityT -> Quake EntityT checkModelIndex2 s1 ent = do if (s1^.esModelIndex2) /= 0 then do model <- if (s1^.esModelIndex2) == 255 -- custom weapon then do Just ci <- preuse $ globals.gCl.csClientInfo.ix ((s1^.esSkinNum) .&. 0xFF) let i = (s1^.esSkinNum) `shiftR` 8 -- 0 is default weapon model clVwepValue <- liftM (^.cvValue) clVwepCVar let i' = if clVwepValue == 0 || i > Constants.maxClientWeaponModels - 1 then 0 else i model = (ci^.ciWeaponModel) V.! i' if isNothing model then do let m = if i' /= 0 then (ci^.ciWeaponModel) V.! 0 else model if isNothing m then do Just m' <- preuse $ globals.gCl.csBaseClientInfo.ciWeaponModel.ix 0 return m' else return m else return model else do Just model <- preuse $ globals.gCl.csModelDraw.ix (s1^.esModelIndex2) return model -- PMM - check for the defender sphere shell .. make it translucent -- replaces the previous version which used the high bit on -- modelindex2 to determine transparency Just configString <- preuse $ globals.gCl.csConfigStrings.ix (Constants.csModels + (s1^.esModelIndex2)) entRef <- io $ if BC.map toLower configString == "models/items/shell/tris.md2" then newIORef ent { _eModel = model , _eAlpha = 0.32 , _enFlags = Constants.rfTranslucent } else newIORef ent { _eModel = model } ClientV.addEntity entRef -- PGM - make sure these get reset return ent { _eModel = model , _eAlpha = 0 , _enFlags = 0 } else return ent checkModelIndex3 :: EntityStateT -> EntityT -> Quake EntityT checkModelIndex3 s1 ent = do if (s1^.esModelIndex3) /= 0 then do Just model <- preuse $ globals.gCl.csModelDraw.ix (s1^.esModelIndex3) let ent' = ent { _eModel = model } entRef <- io $ newIORef ent' ClientV.addEntity entRef return ent' else return ent checkModelIndex4 :: EntityStateT -> EntityT -> Quake EntityT checkModelIndex4 s1 ent = do if (s1^.esModelIndex4) /= 0 then do Just model <- preuse $ globals.gCl.csModelDraw.ix (s1^.esModelIndex4) let ent' = ent { _eModel = model } entRef <- io $ newIORef ent' ClientV.addEntity entRef return ent' else return ent checkPowerScreen :: Int -> EntityT -> Quake EntityT checkPowerScreen effects ent = do if effects .&. Constants.efPowerScreen /= 0 then do model <- use $ clTEntGlobals.clteModPowerScreen let ent' = ent { _eModel = model , _eOldFrame = 0 , _eFrame = 0 , _enFlags = (ent^.enFlags) .|. Constants.rfTranslucent .|. Constants.rfShellGreen , _eAlpha = 0.3 } entRef <- io $ newIORef ent' ClientV.addEntity entRef return ent' else return ent addAutomaticParticleTrails :: Int -> EntityStateT -> EntityT -> Quake EntityT addAutomaticParticleTrails effects s1 ent = do Just cent <- preuse $ globals.gClEntities.ix (s1^.esNumber) if effects .&. (complement Constants.efRotate) /= 0 then do if | effects .&. Constants.efRocket /= 0 -> do CLFX.rocketTrail (cent^.ceLerpOrigin) (ent^.eOrigin) (s1^.esNumber) ClientV.addLight (ent^.eOrigin) 200 1 1 0 return ent | effects .&. Constants.efBlaster /= 0 -> do if effects .&. Constants.efTracker /= 0 -- lame... problematic? then do CLNewFX.blasterTrail2 (cent^.ceLerpOrigin) (ent^.eOrigin) ClientV.addLight (ent^.eOrigin) 200 0 1 0 else do CLFX.blasterTrail (cent^.ceLerpOrigin) (ent^.eOrigin) ClientV.addLight (ent^.eOrigin) 200 1 1 0 return ent | effects .&. Constants.efHyperblaster /= 0 -> do if effects .&. Constants.efTracker /= 0 -- PGM overloaded for blaster2 then ClientV.addLight (ent^.eOrigin) 200 0 1 0 else ClientV.addLight (ent^.eOrigin) 200 1 1 0 return ent | effects .&. Constants.efGib /= 0 -> do CLFX.diminishingTrail (cent^.ceLerpOrigin) (ent^.eOrigin) (s1^.esNumber) effects return ent | effects .&. Constants.efGrenade /= 0 -> do CLFX.diminishingTrail (cent^.ceLerpOrigin) (ent^.eOrigin) (s1^.esNumber) effects return ent | effects .&. Constants.efFlies /= 0 -> do CLFX.flyEffect (s1^.esNumber) (ent^.eOrigin) return ent | effects .&. Constants.efBFG /= 0 -> do i <- if effects .&. Constants.efAnimAllFast /= 0 then do CLFX.bfgParticles ent return 200 else return (bfgLightRamp UV.! (s1^.esFrame)) ClientV.addLight (ent^.eOrigin) (fromIntegral i) 0 1 0 return ent | effects .&. Constants.efTrap /= 0 -> do let origin@(V3 a b c) = ent^.eOrigin ent' = ent { _eOrigin = V3 a b (c + 32) } CLFX.trapParticles ent' r <- Lib.rand let i = fromIntegral (r `mod` 100) + 100 ClientV.addLight (ent'^.eOrigin) i 1 0.8 0.1 return ent' | effects .&. Constants.efFlag1 /= 0 -> do CLFX.flagTrail (cent^.ceLerpOrigin) (ent^.eOrigin) 242 ClientV.addLight (ent^.eOrigin) 225 1 0.1 0.1 return ent | effects .&. Constants.efFlag2 /= 0 -> do CLFX.flagTrail (cent^.ceLerpOrigin) (ent^.eOrigin) 115 ClientV.addLight (ent^.eOrigin) 225 0.1 0.1 1 return ent | effects .&. Constants.efTagTrail /= 0 -> do CLNewFX.tagTrail (cent^.ceLerpOrigin) (ent^.eOrigin) 220 ClientV.addLight (ent^.eOrigin) 225 1.0 1.0 0.0 return ent | effects .&. Constants.efTrackerTrail /= 0 -> if effects .&. Constants.efTracker /= 0 then do time <- use $ globals.gCl.csTime let intensity = 50 + (500 * (sin (fromIntegral time / 500.0) + 1.0)) -- FIXME: check out this effect in rendition -- TODO: there is an extra check in jake2 that we skipped ClientV.addLight (ent^.eOrigin) intensity (-1.0) (-1.0) (-1.0) return ent else do CLNewFX.trackerShell (cent^.ceLerpOrigin) ClientV.addLight (ent^.eOrigin) 155 (-1.0) (-1.0) (-1.0) return ent | effects .&. Constants.efTracker /= 0 -> do CLNewFX.trackerTrail (cent^.ceLerpOrigin) (ent^.eOrigin) 0 -- FIXME: check out this effect in rendition -- TODO: there is an extra check in jake2 that we skipped ClientV.addLight (ent^.eOrigin) 200 (-1) (-1) (-1) return ent | effects .&. Constants.efGreenGib /= 0 -> do CLFX.diminishingTrail (cent^.ceLerpOrigin) (ent^.eOrigin) (s1^.esNumber) effects return ent | effects .&. Constants.efIonRipper /= 0 -> do CLFX.ionRipperTrail (cent^.ceLerpOrigin) (ent^.eOrigin) ClientV.addLight (ent^.eOrigin) 100 1 0.5 0.5 return ent | effects .&. Constants.efBlueHyperblaster /= 0 -> do ClientV.addLight (ent^.eOrigin) 200 0 0 1 return ent | effects .&. Constants.efPlasma /= 0 -> do when (effects .&. Constants.efAnimAllFast /= 0) $ CLFX.blasterTrail (cent^.ceLerpOrigin) (ent^.eOrigin) ClientV.addLight (ent^.eOrigin) 130 1 0.5 0.5 return ent | otherwise -> return ent else return ent copyOrigin :: EntityStateT -> EntityT -> Quake EntityT copyOrigin s1 ent = do globals.gClEntities.ix (s1^.esNumber).ceLerpOrigin .= (ent^.eOrigin) return ent
ksaveljev/hake-2
src/Client/CLEnts.hs
bsd-3-clause
64,875
0
32
25,387
15,573
8,007
7,566
-1
-1
{-# LANGUAGE CPP, OverloadedStrings, NoImplicitPrelude #-} #if __GLASGOW_HASKELL__ >= 704 {-# LANGUAGE Safe #-} #endif -------------------------------------------------------------------------------- -- | -- Module : Data.String.Combinators -- Copyright : (c) 2009-2011 Bas van Dijk -- License : BSD-style (see the file LICENSE) -- Maintainer : Bas van Dijk <[email protected]> -- -------------------------------------------------------------------------------- module Data.String.Combinators ( -- * Combining (<>) , mid , (<+>) , ($$) , intercalate , hcat , unwords , unlines , punctuate -- * Wrapping in delimiters , between , parens , thenParens , brackets , braces , angleBrackets , quotes , doubleQuotes -- * From characters , char , semi , colon , comma , space , newline , equals , lparen , rparen , lbrack , rbrack , lbrace , rbrace , labrack , rabrack -- * From showable values , fromShow , int , integer , float , double , rational ) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- -- from base: import Data.List ( foldr ) import Data.Bool ( Bool(False, True) ) import Data.Char ( Char ) import Data.Function ( id, (.) ) import Data.Int ( Int ) import Data.Ratio ( Rational ) import Data.String ( IsString, fromString ) import Data.Monoid ( Monoid, mempty ) import Text.Show ( Show, show ) import Prelude ( Integer, Float, Double ) #if MIN_VERSION_base(4,5,0) import Data.Monoid ( (<>) ) #else import Data.Monoid ( mappend ) -- | Put two string-likes besides eachother. -- -- Note that: @'<>' = 'mappend'@. (<>) :: Monoid s => s -> s -> s (<>) = mappend infixl 6 <> #endif -------------------------------------------------------------------------------- -- * Combining -------------------------------------------------------------------------------- -- | @mid m x y@ Puts @x@ and @y@ around @m@. -- -- Note that: @mid m x y = 'between' x y m@. mid :: Monoid s => s -> (s -> s -> s) mid m x y = between x y m -- | Put two string-likes besides eachother separated by a 'space'. (<+>) :: (Monoid s, IsString s) => s -> s -> s (<+>) = mid space -- | Put two string-likes above eachother (separated by a 'newline'). ($$) :: (Monoid s, IsString s) => s -> s -> s ($$) = mid newline infixl 6 <+> infixl 5 $$ {-| Combine the string-likes with a given function. @intercalate f [s1, ... sn] = s1 \`f\` (s2 \`f\` (... (sn-1 \`f\` sn)))@ -} intercalate :: Monoid s => (s -> s -> s) -> [s] -> s intercalate f = go where go [] = mempty go (s:[]) = s go (s:ss) = s `f` go ss -- | List version of '<>'. -- -- Note that: @hcat = 'intercalate' ('<>')@. hcat :: Monoid s => [s] -> s hcat = intercalate (<>) -- | List version of '<+>'. -- -- Note that: @unwords = 'intercalate' ('<+>')@. unwords :: (Monoid s, IsString s) => [s] -> s unwords = intercalate (<+>) -- | List version of '$$'. -- -- Note that: @unlines = foldr ('$$') mempty@ unlines :: (Monoid s, IsString s) => [s] -> s unlines = foldr ($$) mempty -- | @punctuate p [s1, ... sn] = [s1 '<>' p, s2 '<>' p, ... sn-1 '<>' p, sn]@. -- -- (Idea and implementation taken from the @pretty@ package.) punctuate :: (Monoid s) => s -> [s] -> [s] punctuate _ [] = [] punctuate p (d:ds) = go d ds where go d' [] = [d'] go d' (e:es) = (d' <> p) : go e es -------------------------------------------------------------------------------- -- * Wrapping in delimiters -------------------------------------------------------------------------------- -- | @between b c s@ wraps the string-like @s@ between @b@ and @c@. between :: (Monoid s) => s -> s -> (s -> s) between open close = \x -> open <> x <> close -- | Wrap a string-like in @(...)@. parens :: (Monoid s, IsString s) => s -> s parens = between "(" ")" -- | Wrap a string-like in @[...]@. brackets :: (Monoid s, IsString s) => s -> s brackets = between "[" "]" -- | Wrap a string-like in @{...}@. braces :: (Monoid s, IsString s) => s -> s braces = between "{" "}" -- | Wrap a string-like in @\<...\>@. angleBrackets :: (Monoid s, IsString s) => s -> s angleBrackets = between "<" ">" -- | Wrap a string-like in @\'...\'@. quotes :: (Monoid s, IsString s) => s -> s quotes = between "'" "'" -- | Wrap a string-like in @\"...\"@. doubleQuotes :: (Monoid s, IsString s) => s -> s doubleQuotes = between "\"" "\"" {-| Like @showParen@ conditionally wraps a string-like in @(...)@ This function is supposed to be used infix as in: @(precedence >= 10) \`thenParens\` (\"fun\" \<+\> \"arg\")@ -} thenParens :: (Monoid s, IsString s) => Bool -> s -> s thenParens True = parens thenParens False = id -------------------------------------------------------------------------------- -- * From characters -------------------------------------------------------------------------------- -- | Convert a character to a string-like. char :: IsString s => Char -> s char c = fromString [c] -- | A ';' character. semi :: IsString s => s semi = char ';' -- | A ':' character. colon :: IsString s => s colon = char ':' -- | A ',' character. comma :: IsString s => s comma = char ',' -- | A ' ' character. space :: IsString s => s space = char ' ' -- | A '\n' character. newline :: IsString s => s newline = char '\n' -- | A '=' character. equals :: IsString s => s equals = char '=' -- | A '(' character. lparen :: IsString s => s lparen = char '(' -- | A ')' character. rparen :: IsString s => s rparen = char ')' -- | A '[' character. lbrack :: IsString s => s lbrack = char '[' -- | A ']' character. rbrack :: IsString s => s rbrack = char ']' -- | A '{' character. lbrace :: IsString s => s lbrace = char '{' -- | A '}' character. rbrace :: IsString s => s rbrace = char '}' -- | A \'<\' character. labrack :: IsString s => s labrack = char '<' -- | A \'>\' character. rabrack :: IsString s => s rabrack = char '>' -------------------------------------------------------------------------------- -- * From showable values -------------------------------------------------------------------------------- -- | Convert a @Show@able value to a string-like. fromShow :: (Show a, IsString s) => a -> s fromShow = fromString . show -- | Convert an @Int@ to a string-like. int :: IsString s => Int -> s int = fromShow -- | Convert an @Integer@ to a string-like. integer :: IsString s => Integer -> s integer = fromShow -- | Convert a @Float@ to a string-like. float :: IsString s => Float -> s float = fromShow -- | Convert a @Double@ to a string-like. double :: IsString s => Double -> s double = fromShow -- | Convert a @Rational@ to a string-like. rational :: IsString s => Rational -> s rational = fromShow
basvandijk/string-combinators
Data/String/Combinators.hs
bsd-3-clause
6,961
0
10
1,505
1,545
887
658
138
3
-- | -- Module : Network.TLS.Parameters -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : unknown -- module Network.TLS.Parameters ( ClientParams(..) , ServerParams(..) , CommonParams , ClientHooks(..) , ServerHooks(..) , Supported(..) , Shared(..) -- * special default , defaultParamsClient -- * Parameters , MaxFragmentEnum(..) , CertificateUsage(..) , CertificateRejectReason(..) ) where import Network.BSD (HostName) import Network.TLS.Extension import Network.TLS.Struct import qualified Network.TLS.Struct as Struct import Network.TLS.Session import Network.TLS.Cipher import Network.TLS.Measurement import Network.TLS.Compression import Network.TLS.Crypto import Network.TLS.Credentials import Network.TLS.X509 import Data.Monoid import Data.Default.Class import qualified Data.ByteString as B type CommonParams = (Supported, Shared) data ClientParams = ClientParams { clientUseMaxFragmentLength :: Maybe MaxFragmentEnum -- | Define the name of the server, along with an extra service identification blob. -- this is important that the hostname part is properly filled for security reason, -- as it allow to properly associate the remote side with the given certificate -- during a handshake. -- -- The extra blob is useful to differentiate services running on the same host, but that -- might have different certificates given. It's only used as part of the X509 validation -- infrastructure. , clientServerIdentification :: (HostName, Bytes) -- | Allow the use of the Server Name Indication TLS extension during handshake, which allow -- the client to specify which host name, it's trying to access. This is useful to distinguish -- CNAME aliasing (e.g. web virtual host). , clientUseServerNameIndication :: Bool -- | try to establish a connection using this session. , clientWantSessionResume :: Maybe (SessionID, SessionData) , clientShared :: Shared , clientHooks :: ClientHooks , clientSupported :: Supported } deriving (Show) defaultParamsClient :: HostName -> Bytes -> ClientParams defaultParamsClient serverName serverId = ClientParams { clientWantSessionResume = Nothing , clientUseMaxFragmentLength = Nothing , clientServerIdentification = (serverName, serverId) , clientUseServerNameIndication = True , clientShared = def , clientHooks = def , clientSupported = def } data ServerParams = ServerParams { -- | request a certificate from client. serverWantClientCert :: Bool -- | This is a list of certificates from which the -- disinguished names are sent in certificate request -- messages. For TLS1.0, it should not be empty. , serverCACertificates :: [SignedCertificate] -- | Server Optional Diffie Hellman parameters. If this value is not -- properly set, no Diffie Hellman key exchange will take place. , serverDHEParams :: Maybe DHParams , serverShared :: Shared , serverHooks :: ServerHooks , serverSupported :: Supported } deriving (Show) defaultParamsServer :: ServerParams defaultParamsServer = ServerParams { serverWantClientCert = False , serverCACertificates = [] , serverDHEParams = Nothing , serverHooks = def , serverShared = def , serverSupported = def } instance Default ServerParams where def = defaultParamsServer -- | List all the supported algorithms, versions, ciphers, etc supported. data Supported = Supported { -- | Supported Versions by this context -- On the client side, the highest version will be used to establish the connection. -- On the server side, the highest version that is less or equal than the client version will be chosed. supportedVersions :: [Version] -- | Supported cipher methods , supportedCiphers :: [Cipher] -- | supported compressions methods , supportedCompressions :: [Compression] -- | All supported hash/signature algorithms pair for client -- certificate verification, ordered by decreasing priority. , supportedHashSignatures :: [HashAndSignatureAlgorithm] -- | Set if we support secure renegotiation. , supportedSecureRenegotiation :: Bool -- | Set if we support session. , supportedSession :: Bool } deriving (Show,Eq) defaultSupported :: Supported defaultSupported = Supported { supportedVersions = [TLS12,TLS11,TLS10] , supportedCiphers = [] , supportedCompressions = [nullCompression] , supportedHashSignatures = [ (Struct.HashSHA512, SignatureRSA) , (Struct.HashSHA384, SignatureRSA) , (Struct.HashSHA256, SignatureRSA) , (Struct.HashSHA224, SignatureRSA) , (Struct.HashSHA1, SignatureRSA) , (Struct.HashSHA1, SignatureDSS) ] , supportedSecureRenegotiation = True , supportedSession = True } instance Default Supported where def = defaultSupported data Shared = Shared { sharedCredentials :: Credentials , sharedSessionManager :: SessionManager , sharedCAStore :: CertificateStore , sharedValidationCache :: ValidationCache } instance Show Shared where show _ = "Shared" instance Default Shared where def = Shared { sharedCAStore = mempty , sharedCredentials = mempty , sharedSessionManager = noSessionManager , sharedValidationCache = def } -- | A set of callbacks run by the clients for various corners of TLS establishment data ClientHooks = ClientHooks { -- | This action is called when the server sends a -- certificate request. The parameter is the information -- from the request. The action should select a certificate -- chain of one of the given certificate types where the -- last certificate in the chain should be signed by one of -- the given distinguished names. Each certificate should -- be signed by the following one, except for the last. At -- least the first of the certificates in the chain must -- have a corresponding private key, because that is used -- for signing the certificate verify message. -- -- Note that is is the responsibility of this action to -- select a certificate matching one of the requested -- certificate types. Returning a non-matching one will -- lead to handshake failure later. -- -- Returning a certificate chain not matching the -- distinguished names may lead to problems or not, -- depending whether the server accepts it. onCertificateRequest :: ([CertificateType], Maybe [HashAndSignatureAlgorithm], [DistinguishedName]) -> IO (Maybe (CertificateChain, PrivKey)) , onNPNServerSuggest :: Maybe ([B.ByteString] -> IO B.ByteString) , onServerCertificate :: CertificateStore -> ValidationCache -> ServiceID -> CertificateChain -> IO [FailedReason] , onSuggestALPN :: IO (Maybe [B.ByteString]) } defaultClientHooks :: ClientHooks defaultClientHooks = ClientHooks { onCertificateRequest = \ _ -> return Nothing , onNPNServerSuggest = Nothing , onServerCertificate = validateDefault , onSuggestALPN = return Nothing } instance Show ClientHooks where show _ = "ClientHooks" instance Default ClientHooks where def = defaultClientHooks -- | A set of callbacks run by the server for various corners of the TLS establishment data ServerHooks = ServerHooks { -- | This action is called when a client certificate chain -- is received from the client. When it returns a -- CertificateUsageReject value, the handshake is aborted. onClientCertificate :: CertificateChain -> IO CertificateUsage -- | This action is called when the client certificate -- cannot be verified. A 'Nothing' argument indicates a -- wrong signature, a 'Just e' message signals a crypto -- error. , onUnverifiedClientCert :: IO Bool -- | Allow the server to choose the cipher relative to the -- the client version and the client list of ciphers. -- -- This could be useful with old clients and as a workaround -- to the BEAST (where RC4 is sometimes prefered with TLS < 1.1) -- -- The client cipher list cannot be empty. , onCipherChoosing :: Version -> [Cipher] -> Cipher -- | suggested next protocols accoring to the next protocol negotiation extension. , onSuggestNextProtocols :: IO (Maybe [B.ByteString]) -- | at each new handshake, we call this hook to see if we allow handshake to happens. , onNewHandshake :: Measurement -> IO Bool , onALPNClientSuggest :: Maybe ([B.ByteString] -> IO B.ByteString) } defaultServerHooks :: ServerHooks defaultServerHooks = ServerHooks { onCipherChoosing = \_ -> head , onClientCertificate = \_ -> return $ CertificateUsageReject $ CertificateRejectOther "no client certificates expected" , onUnverifiedClientCert = return False , onSuggestNextProtocols = return Nothing , onNewHandshake = \_ -> return True , onALPNClientSuggest = Nothing } instance Show ServerHooks where show _ = "ClientHooks" instance Default ServerHooks where def = defaultServerHooks
AaronFriel/hs-tls
core/Network/TLS/Parameters.hs
bsd-3-clause
9,925
0
14
2,671
1,247
788
459
136
1
import Handler.Fib import Handler.Home import Handler.Markdown import Import {- We've now defined all of our handler functions. The last step is create a dispatch function which will reference all of them. The mkYesodDispatch function does this, following the standard naming scheme we've used in our handler modules to get the appropriate function names. This function creates an instance of YesodDispatch. That instance is used by warpEnv to create an application that the Warp webserver is able to execute. -} mkYesodDispatch "App" resourcesApp main :: IO () main = warpEnv App {- Note that warpEnv handles a few important details for us: * Determines which port to listen on based on environment variables. * Sets up a number of WAI middlewares, such as request logging. * Converts our Yesod application into a WAI application. * Runs the whole thing. -}
fdilke/fpc-exp
src/Main.hs
bsd-3-clause
908
0
6
188
47
25
22
-1
-1
import Data.Aeson (eitherDecode, encode) import Data.List (findIndex, intercalate) import Data.MBP (HasDimensions(dims), MBP, branches, elems, matrix, mbp, outputs, position, step, steps) import Data.ByteString.Lazy (ByteString) import Data.Text (Text) import Data.Monoid ((<>)) import System.Exit (die) import qualified Data.ByteString.Lazy as BS import qualified Data.Text as T import qualified Options.Applicative as Opt data Options = Options { source :: Maybe FilePath , target :: Maybe FilePath , selection :: Text } deriving (Eq, Ord, Read, Show) optionsParser :: Opt.Parser Options optionsParser = Options <$> Opt.optional (Opt.strOption ( Opt.short 'i' <> Opt.metavar "FILE" <> Opt.help "input file (default stdin)" ) ) <*> Opt.optional (Opt.strOption ( Opt.short 'o' <> Opt.metavar "FILE" <> Opt.help "output file (default stdout)" ) ) <*> (T.pack <$> Opt.strArgument ( Opt.metavar "STRING" <> Opt.help "matrix branching program output to specialize for" ) ) optionsInfo :: Opt.ParserInfo Options optionsInfo = Opt.info (Opt.helper <*> optionsParser) ( Opt.fullDesc <> Opt.progDesc "Turn a multi-output matrix branching program into a single-output one" ) loadSource :: Maybe FilePath -> IO MBP loadSource source = do bs <- maybe BS.getContents BS.readFile source either die return (eitherDecode bs) specialize :: Text -> MBP -> Either String MBP specialize selection m = do case dims (outputs m) of (1, _) -> return () _ -> multiRowOutput i <- maybe unknownOutput return $ findIndex (selection==) (head (elems (outputs m))) maybe (columnSelectionFailed i) return $ filterMBP i m where filterRow i = take 1 . drop i filterElems i = map (filterRow i) filterMatrix i = matrix . filterElems i . elems filterMap i = traverse (filterMatrix i) filterStep i s = filterMap i (branches s) >>= step (position s) filterMBP i m = do last:init <- return (reverse (steps m)) last' <- filterStep i last output' <- filterMatrix i (outputs m) mbp (reverse (last':init)) output' multiRowOutput = Left "Turning multi-row-output programs into evasive programs is not yet implemented." unknownOutput = Left $ "The specified matrix branching program does not have " <> T.unpack selection <> "\nas an output. Known outputs are:\n" <> (intercalate "\n" . concat . map (map T.unpack) . elems) (outputs m) columnSelectionFailed i = Left $ "The impossible happened: selecting column " <> show i <> " from the last matrix of the program violated some invariant." saveTarget :: Maybe FilePath -> MBP -> IO () saveTarget target mbp = maybe BS.putStr BS.writeFile target (encode mbp) main :: IO () main = do opts <- Opt.execParser optionsInfo mbp <- loadSource (source opts) case specialize (selection opts) mbp of Left err -> die err Right mbp' -> saveTarget (target opts) mbp'
GaloisInc/cryfsm
fsmevade.hs
bsd-3-clause
3,261
0
15
923
991
498
493
69
2
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Dependency.TopDown.Constraints -- Copyright : (c) Duncan Coutts 2008 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- A set of satisfiable constraints on a set of packages. ----------------------------------------------------------------------------- module Distribution.Client.Dependency.TopDown.Constraints ( Constraints, empty, packages, choices, isPaired, addTarget, constrain, Satisfiable(..), conflicting, ) where import Distribution.Client.Dependency.TopDown.Types import qualified Distribution.Client.PackageIndex as PackageIndex import Distribution.Client.PackageIndex (PackageIndex) import Distribution.Package ( PackageName, PackageId, PackageIdentifier(..) , Package(packageId), packageName, packageVersion , Dependency, PackageFixedDeps(depends) ) import Distribution.Version ( Version ) import Distribution.Client.Utils ( mergeBy, MergeResult(..) ) #if !MIN_VERSION_base(4,8,0) import Data.Monoid ( Monoid(mempty) ) #endif import Data.Either ( partitionEithers ) import qualified Data.Map as Map import Data.Map (Map) import qualified Data.Set as Set import Data.Set (Set) import Control.Exception ( assert ) -- | A set of satisfiable constraints on a set of packages. -- -- The 'Constraints' type keeps track of a set of targets (identified by -- package name) that we know that we need. It also keeps track of a set of -- constraints over all packages in the environment. -- -- It maintains the guarantee that, for the target set, the constraints are -- satisfiable, meaning that there is at least one instance available for each -- package name that satisfies the constraints on that package name. -- -- Note that it is possible to over-constrain a package in the environment that -- is not in the target set -- the satisfiability guarantee is only maintained -- for the target set. This is useful because it allows us to exclude packages -- without needing to know if it would ever be needed or not (e.g. allows -- excluding broken installed packages). -- -- Adding a constraint for a target package can fail if it would mean that -- there are no remaining choices. -- -- Adding a constraint for package that is not a target never fails. -- -- Adding a new target package can fail if that package already has conflicting -- constraints. -- data Constraints installed source reason = Constraints -- | Targets that we know we need. This is the set for which we -- guarantee the constraints are satisfiable. !(Set PackageName) -- | The available/remaining set. These are packages that have available -- choices remaining. This is guaranteed to cover the target packages, -- but can also cover other packages in the environment. New targets can -- only be added if there are available choices remaining for them. !(PackageIndex (InstalledOrSource installed source)) -- | The excluded set. Choices that we have excluded by applying -- constraints. Excluded choices are tagged with the reason. !(PackageIndex (ExcludedPkg (InstalledOrSource installed source) reason)) -- | Paired choices, this is an ugly hack. !(Map PackageName (Version, Version)) -- | Purely for the invariant, we keep a copy of the original index !(PackageIndex (InstalledOrSource installed source)) -- | Reasons for excluding all, or some choices for a package version. -- -- Each package version can have a source instance, an installed instance or -- both. We distinguish reasons for constraints that excluded both instances, -- from reasons for constraints that excluded just one instance. -- data ExcludedPkg pkg reason = ExcludedPkg pkg [reason] -- ^ reasons for excluding both source and installed instances [reason] -- ^ reasons for excluding the installed instance [reason] -- ^ reasons for excluding the source instance instance Package pkg => Package (ExcludedPkg pkg reason) where packageId (ExcludedPkg p _ _ _) = packageId p -- | There is a conservation of packages property. Packages are never gained or -- lost, they just transfer from the remaining set to the excluded set. -- invariant :: (Package installed, Package source) => Constraints installed source a -> Bool invariant (Constraints targets available excluded _ original) = -- Relationship between available, excluded and original all check merged -- targets is a subset of available && all (PackageIndex.elemByPackageName available) (Set.elems targets) where merged = mergeBy (\a b -> packageId a `compare` mergedPackageId b) (PackageIndex.allPackages original) (mergeBy (\a b -> packageId a `compare` packageId b) (PackageIndex.allPackages available) (PackageIndex.allPackages excluded)) where mergedPackageId (OnlyInLeft p ) = packageId p mergedPackageId (OnlyInRight p) = packageId p mergedPackageId (InBoth p _) = packageId p -- If the package was originally installed only, then check (InBoth (InstalledOnly _) cur) = case cur of -- now it's either still remaining as installed only OnlyInLeft (InstalledOnly _) -> True -- or it has been excluded OnlyInRight (ExcludedPkg (InstalledOnly _) [] (_:_) []) -> True _ -> False -- If the package was originally available only, then check (InBoth (SourceOnly _) cur) = case cur of -- now it's either still remaining as source only OnlyInLeft (SourceOnly _) -> True -- or it has been excluded OnlyInRight (ExcludedPkg (SourceOnly _) [] [] (_:_)) -> True _ -> False -- If the package was originally installed and source, then check (InBoth (InstalledAndSource _ _) cur) = case cur of -- We can have both remaining: OnlyInLeft (InstalledAndSource _ _) -> True -- both excluded, in particular it can have had the just source or -- installed excluded and later had both excluded so we do not mind if -- the source or installed excluded is empty or non-empty. OnlyInRight (ExcludedPkg (InstalledAndSource _ _) _ _ _) -> True -- the installed remaining and the source excluded: InBoth (InstalledOnly _) (ExcludedPkg (SourceOnly _) [] [] (_:_)) -> True -- the source remaining and the installed excluded: InBoth (SourceOnly _) (ExcludedPkg (InstalledOnly _) [] (_:_) []) -> True _ -> False check _ = False -- | An update to the constraints can move packages between the two piles -- but not gain or loose packages. transitionsTo :: (Package installed, Package source) => Constraints installed source a -> Constraints installed source a -> Bool transitionsTo constraints @(Constraints _ available excluded _ _) constraints'@(Constraints _ available' excluded' _ _) = invariant constraints && invariant constraints' && null availableGained && null excludedLost && map (mapInstalledOrSource packageId packageId) availableLost == map (mapInstalledOrSource packageId packageId) excludedGained where (availableLost, availableGained) = partitionEithers (foldr lostAndGained [] availableChange) (excludedLost, excludedGained) = partitionEithers (foldr lostAndGained [] excludedChange) availableChange = mergeBy (\a b -> packageId a `compare` packageId b) (PackageIndex.allPackages available) (PackageIndex.allPackages available') excludedChange = mergeBy (\a b -> packageId a `compare` packageId b) [ pkg | ExcludedPkg pkg _ _ _ <- PackageIndex.allPackages excluded ] [ pkg | ExcludedPkg pkg _ _ _ <- PackageIndex.allPackages excluded' ] lostAndGained mr rest = case mr of OnlyInLeft pkg -> Left pkg : rest InBoth (InstalledAndSource pkg _) (SourceOnly _) -> Left (InstalledOnly pkg) : rest InBoth (InstalledAndSource _ pkg) (InstalledOnly _) -> Left (SourceOnly pkg) : rest InBoth (SourceOnly _) (InstalledAndSource pkg _) -> Right (InstalledOnly pkg) : rest InBoth (InstalledOnly _) (InstalledAndSource _ pkg) -> Right (SourceOnly pkg) : rest OnlyInRight pkg -> Right pkg : rest _ -> rest mapInstalledOrSource f g pkg = case pkg of InstalledOnly a -> InstalledOnly (f a) SourceOnly b -> SourceOnly (g b) InstalledAndSource a b -> InstalledAndSource (f a) (g b) -- | We construct 'Constraints' with an initial 'PackageIndex' of all the -- packages available. -- empty :: (PackageFixedDeps installed, Package source) => PackageIndex installed -> PackageIndex source -> Constraints installed source reason empty installed source = Constraints targets pkgs excluded pairs pkgs where targets = mempty excluded = mempty pkgs = PackageIndex.fromList . map toInstalledOrSource $ mergeBy (\a b -> packageId a `compare` packageId b) (PackageIndex.allPackages installed) (PackageIndex.allPackages source) toInstalledOrSource (OnlyInLeft i ) = InstalledOnly i toInstalledOrSource (OnlyInRight a) = SourceOnly a toInstalledOrSource (InBoth i a) = InstalledAndSource i a -- pick up cases like base-3 and 4 where one version depends on the other: pairs = Map.fromList [ (name, (packageVersion pkgid1, packageVersion pkgid2)) | [pkg1, pkg2] <- PackageIndex.allPackagesByName installed , let name = packageName pkg1 pkgid1 = packageId pkg1 pkgid2 = packageId pkg2 , any ((pkgid1==) . packageId) (depends pkg2) || any ((pkgid2==) . packageId) (depends pkg1) ] -- | The package targets. -- packages :: Constraints installed source reason -> Set PackageName packages (Constraints ts _ _ _ _) = ts -- | The package choices that are still available. -- choices :: Constraints installed source reason -> PackageIndex (InstalledOrSource installed source) choices (Constraints _ available _ _ _) = available isPaired :: Constraints installed source reason -> PackageId -> Maybe PackageId isPaired (Constraints _ _ _ pairs _) (PackageIdentifier name version) = case Map.lookup name pairs of Just (v1, v2) | version == v1 -> Just (PackageIdentifier name v2) | version == v2 -> Just (PackageIdentifier name v1) _ -> Nothing data Satisfiable constraints discarded reason = Satisfiable constraints discarded | Unsatisfiable | ConflictsWith [(PackageId, [reason])] addTarget :: (Package installed, Package source) => PackageName -> Constraints installed source reason -> Satisfiable (Constraints installed source reason) () reason addTarget pkgname constraints@(Constraints targets available excluded paired original) -- If it's already a target then there's no change | pkgname `Set.member` targets = Satisfiable constraints () -- If there is some possible choice available for this target then we're ok | PackageIndex.elemByPackageName available pkgname = let targets' = Set.insert pkgname targets constraints' = Constraints targets' available excluded paired original in assert (constraints `transitionsTo` constraints') $ Satisfiable constraints' () -- If it's not available and it is excluded then we return the conflicts | PackageIndex.elemByPackageName excluded pkgname = ConflictsWith conflicts -- Otherwise, it's not available and it has not been excluded so the -- package is simply completely unknown. | otherwise = Unsatisfiable where conflicts = [ (packageId pkg, reasons) | let excludedChoices = PackageIndex.lookupPackageName excluded pkgname , ExcludedPkg pkg isReasons iReasons sReasons <- excludedChoices , let reasons = isReasons ++ iReasons ++ sReasons ] constrain :: (Package installed, Package source) => PackageName -- ^ which package to constrain -> (Version -> Bool -> Bool) -- ^ the constraint test -> reason -- ^ the reason for the constraint -> Constraints installed source reason -> Satisfiable (Constraints installed source reason) [PackageId] reason constrain pkgname constraint reason constraints@(Constraints targets available excluded paired original) | pkgname `Set.member` targets && not anyRemaining = if null conflicts then Unsatisfiable else ConflictsWith conflicts | otherwise = let constraints' = Constraints targets available' excluded' paired original in assert (constraints `transitionsTo` constraints') $ Satisfiable constraints' (map packageId newExcluded) where -- This tells us if any packages would remain at all for this package name if -- we applied this constraint. This amounts to checking if any package -- satisfies the given constraint, including version range and installation -- status. -- (available', excluded', newExcluded, anyRemaining, conflicts) = updatePkgsStatus available excluded [] False [] (mergeBy (\pkg pkg' -> packageVersion pkg `compare` packageVersion pkg') (PackageIndex.lookupPackageName available pkgname) (PackageIndex.lookupPackageName excluded pkgname)) testConstraint pkg = let ver = packageVersion pkg in case Map.lookup (packageName pkg) paired of Just (v1, v2) | ver == v1 || ver == v2 -> case pkg of InstalledOnly ipkg -> InstalledOnly (ipkg, iOk) SourceOnly spkg -> SourceOnly (spkg, sOk) InstalledAndSource ipkg spkg -> InstalledAndSource (ipkg, iOk) (spkg, sOk) where iOk = constraint v1 True || constraint v2 True sOk = constraint v1 False || constraint v2 False _ -> case pkg of InstalledOnly ipkg -> InstalledOnly (ipkg, iOk) SourceOnly spkg -> SourceOnly (spkg, sOk) InstalledAndSource ipkg spkg -> InstalledAndSource (ipkg, iOk) (spkg, sOk) where iOk = constraint ver True sOk = constraint ver False -- For the info about available and excluded versions of the package in -- question, update the info given the current constraint -- -- We update the available package map and the excluded package map -- we also collect: -- * the change in available packages (for logging) -- * whether there are any remaining choices -- * any constraints that conflict with the current constraint updatePkgsStatus _ _ nePkgs ok cs _ | seq nePkgs $ seq ok $ seq cs False = undefined updatePkgsStatus aPkgs ePkgs nePkgs ok cs [] = (aPkgs, ePkgs, reverse nePkgs, ok, reverse cs) updatePkgsStatus aPkgs ePkgs nePkgs ok cs (pkg:pkgs) = let (aPkgs', ePkgs', mnePkg, ok', mc) = updatePkgStatus aPkgs ePkgs pkg nePkgs' = maybeCons mnePkg nePkgs cs' = maybeCons mc cs in updatePkgsStatus aPkgs' ePkgs' nePkgs' (ok' || ok) cs' pkgs maybeCons Nothing xs = xs maybeCons (Just x) xs = x:xs -- For the info about an available or excluded version of the package in -- question, update the info given the current constraint. -- updatePkgStatus aPkgs ePkgs pkg = case viewPackageStatus pkg of AllAvailable (InstalledOnly (aiPkg, False)) -> removeAvailable False (InstalledOnly aiPkg) (PackageIndex.deletePackageId pkgid) (ExcludedPkg (InstalledOnly aiPkg) [] [reason] []) Nothing AllAvailable (SourceOnly (asPkg, False)) -> removeAvailable False (SourceOnly asPkg) (PackageIndex.deletePackageId pkgid) (ExcludedPkg (SourceOnly asPkg) [] [] [reason]) Nothing AllAvailable (InstalledAndSource (aiPkg, False) (asPkg, False)) -> removeAvailable False (InstalledAndSource aiPkg asPkg) (PackageIndex.deletePackageId pkgid) (ExcludedPkg (InstalledAndSource aiPkg asPkg) [reason] [] []) Nothing AllAvailable (InstalledAndSource (aiPkg, True) (asPkg, False)) -> removeAvailable True (SourceOnly asPkg) (PackageIndex.insert (InstalledOnly aiPkg)) (ExcludedPkg (SourceOnly asPkg) [] [] [reason]) Nothing AllAvailable (InstalledAndSource (aiPkg, False) (asPkg, True)) -> removeAvailable True (InstalledOnly aiPkg) (PackageIndex.insert (SourceOnly asPkg)) (ExcludedPkg (InstalledOnly aiPkg) [] [reason] []) Nothing AllAvailable _ -> noChange True Nothing AvailableExcluded (aiPkg, False) (ExcludedPkg (esPkg, False) _ _ srs) -> removeAvailable False (InstalledOnly aiPkg) (PackageIndex.deletePackageId pkgid) (ExcludedPkg (InstalledAndSource aiPkg esPkg) [reason] [] srs) Nothing AvailableExcluded (_aiPkg, True) (ExcludedPkg (esPkg, False) _ _ srs) -> addExtraExclusion True (ExcludedPkg (SourceOnly esPkg) [] [] (reason:srs)) Nothing AvailableExcluded (aiPkg, False) (ExcludedPkg (esPkg, True) _ _ srs) -> removeAvailable True (InstalledOnly aiPkg) (PackageIndex.deletePackageId pkgid) (ExcludedPkg (InstalledAndSource aiPkg esPkg) [] [reason] srs) (Just (pkgid, srs)) AvailableExcluded (_aiPkg, True) (ExcludedPkg (_esPkg, True) _ _ srs) -> noChange True (Just (pkgid, srs)) ExcludedAvailable (ExcludedPkg (eiPkg, False) _ irs _) (asPkg, False) -> removeAvailable False (SourceOnly asPkg) (PackageIndex.deletePackageId pkgid) (ExcludedPkg (InstalledAndSource eiPkg asPkg) [reason] irs []) Nothing ExcludedAvailable (ExcludedPkg (eiPkg, True) _ irs _) (asPkg, False) -> removeAvailable False (SourceOnly asPkg) (PackageIndex.deletePackageId pkgid) (ExcludedPkg (InstalledAndSource eiPkg asPkg) [] irs [reason]) (Just (pkgid, irs)) ExcludedAvailable (ExcludedPkg (eiPkg, False) _ irs _) (_asPkg, True) -> addExtraExclusion True (ExcludedPkg (InstalledOnly eiPkg) [] (reason:irs) []) Nothing ExcludedAvailable (ExcludedPkg (_eiPkg, True) _ irs _) (_asPkg, True) -> noChange True (Just (pkgid, irs)) AllExcluded (ExcludedPkg (InstalledOnly (eiPkg, False)) _ irs _) -> addExtraExclusion False (ExcludedPkg (InstalledOnly eiPkg) [] (reason:irs) []) Nothing AllExcluded (ExcludedPkg (InstalledOnly (_eiPkg, True)) _ irs _) -> noChange False (Just (pkgid, irs)) AllExcluded (ExcludedPkg (SourceOnly (esPkg, False)) _ _ srs) -> addExtraExclusion False (ExcludedPkg (SourceOnly esPkg) [] [] (reason:srs)) Nothing AllExcluded (ExcludedPkg (SourceOnly (_esPkg, True)) _ _ srs) -> noChange False (Just (pkgid, srs)) AllExcluded (ExcludedPkg (InstalledAndSource (eiPkg, False) (esPkg, False)) isrs irs srs) -> addExtraExclusion False (ExcludedPkg (InstalledAndSource eiPkg esPkg) (reason:isrs) irs srs) Nothing AllExcluded (ExcludedPkg (InstalledAndSource (eiPkg, True) (esPkg, False)) isrs irs srs) -> addExtraExclusion False (ExcludedPkg (InstalledAndSource eiPkg esPkg) isrs irs (reason:srs)) (Just (pkgid, irs)) AllExcluded (ExcludedPkg (InstalledAndSource (eiPkg, False) (esPkg, True)) isrs irs srs) -> addExtraExclusion False (ExcludedPkg (InstalledAndSource eiPkg esPkg) isrs (reason:irs) srs) (Just (pkgid, srs)) AllExcluded (ExcludedPkg (InstalledAndSource (_eiPkg, True) (_esPkg, True)) isrs irs srs) -> noChange False (Just (pkgid, isrs ++ irs ++ srs)) where removeAvailable ok nePkg adjustAvailable ePkg c = let aPkgs' = adjustAvailable aPkgs ePkgs' = PackageIndex.insert ePkg ePkgs in aPkgs' `seq` ePkgs' `seq` (aPkgs', ePkgs', Just nePkg, ok, c) addExtraExclusion ok ePkg c = let ePkgs' = PackageIndex.insert ePkg ePkgs in ePkgs' `seq` (aPkgs, ePkgs', Nothing, ok, c) noChange ok c = (aPkgs, ePkgs, Nothing, ok, c) pkgid = case pkg of OnlyInLeft p -> packageId p OnlyInRight p -> packageId p InBoth p _ -> packageId p viewPackageStatus :: (Package installed, Package source) => MergeResult (InstalledOrSource installed source) (ExcludedPkg (InstalledOrSource installed source) reason) -> PackageStatus (installed, Bool) (source, Bool) reason viewPackageStatus merged = case merged of OnlyInLeft aPkg -> AllAvailable (testConstraint aPkg) OnlyInRight (ExcludedPkg ePkg isrs irs srs) -> AllExcluded (ExcludedPkg (testConstraint ePkg) isrs irs srs) InBoth (InstalledOnly aiPkg) (ExcludedPkg (SourceOnly esPkg) [] [] srs) -> case testConstraint (InstalledAndSource aiPkg esPkg) of InstalledAndSource (aiPkg', iOk) (esPkg', sOk) -> AvailableExcluded (aiPkg', iOk) (ExcludedPkg (esPkg', sOk) [] [] srs) _ -> impossible InBoth (SourceOnly asPkg) (ExcludedPkg (InstalledOnly eiPkg) [] irs []) -> case testConstraint (InstalledAndSource eiPkg asPkg) of InstalledAndSource (eiPkg', iOk) (asPkg', sOk) -> ExcludedAvailable (ExcludedPkg (eiPkg', iOk) [] irs []) (asPkg', sOk) _ -> impossible _ -> impossible where impossible = error "impossible: viewPackageStatus invariant violation" -- A intermediate structure that enumerates all the possible cases given the -- invariant. This helps us to get simpler and complete pattern matching in -- updatePkg above -- data PackageStatus installed source reason = AllAvailable (InstalledOrSource installed source) | AllExcluded (ExcludedPkg (InstalledOrSource installed source) reason) | AvailableExcluded installed (ExcludedPkg source reason) | ExcludedAvailable (ExcludedPkg installed reason) source conflicting :: (Package installed, Package source) => Constraints installed source reason -> Dependency -> [(PackageId, [reason])] conflicting (Constraints _ _ excluded _ _) dep = [ (packageId pkg, reasonsAll ++ reasonsAvail ++ reasonsInstalled) --TODO | ExcludedPkg pkg reasonsAll reasonsAvail reasonsInstalled <- PackageIndex.lookupDependency excluded dep ]
christiaanb/cabal
cabal-install/Distribution/Client/Dependency/TopDown/Constraints.hs
bsd-3-clause
24,152
10
17
6,826
5,399
2,884
2,515
393
39
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} module Api where import Control.Monad.Reader (ReaderT, lift, runReaderT) -- import Control.Monad.Trans.Either (EitherT, left) import Control.Monad.Trans.Except (ExceptT, throwE) import Data.Int (Int64) import Database.Persist.Postgresql (Entity (..), fromSqlKey, insert, selectList, (==.)) import Network.Wai (Application) import Servant -- import Servant.JQuery import Config (Config (..)) import Models type PersonAPI = "users" :> Get '[JSON] [Person] :<|> "users" :> Capture "name" String :> Get '[JSON] Person :<|> "users" :> ReqBody '[JSON] Person :> Post '[JSON] Int64 type API = PersonAPI :<|> Raw type AppM = ReaderT Config (ExceptT ServantErr IO) userAPI :: Proxy PersonAPI userAPI = Proxy api :: Proxy API api = Proxy server :: ServerT PersonAPI AppM server = allPersons :<|> singlePerson :<|> createPerson www :: FilePath www = "content" readerServer :: Config -> Server API readerServer cfg = enter (readerToEither cfg) server :<|> serveDirectory www readerToEither :: Config -> AppM :~> ExceptT ServantErr IO readerToEither cfg = Nat $ \x -> runReaderT x cfg app :: Config -> Application app cfg = serve api (readerServer cfg) allPersons :: AppM [Person] allPersons = do users <- runDb $ selectList [] [] let people = map (\(Entity _ y) -> userToPerson y) users return people singlePerson :: String -> AppM Person singlePerson str = do users <- runDb $ selectList [UserName ==. str] [] let list = map (\(Entity _ y) -> userToPerson y) users case list of [] -> lift $ throwE err404 (x:xs) -> return x createPerson :: Person -> AppM Int64 createPerson p = do newPerson <- runDb $ insert $ User (name p) (email p) (registrationDate p) return $ fromSqlKey newPerson -- apiJS :: String -- apiJS = jsForAPI userAPI
radicaljims/pvn-webservice
src/Api.hs
bsd-3-clause
2,083
0
14
580
646
341
305
48
2
module CS.JsonDotNet.Internal ( module CS.JsonDotNet.Internal.Types ) where import CS.JsonDotNet.Internal.Types
cutsea110/servant-csharp
src/CS/JsonDotNet/Internal.hs
bsd-3-clause
143
0
5
40
24
17
7
2
0
-- Copyright 2013 Kevin Backhouse. module TestOrdCons ( tests, instanceTest ) where import qualified Test.Framework as TF ( Test ) import Test.Framework.Providers.QuickCheck2 ( testProperty ) import Control.Monad.ST2 import Control.Monad.MultiPass import Control.Monad.MultiPass.Instrument.OrdCons import Control.Monad.MultiPass.Example.OrdCons import Control.Monad.MultiPass.Utils.InstanceTest import Control.Monad.State.Strict import Control.Monad.Writer.Strict import TestST2 tests :: [TF.Test] tests = [ testProperty "equivalence" prop_equivalence ] -- Generate an array with a repeating sequence of integers. -- For example: -- -- [3,4,5,3,4,5,3,4,5,3,4,5] -- -- Then check that convertArray correctly classifies the numbers -- in the array: -- -- [0,1,2,0,1,2,0,1,2,0,1,2] -- prop_equivalence :: Int -> Int -> Int -> TestST2 Bool prop_equivalence n0 m0 k = let n = n0 `mod` 256 in let m = 1 + (m0 `mod` 256) in TestST2 $ PureST2 $ do xs <- newST2Array_ (0,n-1) sequence_ [ writeST2Array xs i (k + (i `mod` m)) | i <- [0 .. n-1] ] ys <- convertArray (NumThreads 4) xs All success <- execWriterT $ sequence_ [ do x <- lift $ readST2Array xs i y <- lift $ readST2Array ys i tell $ All $ x == y + k | i <- [0 .. n-1] ] return success -- This test checks that all the necessary instances have been -- defined. Its only purpose is to check that there are no compile -- errors, so it does not need to be executed. instanceTest :: ST2 r w () instanceTest = run instanceTestBody instanceTestBody :: TestInstrument2 (OrdCons String r w) r w instanceTestBody = testInstrument2
kevinbackhouse/Control-Monad-MultiPass
tests/TestOrdCons.hs
bsd-3-clause
1,699
0
21
371
440
246
194
37
1
module Arhelk.Armenian.Lemma.Data.Substantive where import Arhelk.Armenian.Lemma.Data.Common import Lens.Simple import Data.Monoid import TextShow -- | Склонение. Describes declension of substantives data Declension = FirstDeclension | SecondDeclension | ThirdDeclension deriving (Eq, Ord, Enum, Show, Bounded) instance TextShow Declension where showb v = case v of FirstDeclension -> "I скл." SecondDeclension -> "II скл." ThirdDeclension -> "III скл." -- | Имя нарицательное или собственное data Appellativity = AppellativeNoun -- ^ Нарицательное | ProperNoun -- ^ Собственное deriving (Eq, Ord, Enum, Show, Bounded) instance TextShow Appellativity where showb v = case v of AppellativeNoun -> "нариц." ProperNoun -> "собств." data Article = Definite | Undefinite | FirstPersonArticle | SecondPersonArticle | ThirdPersonArticle deriving (Eq, Ord, Enum, Show, Bounded) instance TextShow Article where showb v = case v of Definite -> "опр. артикль" Undefinite -> "неопр. артикль" FirstPersonArticle -> "1л притяж. артикль" SecondPersonArticle -> "2л притяж. артикль" ThirdPersonArticle -> "3л притяж. артикль" -- | Substantive morphological properties data SubstantiveProperties = SubstantiveProperties { _substAppellativity :: Maybe Appellativity , _substDeclension :: Maybe Declension , _substQuantity :: Maybe GrammarQuantity , _substCase :: Maybe Հոլով , _substArticle :: Maybe Article } deriving (Eq, Show) $(makeLenses ''SubstantiveProperties) instance Monoid SubstantiveProperties where mempty = SubstantiveProperties { _substAppellativity = Nothing , _substDeclension = Nothing , _substQuantity = Nothing , _substCase = Nothing , _substArticle = Nothing } mappend a b = SubstantiveProperties { _substAppellativity = getFirst $ First (_substAppellativity a) <> First (_substAppellativity b) , _substDeclension = getFirst $ First (_substDeclension a) <> First (_substDeclension b) , _substQuantity = getFirst $ First (_substQuantity a) <> First (_substQuantity b) , _substCase = getFirst $ First (_substCase a) <> First (_substCase b) , _substArticle = getFirst $ First (_substArticle a) <> First (_substArticle b) } instance TextShow SubstantiveProperties where showb SubstantiveProperties{..} = unwordsB [ maybe "" showb _substAppellativity , maybe "" showb _substDeclension , maybe "" showb _substQuantity , maybe "" showb _substCase , maybe "" showb _substArticle ]
Teaspot-Studio/arhelk-armenian
src/Arhelk/Armenian/Lemma/Data/Substantive.hs
bsd-3-clause
2,690
0
12
475
643
344
299
-1
-1
[ ("chord1_begin_fade", "sounds/mono_chord1_begin_fade.wav", (0,11)) , ("chord2_begin_fade", "sounds/mono_chord2_begin_fade.wav", (0,11)) , ("chord3_begin_fade", "sounds/mono_chord3_begin_fade.wav", (0,11)) , ("chord4_begin_fade", "sounds/mono_chord4_begin_fade.wav", (0,11)) , ("chord5_begin_fade", "sounds/mono_chord5_begin_fade.wav", (0,11)) , ("chord6_begin_fade", "sounds/mono_chord6_begin_fade.wav", (0,11)) , ("chord7_begin_fade", "sounds/mono_chord7_begin_fade.wav", (0,11)) , ("chord8_begin_fade", "sounds/mono_chord8_begin_fade.wav", (0,11)) , ("chord1_begin_rev", "sounds/mono_chord1_begin_rev.wav", (0,21)) , ("chord2_begin_rev", "sounds/mono_chord2_begin_rev.wav", (0,21)) , ("chord3_begin_rev", "sounds/mono_chord3_begin_rev.wav", (0,21)) , ("chord4_begin_rev", "sounds/mono_chord4_begin_rev.wav", (0,21)) , ("chord5_begin_rev", "sounds/mono_chord5_begin_rev.wav", (0,21)) , ("chord6_begin_rev", "sounds/mono_chord6_begin_rev.wav", (0,21)) , ("chord7_begin_rev", "sounds/mono_chord7_begin_rev.wav", (0,21)) , ("chord8_begin_rev", "sounds/mono_chord8_begin_rev.wav", (0,21)) , ("mono_crotarc_d_rev", "sounds/mono_crotarc_d_rev.wav", (0,22)) , ("mono_crotarc_e_rev", "sounds/mono_crotarc_e_rev.wav", (0,14)) , ("mono_crotarc_a_rev", "sounds/mono_crotarc_a_rev.wav", (0,13)) , ("mono_crotarc_b_rev", "sounds/mono_crotarc_b_rev.wav", (0,10)) , ("crossing_bass", "sounds/mono_crossing_bass_with_fade.wav", (0,25)) ]
hanshoglund/fluent
setupFluent.hs
bsd-3-clause
1,434
0
7
94
382
253
129
-1
-1
module Hive.WebSocketServer.State ( ServerState(..) , initialServerState ) where import Mitchell.Prelude import Hive.WebSocketServer.Room data ServerState = ServerState { stateRoom :: IORef Room -- ^ The one and only game room the server contains. } initialServerState :: IO ServerState initialServerState = do room <- newRoom roomRef <- newIORef room pure (ServerState roomRef)
mitchellwrosen/hive
hive-websocket-server/src/Hive/WebSocketServer/State.hs
bsd-3-clause
401
0
9
72
91
50
41
12
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE NoRebindableSyntax #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} module Duckling.Duration.Types where import Control.DeepSeq import Data.Aeson import Data.Hashable import Data.Text (Text) import GHC.Generics import TextShow (showt) import Prelude import Duckling.Resolve (Resolve(..)) import Duckling.TimeGrain.Types (Grain(..), inSeconds) data DurationData = DurationData { value :: Int , grain :: Grain } deriving (Eq, Generic, Hashable, Show, Ord, NFData) instance Resolve DurationData where type ResolvedValue DurationData = DurationData resolve _ x = Just x instance ToJSON DurationData where toJSON DurationData {value, grain} = object [ "value" .= value , "unit" .= grain , showt grain .= value , "normalized" .= object [ "unit" .= ("second" :: Text) , "value" .= inSeconds grain value ] ]
rfranek/duckling
Duckling/Duration/Types.hs
bsd-3-clause
1,302
0
12
252
257
151
106
31
0
module Opaleye.Internal.QueryArr where import Prelude hiding (id) import qualified Opaleye.Internal.Unpackspec as U import qualified Opaleye.Internal.Tag as Tag import Opaleye.Internal.Tag (Tag) import qualified Opaleye.Internal.PrimQuery as PQ import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ import qualified Control.Arrow as Arr import Control.Arrow ((&&&), (***), arr) import qualified Control.Category as C import Control.Category ((<<<), id) import Control.Applicative (Applicative, pure, (<*>)) import qualified Data.Profunctor as P import qualified Data.Profunctor.Product as PP -- | @QueryArr a b@ is analogous to a Haskell function @a -> [b]@. newtype QueryArr a b = QueryArr ((a, PQ.PrimQuery, Tag) -> (b, PQ.PrimQuery, Tag)) -- | @Query a@ is analogous to a Haskell value @[a]@. type Query = QueryArr () simpleQueryArr :: ((a, Tag) -> (b, PQ.PrimQuery, Tag)) -> QueryArr a b simpleQueryArr f = QueryArr g where g (a0, primQuery, t0) = (a1, PQ.times primQuery primQuery', t1) where (a1, primQuery', t1) = f (a0, t0) runQueryArr :: QueryArr a b -> (a, PQ.PrimQuery, Tag) -> (b, PQ.PrimQuery, Tag) runQueryArr (QueryArr f) = f runSimpleQueryArr :: QueryArr a b -> (a, Tag) -> (b, PQ.PrimQuery, Tag) runSimpleQueryArr f (a, t) = runQueryArr f (a, PQ.Unit, t) runSimpleQueryArrStart :: QueryArr a b -> a -> (b, PQ.PrimQuery, Tag) runSimpleQueryArrStart q a = runSimpleQueryArr q (a, Tag.start) runQueryArrUnpack :: U.Unpackspec a b -> Query a -> ([HPQ.PrimExpr], PQ.PrimQuery, Tag) runQueryArrUnpack unpackspec q = (primExprs, primQ, endTag) where (columns, primQ, endTag) = runSimpleQueryArrStart q () primExprs = U.collectPEs unpackspec columns first3 :: (a1 -> b) -> (a1, a2, a3) -> (b, a2, a3) first3 f (a1, a2, a3) = (f a1, a2, a3) instance C.Category QueryArr where id = QueryArr id QueryArr f . QueryArr g = QueryArr (f . g) instance Arr.Arrow QueryArr where arr f = QueryArr (first3 f) first f = QueryArr g where g ((b, d), primQ, t0) = ((c, d), primQ', t1) where (c, primQ', t1) = runQueryArr f (b, primQ, t0) instance Functor (QueryArr a) where fmap f = (arr f <<<) instance Applicative (QueryArr a) where pure = arr . const f <*> g = arr (uncurry ($)) <<< (f &&& g) instance P.Profunctor QueryArr where dimap f g a = arr g <<< a <<< arr f instance PP.ProductProfunctor QueryArr where empty = id (***!) = (***)
hesselink/haskell-opaleye
src/Opaleye/Internal/QueryArr.hs
bsd-3-clause
2,486
0
11
515
947
549
398
51
1
-- | See Hoffman, Gelman (2011) The No U-Turn Sampler: Adaptively Setting Path -- Lengths in Hamiltonian Monte Carlo. -- -- This code pretty much follows the notation/structure as the algo in the -- paper. {-# OPTIONS_GHC -Wall #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# LANGUAGE DoAndIfThenElse, FlexibleContexts #-} module Strategy.NUTSDualAveraging (nutsDualAveraging) where import Control.Monad.State.Strict import qualified Data.Vector.Storable as V import Math.Probably.Sampler import Math.Probably.Types import Math.Probably.Utils nutsDualAveraging :: Transition (Maybe DualAveragingParameters) nutsDualAveraging = do c@(Chain (ds, t) target _ tune) <- get r0 <- V.replicateM (V.length t) (lift unormal) z0 <- lift $ expDist 1 let lTarget = curry (logObjective target) ds glTarget = handleGradient $ gradient target logu = auxilliaryTarget lTarget (t, r0) - z0 daParams <- lift $ getDaParams tune c let e = daStep daParams go (tn, tp, rn, rp, tm, j, n, s, a, na) | s == 1 = do vj <- lift $ oneOf [-1, 1] z <- lift unit (tnn, rnn, tpp, rpp, t1, n1, s1, a1, na1) <- if vj == -1 then do (tnn', rnn', _, _, t1', n1', s1', a1', na1') <- buildTreeDualAvg lTarget glTarget tn rn logu vj j e t r0 return (tnn', rnn', tp, rp, t1', n1', s1', a1', na1') else do (_, _, tpp', rpp', t1', n1', s1', a1', na1') <- buildTreeDualAvg lTarget glTarget tp rp logu vj j e t r0 return (tn, rn, tpp', rpp', t1', n1', s1', a1', na1') let accept = s1 == 1 && (min 1 (fi n1 / fi n :: Double)) > z n2 = n + n1 s2 = s1 * stopCriterion tnn tpp rnn rpp j1 = succ j t2 | accept = t1 | otherwise = tm go (tnn, tpp, rnn, rpp, t2, j1, n2, s2, a1, na1) | otherwise = do put $ Chain (ds, tm) target (lTarget tm) (Just daParams) return (a, na) (alpha, nalpha) <- go (t, t, r0, r0, t, 0, 1, 1, 0, 0) let (hNext, eNext, eAvgNext) = if mAdapt daParams <= 0 then (hm, exp logEm, exp logEbarM) else (daH daParams, daStepAvg daParams, daStepAvg daParams) where eta = 1 / (fromIntegral (mAdapt daParams) + tau0 daParams) hm = (1 - eta) * daH daParams + eta * (delta daParams - alpha / fromIntegral nalpha) zeta = fromIntegral (mAdapt daParams) ** (- (kappa daParams)) logEm = mu daParams - sqrt (fromIntegral (mAdapt daParams)) / gammaP daParams * hm logEbarM = (1 - zeta) * log (daStepAvg daParams) + zeta * logEm let newDaParams = DualAveragingParameters { mAdapt = max 0 (pred $ mAdapt daParams) , delta = delta daParams , mu = mu daParams , gammaP = gammaP daParams , tau0 = tau0 daParams , kappa = kappa daParams , daStep = eNext , daStepAvg = eAvgNext , daH = hNext } modify (\s -> s { tunables = Just newDaParams }) gets parameterSpacePosition stopCriterion :: ContinuousParams -> ContinuousParams -> ContinuousParams -> ContinuousParams -> Int stopCriterion tn tp rn rp = indicate (positionDifference `innerProduct` rn >= 0) * indicate (positionDifference `innerProduct` rp >= 0) where positionDifference = tp .- tn buildTreeDualAvg lTarget glTarget t r logu v 0 e t0 r0 = do let (t1, r1) = leapfrog glTarget (t, r) (v * e) jointL = auxilliaryTarget lTarget (t1, r1) n = indicate (logu < jointL) s = indicate (logu - 1000 < jointL) a = min 0 (logAcceptProb lTarget (t0, t1) (r0, r1)) return (t1, r1, t1, r1, t1, n, s, a, 1) buildTreeDualAvg lTarget glTarget t r logu v j e t0 r0 = do z <- lift unit (tn, rn, tp, rp, t1, n1, s1, a1, na1) <- buildTreeDualAvg lTarget glTarget t r logu v (pred j) e t0 r0 if s1 == 1 then do (tnn, rnn, tpp, rpp, t2, n2, s2, a2, na2) <- if v == -1 then do (tnn', rnn', _, _, t1', n1', s1', a1', na1') <- buildTreeDualAvg lTarget glTarget tn rn logu v (pred j) e t0 r0 return (tnn', rnn', tp, rp, t1', n1', s1', a1', na1') else do (_, _, tpp', rpp', t1', n1', s1', a1', na1') <- buildTreeDualAvg lTarget glTarget tp rp logu v (pred j) e t0 r0 return (tn, rn, tpp', rpp', t1', n1', s1', a1', na1') let p = fromIntegral n2 / max (fromIntegral (n1 + n2)) 1 accept = p > (z :: Double) n3 = n1 + n2 a3 = a1 + a2 na3 = na1 + na2 s3 = s1 * s2 * stopCriterion tnn tpp rnn rpp t3 | accept = t2 | otherwise = t1 return (tnn, rnn, tpp, rpp, t3, n3, s3, a3, na3) else return (tn, rn, tp, rp, t1, n1, s1, a1, na1) findReasonableEpsilon :: (ContinuousParams -> Double) -> Gradient -> ContinuousParams -> Prob Double findReasonableEpsilon lTarget glTarget t0 = do r0 <- V.replicateM (V.length t0) unormal let (t1, r1) = leapfrog glTarget (t0, r0) 1.0 a = 2 * indicate (pAccept > 0.5) - 1 :: Int pAccept = exp $ logAcceptProb lTarget (t0, t1) (r0, r1) go j e t r | j <= 0 = e -- no need to shrink this excessively | (exp $ logAcceptProb lTarget (t0, t) (r0, r)) ^^ a > 2 ^^ (-a) = let (tn, rn) = leapfrog glTarget (t, r) e in go (pred j) (2 ^^ a * e) tn rn | otherwise = e return $ go 10 1.0 t1 r1 logAcceptProb :: (ContinuousParams -> Double) -> Particle -> Particle -> Double logAcceptProb lTarget (t0, t1) (r0, r1) = auxilliaryTarget lTarget (t1, r1) - auxilliaryTarget lTarget (t0, r0) getDaParams :: Maybe DualAveragingParameters -> Chain (Maybe DualAveragingParameters) -> Prob DualAveragingParameters getDaParams Nothing (Chain (ds, t) target _ Nothing) = do let lTarget = curry (logObjective target) ds glTarget = handleGradient $ gradient target step <- findReasonableEpsilon lTarget glTarget t return $ defaultDualAveragingParameters step 1000 getDaParams Nothing (Chain _ _ _ (Just daParams)) = return daParams getDaParams (Just daParams) (Chain _ _ _ Nothing) = return daParams getDaParams (Just _) (Chain _ _ _ (Just daParams)) = return daParams
glutamate/probably-baysig
src/Strategy/NUTSDualAveraging.hs
bsd-3-clause
6,523
0
22
2,028
2,509
1,346
1,163
144
3
{- - Route.hs - By Steven Smith -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} -- | 'Route' is a data type defining the hierarchy of web routes for a web -- application. -- -- A web route is a URI path to a resource. Consider the following URL: -- -- > http://www.example.com/users/103/history?query=foo&s=bar -- -- The route for this URL would be \"@users\/103\/history@\". When a request is -- received it is split up into path segments and walked down the tree matching -- segments (and potentially back-tracking) until it reaches an 'EndPoint' that -- matches on the request method (@GET@, @PUT@, etc.). An 'EndPoint' then -- generates the response to send back to the client. -- -- Web routes are naturally hierarchical, so the 'Route' data type -- represents a tree. It fully supports back-tracking, so branches that end -- without matching an 'EndPoint' will simply back-track up the tree and -- continue attempting to match. module Web.DumpTruck.Route ( Route , route , routeEnd , capture , captureInt , get , post , put , delete , options , patch , method , matchAny , remainingPath , directory , directory' , mkDumpTruckApp , mkDumpTruckApp' ) where import Web.DumpTruck.Capture import Web.DumpTruck.EndPoint import Data.ByteString.Lazy (ByteString) import Data.List (intersperse, stripPrefix) import Data.Text (Text) import Control.Applicative import Control.Monad import Network.Wai import Network.HTTP.Types import qualified Data.Text as T -- | The 'Route' web routing tree data type. A DumpTruck web application is a -- 'Route' routing tree with some number of 'EndPoint' leaves that produce a -- 'Response'. 'Route' is a 'Monad', and @do@ notation is the prefered means of -- building up 'Route' values. newtype Route s a = Route { runRoute :: [Text] -> Method -> Either (EndPoint s IO ()) a } instance Functor (Route s) where fmap f (Route r) = Route go where go ts m = fmap f (r ts m) instance Applicative (Route s) where pure x = Route go where go _ _ = Right x (Route f) <*> (Route r) = Route go where go ts m = let f' = f ts m r' = r ts m in f' <*> r' instance Monad (Route s) where return = pure (Route f) >>= k = Route go where go ts m = case f ts m of Left e -> Left e Right a -> (runRoute (k a)) ts m ------------------------------------------------------------------------------- -- Route Smart Constructors ------------------------------------------------------------------------------- -- | Attempts to match the current path segment with the given 'Text'. If -- successful, it will consume the path segment and continue down the given -- 'Route'. Otherwise, matching will fall through to the next 'Route'. route :: Text -- ^ The path segment to match on. Multiple path segments can be -- specified at once by separating them with "@\/@" characters. -- Leading and trailing "@\/@" characters are ignored. -> Route s () -- ^ The route to take if matching succeeds. -> Route s () route t (Route r) = Route go where go [] _ = return () go ps m = case stripPrefix (filter (/= "") (T.splitOn "/" t)) ps of Nothing -> return () Just xs -> r xs m -- | Will only match if there are no more path segments to consider. Otherwise, -- matching will fall through to the next 'Route'. routeEnd :: Route s () -- ^ The route to take if matching succeeds. -> Route s () routeEnd (Route r) = Route go where go [] m = r [] m go _ _ = return () -- | Matches any path segment that can be parsed into a 'Captureable' type. If -- parsing succeeds the path segment is consumed and passed to the given -- function as the parsed value to produce the 'Route' to continue on. -- Otherwise matching falls through to the next 'Route'. -- -- Note: Since this function is polymorphic in the argument but not the result, -- it may be necessary to include a type annotation in the given function to -- force its argument type to be monomorphic. capture :: Captureable a => (a -> Route s ()) -- ^ The function called when there is a path -- segment and it can be parsed into the -- appropriate type. The parsed value will be fed -- into this function to produce the next 'Route' -- to take. -> Route s () capture f = Route go where go [] _ = return () go (x:xs) m = case performCapture x of Nothing -> return () Just a -> (runRoute (f a)) xs m -- | Matches any path segment that can be parsed into an 'Int'. If parsing -- succeeds the path segment is consumed and passed to the given function as the -- parsed value to produce the 'Route' to continue on. Otherwise matching falls -- through to the next 'Route'. -- -- Note: This function is just a monomorphic version of 'capture'. captureInt :: (Int -> Route s ()) -- ^ The function called when there is a path -- segment and it can be parsed into an 'Int'. -- The parsed value will be fed into this -- function to produce the route to take. -> Route s () captureInt = capture -- | Matches if the request method is @GET@. This is a terminal node. If -- matching succeeds, the 'EndPoint' will be executed to generate the final -- 'Response' and matching will end. get :: EndPoint s IO () -> Route s () get = method methodGet -- | Matches if the request method is @POST@. This is a terminal node. If -- matching succeeds, the 'EndPoint' will be executed to generate the final -- 'Response' and matching will end. post :: EndPoint s IO () -> Route s () post = method methodPost -- | Matches if the request method is @PUT@. This is a terminal node. If -- matching succeeds, the 'EndPoint' will be executed to generate the final -- 'Response' and matching will end. put :: EndPoint s IO () -> Route s () put = method methodPut -- | Matches if the request method is @DELETE@. This is a terminal node. If -- matching succeeds, the 'EndPoint' will be executed to generate the final -- 'Response' and matching will end. delete :: EndPoint s IO () -> Route s () delete = method methodDelete -- | Matches if the request method is @OPTIONS@. This is a terminal node. If -- matching succeeds, the 'EndPoint' will be executed to generate the final -- 'Response' and matching will end. options :: EndPoint s IO () -> Route s () options = method methodOptions -- | Matches if the request method is @PATCH@. This is a terminal node. If -- matching succeeds, the 'EndPoint' will be executed to generate the final -- 'Response' and matching will end. patch :: EndPoint s IO () -> Route s () patch = method methodPatch -- | Matches if the request method is the one provided. This is a terminal node. -- If matching succeeds, the 'EndPoint' will be executed to generate the final -- 'Response' and matching will end. method :: Method -> EndPoint s IO () -> Route s () method m e = Route go where go _ m' | m == m' = Left e | otherwise = return () -- | Matching will always succeed. This is a terminal node. The 'EndPoint' -- will always be executed to generate the final 'Response' and matching will -- end. matchAny :: EndPoint s IO () -> Route s () matchAny e = Route go where go _ _ = Left e -- | Produces the remaining path to match against as a list of 'Text' path -- segments. remainingPath :: Route s [Text] remainingPath = Route go where go p _ = return p -- Derived -- | Attempts to match the given 'Text' path segment in the same manner as -- 'route'. If matching succeeds and the request method is @GET@, then it will -- take the given path segment and the remaining request path, append them, and -- attempt to serve the file at the resulting file path. Will give a @404 Not -- Found@ if the file does not exist. -- -- This will also filter out any path segments that are "@..@" because this can -- be a potential security hole and is essentially never desired behavior. directory :: Text -> Route s () directory fp = directory' fp fp -- | This is a variation of 'directory' in which the route to match and the base -- path of the file to serve can be different. directory' :: Text -- ^ The route to match -> Text -- ^ The base path for the path to serve -> Route s () directory' rt fp = route rt $ do path <- remainingPath get $ go path where go = file . T.unpack . T.concat . intersperse "/" . (fp :) . filter (/= "..") ------------------------------------------------------------------------------- -- Running DumpTruck Apps ------------------------------------------------------------------------------- -- | Converts a DumpTruck app into a WAI 'Application', which can be run on any -- web server that can serve WAI 'Application's. mkDumpTruckApp :: Route s a -> s -> Application mkDumpTruckApp (Route r) s req cont = case r (pathInfo req) (requestMethod req) of Right _ -> cont' notFound Left e -> cont' e where cont' = generateResponse req s >=> cont -- | Converts a DumpTruck app into a WAI 'Application', which can be run on any -- web server that can serve WAI 'Application's. This variant can be used in -- instances where the environment value is not used. mkDumpTruckApp' :: (forall s. Route s a) -> Application mkDumpTruckApp' r = mkDumpTruckApp r undefined
stevely/DumpTruck
src/Web/DumpTruck/Route.hs
bsd-3-clause
9,583
0
15
2,289
1,550
828
722
112
3
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Brancher -- Copyright : (c) Andrea Vezzosi 2008 -- Duncan Coutts 2011 -- John Millikin 2012 -- Rahul Muttineni 2017 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Helper functions for fetching package sources from SCM systems ----------------------------------------------------------------------------- module Distribution.Client.Brancher ( findUsableBranchers, forkPackage ) where import Distribution.Verbosity ( Verbosity ) import System.Exit ( ExitCode(..) ) import qualified Distribution.PackageDescription as PD import qualified Data.Map import Distribution.Compat.Exception ( catchIO ) import Distribution.Client.Compat.Process ( readProcessWithExitCode ) import Control.Monad ( filterM, when ) import Distribution.Package ( PackageId, PackageName ) import Distribution.Text(display) import System.FilePath ( (</>) ) import System.Directory ( doesDirectoryExist, doesFileExist ) import Distribution.Simple.Utils ( notice, die ) import System.Process ( rawSystem ) import Data.Maybe ( listToMaybe, mapMaybe ) import Data.List ( sortBy ) import Data.Ord ( comparing ) -- ------------------------------------------------------------ -- * Forking the source repository -- ------------------------------------------------------------ data BranchCmd = BranchCmd (Verbosity -> FilePath -> IO ExitCode) data Brancher = Brancher { brancherBinary :: String , brancherBuildCmd :: PD.SourceRepo -> Maybe BranchCmd } -- | The set of all supported branch drivers. allBranchers :: [(PD.RepoType, Brancher)] allBranchers = [ (PD.Bazaar, branchBzr) , (PD.Darcs, branchDarcs) , (PD.Git, branchGit) , (PD.Mercurial, branchHg) , (PD.SVN, branchSvn) ] -- | Find which usable branch drivers (selected from 'allBranchers') are -- available and usable on the local machine. -- -- Each driver's main command is run with @--help@, and if the child process -- exits successfully, that brancher is considered usable. findUsableBranchers :: IO (Data.Map.Map PD.RepoType Brancher) findUsableBranchers = do let usable (_, brancher) = flip catchIO (const (return False)) $ do let cmd = brancherBinary brancher (exitCode, _, _) <- readProcessWithExitCode cmd ["--help"] "" return (exitCode == ExitSuccess) pairs <- filterM usable allBranchers return (Data.Map.fromList pairs) -- | Fork a single package from a remote source repository to the local -- file system. forkPackage :: Verbosity -> Data.Map.Map PD.RepoType Brancher -- ^ Branchers supported by the local machine. -> FilePath -- ^ The directory in which new branches or repositories will -- be created. -> (Maybe PD.RepoKind) -- ^ Which repo to choose. -> PackageId -> [PD.SourceRepo] -- ^ The package to fork. -> IO () forkPackage verbosity branchers prefix kind pkgid' repos = do let pkgid = display pkgid' destdir = prefix destDirExists <- doesDirectoryExist destdir when destDirExists $ do die ("The directory " ++ show destdir ++ " already exists, not forking.") destFileExists <- doesFileExist destdir when destFileExists $ do die ("A file " ++ show destdir ++ " is in the way, not forking.") case findBranchCmd branchers repos kind of Just (BranchCmd io) -> do exitCode <- io verbosity destdir case exitCode of ExitSuccess -> return () ExitFailure _ -> die ("Couldn't fork package " ++ pkgid) Nothing -> case repos of [] -> die ("Package " ++ pkgid ++ " does not have any source repositories.") _ -> die ("Package " ++ pkgid ++ " does not have any usable source repositories.") -- | Given a set of possible branchers, and a set of possible source -- repositories, find a repository that is both 1) likely to be specific to -- this source version and 2) is supported by the local machine. findBranchCmd :: Data.Map.Map PD.RepoType Brancher -> [PD.SourceRepo] -> (Maybe PD.RepoKind) -> Maybe BranchCmd findBranchCmd branchers allRepos maybeKind = cmd where -- Sort repositories by kind, from This to Head to Unknown. Repositories -- with equivalent kinds are selected based on the order they appear in -- the Cabal description file. repos' = sortBy (comparing thisFirst) allRepos thisFirst r = case PD.repoKind r of PD.RepoThis -> 0 :: Int PD.RepoHead -> case PD.repoTag r of -- If the type is 'head' but the author specified a tag, they -- probably meant to create a 'this' repository but screwed up. Just _ -> 0 Nothing -> 1 PD.RepoKindUnknown _ -> 2 -- If the user has specified the repo kind, filter out the repositories -- she's not interested in. repos = maybe repos' (\k -> filter ((==) k . PD.repoKind) repos') maybeKind repoBranchCmd repo = do t <- PD.repoType repo brancher <- Data.Map.lookup t branchers brancherBuildCmd brancher repo cmd = listToMaybe (mapMaybe repoBranchCmd repos) -- | Branch driver for Bazaar. branchBzr :: Brancher branchBzr = Brancher "bzr" $ \repo -> do src <- PD.repoLocation repo let args dst = case PD.repoTag repo of Just tag -> ["branch", src, dst, "-r", "tag:" ++ tag] Nothing -> ["branch", src, dst] return $ BranchCmd $ \verbosity dst -> do notice verbosity ("bzr: branch " ++ show src) rawSystem "bzr" (args dst) -- | Branch driver for Darcs. branchDarcs :: Brancher branchDarcs = Brancher "darcs" $ \repo -> do src <- PD.repoLocation repo let args dst = case PD.repoTag repo of Just tag -> ["get", src, dst, "-t", tag] Nothing -> ["get", src, dst] return $ BranchCmd $ \verbosity dst -> do notice verbosity ("darcs: get " ++ show src) rawSystem "darcs" (args dst) -- | Branch driver for Git. branchGit :: Brancher branchGit = Brancher "git" $ \repo -> do src <- PD.repoLocation repo let branchArgs = ["--depth","1"] ++ case PD.repoBranch repo of Just b -> ["--branch", b] Nothing -> case PD.repoTag repo of Just t -> ["--branch", t] Nothing -> [] return $ BranchCmd $ \verbosity dst -> do notice verbosity ("git: clone " ++ show src) rawSystem "git" (["clone", src, dst] ++ branchArgs) -- | Branch driver for Mercurial. branchHg :: Brancher branchHg = Brancher "hg" $ \repo -> do src <- PD.repoLocation repo let branchArgs = case PD.repoBranch repo of Just b -> ["--branch", b] Nothing -> [] let tagArgs = case PD.repoTag repo of Just t -> ["--rev", t] Nothing -> [] let args dst = ["clone", src, dst] ++ branchArgs ++ tagArgs return $ BranchCmd $ \verbosity dst -> do notice verbosity ("hg: clone " ++ show src) rawSystem "hg" (args dst) -- | Branch driver for Subversion. branchSvn :: Brancher branchSvn = Brancher "svn" $ \repo -> do src <- PD.repoLocation repo let args dst = ["checkout", src, dst] return $ BranchCmd $ \verbosity dst -> do notice verbosity ("svn: checkout " ++ show src) rawSystem "svn" (args dst)
typelead/epm
epm/Distribution/Client/Brancher.hs
bsd-3-clause
7,738
0
19
2,070
1,823
956
867
143
4
{-# OPTIONS -Wall #-} module TuringMachine.Models.TM3 ( mach ) where import Basic.Types (Pointed(..)) import Basic.MemoryImpl import TuringMachine.State import TuringMachine.Machine -------------------------------------------------------------------------- --------------------------specilized model operations & models -------------------------------------------------------------------------- -- MTM (Multidimensional Turing Machine) -- 1 Examples of Turing Machine data CState = B | C | D | HALT deriving (Show, Eq) data TMAlp = Zero | One deriving (Show, Eq) instance Pointed TMAlp where pt = Zero trans :: CState -> [TMAlp] -> (CState, [TMAlp], [TMDirection]) trans D [Zero, Zero] = (B, [One, One] , [TMRight, TMRight]) trans D [One , One ] = (C, [One, One] , [TMLeft, TMLeft]) trans B [Zero, Zero] = (D, [One, One] , [TMLeft, TMLeft]) trans B [One , One ] = (B, [One, One] , [TMRight, TMRight]) trans C [Zero, Zero] = (B, [One, One] , [TMLeft, TMLeft]) trans C [One , One ] = (HALT, [One, One] , [TMRight, TMRight]) trans _ _ = error "undefined transition" initialState :: TMStaten ITwo MapMem TMAlp TapeMem CState initialState = initialTMStaten Zero D finalState :: ListMem CState finalState = fillMem [HALT] mach :: TMn ITwo MapMem TMAlp TapeMem CState ListMem mach = TM initialState finalState (gcompile $ translate trans)
davidzhulijun/TAM
TuringMachine/Models/TM3.hs
bsd-3-clause
1,346
0
8
207
459
273
186
24
1
module Main where import qualified Test.Binary as Binary import qualified Test.Vector as Vector import Test.Tasty main = defaultMain tests tests :: TestTree tests = testGroup "Test" [binaryTrie] binaryTrie :: TestTree binaryTrie = testGroup "Binary Trie" Binary.tests vector :: TestTree vector = testGroup "Trie" Vector.tests
TikhonJelvis/different-tries
tests/tests.hs
bsd-3-clause
342
0
6
60
85
50
35
11
1
{-# LANGUAGE NoMonomorphismRestriction #-} module Grammar.Utils where import Control.Applicative import Control.Arrow (second) import Data.Map (Map) import qualified Data.Map as M import Data.Maybe import AST import CppToken import Grammar.Parser infixl 3 $> ($>) = flip (<$) type MParser a = Parser ParserState Tok a {-# INLINE token #-} token t = satisfy (show t) (== t) lookToken t = satisfyLook (show t) (== t) addLocation :: MParser a -> MParser (Loc a) addLocation p = (\start p end -> Loc (Location start end) p) <$> lookPosition <*> p <*> lookPosition keyword str = token (Reserved str) {-# INLINE parseJust #-} parseJust msg f = second (fromJust . f) <$> satisfy msg (isJust . f) identifier = parseJust "Identifier" fromIdentifier integer = second fromIntegral <$> parseJust "integer" fromIntegerTok string = parseJust "string" fromStringTok char = parseJust "char" fromCharTok fromIdentifier (Identifier s) = Just s fromIdentifier _ = Nothing fromIntegerTok (IntegerTok i) = Just i fromIntegerTok _ = Nothing fromStringTok (StringTok s) = Just s fromStringTok _ = Nothing fromCharTok (CharTok c) = Just c fromCharTok _ = Nothing postfixOperator = choice (map (token.snd) postfixOperators) prefixOperator = choice (map (token.snd) prefixOperators) inBraces p = token OpenBrace *> p <* token CloseBrace inBrackets p = token OpenBracket *> p <* token CloseBracket inParens p = token OpenParen *> p <* token CloseParen inTypeBrackets p = token OpenTypeBracket *> p <* token CloseTypeBracket listOf p = sepBy p (token Comma) pSimpleName = (\(_,nm) -> QualifiedName [nm]) <$> identifier pName = QualifiedName . map snd <$> sepBy1 identifier (token DoubleColon) pStringName = (\(_,str) -> QualifiedName [str]) <$> string data ParserState = PState (Map Name Type) deriving Show initialParserState = PState M.empty
olsner/m3
Grammar/Utils.hs
bsd-3-clause
1,837
0
12
296
665
345
320
45
1
{-# LANGUAGE FlexibleContexts, RecordWildCards, CPP #-} module AWS.EC2.Route ( createRoute , deleteRoute , replaceRoute ) where import Data.ByteString (ByteString) #if MIN_VERSION_conduit(1,1,0) import Control.Monad.Trans.Resource (MonadBaseControl, MonadResource) #else import Data.Conduit (MonadBaseControl, MonadResource) #endif import Data.IP (AddrRange, IPv4) import Data.Text (Text) import AWS.EC2.Internal (EC2) import AWS.EC2.Query (ec2Query, (|=)) import AWS.EC2.Types (CreateRouteRequest(..)) import AWS.Lib.Parser (getT) import AWS.Util (toText) createRoute :: (MonadResource m, MonadBaseControl IO m) => CreateRouteRequest -> EC2 m Bool createRoute = routeRequest "CreateRoute" deleteRoute :: (MonadResource m, MonadBaseControl IO m) => Text -- ^ The ID of the route table. -> AddrRange IPv4 -- ^ The CIDR range of the destination for the route to delete. -> EC2 m Bool deleteRoute tableId cidrBlock = ec2Query "DeleteRoute" [ "RouteTableId" |= tableId , "DestinationCidrBlock" |= toText cidrBlock ] $ getT "return" replaceRoute :: (MonadResource m, MonadBaseControl IO m) => CreateRouteRequest -> EC2 m Bool replaceRoute = routeRequest "ReplaceRoute" routeRequest :: (MonadResource m, MonadBaseControl IO m) => ByteString -> CreateRouteRequest -> EC2 m Bool routeRequest action (CreateRouteToGateway{..}) = routeRequest' action createRouteTableId createRouteDestinationCidrBlock "GatewayId" createRouteGatewayId routeRequest action (CreateRouteToInstance{..}) = routeRequest' action createRouteTableId createRouteDestinationCidrBlock "InstanceId" createRouteInstanceId routeRequest action (CreateRouteToNetworkInterface{..}) = routeRequest' action createRouteTableId createRouteDestinationCidrBlock "NetworkInterfaceId" createRouteNetworkInterfaceId routeRequest' :: (MonadResource m, MonadBaseControl IO m) => ByteString -> Text -> AddrRange IPv4 -> Text -> Text -> EC2 m Bool routeRequest' action tableId cidrBlock targetName targetId = ec2Query action [ "RouteTableId" |= tableId , "DestinationCidrBlock" |= toText cidrBlock , targetName |= targetId ] $ getT "return"
IanConnolly/aws-sdk-fork
AWS/EC2/Route.hs
bsd-3-clause
2,274
0
11
427
517
281
236
59
1
{-# LANGUAGE StandaloneDeriving #-} import Control.Parallel.Foldl import Control.Applicative import Numeric.Datasets.Iris import Numeric.Datasets.BostonHousing import Numeric.Datasets import qualified Data.Map.Strict as Map irisApply :: Fold Double Double -> Fold Iris Iris irisApply f = Iris <$> premap sepalLength f <*> premap sepalWidth f <*> premap petalLength f <*> premap petalWidth f <*> premap irisClass mode main :: IO () main = do print $ ("iris average seplen", fold (premap sepalLength average) iris) print $ ("iris variance seplen", fold (premap sepalLength variance) iris) print $ ("iris twopvar seplen", twoPassVariance $ map sepalLength iris) print $ fold (irisApply average) iris let byClass = Map.toList $ fold (groupBy irisClass $ irisApply average) iris mapM_ print byClass bh <- getDataset bostonHousing print $ length bh print $ fold (premap tax average) bh print $ fold (premap tax variance) bh print $ twoPassVariance $ map tax bh let manyNums = [1..10000] print $ twoPassVariance manyNums print $ fold variance manyNums {- scikit-learn >>> iris.data[:,0].var(ddof=0) 0.6811222222222223 >>> iris.data[:,0].var(ddof=1) 0.68569351230425069 >>> boston.data[:,9].var(ddof=0) 28348.62359980628 >>> boston.data[:,9].var(ddof=1) 28404.759488122731 -}
filopodia/open
parfoldl/TestParFoldl.hs
mit
1,488
0
14
387
372
180
192
28
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} -- Module : Khan.Model.EC2.Image -- Copyright : (c) 2013 Brendan Hay <[email protected]> -- 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 <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) module Khan.Model.EC2.Image ( find , findAll , findAllCatch , create ) where import Control.Monad import qualified Data.Text as Text import Khan.Internal import qualified Khan.Model.Tag as Tag import Khan.Prelude hiding (find, min, max) import Network.AWS.EC2 hiding (Instance, wait) find :: [Text] -> [Filter] -> AWS DescribeImagesResponseItemType find ids fs = findAll ids fs >>= hoistError . note "Failed to find any matching Images" . listToMaybe findAll :: [Text] -> [Filter] -> AWS [DescribeImagesResponseItemType] findAll ids fs = do if null ids then log_ "Searching for Images..." else say "Searching for Images {}" [L ids] djImagesSet <$> send (DescribeImages [] ids [] fs) findAllCatch :: [Text] -> [Filter] -> AWS (Either EC2ErrorResponse [DescribeImagesResponseItemType]) findAllCatch ids fs = fmap djImagesSet <$> sendCatch (DescribeImages [] ids [] fs) create :: Naming a => a -> Text -> [BlockDeviceMappingItemType] -> AWS Text create (names -> n@Names{..}) i bs = do say "Creating Image {} from {}" [imageName, i] img <- cjImageId <$> send (CreateImage i imageName Nothing Nothing bs) wait limit img Tag.images n [img] return img where wait 0 img = throwAWS "Image creation failed: {}" [B img] wait l img = do say "Waiting {} seconds for Image {} creation..." [show delay, Text.unpack img] delaySeconds delay rs <- findAllCatch [img] [] verifyEC2 "InvalidAMIID.NotFound" rs if pending (hush rs) then say "Image still pending: {}" [img] >> wait (l - 1) img else say "Image marked as available: {}" [img] pending (Just (x:_)) = diritImageState x /= "available" pending _ = True limit = 24 :: Int -- 24 * 20 seconds = 8 minutes delay = 20 -- 20 seconds
zinfra/khan
khan/src/Khan/Model/EC2/Image.hs
mpl-2.0
2,586
0
13
704
620
327
293
50
4
{- | Module : Data.PDRS.Merge Copyright : (c) Harm Brouwer and Noortje Venhuizen License : Apache-2.0 Maintainer : [email protected], [email protected] Stability : provisional Portability : portable The module "Data.PDRS.Merge" contains functions required for merging 'PDRS's. -} module Data.PDRS.Merge ( pdrsAMerge , (<<+>>) , pdrsPMerge , (<<*>>) , pdrsCombine , (<<&>>) , pdrsResolveMerges , pdrsDisjoin ) where import Data.PDRS.LambdaCalculus import Data.PDRS.DataType import Data.PDRS.Structure import Data.PDRS.Variables import Data.List (intersect, union) --------------------------------------------------------------------------- -- * Exported --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- | Applies assertive merge to 'PDRS' @p1@ and 'PDRS' @p2@. --------------------------------------------------------------------------- pdrsAMerge :: PDRS -> PDRS -> PDRS pdrsAMerge p lp@(LambdaPDRS _) = AMerge p lp pdrsAMerge lp@(LambdaPDRS _) p = AMerge lp p pdrsAMerge p am@(AMerge k1 k2) | isLambdaPDRS k1 = AMerge k1 (pdrsAMerge p k2) -- p + (lk1 + k2) = lk1 + (p + k2) | isLambdaPDRS k2 = AMerge (pdrsAMerge p k1) k2 -- p + (k1 + lk2) = (p + k1) + lk2 | otherwise = pdrsAMerge p (pdrsResolveMerges am) pdrsAMerge am@(AMerge k1 k2) p | isLambdaPDRS k1 = AMerge k1 (pdrsAMerge k2 p) -- (lk1 + k2) + p = lk1 + (k2 + p) | isLambdaPDRS k2 = AMerge k2 (pdrsAMerge k1 p) -- (k1 + lk2) + p = lk2 + (k1 + p) | otherwise = pdrsAMerge (pdrsResolveMerges am) p pdrsAMerge p pm@(PMerge k1 k2) | isLambdaPDRS k1 = PMerge k1 (pdrsAMerge p k2) -- p + (lk1 * k2) = lk1 * (p + k2) | isLambdaPDRS k2 = AMerge (pdrsPMerge k1 p) k2 -- p + (k1 * lk2) = (k1 * p) + lk2 | otherwise = pdrsAMerge p (pdrsResolveMerges pm) pdrsAMerge pm@(PMerge k1 k2) p | isLambdaPDRS k1 = PMerge k1 (pdrsAMerge k2 p) -- (lk1 * k2) + p = lk1 * (k2 + p) | isLambdaPDRS k2 = AMerge k2 (pdrsPMerge k1 p) -- (k1 * lk2) + p = lk2 + (k1 * p) | otherwise = pdrsAMerge (pdrsResolveMerges pm) p pdrsAMerge p1@(PDRS{}) p2@(PDRS{}) = pdrsPurify $ amerge p1 (pdrsDisjoin p2' p1') where p1' = pdrsPurify $ pdrsResolveMerges p1 p2' = pdrsPurify $ pdrsResolveMerges p2 amerge :: PDRS -> PDRS -> PDRS -- | Make sure all asserted content in 'PDRS' @p@ remains -- asserted by renaming global label to @l@ before merging. amerge p@(PDRS l1 _ _ _) (PDRS l2 m2 u2 c2) = PDRS l2 (m1 `union` m2') (u1 `union` u2') (c1 `union` c2') where (PDRS _ m1 u1 c1) = pdrsAlphaConvert p [(l1,l2)] [] (PDRS _ m2' u2' c2') = pdrsAlphaConvert (PDRS l1 m2 u2 c2) [(l1,l2)] [] -- ^ in order to make sure that projected variables can -- become bound by means of assertive merge amerge pdrs1 pdrs2 = AMerge pdrs1 pdrs2 -- | Infix notation for 'pdrsAMerge' (<<+>>) :: PDRS -> PDRS -> PDRS p1 <<+>> p2 = p1 `pdrsAMerge` p2 --------------------------------------------------------------------------- -- | Applies projective merge to 'PDRS' @p1@ and 'PDRS' @p2@. --------------------------------------------------------------------------- pdrsPMerge :: PDRS -> PDRS -> PDRS pdrsPMerge p lp@(LambdaPDRS _) = PMerge p lp pdrsPMerge lp@(LambdaPDRS _) p = PMerge lp p pdrsPMerge p am@(AMerge k1 k2) | isLambdaPDRS k1 = AMerge k1 (pdrsPMerge p k2) -- p * (lk1 + k2) = lk1 + (p * k2) | isLambdaPDRS k2 = AMerge (pdrsPMerge p k1) k2 -- p * (k1 + lk2) = (p * k1) + lk2 | otherwise = pdrsPMerge p (pdrsResolveMerges am) pdrsPMerge am@(AMerge k1 k2) p | isLambdaPDRS k1 = PMerge (pdrsAMerge k1 (emptyPDRS k2)) (pdrsPMerge k2 p) -- (lk1 + k2) * p = (lk1 + ek2) * (l2 * p) | isLambdaPDRS k2 = PMerge (pdrsAMerge k2 (emptyPDRS k1)) (pdrsPMerge k1 p) -- (k1 + lk2) * p = (lk2 + ek1) * (k1 * p) | otherwise = pdrsPMerge (pdrsResolveMerges am) p pdrsPMerge p pm@(PMerge k1 k2) | isLambdaPDRS k1 = PMerge k1 (pdrsPMerge p k2) -- p * (lk1 * k2) = lk1 * (p * k2) | isLambdaPDRS k2 = PMerge (pdrsPMerge p k1) k2 -- p * (k1 * lk2) = (p * k1) * lk2 | otherwise = pdrsPMerge p (pdrsResolveMerges pm) pdrsPMerge pm@(PMerge k1 k2) p | isLambdaPDRS k1 = PMerge k1 (pdrsPMerge k2 p) -- (lk1 * k2) * p = lk1 * (k2 * p) | isLambdaPDRS k2 = PMerge k2 (pdrsPMerge k1 p) -- (k1 * lk2) * p = lk2 * (k1 * p) | otherwise = pdrsPMerge (pdrsResolveMerges pm) p pdrsPMerge p1@(PDRS{}) p2@(PDRS{}) = pdrsPurify $ pmerge p1' (pdrsDisjoin p2' p1') where p1' = pdrsPurify $ pdrsResolveMerges p1 p2' = pdrsPurify $ pdrsResolveMerges p2 pmerge :: PDRS -> PDRS -> PDRS -- | Content of 'PDRS' @p@ is added to 'PDRS' @p'@ without -- replacing pointers, resulting in the content of @p@ becoming -- projected in the resulting 'PDRS'. pmerge (PDRS l m u c) (PDRS l' m' u' c') = PDRS l' ([(l',l)] `union` m `union` m') (u `union` u') (c `union` c') pmerge pdrs1 pdrs2 = PMerge pdrs1 pdrs2 -- | Infix notation for 'pdrsPMerge' (<<*>>) :: PDRS -> PDRS -> PDRS p1 <<*>> p2 = p1 `pdrsPMerge` p2 --------------------------------------------------------------------------- -- | Combines an unresolved 'PDRS' and a 'PDRS' into a resolved 'PDRS'. --------------------------------------------------------------------------- pdrsCombine :: ((PDRSRef -> PDRS) -> PDRS) -> PDRS -> PDRS pdrsCombine up p = pdrsPurify $ pdrsResolveMerges (up (const p)) -- | Infix notation for 'pdrsCombine' (<<&>>) :: ((PDRSRef -> PDRS) -> PDRS) -> PDRS -> PDRS up <<&>> p = up `pdrsCombine` p --------------------------------------------------------------------------- -- | Resolves all unresolved merges in a 'PDRS'. --------------------------------------------------------------------------- pdrsResolveMerges :: PDRS -> PDRS pdrsResolveMerges lp@(LambdaPDRS _) = lp pdrsResolveMerges (AMerge p1 p2) = pdrsResolveMerges p1 <<+>> pdrsResolveMerges p2 pdrsResolveMerges (PMerge p1 p2) = pdrsResolveMerges p1 <<*>> pdrsResolveMerges p2 pdrsResolveMerges (PDRS l m u c) = PDRS l m u (map resolve c) where resolve :: PCon -> PCon resolve pc@(PCon _ (Rel _ _)) = pc resolve (PCon p (Neg p1)) = PCon p (Neg (pdrsResolveMerges p1)) resolve (PCon p (Imp p1 p2)) = PCon p (Imp (pdrsResolveMerges p1) (pdrsResolveMerges p2)) resolve (PCon p (Or p1 p2)) = PCon p (Or (pdrsResolveMerges p1) (pdrsResolveMerges p2)) resolve (PCon p (Prop r p1)) = PCon p (Prop r (pdrsResolveMerges p1)) resolve (PCon p (Diamond p1)) = PCon p (Diamond (pdrsResolveMerges p1)) resolve (PCon p (Box p1)) = PCon p (Box (pdrsResolveMerges p1)) --------------------------------------------------------------------------- -- | Disjoins 'PDRS' @p1@ from 'PDRS' @p2@, where: -- -- [@p1@ is disjoined from @p2@ /iff/] -- -- * All duplicate occurrences of 'PVar's and 'PDRSRef's from 'PDRS' @p2@ -- in 'PDRS' @p1@ are replaced by new variables. --------------------------------------------------------------------------- pdrsDisjoin :: PDRS -> PDRS -> PDRS pdrsDisjoin p p' = pdrsAlphaConvert p (zip ops nps) (zip ors nrs) where ops = pdrsPVars p `intersect` pdrsPVars p' nps = newPVars ops (pdrsPVars p `union` pdrsPVars p') ors = pdrsVariables p `intersect` pdrsVariables p' nrs = newPDRSRefs ors (pdrsVariables p `union` pdrsVariables p')
hbrouwer/pdrt-sandbox
src/Data/PDRS/Merge.hs
apache-2.0
7,917
0
12
2,011
2,135
1,098
1,037
93
7
{-# LANGUAGE TemplateHaskell, ScopedTypeVariables, DataKinds, TupleSections #-} {-| This module provides common definitions for equivalence unification. -} module Language.K3.TypeSystem.Simplification.EquivalenceUnification.Common ( simplifyByEquivalenceUnification , EquivocatorFunction , Equivocator(..) , TVarEquivMap , UVarEquivMap , QVarEquivMap , VarEquivMap , mconcatMultiMaps , findEquivsByIdentification , symmetricRelationshipMap , symmetricRelationshipMapToReplacementMap , cleanPreservations , closeEquivMap , filterPairsBySymmetry , prioritizeReplacementMap , equivToSubstitutions ) where import Control.Applicative import Control.Monad.Reader import Control.Monad.Writer import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Language.K3.TypeSystem.Data import Language.K3.TypeSystem.Morphisms.ReplaceVariables import Language.K3.TypeSystem.Simplification.Common import Language.K3.TypeSystem.Utils import Language.K3.Utils.Logger import Language.K3.Utils.Pretty $(loggingFunctions) -- * Simplification routine -- |A routine which, given a simplifier, will perform its substitution on a -- constraint set. simplifyByEquivalenceUnification :: Equivocator -> Simplifier simplifyByEquivalenceUnification (Equivocator name eqvrFn) cs = bracketLogM _debugI (boxToString $ ["Unifying by " ++ name ++ " on: "] %+ prettyLines cs) (\cs' -> boxToString $ ["Unified by " ++ name ++ " on: "] %+ prettyLines cs %$ indent 2 (["yielding: "] %+ prettyLines cs')) $ do (qvarEquivs,uvarEquivs) <- eqvrFn cs let uvarRepls = mconcat $ map equivToSubstitutions $ Map.toList uvarEquivs let qvarRepls = mconcat $ map equivToSubstitutions $ Map.toList qvarEquivs tellSubstitution (qvarRepls, uvarRepls) return $ logDiscoveries qvarRepls uvarRepls $ replaceVariables qvarRepls uvarRepls cs where logDiscoveries qm um = _debugI (if Map.null um && Map.null qm then "Unficiation by " ++ name ++ " made no discoveries." else boxToString $ ["Unification by " ++ name ++ " discovered:"] %$ indent 2 ( ["Unqualified variables: "] %+ prettyVarMap um %$ ["Qualified variables: "] %+ prettyVarMap qm ) ) -- * Relevant data types -- |A type alias for a routine which will compute a variable equivalence mapping -- from a constraint set. The resulting mapping should map each variable to -- the set of variables to which it is equivalent. It is acceptable for this -- mapping to be asymmetric as long as it is overly sparse; this will simply -- result in loss of some equivalences. type EquivocatorFunction = ConstraintSet -> SimplifyM VarEquivMap -- |A data type describing an equivocator function and its name. data Equivocator = Equivocator String EquivocatorFunction -- |An alias for a type variable equivalence map. type TVarEquivMap q = Map (TVar q) (Set (TVar q)) type UVarEquivMap = TVarEquivMap UnqualifiedTVar type QVarEquivMap = TVarEquivMap QualifiedTVar type VarEquivMap = (QVarEquivMap, UVarEquivMap) -- * Helpful utility functions mconcatMultiMaps :: (Ord a, Ord b) => [Map a (Set b)] -> Map a (Set b) mconcatMultiMaps = Map.unionsWith Set.union prettyVarMap :: Map (TVar q) (TVar q) -> [String] prettyVarMap m = sequenceBoxes maxWidth ", " $ map (uncurry prettyPair) $ Map.toList m where prettyPair v v' = prettyLines v %+ ["~="] %+ prettyLines v' -- |Finds an equivalence map over a single kind of type variable. This is -- accomplished by using an identification function on each variable and then -- defining the equivalence by equal identifications. findEquivsByIdentification :: forall q a. (Eq a, Ord a) => (AnyTVar -> Maybe (TVar q)) -> (TVar q -> SimplifyM a) -> [TVar q] -> SimplifyM (TVarEquivMap q) findEquivsByIdentification destr identify vars = do varsToIdsMap <- Map.fromList <$> mapM varToMapping vars let equivVarsByIdsMap = symmetricRelationshipMap varsToIdsMap symmetricRelationshipMapToReplacementMap destr equivVarsByIdsMap where varToMapping x = (x,) <$> identify x symmetricRelationshipMapToReplacementMap :: (AnyTVar -> Maybe (TVar q)) -> Map (TVar q) (Set (TVar q)) -> SimplifyM (TVarEquivMap q) symmetricRelationshipMapToReplacementMap destr origMap = do -- Calculate closed map let closedMap = closeEquivMap origMap -- Remove the prohibited replacements from the map cleanedMap <- cleanPreservations destr closedMap -- Pick a priority for the elements in the map let finalMap = prioritizeReplacementMap cleanedMap -- Finally, remove silly (identity) replacements from the map return $ Map.mapWithKey Set.delete finalMap -- |Given a mapping from an entity onto a description of its identity, produces -- a map describing for each entity to which entities it is equivalent. symmetricRelationshipMap :: (Eq a, Eq b, Ord a, Ord b) => Map a b -> Map a (Set a) symmetricRelationshipMap m = let inverseMap = mconcatMultiMaps $ map (uncurry $ flip Map.singleton . Set.singleton) $ Map.toList m in let relateMap = Map.map (fromMaybe Set.empty . (`Map.lookup` inverseMap)) m in Map.mapWithKey (\k -> Set.filter (maybe False (Set.member k) . (`Map.lookup` relateMap))) relateMap cleanPreservations :: (AnyTVar -> Maybe (TVar q)) -> Map (TVar q) (Set (TVar q)) -> SimplifyM (TVarEquivMap q) cleanPreservations destr m = do toPreserve <- Set.fromList . mapMaybe destr . Set.toList . preserveVars <$> ask return $ Map.map (Set.\\ toPreserve) m closeEquivMap :: forall a. (Eq a, Ord a) => Map a (Set a) -> Map a (Set a) closeEquivMap = leastFixedPoint closeEquivMapOnce closeEquivMapOnce :: forall a. (Eq a, Ord a) => Map a (Set a) -> Map a (Set a) closeEquivMapOnce m = Map.map extendSet m where extendSet :: Set a -> Set a extendSet as = Set.unions $ as : mapMaybe (`Map.lookup` m) (Set.toList as) -- |Given a list of pairs, reduces it to another list such that @(x,y)@ is -- in the list only if @(y,x)@ is also in the list. filterPairsBySymmetry :: (Eq a, Ord a) => [(a,a)] -> [(a,a)] filterPairsBySymmetry xs = let xS = Set.fromList xs in filter (\(x,y) -> (y,x) `Set.member` xS) xs -- |A function to select groups of type variable substitutions to use. The -- input mapping describes equivalences; the output mapping describes which -- variables will actually do the replacement (to prevent replacing each -- variable by the other). prioritizeReplacementMap :: TVarEquivMap q -> TVarEquivMap q prioritizeReplacementMap replMap = fst $ foldr selectGroups (Map.empty, Set.empty) $ Map.toList replMap where -- |A function which selects groups of type variable substitutions to -- use. The output type is a pair between the mapping of equivalences -- which is intended to be used (initially empty) and the set of -- variables which, already being part of an equivalence in the map, -- should not be included as a key. By the end, the key-value pairs -- should be disjoint from one another when viewed as simple sets of -- variables. selectGroups :: (TVar q, Set (TVar q)) -> (TVarEquivMap q, Set (TVar q)) -> (TVarEquivMap q, Set (TVar q)) selectGroups (k,v) (m, used) = if k `Set.member` used then (m, used) else (Map.insert k (v Set.\\ used) m, used `Set.union` v) equivToSubstitutions :: (TVar q, Set (TVar q)) -> Map (TVar q) (TVar q) equivToSubstitutions (a, as) = Map.fromList $ map (,a) $ Set.toList as
DaMSL/K3
src/Language/K3/TypeSystem/Simplification/EquivalenceUnification/Common.hs
apache-2.0
7,887
0
18
1,745
1,906
1,013
893
130
2
{-# LANGUAGE BangPatterns #-} import Control.Exception import Control.Monad import Control.Monad.ST import Gauge.Main import Data.Int import Data.Word import qualified Data.Vector.Unboxed as U import qualified System.Random as R import System.Random.MWC import System.Random.MWC.Distributions import System.Random.MWC.CondensedTable import qualified System.Random.Mersenne as M makeTableUniform :: Int -> CondensedTable U.Vector Int makeTableUniform n = tableFromProbabilities $ U.zip (U.enumFromN 0 n) (U.replicate n (1 / fromIntegral n)) {-# INLINE makeTableUniform #-} main = do mwc <- create mtg <- M.newMTGen . Just =<< uniform mwc defaultMain [ bgroup "mwc" -- One letter group names are used so they will fit on the plot. -- -- U - uniform -- R - uniformR -- D - distribution [ bgroup "U" [ bench "Double" $ nfIO (uniform mwc :: IO Double) , bench "Int" $ nfIO (uniform mwc :: IO Int) , bench "Int8" $ nfIO (uniform mwc :: IO Int8) , bench "Int16" $ nfIO (uniform mwc :: IO Int16) , bench "Int32" $ nfIO (uniform mwc :: IO Int32) , bench "Int64" $ nfIO (uniform mwc :: IO Int64) , bench "Word" $ nfIO (uniform mwc :: IO Word) , bench "Word8" $ nfIO (uniform mwc :: IO Word8) , bench "Word16" $ nfIO (uniform mwc :: IO Word16) , bench "Word32" $ nfIO (uniform mwc :: IO Word32) , bench "Word64" $ nfIO (uniform mwc :: IO Word64) ] , bgroup "R" -- I'm not entirely convinced that this is right way to test -- uniformR. /A.Khudyakov/ [ bench "Double" $ nfIO (uniformR (-3.21,26) mwc :: IO Double) , bench "Int" $ nfIO (uniformR (-12,679) mwc :: IO Int) , bench "Int8" $ nfIO (uniformR (-12,4) mwc :: IO Int8) , bench "Int16" $ nfIO (uniformR (-12,679) mwc :: IO Int16) , bench "Int32" $ nfIO (uniformR (-12,679) mwc :: IO Int32) , bench "Int64" $ nfIO (uniformR (-12,679) mwc :: IO Int64) , bench "Word" $ nfIO (uniformR (34,633) mwc :: IO Word) , bench "Word8" $ nfIO (uniformR (34,63) mwc :: IO Word8) , bench "Word16" $ nfIO (uniformR (34,633) mwc :: IO Word16) , bench "Word32" $ nfIO (uniformR (34,633) mwc :: IO Word32) , bench "Word64" $ nfIO (uniformR (34,633) mwc :: IO Word64) ] , bgroup "D" [ bench "standard" $ nfIO (standard mwc :: IO Double) , bench "normal" $ nfIO (normal 1 3 mwc :: IO Double) -- Regression tests for #16. These functions should take 10x -- longer to execute. -- -- N.B. Bang patterns are necessary to trigger the bug with -- GHC 7.6 , bench "standard/N" $ nfIO $ replicateM_ 10 $ do !_ <- standard mwc :: IO Double return () , bench "normal/N" $ nfIO $ replicateM_ 10 $ do !_ <- normal 1 3 mwc :: IO Double return () , bench "exponential" $ nfIO (exponential 3 mwc :: IO Double) , bench "gamma,a<1" $ nfIO (gamma 0.5 1 mwc :: IO Double) , bench "gamma,a>1" $ nfIO (gamma 2 1 mwc :: IO Double) , bench "chiSquare" $ nfIO (chiSquare 4 mwc :: IO Double) ] , bgroup "CT/gen" $ concat [ [ bench ("uniform "++show i) $ nfIO (genFromTable (makeTableUniform i) mwc :: IO Int) | i <- [2..10] ] , [ bench ("poisson " ++ show l) $ nfIO (genFromTable (tablePoisson l) mwc :: IO Int) | l <- [0.01, 0.2, 0.8, 1.3, 2.4, 8, 12, 100, 1000] ] , [ bench ("binomial " ++ show p ++ " " ++ show n) $ nfIO (genFromTable (tableBinomial n p) mwc :: IO Int) | (n,p) <- [ (4, 0.5), (10,0.1), (10,0.6), (10, 0.8), (100,0.4)] ] ] , bgroup "CT/table" $ concat [ [ bench ("uniform " ++ show i) $ whnf makeTableUniform i | i <- [2..30] ] , [ bench ("poisson " ++ show l) $ whnf tablePoisson l | l <- [0.01, 0.2, 0.8, 1.3, 2.4, 8, 12, 100, 1000] ] , [ bench ("binomial " ++ show p ++ " " ++ show n) $ whnf (tableBinomial n) p | (n,p) <- [ (4, 0.5), (10,0.1), (10,0.6), (10, 0.8), (100,0.4)] ] ] ] , bgroup "random" [ bench "Double" $ nfIO (R.randomIO >>= evaluate :: IO Double) , bench "Int" $ nfIO (R.randomIO >>= evaluate :: IO Int) ] , bgroup "mersenne" [ bench "Double" $ nfIO (M.random mtg :: IO Double) , bench "Int" $ nfIO (M.random mtg :: IO Int) ] ]
Shimuuar/mwc-random
bench/Benchmark.hs
bsd-2-clause
4,765
0
21
1,627
1,757
912
845
81
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} -- | Authentication backend using HDBC module Snap.Snaplet.Auth.Backends.Hdbc where import Control.Concurrent.MVar import Control.Monad.State import Data.Convertible.Base import qualified Data.HashMap.Strict as HM import Data.Lens.Lazy import Data.List import Data.Map (Map) import qualified Data.Map as DM import Data.Maybe import Data.Text (Text) import Database.HDBC import Snap.Snaplet import Snap.Snaplet.Auth import Snap.Snaplet.Hdbc.Types import Snap.Snaplet.Session import Snap.Snaplet.Session.Common import Web.ClientSession -- | Initialises this HDBC snaplet. It automatically configures a resource -- pool with commonly acceptable default settings. Use `initHdbcAuthManager'` -- to initialise with a custom resource pool. initHdbcAuthManager :: (ConnSrc s, IConnection c) => AuthSettings -- ^ Auth settings -> Lens b (Snaplet SessionManager) -- ^ Lens to the session manager -> s c -- ^ Raw HDBC connection -> AuthTable -- ^ Authentication table configuration -> Queries -- ^ Queries to be used for authentication -> SnapletInit b (AuthManager b) initHdbcAuthManager s l conn tbl qs = makeSnaplet "HdbcAuthManager" "A snaplet providing user authentication using an HDBC backend" Nothing $ liftIO $ do mv <- newEmptyMVar key <- getKey (asSiteKey s) rng <- mkRNG return AuthManager { backend = HdbcAuthManager (HdbcSnaplet conn mv) tbl qs , session = l , activeUser = Nothing , minPasswdLen = asMinPasswdLen s , rememberCookieName = asRememberCookieName s , rememberPeriod = asRememberPeriod s , siteKey = key , lockout = asLockout s , randomNumberGenerator = rng } -- | Authmanager state containing the resource pool and the table/query -- configuration. data HdbcAuthManager = forall c s. (IConnection c, ConnSrc s) => HdbcAuthManager { connSt :: HdbcSnaplet c s , table :: AuthTable , qries :: Queries } -- | Datatype containing the names of the columns for the authentication table. data AuthTable = AuthTable { tblName :: String , colId :: String , colLogin :: String , colPassword :: String , colActivatedAt :: String , colSuspendedAt :: String , colRememberToken :: String , colLoginCount :: String , colFailedLoginCount :: String , colLockedOutUntil :: String , colCurrentLoginAt :: String , colLastLoginAt :: String , colCurrentLoginIp :: String , colLastLoginIp :: String , colCreatedAt :: String , colUpdatedAt :: String , colRoles :: String , colMeta :: String } -- | Default authentication table layout defAuthTable :: AuthTable defAuthTable = AuthTable { tblName = "users" , colId = "uid" , colLogin = "email" , colPassword = "password" , colActivatedAt = "activated_at" , colSuspendedAt = "suspended_at" , colRememberToken = "remember_token" , colLoginCount = "login_count" , colFailedLoginCount = "failed_login_count" , colLockedOutUntil = "locked_out_until" , colCurrentLoginAt = "current_login_at" , colLastLoginAt = "last_login_at" , colCurrentLoginIp = "current_login_ip" , colLastLoginIp = "last_login_ip" , colCreatedAt = "created_at" , colUpdatedAt = "updated_at" , colRoles = "roles" , colMeta = "meta" } -- | List of deconstructors so it's easier to extract column names form an -- 'AuthTable'. colLst :: [AuthTable -> String] colLst = [ colLogin , colPassword , colActivatedAt , colSuspendedAt , colRememberToken , colLoginCount , colFailedLoginCount , colLockedOutUntil , colCurrentLoginAt , colLastLoginAt , colCurrentLoginIp , colLastLoginIp , colCreatedAt , colUpdatedAt , colRoles , colMeta ] data LookupQuery = ByUserId | ByLogin | ByRememberToken data Queries = Queries { selectQuery :: AuthTable -> LookupQuery -> [SqlValue] -> (String, [SqlValue]) , saveQuery :: AuthTable -> AuthUser -> (String, String, [SqlValue]) , deleteQuery :: AuthTable -> AuthUser -> (String, [SqlValue]) } defQueries :: Queries defQueries = Queries { selectQuery = defSelectQuery , saveQuery = defSaveQuery , deleteQuery = defDeleteQuery } defSelectQuery :: AuthTable -> LookupQuery -> [SqlValue] -> (String, [SqlValue]) defSelectQuery tbl luq sqlVals = case luq of ByUserId -> (mkSelect colId, sqlVals) ByLogin -> (mkSelect colLogin, sqlVals) ByRememberToken -> (mkSelect colRememberToken, sqlVals) where mkSelect whr = "SELECT * FROM " ++ tblName tbl ++ " WHERE " ++ whr tbl ++ " = ? " defSaveQuery :: AuthTable -> AuthUser -> (String, String, [SqlValue]) defSaveQuery tbl au = (mkQry uid, mkIdQry, mkVals uid) where uid = userId au qval f = f tbl ++ " = ?" mkQry Nothing = "INSERT INTO " ++ tblName tbl ++ " (" ++ intercalate "," (map (\f -> f tbl) colLst) ++ ") VALUES (" ++ intercalate "," (map (const "?") colLst) ++ ")" mkQry (Just _) = "UPDATE " ++ tblName tbl ++ " SET " ++ intercalate "," (map qval colLst) ++ " WHERE " ++ colId tbl ++ " = ?" mkIdQry = "SELECT " ++ colId tbl ++ " FROM " ++ tblName tbl ++ " WHERE " ++ intercalate " AND " (map qval [colLogin, colPassword]) mkVals Nothing = mkVals' mkVals (Just i) = mkVals' ++ [toSql i] mkVals' = [ toSql $ userLogin au , toSql $ userPassword au , toSql $ userActivatedAt au , toSql $ userSuspendedAt au , toSql $ userRememberToken au , toSql $ userLoginCount au , toSql $ userFailedLoginCount au , toSql $ userLockedOutUntil au , toSql $ userCurrentLoginAt au , toSql $ userLastLoginAt au , toSql $ userCurrentLoginIp au , toSql $ userLastLoginIp au , toSql $ userCreatedAt au , toSql $ userUpdatedAt au , SqlNull -- userRoles au TODO: Implement when ACL system is live , SqlNull -- userMeta au TODO: What should we store here? ] defDeleteQuery :: AuthTable -> AuthUser -> (String, [SqlValue]) defDeleteQuery tbl ausr = case userId ausr of Nothing -> error "Cannot delete user without unique ID" Just uid -> ( "DELETE FROM " ++ tblName tbl ++ " WHERE " ++ colId tbl ++ " = ? " , [toSql uid]) instance Convertible Password SqlValue where safeConvert (ClearText bs) = Right $ toSql bs safeConvert (Encrypted bs) = Right $ toSql bs instance Convertible UserId SqlValue where safeConvert (UserId uid) = Right $ toSql uid instance IAuthBackend HdbcAuthManager where destroy (HdbcAuthManager st tbl qs) au = let (qry, vals) = deleteQuery qs tbl au in withConn st $ prepExec qry vals save (HdbcAuthManager st tbl qs) au = do let (qry, idQry, vals) = saveQuery qs tbl au withConn st $ prepExec qry vals if isJust $ userId au then return au else do rw <- withConn st $ \conn -> withTransaction conn $ \conn' -> do stmt' <- prepare conn' idQry _ <- execute stmt' [ toSql $ userLogin au , toSql $ userPassword au] fetchRow stmt' nid <- case rw of Nothing -> fail $ "Failed to fetch the newly inserted row. " ++ "It might not have been inserted at all." Just [] -> fail "Something went wrong" Just (x:_) -> return (fromSql x :: Text) return $ au { userId = Just (UserId nid) } lookupByUserId mgr@(HdbcAuthManager _ tbl qs) uid = authQuery mgr $ selectQuery qs tbl ByUserId [toSql uid] lookupByLogin mgr@(HdbcAuthManager _ tbl qs) lgn = authQuery mgr $ selectQuery qs tbl ByLogin [toSql lgn] lookupByRememberToken mgr@(HdbcAuthManager _ tbl qs) rmb = authQuery mgr $ selectQuery qs tbl ByRememberToken [toSql rmb] prepExec :: IConnection conn => String -> [SqlValue] -> conn -> IO () prepExec qry vals conn = withTransaction conn $ \conn' -> do stmt <- prepare conn' qry _ <- execute stmt vals return () authQuery :: HdbcAuthManager -> (String, [SqlValue]) -> IO (Maybe AuthUser) authQuery (HdbcAuthManager st tbl _) (qry, vals) = do res <- withConn st $ \conn -> do stmt <- prepare conn qry _ <- execute stmt vals fetchRowMap stmt return $ (return . mkUser tbl) =<< res mkUser :: AuthTable -> Map String SqlValue -> AuthUser mkUser tbl mp = let colLU col' = mp DM.! col' tbl rdSql con col' = case colLU col' of SqlNull -> Nothing x -> Just . con $ fromSql x rdInt col = case colLU col of SqlNull -> 0 x -> fromSql x in AuthUser { userId = rdSql UserId colId , userLogin = fromSql $ colLU colLogin , userPassword = rdSql Encrypted colPassword , userActivatedAt = rdSql id colActivatedAt , userSuspendedAt = rdSql id colSuspendedAt , userRememberToken = rdSql id colRememberToken , userLoginCount = rdInt colLoginCount , userFailedLoginCount = rdInt colFailedLoginCount , userLockedOutUntil = rdSql id colLockedOutUntil , userCurrentLoginAt = rdSql id colCurrentLoginAt , userLastLoginAt = rdSql id colLastLoginAt , userCurrentLoginIp = rdSql id colCurrentLoginIp , userLastLoginIp = rdSql id colLastLoginIp , userCreatedAt = rdSql id colCreatedAt , userUpdatedAt = rdSql id colUpdatedAt , userRoles = [] -- :: [Role] TODO , userMeta = HM.empty } -- :: HashMap Text Value TODO
soenkehahn/snaplet-hdbc
src/Snap/Snaplet/Auth/Backends/Hdbc.hs
bsd-3-clause
10,469
0
22
3,247
2,555
1,373
1,182
241
3
module Bead.Domain.Entity.Assessment where import Bead.Domain.Shared.Evaluation -- | Assesment for a student, without any submission -- just an evaluation for it. data Assessment = Assessment { description :: String , evaluationCfg :: EvConfig } deriving (Eq, Show) assessment f (Assessment desc cfg) = f desc cfg withAssessment a f = assessment f a
pgj/bead
src/Bead/Domain/Entity/Assessment.hs
bsd-3-clause
365
0
8
67
87
50
37
8
1
{- # Functor, Applicative, Monad Functor: (a -> b) Applicative: f (a -> b) Monad: (a -> m b) -} ($) :: (a -> b) -> a -> b (<$>) :: Functor f => (a -> b) -> f a -> f b (<*>) :: Applicative f => f (a -> b) -> f a ->f b (>>=) :: Monad m => (a -> m b) -> m a -> m b class Functor (f :: * -> *) where fmap :: (a -> b) -> f a -> f b class Functor f => Applicative (f :: * -> *) where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b -- Applicative & Lift lift2 f x1s x2s = pure f <*> x1s <*> x2s class Applicative m => Monad (m :: * -> *) where (>>=) :: m a -> (a -> m b) -> m b return :: a -> m a -- what func takes as argument is capured in the do-statement {- # State -} data ST s a = S (s -> (a, s)) instance Monad (ST s) where return x = S $ \s -> (x,s) st >>= f = S $ \s -> let(x,s') = apply st s in apply (f x) s' apply :: ST s a -> s -> (a, s) apply (S f) s = f s {- # Monad Transformer -}
idf/haskell-examples
notes/monad.hs
bsd-3-clause
940
0
12
288
503
261
242
-1
-1
{-# OPTIONS_GHC -fno-warn-orphans -fsimpl-tick-factor=500 #-} module Micro.PkgBinary (serialise, deserialise) where import Micro.Types import Data.Binary as Binary import Data.ByteString.Lazy as BS serialise :: Tree -> BS.ByteString serialise = Binary.encode deserialise :: BS.ByteString -> Tree deserialise = Binary.decode instance Binary Tree
arianvp/binary-serialise-cbor
bench/Micro/PkgBinary.hs
bsd-3-clause
350
0
6
44
78
47
31
10
1
----------------------------------------------------------------------------- -- | -- Module : Control.Monad.ST -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (requires universal quantification for runST) -- -- This library provides support for /strict/ state threads, as -- described in the PLDI \'94 paper by John Launchbury and Simon Peyton -- Jones /Lazy Functional State Threads/. -- ----------------------------------------------------------------------------- module Control.Monad.ST ( -- * The 'ST' Monad ST, -- abstract, instance of Functor, Monad, Typeable. runST, -- :: (forall s. ST s a) -> a fixST, -- :: (a -> ST s a) -> ST s a -- * Converting 'ST' to 'IO' RealWorld, -- abstract stToIO, -- :: ST RealWorld a -> IO a -- * Unsafe operations unsafeInterleaveST, -- :: ST s a -> ST s a unsafeIOToST, -- :: IO a -> ST s a unsafeSTToIO -- :: ST s a -> IO a ) where import Prelude import Control.Monad.Fix #include "Typeable.h" #ifdef __HUGS__ import Data.Typeable import Hugs.ST import qualified Hugs.LazyST as LazyST INSTANCE_TYPEABLE2(ST,sTTc,"ST") INSTANCE_TYPEABLE0(RealWorld,realWorldTc,"RealWorld") fixST :: (a -> ST s a) -> ST s a fixST f = LazyST.lazyToStrictST (LazyST.fixST (LazyST.strictToLazyST . f)) unsafeInterleaveST :: ST s a -> ST s a unsafeInterleaveST = LazyST.lazyToStrictST . LazyST.unsafeInterleaveST . LazyST.strictToLazyST #endif #ifdef __GLASGOW_HASKELL__ import GHC.ST ( ST, runST, fixST, unsafeInterleaveST ) import GHC.Base ( RealWorld ) import GHC.IOBase ( stToIO, unsafeIOToST, unsafeSTToIO ) #endif instance MonadFix (ST s) where mfix = fixST
FranklinChen/hugs98-plus-Sep2006
packages/base/Control/Monad/ST.hs
bsd-3-clause
1,817
22
10
321
301
183
118
14
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module Network.Wai.Handler.Warp.ResponseHeader (composeHeader) where import qualified Data.ByteString as S import Data.ByteString.Internal (create) import qualified Data.CaseInsensitive as CI import Foreign.Ptr import GHC.Storable import qualified Network.HTTP.Types as H import Network.Wai.Handler.Warp.Buffer (copy) import Network.Wai.Handler.Warp.Imports ---------------------------------------------------------------- composeHeader :: H.HttpVersion -> H.Status -> H.ResponseHeaders -> IO ByteString composeHeader !httpversion !status !responseHeaders = create len $ \ptr -> do ptr1 <- copyStatus ptr httpversion status ptr2 <- copyHeaders ptr1 responseHeaders void $ copyCRLF ptr2 where !len = 17 + slen + foldl' fieldLength 0 responseHeaders fieldLength !l (!k,!v) = l + S.length (CI.original k) + S.length v + 4 !slen = S.length $ H.statusMessage status httpVer11 :: ByteString httpVer11 = "HTTP/1.1 " httpVer10 :: ByteString httpVer10 = "HTTP/1.0 " {-# INLINE copyStatus #-} copyStatus :: Ptr Word8 -> H.HttpVersion -> H.Status -> IO (Ptr Word8) copyStatus !ptr !httpversion !status = do ptr1 <- copy ptr httpVer writeWord8OffPtr ptr1 0 (zero + fromIntegral r2) writeWord8OffPtr ptr1 1 (zero + fromIntegral r1) writeWord8OffPtr ptr1 2 (zero + fromIntegral r0) writeWord8OffPtr ptr1 3 spc ptr2 <- copy (ptr1 `plusPtr` 4) (H.statusMessage status) copyCRLF ptr2 where httpVer | httpversion == H.HttpVersion 1 1 = httpVer11 | otherwise = httpVer10 (q0,r0) = H.statusCode status `divMod` 10 (q1,r1) = q0 `divMod` 10 r2 = q1 `mod` 10 {-# INLINE copyHeaders #-} copyHeaders :: Ptr Word8 -> [H.Header] -> IO (Ptr Word8) copyHeaders !ptr [] = return ptr copyHeaders !ptr (h:hs) = do ptr1 <- copyHeader ptr h copyHeaders ptr1 hs {-# INLINE copyHeader #-} copyHeader :: Ptr Word8 -> H.Header -> IO (Ptr Word8) copyHeader !ptr (k,v) = do ptr1 <- copy ptr (CI.original k) writeWord8OffPtr ptr1 0 colon writeWord8OffPtr ptr1 1 spc ptr2 <- copy (ptr1 `plusPtr` 2) v copyCRLF ptr2 {-# INLINE copyCRLF #-} copyCRLF :: Ptr Word8 -> IO (Ptr Word8) copyCRLF !ptr = do writeWord8OffPtr ptr 0 cr writeWord8OffPtr ptr 1 lf return $! ptr `plusPtr` 2 zero :: Word8 zero = 48 spc :: Word8 spc = 32 colon :: Word8 colon = 58 cr :: Word8 cr = 13 lf :: Word8 lf = 10
creichert/wai
warp/Network/Wai/Handler/Warp/ResponseHeader.hs
mit
2,447
0
13
483
846
429
417
69
1
-- Test for trac #314 {-| /* This uses up some lines The following pragmas should not be parsed */ # 23 #pragma -} module ShouldFail where type_error = "Type error on line 25":"Type error on line 25"
sdiehl/ghc
testsuite/tests/parser/should_fail/readFail048.hs
bsd-3-clause
229
0
5
67
15
10
5
2
1
module Main where import LI11718 import qualified Tarefa4_2017li1g186 as T4 import System.Environment import Text.Read main = do args <- getArgs case args of ["atualiza"] -> do str <- getContents let params = readMaybe str case params of Nothing -> error "parâmetros inválidos" Just (tempo,jogo,jogador,acao) -> print $ T4.atualiza tempo jogo jogador acao ["testes"] -> print $ take 100 $ T4.testesT4 otherwise -> error "RunT4 argumentos inválidos"
hpacheco/HAAP
examples/plab/svn/2017li1g186/src/RunT4.hs
mit
554
0
17
168
153
79
74
16
4
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving, DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ViewPatterns,NoMonomorphismRestriction,TypeSynonymInstances #-} module Fixed.Eff where import Control.Monad import Data.Typeable import Data.OpenUnion1 import Fixed.FreeMonad -- Fixed version of the extensible effects -- framework at http://okmij.org/ftp/Haskell/extensible/Eff.hs type Eff r a = FreeMonad (Union r) a instance Functor f => Functor (FreeMonad f) where fmap = liftM -- send a request and wait for a reply send :: Union r a -> Eff r a send u = fromView $ Impure (fmap (fromView . Pure) u) -- ------------------------------------------------------------------------ -- The initial case, no effects data Void -- no constructors -- The type of run ensures that all effects must be handled: -- only pure computations may be run. run :: Eff Void w -> w run (toView -> Pure a) = a -- A convenient pattern: given a request (open union), either -- handle it or relay it. handle_relay :: Typeable1 t => Union (t :> r) v -> (v -> Eff r a) -> (t v -> Eff r a) -> Eff r a handle_relay u loop h = case decomp u of Right x -> h x Left u -> send u >>= loop -- Add something like Control.Exception.catches? It could be useful -- for control with cut. interpose :: (Typeable1 t, Functor t, Member t r) => Union r v -> (v -> Eff r a) -> (t v -> Eff r a) -> Eff r a interpose u loop h = case prj u of Just x -> h x _ -> send u >>= loop --- ------------------------------------------------------------------------ -- State, strict data State s w = State (s->s) (s -> w) deriving (Typeable, Functor) -- The signature is inferred put :: (Typeable s, Member (State s) r) => s -> Eff r () put s = send (inj (State (const s) (const ()))) -- The signature is inferred get :: (Typeable s, Member (State s) r) => Eff r s get = send (inj (State id id)) runState :: Typeable s => Eff (State s :> r) w -> s -> Eff r (w,s) runState m s = loop s m where loop s (toView -> Pure x) = return (x,s) loop s (toView -> Impure u) = handle_relay u (loop s) $ \(State t k) -> let s' = t s in s' `seq` loop s' (k s') -- ------------------------------------------------------------------------ -- Non-determinism (choice) -- choose lst non-deterministically chooses one value from the lst -- choose [] thus corresponds to failure data Choose v = forall a. Choose [a] (a -> v) deriving (Typeable) instance Functor Choose where fmap f (Choose lst k) = Choose lst (f . k) choose :: Member Choose r => [a] -> Eff r a choose lst = send (inj $ Choose lst id) -- MonadPlus-like operators are expressible via choose mzero' :: Member Choose r => Eff r a mzero' = choose [] mplus' m1 m2 = choose [m1,m2] >>= id -- The interpreter makeChoice :: forall a r. Eff (Choose :> r) a -> Eff r [a] makeChoice = loop where loop (toView -> Pure x) = return [x] loop (toView -> Impure u) = handle_relay u loop (\(Choose lst k) -> handle lst k) -- Need the signature since local bindings aren't polymorphic any more handle :: [t] -> (t -> Eff (Choose :> r) a) -> Eff r [a] handle [] _ = return [] handle [x] k = loop (k x) handle lst k = fmap concat $ mapM (loop . k) lst -- ------------------------------------------------------------------------ -- Soft-cut: non-deterministic if-then-else, aka Prolog's *-> -- Declaratively, -- ifte t th el = (t >>= th) `mplus` ((not t) >> el) -- However, t is evaluated only once. In other words, ifte t th el -- is equivalent to t >>= th if t has at least one solution. -- If t fails, ifte t th el is the same as el. ifte :: forall r a b. Member Choose r => Eff r a -> (a -> Eff r b) -> Eff r b -> Eff r b ifte t th el = loop [] t where loop [] (toView -> Pure x) = th x -- add all other latent choices of t to th x -- this is like reflection of t loop jq (toView -> Pure x) = choose ((th x) : map (\t -> t >>= th) jq) >>= id loop jq (toView -> Impure u) = interpose u (loop jq) (\(Choose lst k) -> handle jq lst k) -- Need the signature since local bindings aren't polymorphic any more handle :: [Eff r a] -> [t] -> (t -> Eff r a) -> Eff r b handle [] [] _ = el -- no more choices left handle (j:jq) [] _ = loop jq j handle jq [x] k = loop jq (k x) handle jq (x:rest) k = loop (map k rest ++ jq) (k x) -- DFS guard' :: Member Choose r => Bool -> Eff r () guard' True = return () guard' False = mzero' -- ------------------------------------------------------------------------ -- Co-routines -- The interface is intentionally chosen to be the same as in transf.hs -- The yield request: reporting the value of type e and suspending -- the coroutine data Yield inn out res = Yield out (inn -> res) deriving (Typeable, Functor) -- The signature is inferred yield :: (Typeable inn, Typeable out, Member (Yield inn out) r) => out -> Eff r inn yield x = send (inj $ Yield x id) -- Status of a thread: done or reporting the value of the type a -- (For simplicity, a co-routine reports a value but accepts unit) data Y inn out r a = Done a | Y out (inn -> Eff (Yield inn out :> r) a) -- Launch a thread and report its status runC :: (Typeable inn, Typeable out) => Eff (Yield inn out :> r) a -> Eff r (Y inn out r a) runC m = loop m where loop (toView -> Pure x) = return (Done x) loop (toView -> Impure u) = case decomp u of Right (Yield x c) -> return (Y x c) Left u -> send u >>= loop
atzeus/reflectionwithoutremorse
Fixed/Eff.hs
mit
5,647
0
14
1,270
1,911
989
922
-1
-1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# OPTIONS_GHC -fno-warn-deprecations #-} module Network.Wai.Handler.Warp.Request ( recvRequest , headerLines , pauseTimeoutKey , getFileInfoKey , NoKeepAliveRequest (..) ) where import qualified Control.Concurrent as Conc (yield) import Control.Exception (throwIO, Exception) import Data.Array ((!)) import qualified Data.ByteString as S import qualified Data.ByteString.Unsafe as SU import qualified Data.CaseInsensitive as CI import qualified Data.IORef as I import Data.Typeable (Typeable) import qualified Data.Vault.Lazy as Vault import qualified Network.HTTP.Types as H import Network.Socket (SockAddr) import Network.Wai import qualified Network.Wai.Handler.Warp.Timeout as Timeout import Network.Wai.Handler.Warp.Types import Network.Wai.Internal import Prelude hiding (lines) import System.IO.Unsafe (unsafePerformIO) import Network.Wai.Handler.Warp.Conduit import Network.Wai.Handler.Warp.FileInfoCache import Network.Wai.Handler.Warp.HashMap (hashByteString) import Network.Wai.Handler.Warp.Header import Network.Wai.Handler.Warp.Imports hiding (readInt, lines) import Network.Wai.Handler.Warp.ReadInt import Network.Wai.Handler.Warp.RequestHeader import Network.Wai.Handler.Warp.Settings (Settings, settingsNoParsePath) ---------------------------------------------------------------- -- FIXME come up with good values here maxTotalHeaderLength :: Int maxTotalHeaderLength = 50 * 1024 ---------------------------------------------------------------- -- | Receiving a HTTP request from 'Connection' and parsing its header -- to create 'Request'. recvRequest :: Bool -- ^ first request on this connection? -> Settings -> Connection -> InternalInfo1 -> SockAddr -- ^ Peer's address. -> Source -- ^ Where HTTP request comes from. -> IO (Request ,Maybe (I.IORef Int) ,IndexedHeader ,IO ByteString ,InternalInfo) -- ^ -- 'Request' passed to 'Application', -- how many bytes remain to be consumed, if known -- 'IndexedHeader' of HTTP request for internal use, -- Body producing action used for flushing the request body recvRequest firstRequest settings conn ii1 addr src = do hdrlines <- headerLines firstRequest src (method, unparsedPath, path, query, httpversion, hdr) <- parseHeaderLines hdrlines let idxhdr = indexRequestHeader hdr expect = idxhdr ! fromEnum ReqExpect cl = idxhdr ! fromEnum ReqContentLength te = idxhdr ! fromEnum ReqTransferEncoding handle100Continue = handleExpect conn httpversion expect rawPath = if settingsNoParsePath settings then unparsedPath else path h = hashByteString rawPath ii = toInternalInfo ii1 h th = threadHandle ii vaultValue = Vault.insert pauseTimeoutKey (Timeout.pause th) $ Vault.insert getFileInfoKey (getFileInfo ii) Vault.empty (rbody, remainingRef, bodyLength) <- bodyAndSource src cl te -- body producing function which will produce '100-continue', if needed rbody' <- timeoutBody remainingRef th rbody handle100Continue -- body producing function which will never produce 100-continue rbodyFlush <- timeoutBody remainingRef th rbody (return ()) let req = Request { requestMethod = method , httpVersion = httpversion , pathInfo = H.decodePathSegments path , rawPathInfo = rawPath , rawQueryString = query , queryString = H.parseQuery query , requestHeaders = hdr , isSecure = False , remoteHost = addr , requestBody = rbody' , vault = vaultValue , requestBodyLength = bodyLength , requestHeaderHost = idxhdr ! fromEnum ReqHost , requestHeaderRange = idxhdr ! fromEnum ReqRange , requestHeaderReferer = idxhdr ! fromEnum ReqReferer , requestHeaderUserAgent = idxhdr ! fromEnum ReqUserAgent } return (req, remainingRef, idxhdr, rbodyFlush, ii) ---------------------------------------------------------------- headerLines :: Bool -> Source -> IO [ByteString] headerLines firstRequest src = do bs <- readSource src if S.null bs -- When we're working on a keep-alive connection and trying to -- get the second or later request, we don't want to treat the -- lack of data as a real exception. See the http1 function in -- the Run module for more details. then if firstRequest then throwIO ConnectionClosedByPeer else throwIO NoKeepAliveRequest else push src (THStatus 0 id id) bs data NoKeepAliveRequest = NoKeepAliveRequest deriving (Show, Typeable) instance Exception NoKeepAliveRequest ---------------------------------------------------------------- handleExpect :: Connection -> H.HttpVersion -> Maybe HeaderValue -> IO () handleExpect conn ver (Just "100-continue") = do connSendAll conn continue Conc.yield where continue | ver == H.http11 = "HTTP/1.1 100 Continue\r\n\r\n" | otherwise = "HTTP/1.0 100 Continue\r\n\r\n" handleExpect _ _ _ = return () ---------------------------------------------------------------- bodyAndSource :: Source -> Maybe HeaderValue -- ^ content length -> Maybe HeaderValue -- ^ transfer-encoding -> IO (IO ByteString ,Maybe (I.IORef Int) ,RequestBodyLength ) bodyAndSource src cl te | chunked = do csrc <- mkCSource src return (readCSource csrc, Nothing, ChunkedBody) | otherwise = do isrc@(ISource _ remaining) <- mkISource src len return (readISource isrc, Just remaining, bodyLen) where len = toLength cl bodyLen = KnownLength $ fromIntegral len chunked = isChunked te toLength :: Maybe HeaderValue -> Int toLength Nothing = 0 toLength (Just bs) = readInt bs isChunked :: Maybe HeaderValue -> Bool isChunked (Just bs) = CI.foldCase bs == "chunked" isChunked _ = False ---------------------------------------------------------------- timeoutBody :: Maybe (I.IORef Int) -- ^ remaining -> Timeout.Handle -> IO ByteString -> IO () -> IO (IO ByteString) timeoutBody remainingRef timeoutHandle rbody handle100Continue = do isFirstRef <- I.newIORef True let checkEmpty = case remainingRef of Nothing -> return . S.null Just ref -> \bs -> if S.null bs then return True else do x <- I.readIORef ref return $! x <= 0 return $ do isFirst <- I.readIORef isFirstRef when isFirst $ do -- Only check if we need to produce the 100 Continue status -- when asking for the first chunk of the body handle100Continue -- Timeout handling was paused after receiving the full request -- headers. Now we need to resume it to avoid a slowloris -- attack during request body sending. Timeout.resume timeoutHandle I.writeIORef isFirstRef False bs <- rbody -- As soon as we finish receiving the request body, whether -- because the application is not interested in more bytes, or -- because there is no more data available, pause the timeout -- handler again. isEmpty <- checkEmpty bs when isEmpty (Timeout.pause timeoutHandle) return bs ---------------------------------------------------------------- type BSEndo = ByteString -> ByteString type BSEndoList = [ByteString] -> [ByteString] data THStatus = THStatus {-# UNPACK #-} !Int -- running total byte count BSEndoList -- previously parsed lines BSEndo -- bytestrings to be prepended ---------------------------------------------------------------- {- FIXME close :: Sink ByteString IO a close = throwIO IncompleteHeaders -} push :: Source -> THStatus -> ByteString -> IO [ByteString] push src (THStatus len lines prepend) bs' -- Too many bytes | len > maxTotalHeaderLength = throwIO OverLargeHeader | otherwise = push' mnl where bs = prepend bs' bsLen = S.length bs mnl = do nl <- S.elemIndex 10 bs -- check if there are two more bytes in the bs -- if so, see if the second of those is a horizontal space if bsLen > nl + 1 then let c = S.index bs (nl + 1) b = case nl of 0 -> True 1 -> S.index bs 0 == 13 _ -> False in Just (nl, not b && (c == 32 || c == 9)) else Just (nl, False) {-# INLINE push' #-} push' :: Maybe (Int, Bool) -> IO [ByteString] -- No newline find in this chunk. Add it to the prepend, -- update the length, and continue processing. push' Nothing = do bst <- readSource' src when (S.null bst) $ throwIO IncompleteHeaders push src status bst where len' = len + bsLen prepend' = S.append bs status = THStatus len' lines prepend' -- Found a newline, but next line continues as a multiline header push' (Just (end, True)) = push src status rest where rest = S.drop (end + 1) bs prepend' = S.append (SU.unsafeTake (checkCR bs end) bs) len' = len + end status = THStatus len' lines prepend' -- Found a newline at position end. push' (Just (end, False)) -- leftover | S.null line = do when (start < bsLen) $ leftoverSource src (SU.unsafeDrop start bs) return (lines []) -- more headers | otherwise = let len' = len + start lines' = lines . (line:) status = THStatus len' lines' id in if start < bsLen then -- more bytes in this chunk, push again let bs'' = SU.unsafeDrop start bs in push src status bs'' else do -- no more bytes in this chunk, ask for more bst <- readSource' src when (S.null bs) $ throwIO IncompleteHeaders push src status bst where start = end + 1 -- start of next chunk line = SU.unsafeTake (checkCR bs end) bs {-# INLINE checkCR #-} checkCR :: ByteString -> Int -> Int checkCR bs pos = if pos > 0 && 13 == S.index bs p then p else pos -- 13 is CR where !p = pos - 1 pauseTimeoutKey :: Vault.Key (IO ()) pauseTimeoutKey = unsafePerformIO Vault.newKey {-# NOINLINE pauseTimeoutKey #-} getFileInfoKey :: Vault.Key (FilePath -> IO FileInfo) getFileInfoKey = unsafePerformIO Vault.newKey {-# NOINLINE getFileInfoKey #-}
creichert/wai
warp/Network/Wai/Handler/Warp/Request.hs
mit
11,339
0
19
3,408
2,390
1,273
1,117
214
7
module RL.Generator.Features (FeatureConfig(..), featuresGenerator) where import RL.Generator import RL.Generator.Cells (Cell(..), cmid) import RL.Generator.Paths (Path(..)) import RL.Generator.Items (generateChestItems, ItemConfig(..)) import RL.Item import RL.Map (DLevel(..), Point(..), Feature(..), Difficulty) import RL.Random import Control.Monad import Control.Monad.Reader import Data.Map (Map) import Data.Maybe (maybeToList) data FeatureConfig = FeatureConfig { maxFeatures :: Int, cellFeatureChance :: Rational, -- chance for a cell feature (Chest, Altar, or Fountain) fItemAppearances :: Map ItemType String } instance GenConfig FeatureConfig where generating conf = (< maxFeatures conf) <$> getCounter -- TODO don't generate on player featuresGenerator :: Generator FeatureConfig (DLevel, [Cell]) [(Point, Feature)] featuresGenerator = getGData >>= \(lvl, cs) -> forMConcat cs $ \c -> do conf <- ask r <- randomChance (cellFeatureChance conf) if r then do f <- maybeToList <$> pickFeature return $ zip (repeat (cmid c)) f else return [] -- pick an item at random for the given depth pickFeature :: Generator FeatureConfig (DLevel, [Cell]) (Maybe Feature) pickFeature = do lvl <- fst <$> getGData chestContents <- fillChest =<< asks fItemAppearances pickRarity (featureRarity (depth lvl)) [Chest chestContents, Fountain 2, Altar] where fillChest app = do lvl <- fst <$> getGData app <- asks fItemAppearances g <- getSplit let chestConf = ItemConfig { minItems = 3, maxItems = 10, itemGenChance = 1 % 6, itemAppearances = app } return $ evalGenerator (generateChestItems (depth lvl)) chestConf (mkGenState [] g) featureRarity :: Difficulty -> Feature -> Rational featureRarity d (Chest _) = 1 % 2 featureRarity d (Fountain _) = 1 % 3 featureRarity d (Altar) = 1 % 5 forMConcat :: Monad m => [a] -> (a -> m [b]) -> m [b] forMConcat l = fmap concat . forM l
MichaelMackus/hsrl
RL/Generator/Features.hs
mit
2,175
0
19
579
680
371
309
47
2
module BlueWire.Database where
quantifiedtran/blue-wire-backend
src/BlueWire/Database.hs
mit
31
0
3
3
6
4
2
1
0
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {- | The core data type for this example application. -} module Factory.Types.Widget where import Data.Aeson as Aeson import qualified GHC.Generics as GHC import qualified Data.Text as Text import Data.Swagger.Schema as Swagger {- | A widget. Who knows what it does. -} data Widget = Widget { name :: Text.Text -- ^ The name of this widget. } deriving (Aeson.FromJSON, Aeson.ToJSON, Eq, GHC.Generic, Read, Show, Swagger.ToSchema)
alexanderkjeldaas/factory
library/Factory/Types/Widget.hs
mit
541
0
9
122
99
63
36
11
0
import Control.Monad import Data.List readNumbers :: String -> [Int] readNumbers = map read . words readPair [a, b] = (a, b) readTriple [a, b, k] = (a, b, k) comparator (r1, k1) (r2, k2) = if r1 /= r2 then r1 `compare` r2 else r2 `compare` r1 main :: IO () main = do input <- getLine let (n, m) = readPair $ readNumbers input input <- replicateM m getLine let ranges = map (readTriple . readNumbers) input let marks = foldl' (\acc (a, b, k) -> acc ++ [(a, k)] ++ [(b, -k)]) [] ranges let sortedMarks = sortBy comparator marks let initialAns = map (snd . snd) $ zip [1..2 * m] sortedMarks let foldedAns = sort $ scanl' (+) 0 initialAns print $ last foldedAns
mgrebenets/hackerrank
alg/greedy/algorithmic-crush.hs
mit
697
0
16
167
353
188
165
18
2
module Ringo.Generator ( dimensionTableDefinitionSQL , factTableDefinitionSQL , dimensionTableDefinitionStatements , factTableDefinitionStatements , dimensionTablePopulationSQL , dimensionTablePopulationStatement , factTablePopulationSQL , factTablePopulationStatements ) where import Ringo.Generator.Create import Ringo.Generator.Populate.Dimension import Ringo.Generator.Populate.Fact
abhin4v/ringo
ringo-core/src/Ringo/Generator.hs
mit
451
0
4
90
52
35
17
12
0
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.Blob (js_newBlob, newBlob, js_newBlob', newBlob', js_slice, slice, js_getSize, getSize, js_getType, getType, Blob, castToBlob, gTypeBlob, IsBlob, toBlob) 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 "new window[\"Blob\"]()" js_newBlob :: IO (JSRef Blob) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Blob Mozilla Blob documentation> newBlob :: (MonadIO m) => m Blob newBlob = liftIO (js_newBlob >>= fromJSRefUnchecked) foreign import javascript unsafe "new window[\"Blob\"]($1, $2)" js_newBlob' :: JSRef [JSRef a] -> JSRef BlobPropertyBag -> IO (JSRef Blob) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Blob Mozilla Blob documentation> newBlob' :: (MonadIO m, IsBlobPropertyBag options) => [JSRef a] -> Maybe options -> m Blob newBlob' blobParts options = liftIO (toJSRef blobParts >>= \ blobParts' -> js_newBlob' blobParts' (maybe jsNull (unBlobPropertyBag . toBlobPropertyBag) options) >>= fromJSRefUnchecked) foreign import javascript unsafe "$1[\"slice\"]($2, $3, $4)" js_slice :: JSRef Blob -> Double -> Double -> JSRef (Maybe JSString) -> IO (JSRef Blob) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Blob.slice Mozilla Blob.slice documentation> slice :: (MonadIO m, IsBlob self, ToJSString contentType) => self -> Int64 -> Int64 -> Maybe contentType -> m (Maybe Blob) slice self start end contentType = liftIO ((js_slice (unBlob (toBlob self)) (fromIntegral start) (fromIntegral end) (toMaybeJSString contentType)) >>= fromJSRef) foreign import javascript unsafe "$1[\"size\"]" js_getSize :: JSRef Blob -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/Blob.size Mozilla Blob.size documentation> getSize :: (MonadIO m, IsBlob self) => self -> m Word64 getSize self = liftIO (round <$> (js_getSize (unBlob (toBlob self)))) foreign import javascript unsafe "$1[\"type\"]" js_getType :: JSRef Blob -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Blob.type Mozilla Blob.type documentation> getType :: (MonadIO m, IsBlob self, FromJSString result) => self -> m result getType self = liftIO (fromJSString <$> (js_getType (unBlob (toBlob self))))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/Blob.hs
mit
3,181
36
14
557
865
491
374
58
1
{-# LANGUAGE CPP #-} module TetrisAttack.Grid ( Grid2D, GridLocation2D, generateGrid, fromLists, getRow, gridSize, get2D, update2D, bulkUpdate2D, GridWalker(..), walkRows, walkColumns, walkColumnsRev, mapGrid, mapGridM, mapGridM_, imapGrid, imapGridM, imapGridM_, zipGrid, unzipGrid, GridUpdater(..), updateColumns, updateColumnsRev, eitherGrid ) where -------------------------------------------------------------------------------- import Data.Either import Data.Maybe (fromJust) #if __GLASGOW_HASKELL__ <= 708 import Data.Monoid #endif import qualified Data.Vector as V -------------------------------------------------------------------------------- type Grid2D a = V.Vector (V.Vector a) type GridLocation2D = (Int, Int) gridSize :: Grid2D a -> (Int, Int) gridSize grid | glength == 0 = (0, 0) | otherwise = (glength, V.length $ V.head grid) where glength = V.length grid generateGrid :: Int -> Int -> (Int -> Int -> a) -> Grid2D a generateGrid cols rows f = V.generate cols (\col -> V.generate rows (\row -> f col row)) fromLists :: [[a]] -> Grid2D a fromLists = V.fromList . (map V.fromList) getRow :: Int -> Grid2D a -> [a] getRow row = V.toList . V.map (V.! (row - 1)) mapGrid :: (a -> b) -> Grid2D a -> Grid2D b mapGrid f = V.map (\v -> V.map f v) mapGridM :: Monad m => (a -> m b) -> Grid2D a -> m (Grid2D b) mapGridM f = V.mapM (\v -> V.mapM f v) mapGridM_ :: Monad m => (a -> m b) -> Grid2D a -> m () mapGridM_ f g = do { _ <- mapGridM f g; return () } imapGrid :: (Int -> Int -> a -> b) -> Grid2D a -> Grid2D b imapGrid f = V.imap (\col -> V.imap (\row -> f col row)) imapGridM :: Monad m => ((Int, Int) -> a -> m b) -> Grid2D a -> m (Grid2D b) imapGridM f grid = mapGridM (uncurry f) (zipGrid locGrid grid) where locGrid = uncurry generateGrid (gridSize grid) (,) imapGridM_ :: Monad m => ((Int, Int) -> a -> m b) -> Grid2D a -> m () imapGridM_ f g = do {_ <- imapGridM f g; return ()} zipGrid :: Grid2D a -> Grid2D b -> Grid2D (a, b) zipGrid = V.zipWith V.zip unzipGrid :: Grid2D (b, c) -> (Grid2D b, Grid2D c) unzipGrid = V.unzip . (V.map V.unzip) get2D :: GridLocation2D -> Grid2D a -> a get2D (x, y) b = (b V.! (x - 1)) V.! (y - 1) update2D :: a -> GridLocation2D -> Grid2D a -> Grid2D a update2D val (x, y) board = let col = board V.! (x - 1) newcol = col V.// [((y - 1), val)] in board V.// [((x - 1), newcol)] bulkUpdate2D :: a -> [GridLocation2D] -> V.Vector (V.Vector a) -> V.Vector (V.Vector a) bulkUpdate2D val = flip $ foldr (update2D val) data GridWalker a b = Result b | Walker (Maybe a -> GridWalker a b) stepWalker :: GridWalker a b -> a -> GridWalker a b stepWalker (Result b) _ = Result b stepWalker (Walker f) x = f (Just x) finishWalker :: GridWalker a b -> b finishWalker (Result b) = b finishWalker (Walker f) = finishWalker $ f Nothing walkRows :: Grid2D a -> GridWalker a b -> [b] walkRows grid walker | V.length grid == 0 = [] | otherwise = let step :: V.Vector (GridWalker a b) -> V.Vector a -> V.Vector (GridWalker a b) step = V.zipWith stepWalker in V.toList $ V.map finishWalker $ V.foldl' step (V.map (\_ -> walker) (V.head grid)) grid walkColumns :: Grid2D a -> GridWalker a b -> [b] walkColumns grid walker = V.toList $ V.map (finishWalker . (V.foldl' stepWalker walker)) grid walkColumnsRev :: Grid2D a -> GridWalker a b -> [b] walkColumnsRev grid walker = V.toList $ V.map (finishWalker . (V.foldr' (flip stepWalker) walker)) grid newtype GridUpdater a b = GridUpdater { updateGridValue :: a -> (b, GridUpdater a b) } updateScanFn :: a -> (Maybe b, GridUpdater a b) -> (Maybe b, GridUpdater a b) updateScanFn x (_, GridUpdater fn) = let (y, next) = fn x in (Just y, next) updateColumns :: GridUpdater a b -> Grid2D a -> Grid2D b updateColumns updater = V.map updateColumn where updateColumn = V.map (fromJust . fst) . V.postscanl' (flip updateScanFn) (Nothing, updater) updateColumnsRev :: GridUpdater a b -> Grid2D a -> Grid2D b updateColumnsRev updater = V.map updateColumn where updateColumn = V.map (fromJust . fst) . V.postscanr' updateScanFn (Nothing, updater) eitherGrid :: Monoid e => Grid2D (Either e a) -> Either e (Grid2D a) eitherGrid grid = let collectEithers :: Monoid e => Either e a -> Maybe (Either e a) -> GridWalker (Either e a) (Either e a) collectEithers x Nothing = Result x collectEithers (Right _) (Just (Left y)) = Walker $ collectEithers (Left y) collectEithers (Left x) (Just (Left y)) = Walker $ collectEithers (Left $ x `mappend` y) collectEithers (Right x) (Just (Right _)) = Walker $ collectEithers (Right x) collectEithers (Left x) (Just (Right _)) = Walker $ collectEithers (Left x) mapEither :: Monoid e => Either e a -> e mapEither (Left x) = x mapEither _ = mempty result = walkRows grid $ Walker $ collectEithers (Right undefined) in if (any isLeft result) then Left . mconcat $ map mapEither result else Right $ mapGrid (either undefined id) grid
Mokosha/HsTetrisAttack
TetrisAttack/Grid.hs
mit
4,999
0
14
1,017
2,318
1,189
1,129
96
7
{-# OPTIONS_GHC -Wall -fno-warn-name-shadowing #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} module Yage.Core.Application.Logging ( getAppLogger, getWinLogger , logApp, logging , debugLog, infoLog, noticeLog, warningLog, errorLog, criticalLog, alertLog, emergencyLog , coloredLogFormatter , module Logger -- , module Formatter , module HandlerSimple ) where import Yage.Prelude import Control.Monad.Reader (asks) import System.Log.Logger (Logger, logL) import System.Log.Logger as Logger ( Logger, Priority(..), getLogger, getRootLogger , removeAllHandlers, setHandlers, addHandler , rootLoggerName, setLevel, getLevel, updateGlobalLogger , saveGlobalLogger, logL) import System.Log.Handler.Simple as HandlerSimple import qualified System.Log.Formatter as Formatter import System.Console.ANSI import Control.Concurrent (myThreadId) import Data.Time (getZonedTime) import Yage.Core.Application.Types import Yage.Core.Application.Exception import Yage.Core.Application.Utils -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- getAppLogger :: Application l Logger getAppLogger = asks $ snd . appLogger getWinLogger :: Window -> Logger getWinLogger = snd . winLogger debugLog, infoLog, noticeLog, warningLog, errorLog, criticalLog, alertLog, emergencyLog :: (Show a, MonadApplication m) => a -> m () debugLog = logApp Logger.DEBUG infoLog = logApp Logger.INFO noticeLog = logApp Logger.NOTICE warningLog = logApp Logger.WARNING errorLog = logApp Logger.ERROR criticalLog = logApp Logger.CRITICAL alertLog = logApp Logger.ALERT emergencyLog = logApp Logger.EMERGENCY logApp :: (Show a, MonadApplication m) => Logger.Priority -> a -> m () logApp p m = liftApp $ do l <- getAppLogger logging l p m logging :: (Show a, MonadApplication m) => Logger -> Logger.Priority -> a -> m () logging logger pri msg = liftApp $ ioe $ Logger.logL logger pri (show msg) -------------------------------------------------------------------------------- coloredLogFormatter :: forall a. String -> Formatter.LogFormatter a coloredLogFormatter = formatter where formatter :: String -> Formatter.LogFormatter a formatter format _ (prio,msg) loggername = let vars = [("time", formatTime defaultTimeLocale timeFormat <$> getZonedTime) ,("utcTime", formatTime defaultTimeLocale timeFormat <$> getCurrentTime) ,("msg", return msg) ,("prio", return $ show prio) ,("loggername", return loggername) ,("tid", show <$> myThreadId) ] color = msgColor prio in (\s -> color ++ s ++ reset) <$> replaceVarM vars format msgColor prio | prio == Logger.DEBUG = debugColor | prio == Logger.WARNING = warnColor | prio == Logger.NOTICE = noticeColor | prio >= Logger.ERROR = errColor | otherwise = normColor timeFormat = "%F %X %Z" normColor = setSGRCode [] debugColor = setSGRCode [ SetColor Foreground Vivid Blue ] warnColor = setSGRCode [ SetColor Foreground Vivid Yellow ] noticeColor= setSGRCode [ SetColor Foreground Dull Yellow ] errColor = setSGRCode [ SetColor Foreground Vivid Red ] reset = normColor -------------------------------------------------------------------------------- -- is sadly not exported -- http://hackage.haskell.org/package/hslogger-1.2.3/docs/src/System-Log-Formatter.html#simpleLogFormatter -- | Replace some '$' variables in a string with supplied values replaceVarM :: [(String, IO String)] -- ^ A list of (variableName, action to get the replacement string) pairs -> String -- ^ String to perform substitution on -> IO String -- ^ Resulting string replaceVarM _ [] = return [] replaceVarM keyVals (s:ss) | s=='$' = do (f,rest) <- replaceStart keyVals ss repRest <- replaceVarM keyVals rest return $ f ++ repRest | otherwise = liftM (s:) $ replaceVarM keyVals ss where replaceStart [] str = return ("$",str) replaceStart ((k,v):kvs) str | k `isPrefixOf` str = do vs <- v return (vs, drop (length k) str) | otherwise = replaceStart kvs str
MaxDaten/yage-core
src/Yage/Core/Application/Logging.hs
mit
5,010
0
14
1,551
1,122
617
505
82
2
module Prop where import GildedRoseProp as G main :: IO () main = G.runProps
qwaneu/gilded-rose-haskell-solution
test/Spec.hs
mit
79
0
6
16
26
16
10
4
1
-- When you do a qualified import, type constructors also have to be preceeded -- with a module name. So you'd write: -- type IntMap = Map.Map Int import qualified Data.Map as Map -- Type synonims: type PhoneNumber = String type Name = String type PhoneBook = [(Name, PhoneNumber)] -- inPhoneBook :: Name -> PhoneNumber -> PhoneBook -> Bool type AssocList k v = [(k, v)] type IntMap v = Map.Map Int v -- equivalent with: -- type IntMap = Map Int -- actual new types defined here: -- data Either = Left a | Right b -- deriving (Eq, Ord, Read, Show) -- -- high-school lockers example: -- -- LockerState is a data type representing whether a locker is taken or free data LockerState = Taken | Free deriving (Eq, Show) -- Code is synonim for a locker's code type Code = String -- LockerMap is a synonim that maps from Int to pairs of locker state and code type LockerMap = Map.Map Int (LockerState, Code) lockerLookup :: Int -> LockerMap -> Either String Code lockerLookup lockerNumber map = case Map.lookup lockerNumber map of Nothing -> Left $ "Locker number " ++ show lockerNumber ++ " doesn't exist!" Just (state, code) -> if state /= Taken then Right code else Left $ "Locker number " ++ show lockerNumber ++ " is taken!" lockers :: LockerMap lockers = Map.fromList [(100,(Taken,"ZD39I")) ,(101,(Free,"JAH3I")) ,(103,(Free,"IQSA9")) ,(105,(Free,"QOTSA")) ,(109,(Taken,"893JJ")) ,(110,(Taken,"99292")) ] main = do let s = lockerLookup 101 lockers print s -- -- recursive data types -- -- data List a = Empty | Cons a (List a) -- deriving (Eq, Show, Read, Ord) -- the same definition in record syntax: -- data List a = Empty | Cons { listHead :: a, listTail :: List a } -- deriving (Eq, Show, Read, Ord) -- main = -- print Empty
adizere/nifty-tree
playground/types.hs
mit
1,884
0
11
462
374
228
146
27
3
primes = 2 : primes' where primes' = sieve [3,5..] 9 primes' sieve (x:xs) q ps@ ~(p:t) | x < q = x : sieve xs q ps | True = sieve [x | x <- xs, x `mod` p > 0] (head t^2) t -- Its massively slow, like 30 seconds, but it works sumOfPrimesLessThan2Million = sum . takeWhile (<2000000) $ primes -- And the answer is: -- 142913828922
ciderpunx/project_euler_in_haskell
euler010.hs
gpl-2.0
365
0
12
106
155
81
74
6
1
module PlotLab.Figure where -------------------------------------------------------------------------------- -- Standard Libraries import Control.Monad (unless, when) import Data.IORef (IORef, readIORef) import Data.Maybe (fromJust, isJust) -------------------------------------------------------------------------------- -- Other Modules import Graphics.Rendering.Plot import Graphics.UI.Gtk (Adjustment, adjustmentGetValue) import Numeric.LinearAlgebra (linspace, mapVector) -------------------------------------------------------------------------------- -- PlotLab import PlotLab.Settings -------------------------------------------------------------------------------- updateFigureText :: (Text () -> Figure ()) -> Maybe String -> Double -> Figure () updateFigureText withSomething txt size = case txt of Nothing -> return () Just str -> withSomething . unless (null str) $ do setText str setFontSize size -------------------------------------------------------------------------------- updateAxis :: AxisType -> Bool -> (AxisPosn, AxisSide) -> Maybe (Double, Double) -> Scale -> Maybe String -> FontSize -> Plot () updateAxis axis state location range scale label size = do let (position, side) = location when state $ addAxis axis position (when (isJust label) $ withAxisLabel $ do setText . fromJust $ label setFontSize size) maybe (setRangeFromData axis side scale) (uncurry (setRange axis side scale)) range -------------------------------------------------------------------------------- figurePlot :: ([Double] -> Double -> Double) -> IORef FigureSettings -> [Adjustment] -> IO (Figure ()) figurePlot g iofset adjs = do fset <- readIORef iofset vars <- mapM adjustmentGetValue adjs let rate = samplingRate fset range = fromJust $ xRange fset samples = round $ (\(x, y) -> rate * (y - x)) range domain = linspace samples range func = g vars stype = plotType fset dset = [(stype, domain, mapVector func domain)] return $ buildFigure dset fset -------------------------------------------------------------------------------- buildFigure :: Dataset a => a -> FigureSettings -> Figure () buildFigure dset fset = do withTextDefaults $ setFontFamily (fontFamily fset) let str = plotTitle fset size = plotTitleSize fset in updateFigureText withTitle str size let str = subTitle fset size = subTitleSize fset in updateFigureText withSubTitle str size setPlots 1 1 withPlot (1, 1) $ do setDataset dset -- X-Axis let state = showXAxis fset label = xLabel fset size = xLabelSize fset loc = xLocation fset range = xRange fset scale = plotScaleX fset in updateAxis XAxis state loc range scale label size -- Y-Axis let state = showYAxis fset label = yLabel fset size = yLabelSize fset loc = yLocation fset range = yRange fset scale = plotScaleY fset in updateAxis YAxis state loc range scale label size --------------------------------------------------------------------------------
sumitsahrawat/plot-lab
src/PlotLab/Figure.hs
gpl-2.0
3,432
0
16
914
877
438
439
67
2
{-# LANGUAGE DeriveDataTypeable #-} {-| An implementation of various limits that can be applied to arbitrary code blocks. -} module Limits (limitTime, TimeoutException(..)) where import Control.Concurrent (forkIO, killThread, myThreadId, threadDelay, throwTo) import Control.DeepSeq (deepseq, NFData (..)) import Control.Concurrent.MVar (isEmptyMVar, newEmptyMVar, putMVar, takeMVar) import Control.Exception (AsyncException (ThreadKilled), Handler (Handler), Exception, SomeException, catches, finally) import Control.Monad (when) import Data.Typeable (Typeable) -- | Exception that is thrown when a computation times out data TimeoutException = TimeoutException deriving (Show, Typeable) instance Exception TimeoutException -- | Limit an action so that it max may execute for the specified -- number of microseconds. The 'NFData' constraint is used to fully -- evaluate the result of the action before it is returned, so that -- evaluation is part of the time constraint. limitTime :: NFData a => Int -> IO a -> IO a limitTime timeout action = do -- Who am I? mainId <- myThreadId -- Variable that stores the fully evaluated result of the action resultVar <- newEmptyMVar -- Variable that is non-empty once the action is done executing doneVar <- newEmptyMVar -- The asynchronous action that is going to be performed on the -- child thread let asyncAction = do -- Perform the actual action r <- action -- Fully evaluate the result of the action on this thread -- before storing it in the var r `deepseq` putMVar resultVar r -- Spawn thread to apply time limit to childId <- forkIO $ asyncAction `catches` [ Handler $ -- Handle AsyncException \ e -> case e of -- Was this thread killed? Then it was probably because of the -- timeout, so swallow the exception. ThreadKilled -> return () -- Otherwise, forward exception to main thread _ -> throwTo mainId e , Handler $ -- Handle all other exceptions \ e -> throwTo mainId (e :: SomeException) ] -- Spawn thread to kill the other thread after timeout _ <- forkIO $ do -- Wait for the allowed delay threadDelay timeout -- Check if done notDone <- isEmptyMVar doneVar -- Were we not done? Then report timeout to main thread... when notDone $ throwTo mainId TimeoutException -- ...and kill the child thread killThread childId -- Block until resultVar contains something or we get an exception result <- takeMVar resultVar `finally` putMVar doneVar () -- Return the normal result return result
dflemstr/monad-presentation
src/Limits.hs
gpl-3.0
2,653
0
16
600
423
237
186
37
2
{- ============================================================================ | Copyright 2011 Matthew D. Steele <[email protected]> | | | | This file is part of Fallback. | | | | Fallback 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. | | | | Fallback 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 Fallback. If not, see <http://www.gnu.org/licenses/>. | ============================================================================ -} {-# LANGUAGE GeneralizedNewtypeDeriving, Rank2Types, TypeFamilies #-} module Fallback.Scenario.Compile (-- * Reading the scenario ScenarioTriggers, scenarioInitialProgress, getAreaDevice, getAreaEntrance, getAreaExits, getAreaLinks, getAreaTerrain, getAreaTriggers, getMonsterScript, getRegionBackground, getScriptedBattle, -- * Defining the scenario CompileScenario, compileScenario, newGlobalVar, compileRegion, compileArea, -- * Defining an area CompileArea, newPersistentVar, newTransientVar, makeExit, -- * Scripted battles CompileBattle, ScriptedBattle(..), newScriptedBattle, -- * Defining triggers DefineTrigger(..), onStartDaily, onStartOnce, daily, once, onBattleStart, -- * Devices DefineDevice(..), -- * Monster scripts DefineMonsterScript(..), -- * Variables Var, getVar, readVar, writeVar, modifyVar, -- * Trigger predicates Predicate, periodicP, andP, orP, xorP, notP, getP, whenP, unlessP, varIs, varTrue, varFalse, varEq, varNeq, walkOn, walkOff, walkIn, questUntaken, questActive, areaCleared, monsterReady) where import Control.Applicative (Applicative) import Control.Monad (unless, when) import Control.Monad.Fix (MonadFix) import qualified Control.Monad.State as State import qualified Data.Map as Map import Data.Maybe (fromMaybe) import qualified Data.Set as Set import Fallback.Constants (maxMoments) import qualified Fallback.Data.Grid as Grid import Fallback.Data.Point (rectContains) import qualified Fallback.Data.SparseMap as SM import qualified Fallback.Data.TotalMap as TM import Fallback.Scenario.Script import Fallback.State.Area import Fallback.State.Creature import Fallback.State.Combat (CombatState, csPeriodicTimer) import Fallback.State.Party (Party, partyClearedAreas, partyQuests) import Fallback.State.Progress import Fallback.State.Simple import Fallback.State.Tags (AreaTag, QuestTag, RegionTag) import Fallback.State.Terrain (terrainMap, tmapLookupMark, tmapLookupRect) import Fallback.State.Town (TownState) import Fallback.State.Trigger (Trigger, makeTrigger) ------------------------------------------------------------------------------- -- Reading the scenario: data ScenarioTriggers = ScenarioTriggers { scenarioAreas :: TM.TotalMap AreaTag AreaSpec, scenarioInitialProgress :: Progress, scenarioRegionBackgrounds :: TM.TotalMap RegionTag (Party -> String) } data AreaSpec = AreaSpec { aspecDevices :: Map.Map DeviceId Device, aspecEntrances :: Map.Map AreaTag MarkKey, aspecExits :: [AreaExit], aspecMonsterScripts :: Map.Map MonsterScriptId MonsterScript, aspecScriptedBattles :: Map.Map BattleId ScriptedBattle, aspecTerrain :: Party -> String, aspecTriggers :: [Trigger TownState TownEffect] } getAreaDevice :: ScenarioTriggers -> AreaTag -> DeviceId -> Maybe Device getAreaDevice scenario tag di = Map.lookup di $ aspecDevices $ TM.get tag $ scenarioAreas scenario getAreaEntrance :: ScenarioTriggers -> AreaTag -> AreaTag -> MarkKey getAreaEntrance scenario tag from = Map.findWithDefault err from $ aspecEntrances $ TM.get tag $ scenarioAreas scenario where err = error ("getAreaEntrance: no entrance to " ++ show tag ++ " from " ++ show from) getAreaExits :: ScenarioTriggers -> AreaTag -> [AreaExit] getAreaExits scenario tag = aspecExits $ TM.get tag $ scenarioAreas scenario getAreaLinks :: ScenarioTriggers -> AreaTag -> Set.Set AreaTag getAreaLinks scenario tag = Map.keysSet $ aspecEntrances $ TM.get tag $ scenarioAreas scenario getAreaTerrain :: ScenarioTriggers -> Party -> AreaTag -> String getAreaTerrain scenario party tag = aspecTerrain (TM.get tag (scenarioAreas scenario)) party getAreaTriggers :: ScenarioTriggers -> AreaTag -> [Trigger TownState TownEffect] getAreaTriggers scenario tag = aspecTriggers $ TM.get tag $ scenarioAreas scenario getMonsterScript :: ScenarioTriggers -> AreaTag -> MonsterScriptId -> Grid.Entry Monster -> Script TownEffect () getMonsterScript scenario tag scriptId = fromMaybe (fail ("no such monster script: " ++ show scriptId)) $ Map.lookup scriptId $ aspecMonsterScripts $ TM.get tag $ scenarioAreas scenario getRegionBackground :: ScenarioTriggers -> Party -> RegionTag -> String getRegionBackground scenario party tag = TM.get tag (scenarioRegionBackgrounds scenario) party getScriptedBattle :: ScenarioTriggers -> AreaTag -> BattleId -> ScriptedBattle getScriptedBattle scenario areaTag battleId = fromMaybe (error ("getScriptedBattle: no such battle: " ++ show battleId)) $ Map.lookup battleId $ aspecScriptedBattles $ TM.get areaTag $ scenarioAreas scenario ------------------------------------------------------------------------------- -- Defining the scenario: newtype CompileScenario a = CompileScenario (State.State CompileScenarioState a) deriving (Applicative, Functor, Monad, MonadFix) data CompileScenarioState = CompileScenarioState { cssAllVarSeeds :: Set.Set VarSeed, cssAreas :: Map.Map AreaTag AreaSpec, cssDevices :: Map.Map DeviceId Device, cssMonsterScripts :: Map.Map MonsterScriptId MonsterScript, cssProgress :: Progress, cssRegions :: Map.Map RegionTag (Party -> String) } compileScenario :: CompileScenario () -> ScenarioTriggers compileScenario (CompileScenario compile) = let css = State.execState compile CompileScenarioState { cssAllVarSeeds = Set.empty, cssAreas = Map.empty, cssDevices = Map.empty, cssMonsterScripts = Map.empty, cssProgress = emptyProgress, cssRegions = Map.empty } getArea tag = fromMaybe (error $ "Missing area: " ++ show tag) $ Map.lookup tag $ cssAreas css -- TODO Verify symmetry of links getRegion tag = fromMaybe (error $ "Missing region: " ++ show tag) $ Map.lookup tag $ cssRegions css in ScenarioTriggers { scenarioAreas = TM.make getArea, scenarioRegionBackgrounds = TM.make getRegion, scenarioInitialProgress = cssProgress css } newGlobalVar :: (VarType a) => VarSeed -> a -> CompileScenario (Var a) newGlobalVar vseed value = do var <- newVar vseed CompileScenario $ do css <- State.get State.put css { cssProgress = progressSetVar var value $ cssProgress css } return var compileRegion :: RegionTag -> (Party -> String) -> CompileScenario () compileRegion tag backgroundFn = CompileScenario $ do css <- State.get when (Map.member tag $ cssRegions css) $ do fail ("Repeated region: " ++ show tag) State.put css { cssRegions = Map.insert tag backgroundFn (cssRegions css) } compileArea :: AreaTag -> Maybe (Party -> String) -> CompileArea () -> CompileScenario () compileArea tag mbTerraFn (CompileArea compile) = CompileScenario $ do css <- State.get when (Map.member tag $ cssAreas css) $ do fail ("Repeated area: " ++ show tag) let cas = State.execState compile CompileAreaState { casAllVarSeeds = cssAllVarSeeds css, casDevices = cssDevices css, casEntrances = Map.empty, casMonsterScripts = cssMonsterScripts css, casProgress = cssProgress css, casScriptedBattles = Map.empty, casTriggers = [] } let mkExit (dest, (rectKeys, _)) = AreaExit { aeDestination = dest, aeRectKeys = rectKeys } let aspec = AreaSpec { aspecDevices = casDevices cas, aspecEntrances = fmap snd $ casEntrances cas, aspecExits = map mkExit $ Map.assocs $ casEntrances cas, aspecMonsterScripts = casMonsterScripts cas, aspecScriptedBattles = casScriptedBattles cas, aspecTerrain = fromMaybe (const $ show tag) mbTerraFn, aspecTriggers = reverse (casTriggers cas) } State.put css { cssAllVarSeeds = casAllVarSeeds cas, cssAreas = Map.insert tag aspec (cssAreas css), cssProgress = casProgress cas } ------------------------------------------------------------------------------- -- Defining an area: newtype CompileArea a = CompileArea (State.State CompileAreaState a) deriving (Applicative, Functor, Monad, MonadFix) data CompileAreaState = CompileAreaState { casAllVarSeeds :: Set.Set VarSeed, casDevices :: Map.Map DeviceId Device, casEntrances :: Map.Map AreaTag ([RectKey], MarkKey), casMonsterScripts :: Map.Map MonsterScriptId MonsterScript, casProgress :: Progress, casScriptedBattles :: Map.Map BattleId ScriptedBattle, casTriggers :: [Trigger TownState TownEffect] } newPersistentVar :: (VarType a) => VarSeed -> a -> CompileArea (Var a) newPersistentVar vseed value = do var <- newVar vseed CompileArea $ do cas <- State.get State.put cas { casProgress = progressSetVar var value $ casProgress cas } return var newTransientVar :: (VarType a) => VarSeed -> Script TownEffect a -> CompileArea (Var a) newTransientVar vseed initialize = do (vseed', vseed'') <- splitVarSeed vseed var <- newPersistentVar vseed' varDefaultValue onStartDaily vseed'' $ do writeVar var =<< initialize return var makeExit :: AreaTag -> [RectKey] -> MarkKey -> CompileArea () makeExit tag rectKeys markKey = CompileArea $ do cas <- State.get let entrances = casEntrances cas when (Map.member tag entrances) $ do fail ("Repeated exit: " ++ show tag) State.put cas { casEntrances = Map.insert tag (rectKeys, markKey) entrances } ------------------------------------------------------------------------------- newtype CompileBattle a = CompileBattle (State.State CompileBattleState a) deriving (Applicative, Functor, Monad, MonadFix) data CompileBattleState = CompileBattleState { cbsAllVarSeeds :: Set.Set VarSeed, cbsTriggers :: [Trigger CombatState CombatEffect] } data ScriptedBattle = ScriptedBattle { sbId :: BattleId, sbRectKey :: RectKey, sbTriggers :: [Trigger CombatState CombatEffect] } newScriptedBattle :: VarSeed -> RectKey -> CompileBattle () -> CompileArea BattleId newScriptedBattle vseed rectKey (CompileBattle compile) = do battleId <- newBattleId vseed CompileArea $ do cas <- State.get let cbs = State.execState compile CompileBattleState { cbsAllVarSeeds = casAllVarSeeds cas, cbsTriggers = [] } let battle = ScriptedBattle { sbId = battleId, sbRectKey = rectKey, sbTriggers = cbsTriggers cbs } State.put cas { casAllVarSeeds = cbsAllVarSeeds cbs, casScriptedBattles = Map.insert battleId battle $ casScriptedBattles cas } return battleId ------------------------------------------------------------------------------- -- Checking VarSeeds: instance HasVarSeeds CompileScenario where useVarSeed vseed = CompileScenario $ do varSeeds <- State.gets cssAllVarSeeds when (Set.member vseed varSeeds) $ do fail ("Repeated VarSeed: " ++ show vseed) State.modify $ \css -> css { cssAllVarSeeds = Set.insert vseed varSeeds } instance HasVarSeeds CompileArea where useVarSeed vseed = CompileArea $ do varSeeds <- State.gets casAllVarSeeds when (Set.member vseed varSeeds) $ do fail ("Repeated VarSeed: " ++ show vseed) State.modify $ \cas -> cas { casAllVarSeeds = Set.insert vseed varSeeds } instance HasVarSeeds CompileBattle where useVarSeed vseed = CompileBattle $ do varSeeds <- State.gets cbsAllVarSeeds when (Set.member vseed varSeeds) $ do fail ("Repeated VarSeed: " ++ show vseed) State.modify $ \cbs -> cbs { cbsAllVarSeeds = Set.insert vseed varSeeds } ------------------------------------------------------------------------------- -- Defining triggers: class (HasVarSeeds m) => DefineTrigger m where type TriggerState m :: * type TriggerEffect m :: * -> * trigger :: VarSeed -> Predicate (TriggerState m) -> Script (TriggerEffect m) () -> m () instance DefineTrigger CompileArea where type TriggerState CompileArea = TownState type TriggerEffect CompileArea = TownEffect trigger vseed (Predicate predicate) action = do tid <- newTriggerId vseed CompileArea $ do cas <- State.get State.put cas { casTriggers = makeTrigger tid predicate action : casTriggers cas } instance DefineTrigger CompileBattle where type TriggerState CompileBattle = CombatState type TriggerEffect CompileBattle = CombatEffect trigger vseed (Predicate predicate) action = do tid <- newTriggerId vseed CompileBattle $ do cbs <- State.get State.put cbs { cbsTriggers = makeTrigger tid predicate action : cbsTriggers cbs } onStartDaily :: VarSeed -> Script TownEffect () -> CompileArea () onStartDaily vseed = trigger vseed alwaysP onStartOnce :: VarSeed -> Script TownEffect () -> CompileArea () onStartOnce vseed = once vseed alwaysP daily :: VarSeed -> Predicate TownState -> Script TownEffect () -> CompileArea () daily vseed predicate script = do (vseed', vseed'') <- splitVarSeed vseed canFire <- newTransientVar vseed' (return True) trigger vseed'' (varTrue canFire `andP` predicate) $ do writeVar canFire False >> script once :: VarSeed -> Predicate TownState -> Script TownEffect () -> CompileArea () once vseed predicate script = do (vseed', vseed'') <- splitVarSeed vseed canFire <- newPersistentVar vseed' True trigger vseed'' (varTrue canFire `andP` predicate) $ do writeVar canFire False >> script onBattleStart :: VarSeed -> Script CombatEffect () -> CompileBattle () onBattleStart vseed = trigger vseed alwaysP ------------------------------------------------------------------------------- -- Defining devices: class (HasVarSeeds m) => DefineDevice m where newDevice :: VarSeed -> Int -> (Grid.Entry Device -> CharacterNumber -> Script AreaEffect ()) -> m Device instance DefineDevice CompileScenario where newDevice vseed radius sfn = do di <- newDeviceId vseed CompileScenario $ do css <- State.get when (Map.member di (cssDevices css)) $ do fail ("Internal error: Repeated device ID: " ++ show di) let device = Device { devId = di, devInteract = sfn, devRadius = radius } State.put css { cssDevices = Map.insert di device (cssDevices css) } return device instance DefineDevice CompileArea where newDevice vseed radius sfn = do di <- newDeviceId vseed CompileArea $ do cas <- State.get when (Map.member di $ casDevices cas) $ do fail ("Internal error: Repeated device ID: " ++ show di) let device = Device { devId = di, devInteract = sfn, devRadius = radius } State.put cas { casDevices = Map.insert di device (casDevices cas) } return device ------------------------------------------------------------------------------- -- Defining monster scripts: type MonsterScript = Grid.Entry Monster -> Script TownEffect () class (HasVarSeeds m) => DefineMonsterScript m where newMonsterScript :: VarSeed -> MonsterScript -> m MonsterScriptId instance DefineMonsterScript CompileArea where newMonsterScript vseed sfn = do msi <- newMonsterScriptId vseed CompileArea $ do cas <- State.get State.put cas { casMonsterScripts = Map.insert msi sfn (casMonsterScripts cas) } return msi ------------------------------------------------------------------------------- -- Variables: getVar :: (VarType a, HasProgress s) => Var a -> s -> a getVar var = progressGetVar var . getProgress readVar :: (VarType a, FromAreaEffect f) => Var a -> Script f a readVar var = areaGet $ getVar var writeVar :: (VarType a, FromAreaEffect f) => Var a -> a -> Script f () writeVar var value = emitAreaEffect $ EffAreaParty $ EffSetVar var value modifyVar :: (VarType a, FromAreaEffect f) => Var a -> (a -> a) -> Script f () modifyVar var fn = do value <- readVar var writeVar var (fn value) ------------------------------------------------------------------------------- -- Trigger predicates: newtype Predicate s = Predicate (s -> Bool) -- | A predicate that is always true. alwaysP :: Predicate s alwaysP = Predicate (const True) -- | A predicate that is true just after each periodic combat tick (once per -- round). periodicP :: Predicate CombatState periodicP = Predicate ((0 ==) . csPeriodicTimer) infixr 3 `andP` andP :: Predicate s -> Predicate s -> Predicate s andP (Predicate fn1) (Predicate fn2) = Predicate (\s -> fn1 s && fn2 s) infixr 2 `orP` orP :: Predicate s -> Predicate s -> Predicate s orP (Predicate fn1) (Predicate fn2) = Predicate (\s -> fn1 s || fn2 s) infixr 2 `xorP` xorP :: Predicate s -> Predicate s -> Predicate s xorP (Predicate fn1) (Predicate fn2) = Predicate (\s -> fn1 s /= fn2 s) notP :: Predicate s -> Predicate s notP (Predicate fn) = Predicate (not . fn) -- | Evaluate a predicate from within a script. getP :: (FromAreaEffect f) => (forall s. (AreaState s) => Predicate s) -> Script f Bool getP predicate = areaGet (case predicate of Predicate fn -> fn) whenP :: (FromAreaEffect f) => (forall s. (AreaState s) => Predicate s) -> Script f () -> Script f () whenP predicate action = do bool <- getP predicate when bool action unlessP :: (FromAreaEffect f) => (forall s. (AreaState s) => Predicate s) -> Script f () -> Script f () unlessP predicate action = do bool <- getP predicate unless bool action varIs :: (VarType a, HasProgress s) => (a -> Bool) -> Var a -> Predicate s varIs fn var = Predicate (fn . getVar var) varTrue :: (HasProgress s) => Var Bool -> Predicate s varTrue var = Predicate (getVar var) varFalse :: (HasProgress s) => Var Bool -> Predicate s varFalse var = Predicate (not . getVar var) varEq :: (Eq a, VarType a, HasProgress s) => Var a -> a -> Predicate s varEq var value = Predicate ((value ==) . getVar var) varNeq :: (Eq a, VarType a, HasProgress s) => Var a -> a -> Predicate s varNeq var value = Predicate ((value /=) . getVar var) walkOn :: (AreaState s) => MarkKey -> Predicate s walkOn key = Predicate $ \s -> any (flip Set.member (tmapLookupMark key $ terrainMap $ arsTerrain s)) $ arsPartyPositions s walkOff :: (AreaState s) => MarkKey -> Predicate s walkOff = notP . walkOn -- | True if the specified terrain rect exists and at least one character is -- currently within it. walkIn :: (AreaState s) => RectKey -> Predicate s walkIn key = Predicate $ \s -> maybe False (\r -> any (rectContains r) (arsPartyPositions s)) $ tmapLookupRect key $ terrainMap $ arsTerrain s questUntaken :: (AreaState s) => QuestTag -> Predicate s questUntaken = questStatus (== QuestUntaken) questActive :: (AreaState s) => QuestTag -> Predicate s questActive = questStatus (== QuestActive) questStatus :: (AreaState s) => (QuestStatus -> Bool) -> QuestTag -> Predicate s questStatus fn tag = Predicate (fn . SM.get tag . partyQuests . arsParty) -- | A predicate that is true when the given area has been cleared. areaCleared :: (AreaState s) => AreaTag -> Predicate s areaCleared tag = Predicate (Set.member tag . partyClearedAreas . arsParty) monsterReady :: Var (Grid.Key Monster) -> Predicate CombatState monsterReady var = Predicate $ \cs -> -- TODO: Right now, monster moment-gain and turn-taking are atomic, so this -- won't really work. We need to change it so trigger testing happens in -- between increasing monster moments and checking if monsters are ready. maybe False ((maxMoments <=) . monstMoments . Grid.geValue) (Grid.lookup (getVar var cs) (arsMonsters cs)) -------------------------------------------------------------------------------
mdsteele/fallback
src/Fallback/Scenario/Compile.hs
gpl-3.0
21,398
0
17
4,823
5,805
2,987
2,818
375
1
{-# LANGUAGE NoImplicitPrelude #-} module Jumpie.Types ( OutgoingAction(..), PointReal, RectReal, LineSegmentReal, LineSegmentInt, Real, RectInt, PointInt, Keydowns, isStarCollected, ) where import Jumpie.Geometry.LineSegment (LineSegment) import Jumpie.Geometry.Point (Point2) import Jumpie.Geometry.Rect (Rect()) import Wrench.Keysym (Keysym) import ClassyPrelude hiding (Real) type RectInt = Rect (Point2 Int) type Real = Double type PointInt = Point2 Int type PointReal = Point2 Real type RectReal = Rect PointReal type LineSegmentReal = LineSegment PointReal type LineSegmentInt = LineSegment PointInt data OutgoingAction = StarCollected isStarCollected :: OutgoingAction -> Bool isStarCollected StarCollected = True type Keydowns = Set Keysym
pmiddend/jumpie
lib/Jumpie/Types.hs
gpl-3.0
849
0
7
188
198
120
78
28
1
{-# LANGUAGE TemplateHaskell #-} module Lamdu.GUI.ExpressionEdit.HoleEdit.ShownResult ( PickedResult(..), pickedEventResult, pickedIdTranslations , ShownResult(..) ) where import qualified Control.Lens as Lens import qualified Data.Store.Transaction as Transaction import qualified Graphics.UI.Bottle.Widget as Widget import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM) type T = Transaction.Transaction data PickedResult = PickedResult { _pickedEventResult :: Widget.EventResult , _pickedIdTranslations :: Widget.Id -> Widget.Id } Lens.makeLenses ''PickedResult data ShownResult m = ShownResult { srMkEventMap :: ExprGuiM m (Widget.EventMap (T m Widget.EventResult)) , srHasHoles :: Bool , srPick :: T m PickedResult }
da-x/lamdu
Lamdu/GUI/ExpressionEdit/HoleEdit/ShownResult.hs
gpl-3.0
769
0
14
132
176
110
66
17
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.URLMaps.Insert -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a UrlMap resource in the specified project using the data -- included in the request. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.urlMaps.insert@. module Network.Google.Resource.Compute.URLMaps.Insert ( -- * REST Resource URLMapsInsertResource -- * Creating a Request , urlMapsInsert , URLMapsInsert -- * Request Lenses , umiRequestId , umiProject , umiPayload ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.urlMaps.insert@ method which the -- 'URLMapsInsert' request conforms to. type URLMapsInsertResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "urlMaps" :> QueryParam "requestId" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] URLMap :> Post '[JSON] Operation -- | Creates a UrlMap resource in the specified project using the data -- included in the request. -- -- /See:/ 'urlMapsInsert' smart constructor. data URLMapsInsert = URLMapsInsert' { _umiRequestId :: !(Maybe Text) , _umiProject :: !Text , _umiPayload :: !URLMap } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'URLMapsInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'umiRequestId' -- -- * 'umiProject' -- -- * 'umiPayload' urlMapsInsert :: Text -- ^ 'umiProject' -> URLMap -- ^ 'umiPayload' -> URLMapsInsert urlMapsInsert pUmiProject_ pUmiPayload_ = URLMapsInsert' { _umiRequestId = Nothing , _umiProject = pUmiProject_ , _umiPayload = pUmiPayload_ } -- | An optional request ID to identify requests. Specify a unique request ID -- so that if you must retry your request, the server will know to ignore -- the request if it has already been completed. For example, consider a -- situation where you make an initial request and the request times out. -- If you make the request again with the same request ID, the server can -- check if original operation with the same request ID was received, and -- if so, will ignore the second request. This prevents clients from -- accidentally creating duplicate commitments. The request ID must be a -- valid UUID with the exception that zero UUID is not supported -- (00000000-0000-0000-0000-000000000000). umiRequestId :: Lens' URLMapsInsert (Maybe Text) umiRequestId = lens _umiRequestId (\ s a -> s{_umiRequestId = a}) -- | Project ID for this request. umiProject :: Lens' URLMapsInsert Text umiProject = lens _umiProject (\ s a -> s{_umiProject = a}) -- | Multipart request metadata. umiPayload :: Lens' URLMapsInsert URLMap umiPayload = lens _umiPayload (\ s a -> s{_umiPayload = a}) instance GoogleRequest URLMapsInsert where type Rs URLMapsInsert = Operation type Scopes URLMapsInsert = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient URLMapsInsert'{..} = go _umiProject _umiRequestId (Just AltJSON) _umiPayload computeService where go = buildClient (Proxy :: Proxy URLMapsInsertResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/URLMaps/Insert.hs
mpl-2.0
4,213
0
16
955
484
292
192
74
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.TargetPools.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns the specified target pool. Get a list of available target pools -- by making a list() request. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetPools.get@. module Network.Google.Resource.Compute.TargetPools.Get ( -- * REST Resource TargetPoolsGetResource -- * Creating a Request , targetPoolsGet , TargetPoolsGet -- * Request Lenses , tpgProject , tpgTargetPool , tpgRegion ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.targetPools.get@ method which the -- 'TargetPoolsGet' request conforms to. type TargetPoolsGetResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "targetPools" :> Capture "targetPool" Text :> QueryParam "alt" AltJSON :> Get '[JSON] TargetPool -- | Returns the specified target pool. Get a list of available target pools -- by making a list() request. -- -- /See:/ 'targetPoolsGet' smart constructor. data TargetPoolsGet = TargetPoolsGet' { _tpgProject :: !Text , _tpgTargetPool :: !Text , _tpgRegion :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TargetPoolsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tpgProject' -- -- * 'tpgTargetPool' -- -- * 'tpgRegion' targetPoolsGet :: Text -- ^ 'tpgProject' -> Text -- ^ 'tpgTargetPool' -> Text -- ^ 'tpgRegion' -> TargetPoolsGet targetPoolsGet pTpgProject_ pTpgTargetPool_ pTpgRegion_ = TargetPoolsGet' { _tpgProject = pTpgProject_ , _tpgTargetPool = pTpgTargetPool_ , _tpgRegion = pTpgRegion_ } -- | Project ID for this request. tpgProject :: Lens' TargetPoolsGet Text tpgProject = lens _tpgProject (\ s a -> s{_tpgProject = a}) -- | Name of the TargetPool resource to return. tpgTargetPool :: Lens' TargetPoolsGet Text tpgTargetPool = lens _tpgTargetPool (\ s a -> s{_tpgTargetPool = a}) -- | Name of the region scoping this request. tpgRegion :: Lens' TargetPoolsGet Text tpgRegion = lens _tpgRegion (\ s a -> s{_tpgRegion = a}) instance GoogleRequest TargetPoolsGet where type Rs TargetPoolsGet = TargetPool type Scopes TargetPoolsGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient TargetPoolsGet'{..} = go _tpgProject _tpgRegion _tpgTargetPool (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy TargetPoolsGetResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/TargetPools/Get.hs
mpl-2.0
3,747
0
16
901
468
280
188
76
1
{-# LANGUAGE OverloadedStrings #-} module Core.Request.Content where import qualified Data.Attoparsec.ByteString.Lazy as AL import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy.Char8 as LS import qualified Misc.Parser as P import qualified Data.Map as M import qualified Core.Request.ContentDisposition as Cont import Control.Applicative (many) import Misc.ByteString (QueryString, splitAndDecode) import Data.Maybe (fromJust) import Data.Char (toLower) -- * Data types type Content = M.Map BS.ByteString Context data Context = MkText BS.ByteString | MkFile { filename :: Maybe BS.ByteString , contentType :: Maybe BS.ByteString , content :: BS.ByteString } deriving (Eq, Show) getBoundary :: P.Parser BS.ByteString -- ^ Parse and read the boundary getBoundary = P.string "multipart/form-data" *> P.skipSpace *> P.char ';' *> P.skipSpace *> P.string "boundary=" *> P.noneOf1 " " parseMultipart :: BS.ByteString -> P.Parser Content parseMultipart boundary = do _ <- P.string "--" <* P.string boundary <* P.string "\r\n" headers <- (M.fromList <$> many header) <* P.endOfLine (name, fname) <- case M.lookup "content-disposition" headers of Just disp -> case P.parseOnly Cont.parse disp of Right val -> return (Cont.name val, Cont.filename val) Left _ -> return (Nothing, Nothing) _ -> return (Nothing, Nothing) cont <- BS.pack <$> P.manyTill P.anyChar (P.try $ P.string "\r\n--") <* P.string boundary return $ M.fromList $ case name of Just n -> [( n , MkFile { filename = fname , contentType = M.lookup "content-type" headers , content = cont } )] Nothing -> [] where header = (,) <$> (BS.map toLower <$> (P.takeWhile P.isToken <* P.char ':' <* P.skipWhile P.isHorizontalSpace)) <*> (P.takeTill P.isEndOfLine <* P.endOfLine) fromQS :: QueryString -> Content fromQS = M.map MkText mkContent :: Maybe BS.ByteString -> LS.ByteString -> Content mkContent contType cont = case fromJust contType of "application/x-www-form-urlencoded" -> fromQS $ splitAndDecode '&' $ LS.toStrict cont x -> case P.parseOnly getBoundary x of Left _ -> M.empty Right b -> case P.parse (parseMultipart b) cont of AL.Done _ res -> res AL.Fail _ _ _ -> M.empty lookup :: BS.ByteString -> Content -> Maybe Context lookup = M.lookup
inq/manicure
src/Core/Request/Content.hs
agpl-3.0
2,419
0
17
507
804
421
383
60
4
-- | More functions on List module ListX (stripAnyPrefix) where import Data.List(stripPrefix) -- | stripAnyPrefix A b = Just (a, c) when the first a∈A that satisfies b = -- a ++ c is found, otherwise return Nothing stripAnyPrefix :: (Eq a) => [[a]] -> [a] -> Maybe ([a], [a]) stripAnyPrefix (a:as) b | Just c <- stripPrefix a b = Just (a, c) | otherwise = stripAnyPrefix as b stripAnyPrefix [] _ = Nothing
yjwen/hada
src/ListX.hs
lgpl-3.0
413
0
10
80
138
75
63
7
1
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} module MyWmii where import XMonad hiding ((|||)) import qualified XMonad.Layout.Groups as G import XMonad.Layout.Groups.Examples import XMonad.Layout.Groups.Helpers import XMonad.Layout.LayoutCombinators import XMonad.Layout.MessageControl import XMonad.Layout.Named import XMonad.Layout.Renamed import XMonad.Layout.Simplest import XMonad.Layout.Tabbed wmii s t = G.group innerLayout zoomRowG where tall = named "tall" $ Tall 0 (1/50) (1/2) tabs = named "tabs" $ Simplest full = named "full" $ Full innerLayout = id -- $ renamed [CutWordsLeft 3] $ addTabs s t $ ignore NextLayout $ ignore (JumpToLayout "") $ unEscape $ tall ||| tabs ||| full -- | Increase the width of the focused group zoomGroupIn :: X () zoomGroupIn = zoomColumnIn -- | Decrease the size of the focused group zoomGroupOut :: X () zoomGroupOut = zoomColumnOut -- | Reset the size of the focused group to the default zoomGroupReset :: X () zoomGroupReset = zoomColumnReset -- | Toggle whether the currently focused group should be maximized -- whenever it has focus. toggleGroupFull :: X () toggleGroupFull = toggleGroupFull -- | Rotate the layouts in the focused group. groupToNextLayout :: X () groupToNextLayout = sendMessage $ escape NextLayout -- | Switch the focused group to the \"maximized\" layout. groupToFullLayout :: X () groupToFullLayout = sendMessage $ escape $ JumpToLayout "Full" -- | Switch the focused group to the \"tabbed\" layout. groupToTabbedLayout :: X () groupToTabbedLayout = sendMessage $ escape $ JumpToLayout "Tabs" -- | Switch the focused group to the \"column\" layout. groupToVerticalLayout :: X () groupToVerticalLayout = sendMessage $ escape $ JumpToLayout "Column"
duckwork/dots
xmonad/lib/MyWmii.hs
unlicense
1,987
0
14
515
371
207
164
37
1
{- | Module : Cantor.Parser.Java Copyright : Copyright (C) 2014 Krzysztof Langner License : BSD3 Maintainer : Krzysztof Langner <[email protected]> Stability : alpha Portability : portable Parser for Java sources. To parse single file use: parseFile To parse all files in given directory use: parseProject -} module Cantor.Parser.Java ( parseFile ) where import Cantor.Parser.AST import Text.ParserCombinators.Parsec import Control.Monad (void) import Cantor.Utils.Folder (listFilesR) -- | Parse java source file parseFile :: FilePath -> IO (Either ParseError Package) parseFile = parseFromFile compilationUnit -- | Parse java compilation unit compilationUnit :: Parser Package compilationUnit = do skipWhitespaces val <- package skipWhitespaces imps <- importDecls return $ addImports (mkPackage val) imps -- | Parse package declaration package :: Parser String package = do skipWhitespaces option "" (packageDecl "package") -- | Parse import declaration importDecls :: Parser [ImportDecl] importDecls = many $ do x <- packageDecl "import" skipWhitespaces return $ mkImportDecl x -- | Parse package declaration -- keyword com.abc.ef packageDecl :: String -> Parser String packageDecl keyword = do _ <- string keyword skipMany1 space name <- pkgName spaces _ <- char ';' return name where pkgName = many1 (alphaNum <|> char '.' <|> char '*') -- | skip comments and spaces skipWhitespaces :: Parser () skipWhitespaces = skipMany $ void comment <|> skipMany1 (oneOf " \n\r\t") -- | comment comment :: Parser String comment = try multiLineComment <|> singleLineComment -- | Parse comment /* */ multiLineComment :: Parser String multiLineComment = do _ <- string "/*" manyTill anyChar (try (string "*/")) -- | Parse comment // singleLineComment :: Parser String singleLineComment = do _ <- string "//" many (noneOf "\n")
klangner/cantor
src/Cantor/Parser/Java.hs
bsd-2-clause
1,989
0
11
438
430
213
217
45
1
import "hint" HLint.Default import "hint" HLint.Dollar ignore "Use fewer imports" ignore "Use ."
konn/hskk
HLint.hs
bsd-3-clause
98
0
5
14
25
12
13
-1
-1
module Abstract.Impl.Libs.Counter.MVar.Dec ( module Abstract.Interfaces.Counter.Dec, mkCounter'MVar'Dec ) where import Abstract.Interfaces.Counter.Dec import qualified Abstract.Impl.Libs.Counter.MVar.Internal as MVAR (mkCounter'MVar) mkCounter'MVar'Dec t = do v <- MVAR.mkCounter'MVar t return $ counterToDec v
adarqui/Abstract-Impl-Libs
src/Abstract/Impl/Libs/Counter/MVar/Dec.hs
bsd-3-clause
318
0
9
35
77
48
29
8
1
-- -- Copyright © 2013-2014 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. -- {-# LANGUAGE OverloadedStrings #-} module Sieste.Util where import Control.Applicative import Data.Aeson import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy as LB import Data.ByteString.Lazy.Builder (Builder, stringUtf8, toLazyByteString) import Data.Text (Text) import Data.Text.Encoding (decodeUtf8') import Data.Text.Lazy.Encoding (decodeUtf8) import Data.Word (Word64) import Pipes import qualified Pipes.Prelude as Pipes import Sieste.Types.Util import Snap.Core import System.Clock (Clock (..), getTime, nsec, sec) fromEpoch :: Int -> Word64 fromEpoch = fromIntegral . (* 1000000000) toEpoch :: Word64 -> Int toEpoch = fromIntegral . (`div` 1000000000) writeJSON :: ToJSON a => a -> Snap () writeJSON a = do modifyResponse $ setContentType "application/json" writeLBS $ encode $ toJSON a writeError :: Int -> Builder -> Snap a writeError code builder = do let pretty = PrettyError $ decodeUtf8 $ toLazyByteString builder modifyResponse $ setResponseCode code writeJSON pretty getResponse >>= finishWith logException :: Show a => a -> Snap () logException = logError . B.pack . show orFail :: Bool -> String -> Snap () orFail True _ = return () orFail False msg = writeError 400 $ stringUtf8 msg utf8Or400 :: ByteString -> Snap Text utf8Or400 = either conversionError return . decodeUtf8' where conversionError _ = writeError 400 $ stringUtf8 "Invalid UTF-8 in request" timeNow :: MonadIO m => m Word64 timeNow = liftIO $ fmap fromIntegral $ (+) <$> ((1000000000*) . sec) <*> nsec <$> getTime Realtime toInt :: Integral a => ByteString -> a toInt bs = maybe 0 (fromIntegral . fst) (B.readInteger bs) validateW64 :: (Word64 -> Bool) -- ^ function to check if user's value is OK -> String -- ^ error message if it is not okay -> Snap Word64 -- ^ action to retrieve default value -> Maybe ByteString -- ^ possible user input -> Snap Word64 validateW64 check error_msg def user_input = case user_input of Just bs -> do let parsed = fromEpoch $ toInt bs check parsed `orFail` error_msg return parsed Nothing -> def -- Useful pipes follow jsonEncode :: (Monad m, ToJSON j) => Pipe j LB.ByteString m () jsonEncode = Pipes.map (encode . toJSON) -- We want to prepend all but the first burst with a comma. addCommas :: Monad m => Bool -> Pipe LB.ByteString LB.ByteString m () addCommas is_first | is_first = await >>= yield >> addCommas False | otherwise = do burst <- await yield $ LB.append "," burst addCommas False
anchor/sieste
src/Sieste/Util.hs
bsd-3-clause
2,979
0
14
655
819
432
387
65
2
-- | Non-crossing partitions. -- -- See eg. <http://en.wikipedia.org/wiki/Noncrossing_partition> -- -- Non-crossing partitions of the set @[1..n]@ are encoded as lists of lists -- in standard form: Entries decreasing in each block and blocks listed in increasing order of their first entries. -- For example the partition in the diagram -- -- <<svg/noncrossing.svg>> -- -- is represented as -- -- > NonCrossing [[3],[5,4,2],[7,6,1],[9,8]] -- {-# LANGUAGE BangPatterns #-} module Math.Combinat.Partitions.NonCrossing where -------------------------------------------------------------------------------- import Control.Applicative import Data.List import Data.Ord import System.Random import Math.Combinat.Numbers import Math.Combinat.LatticePaths import Math.Combinat.Helper import Math.Combinat.Partitions.Set import Math.Combinat.Partitions ( HasNumberOfParts(..) ) -------------------------------------------------------------------------------- -- * The type of non-crossing partitions -- | A non-crossing partition of the set @[1..n]@ in standard form: -- entries decreasing in each block and blocks listed in increasing order of their first entries. newtype NonCrossing = NonCrossing [[Int]] deriving (Eq,Ord,Show,Read) -- | Checks whether a set partition is noncrossing. -- -- Implementation method: we convert to a Dyck path and then back again, and finally compare. -- Probably not very efficient, but should be better than a naive check for crosses...) -- _isNonCrossing :: [[Int]] -> Bool _isNonCrossing zzs0 = _isNonCrossingUnsafe (_standardizeNonCrossing zzs0) -- | Warning: This function assumes the standard ordering! _isNonCrossingUnsafe :: [[Int]] -> Bool _isNonCrossingUnsafe zzs = case _nonCrossingPartitionToDyckPathMaybe zzs of Nothing -> False Just dyck -> case dyckPathToNonCrossingPartitionMaybe dyck of Nothing -> False Just (NonCrossing yys) -> yys == zzs -- | Convert to standard form: entries decreasing in each block -- and blocks listed in increasing order of their first entries. _standardizeNonCrossing :: [[Int]] -> [[Int]] _standardizeNonCrossing = sortBy (comparing myhead) . map reverseSort where myhead xs = case xs of (x:xs) -> x [] -> error "_standardizeNonCrossing: empty subset" fromNonCrossing :: NonCrossing -> [[Int]] fromNonCrossing (NonCrossing xs) = xs toNonCrossingUnsafe :: [[Int]] -> NonCrossing toNonCrossingUnsafe = NonCrossing -- | Throws an error if the input is not a non-crossing partition toNonCrossing :: [[Int]] -> NonCrossing toNonCrossing xxs = case toNonCrossingMaybe xxs of Just nc -> nc Nothing -> error "toNonCrossing: not a non-crossing partition" toNonCrossingMaybe :: [[Int]] -> Maybe NonCrossing toNonCrossingMaybe xxs0 = if _isNonCrossingUnsafe xxs then Just $ NonCrossing xxs else Nothing where xxs = _standardizeNonCrossing xxs0 -- | If a set partition is actually non-crossing, then we can convert it setPartitionToNonCrossing :: SetPartition -> Maybe NonCrossing setPartitionToNonCrossing (SetPartition zzs0) = if _isNonCrossingUnsafe zzs then Just $ NonCrossing zzs else Nothing where zzs = _standardizeNonCrossing zzs0 instance HasNumberOfParts NonCrossing where numberOfParts (NonCrossing p) = length p -------------------------------------------------------------------------------- -- * Bijection to Dyck paths -- | Bijection between Dyck paths and noncrossing partitions -- -- Based on: David Callan: /Sets, Lists and Noncrossing Partitions/ -- -- Fails if the input is not a Dyck path. dyckPathToNonCrossingPartition :: LatticePath -> NonCrossing dyckPathToNonCrossingPartition = NonCrossing . go 0 [] [] [] where go :: Int -> [Int] -> [Int] -> [[Int]] -> LatticePath -> [[Int]] go !cnt stack small big path = case path of (x:xs) -> case x of UpStep -> let cnt' = cnt + 1 in case xs of (y:ys) -> case y of UpStep -> go cnt' (cnt':stack) small big xs DownStep -> go cnt' (cnt':stack) [] (reverse small : big) xs [] -> error "dyckPathToNonCrossingPartition: last step is an UpStep (thus input was not a Dyck path)" DownStep -> case stack of (k:ks) -> go cnt ks (k:small) big xs [] -> error "dyckPathToNonCrossingPartition: empty stack, shouldn't happen (thus input was not a Dyck path)" [] -> tail $ reverse (reverse small : big) -- | Safe version of 'dyckPathToNonCrossingPartition' dyckPathToNonCrossingPartitionMaybe :: LatticePath -> Maybe NonCrossing dyckPathToNonCrossingPartitionMaybe = fmap NonCrossing . go 0 [] [] [] where go :: Int -> [Int] -> [Int] -> [[Int]] -> LatticePath -> Maybe [[Int]] go !cnt stack small big path = case path of (x:xs) -> case x of UpStep -> let cnt' = cnt + 1 in case xs of (y:ys) -> case y of UpStep -> go cnt' (cnt':stack) small big xs DownStep -> go cnt' (cnt':stack) [] (reverse small : big) xs [] -> Nothing DownStep -> case stack of (k:ks) -> go cnt ks (k:small) big xs [] -> Nothing [] -> Just $ tail $ reverse (reverse small : big) -- | The inverse bijection (should never fail proper 'NonCrossing'-s) nonCrossingPartitionToDyckPath :: NonCrossing -> LatticePath nonCrossingPartitionToDyckPath (NonCrossing zzs) = go 0 zzs where go !k (ys@(y:_):yys) = replicate (y-k) UpStep ++ replicate (length ys) DownStep ++ go y yys go !k [] = [] go _ _ = error "nonCrossingPartitionToDyckPath: shouldnt't happen" -- | Safe version 'nonCrossingPartitionToDyckPath' _nonCrossingPartitionToDyckPathMaybe :: [[Int]] -> Maybe LatticePath _nonCrossingPartitionToDyckPathMaybe = go 0 where go !k (ys@(y:_):yys) = fmap (\zs -> replicate (y-k) UpStep ++ replicate (length ys) DownStep ++ zs) (go y yys) go !k [] = Just [] go _ _ = Nothing -------------------------------------------------------------------------------- {- -- this should be mapped to NonCrossing [[3],[5,4,2],[7,6,1],[9,8]] testpath = [u,u,u,d,u,u,d,d,d,u,u,d,d,d,u,u,d,d] where u = UpStep d = DownStep testnc = NonCrossing [[3],[5,4,2],[7,6,1],[9,8]] -} -------------------------------------------------------------------------------- -- * Generating non-crossing partitions -- | Lists all non-crossing partitions of @[1..n]@ -- -- Equivalent to (but orders of magnitude faster than) filtering out the non-crossing ones: -- -- > (sort $ catMaybes $ map setPartitionToNonCrossing $ setPartitions n) == sort (nonCrossingPartitions n) -- nonCrossingPartitions :: Int -> [NonCrossing] nonCrossingPartitions = map dyckPathToNonCrossingPartition . dyckPaths -- | Lists all non-crossing partitions of @[1..n]@ into @k@ parts. -- -- > sort (nonCrossingPartitionsWithKParts k n) == sort [ p | p <- nonCrossingPartitions n , numberOfParts p == k ] -- nonCrossingPartitionsWithKParts :: Int -- ^ @k@ = number of parts -> Int -- ^ @n@ = size of the set -> [NonCrossing] nonCrossingPartitionsWithKParts k n = map dyckPathToNonCrossingPartition $ peakingDyckPaths k n -- | Non-crossing partitions are counted by the Catalan numbers countNonCrossingPartitions :: Int -> Integer countNonCrossingPartitions = countDyckPaths -- | Non-crossing partitions with @k@ parts are counted by the Naranaya numbers countNonCrossingPartitionsWithKParts :: Int -- ^ @k@ = number of parts -> Int -- ^ @n@ = size of the set -> Integer countNonCrossingPartitionsWithKParts = countPeakingDyckPaths -------------------------------------------------------------------------------- -- | Uniformly random non-crossing partition randomNonCrossingPartition :: RandomGen g => Int -> g -> (NonCrossing,g) randomNonCrossingPartition n g0 = (dyckPathToNonCrossingPartition dyck, g1) where (dyck,g1) = randomDyckPath n g0 --------------------------------------------------------------------------------
chadbrewbaker/combinat
Math/Combinat/Partitions/NonCrossing.hs
bsd-3-clause
8,253
6
26
1,752
1,570
855
715
105
6
-- | Description: Shared types and functions module Utilities where import Data.Set (Set) import qualified Data.Set as S type Nat = Int type Error = String class Variable v where newVar :: Set v -> v newtype IntVar = IntVar { unpackIntVar :: Int } deriving (Ord, Eq) instance Show IntVar where show = show . unpackIntVar instance Read IntVar where readsPrec _ = \s -> lol <$> reads s where lol (v, vs) = (IntVar v, vs) instance Variable IntVar where newVar s = let (IntVar m) = maximum . S.toList $ s in IntVar (m+1)
thsutton/type-assignment
lib/Utilities.hs
bsd-3-clause
572
0
12
152
204
112
92
18
0
{-# LANGUAGE CPP , GADTs , EmptyCase , KindSignatures , DataKinds , PolyKinds , TypeOperators , ScopedTypeVariables , Rank2Types , MultiParamTypeClasses , TypeSynonymInstances , FlexibleInstances , FlexibleContexts , UndecidableInstances #-} {-# OPTIONS_GHC -Wall -fwarn-tabs #-} ---------------------------------------------------------------- -- 2016.06.29 -- | -- Module : Language.Hakaru.Disintegrate -- Copyright : Copyright (c) 2016 the Hakaru team -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC-only -- -- Disintegration via lazy partial evaluation. -- -- N.B., the forward direction of disintegration is /not/ just -- partial evaluation! In the version discussed in the paper we -- must also ensure that no heap-bound variables occur in the result, -- which requires using HNFs rather than WHNFs. That condition is -- sound, but a bit too strict; we could generalize this to handle -- cases where there may be heap-bound variables remaining in neutral -- terms, provided we (a) don't end up trying to go both forward -- and backward on the same variable, and (more importantly) (b) -- end up with the proper Jacobian. The paper version is rigged to -- ensure that whenever we recurse into two subexpressions (e.g., -- the arguments to addition) one of them has a Jacobian of zero, -- thus when going from @x*y@ to @dx*y + x*dy@ one of the terms -- cancels out. -- -- /Developer's Note:/ To help keep the code clean, we use the -- worker\/wrapper transform. However, due to complexities in -- typechecking GADTs, this often confuses GHC if you don't give -- just the right type signature on definitions. This confusion -- shows up whenever you get error messages about an \"ambiguous\" -- choice of 'ABT' instance, or certain types of \"couldn't match -- @a@ with @a1@\" error messages. To eliminate these issues we use -- @-XScopedTypeVariables@. In particular, the @abt@ type variable -- must be bound by the wrapper (i.e., the top-level definition), -- and the workers should just refer to that same type variable -- rather than quantifying over abother @abt@ type. In addition, -- whatever other type variables there are (e.g., the @xs@ and @a@ -- of an @abt xs a@ argument) should be polymorphic in the workers -- and should /not/ reuse the other analogous type variables bound -- by the wrapper. -- -- /Developer's Note:/ In general, we'd like to emit weights and -- guards \"as early as possible\"; however, determining when that -- actually is can be tricky. If we emit them way-too-early then -- we'll get hygiene errors because bindings for the variables they -- use have not yet been emitted. We can fix these hygiene erors -- by calling 'atomize', to ensure that all the necessary bindings -- have already been emitted. But that may still emit things too -- early, because emitting th variable-binding statements now means -- that we can't go forward\/backward on them later on; which may -- cause us to bot unnecessarily. One way to avoid this bot issue -- is to emit guards\/weights later than necessary, by actually -- pushing them onto the context (and then emitting them whenever -- we residualize the context). This guarantees we don't emit too -- early; but the tradeoff is we may end up generating duplicate -- code by emitting too late. One possible (currently unimplemented) -- solution to that code duplication issue is to let these statements -- be emitted too late, but then have a post-processing step to -- lift guards\/weights up as high as they can go. To avoid problems -- about testing programs\/expressions for equality, we can use a -- hash-consing trick so we keep track of the identity of guard\/weight -- statements, then we can simply compare those identities and only -- after the lifting do we replace the identity hash with the actual -- statement. ---------------------------------------------------------------- module Language.Hakaru.Disintegrate ( -- * the Hakaru API disintegrateWithVar , disintegrate , densityWithVar , density , observe , determine -- * Implementation details , perform , atomize , constrainValue , constrainOutcome ) where #if __GLASGOW_HASKELL__ < 710 import Data.Functor ((<$>)) import Data.Foldable (Foldable, foldMap) import Data.Traversable (Traversable) import Control.Applicative (Applicative(..)) #endif import Control.Applicative (Alternative(..)) import Control.Monad ((<=<), guard) import Data.Functor.Compose (Compose(..)) import qualified Data.Traversable as T import Data.List.NonEmpty (NonEmpty(..)) import qualified Data.List.NonEmpty as L import qualified Data.Text as Text import qualified Data.IntMap as IM import Data.Sequence (Seq) import qualified Data.Sequence as S import Data.Proxy (KProxy(..)) import Data.Maybe (fromMaybe, fromJust) import Language.Hakaru.Syntax.IClasses import Data.Number.Natural import Language.Hakaru.Types.DataKind import Language.Hakaru.Types.Sing import qualified Language.Hakaru.Types.Coercion as C import Language.Hakaru.Types.HClasses import Language.Hakaru.Syntax.TypeOf import Language.Hakaru.Syntax.AST import Language.Hakaru.Syntax.Datum import Language.Hakaru.Syntax.DatumCase (DatumEvaluator, MatchResult(..), matchBranches) import Language.Hakaru.Syntax.ABT import Language.Hakaru.Evaluation.Types import Language.Hakaru.Evaluation.Lazy import Language.Hakaru.Evaluation.DisintegrationMonad import qualified Language.Hakaru.Syntax.Prelude as P import qualified Language.Hakaru.Expect as E #ifdef __TRACE_DISINTEGRATE__ import qualified Text.PrettyPrint as PP import Language.Hakaru.Pretty.Haskell import Debug.Trace (trace, traceM) #endif ---------------------------------------------------------------- lam_ :: (ABT Term abt) => Variable a -> abt '[] b -> abt '[] (a ':-> b) lam_ x e = syn (Lam_ :$ bind x e :* End) -- | Disintegrate a measure over pairs with respect to the lebesgue -- measure on the first component. That is, for each measure kernel -- @n <- disintegrate m@ we have that @m == bindx lebesgue n@. The -- first two arguments give the hint and type of the lambda-bound -- variable in the result. If you want to automatically fill those -- in, then see 'disintegrate'. -- -- N.B., the resulting functions from @a@ to @'HMeasure b@ are -- indeed measurable, thus it is safe\/appropriate to use Hakaru's -- @(':->)@ rather than Haskell's @(->)@. -- -- BUG: Actually, disintegration is with respect to the /Borel/ -- measure on the first component of the pair! Alas, we don't really -- have a clean way of describing this since we've no primitive -- 'MeasureOp' for Borel measures. -- -- /Developer's Note:/ This function fills the role that the old -- @runDisintegrate@ did (as opposed to the old function called -- @disintegrate@). [Once people are familiar enough with the new -- code base and no longer recall what the old code base was doing, -- this note should be deleted.] disintegrateWithVar :: (ABT Term abt) => Text.Text -> Sing a -> abt '[] ('HMeasure (HPair a b)) -> [abt '[] (a ':-> 'HMeasure b)] disintegrateWithVar hint typ m = let x = Variable hint (nextFreeOrBind m) typ in map (lam_ x) . flip runDis [Some2 m, Some2 (var x)] $ do ab <- perform m #ifdef __TRACE_DISINTEGRATE__ ss <- getStatements trace ("-- disintegrate: finished perform\n" ++ show (pretty_Statements ss PP.$+$ PP.sep(prettyPrec_ 11 ab)) ++ "\n") $ return () #endif -- BUG: Why does 'testDisintegrate1a' return no solutions? -- -- In older code (up to git#38889a5): It's because 'emitUnpair' -- isn't quite smart enough. When the @ab@ expression is a -- 'Neutral' case expression, we need to go underneath the -- case expression and call 'constrainValue' on each branch. -- Instead, what we currently do is emit an @unpair@ case -- statement with the scrutinee being the 'Neutral' case -- expression, and then just return the pair of variables -- bound by the emitted @unpair@; but, of course, -- 'constrainValue' can't do anything with those variables -- (since they appear to be free, given as they've already -- been emitted). Another way to think about what it is we -- need to do to correct this is that we need to perform -- the case-of-case transformation (where one of the cases -- is the 'Neutral' one, and the other is the @unpair@). -- -- In newer code (git#e8a0c66 and later): When we call 'perform' -- on an 'SBind' statement we emit some code and update the -- binding to become an 'SLet' of some local variable to -- the emitted variable. Later on when we call 'constrainVariable' -- on the local variable, we will look that 'SLet' statement -- up; and then when we call 'constrainVariable' on the -- emitted variable, things will @bot@ because we cannot -- constrain free variables in general. (a,b) <- emitUnpair ab #ifdef __TRACE_DISINTEGRATE__ trace ("-- disintegrate: finished emitUnpair: " ++ show (pretty a, pretty b)) $ return () #endif constrainValue (var x) a #ifdef __TRACE_DISINTEGRATE__ ss <- getStatements extras <- getExtras traceM ("-- disintegrate: finished constrainValue\n" ++ show (pretty_Statements ss) ++ "\n" ++ show (prettyExtras extras) ) #endif return b -- | A variant of 'disintegrateWithVar' which automatically computes -- the type via 'typeOf'. disintegrate :: (ABT Term abt) => abt '[] ('HMeasure (HPair a b)) -> [abt '[] (a ':-> 'HMeasure b)] disintegrate m = disintegrateWithVar Text.empty (fst . sUnPair . sUnMeasure $ typeOf m) -- TODO: change the exception thrown form 'typeOf' so that we know it comes from here m -- | Return the density function for a given measure. The first two -- arguments give the hint and type of the lambda-bound variable -- in the result. If you want to automatically fill those in, then -- see 'density'. -- -- TODO: is the resulting function guaranteed to be measurable? If -- so, update this documentation to reflect that fact; if not, then -- we should make it into a Haskell function instead. densityWithVar :: (ABT Term abt) => Text.Text -> Sing a -> abt '[] ('HMeasure a) -> [abt '[] (a ':-> 'HProb)] densityWithVar hint typ m = let x = Variable hint (nextFree m `max` nextBind m) typ in (lam_ x . E.total) <$> observe m (var x) -- | A variant of 'densityWithVar' which automatically computes the -- type via 'typeOf'. density :: (ABT Term abt) => abt '[] ('HMeasure a) -> [abt '[] (a ':-> 'HProb)] density m = densityWithVar Text.empty (sUnMeasure $ typeOf m) m -- | Constrain a measure such that it must return the observed -- value. In other words, the resulting measure returns the observed -- value with weight according to its density in the original -- measure, and gives all other values weight zero. observe :: (ABT Term abt) => abt '[] ('HMeasure a) -> abt '[] a -> [abt '[] ('HMeasure a)] observe m x = runDis (constrainOutcome x m >> return x) [Some2 m, Some2 x] -- | Arbitrarily choose one of the possible alternatives. In the -- future, this function should be replaced by a better one that -- takes some sort of strategy for deciding which alternative to -- choose. determine :: (ABT Term abt) => [abt '[] a] -> Maybe (abt '[] a) determine [] = Nothing determine (m:_) = Just m ---------------------------------------------------------------- ---------------------------------------------------------------- firstM :: Functor f => (a -> f b) -> (a,c) -> f (b,c) firstM f (x,y) = (\z -> (z, y)) <$> f x -- N.B., forward disintegration is not identical to partial evaluation, -- as noted at the top of the file. For correctness we need to -- ensure the result is emissible (i.e., has no heap-bound variables). -- More specifically, we need to ensure emissibility in the places -- where we call 'emitMBind' evaluate_ :: (ABT Term abt) => TermEvaluator abt (Dis abt) evaluate_ = evaluate perform evaluateDatum :: (ABT Term abt) => DatumEvaluator (abt '[]) (Dis abt) evaluateDatum e = viewWhnfDatum <$> evaluate_ e -- | Simulate performing 'HMeasure' actions by simply emitting code -- for those actions, returning the bound variable. -- -- This is the function called @(|>>)@ in the disintegration paper. perform :: forall abt. (ABT Term abt) => MeasureEvaluator abt (Dis abt) perform = \e0 -> #ifdef __TRACE_DISINTEGRATE__ getStatements >>= \ss -> getExtras >>= \extras -> getIndices >>= \inds -> trace ("\n-- perform --\n" ++ "at " ++ show (ppInds inds) ++ "\n" ++ show (prettyExtras extras) ++ "\n" ++ show (pretty_Statements_withTerm ss e0) ++ "\n") $ #endif caseVarSyn e0 performVar performTerm where performTerm :: forall a. Term abt ('HMeasure a) -> Dis abt (Whnf abt a) performTerm (Dirac :$ e1 :* End) = evaluate_ e1 performTerm (MeasureOp_ o :$ es) = performMeasureOp o es performTerm (MBind :$ e1 :* e2 :* End) = caseBind e2 $ \x e2' -> do inds <- getIndices push (SBind x (Thunk e1) inds) e2' >>= perform performTerm (Plate :$ e1 :* e2 :* End) = do x1 <- pushPlate e1 e2 return $ fromJust (toWhnf x1) performTerm (Superpose_ pes) = do inds <- getIndices if not (null inds) && L.length pes > 1 then bot else emitFork_ (P.superpose . fmap ((,) P.one)) (fmap (\(p,e) -> push (SWeight (Thunk p) inds) e >>= perform) pes) -- Avoid falling through to the @performWhnf <=< evaluate_@ case performTerm (Let_ :$ e1 :* e2 :* End) = caseBind e2 $ \x e2' -> do inds <- getIndices push (SLet x (Thunk e1) inds) e2' >>= perform -- TODO: we could optimize this by calling some @evaluateTerm@ -- directly, rather than calling 'syn' to rebuild @e0@ from -- @t0@ and then calling 'evaluate_' (which will just use -- 'caseVarSyn' to get the @t0@ back out from the @e0@). -- -- BUG: when @t0@ is a 'Case_', this doesn't work right. This -- is the source of the hygiene bug in 'testPerform1b'. Alas, -- we cannot use 'emitCaseWith' here since that would require -- the scrutinee to be emissible; but we'd want something pretty -- similar... performTerm t0 = do w <- evaluate_ (syn t0) #ifdef __TRACE_DISINTEGRATE__ trace ("-- perform: finished evaluate, with:\n" ++ show (PP.sep(prettyPrec_ 11 w))) $ return () #endif performWhnf w performVar :: forall a. Variable ('HMeasure a) -> Dis abt (Whnf abt a) performVar = performWhnf <=< evaluateVar perform evaluate_ -- BUG: it's not clear this is actually doing the right thing for its call-sites. In particular, we should handle 'Case_' specially, to deal with the hygiene bug in 'testPerform1b'... -- -- BUG: found the 'testPerform1b' hygiene bug! We can't simply call 'emitMBind' on @e@, because @e@ may not be emissible! performWhnf :: forall a. Whnf abt ('HMeasure a) -> Dis abt (Whnf abt a) performWhnf (Head_ v) = perform $ fromHead v performWhnf (Neutral e) = (Neutral . var) <$> emitMBind e -- TODO: right now we do the simplest thing. However, for better -- coverage and cleaner produced code we'll need to handle each -- of the ops separately. (For example, see how 'Uniform' is -- handled in the old code; how it has two options for what to -- do.) performMeasureOp :: forall typs args a . (typs ~ UnLCs args, args ~ LCs typs) => MeasureOp typs a -> SArgs abt args -> Dis abt (Whnf abt a) performMeasureOp = \o es -> nice o es <|> complete o es where -- Try to generate nice pretty output. nice :: MeasureOp typs a -> SArgs abt args -> Dis abt (Whnf abt a) nice o es = do es' <- traverse21 atomizeCore es x <- emitMBind2 $ syn (MeasureOp_ o :$ es') -- return (Neutral $ var x) return (Neutral x) -- Try to be as complete as possible (i.e., 'bot' as little as possible), no matter how ugly the output code gets. complete :: MeasureOp typs a -> SArgs abt args -> Dis abt (Whnf abt a) complete Normal = \(mu :* sd :* End) -> do x <- var <$> emitMBind P.lebesgue pushWeight (P.densityNormal mu sd x) return (Neutral x) complete Uniform = \(lo :* hi :* End) -> do x <- var <$> emitMBind P.lebesgue pushGuard (lo P.< x P.&& x P.< hi) pushWeight (P.densityUniform lo hi x) return (Neutral x) complete _ = \_ -> bot -- Calls unsafePush pushWeight :: (ABT Term abt) => abt '[] 'HProb -> Dis abt () pushWeight w = do inds <- getIndices unsafePush $ SWeight (Thunk w) inds -- Calls unsafePush pushGuard :: (ABT Term abt) => abt '[] HBool -> Dis abt () pushGuard b = do inds <- getIndices unsafePush $ SGuard Nil1 pTrue (Thunk b) inds -- | The goal of this function is to ensure the correctness criterion -- that given any term to be emitted, the resulting term is -- semantically equivalent but contains no heap-bound variables. -- That correctness criterion is necessary to ensure hygiene\/scoping. -- -- This particular implementation calls 'evaluate' recursively, -- giving us something similar to full-beta reduction. However, -- that is considered an implementation detail rather than part of -- the specification of what the function should do. Also, it's a -- gross hack and prolly a big part of why we keep running into -- infinite looping issues. -- -- This name is taken from the old finally tagless code, where -- \"atomic\" terms are (among other things) emissible; i.e., contain -- no heap-bound variables. -- -- BUG: this function infinitely loops in certain circumstances -- (namely when dealing with neutral terms) atomize :: (ABT Term abt) => TermEvaluator abt (Dis abt) atomize e = #ifdef __TRACE_DISINTEGRATE__ trace ("\n-- atomize --\n" ++ show (pretty e)) $ #endif traverse21 atomizeCore =<< evaluate_ e -- | A variant of 'atomize' which is polymorphic in the locally -- bound variables @xs@ (whereas 'atomize' requires @xs ~ '[]@). -- We factored this out because we often want this more polymorphic -- variant when using our indexed @TraversableMN@ classes. atomizeCore :: (ABT Term abt) => abt xs a -> Dis abt (abt xs a) atomizeCore e = do -- HACK: this check for 'disjointVarSet' is sufficient to catch -- the particular infinite loops we were encountering, but it -- will not catch all of them. If the call to 'evaluate_' in -- 'atomize' returns a neutral term which contains heap-bound -- variables, then we'll still loop forever since we don't -- traverse\/fmap over the top-level term constructor of neutral -- terms. xs <- getHeapVars if disjointVarSet xs (freeVars e) then return e else let (ys, e') = caseBinds e in (binds_ ys . fromWhnf) <$> atomize e' where -- TODO: does @IM.null . IM.intersection@ fuse correctly? disjointVarSet xs ys = IM.null (IM.intersection (unVarSet xs) (unVarSet ys)) -- HACK: if we really want to go through with this approach, then -- we should memoize the set of heap-bound variables in the -- 'ListContext' itself rather than recomputing it every time! getHeapVars :: Dis abt (VarSet ('KProxy :: KProxy Hakaru)) getHeapVars = Dis $ \_ c h -> c (foldMap statementVars (statements h)) h ---------------------------------------------------------------- isLitBool :: (ABT Term abt) => abt '[] a -> Maybe (Datum (abt '[]) HBool) isLitBool e = caseVarSyn e (const Nothing) $ \b -> case b of Datum_ d@(Datum _ typ _) -> case (jmEq1 typ sBool) of Just Refl -> Just d Nothing -> Nothing _ -> Nothing isLitTrue :: (ABT Term abt) => Datum (abt '[]) HBool -> Bool isLitTrue (Datum tdTrue sBool (Inl Done)) = True isLitTrue _ = False isLitFalse :: (ABT Term abt) => Datum (abt '[]) HBool -> Bool isLitFalse (Datum tdFalse sBool (Inr (Inl Done))) = True isLitFalse _ = False ---------------------------------------------------------------- -- | Given an emissible term @v0@ (the first argument) and another -- term @e0@ (the second argument), compute the constraints such -- that @e0@ must evaluate to @v0@. This is the function called -- @(<|)@ in the disintegration paper, though notably we swap the -- argument order so that the \"value\" is the first argument. -- -- N.B., this function assumes (and does not verify) that the first -- argument is emissible. So callers (including recursive calls) -- must guarantee this invariant, by calling 'atomize' as necessary. -- -- TODO: capture the emissibility requirement on the first argument -- in the types, to help avoid accidentally passing the arguments -- in the wrong order! constrainValue :: (ABT Term abt) => abt '[] a -> abt '[] a -> Dis abt () constrainValue v0 e0 = #ifdef __TRACE_DISINTEGRATE__ getStatements >>= \ss -> getExtras >>= \extras -> getIndices >>= \inds -> trace ("\n-- constrainValue: " ++ show (pretty v0) ++ "\n" ++ show (pretty_Statements_withTerm ss e0) ++ "\n" ++ "at " ++ show (ppInds inds) ++ "\n" ++ show (prettyExtras extras) ++ "\n" ) $ #endif caseVarSyn e0 (constrainVariable v0) $ \t -> case t of -- There's a bunch of stuff we don't even bother trying to handle Empty_ _ -> error "TODO: disintegrate empty arrays" Array_ n e -> caseBind e $ \x body -> do j <- freshInd n let x' = indVar j body' <- extSubst x (var x') body inds <- getIndices withIndices (extendIndices j inds) $ constrainValue (v0 P.! (var x')) body' -- TODO use meta-index ArrayLiteral_ _ -> error "TODO: disintegrate literal arrays" ArrayOp_ o@(Index _) :$ args@(e1 :* e2 :* End) -> do w1 <- evaluate_ e1 case w1 of Neutral e1' -> bot Head_ (WArray _ b) -> caseBind b $ \x body -> extSubst x e2 body >>= constrainValue v0 Head_ (WEmpty _) -> bot -- TODO: check this -- Special case for [true,false] ! i, and [false, true] ! i -- This helps us disintegrate bern Head_ (WArrayLiteral [a1,a2]) -> case (jmEq1 (typeOf v0) sBool) of Just Refl -> let constrainInd = flip constrainValue e2 in case (isLitBool a1, isLitBool a2) of (Just b1, Just b2) | isLitTrue b1 && isLitFalse b2 -> constrainInd $ P.if_ v0 (P.nat_ 0) (P.nat_ 1) | isLitTrue b2 && isLitFalse b1 -> constrainInd $ P.if_ v0 (P.nat_ 1) (P.nat_ 0) | otherwise -> error "constrainValue: cannot invert (Index [b,b] i)" _ -> error "TODO: constrainValue (Index [b1,b2] i)" Nothing -> error "TODO: constrainValue (Index [a1,a2] i)" Head_ (WArrayLiteral _) -> bot _ -> error "constrainValue {ArrayOp Index}: uknown whnf of array type" ArrayOp_ _ :$ _ -> error "TODO: disintegrate non-Index arrayOps" Lam_ :$ _ :* End -> error "TODO: disintegrate lambdas" App_ :$ _ :* _ :* End -> error "TODO: disintegrate lambdas" Integrate :$ _ :* _ :* _ :* End -> error "TODO: disintegrate integration" Summate _ _ :$ _ :* _ :* _ :* End -> error "TODO: disintegrate integration" -- N.B., the semantically correct definition is: -- -- > Literal_ v -- > | "dirac v has a density wrt the ambient measure" -> ... -- > | otherwise -> bot -- -- For the case where the ambient measure is Lebesgue, dirac -- doesn't have a density, so we return 'bot'. However, we -- will need to generalize this when we start handling other -- ambient measures. Literal_ v -> bot -- unsolvable. (kinda; see note) Datum_ d -> constrainDatum v0 d Dirac :$ _ :* End -> bot -- giving up. MBind :$ _ :* _ :* End -> bot -- giving up. MeasureOp_ o :$ es -> constrainValueMeasureOp v0 o es Superpose_ pes -> bot -- giving up. Reject_ _ -> bot -- giving up. Let_ :$ e1 :* e2 :* End -> caseBind e2 $ \x e2' -> push (SLet x (Thunk e1) []) e2' >>= constrainValue v0 CoerceTo_ c :$ e1 :* End -> -- TODO: we need to insert some kind of guard that says -- @v0@ is in the range of @coerceTo c@, or equivalently -- that @unsafeFrom c v0@ will always succeed. We need -- to emit this guard (for correctness of the generated -- program) because if @v0@ isn't in the range of the -- coercion, then there's no possible way the program -- @e1@ could in fact be observed at @v0@. The only -- question is how to perform that check; for the -- 'Signed' coercions it's easy enough, but for the -- 'Continuous' coercions it's not really clear. constrainValue (P.unsafeFrom_ c v0) e1 UnsafeFrom_ c :$ e1 :* End -> -- TODO: to avoid returning garbage, we'd need to place -- some constraint on @e1@ so that if the original -- program would've crashed due to a bad unsafe-coercion, -- then we won't return a disintegrated program (since -- it too should always crash). Avoiding this check is -- sound (i.e., if the input program is well-formed -- then the output program is a well-formed disintegration), -- it just overgeneralizes. constrainValue (P.coerceTo_ c v0) e1 NaryOp_ o es -> constrainNaryOp v0 o es PrimOp_ o :$ es -> constrainPrimOp v0 o es Expect :$ e1 :* e2 :* End -> error "TODO: constrainValue{Expect}" Case_ e bs -> -- First we try going forward on the scrutinee, to make -- pretty resulting programs; but if that doesn't work -- out, we fall back to just constraining the branches. do match <- matchBranches evaluateDatum e bs case match of Nothing -> -- If desired, we could return the Hakaru program -- that always crashes, instead of throwing a -- Haskell error. error "constrainValue{Case_}: nothing matched!" Just GotStuck -> constrainBranches v0 e bs Just (Matched rho body) -> pushes (toVarStatements rho) body >>= constrainValue v0 <|> constrainBranches v0 e bs _ :$ _ -> error "constrainValue: the impossible happened" -- | The default way of doing 'constrainValue' on a 'Case_' expression: -- by constraining each branch. To do this we rely on the fact that -- we're in a 'HMeasure' context (i.e., the continuation produces -- programs of 'HMeasure' type). For each branch we first assert the -- branch's pattern holds (via 'SGuard') and then call 'constrainValue' -- on the body of the branch; and the final program is the superposition -- of all these branches. -- -- TODO: how can we avoid duplicating the scrutinee expression? -- Would pushing a 'SLet' statement before the superpose be sufficient -- to achieve maximal sharing? constrainBranches :: (ABT Term abt) => abt '[] a -> abt '[] b -> [Branch b abt a] -> Dis abt () constrainBranches v0 e = choose . map constrainBranch where constrainBranch (Branch pat body) = let (vars,body') = caseBinds body in push (SGuard vars pat (Thunk e) []) body' >>= constrainValue v0 constrainDatum :: (ABT Term abt) => abt '[] a -> Datum (abt '[]) a -> Dis abt () constrainDatum v0 d = case patternOfDatum d of PatternOfDatum pat es -> do xs <- freshVars $ fmap11 (Hint Text.empty . typeOf) es emit_ $ \body -> syn $ Case_ v0 [ Branch pat (binds_ xs body) , Branch PWild (P.reject $ (typeOf body)) ] constrainValues xs es constrainValues :: (ABT Term abt) => List1 Variable xs -> List1 (abt '[]) xs -> Dis abt () constrainValues (Cons1 x xs) (Cons1 e es) = constrainValue (var x) e >> constrainValues xs es constrainValues Nil1 Nil1 = return () constrainValues _ _ = error "constrainValues: the impossible happened" data PatternOfDatum (ast :: Hakaru -> *) (a :: Hakaru) = forall xs. PatternOfDatum !(Pattern xs a) !(List1 ast xs) -- | Given a datum, return the pattern which will match it along -- with the subexpressions which would be bound to patter-variables. patternOfDatum :: Datum ast a -> PatternOfDatum ast a patternOfDatum = \(Datum hint _typ d) -> podCode d $ \p es -> PatternOfDatum (PDatum hint p) es where podCode :: DatumCode xss ast a -> (forall bs. PDatumCode xss bs a -> List1 ast bs -> r) -> r podCode (Inr d) k = podCode d $ \ p es -> k (PInr p) es podCode (Inl d) k = podStruct d $ \ p es -> k (PInl p) es podStruct :: DatumStruct xs ast a -> (forall bs. PDatumStruct xs bs a -> List1 ast bs -> r) -> r podStruct (Et d1 d2) k = podFun d1 $ \p1 es1 -> podStruct d2 $ \p2 es2 -> k (PEt p1 p2) (es1 `append1` es2) podStruct Done k = k PDone Nil1 podFun :: DatumFun x ast a -> (forall bs. PDatumFun x bs a -> List1 ast bs -> r) -> r podFun (Konst e) k = k (PKonst PVar) (Cons1 e Nil1) podFun (Ident e) k = k (PIdent PVar) (Cons1 e Nil1) ---------------------------------------------------------------- -- | N.B., as with 'constrainValue', we assume that the first -- argument is emissible. So it is the caller's responsibility to -- ensure this (by calling 'atomize' as appropriate). -- -- TODO: capture the emissibility requirement on the first argument -- in the types. constrainVariable :: (ABT Term abt) => abt '[] a -> Variable a -> Dis abt () constrainVariable v0 x = do extras <- getExtras -- If we get 'Nothing', then it turns out @x@ is a free variable. -- If @x@ is a free variable, then it's a neutral term; and we -- return 'bot' for neutral terms maybe bot lookForLoc (lookupAssoc x extras) where lookForLoc (Loc l jxs) = -- If we get 'Nothing', then it turns out @l@ is a free location. -- This is an error because of the invariant: -- if there exists an 'Assoc x ({Multi}Loc l _)' inside @extras@ -- then there must be a statement on the 'ListContext' that binds @l@ (maybe (freeLocError l) return =<<) . select l $ \s -> case s of SBind l' e ixs -> do Refl <- locEq l l' guard (length ixs == length jxs) -- will error otherwise Just $ do inds <- getIndices guard (jxs `permutes` inds) -- will bot otherwise e' <- apply ixs inds (fromLazy e) constrainOutcome v0 e' unsafePush (SLet l (Whnf_ (Neutral v0)) inds) SLet l' e ixs -> do Refl <- locEq l l' guard (length ixs == length jxs) -- will error otherwise Just $ do inds <- getIndices guard (jxs `permutes` inds) -- will bot otherwise e' <- apply ixs inds (fromLazy e) constrainValue v0 e' unsafePush (SLet l (Whnf_ (Neutral v0)) inds) SWeight _ _ -> Nothing SGuard ls' pat scrutinee i -> error "TODO: constrainVariable{SGuard}" ---------------------------------------------------------------- -- | N.B., as with 'constrainValue', we assume that the first -- argument is emissible. So it is the caller's responsibility to -- ensure this (by calling 'atomize' as appropriate). -- -- TODO: capture the emissibility requirement on the first argument -- in the types. constrainValueMeasureOp :: forall abt typs args a . (ABT Term abt, typs ~ UnLCs args, args ~ LCs typs) => abt '[] ('HMeasure a) -> MeasureOp typs a -> SArgs abt args -> Dis abt () constrainValueMeasureOp v0 = go where -- TODO: for Lebesgue and Counting we use @bot@ because that's -- what the old finally-tagless code seems to have been doing. -- But is that right, or should they really be @return ()@? go :: MeasureOp typs a -> SArgs abt args -> Dis abt () go Lebesgue = \End -> bot -- TODO: see note above go Counting = \End -> bot -- TODO: see note above go Categorical = \(e1 :* End) -> constrainValue v0 (P.categorical e1) go Uniform = \(e1 :* e2 :* End) -> constrainValue v0 (P.uniform' e1 e2) go Normal = \(e1 :* e2 :* End) -> constrainValue v0 (P.normal' e1 e2) go Poisson = \(e1 :* End) -> constrainValue v0 (P.poisson' e1) go Gamma = \(e1 :* e2 :* End) -> constrainValue v0 (P.gamma' e1 e2) go Beta = \(e1 :* e2 :* End) -> constrainValue v0 (P.beta' e1 e2) ---------------------------------------------------------------- -- | N.B., We assume that the first argument, @v0@, is already -- atomized. So, this must be ensured before recursing, but we can -- assume it's already been done by the IH. -- -- N.B., we also rely on the fact that our 'HSemiring' instances -- are actually all /commutative/ semirings. If that ever becomes -- not the case, then we'll need to fix things here. -- -- As written, this will do a lot of redundant work in atomizing -- the subterms other than the one we choose to go backward on. -- Because evaluation has side-effects on the heap and is heap -- dependent, it seems like there may not be a way around that -- issue. (I.e., we could use dynamic programming to efficiently -- build up the 'M' computations, but not to evaluate them.) Of -- course, really we shouldn't be relying on the structure of the -- program here; really we should be looking at the heap-bound -- variables in the term: choosing each @x@ to go backward on, treat -- the term as a function of @x@, atomize that function (hence going -- forward on the rest of the variables), and then invert it and -- get the Jacobian. -- -- TODO: find some way to capture in the type that the first argument -- must be emissible. constrainNaryOp :: (ABT Term abt) => abt '[] a -> NaryOp a -> Seq (abt '[] a) -> Dis abt () constrainNaryOp v0 o = case o of Sum theSemi -> lubSeq $ \es1 e es2 -> do u <- atomize $ syn (NaryOp_ (Sum theSemi) (es1 S.>< es2)) v <- evaluate_ $ P.unsafeMinus_ theSemi v0 (fromWhnf u) constrainValue (fromWhnf v) e Prod theSemi -> lubSeq $ \es1 e es2 -> do u <- atomize $ syn (NaryOp_ (Prod theSemi) (es1 S.>< es2)) let u' = fromWhnf u -- TODO: emitLet? emitWeight $ P.recip (toProb_abs theSemi u') v <- evaluate_ $ P.unsafeDiv_ theSemi v0 u' constrainValue (fromWhnf v) e Max theOrd -> chooseSeq $ \es1 e es2 -> do u <- atomize $ syn (NaryOp_ (Max theOrd) (es1 S.>< es2)) emitGuard $ P.primOp2_ (Less theOrd) (fromWhnf u) v0 constrainValue v0 e _ -> error $ "TODO: constrainNaryOp{" ++ show o ++ "}" -- TODO: if this function (or the component @toProb@ and @semiringAbs@ -- parts) turn out to be useful elsewhere, then we should move it -- to the Prelude. toProb_abs :: (ABT Term abt) => HSemiring a -> abt '[] a -> abt '[] 'HProb toProb_abs HSemiring_Nat = P.nat2prob toProb_abs HSemiring_Int = P.nat2prob . P.abs_ toProb_abs HSemiring_Prob = id toProb_abs HSemiring_Real = P.abs_ -- TODO: is there any way to optimise the zippering over the Seq, a la 'S.inits' or 'S.tails'? -- TODO: really we want a dynamic programming approach to avoid unnecessary repetition of calling @evaluateNaryOp evaluate_@ on the two subsequences... lubSeq :: (Alternative m) => (Seq a -> a -> Seq a -> m b) -> Seq a -> m b lubSeq f = go S.empty where go xs ys = case S.viewl ys of S.EmptyL -> empty y S.:< ys' -> f xs y ys' <|> go (xs S.|> y) ys' chooseSeq :: (ABT Term abt) => (Seq a -> a -> Seq a -> Dis abt b) -> Seq a -> Dis abt b chooseSeq f = choose . go S.empty where go xs ys = case S.viewl ys of S.EmptyL -> [] y S.:< ys' -> f xs y ys' : go (xs S.|> y) ys' ---------------------------------------------------------------- -- HACK: for a lot of these, we can't use the prelude functions -- because Haskell can't figure out our polymorphism, so we have -- to define our own versions for manually passing dictionaries -- around. -- -- | N.B., We assume that the first argument, @v0@, is already -- atomized. So, this must be ensured before recursing, but we can -- assume it's already been done by the IH. -- -- TODO: find some way to capture in the type that the first argument -- must be emissible. constrainPrimOp :: forall abt typs args a . (ABT Term abt, typs ~ UnLCs args, args ~ LCs typs) => abt '[] a -> PrimOp typs a -> SArgs abt args -> Dis abt () constrainPrimOp v0 = go where error_TODO op = error $ "TODO: constrainPrimOp{" ++ op ++"}" go :: PrimOp typs a -> SArgs abt args -> Dis abt () go Not = \(e1 :* End) -> error_TODO "Not" go Impl = \(e1 :* e2 :* End) -> error_TODO "Impl" go Diff = \(e1 :* e2 :* End) -> error_TODO "Diff" go Nand = \(e1 :* e2 :* End) -> error_TODO "Nand" go Nor = \(e1 :* e2 :* End) -> error_TODO "Nor" go Pi = \End -> bot -- because @dirac pi@ has no density wrt lebesgue go Sin = \(e1 :* End) -> do x0 <- emitLet' v0 n <- var <$> emitMBind P.counting let tau_n = P.real_ 2 P.* P.fromInt n P.* P.pi -- TODO: emitLet? emitGuard (P.negate P.one P.< x0 P.&& x0 P.< P.one) v <- var <$> emitSuperpose [ P.dirac (tau_n P.+ P.asin x0) , P.dirac (tau_n P.+ P.pi P.- P.asin x0) ] emitWeight . P.recip . P.sqrt . P.unsafeProb $ (P.one P.- x0 P.^ P.nat_ 2) constrainValue v e1 go Cos = \(e1 :* End) -> do x0 <- emitLet' v0 n <- var <$> emitMBind P.counting let tau_n = P.real_ 2 P.* P.fromInt n P.* P.pi emitGuard (P.negate P.one P.< x0 P.&& x0 P.< P.one) r <- emitLet' (tau_n P.+ P.acos x0) v <- var <$> emitSuperpose [P.dirac r, P.dirac (r P.+ P.pi)] emitWeight . P.recip . P.sqrt . P.unsafeProb $ (P.one P.- x0 P.^ P.nat_ 2) constrainValue v e1 go Tan = \(e1 :* End) -> do x0 <- emitLet' v0 n <- var <$> emitMBind P.counting r <- emitLet' (P.fromInt n P.* P.pi P.+ P.atan x0) emitWeight $ P.recip (P.one P.+ P.square x0) constrainValue r e1 go Asin = \(e1 :* End) -> do x0 <- emitLet' v0 emitWeight $ P.unsafeProb (P.cos x0) -- TODO: bounds check for -pi/2 <= v0 < pi/2 constrainValue (P.sin x0) e1 go Acos = \(e1 :* End) -> do x0 <- emitLet' v0 emitWeight $ P.unsafeProb (P.sin x0) constrainValue (P.cos x0) e1 go Atan = \(e1 :* End) -> do x0 <- emitLet' v0 emitWeight $ P.recip (P.unsafeProb (P.cos x0 P.^ P.nat_ 2)) constrainValue (P.tan x0) e1 go Sinh = \(e1 :* End) -> error_TODO "Sinh" go Cosh = \(e1 :* End) -> error_TODO "Cosh" go Tanh = \(e1 :* End) -> error_TODO "Tanh" go Asinh = \(e1 :* End) -> error_TODO "Asinh" go Acosh = \(e1 :* End) -> error_TODO "Acosh" go Atanh = \(e1 :* End) -> error_TODO "Atanh" go RealPow = \(e1 :* e2 :* End) -> -- TODO: There's a discrepancy between @(**)@ and @pow_@ in the old code... do -- TODO: if @v1@ is 0 or 1 then bot. Maybe the @log v1@ in @w@ takes care of the 0 case? u <- emitLet' v0 -- either this from @(**)@: -- emitGuard $ P.zero P.< u -- w <- atomize $ P.recip (P.abs (v0 P.* P.log v1)) -- emitWeight $ P.unsafeProb (fromWhnf w) -- constrainValue (P.logBase v1 v0) e2 -- or this from @pow_@: let w = P.recip (u P.* P.unsafeProb (P.abs (P.log e1))) emitWeight w constrainValue (P.log u P./ P.log e1) e2 -- end. <|> do -- TODO: if @v2@ is 0 then bot. Maybe the weight @w@ takes care of this case? u <- emitLet' v0 let ex = v0 P.** P.recip e2 -- either this from @(**)@: -- emitGuard $ P.zero P.< u -- w <- atomize $ abs (ex / (v2 * v0)) -- or this from @pow_@: let w = P.abs (P.fromProb ex P./ (e2 P.* P.fromProb u)) -- end. emitWeight $ P.unsafeProb w constrainValue ex e1 go Exp = \(e1 :* End) -> do x0 <- emitLet' v0 -- TODO: do we still want\/need the @emitGuard (0 < x0)@ which is now equivalent to @emitGuard (0 /= x0)@ thanks to the types? emitWeight (P.recip x0) constrainValue (P.log x0) e1 go Log = \(e1 :* End) -> do exp_x0 <- emitLet' (P.exp v0) emitWeight exp_x0 constrainValue exp_x0 e1 go (Infinity _) = \End -> error_TODO "Infinity" -- scalar0 go GammaFunc = \(e1 :* End) -> error_TODO "GammaFunc" -- scalar1 go BetaFunc = \(e1 :* e2 :* End) -> error_TODO "BetaFunc" -- scalar2 go (Equal theOrd) = \(e1 :* e2 :* End) -> error_TODO "Equal" go (Less theOrd) = \(e1 :* e2 :* End) -> error_TODO "Less" go (NatPow theSemi) = \(e1 :* e2 :* End) -> error_TODO "NatPow" go (Negate theRing) = \(e1 :* End) -> -- TODO: figure out how to merge this implementation of @rr1 negate@ with the one in 'evaluatePrimOp' to DRY -- TODO: just emitLet the @v0@ and pass the neutral term to the recursive call? let negate_v0 = syn (PrimOp_ (Negate theRing) :$ v0 :* End) -- case v0 of -- Neutral e -> -- Neutral $ syn (PrimOp_ (Negate theRing) :$ e :* End) -- Head_ v -> -- case theRing of -- HRing_Int -> Head_ . reflect . negate $ reify v -- HRing_Real -> Head_ . reflect . negate $ reify v in constrainValue negate_v0 e1 go (Abs theRing) = \(e1 :* End) -> do let theSemi = hSemiring_HRing theRing theOrd = case theRing of HRing_Int -> HOrd_Int HRing_Real -> HOrd_Real theEq = hEq_HOrd theOrd signed = C.singletonCoercion (C.Signed theRing) zero = P.zero_ theSemi lt = P.primOp2_ $ Less theOrd eq = P.primOp2_ $ Equal theEq neg = P.primOp1_ $ Negate theRing x0 <- emitLet' (P.coerceTo_ signed v0) v <- var <$> emitMBind (P.if_ (lt zero x0) (P.dirac x0 P.<|> P.dirac (neg x0)) (P.if_ (eq zero x0) (P.dirac zero) (P.reject . SMeasure $ typeOf zero))) constrainValue v e1 go (Signum theRing) = \(e1 :* End) -> case theRing of HRing_Real -> bot HRing_Int -> do x <- var <$> emitMBind P.counting emitGuard $ P.signum x P.== v0 constrainValue x e1 go (Recip theFractional) = \(e1 :* End) -> do x0 <- emitLet' v0 emitWeight . P.recip . P.unsafeProbFraction_ theFractional -- TODO: define a dictionary-passing variant of 'P.square' instead, to include the coercion in there explicitly... $ square (hSemiring_HFractional theFractional) x0 constrainValue (P.primOp1_ (Recip theFractional) x0) e1 go (NatRoot theRadical) = \(e1 :* e2 :* End) -> case theRadical of HRadical_Prob -> do x0 <- emitLet' v0 u2 <- fromWhnf <$> atomize e2 emitWeight (P.nat2prob u2 P.* x0) constrainValue (x0 P.^ u2) e1 go (Erf theContinuous) = \(e1 :* End) -> error "TODO: constrainPrimOp: need InvErf to disintegrate Erf" -- HACK: can't use @(P.^)@ because Haskell can't figure out our polymorphism square :: (ABT Term abt) => HSemiring a -> abt '[] a -> abt '[] a square theSemiring e = syn (PrimOp_ (NatPow theSemiring) :$ e :* P.nat_ 2 :* End) ---------------------------------------------------------------- ---------------------------------------------------------------- -- TODO: do we really want the first argument to be a term at all, -- or do we want something more general like patters for capturing -- measurable events? -- -- | This is a helper function for 'constrainValue' to handle 'SBind' -- statements (just as the 'perform' argument to 'evaluate' is a -- helper for handling 'SBind' statements). -- -- N.B., We assume that the first argument, @v0@, is already -- atomized. So, this must be ensured before recursing, but we can -- assume it's already been done by the IH. Technically, we con't -- care whether the first argument is in normal form or not, just -- so long as it doesn't contain any heap-bound variables. -- -- This is the function called @(<<|)@ in the paper, though notably -- we swap the argument order. -- -- TODO: find some way to capture in the type that the first argument -- must be emissible, to help avoid accidentally passing the arguments -- in the wrong order! -- -- TODO: under what circumstances is @constrainOutcome x m@ different -- from @constrainValue x =<< perform m@? If they're always the -- same, then we should just use that as the definition in order -- to avoid repeating ourselves constrainOutcome :: forall abt a . (ABT Term abt) => abt '[] a -> abt '[] ('HMeasure a) -> Dis abt () constrainOutcome v0 e0 = #ifdef __TRACE_DISINTEGRATE__ getExtras >>= \extras -> getIndices >>= \inds -> trace ( let s = "-- constrainOutcome" in "\n" ++ s ++ ": " ++ show (pretty v0) ++ "\n" ++ replicate (length s) ' ' ++ ": " ++ show (pretty e0) ++ "\n" ++ "at " ++ show (ppInds inds) ++ "\n" ++ show (prettyExtras extras) ) $ #endif do w0 <- evaluate_ e0 case w0 of Neutral _ -> bot Head_ v -> go v where impossible = error "constrainOutcome: the impossible happened" go :: Head abt ('HMeasure a) -> Dis abt () go (WLiteral _) = impossible -- go (WDatum _) = impossible -- go (WEmpty _) = impossible -- go (WArray _ _) = impossible -- go (WLam _) = impossible -- go (WIntegrate _ _ _) = impossible -- go (WSummate _ _ _) = impossible go (WCoerceTo _ _) = impossible go (WUnsafeFrom _ _) = impossible go (WMeasureOp o es) = constrainOutcomeMeasureOp v0 o es go (WDirac e1) = constrainValue v0 e1 go (WMBind e1 e2) = caseBind e2 $ \x e2' -> do i <- getIndices push (SBind x (Thunk e1) i) e2' >>= constrainOutcome v0 go (WPlate e1 e2) = do x' <- pushPlate e1 e2 constrainValue v0 x' go (WChain e1 e2 e3) = error "TODO: constrainOutcome{Chain}" go (WReject typ) = emit_ $ \m -> P.reject (typeOf m) go (WSuperpose pes) = do i <- getIndices if not (null i) && L.length pes > 1 then bot else emitFork_ (P.superpose . fmap ((,) P.one)) (fmap (\(p,e) -> push (SWeight (Thunk p) i) e >>= constrainOutcome v0) pes) -- TODO: should this really be different from 'constrainValueMeasureOp'? -- -- TODO: find some way to capture in the type that the first argument -- must be emissible. constrainOutcomeMeasureOp :: (ABT Term abt, typs ~ UnLCs args, args ~ LCs typs) => abt '[] a -> MeasureOp typs a -> SArgs abt args -> Dis abt () constrainOutcomeMeasureOp v0 = go where -- Per the paper go Lebesgue = \End -> return () -- TODO: I think, based on Hakaru v0.2.0 go Counting = \End -> return () go Categorical = \(e1 :* End) -> do -- TODO: check that v0' is < then length of e1 pushWeight (P.densityCategorical e1 v0) -- Per the paper go Uniform = \(lo :* hi :* End) -> do v0' <- emitLet' v0 pushGuard (lo P.<= v0' P.&& v0' P.<= hi) pushWeight (P.densityUniform lo hi v0') -- TODO: Add fallback handling of Normal that does not atomize mu,sd. -- This fallback is as if Normal were defined in terms of Lebesgue -- and a density Weight. This fallback is present in Hakaru v0.2.0 -- in order to disintegrate a program such as -- x <~ normal(0,1) -- y <~ normal(x,1) -- return ((x+(y+y),x)::pair(real,real)) go Normal = \(mu :* sd :* End) -> do -- N.B., if\/when extending this to higher dimensions, the real equation is @recip (sqrt (2*pi*sd^2) ^ n) * exp (negate (norm_n (v0 - mu) ^ 2) / (2*sd^2))@ for @Real^n@. pushWeight (P.densityNormal mu sd v0) go Poisson = \(e1 :* End) -> do v0' <- emitLet' v0 pushGuard (P.nat_ 0 P.<= v0' P.&& P.prob_ 0 P.< e1) pushWeight (P.densityPoisson e1 v0') go Gamma = \(e1 :* e2 :* End) -> do v0' <- emitLet' v0 pushGuard (P.prob_ 0 P.< v0' P.&& P.prob_ 0 P.< e1 P.&& P.prob_ 0 P.< e2) pushWeight (P.densityGamma e1 e2 v0') go Beta = \(e1 :* e2 :* End) -> do v0' <- emitLet' v0 pushGuard (P.prob_ 0 P.<= v0' P.&& P.prob_ 1 P.>= v0' P.&& P.prob_ 0 P.< e1 P.&& P.prob_ 0 P.< e2) pushWeight (P.densityBeta e1 e2 v0') ---------------------------------------------------------------- ----------------------------------------------------------- fin.
zaxtax/hakaru
haskell/Language/Hakaru/Disintegrate.hs
bsd-3-clause
52,600
1
34
15,880
11,292
5,779
5,513
-1
-1
{- The number 512 is interesting because it is equal to the sum of its digits raised to some power: 5 + 1 + 2 = 8, and 83 = 512. Another example of a number with this property is 614656 = 284. We shall define an to be the nth term of this sequence and insist that a number must contain at least two digits to have a sum. You are given that a2 = 512 and a10 = 614656. Find a30. -} {-# LANGUAGE ScopedTypeVariables #-} import qualified Zora.List as ZList import qualified Zora.Math as ZMath import qualified Data.Ord as Ord import qualified Data.Set as Set import qualified Data.Char as Char import qualified Data.List as List import qualified Data.MemoCombinators as Memo import Data.Maybe import Control.Applicative sum_of_digits :: Integer -> Integer sum_of_digits = fromIntegral . sum . map Char.digitToInt . show sought :: Integer sought = last . take 30 . List.sort . filter (> 10) . concatMap (\l -> filter (\n -> (sum_of_digits n) == (head l)) l) . map (\x -> takeWhile (< 10^20) . map (x^) $ [1..25]) $ [2..1000] main :: IO () main = do putStrLn . show $ sought
bgwines/project-euler
src/solved/problem119.hs
bsd-3-clause
1,093
4
16
220
263
152
111
28
1
-------------------------------------------------------------------------------- -- Copyright © 2011 National Institute of Aerospace / Galois, Inc. -------------------------------------------------------------------------------- {-# LANGUAGE ExistentialQuantification #-} module Copilot.Compile.C99.Test.CheckSpec (checkSpec) where import Copilot.Core ( Spec (..), Trigger(..)) import Copilot.Core.Expr (Name, UExpr (..)) import Copilot.Core.Type.Eq (UVal (..)) import Copilot.Core.Interpret.Eval (eval) import Copilot.Compile.C99 (compile, c99DirName, c99FileRoot) import Copilot.Compile.C99.Params (Params (..), defaultParams) import Copilot.Compile.C99.Test.Driver (driver) import Copilot.Compile.C99.Test.Iteration (Iteration(..), execTraceToIterations) import Copilot.Compile.C99.Test.ReadCSV (iterationsFromCSV) import Copilot.Core.Type.Show (ShowType(..)) import Copilot.Core.Type.Read (readWithType) import qualified Data.Map as M import Data.List (foldl') import qualified Data.ByteString.Char8 as B import qualified Data.Text.IO as TIO import System.Directory (removeDirectoryRecursive) import System.Process (system, readProcess) import Control.Monad (when, unless) import Text.PrettyPrint (text, (<+>), ($$), render, vcat, hang) -------------------------------------------------------------------------------- checkSpec :: Int -> Spec -> IO Bool checkSpec numIterations spec = do genCFiles numIterations spec compileCFiles csv <- execute numIterations let is1 = iterationsFromCSV csv let is2 = interp numIterations spec let eq = typedOutputs spec is1 == typedOutputs spec is2 unless eq (putStrLn $ showCompare is1 is2) when eq cleanUp -- Keep things around if there's a failure return eq -------------------------------------------------------------------------------- showCompare :: [Iteration] -> [Iteration] -> String showCompare s1 s2 = render $ text "From C:" <+> text "---" <+> text "From Interpreter:" $$ (vcat $ map (\(a,b) -> hang a 10 b) zipped) where zipped = zip (toDoc s1) (toDoc s2) toDoc = map (text . show) -------------------------------------------------------------------------------- -- mapping triggers to arg values type TypedIteration = M.Map Name [UVal] -- list of output values for comparison typedOutputs :: Spec -> [Iteration] -> [TypedIteration] typedOutputs Spec { specTriggers = triggers } = map recoverTypes where recoverTypes :: Iteration -> TypedIteration recoverTypes Iteration { iterationOutputs = iterMap } = M.mapWithKey recoverType iterMap recoverType :: Name -> [String] -> [UVal] recoverType trigName outs = let types = typedTriggerArgs M.! trigName in map typedRead (zip types outs) typedRead :: (UExpr, String) -> UVal typedRead (UExpr { uExprType = t }, output) = UVal { uType = t , uVal = readWithType t output } typedTriggerArgs :: M.Map Name [UExpr] typedTriggerArgs = foldl' mkMap M.empty triggers where mkMap mp trig = M.insert (triggerName trig) (triggerArgs trig) mp -------------------------------------------------------------------------------- driverFile :: String driverFile = "driver.c" outputFile :: String outputFile = "_test" -------------------------------------------------------------------------------- genCFiles :: Int -> Spec -> IO () genCFiles numIterations spec = do compile (defaultParams { prefix = Nothing, verbose = False }) spec TIO.writeFile (c99DirName ++ "/" ++ driverFile) (driver numIterations spec) -------------------------------------------------------------------------------- compileCFiles :: IO () compileCFiles = do _ <- system $ unwords [ "cd " ++ c99DirName ++ ";" , "gcc" , c99FileRoot ++ ".c" , driverFile , "-o" , outputFile ] return () -------------------------------------------------------------------------------- execute :: Int -> IO B.ByteString execute _ = fmap B.pack (readProcess ("./" ++ c99DirName ++ "/" ++ outputFile) [] "") -------------------------------------------------------------------------------- interp :: Int -> Spec -> [Iteration] interp numIterations = execTraceToIterations . eval C numIterations -------------------------------------------------------------------------------- cleanUp :: IO () cleanUp = removeDirectoryRecursive c99DirName -- removeFile $ c99FileRoot ++ ".c" -- removeFile $ c99FileRoot ++ ".h" -- removeFile driverFile -- removeFile outputFile --------------------------------------------------------------------------------
leepike/copilot-c99
src/Copilot/Compile/C99/Test/CheckSpec.hs
bsd-3-clause
4,661
0
12
776
1,113
625
488
83
1
{-# LANGUAGE GADTs, FlexibleInstances, MultiParamTypeClasses #-} module Main where import QueryArrow.Config import System.Environment import Database.HDBC import Database.HDBC.PostgreSQL import Data.List main :: IO () main = do args <- getArgs ps0 <- getConfig (args !! 1) let ps = db_info (head (db_plugins ps0)) conn <- connectPostgreSQL ("host="++db_host ps++ " port="++show (db_port ps)++" dbname="++(db_name ps)++" user="++db_username ps++" password="++db_password ps) stmt <- prepare conn (head args) execute stmt [] rows <- fetchAllRows stmt print rows
xu-hao/QueryArrow
QueryArrow-db-sql-hdbc-postgresql/app/PostgreSQLTest.hs
bsd-3-clause
615
0
19
127
211
102
109
17
1
{-# LANGUAGE DeriveGeneric #-} module UeContextStates ( UeContext_enb (..) , UeContext_mme (..) , UeContext_ue (..) , RrcState (..) , initialUeState , initialUeContext_enb , defaultUeContext_enb , initialUeContext_mme , defaultUeContext_mme , addSrb_ue , addSrb_enb , addImsi_enb , changeStateAddEnbId_enb , addSecurityKeyEpsId_enb , changeStateToIdle_enb , addRat_enb ) where import Network.Socket import qualified RrcMessages as Rrc import Identifiers {----------------------------------------------------- Context Definitions ------------------------------------------------------} data UeContext_enb = UeContext_enb{ rrcState :: RrcState, c_rnti :: !Int, imsi :: !Imsi, srbIdentity :: !String, enbUeS1ApId :: !Int, ratCapabilities :: [(Rrc.Rat,Bool)], securityKey :: !Int, epsBearerId :: !String } instance Show UeContext_enb where show m = "UeContext_eNB {RRC state: "++ show (rrcState m) ++ " C-RNTI: " ++ show (c_rnti m)++ " IMSI: " ++ show (imsi m)++ " SRB Identity: "++show (srbIdentity m)++" eNB S1 Identity:"++show (enbUeS1ApId m)++ " RAT Capabilities: "++show (ratCapabilities m)++" Security Key: "++show (securityKey m)++" EPS Bearer Id: "++show (epsBearerId m)++"}" data RrcState = RRC_Idle | RRC_Connected deriving Show data UeContext_mme = UeContext_mme{ mmeUeS1ApId :: !Int, securityKey_mme :: !Int } instance Show UeContext_mme where show m = "UeContext_mme {MME S1AP UE ID: "++ show (mmeUeS1ApId m) ++ " Security Key: " ++ show (securityKey_mme m)++ "}" data UeContext_ue = UeContext_ue{ imsi_ue :: !Imsi, securityKey_ue :: !Int, srbId :: !String } instance Show UeContext_ue where show m = "UeContext_ue {IMSI: "++ show (imsi_ue m) ++ " Security Key: " ++ show (securityKey_ue m) ++ " SRB ID: " ++ show (srbId m)++ "}" {----------------------------------------------------- Default Contents ------------------------------------------------------} initialUeState :: Int -> UeContext_ue initialUeState seed = UeContext_ue{ imsi_ue = genImsi seed (seed+2), securityKey_ue = seed*18, srbId = "0" } initialUeContext_enb :: Int -> UeContext_enb initialUeContext_enb crnti = UeContext_enb { rrcState = RRC_Idle, c_rnti = crnti, imsi = Imsi "0" "0" "0", srbIdentity = "0", enbUeS1ApId = 0, ratCapabilities =[(Rrc.E_UTRA,False)], securityKey = 0, epsBearerId = "0" } defaultUeContext_enb :: UeContext_enb defaultUeContext_enb = UeContext_enb {rrcState = RRC_Idle, c_rnti = -1, imsi = Imsi "0" "0" "0", srbIdentity = "0", enbUeS1ApId = 0, ratCapabilities =[(Rrc.E_UTRA,False)], securityKey = 0, epsBearerId = "0" } initialUeContext_mme :: Int -> Int -> UeContext_mme initialUeContext_mme mmeId securityKey= UeContext_mme{ mmeUeS1ApId = mmeId, securityKey_mme = securityKey } defaultUeContext_mme :: UeContext_mme defaultUeContext_mme = UeContext_mme{ mmeUeS1ApId = -1, securityKey_mme = -1 } {----------------------------------------------------- Modifiers ------------------------------------------------------} addSrb_ue :: UeContext_ue -> (Rrc.RrcMessage,Socket) -> UeContext_ue addSrb_ue oldState (message, _)= UeContext_ue{ imsi_ue = imsi_ue oldState, securityKey_ue = securityKey_ue oldState, srbId = Rrc.srbIdentity message } addSrb_enb :: String -> UeContext_enb -> UeContext_enb addSrb_enb srb oldContent = UeContext_enb { rrcState = rrcState oldContent, c_rnti = c_rnti oldContent, imsi = imsi oldContent, srbIdentity = srb, enbUeS1ApId =enbUeS1ApId oldContent , ratCapabilities =ratCapabilities oldContent, securityKey = securityKey oldContent, epsBearerId = epsBearerId oldContent } addImsi_enb :: Imsi -> UeContext_enb -> UeContext_enb addImsi_enb imsi oldContent = UeContext_enb { rrcState = rrcState oldContent, c_rnti = c_rnti oldContent, imsi = imsi, srbIdentity = srbIdentity oldContent, enbUeS1ApId =enbUeS1ApId oldContent , ratCapabilities =ratCapabilities oldContent, securityKey = securityKey oldContent, epsBearerId = epsBearerId oldContent } changeStateAddEnbId_enb :: Int -> UeContext_enb -> UeContext_enb changeStateAddEnbId_enb enbId oldContent = UeContext_enb { rrcState =RRC_Connected, c_rnti = c_rnti oldContent, imsi = imsi oldContent, srbIdentity = srbIdentity oldContent, enbUeS1ApId =enbId, ratCapabilities =ratCapabilities oldContent, securityKey = securityKey oldContent, epsBearerId = epsBearerId oldContent } addSecurityKeyEpsId_enb :: Int -> String -> UeContext_enb -> UeContext_enb addSecurityKeyEpsId_enb key epsId oldContent = UeContext_enb{ rrcState =rrcState oldContent, c_rnti = c_rnti oldContent, imsi = imsi oldContent, srbIdentity = srbIdentity oldContent, enbUeS1ApId =enbUeS1ApId oldContent, ratCapabilities =ratCapabilities oldContent, securityKey = key, epsBearerId = epsId } changeStateToIdle_enb :: UeContext_enb -> UeContext_enb changeStateToIdle_enb oldContent = UeContext_enb { rrcState =RRC_Idle, c_rnti = c_rnti oldContent, imsi = imsi oldContent, srbIdentity = srbIdentity oldContent, enbUeS1ApId =enbUeS1ApId oldContent, ratCapabilities =ratCapabilities oldContent, securityKey = securityKey oldContent, epsBearerId = epsBearerId oldContent } addRat_enb :: [(Rrc.Rat,Bool)] -> UeContext_enb -> UeContext_enb addRat_enb ratList oldContent = UeContext_enb { rrcState =rrcState oldContent, c_rnti = c_rnti oldContent, imsi = imsi oldContent, srbIdentity = srbIdentity oldContent, enbUeS1ApId =enbUeS1ApId oldContent, ratCapabilities =ratList, securityKey = securityKey oldContent, epsBearerId = epsBearerId oldContent }
Ilydocus/frp-prototype
src/UeContextStates.hs
bsd-3-clause
5,798
0
24
1,051
1,417
797
620
166
1
module CacheDNS.Concurrent.CondVar ( CondVar , newCondVar , wakup , wait , reset ) where import Control.Applicative ((<$>)) import Control.Concurrent.STM import Data.IORef (newIORef, readIORef, atomicModifyIORef', IORef) newtype CondVar = CondVar (TMVar Int) newCondVar :: IO CondVar newCondVar = CondVar <$> newEmptyTMVarIO wakup :: CondVar -> IO () wakup (CondVar var) = atomically $ putTMVar var 0 wait :: CondVar -> IO Int wait (CondVar var) = atomically $ readTMVar var reset :: CondVar -> IO Int reset (CondVar var) = atomically $ do empty <- isEmptyTMVar var if empty then return 0 else takeTMVar var
DavidAlphaFox/CacheDNS
src/CacheDNS/Concurrent/CondVar.hs
bsd-3-clause
652
0
9
138
219
118
101
21
2
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, FlexibleContexts #-} -- | Type classes to allow for XML handling functions to be generalized to -- work with different document types. module Text.XML.Expat.Internal.DocumentClass where import Text.XML.Expat.Internal.NodeClass (NodeClass) import Control.DeepSeq import Control.Monad (mzero) import Data.List.Class -- | XML declaration, consisting of version, encoding and standalone. -- -- The formatting functions always outputs only UTF-8, regardless -- of what encoding is specified here. If you want to produce a document in a -- different encoding, then set the encoding here, format the document, and then -- convert the output text from UTF-8 to your desired encoding using some -- text conversion library. data XMLDeclaration text = XMLDeclaration text (Maybe text) (Maybe Bool) deriving (Eq, Show) -- | Stub for future expansion. data DocumentTypeDeclaration c tag text = DocumentTypeDeclaration deriving (Eq, Show) data Misc text = Comment !text | ProcessingInstruction !text !text instance Show text => Show (Misc text) where showsPrec d (ProcessingInstruction t txt) = showParen (d > 10) $ ("ProcessingInstruction "++) . showsPrec 11 t . (" "++) . showsPrec 11 txt showsPrec d (Comment t) = showParen (d > 10) $ ("Comment "++) . showsPrec 11 t instance Eq text => Eq (Misc text) where ProcessingInstruction t1 d1 == ProcessingInstruction t2 d2 = t1 == t2 && d1 == d2 Comment t1 == Comment t2 = t1 == t2 _ == _ = False instance NFData text => NFData (Misc text) where rnf (ProcessingInstruction target txt) = rnf (target, txt) rnf (Comment txt) = rnf txt type family NodeType d :: (* -> *) -> * -> * -> * class (Functor c, List c, NodeClass (NodeType d) c) => DocumentClass d c where -- | Get the XML declaration for this document. getXMLDeclaration :: d c tag text -> Maybe (XMLDeclaration text) -- | Get the Document Type Declaration (DTD) for this document. getDocumentTypeDeclaration :: d c tag text -> Maybe (DocumentTypeDeclaration c tag text) -- | Get the top-level 'Misc' nodes for this document. getTopLevelMiscs :: d c tag text -> c (Misc text) -- | Get the root element for this document. getRoot :: d c tag text -> NodeType d c tag text -- | Make a document with the specified fields. mkDocument :: Maybe (XMLDeclaration text) -> Maybe (DocumentTypeDeclaration c tag text) -> c (Misc text) -> NodeType d c tag text -> d c tag text -- | Make a document with the specified root node and all other information -- set to defaults. mkPlainDocument :: DocumentClass d c => NodeType d c tag text -> d c tag text mkPlainDocument = mkDocument Nothing Nothing mzero modifyXMLDeclaration :: DocumentClass d c => (Maybe (XMLDeclaration text) -> Maybe (XMLDeclaration text)) -> d c tag text -> d c tag text modifyXMLDeclaration f doc = mkDocument (f $ getXMLDeclaration doc) (getDocumentTypeDeclaration doc) (getTopLevelMiscs doc) (getRoot doc) modifyDocumentTypeDeclaration :: DocumentClass d c => (Maybe (DocumentTypeDeclaration c tag text) -> Maybe (DocumentTypeDeclaration c tag text)) -> d c tag text -> d c tag text modifyDocumentTypeDeclaration f doc = mkDocument (getXMLDeclaration doc) (f $ getDocumentTypeDeclaration doc) (getTopLevelMiscs doc) (getRoot doc) modifyTopLevelMiscs :: DocumentClass d c => (c (Misc text) -> c (Misc text)) -> d c tag text -> d c tag text modifyTopLevelMiscs f doc = mkDocument (getXMLDeclaration doc) (getDocumentTypeDeclaration doc) (f $ getTopLevelMiscs doc) (getRoot doc) modifyRoot :: DocumentClass d c => (NodeType d c tag text -> NodeType d c tag text) -> d c tag text -> d c tag text modifyRoot f doc = mkDocument (getXMLDeclaration doc) (getDocumentTypeDeclaration doc) (getTopLevelMiscs doc) (f $ getRoot doc)
sol/hexpat
Text/XML/Expat/Internal/DocumentClass.hs
bsd-3-clause
4,191
0
12
1,069
1,140
576
564
67
1
-- Tower of Hanoi Solver -- Author: David Terei -- -- This program will solve the tower of hanoi problem for you. -- It can be run in two modes, one which will print out all the -- steps that need to be made for the solution and a second mode -- which doesn't print out anything, useful for benchmarking the -- algorithms performance. -- import Data.List import System.Console.GetOpt import System.Environment import System.Exit import System.IO data Flag = Help | Benchmark deriving (Eq, Ord, Show, Enum, Bounded) data Pole = A | B | C deriving (Eq, Show) type StackItem = Int type Stack = [StackItem] type SolnPrinter = Int -> Pole -> Pole -> [String] flags = [ Option ['h'] ["help"] (NoArg Help) "Print this help message." , Option ['b'] ["benchmark"] (NoArg Benchmark) "Solve without printing the solution." ] main :: IO () main = getArgs >>= parse parse argv = case getOpt Permute flags argv of (args,[num],[]) -> do let n = read num if Help `elem` args then do hPutStrLn stderr (usageInfo header flags) exitWith ExitSuccess else if Benchmark `elem` args then putStrLn . show . length $ solveTower n benchSoln else mapM_ putStrLn $ solveTower n printSoln (_, x:xs, []) -> do hPutStrLn stderr ("More then one tower size specified!\n\n" ++ usageInfo header flags) exitWith (ExitFailure 1) (_, _, errs) -> do hPutStrLn stderr (concat errs ++ usageInfo header flags) exitWith (ExitFailure 1) where header = "Usage: tower [-hb] <height of tower>" solveTower :: Int -> SolnPrinter -> [String] solveTower n p | n < 1 = error "Must be a tower of size 1 or greater" | otherwise = tower ([n,(n-1)..1]) A C p tower :: Stack -> Pole -> Pole -> SolnPrinter -> [String] tower (x:[]) on to p = p x on to tower xs on to p = let spair = head $ [A,B,C] \\ [on,to] in tower (tail xs) on spair p ++ tower ([head xs]) on to p ++ tower (tail xs) spair to p printSoln :: SolnPrinter printSoln x on to = ["Move S" ++ (show x) ++ " from " ++ (show on) ++ " to " ++ (show to)] benchSoln :: SolnPrinter benchSoln _ _ _ = []
dterei/Scraps
haskell/tower.hs
bsd-3-clause
2,231
0
15
600
754
398
356
48
5
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns, CPP #-} {-# LANGUAGE RecordWildCards, NamedFieldPuns #-} module Network.Wai.Handler.Warp.HTTP2.Sender (frameSender) where #if __GLASGOW_HASKELL__ < 709 import Control.Applicative #endif import Control.Concurrent (forkIO) import Control.Concurrent.STM import qualified Control.Exception as E import Control.Monad (unless, void, when) import qualified Data.ByteString as BS import qualified Data.ByteString.Builder.Extra as B import Foreign.Ptr import Network.HTTP2 import Network.HTTP2.Priority import Network.Wai import Network.Wai.Handler.Warp.Buffer import Network.Wai.Handler.Warp.HTTP2.EncodeFrame import Network.Wai.Handler.Warp.HTTP2.HPACK import Network.Wai.Handler.Warp.HTTP2.Types import Network.Wai.Handler.Warp.IORef import qualified Network.Wai.Handler.Warp.Settings as S import qualified Network.Wai.Handler.Warp.Timeout as T import Network.Wai.Handler.Warp.Types import Network.Wai.Internal (Response(..)) import qualified System.PosixCompat.Files as P #ifdef WINDOWS import qualified System.IO as IO #else import Network.Wai.Handler.Warp.FdCache import Network.Wai.Handler.Warp.SendFile (positionRead) import System.Posix.IO (openFd, OpenFileFlags(..), defaultFileFlags, OpenMode(ReadOnly), closeFd) import System.Posix.Types #endif ---------------------------------------------------------------- data Leftover = LZero | LOne B.BufferWriter | LTwo BS.ByteString B.BufferWriter ---------------------------------------------------------------- unlessClosed :: Context -> Connection -> Stream -> IO () -> IO () unlessClosed ctx Connection{connSendAll} strm@Stream{streamState,streamNumber} body = E.handle resetStream $ do state <- readIORef streamState unless (isClosed state) body where resetStream e = do closed ctx strm (ResetByMe e) let rst = resetFrame InternalError streamNumber connSendAll rst checkWindowSize :: TVar WindowSize -> TVar WindowSize -> PriorityTree Output -> Output -> Priority -> (WindowSize -> IO ()) -> IO () checkWindowSize connWindow strmWindow outQ out pri body = do cw <- atomically $ do w <- readTVar connWindow check (w > 0) return w sw <- atomically $ readTVar strmWindow if sw == 0 then void $ forkIO $ do -- checkme: if connection is closed? GC throws dead lock error? atomically $ do x <- readTVar strmWindow check (x > 0) enqueue outQ out pri else body (min cw sw) frameSender :: Context -> Connection -> InternalInfo -> S.Settings -> IO () frameSender ctx@Context{outputQ,connectionWindow} conn@Connection{connWriteBuffer,connBufferSize,connSendAll} ii settings = go `E.catch` ignore where initialSettings = [(SettingsMaxConcurrentStreams,recommendedConcurrency)] initialFrame = settingsFrame id initialSettings bufHeaderPayload = connWriteBuffer `plusPtr` frameHeaderLength headerPayloadLim = connBufferSize - frameHeaderLength go = do connSendAll initialFrame loop loop = dequeue outputQ >>= \(out, pri) -> switch out pri ignore :: E.SomeException -> IO () ignore _ = return () switch OFinish _ = return () switch (OGoaway frame) _ = connSendAll frame switch (OFrame frame) _ = do connSendAll frame loop switch out@(OResponse strm rsp aux) pri = unlessClosed ctx conn strm $ do checkWindowSize connectionWindow (streamWindow strm) outputQ out pri $ \lim -> do -- Header frame and Continuation frame let sid = streamNumber strm endOfStream = case aux of Persist{} -> False Oneshot hb -> not hb len <- headerContinue sid rsp endOfStream let total = len + frameHeaderLength case aux of Oneshot True -> do -- hasBody -- Data frame payload (off, _) <- sendHeadersIfNecessary total let payloadOff = off + frameHeaderLength Next datPayloadLen mnext <- fillResponseBodyGetNext conn ii payloadOff lim rsp fillDataHeaderSend strm total datPayloadLen mnext maybeEnqueueNext strm mnext pri Oneshot False -> do -- "closed" must be before "connSendAll". If not, -- the context would be switched to the receiver, -- resulting the inconsistency of concurrency. closed ctx strm Finished flushN total Persist sq tvar -> do (off, needSend) <- sendHeadersIfNecessary total let payloadOff = off + frameHeaderLength Next datPayloadLen mnext <- fillStreamBodyGetNext conn payloadOff lim sq tvar -- If no data was immediately available, avoid sending an -- empty data frame. if datPayloadLen > 0 then fillDataHeaderSend strm total datPayloadLen mnext else when needSend $ flushN off maybeEnqueueNext strm mnext pri loop switch out@(ONext strm curr) pri = unlessClosed ctx conn strm $ do checkWindowSize connectionWindow (streamWindow strm) outputQ out pri $ \lim -> do -- Data frame payload Next datPayloadLen mnext <- curr lim fillDataHeaderSend strm 0 datPayloadLen mnext maybeEnqueueNext strm mnext pri loop -- Flush the connection buffer to the socket, where the first 'n' bytes of -- the buffer are filled. flushN :: Int -> IO () flushN n = bufferIO connWriteBuffer n connSendAll headerContinue sid rsp endOfStream = do builder <- hpackEncodeHeader ctx ii settings rsp (len, signal) <- B.runBuilder builder bufHeaderPayload headerPayloadLim let flag0 = case signal of B.Done -> setEndHeader defaultFlags _ -> defaultFlags flag = if endOfStream then setEndStream flag0 else flag0 fillFrameHeader FrameHeaders len sid flag connWriteBuffer continue sid len signal continue _ len B.Done = return len continue sid len (B.More _ writer) = do flushN $ len + frameHeaderLength (len', signal') <- writer bufHeaderPayload headerPayloadLim let flag = case signal' of B.Done -> setEndHeader defaultFlags _ -> defaultFlags fillFrameHeader FrameContinuation len' sid flag connWriteBuffer continue sid len' signal' continue sid len (B.Chunk bs writer) = do flushN $ len + frameHeaderLength let (bs1,bs2) = BS.splitAt headerPayloadLim bs len' = BS.length bs1 void $ copy bufHeaderPayload bs1 fillFrameHeader FrameContinuation len' sid defaultFlags connWriteBuffer if bs2 == "" then continue sid len' (B.More 0 writer) else continue sid len' (B.Chunk bs2 writer) -- True if the connection buffer has room for a 1-byte data frame. canFitDataFrame total = total + frameHeaderLength < connBufferSize -- Re-enqueue the stream in the output queue if more output is immediately -- available; do nothing otherwise. If the stream is not finished, it must -- already have been written to the 'TVar' owned by 'waiter', which will -- put it back into the queue when more output becomes available. maybeEnqueueNext :: Stream -> Control DynaNext -> Priority -> IO () maybeEnqueueNext strm (CNext next) = enqueue outputQ (ONext strm next) maybeEnqueueNext _ _ = const $ return () -- Send headers if there is not room for a 1-byte data frame, and return -- the offset of the next frame's first header byte and whether the headers -- still need to be sent. sendHeadersIfNecessary total | canFitDataFrame total = return (total, True) | otherwise = do flushN total return (0, False) fillDataHeaderSend strm otherLen datPayloadLen mnext = do -- Data frame header let sid = streamNumber strm buf = connWriteBuffer `plusPtr` otherLen total = otherLen + frameHeaderLength + datPayloadLen flag = case mnext of CFinish -> setEndStream defaultFlags _ -> defaultFlags fillFrameHeader FrameData datPayloadLen sid flag buf -- "closed" must be before "connSendAll". If not, -- the context would be switched to the receiver, -- resulting the inconsistency of concurrency. case mnext of CFinish -> closed ctx strm Finished _ -> return () flushN total atomically $ do modifyTVar' connectionWindow (subtract datPayloadLen) modifyTVar' (streamWindow strm) (subtract datPayloadLen) fillFrameHeader ftyp len sid flag buf = encodeFrameHeaderBuf ftyp hinfo buf where hinfo = FrameHeader len flag sid ---------------------------------------------------------------- {- ResponseFile Status ResponseHeaders FilePath (Maybe FilePart) ResponseBuilder Status ResponseHeaders Builder ResponseStream Status ResponseHeaders StreamingBody ResponseRaw (IO ByteString -> (ByteString -> IO ()) -> IO ()) Response -} fillResponseBodyGetNext :: Connection -> InternalInfo -> Int -> WindowSize -> Response -> IO Next fillResponseBodyGetNext Connection{connWriteBuffer,connBufferSize} _ off lim (ResponseBuilder _ _ bb) = do let datBuf = connWriteBuffer `plusPtr` off room = min (connBufferSize - off) lim (len, signal) <- B.runBuilder bb datBuf room return $ nextForBuilder connWriteBuffer connBufferSize len signal #ifdef WINDOWS fillResponseBodyGetNext Connection{connWriteBuffer,connBufferSize} _ off lim (ResponseFile _ _ path mpart) = do let datBuf = connWriteBuffer `plusPtr` off room = min (connBufferSize - off) lim (start, bytes) <- fileStartEnd path mpart -- fixme: how to close Handle? GC does it at this moment. h <- IO.openBinaryFile path IO.ReadMode IO.hSeek h IO.AbsoluteSeek start len <- IO.hGetBufSome h datBuf (mini room bytes) let bytes' = bytes - fromIntegral len return $ nextForFile len connWriteBuffer connBufferSize h bytes' (return ()) #else fillResponseBodyGetNext Connection{connWriteBuffer,connBufferSize} ii off lim (ResponseFile _ _ path mpart) = do (fd, refresh) <- case fdCacher ii of Just fdcache -> getFd fdcache path Nothing -> do fd' <- openFd path ReadOnly Nothing defaultFileFlags{nonBlock=True} th <- T.register (timeoutManager ii) (closeFd fd') return (fd', T.tickle th) let datBuf = connWriteBuffer `plusPtr` off room = min (connBufferSize - off) lim (start, bytes) <- fileStartEnd path mpart len <- positionRead fd datBuf (mini room bytes) start refresh let len' = fromIntegral len return $ nextForFile len connWriteBuffer connBufferSize fd (start + len') (bytes - len') refresh #endif fillResponseBodyGetNext _ _ _ _ _ = error "fillResponseBodyGetNext" fileStartEnd :: FilePath -> Maybe FilePart -> IO (Integer, Integer) fileStartEnd path Nothing = do end <- fromIntegral . P.fileSize <$> P.getFileStatus path return (0, end) fileStartEnd _ (Just part) = return (filePartOffset part, filePartByteCount part) ---------------------------------------------------------------- fillStreamBodyGetNext :: Connection -> Int -> WindowSize -> TBQueue Sequence -> TVar Sync -> IO Next fillStreamBodyGetNext Connection{connWriteBuffer,connBufferSize} off lim sq tvar = do let datBuf = connWriteBuffer `plusPtr` off room = min (connBufferSize - off) lim (leftover, cont, len) <- runStreamBuilder datBuf room sq nextForStream connWriteBuffer connBufferSize sq tvar leftover cont len ---------------------------------------------------------------- fillBufBuilder :: Buffer -> BufSize -> Leftover -> DynaNext fillBufBuilder buf0 siz0 leftover lim = do let payloadBuf = buf0 `plusPtr` frameHeaderLength room = min (siz0 - frameHeaderLength) lim case leftover of LZero -> error "fillBufBuilder: LZero" LOne writer -> do (len, signal) <- writer payloadBuf room getNext len signal LTwo bs writer | BS.length bs <= room -> do buf1 <- copy payloadBuf bs let len1 = BS.length bs (len2, signal) <- writer buf1 (room - len1) getNext (len1 + len2) signal | otherwise -> do let (bs1,bs2) = BS.splitAt room bs void $ copy payloadBuf bs1 getNext room (B.Chunk bs2 writer) where getNext l s = return $ nextForBuilder buf0 siz0 l s nextForBuilder :: Buffer -> BufSize -> BytesFilled -> B.Next -> Next nextForBuilder _ _ len B.Done = Next len CFinish nextForBuilder buf siz len (B.More _ writer) = Next len (CNext (fillBufBuilder buf siz (LOne writer))) nextForBuilder buf siz len (B.Chunk bs writer) = Next len (CNext (fillBufBuilder buf siz (LTwo bs writer))) ---------------------------------------------------------------- runStreamBuilder :: Buffer -> BufSize -> TBQueue Sequence -> IO (Leftover, Bool, BytesFilled) runStreamBuilder buf0 room0 sq = loop buf0 room0 0 where loop !buf !room !total = do mbuilder <- atomically $ tryReadTBQueue sq case mbuilder of Nothing -> return (LZero, True, total) Just (SBuilder builder) -> do (len, signal) <- B.runBuilder builder buf room let !total' = total + len case signal of B.Done -> loop (buf `plusPtr` len) (room - len) total' B.More _ writer -> return (LOne writer, True, total') B.Chunk bs writer -> return (LTwo bs writer, True, total') Just SFlush -> return (LZero, True, total) Just SFinish -> return (LZero, False, total) fillBufStream :: Buffer -> BufSize -> Leftover -> TBQueue Sequence -> TVar Sync -> DynaNext fillBufStream buf0 siz0 leftover0 sq tvar lim0 = do let payloadBuf = buf0 `plusPtr` frameHeaderLength room0 = min (siz0 - frameHeaderLength) lim0 case leftover0 of LZero -> do (leftover, cont, len) <- runStreamBuilder payloadBuf room0 sq getNext leftover cont len LOne writer -> write writer payloadBuf room0 0 LTwo bs writer | BS.length bs <= room0 -> do buf1 <- copy payloadBuf bs let len = BS.length bs write writer buf1 (room0 - len) len | otherwise -> do let (bs1,bs2) = BS.splitAt room0 bs void $ copy payloadBuf bs1 getNext (LTwo bs2 writer) True room0 where getNext = nextForStream buf0 siz0 sq tvar write writer1 buf room sofar = do (len, signal) <- writer1 buf room case signal of B.Done -> do (leftover, cont, extra) <- runStreamBuilder (buf `plusPtr` len) (room - len) sq let !total = sofar + len + extra getNext leftover cont total B.More _ writer -> do let !total = sofar + len getNext (LOne writer) True total B.Chunk bs writer -> do let !total = sofar + len getNext (LTwo bs writer) True total nextForStream :: Buffer -> BufSize -> TBQueue Sequence -> TVar Sync -> Leftover -> Bool -> BytesFilled -> IO Next nextForStream _ _ _ tvar _ False len = do atomically $ writeTVar tvar SyncFinish return $ Next len CFinish nextForStream buf siz sq tvar LZero True len = do atomically $ writeTVar tvar $ SyncNext (fillBufStream buf siz LZero sq tvar) return $ Next len CNone nextForStream buf siz sq tvar leftover True len = return $ Next len (CNext (fillBufStream buf siz leftover sq tvar)) ---------------------------------------------------------------- #ifdef WINDOWS fillBufFile :: Buffer -> BufSize -> IO.Handle -> Integer -> IO () -> DynaNext fillBufFile buf siz h bytes refresh lim = do let payloadBuf = buf `plusPtr` frameHeaderLength room = min (siz - frameHeaderLength) lim len <- IO.hGetBufSome h payloadBuf room refresh let bytes' = bytes - fromIntegral len return $ nextForFile len buf siz h bytes' refresh nextForFile :: BytesFilled -> Buffer -> BufSize -> IO.Handle -> Integer -> IO () -> Next nextForFile 0 _ _ _ _ _ = Next 0 CFinish nextForFile len _ _ _ 0 _ = Next len CFinish nextForFile len buf siz h bytes refresh = Next len (CNext (fillBufFile buf siz h bytes refresh)) #else fillBufFile :: Buffer -> BufSize -> Fd -> Integer -> Integer -> IO () -> DynaNext fillBufFile buf siz fd start bytes refresh lim = do let payloadBuf = buf `plusPtr` frameHeaderLength room = min (siz - frameHeaderLength) lim len <- positionRead fd payloadBuf (mini room bytes) start let len' = fromIntegral len refresh return $ nextForFile len buf siz fd (start + len') (bytes - len') refresh nextForFile :: BytesFilled -> Buffer -> BufSize -> Fd -> Integer -> Integer -> IO () -> Next nextForFile 0 _ _ _ _ _ _ = Next 0 CFinish nextForFile len _ _ _ _ 0 _ = Next len CFinish nextForFile len buf siz fd start bytes refresh = Next len (CNext (fillBufFile buf siz fd start bytes refresh)) #endif mini :: Int -> Integer -> Int mini i n | fromIntegral i < n = i | otherwise = fromIntegral n
mfine/wai
warp/Network/Wai/Handler/Warp/HTTP2/Sender.hs
mit
18,150
0
22
5,184
4,402
2,178
2,224
305
18
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RankNTypes #-} -- TODO: Not sure about the best way to avoid the orphan instances here {-# OPTIONS_GHC -fno-warn-orphans -Wno-redundant-constraints #-} -- | HD wallets module Cardano.Wallet.Kernel.DB.HdWallet ( -- * Supporting types WalletName(..) , AccountName(..) , HdAccountIx(..) , HdAddressIx(..) , AssuranceLevel(..) , assuredBlockDepth , HasSpendingPassword(..) -- * HD wallet types proper , HdWallets(..) , HdRootId(..) , HdAccountId(..) , HdAddressId(..) , HdRoot(..) , HdAccount(..) , HdAddress(..) -- * IsOurs , IsOurs(..) , decryptHdLvl2DerivationPath -- * HD Wallet state , HdAccountState(..) , HdAccountUpToDate(..) , HdAccountIncomplete(..) , WithAccountState(..) , CombinedWithAccountState , finishRestoration -- ** Initialiser , initHdWallets -- ** Lenses -- *** Wallet collection , hdWalletsRoots , hdWalletsAccounts , hdWalletsAddresses -- *** Account ID , hdAccountIdParent , hdAccountIdIx , hdAccountAutoPkCounter -- ** Address ID , hdAddressIdParent , hdAddressIdIx -- *** Root , hdRootId , hdRootName , hdRootHasPassword , hdRootAssurance , hdRootCreatedAt -- *** Account , hdAccountId , hdAccountName , hdAccountState , hdAccountStateCurrent , hdAccountStateCurrentCombined , hdAccountStateUpToDate , hdAccountRestorationState -- *** Account state: up to date , hdUpToDateCheckpoints -- *** Account state: under restoration , hdIncompleteCurrent , hdIncompleteHistorical -- *** Address , hdAddressId , hdAddressAddress -- ** Composite lenses , hdAccountRootId , hdAddressRootId , hdAddressAccountId -- * Unknown identifiers , UnknownHdRoot(..) , UnknownHdAccount(..) , UnknownHdAddress(..) , embedUnknownHdRoot , embedUnknownHdAccount -- * Zoom to parts of the HD wallet , zoomHdRootId , zoomHdAccountId , zoomHdAddressId , zoomHdCardanoAddress , matchHdAccountState , zoomHdAccountCheckpoints , zoomHdAccountCurrent , zoomHdAccountCurrentCombine , matchHdAccountCheckpoints -- * Zoom variations that create on request , zoomOrCreateHdRoot , zoomOrCreateHdAccount , zoomOrCreateHdAddress , assumeHdRootExists , assumeHdAccountExists -- * General-utility functions , eskToHdRootId , pkToHdRootId ) where import Universum hiding ((:|)) import Control.Lens (Getter, at, lazy, to, (+~), _Wrapped) import Control.Lens.TH (makeLenses) import qualified Data.ByteString as BS import qualified Data.IxSet.Typed as IxSet (Indexable (..)) import Data.SafeCopy (base, deriveSafeCopy) import Test.QuickCheck (Arbitrary (..), oneof, vectorOf) import Formatting (bprint, build, (%)) import qualified Formatting.Buildable import Serokell.Util (listJson) import qualified Pos.Core as Core import Pos.Core.Chrono (NewestFirst (..)) import Pos.Core.NetworkMagic (NetworkMagic (..)) import Pos.Crypto (HDPassphrase) import qualified Pos.Crypto as Core import Cardano.Wallet.API.V1.Types (V1 (..), WAddressMeta(WAddressMeta)) import Cardano.Wallet.Kernel.DB.BlockContext import Cardano.Wallet.Kernel.DB.InDb import Cardano.Wallet.Kernel.DB.Spec import Cardano.Wallet.Kernel.DB.Util.AcidState import Cardano.Wallet.Kernel.DB.Util.IxSet hiding (foldl') import qualified Cardano.Wallet.Kernel.DB.Util.IxSet as IxSet hiding (Indexable) import qualified Cardano.Wallet.Kernel.DB.Util.Zoomable as Z import Cardano.Wallet.Kernel.Decrypt (WalletDecrCredentials, decryptAddress) import Cardano.Wallet.Kernel.NodeStateAdaptor (SecurityParameter (..)) import qualified Cardano.Wallet.Kernel.Util.StrictList as SL import Cardano.Wallet.Kernel.Util.StrictNonEmpty (StrictNonEmpty (..)) import qualified Cardano.Wallet.Kernel.Util.StrictNonEmpty as SNE import UTxO.Util (liftNewestFirst, modifyAndGetOld) {------------------------------------------------------------------------------- Supporting types -------------------------------------------------------------------------------} -- | Wallet name newtype WalletName = WalletName { getWalletName :: Text } deriving (Eq, Show, Arbitrary) -- | Account name newtype AccountName = AccountName { getAccountName :: Text } -- | Account index newtype HdAccountIx = HdAccountIx { getHdAccountIx :: Word32 } deriving (Eq, Ord, Generic) instance NFData HdAccountIx -- NOTE(adn) if we need to generate only @hardened@ account indexes, we -- need to extend this arbitrary instance accordingly. instance Arbitrary HdAccountIx where arbitrary = HdAccountIx <$> arbitrary -- | Address index newtype HdAddressIx = HdAddressIx { getHdAddressIx :: Word32 } deriving (Eq, Ord) instance Arbitrary HdAddressIx where arbitrary = HdAddressIx <$> arbitrary -- | Wallet assurance level data AssuranceLevel = AssuranceLevelNormal | AssuranceLevelStrict deriving (Show, Eq) instance Arbitrary AssuranceLevel where arbitrary = oneof [ pure AssuranceLevelNormal , pure AssuranceLevelStrict ] -- | Interpretation of 'AssuranceLevel' -- -- This is adopted from the legacy wallet, which claims that these values -- are taken from <https://cardanodocs.com/cardano/transaction-assurance/> assuredBlockDepth :: AssuranceLevel -> Core.BlockCount assuredBlockDepth AssuranceLevelNormal = 9 assuredBlockDepth AssuranceLevelStrict = 15 -- | Does this wallet have a spending password data HasSpendingPassword = -- | No spending password set NoSpendingPassword -- | If there is a spending password, we record when it was last updated. | HasSpendingPassword !(InDb Core.Timestamp) deriving (Show, Eq) instance Arbitrary HasSpendingPassword where arbitrary = oneof [ pure NoSpendingPassword , HasSpendingPassword . InDb <$> arbitrary ] deriveSafeCopy 1 'base ''WalletName deriveSafeCopy 1 'base ''AccountName deriveSafeCopy 1 'base ''HdAccountIx deriveSafeCopy 1 'base ''HdAddressIx deriveSafeCopy 1 'base ''AssuranceLevel deriveSafeCopy 1 'base ''HasSpendingPassword {------------------------------------------------------------------------------- General-utility functions -------------------------------------------------------------------------------} -- | Computes the 'HdRootId' from the given 'EncryptedSecretKey'. See the -- comment in the definition of 'makePubKeyAddressBoot' on why this is -- acceptable. -- -- TODO: This may well disappear as part of [CBR-325]. eskToHdRootId :: NetworkMagic -> Core.EncryptedSecretKey -> HdRootId eskToHdRootId nm = HdRootId . InDb . (Core.makePubKeyAddressBoot nm) . Core.encToPublic eskToHdPassphrase :: Core.EncryptedSecretKey -> HDPassphrase eskToHdPassphrase = Core.deriveHDPassphrase . Core.encToPublic pkToHdRootId :: NetworkMagic -> Core.PublicKey -> HdRootId pkToHdRootId nm = HdRootId . InDb . (Core.makePubKeyAddressBoot nm) {------------------------------------------------------------------------------- HD wallets -------------------------------------------------------------------------------} -- | HD wallet root ID. -- -- Conceptually, this is just an 'Address' in the form -- of 'Ae2tdPwUPEZ18ZjTLnLVr9CEvUEUX4eW1LBHbxxxJgxdAYHrDeSCSbCxrvx', but is, -- in a sense, a special breed as it's derived from the 'PublicKey' (derived -- from some BIP-39 mnemonics, typically) and which does not depend from any -- delegation scheme, as you cannot really pay into this 'Address'. This -- ensures that, given an 'EncryptedSecretKey' we can derive its 'PublicKey' -- and from that the 'Core.Address'. -- On the \"other side\", given a RESTful 'WalletId' (which is ultimately -- just a Text) it's possible to call 'decodeTextAddress' to grab a valid -- 'Core.Address', and then transform this into a 'Kernel.WalletId' type -- easily. -- -- NOTE: Comparing 'HdRootId' is a potentially expensive computation, as it -- implies comparing large addresses. Use with care. -- -- TODO: It would be better not to have the address here, and just use an 'Int' -- as a primary key. This however is a slightly larger refactoring we don't -- currently have time for. newtype HdRootId = HdRootId { getHdRootId :: InDb Core.Address } deriving (Eq, Ord, Show, Generic) instance NFData HdRootId instance Arbitrary HdRootId where arbitrary = do (_, esk) <- Core.safeDeterministicKeyGen <$> (BS.pack <$> vectorOf 32 arbitrary) <*> pure mempty nm <- arbitrary pure (eskToHdRootId nm esk) -- | HD wallet account ID data HdAccountId = HdAccountId { _hdAccountIdParent :: !HdRootId , _hdAccountIdIx :: !HdAccountIx } deriving (Eq, Generic) instance NFData HdAccountId -- | We make sure to compare the account index first to avoid doing an -- unnecessary comparison of the root ID instance Ord HdAccountId where compare a b = compare (_hdAccountIdIx a) (_hdAccountIdIx b) <> compare (_hdAccountIdParent a) (_hdAccountIdParent b) instance Arbitrary HdAccountId where arbitrary = HdAccountId <$> arbitrary <*> arbitrary -- | HD wallet address ID data HdAddressId = HdAddressId { _hdAddressIdParent :: !HdAccountId , _hdAddressIdIx :: !HdAddressIx } deriving Eq -- | We make sure to compare the address index first to avoid doing an -- unnecessary comparison of the account ID instance Ord HdAddressId where compare a b = compare (_hdAddressIdIx a) (_hdAddressIdIx b) <> compare (_hdAddressIdParent a) (_hdAddressIdParent b) instance Arbitrary HdAddressId where arbitrary = HdAddressId <$> arbitrary <*> arbitrary -- | Root of a HD wallet -- -- The wallet has sequentially assigned account indices and randomly assigned -- address indices. -- -- NOTE: We do not store the encrypted key of the wallet. data HdRoot = HdRoot { -- | Wallet ID _hdRootId :: !HdRootId -- | Wallet name , _hdRootName :: !WalletName -- | Does this wallet have a spending password? -- -- NOTE: We do not store the spending password itself, but merely record -- whether there is one. Updates to the spending password affect only the -- external key storage, not the wallet DB proper. , _hdRootHasPassword :: !HasSpendingPassword -- | Assurance level , _hdRootAssurance :: !AssuranceLevel -- | When was this wallet created? , _hdRootCreatedAt :: !(InDb Core.Timestamp) } deriving (Eq, Show) instance Arbitrary HdRoot where arbitrary = HdRoot <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> (fmap InDb arbitrary) -- | Account in a HD wallet -- -- Key derivation is cheap data HdAccount = HdAccount { -- | Account index _hdAccountId :: !HdAccountId -- | Account name , _hdAccountName :: !AccountName -- | Account state -- -- When the account is up to date with the blockchain, the account state -- coincides with the state of a " wallet " as mandated by the formal -- spec. , _hdAccountState :: !HdAccountState -- | A local counter used to generate new 'AutoIncrementKey' for -- addresses. , _hdAccountAutoPkCounter :: !AutoIncrementKey } -- | Address in an account of a HD wallet data HdAddress = HdAddress { -- | Address ID _hdAddressId :: !HdAddressId -- | The actual address , _hdAddressAddress :: !(InDb Core.Address) } deriving Eq {------------------------------------------------------------------------------- Account state -------------------------------------------------------------------------------} -- | Account state (essentially, how much historical data do we have?) data HdAccountState = HdAccountStateUpToDate !HdAccountUpToDate | HdAccountStateIncomplete !HdAccountIncomplete -- | Account state for an account which has complete historical data data HdAccountUpToDate = HdAccountUpToDate { _hdUpToDateCheckpoints :: !(Checkpoints Checkpoint) } -- | Account state for an account which is lacking some historical checkpoints -- (which is currently being restored) data HdAccountIncomplete = HdAccountIncomplete { -- | Current checkpoints -- -- During wallet restoration we always track the underlying node, but may -- lack historical checkpoints. We synchronously construct a partial -- checkpoint for the current tip, and then as we get new blocks from -- the BListener, we add new partial checkpoints. _hdIncompleteCurrent :: !(Checkpoints PartialCheckpoint) -- | Historical full checkpoints -- -- Meanwhile, we asynchronously construct full checkpoints, starting -- from genesis. Once this gets to within k slots of the tip, we start -- keeping all of these. , _hdIncompleteHistorical :: !(Checkpoints Checkpoint) } makeLenses ''HdAccountUpToDate makeLenses ''HdAccountIncomplete data WithAccountState a b = UpToDate a | Incomplete b type CombinedWithAccountState a = WithAccountState a a -- | Restoration is complete when we have all historical checkpoints -- -- NOTE: -- -- * The local block metadata in the partial checkpoints /already/ -- accumulates (the local block metadata in the next partial checkpoint -- includes the local block metadata in the previous). Therefore we get the -- most recent /full/ checkpoint, and use that as the basis for constructing -- full block metadata for /all/ partial checkpoints. -- -- * We do NOT use the oldest partial checkpoint, since it will have its -- UTxO set from the underlying node's UTxO rather than from a block, and -- will therefore not have valid block metadata associated with it. -- (It is also possible that the initial checkpoint was created later, with -- an empty UTxO, if we discover it /during/ restoration). -- -- * We verify that the second-oldest partial checkpoint's previous pointer (if -- one exists) lines up with the most recent historical checkpoint. finishRestoration :: SecurityParameter -> HdAccountIncomplete -> HdAccountUpToDate finishRestoration (SecurityParameter k) (HdAccountIncomplete (Checkpoints partial) (Checkpoints historical)) = case SL.last initPartial of Nothing -> HdAccountUpToDate $ Checkpoints $ takeNewest k $ NewestFirst $ (mostRecentHistorical :| olderHistorical) Just secondLast -> let checkpoint = secondLast ^. pcheckpointContext in if checkpoint `blockContextSucceeds` (mostRecentHistorical ^. checkpointContext . lazy) then HdAccountUpToDate $ Checkpoints $ takeNewest k $ NewestFirst $ SNE.prependList (mkFull <$> initPartial) (mostRecentHistorical :| olderHistorical) else error "finishRestoration: checkpoints do not line up!" where (initPartial, _oldestPartial) = SNE.splitLast $ getNewestFirst partial mostRecentHistorical :| olderHistorical = getNewestFirst historical mkFull :: PartialCheckpoint -> Checkpoint mkFull = toFullCheckpoint (mostRecentHistorical ^. checkpointBlockMeta) takeNewest :: Int -> NewestFirst StrictNonEmpty a -> NewestFirst StrictNonEmpty a takeNewest = liftNewestFirst . SNE.take {------------------------------------------------------------------------------- Template Haskell splices -------------------------------------------------------------------------------} makeLenses ''HdAccountId makeLenses ''HdAddressId makeLenses ''HdRoot makeLenses ''HdAccount makeLenses ''HdAddress deriveSafeCopy 1 'base ''HdRootId deriveSafeCopy 1 'base ''HdAccountId deriveSafeCopy 1 'base ''HdAddressId deriveSafeCopy 1 'base ''HdRoot deriveSafeCopy 1 'base ''HdAccount deriveSafeCopy 1 'base ''HdAddress deriveSafeCopy 1 'base ''HdAccountState deriveSafeCopy 1 'base ''HdAccountUpToDate deriveSafeCopy 1 'base ''HdAccountIncomplete {------------------------------------------------------------------------------- Derived lenses -------------------------------------------------------------------------------} hdAccountRootId :: Lens' HdAccount HdRootId hdAccountRootId = hdAccountId . hdAccountIdParent hdAddressAccountId :: Lens' HdAddress HdAccountId hdAddressAccountId = hdAddressId . hdAddressIdParent hdAddressRootId :: Lens' HdAddress HdRootId hdAddressRootId = hdAddressAccountId . hdAccountIdParent hdAccountStateCurrent :: (forall c. IsCheckpoint c => Getter c a) -> Getter HdAccountState a hdAccountStateCurrent g = to $ \case HdAccountStateUpToDate st -> st ^. hdUpToDateCheckpoints . unCheckpoints . _Wrapped . SNE.head . g HdAccountStateIncomplete st -> st ^. hdIncompleteCurrent . unCheckpoints . _Wrapped . SNE.head . g hdAccountStateCurrentCombined :: (a -> a -> a) -> (forall c. IsCheckpoint c => Getter c a) -> Getter HdAccountState a hdAccountStateCurrentCombined combine g = to $ \case HdAccountStateUpToDate st -> st ^. hdUpToDateCheckpoints . unCheckpoints . _Wrapped . SNE.head . g HdAccountStateIncomplete st -> combine (st ^. hdIncompleteCurrent . unCheckpoints . _Wrapped . SNE.head . g) (st ^. hdIncompleteHistorical . unCheckpoints . _Wrapped . SNE.head . g) {------------------------------------------------------------------------------- Predicates and tests -------------------------------------------------------------------------------} hdAccountStateUpToDate :: HdAccount -> Bool hdAccountStateUpToDate a = case a ^. hdAccountState of HdAccountStateUpToDate _ -> True HdAccountStateIncomplete _ -> False hdAccountRestorationState :: HdAccount -> Maybe (Maybe BlockContext, BlockContext) hdAccountRestorationState a = case a ^. hdAccountState of HdAccountStateUpToDate _ -> Nothing HdAccountStateIncomplete HdAccountIncomplete{..} -> Just $ ( _hdIncompleteHistorical ^. currentCheckpoint . cpContext . lazy, _hdIncompleteCurrent ^. oldestCheckpoint . pcheckpointContext) {------------------------------------------------------------------------------- Address relationship: isOurs? -------------------------------------------------------------------------------} class IsOurs s where isOurs :: Core.Address -> s -> (Maybe HdAddress, s) {------------------------------------------------------------------------------- isOurs for Hd Random wallets -------------------------------------------------------------------------------} -- | NOTE: We could modify the given state here to actually store decrypted -- addresses in a `Map` to trade a decryption against a map lookup for already -- decrypted addresses. instance IsOurs [(HdRootId, Core.EncryptedSecretKey)] where isOurs addr s = (,s) $ foldl' (<|>) Nothing $ flip map s $ \(rootId, esk) -> do (accountIx, addressIx) <- decryptHdLvl2DerivationPath (eskToHdPassphrase esk) addr let accId = HdAccountId rootId accountIx let addrId = HdAddressId accId addressIx return $ HdAddress addrId (InDb addr) instance IsOurs [ (HdRootId, WalletDecrCredentials) ] where isOurs addr s = (,s) $ foldl' (<|>) Nothing $ flip map s $ \(rootId, wdc) -> do case decryptAddress wdc (addr::Core.Address) of Just (WAddressMeta _wid accountIx addressIx _addrv1) -> do let accId = HdAccountId rootId (HdAccountIx accountIx) addrId = HdAddressId accId (HdAddressIx addressIx) pure (HdAddress addrId (InDb addr)) Nothing -> Nothing decryptHdLvl2DerivationPath :: Core.HDPassphrase -> Core.Address -> Maybe (HdAccountIx, HdAddressIx) decryptHdLvl2DerivationPath hdPass addr = do hdPayload <- Core.aaPkDerivationPath $ Core.addrAttributesUnwrapped addr derPath <- Core.unpackHDAddressAttr hdPass hdPayload case derPath of [a,b] -> Just (HdAccountIx a, HdAddressIx b) _ -> Nothing {------------------------------------------------------------------------------- Unknown identifiers -------------------------------------------------------------------------------} -- | Unknown root data UnknownHdRoot = -- | Unknown root ID UnknownHdRoot HdRootId deriving Eq instance Arbitrary UnknownHdRoot where arbitrary = oneof [ UnknownHdRoot <$> arbitrary ] -- | Unknown account data UnknownHdAccount = -- | Unknown root ID UnknownHdAccountRoot HdRootId -- | Unknown account (implies the root is known) | UnknownHdAccount HdAccountId deriving Eq instance Arbitrary UnknownHdAccount where arbitrary = oneof [ UnknownHdAccountRoot <$> arbitrary , UnknownHdAccount <$> arbitrary ] -- | Unknown address data UnknownHdAddress = -- | Unknown root ID UnknownHdAddressRoot HdRootId -- | Unknown account (implies the root is known) | UnknownHdAddressAccount HdAccountId -- | Unknown address (implies the account is known) | UnknownHdAddress HdAddressId -- | Unknown address (implies it was not derived from the given Address) | UnknownHdCardanoAddress Core.Address instance Arbitrary UnknownHdAddress where arbitrary = oneof [ UnknownHdAddressRoot <$> arbitrary , UnknownHdAddressAccount <$> arbitrary , UnknownHdAddress <$> arbitrary , UnknownHdCardanoAddress <$> arbitrary ] embedUnknownHdRoot :: UnknownHdRoot -> UnknownHdAccount embedUnknownHdRoot = go where go (UnknownHdRoot rootId) = UnknownHdAccountRoot rootId embedUnknownHdAccount :: UnknownHdAccount -> UnknownHdAddress embedUnknownHdAccount = go where go (UnknownHdAccountRoot rootId) = UnknownHdAddressRoot rootId go (UnknownHdAccount accountId) = UnknownHdAddressAccount accountId deriveSafeCopy 1 'base ''UnknownHdRoot deriveSafeCopy 1 'base ''UnknownHdAddress deriveSafeCopy 1 'base ''UnknownHdAccount {------------------------------------------------------------------------------- IxSet instantiations -------------------------------------------------------------------------------} instance HasPrimKey HdRoot where type PrimKey HdRoot = HdRootId primKey = _hdRootId instance HasPrimKey HdAccount where type PrimKey HdAccount = HdAccountId primKey = _hdAccountId instance HasPrimKey (Indexed HdAddress) where type PrimKey (Indexed HdAddress) = HdAddressId primKey = _hdAddressId . _ixedIndexed type SecondaryHdRootIxs = '[] type SecondaryHdAccountIxs = '[HdRootId] type SecondaryIndexedHdAddressIxs = '[AutoIncrementKey, HdRootId, HdAccountId, V1 Core.Address] type instance IndicesOf HdRoot = SecondaryHdRootIxs type instance IndicesOf HdAccount = SecondaryHdAccountIxs type instance IndicesOf (Indexed HdAddress) = SecondaryIndexedHdAddressIxs instance IxSet.Indexable (HdRootId ': SecondaryHdRootIxs) (OrdByPrimKey HdRoot) where indices = ixList instance IxSet.Indexable (HdAccountId ': SecondaryHdAccountIxs) (OrdByPrimKey HdAccount) where indices = ixList (ixFun ((:[]) . view hdAccountRootId)) instance IxSet.Indexable (HdAddressId ': SecondaryIndexedHdAddressIxs) (OrdByPrimKey (Indexed HdAddress)) where indices = ixList (ixFun ((:[]) . view ixedIndex)) (ixFun ((:[]) . view (ixedIndexed . hdAddressRootId))) (ixFun ((:[]) . view (ixedIndexed . hdAddressAccountId))) (ixFun ((:[]) . V1 . view (ixedIndexed . hdAddressAddress . fromDb))) {------------------------------------------------------------------------------- Top-level HD wallet structure -------------------------------------------------------------------------------} -- | All wallets, accounts and addresses in the HD wallets -- -- We use a flat "relational" structure rather than nested maps so that we can -- go from address to wallet just as easily as the other way around. data HdWallets = HdWallets { _hdWalletsRoots :: !(IxSet HdRoot) , _hdWalletsAccounts :: !(IxSet HdAccount) , _hdWalletsAddresses :: !(IxSet (Indexed HdAddress)) } deriveSafeCopy 1 'base ''HdWallets makeLenses ''HdWallets initHdWallets :: HdWallets initHdWallets = HdWallets IxSet.empty IxSet.empty IxSet.empty {------------------------------------------------------------------------------- Zoom to existing parts of a HD wallet -------------------------------------------------------------------------------} zoomHdRootId :: forall f e a. CanZoom f => (UnknownHdRoot -> e) -> HdRootId -> f e HdRoot a -> f e HdWallets a zoomHdRootId embedErr rootId = zoomDef err (hdWalletsRoots . at rootId) where err :: f e HdWallets a err = missing $ embedErr (UnknownHdRoot rootId) zoomHdAccountId :: forall f e a. CanZoom f => (UnknownHdAccount -> e) -> HdAccountId -> f e HdAccount a -> f e HdWallets a zoomHdAccountId embedErr accId = zoomDef err (hdWalletsAccounts . at accId) where err :: f e HdWallets a err = zoomHdRootId embedErr' (accId ^. hdAccountIdParent) $ missing $ embedErr (UnknownHdAccount accId) embedErr' :: UnknownHdRoot -> e embedErr' = embedErr . embedUnknownHdRoot zoomHdAddressId :: forall f e a. CanZoom f => (UnknownHdAddress -> e) -> HdAddressId -> f e HdAddress a -> f e HdWallets a zoomHdAddressId embedErr addrId = zoomDef err (hdWalletsAddresses . at addrId) . zoom ixedIndexed where err :: f e HdWallets a err = zoomHdAccountId embedErr' (addrId ^. hdAddressIdParent) $ missing $ embedErr (UnknownHdAddress addrId) embedErr' :: UnknownHdAccount -> e embedErr' = embedErr . embedUnknownHdAccount -- | Zoom to the specified Cardano address -- -- This is defined on queries only for now. In principle we could define this -- more generally, but that would require somehow taking advantage of the fact -- that there cannot be more than one 'HdAddress' with a given 'Core.Address'. zoomHdCardanoAddress :: forall e a. (UnknownHdAddress -> e) -> Core.Address -> Query' e HdAddress a -> Query' e HdWallets a zoomHdCardanoAddress embedErr addr = localQuery findAddress where findAddress :: Query' e HdWallets HdAddress findAddress = do addresses <- view hdWalletsAddresses maybe err return $ (fmap _ixedIndexed $ getOne $ getEQ (V1 addr) addresses) err :: Query' e HdWallets x err = missing $ embedErr (UnknownHdCardanoAddress addr) -- | Pattern match on the state of the account matchHdAccountState :: CanZoom f => f e HdAccountUpToDate a -> f e HdAccountIncomplete a -> f e HdAccount a matchHdAccountState updUpToDate updIncomplete = withZoomableConstraints $ Z.wrap $ \acc -> case acc ^. hdAccountState of HdAccountStateUpToDate st -> do let upd st' = acc & hdAccountState .~ HdAccountStateUpToDate st' second upd $ Z.unwrap updUpToDate st HdAccountStateIncomplete st -> do let upd st' = acc & hdAccountState .~ HdAccountStateIncomplete st' second upd $ Z.unwrap updIncomplete st -- | Zoom to the current checkpoints of the wallet zoomHdAccountCheckpoints :: CanZoom f => ( forall c. IsCheckpoint c => f e (Checkpoints c) a ) -> f e HdAccount a zoomHdAccountCheckpoints upd = matchHdAccountCheckpoints upd upd -- | Zoom to the current checkpoints of the wallet. If the account is under -- restoration we combine the current historical and partial checkpoint. zoomHdAccountCheckpointsCombine :: CanZoom f => (a -> a -> a) -> ( forall c. IsCheckpoint c => f e (Checkpoints c) a ) -> f e HdAccount (CombinedWithAccountState a) zoomHdAccountCheckpointsCombine combine upd = matchHdAccountCheckpointsCombine combine upd upd -- | Zoom to the most recent checkpoint zoomHdAccountCurrent :: CanZoom f => (forall c. IsCheckpoint c => f e c a) -> f e HdAccount a zoomHdAccountCurrent upd = withZoomableConstraints $ zoomHdAccountCheckpoints $ Z.wrap $ \cps -> do let l :: Lens' (Checkpoints c) c l = unCheckpoints . _Wrapped . SNE.head second (\cp' -> cps & l .~ cp') $ Z.unwrap upd (cps ^. l) -- | Zoom to the most recent checkpoint. If the account is under -- restoration we combine the current historical and partial checkpoint. zoomHdAccountCurrentCombine :: CanZoom f => (a -> a -> a) -> (forall c. IsCheckpoint c => f e c a) -> f e HdAccount (CombinedWithAccountState a) zoomHdAccountCurrentCombine combine upd = withZoomableConstraints $ zoomHdAccountCheckpointsCombine combine $ Z.wrap $ \cps -> do let l :: Lens' (Checkpoints c) c l = unCheckpoints . _Wrapped . SNE.head second (\cp' -> cps & l .~ cp') $ Z.unwrap upd (cps ^. l) -- | Variant of 'zoomHdAccountCheckpoints' that distinguishes between -- full checkpoints (wallet is up to date) and partial checkpoints -- (wallet is still recovering historical data) matchHdAccountCheckpoints :: CanZoom f => f e (Checkpoints Checkpoint) a -> f e (Checkpoints PartialCheckpoint) a -> f e HdAccount a matchHdAccountCheckpoints updFull updPartial = matchHdAccountState (zoom hdUpToDateCheckpoints updFull) (zoom hdIncompleteCurrent updPartial) -- | Like matchHdAccountCheckpoints, but if also returns the state and if -- the account is under restoration we combine the current historical -- and partial checkpoint. matchHdAccountCheckpointsCombine :: CanZoom f => (a -> a -> a) -> f e (Checkpoints Checkpoint) a -> f e (Checkpoints PartialCheckpoint) a -> f e HdAccount (CombinedWithAccountState a) matchHdAccountCheckpointsCombine combine updFull updPartial = matchHdAccountState (withZoomableConstraints $ UpToDate <$> zoom hdUpToDateCheckpoints updFull) (withZoomableConstraints $ Incomplete <$> (combine <$> zoom hdIncompleteCurrent updPartial <*> zoom hdIncompleteHistorical updFull)) {------------------------------------------------------------------------------- Zoom to parts of the wallet, creating them if they don't exist -------------------------------------------------------------------------------} -- | Variation on 'zoomHdRootId' that creates the 'HdRoot' if it doesn't exist -- -- Precondition: @newRoot ^. hdRootId == rootId@ zoomOrCreateHdRoot :: HdRoot -> HdRootId -> Update' e HdRoot a -> Update' e HdWallets a zoomOrCreateHdRoot newRoot rootId upd = zoomCreate (return newRoot) (hdWalletsRoots . at rootId) $ upd -- | Variation on 'zoomHdAccountId' that creates the 'HdAccount' if it doesn't exist -- -- Precondition: @newAccount ^. hdAccountId == accountId@ zoomOrCreateHdAccount :: (HdRootId -> Update' e HdWallets ()) -> HdAccount -> HdAccountId -> Update' e HdAccount a -> Update' e HdWallets a zoomOrCreateHdAccount checkRootExists newAccount accId upd = do checkRootExists $ accId ^. hdAccountIdParent zoomCreate (return newAccount) (hdWalletsAccounts . at accId) $ upd -- | Variation on 'zoomHdAddressId' that creates the 'HdAddress' if it doesn't exist -- -- Precondition: @newAddress ^. hdAddressId == AddressId@ zoomOrCreateHdAddress :: (HdAccountId -> Update' e HdWallets ()) -> HdAddress -> HdAddressId -> Update' e HdAddress a -> Update' e HdWallets a zoomOrCreateHdAddress checkAccountExists newAddress addrId upd = do checkAccountExists accId zoomCreate createAddress (hdWalletsAddresses . at addrId) . zoom ixedIndexed $ upd where accId :: HdAccountId accId = addrId ^. hdAddressIdParent createAddress :: Update' e HdWallets (Indexed HdAddress) createAddress = do let err = "zoomOrCreateHdAddress: we checked that the account existed " <> "before calling this function, but the DB lookup failed nonetheless." acc <- zoomHdAccountId (error err) accId $ do modifyAndGetOld (hdAccountAutoPkCounter +~ 1) return $ Indexed (acc ^. hdAccountAutoPkCounter) newAddress -- | Assume that the given HdRoot exists -- -- Helper function which can be used as an argument to 'zoomOrCreateHdAccount' assumeHdRootExists :: HdRootId -> Update' e HdWallets () assumeHdRootExists _id = return () -- | Assume that the given HdAccount exists -- -- Helper function which can be used as an argument to 'zoomOrCreateHdAddress' assumeHdAccountExists :: HdAccountId -> Update' e HdWallets () assumeHdAccountExists _id = return () {------------------------------------------------------------------------------- Pretty printing -------------------------------------------------------------------------------} instance Buildable WalletName where build (WalletName wName) = bprint build wName instance Buildable AccountName where build (AccountName txt) = bprint build txt instance Buildable AssuranceLevel where build AssuranceLevelNormal = "normal" build AssuranceLevelStrict = "strict" instance Buildable HasSpendingPassword where build NoSpendingPassword = "no" build (HasSpendingPassword (InDb lastUpdate)) = bprint ("updated " % build) lastUpdate instance Buildable HdRoot where build HdRoot{..} = bprint ( "HdRoot " % "{ id: " % build % ", name: " % build % ", hasPassword: " % build % ", assurance: " % build % ", createdAt: " % build % "}" ) _hdRootId _hdRootName _hdRootHasPassword _hdRootAssurance (_fromDb _hdRootCreatedAt) instance Buildable HdAccount where build HdAccount{..} = bprint ( "HdAccount " % "{ id " % build % ", name " % build % ", state " % build % ", autoPkCounter " % build % "}" ) _hdAccountId _hdAccountName _hdAccountState _hdAccountAutoPkCounter instance Buildable HdAccountState where build (HdAccountStateUpToDate st) = bprint ("HdAccountStateUpToDate " % build) st build (HdAccountStateIncomplete st) = bprint ("HdAccountStateIncomplete " % build) st instance Buildable HdAccountUpToDate where build HdAccountUpToDate{..} = bprint ( "HdAccountUpToDate " % "{ checkpoints: " % listJson % "}" ) _hdUpToDateCheckpoints instance Buildable HdAccountIncomplete where build HdAccountIncomplete{..} = bprint ( "HdAccountIncomplete " % "{ current: " % listJson % ", historical: " % listJson % "}" ) _hdIncompleteCurrent _hdIncompleteHistorical instance Buildable HdAddress where build HdAddress{..} = bprint ( "HdAddress " % "{ id " % build % ", address " % build % "}" ) _hdAddressId (_fromDb _hdAddressAddress) instance Buildable HdRootId where build (HdRootId addr) = bprint ("HdRootId " % build) (_fromDb addr) instance Buildable HdAccountId where build HdAccountId{..} = bprint ( "HdAccountId " % "{ parent " % build % ", ix " % build % "}" ) _hdAccountIdParent _hdAccountIdIx instance Buildable HdAddressId where build HdAddressId{..} = bprint ( "HdAddressId " % " parent " % build % " ix " % build % "}" ) _hdAddressIdParent _hdAddressIdIx instance Buildable HdAccountIx where build (HdAccountIx ix) = bprint ("HdAccountIx " % build) ix instance Buildable HdAddressIx where build (HdAddressIx ix) = bprint ("HdAddressIx " % build) ix instance Buildable UnknownHdRoot where build (UnknownHdRoot rootId) = bprint ("UnknownHdRoot " % build) rootId instance Buildable UnknownHdAccount where build (UnknownHdAccountRoot rootId) = bprint ("UnknownHdAccountRoot " % build) rootId build (UnknownHdAccount accountId) = bprint ("UnknownHdAccount accountId " % build) accountId instance Buildable UnknownHdAddress where build (UnknownHdAddressRoot rootId) = bprint ("UnknownHdAddressRoot " % build) rootId build (UnknownHdAddressAccount accountId) = bprint ("UnknownHdAddress accountId " % build) accountId build (UnknownHdAddress addressId) = bprint ("UnknownHdAddress " % build) addressId build (UnknownHdCardanoAddress coreAddress) = bprint ("UnknownHdCardanoAddress " % build) coreAddress
input-output-hk/pos-haskell-prototype
wallet/src/Cardano/Wallet/Kernel/DB/HdWallet.hs
mit
38,022
0
20
8,901
6,895
3,715
3,180
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 The @Inst@ type: dictionaries or method instances -} {-# LANGUAGE CPP, MultiWayIf, TupleSections #-} module Inst ( deeplySkolemise, topInstantiate, topInstantiateInferred, deeplyInstantiate, instCall, instDFunType, instStupidTheta, newWanted, newWanteds, tcInstBinders, tcInstBindersX, newOverloadedLit, mkOverLit, newClsInst, tcGetInsts, tcGetInstEnvs, getOverlapFlag, tcExtendLocalInstEnv, instCallConstraints, newMethodFromName, tcSyntaxName, -- Simple functions over evidence variables tyCoVarsOfWC, tyCoVarsOfCt, tyCoVarsOfCts, ) where #include "HsVersions.h" import {-# SOURCE #-} TcExpr( tcPolyExpr, tcSyntaxOp ) import {-# SOURCE #-} TcUnify( unifyType, unifyKind, noThing ) import FastString import HsSyn import TcHsSyn import TcRnMonad import TcEnv import TcEvidence import InstEnv import TysWiredIn ( heqDataCon, coercibleDataCon ) import CoreSyn ( isOrphan ) import FunDeps import TcMType import Type import TcType import HscTypes import Class( Class ) import MkId( mkDictFunId ) import Id import Name import Var ( EvVar, mkTyVar ) import DataCon import TyCon import VarEnv import PrelNames import SrcLoc import DynFlags import Util import Outputable import qualified GHC.LanguageExtensions as LangExt import Control.Monad( unless ) import Data.Maybe( isJust ) {- ************************************************************************ * * Creating and emittind constraints * * ************************************************************************ -} newMethodFromName :: CtOrigin -> Name -> TcRhoType -> TcM (HsExpr TcId) -- Used when Name is the wired-in name for a wired-in class method, -- so the caller knows its type for sure, which should be of form -- forall a. C a => <blah> -- newMethodFromName is supposed to instantiate just the outer -- type variable and constraint newMethodFromName origin name inst_ty = do { id <- tcLookupId name -- Use tcLookupId not tcLookupGlobalId; the method is almost -- always a class op, but with -XRebindableSyntax GHC is -- meant to find whatever thing is in scope, and that may -- be an ordinary function. ; let ty = piResultTy (idType id) inst_ty (theta, _caller_knows_this) = tcSplitPhiTy ty ; wrap <- ASSERT( not (isForAllTy ty) && isSingleton theta ) instCall origin [inst_ty] theta ; return (mkHsWrap wrap (HsVar (noLoc id))) } {- ************************************************************************ * * Deep instantiation and skolemisation * * ************************************************************************ Note [Deep skolemisation] ~~~~~~~~~~~~~~~~~~~~~~~~~ deeplySkolemise decomposes and skolemises a type, returning a type with all its arrows visible (ie not buried under foralls) Examples: deeplySkolemise (Int -> forall a. Ord a => blah) = ( wp, [a], [d:Ord a], Int -> blah ) where wp = \x:Int. /\a. \(d:Ord a). <hole> x deeplySkolemise (forall a. Ord a => Maybe a -> forall b. Eq b => blah) = ( wp, [a,b], [d1:Ord a,d2:Eq b], Maybe a -> blah ) where wp = /\a.\(d1:Ord a).\(x:Maybe a)./\b.\(d2:Ord b). <hole> x In general, if deeplySkolemise ty = (wrap, tvs, evs, rho) and e :: rho then wrap e :: ty and 'wrap' binds tvs, evs ToDo: this eta-abstraction plays fast and loose with termination, because it can introduce extra lambdas. Maybe add a `seq` to fix this -} deeplySkolemise :: TcSigmaType -> TcM ( HsWrapper , [TyVar] -- all skolemised variables , [EvVar] -- all "given"s , TcRhoType) deeplySkolemise ty | Just (arg_tys, tvs, theta, ty') <- tcDeepSplitSigmaTy_maybe ty = do { ids1 <- newSysLocalIds (fsLit "dk") arg_tys ; (subst, tvs1) <- tcInstSkolTyVars tvs ; ev_vars1 <- newEvVars (substThetaUnchecked subst theta) ; (wrap, tvs2, ev_vars2, rho) <- deeplySkolemise (substTyAddInScope subst ty') ; return ( mkWpLams ids1 <.> mkWpTyLams tvs1 <.> mkWpLams ev_vars1 <.> wrap <.> mkWpEvVarApps ids1 , tvs1 ++ tvs2 , ev_vars1 ++ ev_vars2 , mkFunTys arg_tys rho ) } | otherwise = return (idHsWrapper, [], [], ty) -- | Instantiate all outer type variables -- and any context. Never looks through arrows. topInstantiate :: CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcRhoType) -- if topInstantiate ty = (wrap, rho) -- and e :: ty -- then wrap e :: rho (that is, wrap :: ty "->" rho) topInstantiate = top_instantiate True -- | Instantiate all outer 'Invisible' binders -- and any context. Never looks through arrows or specified type variables. -- Used for visible type application. topInstantiateInferred :: CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcSigmaType) -- if topInstantiate ty = (wrap, rho) -- and e :: ty -- then wrap e :: rho topInstantiateInferred = top_instantiate False top_instantiate :: Bool -- True <=> instantiate *all* variables -> CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcRhoType) top_instantiate inst_all orig ty | not (null binders && null theta) = do { let (inst_bndrs, leave_bndrs) = span should_inst binders (inst_theta, leave_theta) | null leave_bndrs = (theta, []) | otherwise = ([], theta) ; (subst, inst_tvs') <- newMetaTyVars (map (binderVar "top_inst") inst_bndrs) ; let inst_theta' = substThetaUnchecked subst inst_theta sigma' = substTyAddInScope subst (mkForAllTys leave_bndrs $ mkFunTys leave_theta rho) ; wrap1 <- instCall orig (mkTyVarTys inst_tvs') inst_theta' ; traceTc "Instantiating" (vcat [ text "all tyvars?" <+> ppr inst_all , text "origin" <+> pprCtOrigin orig , text "type" <+> ppr ty , text "with" <+> ppr inst_tvs' , text "theta:" <+> ppr inst_theta' ]) ; (wrap2, rho2) <- if null leave_bndrs -- account for types like forall a. Num a => forall b. Ord b => ... then top_instantiate inst_all orig sigma' -- but don't loop if there were any un-inst'able tyvars else return (idHsWrapper, sigma') ; return (wrap2 <.> wrap1, rho2) } | otherwise = return (idHsWrapper, ty) where (binders, phi) = tcSplitNamedPiTys ty (theta, rho) = tcSplitPhiTy phi should_inst bndr | inst_all = True | otherwise = binderVisibility bndr == Invisible deeplyInstantiate :: CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcRhoType) -- Int -> forall a. a -> a ==> (\x:Int. [] x alpha) :: Int -> alpha -- In general if -- if deeplyInstantiate ty = (wrap, rho) -- and e :: ty -- then wrap e :: rho -- That is, wrap :: ty "->" rho deeplyInstantiate orig ty | Just (arg_tys, tvs, theta, rho) <- tcDeepSplitSigmaTy_maybe ty = do { (subst, tvs') <- newMetaTyVars tvs ; ids1 <- newSysLocalIds (fsLit "di") (substTysUnchecked subst arg_tys) ; let theta' = substThetaUnchecked subst theta ; wrap1 <- instCall orig (mkTyVarTys tvs') theta' ; traceTc "Instantiating (deeply)" (vcat [ text "origin" <+> pprCtOrigin orig , text "type" <+> ppr ty , text "with" <+> ppr tvs' , text "args:" <+> ppr ids1 , text "theta:" <+> ppr theta' , text "subst:" <+> ppr subst ]) ; (wrap2, rho2) <- deeplyInstantiate orig (substTyUnchecked subst rho) ; return (mkWpLams ids1 <.> wrap2 <.> wrap1 <.> mkWpEvVarApps ids1, mkFunTys arg_tys rho2) } | otherwise = return (idHsWrapper, ty) {- ************************************************************************ * * Instantiating a call * * ************************************************************************ Note [Handling boxed equality] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The solver deals entirely in terms of unboxed (primitive) equality. There should never be a boxed Wanted equality. Ever. But, what if we are calling `foo :: forall a. (F a ~ Bool) => ...`? That equality is boxed, so naive treatment here would emit a boxed Wanted equality. So we simply check for this case and make the right boxing of evidence. -} ---------------- instCall :: CtOrigin -> [TcType] -> TcThetaType -> TcM HsWrapper -- Instantiate the constraints of a call -- (instCall o tys theta) -- (a) Makes fresh dictionaries as necessary for the constraints (theta) -- (b) Throws these dictionaries into the LIE -- (c) Returns an HsWrapper ([.] tys dicts) instCall orig tys theta = do { dict_app <- instCallConstraints orig theta ; return (dict_app <.> mkWpTyApps tys) } ---------------- instCallConstraints :: CtOrigin -> TcThetaType -> TcM HsWrapper -- Instantiates the TcTheta, puts all constraints thereby generated -- into the LIE, and returns a HsWrapper to enclose the call site. instCallConstraints orig preds | null preds = return idHsWrapper | otherwise = do { evs <- mapM go preds ; traceTc "instCallConstraints" (ppr evs) ; return (mkWpEvApps evs) } where go pred | Just (Nominal, ty1, ty2) <- getEqPredTys_maybe pred -- Try short-cut #1 = do { co <- unifyType noThing ty1 ty2 ; return (EvCoercion co) } -- Try short-cut #2 | Just (tc, args@[_, _, ty1, ty2]) <- splitTyConApp_maybe pred , tc `hasKey` heqTyConKey = do { co <- unifyType noThing ty1 ty2 ; return (EvDFunApp (dataConWrapId heqDataCon) args [EvCoercion co]) } | otherwise = emitWanted orig pred instDFunType :: DFunId -> [DFunInstType] -> TcM ( [TcType] -- instantiated argument types , TcThetaType ) -- instantiated constraint -- See Note [DFunInstType: instantiating types] in InstEnv instDFunType dfun_id dfun_inst_tys = do { (subst, inst_tys) <- go emptyTCvSubst dfun_tvs dfun_inst_tys ; return (inst_tys, substThetaUnchecked subst dfun_theta) } where (dfun_tvs, dfun_theta, _) = tcSplitSigmaTy (idType dfun_id) go :: TCvSubst -> [TyVar] -> [DFunInstType] -> TcM (TCvSubst, [TcType]) go subst [] [] = return (subst, []) go subst (tv:tvs) (Just ty : mb_tys) = do { (subst', tys) <- go (extendTvSubst subst tv ty) tvs mb_tys ; return (subst', ty : tys) } go subst (tv:tvs) (Nothing : mb_tys) = do { (subst', tv') <- newMetaTyVarX subst tv ; (subst'', tys) <- go subst' tvs mb_tys ; return (subst'', mkTyVarTy tv' : tys) } go _ _ _ = pprPanic "instDFunTypes" (ppr dfun_id $$ ppr dfun_inst_tys) ---------------- instStupidTheta :: CtOrigin -> TcThetaType -> TcM () -- Similar to instCall, but only emit the constraints in the LIE -- Used exclusively for the 'stupid theta' of a data constructor instStupidTheta orig theta = do { _co <- instCallConstraints orig theta -- Discard the coercion ; return () } {- ************************************************************************ * * Instantiating Kinds * * ************************************************************************ -} --------------------------- -- | This is used to instantiate binders when type-checking *types* only. -- See also Note [Bidirectional type checking] tcInstBinders :: [TyBinder] -> TcM (TCvSubst, [TcType]) tcInstBinders = tcInstBindersX emptyTCvSubst Nothing -- | This is used to instantiate binders when type-checking *types* only. -- The @VarEnv Kind@ gives some known instantiations. -- See also Note [Bidirectional type checking] tcInstBindersX :: TCvSubst -> Maybe (VarEnv Kind) -> [TyBinder] -> TcM (TCvSubst, [TcType]) tcInstBindersX subst mb_kind_info bndrs = do { (subst, args) <- mapAccumLM (tcInstBinderX mb_kind_info) subst bndrs ; traceTc "instantiating tybinders:" (vcat $ zipWith (\bndr arg -> ppr bndr <+> text ":=" <+> ppr arg) bndrs args) ; return (subst, args) } -- | Used only in *types* tcInstBinderX :: Maybe (VarEnv Kind) -> TCvSubst -> TyBinder -> TcM (TCvSubst, TcType) tcInstBinderX mb_kind_info subst binder | Just tv <- binderVar_maybe binder = case lookup_tv tv of Just ki -> return (extendTvSubstAndInScope subst tv ki, ki) Nothing -> do { (subst', tv') <- newMetaTyVarX subst tv ; return (subst', mkTyVarTy tv') } -- This is the *only* constraint currently handled in types. | Just (mk, role, k1, k2) <- get_pred_tys_maybe substed_ty = do { let origin = TypeEqOrigin { uo_actual = k1 , uo_expected = mkCheckExpType k2 , uo_thing = Nothing } ; co <- case role of Nominal -> unifyKind noThing k1 k2 Representational -> emitWantedEq origin KindLevel role k1 k2 Phantom -> pprPanic "tcInstBinderX Phantom" (ppr binder) ; arg' <- mk co k1 k2 ; return (subst, arg') } | isPredTy substed_ty = do { let (env, tidy_ty) = tidyOpenType emptyTidyEnv substed_ty ; addErrTcM (env, text "Illegal constraint in a type:" <+> ppr tidy_ty) -- just invent a new variable so that we can continue ; u <- newUnique ; let name = mkSysTvName u (fsLit "dict") ; return (subst, mkTyVarTy $ mkTyVar name substed_ty) } | otherwise = do { ty <- newFlexiTyVarTy substed_ty ; return (subst, ty) } where substed_ty = substTy subst (binderType binder) lookup_tv tv = do { env <- mb_kind_info -- `Maybe` monad ; lookupVarEnv env tv } -- handle boxed equality constraints, because it's so easy get_pred_tys_maybe ty | Just (r, k1, k2) <- getEqPredTys_maybe ty = Just (\co _ _ -> return $ mkCoercionTy co, r, k1, k2) | Just (tc, [_, _, k1, k2]) <- splitTyConApp_maybe ty = if | tc `hasKey` heqTyConKey -> Just (mkHEqBoxTy, Nominal, k1, k2) | otherwise -> Nothing | Just (tc, [_, k1, k2]) <- splitTyConApp_maybe ty = if | tc `hasKey` eqTyConKey -> Just (mkEqBoxTy, Nominal, k1, k2) | tc `hasKey` coercibleTyConKey -> Just (mkCoercibleBoxTy, Representational, k1, k2) | otherwise -> Nothing | otherwise = Nothing ------------------------------- -- | This takes @a ~# b@ and returns @a ~~ b@. mkHEqBoxTy :: TcCoercion -> Type -> Type -> TcM Type -- monadic just for convenience with mkEqBoxTy mkHEqBoxTy co ty1 ty2 = return $ mkTyConApp (promoteDataCon heqDataCon) [k1, k2, ty1, ty2, mkCoercionTy co] where k1 = typeKind ty1 k2 = typeKind ty2 -- | This takes @a ~# b@ and returns @a ~ b@. mkEqBoxTy :: TcCoercion -> Type -> Type -> TcM Type mkEqBoxTy co ty1 ty2 = do { eq_tc <- tcLookupTyCon eqTyConName ; let [datacon] = tyConDataCons eq_tc ; hetero <- mkHEqBoxTy co ty1 ty2 ; return $ mkTyConApp (promoteDataCon datacon) [k, ty1, ty2, hetero] } where k = typeKind ty1 -- | This takes @a ~R# b@ and returns @Coercible a b@. mkCoercibleBoxTy :: TcCoercion -> Type -> Type -> TcM Type -- monadic just for convenience with mkEqBoxTy mkCoercibleBoxTy co ty1 ty2 = do { return $ mkTyConApp (promoteDataCon coercibleDataCon) [k, ty1, ty2, mkCoercionTy co] } where k = typeKind ty1 {- ************************************************************************ * * Literals * * ************************************************************************ -} {- In newOverloadedLit we convert directly to an Int or Integer if we know that's what we want. This may save some time, by not temporarily generating overloaded literals, but it won't catch all cases (the rest are caught in lookupInst). -} newOverloadedLit :: HsOverLit Name -> ExpRhoType -> TcM (HsOverLit TcId) newOverloadedLit lit@(OverLit { ol_val = val, ol_rebindable = rebindable }) res_ty | not rebindable -- all built-in overloaded lits are tau-types, so we can just -- tauify the ExpType = do { res_ty <- expTypeToType res_ty ; dflags <- getDynFlags ; case shortCutLit dflags val res_ty of -- Do not generate a LitInst for rebindable syntax. -- Reason: If we do, tcSimplify will call lookupInst, which -- will call tcSyntaxName, which does unification, -- which tcSimplify doesn't like Just expr -> return (lit { ol_witness = expr, ol_type = res_ty , ol_rebindable = False }) Nothing -> newNonTrivialOverloadedLit orig lit (mkCheckExpType res_ty) } | otherwise = newNonTrivialOverloadedLit orig lit res_ty where orig = LiteralOrigin lit -- Does not handle things that 'shortCutLit' can handle. See also -- newOverloadedLit in TcUnify newNonTrivialOverloadedLit :: CtOrigin -> HsOverLit Name -> ExpRhoType -> TcM (HsOverLit TcId) newNonTrivialOverloadedLit orig lit@(OverLit { ol_val = val, ol_witness = HsVar (L _ meth_name) , ol_rebindable = rebindable }) res_ty = do { hs_lit <- mkOverLit val ; let lit_ty = hsLitType hs_lit ; (_, fi') <- tcSyntaxOp orig (mkRnSyntaxExpr meth_name) [synKnownType lit_ty] res_ty $ \_ -> return () ; let L _ witness = nlHsSyntaxApps fi' [nlHsLit hs_lit] ; res_ty <- readExpType res_ty ; return (lit { ol_witness = witness , ol_type = res_ty , ol_rebindable = rebindable }) } newNonTrivialOverloadedLit _ lit _ = pprPanic "newNonTrivialOverloadedLit" (ppr lit) ------------ mkOverLit :: OverLitVal -> TcM HsLit mkOverLit (HsIntegral src i) = do { integer_ty <- tcMetaTy integerTyConName ; return (HsInteger src i integer_ty) } mkOverLit (HsFractional r) = do { rat_ty <- tcMetaTy rationalTyConName ; return (HsRat r rat_ty) } mkOverLit (HsIsString src s) = return (HsString src s) {- ************************************************************************ * * Re-mappable syntax Used only for arrow syntax -- find a way to nuke this * * ************************************************************************ Suppose we are doing the -XRebindableSyntax thing, and we encounter a do-expression. We have to find (>>) in the current environment, which is done by the rename. Then we have to check that it has the same type as Control.Monad.(>>). Or, more precisely, a compatible type. One 'customer' had this: (>>) :: HB m n mn => m a -> n b -> mn b So the idea is to generate a local binding for (>>), thus: let then72 :: forall a b. m a -> m b -> m b then72 = ...something involving the user's (>>)... in ...the do-expression... Now the do-expression can proceed using then72, which has exactly the expected type. In fact tcSyntaxName just generates the RHS for then72, because we only want an actual binding in the do-expression case. For literals, we can just use the expression inline. -} tcSyntaxName :: CtOrigin -> TcType -- Type to instantiate it at -> (Name, HsExpr Name) -- (Standard name, user name) -> TcM (Name, HsExpr TcId) -- (Standard name, suitable expression) -- USED ONLY FOR CmdTop (sigh) *** -- See Note [CmdSyntaxTable] in HsExpr tcSyntaxName orig ty (std_nm, HsVar (L _ user_nm)) | std_nm == user_nm = do rhs <- newMethodFromName orig std_nm ty return (std_nm, rhs) tcSyntaxName orig ty (std_nm, user_nm_expr) = do std_id <- tcLookupId std_nm let -- C.f. newMethodAtLoc ([tv], _, tau) = tcSplitSigmaTy (idType std_id) sigma1 = substTyWith [tv] [ty] tau -- Actually, the "tau-type" might be a sigma-type in the -- case of locally-polymorphic methods. addErrCtxtM (syntaxNameCtxt user_nm_expr orig sigma1) $ do -- Check that the user-supplied thing has the -- same type as the standard one. -- Tiresome jiggling because tcCheckSigma takes a located expression span <- getSrcSpanM expr <- tcPolyExpr (L span user_nm_expr) sigma1 return (std_nm, unLoc expr) syntaxNameCtxt :: HsExpr Name -> CtOrigin -> Type -> TidyEnv -> TcRn (TidyEnv, SDoc) syntaxNameCtxt name orig ty tidy_env = do { inst_loc <- getCtLocM orig (Just TypeLevel) ; let msg = vcat [ text "When checking that" <+> quotes (ppr name) <+> text "(needed by a syntactic construct)" , nest 2 (text "has the required type:" <+> ppr (tidyType tidy_env ty)) , nest 2 (pprCtLoc inst_loc) ] ; return (tidy_env, msg) } {- ************************************************************************ * * Instances * * ************************************************************************ -} getOverlapFlag :: Maybe OverlapMode -> TcM OverlapFlag -- Construct the OverlapFlag from the global module flags, -- but if the overlap_mode argument is (Just m), -- set the OverlapMode to 'm' getOverlapFlag overlap_mode = do { dflags <- getDynFlags ; let overlap_ok = xopt LangExt.OverlappingInstances dflags incoherent_ok = xopt LangExt.IncoherentInstances dflags use x = OverlapFlag { isSafeOverlap = safeLanguageOn dflags , overlapMode = x } default_oflag | incoherent_ok = use (Incoherent "") | overlap_ok = use (Overlaps "") | otherwise = use (NoOverlap "") final_oflag = setOverlapModeMaybe default_oflag overlap_mode ; return final_oflag } tcGetInsts :: TcM [ClsInst] -- Gets the local class instances. tcGetInsts = fmap tcg_insts getGblEnv newClsInst :: Maybe OverlapMode -> Name -> [TyVar] -> ThetaType -> Class -> [Type] -> TcM ClsInst newClsInst overlap_mode dfun_name tvs theta clas tys = do { (subst, tvs') <- freshenTyVarBndrs tvs -- Be sure to freshen those type variables, -- so they are sure not to appear in any lookup ; let tys' = substTys subst tys theta' = substTheta subst theta dfun = mkDictFunId dfun_name tvs' theta' clas tys' -- Substituting in the DFun type just makes sure that -- we are using TyVars rather than TcTyVars -- Not sure if this is really the right place to do so, -- but it'll do fine ; oflag <- getOverlapFlag overlap_mode ; let inst = mkLocalInstance dfun oflag tvs' clas tys' ; dflags <- getDynFlags ; warnIf (Reason Opt_WarnOrphans) (isOrphan (is_orphan inst) && wopt Opt_WarnOrphans dflags) (instOrphWarn inst) ; return inst } instOrphWarn :: ClsInst -> SDoc instOrphWarn inst = hang (text "Orphan instance:") 2 (pprInstanceHdr inst) $$ text "To avoid this" $$ nest 4 (vcat possibilities) where possibilities = text "move the instance declaration to the module of the class or of the type, or" : text "wrap the type with a newtype and declare the instance on the new type." : [] tcExtendLocalInstEnv :: [ClsInst] -> TcM a -> TcM a -- Add new locally-defined instances tcExtendLocalInstEnv dfuns thing_inside = do { traceDFuns dfuns ; env <- getGblEnv ; (inst_env', cls_insts') <- foldlM addLocalInst (tcg_inst_env env, tcg_insts env) dfuns ; let env' = env { tcg_insts = cls_insts' , tcg_inst_env = inst_env' } ; setGblEnv env' thing_inside } addLocalInst :: (InstEnv, [ClsInst]) -> ClsInst -> TcM (InstEnv, [ClsInst]) -- Check that the proposed new instance is OK, -- and then add it to the home inst env -- If overwrite_inst, then we can overwrite a direct match addLocalInst (home_ie, my_insts) ispec = do { -- Load imported instances, so that we report -- duplicates correctly -- 'matches' are existing instance declarations that are less -- specific than the new one -- 'dups' are those 'matches' that are equal to the new one ; isGHCi <- getIsGHCi ; eps <- getEps ; tcg_env <- getGblEnv -- In GHCi, we *override* any identical instances -- that are also defined in the interactive context -- See Note [Override identical instances in GHCi] ; let home_ie' | isGHCi = deleteFromInstEnv home_ie ispec | otherwise = home_ie -- If we're compiling sig-of and there's an external duplicate -- instance, silently ignore it (that's the instance we're -- implementing!) NB: we still count local duplicate instances -- as errors. -- See Note [Signature files and type class instances] global_ie | isJust (tcg_sig_of tcg_env) = emptyInstEnv | otherwise = eps_inst_env eps inst_envs = InstEnvs { ie_global = global_ie , ie_local = home_ie' , ie_visible = tcVisibleOrphanMods tcg_env } -- Check for inconsistent functional dependencies ; let inconsistent_ispecs = checkFunDeps inst_envs ispec ; unless (null inconsistent_ispecs) $ funDepErr ispec inconsistent_ispecs -- Check for duplicate instance decls. ; let (_tvs, cls, tys) = instanceHead ispec (matches, _, _) = lookupInstEnv False inst_envs cls tys dups = filter (identicalClsInstHead ispec) (map fst matches) ; unless (null dups) $ dupInstErr ispec (head dups) ; return (extendInstEnv home_ie' ispec, ispec : my_insts) } {- Note [Signature files and type class instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Instances in signature files do not have an effect when compiling: when you compile a signature against an implementation, you will see the instances WHETHER OR NOT the instance is declared in the file (this is because the signatures go in the EPS and we can't filter them out easily.) This is also why we cannot place the instance in the hi file: it would show up as a duplicate, and we don't have instance reexports anyway. However, you might find them useful when typechecking against a signature: the instance is a way of indicating to GHC that some instance exists, in case downstream code uses it. Implementing this is a little tricky. Consider the following situation (sigof03): module A where instance C T where ... module ASig where instance C T When compiling ASig, A.hi is loaded, which brings its instances into the EPS. When we process the instance declaration in ASig, we should ignore it for the purpose of doing a duplicate check, since it's not actually a duplicate. But don't skip the check entirely, we still want this to fail (tcfail221): module ASig where instance C T instance C T Note that in some situations, the interface containing the type class instances may not have been loaded yet at all. The usual situation when A imports another module which provides the instances (sigof02m): module A(module B) where import B See also Note [Signature lazy interface loading]. We can't rely on this, however, since sometimes we'll have spurious type class instances in the EPS, see #9422 (sigof02dm) ************************************************************************ * * Errors and tracing * * ************************************************************************ -} traceDFuns :: [ClsInst] -> TcRn () traceDFuns ispecs = traceTc "Adding instances:" (vcat (map pp ispecs)) where pp ispec = hang (ppr (instanceDFunId ispec) <+> colon) 2 (ppr ispec) -- Print the dfun name itself too funDepErr :: ClsInst -> [ClsInst] -> TcRn () funDepErr ispec ispecs = addClsInstsErr (text "Functional dependencies conflict between instance declarations:") (ispec : ispecs) dupInstErr :: ClsInst -> ClsInst -> TcRn () dupInstErr ispec dup_ispec = addClsInstsErr (text "Duplicate instance declarations:") [ispec, dup_ispec] addClsInstsErr :: SDoc -> [ClsInst] -> TcRn () addClsInstsErr herald ispecs = setSrcSpan (getSrcSpan (head sorted)) $ addErr (hang herald 2 (pprInstances sorted)) where sorted = sortWith getSrcLoc ispecs -- The sortWith just arranges that instances are dislayed in order -- of source location, which reduced wobbling in error messages, -- and is better for users
oldmanmike/ghc
compiler/typecheck/Inst.hs
bsd-3-clause
30,943
8
17
9,465
5,612
2,933
2,679
410
7
------------------------------------------------------------------------------ {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} module Snap.Snaplet.Session.Backends.CookieSession ( initCookieSessionManager ) where ------------------------------------------------------------------------------ import Control.Monad.Reader import Data.ByteString (ByteString) import Data.Typeable import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM import Data.Serialize (Serialize) import qualified Data.Serialize as S import Data.Text (Text) import Data.Text.Encoding import Snap.Core (Snap) import Web.ClientSession #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif ------------------------------------------------------------------------------ import Snap.Snaplet import Snap.Snaplet.Session import Snap.Snaplet.Session.SessionManager ------------------------------------------------------------------------------- ------------------------------------------------------------------------------ -- | Session data are kept in a 'HashMap' for this backend -- type Session = HashMap Text Text ------------------------------------------------------------------------------ -- | This is what the 'Payload' will be for the CookieSession backend -- data CookieSession = CookieSession { csCSRFToken :: Text , csSession :: Session } deriving (Eq, Show) ------------------------------------------------------------------------------ instance Serialize CookieSession where put (CookieSession a b) = S.put (encodeUtf8 a, map encodeTuple $ HM.toList b) get = let unpack (a,b) = CookieSession (decodeUtf8 a) (HM.fromList $ map decodeTuple b) in unpack <$> S.get encodeTuple :: (Text, Text) -> (ByteString, ByteString) encodeTuple (a,b) = (encodeUtf8 a, encodeUtf8 b) decodeTuple :: (ByteString, ByteString) -> (Text, Text) decodeTuple (a,b) = (decodeUtf8 a, decodeUtf8 b) ------------------------------------------------------------------------------ mkCookieSession :: RNG -> IO CookieSession mkCookieSession rng = do t <- liftIO $ mkCSRFToken rng return $ CookieSession t HM.empty ------------------------------------------------------------------------------ -- | The manager data type to be stuffed into 'SessionManager' -- data CookieSessionManager = CookieSessionManager { session :: Maybe CookieSession -- ^ Per request cache for 'CookieSession' , siteKey :: Key -- ^ A long encryption key used for secure cookie transport , cookieName :: ByteString -- ^ Cookie name for the session system , cookieDomain :: Maybe ByteString -- ^ Cookie domain for session system. You may want to set it to -- dot prefixed domain name like ".example.com", so the cookie is -- available to sub domains. , timeOut :: Maybe Int -- ^ Session cookies will be considered "stale" after this many -- seconds. , randomNumberGenerator :: RNG -- ^ handle to a random number generator } deriving (Typeable) ------------------------------------------------------------------------------ loadDefSession :: CookieSessionManager -> IO CookieSessionManager loadDefSession mgr@(CookieSessionManager ses _ _ _ _ rng) = case ses of Nothing -> do ses' <- mkCookieSession rng return $! mgr { session = Just ses' } Just _ -> return mgr ------------------------------------------------------------------------------ modSession :: (Session -> Session) -> CookieSession -> CookieSession modSession f (CookieSession t ses) = CookieSession t (f ses) ------------------------------------------------------------------------------ -- | Initialize a cookie-backed session, returning a 'SessionManager' to be -- stuffed inside your application's state. This 'SessionManager' will enable -- the use of all session storage functionality defined in -- 'Snap.Snaplet.Session' -- initCookieSessionManager :: FilePath -- ^ Path to site-wide encryption key -> ByteString -- ^ Session cookie name -> Maybe ByteString -- ^ Session cookie domain -> Maybe Int -- ^ Session time-out (replay attack protection) -> SnapletInit b SessionManager initCookieSessionManager fp cn dom to = makeSnaplet "CookieSession" "A snaplet providing sessions via HTTP cookies." Nothing $ liftIO $ do key <- getKey fp rng <- liftIO mkRNG return $! SessionManager $ CookieSessionManager Nothing key cn dom to rng ------------------------------------------------------------------------------ instance ISessionManager CookieSessionManager where -------------------------------------------------------------------------- load mgr@(CookieSessionManager r _ _ _ _ _) = case r of Just _ -> return mgr Nothing -> do pl <- getPayload mgr case pl of Nothing -> liftIO $ loadDefSession mgr Just (Payload x) -> do let c = S.decode x case c of Left _ -> liftIO $ loadDefSession mgr Right cs -> return $ mgr { session = Just cs } -------------------------------------------------------------------------- commit mgr@(CookieSessionManager r _ _ _ _ rng) = do pl <- case r of Just r' -> return . Payload $ S.encode r' Nothing -> liftIO (mkCookieSession rng) >>= return . Payload . S.encode setPayload mgr pl -------------------------------------------------------------------------- reset mgr = do cs <- liftIO $ mkCookieSession (randomNumberGenerator mgr) return $ mgr { session = Just cs } -------------------------------------------------------------------------- touch = id -------------------------------------------------------------------------- insert k v mgr@(CookieSessionManager r _ _ _ _ _) = case r of Just r' -> mgr { session = Just $ modSession (HM.insert k v) r' } Nothing -> mgr -------------------------------------------------------------------------- lookup k (CookieSessionManager r _ _ _ _ _) = r >>= HM.lookup k . csSession -------------------------------------------------------------------------- delete k mgr@(CookieSessionManager r _ _ _ _ _) = case r of Just r' -> mgr { session = Just $ modSession (HM.delete k) r' } Nothing -> mgr -------------------------------------------------------------------------- csrf (CookieSessionManager r _ _ _ _ _) = case r of Just r' -> csCSRFToken r' Nothing -> "" -------------------------------------------------------------------------- toList (CookieSessionManager r _ _ _ _ _) = case r of Just r' -> HM.toList . csSession $ r' Nothing -> [] ------------------------------------------------------------------------------ -- | A session payload to be stored in a SecureCookie. newtype Payload = Payload ByteString deriving (Eq, Show, Ord, Serialize) ------------------------------------------------------------------------------ -- | Get the current client-side value getPayload :: CookieSessionManager -> Snap (Maybe Payload) getPayload mgr = getSecureCookie (cookieName mgr) (siteKey mgr) (timeOut mgr) ------------------------------------------------------------------------------ -- | Set the client-side value setPayload :: CookieSessionManager -> Payload -> Snap () setPayload mgr x = setSecureCookie (cookieName mgr) (cookieDomain mgr) (siteKey mgr) (timeOut mgr) x
sopvop/snap
src/Snap/Snaplet/Session/Backends/CookieSession.hs
bsd-3-clause
8,256
24
20
2,049
1,486
803
683
113
2
{-# OPTIONS_GHC -cpp -fffi #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Utils -- Copyright : Isaac Jones, Simon Marlow 2003-2004 -- -- Maintainer : Isaac Jones <[email protected]> -- Stability : alpha -- Portability : portable -- -- Explanation: Misc. Utilities, especially file-related utilities. -- Stuff used by multiple modules that doesn't fit elsewhere. {- All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Isaac Jones nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Distribution.Simple.Utils ( die, dieWithLocation, warn, rawSystemPath, rawSystemVerbose, rawSystemExit, maybeExit, xargs, matchesDescFile, rawSystemPathExit, smartCopySources, copyFileVerbose, copyDirectoryRecursiveVerbose, moduleToFilePath, mkLibName, mkProfLibName, currentDir, dirOf, dotToSep, withTempFile, findFile, defaultPackageDesc, findPackageDesc, defaultHookedPackageDesc, findHookedPackageDesc, distPref, haddockPref, srcPref, #ifdef DEBUG hunitTests #endif ) where #if __GLASGOW_HASKELL__ && __GLASGOW_HASKELL__ < 604 #if __GLASGOW_HASKELL__ < 603 #include "config.h" #else #include "ghcconfig.h" #endif #endif import Distribution.Compat.RawSystem (rawSystem) import Distribution.Compat.Exception (finally) import Control.Monad(when, filterM, unless) import Data.List (nub, unfoldr) import System.Environment (getProgName) import System.IO (hPutStrLn, stderr, hFlush, stdout) import System.IO.Error import System.Exit #if (__GLASGOW_HASKELL__ || __HUGS__) && !(mingw32_HOST_OS || mingw32_TARGET_OS) import System.Posix.Internals (c_getpid) #endif import Distribution.Compat.FilePath (splitFileName, splitFileExt, joinFileName, joinFileExt, joinPaths, pathSeparator,splitFilePath) import System.Directory (getDirectoryContents, getCurrentDirectory , doesDirectoryExist, doesFileExist, removeFile, getPermissions , Permissions(executable)) import Distribution.Compat.Directory (copyFile, findExecutable, createDirectoryIfMissing, getDirectoryContentsWithoutSpecial) #ifdef DEBUG import HUnit ((~:), (~=?), Test(..), assertEqual) #endif -- ------------------------------------------------------------------------------- Utils for setup dieWithLocation :: FilePath -> (Maybe Int) -> String -> IO a dieWithLocation fname Nothing msg = die (fname ++ ": " ++ msg) dieWithLocation fname (Just n) msg = die (fname ++ ":" ++ show n ++ ": " ++ msg) die :: String -> IO a die msg = do hFlush stdout pname <- getProgName hPutStrLn stderr (pname ++ ": " ++ msg) exitWith (ExitFailure 1) warn :: String -> IO () warn msg = do hFlush stdout pname <- getProgName hPutStrLn stderr (pname ++ ": Warning: " ++ msg) -- ----------------------------------------------------------------------------- -- rawSystem variants rawSystemPath :: Int -> String -> [String] -> IO ExitCode rawSystemPath verbose prog args = do r <- findExecutable prog case r of Nothing -> die ("Cannot find: " ++ prog) Just path -> rawSystemVerbose verbose path args rawSystemVerbose :: Int -> FilePath -> [String] -> IO ExitCode rawSystemVerbose verbose prog args = do when (verbose > 0) $ putStrLn (prog ++ concatMap (' ':) args) e <- doesFileExist prog if e then do perms <- getPermissions prog if (executable perms) then rawSystem prog args else die ("Error: file is not executable: " ++ show prog) else die ("Error: file does not exist: " ++ show prog) maybeExit :: IO ExitCode -> IO () maybeExit cmd = do res <- cmd if res /= ExitSuccess then exitWith res else return () -- Exit with the same exitcode if the subcommand fails rawSystemExit :: Int -> FilePath -> [String] -> IO () rawSystemExit verbose path args = do when (verbose > 0) $ putStrLn (path ++ concatMap (' ':) args) maybeExit $ rawSystem path args -- Exit with the same exitcode if the subcommand fails rawSystemPathExit :: Int -> String -> [String] -> IO () rawSystemPathExit verbose prog args = do maybeExit $ rawSystemPath verbose prog args -- | Like the unix xargs program. Useful for when we've got very long command -- lines that might overflow an OS limit on command line length and so you -- need to invoke a command multiple times to get all the args in. -- -- Use it with either of the rawSystem variants above. For example: -- -- > xargs (32*1024) (rawSystemPath verbose) prog fixedArgs bigArgs -- xargs :: Int -> (FilePath -> [String] -> IO ExitCode) -> FilePath -> [String] -> [String] -> IO ExitCode xargs maxSize rawSystem prog fixedArgs bigArgs = let fixedArgSize = sum (map length fixedArgs) + length fixedArgs chunkSize = maxSize - fixedArgSize loop [] = return ExitSuccess loop (args:remainingArgs) = do status <- rawSystem prog (fixedArgs ++ args) case status of ExitSuccess -> loop remainingArgs _ -> return status in loop (chunks chunkSize bigArgs) where chunks len = unfoldr $ \s -> if null s then Nothing else Just (chunk [] len s) chunk acc len [] = (reverse acc,[]) chunk acc len (s:ss) | len' < len = chunk (s:acc) (len-len'-1) ss | otherwise = (reverse acc, s:ss) where len' = length s -- ------------------------------------------------------------ -- * File Utilities -- ------------------------------------------------------------ -- |Get the file path for this particular module. In the IO monad -- because it looks for the actual file. Might eventually interface -- with preprocessor libraries in order to correctly locate more -- filenames. -- Returns empty list if no such files exist. moduleToFilePath :: [FilePath] -- ^search locations -> String -- ^Module Name -> [String] -- ^possible suffixes -> IO [FilePath] moduleToFilePath pref s possibleSuffixes = filterM doesFileExist $ concatMap (searchModuleToPossiblePaths s possibleSuffixes) pref where searchModuleToPossiblePaths :: String -> [String] -> FilePath -> [FilePath] searchModuleToPossiblePaths s' suffs searchP = moduleToPossiblePaths searchP s' suffs -- |Like 'moduleToFilePath', but return the location and the rest of -- the path as separate results. moduleToFilePath2 :: [FilePath] -- ^search locations -> String -- ^Module Name -> [String] -- ^possible suffixes -> IO [(FilePath, FilePath)] -- ^locations and relative names moduleToFilePath2 locs mname possibleSuffixes = filterM exists $ [(loc, fname `joinFileExt` ext) | loc <- locs, ext <- possibleSuffixes] where fname = dotToSep mname exists (loc, relname) = doesFileExist (loc `joinFileName` relname) -- |Get the possible file paths based on this module name. moduleToPossiblePaths :: FilePath -- ^search prefix -> String -- ^module name -> [String] -- ^possible suffixes -> [FilePath] moduleToPossiblePaths searchPref s possibleSuffixes = let fname = searchPref `joinFileName` (dotToSep s) in [fname `joinFileExt` ext | ext <- possibleSuffixes] findFile :: [FilePath] -- ^search locations -> FilePath -- ^File Name -> IO FilePath findFile prefPathsIn locPath = do let prefPaths = nub prefPathsIn -- ignore dups paths <- filterM doesFileExist [prefPath `joinFileName` locPath | prefPath <- prefPaths] case nub paths of -- also ignore dups, though above nub should fix this. [path] -> return path [] -> die (locPath ++ " doesn't exist") paths -> die (locPath ++ " is found in multiple places:" ++ unlines (map ((++) " ") paths)) dotToSep :: String -> String dotToSep = map dts where dts '.' = pathSeparator dts c = c -- |Copy the source files into the right directory. Looks in the -- build prefix for files that look like the input modules, based on -- the input search suffixes. It copies the files into the target -- directory. smartCopySources :: Int -- ^verbose -> [FilePath] -- ^build prefix (location of objects) -> FilePath -- ^Target directory -> [String] -- ^Modules -> [String] -- ^search suffixes -> Bool -- ^Exit if no such modules -> Bool -- ^Preserve directory structure -> IO () smartCopySources verbose srcDirs targetDir sources searchSuffixes exitIfNone preserveDirs = do createDirectoryIfMissing True targetDir allLocations <- mapM moduleToFPErr sources let copies = [(srcDir `joinFileName` name, if preserveDirs then targetDir `joinFileName` srcDir `joinFileName` name else targetDir `joinFileName` name) | (srcDir, name) <- concat allLocations] -- Create parent directories for everything: mapM_ (createDirectoryIfMissing True) $ nub $ [fst (splitFileName targetFile) | (_, targetFile) <- copies] -- Put sources into place: sequence_ [copyFileVerbose verbose srcFile destFile | (srcFile, destFile) <- copies] where moduleToFPErr m = do p <- moduleToFilePath2 srcDirs m searchSuffixes when (null p && exitIfNone) (die ("Error: Could not find module: " ++ m ++ " with any suffix: " ++ (show searchSuffixes))) return p copyFileVerbose :: Int -> FilePath -> FilePath -> IO () copyFileVerbose verbose src dest = do when (verbose > 0) $ putStrLn ("copy " ++ src ++ " to " ++ dest) copyFile src dest -- adaptation of removeDirectoryRecursive copyDirectoryRecursiveVerbose :: Int -> FilePath -> FilePath -> IO () copyDirectoryRecursiveVerbose verbose srcDir destDir = do when (verbose > 0) $ putStrLn ("copy directory '" ++ srcDir ++ "' to '" ++ destDir ++ "'.") let aux src dest = let cp :: FilePath -> IO () cp f = let srcFile = joinPaths src f destFile = joinPaths dest f in do success <- try (copyFileVerbose verbose srcFile destFile) case success of Left e -> do isDir <- doesDirectoryExist srcFile -- If f is not a directory, re-throw the error unless isDir $ ioError e aux srcFile destFile Right _ -> return () in do createDirectoryIfMissing False dest getDirectoryContentsWithoutSpecial src >>= mapM_ cp in aux srcDir destDir -- | The path name that represents the current directory. -- In Unix, it's @\".\"@, but this is system-specific. -- (E.g. AmigaOS uses the empty string @\"\"@ for the current directory.) currentDir :: FilePath currentDir = "." dirOf :: FilePath -> FilePath dirOf f = (\ (x, _, _) -> x) $ (splitFilePath f) mkLibName :: FilePath -- ^file Prefix -> String -- ^library name. -> String mkLibName pref lib = pref `joinFileName` ("libHS" ++ lib ++ ".a") mkProfLibName :: FilePath -- ^file Prefix -> String -- ^library name. -> String mkProfLibName pref lib = mkLibName pref (lib++"_p") -- ------------------------------------------------------------ -- * Some Paths -- ------------------------------------------------------------ distPref :: FilePath distPref = "dist" srcPref :: FilePath srcPref = distPref `joinFileName` "src" haddockPref :: FilePath haddockPref = foldl1 joinPaths [distPref, "doc", "html"] -- ------------------------------------------------------------ -- * temporary file names -- ------------------------------------------------------------ -- use a temporary filename that doesn't already exist. -- NB. *not* secure (we don't atomically lock the tmp file we get) withTempFile :: FilePath -> String -> (FilePath -> IO a) -> IO a withTempFile tmp_dir extn action = do x <- getProcessID findTempName x where findTempName x = do let filename = ("tmp" ++ show x) `joinFileExt` extn path = tmp_dir `joinFileName` filename b <- doesFileExist path if b then findTempName (x+1) else action path `finally` try (removeFile path) #if mingw32_HOST_OS || mingw32_TARGET_OS foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows #elif __GLASGOW_HASKELL__ || __HUGS__ getProcessID :: IO Int getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral #else -- error ToDo: getProcessID foreign import ccall unsafe "getpid" getProcessID :: IO Int #endif -- ------------------------------------------------------------ -- * Finding the description file -- ------------------------------------------------------------ oldDescFile :: String oldDescFile = "Setup.description" cabalExt :: String cabalExt = "cabal" buildInfoExt :: String buildInfoExt = "buildinfo" matchesDescFile :: FilePath -> Bool matchesDescFile p = (snd $ splitFileExt p) == cabalExt || p == oldDescFile noDesc :: IO a noDesc = die $ "No description file found, please create a cabal-formatted description file with the name <pkgname>." ++ cabalExt multiDesc :: [String] -> IO a multiDesc l = die $ "Multiple description files found. Please use only one of : " ++ show (filter (/= oldDescFile) l) -- |A list of possibly correct description files. Should be pre-filtered. descriptionCheck :: [FilePath] -> IO FilePath descriptionCheck [] = noDesc descriptionCheck [x] | x == oldDescFile = do warn $ "The filename \"Setup.description\" is deprecated, please move to <pkgname>." ++ cabalExt return x | matchesDescFile x = return x | otherwise = noDesc descriptionCheck [x,y] | x == oldDescFile = do warn $ "The filename \"Setup.description\" is deprecated. Please move out of the way. Using \"" ++ y ++ "\"" return y | y == oldDescFile = do warn $ "The filename \"Setup.description\" is deprecated. Please move out of the way. Using \"" ++ x ++ "\"" return x | otherwise = multiDesc [x,y] descriptionCheck l = multiDesc l -- |Package description file (/pkgname/@.cabal@) defaultPackageDesc :: IO FilePath defaultPackageDesc = getCurrentDirectory >>= findPackageDesc -- |Find a package description file in the given directory. Looks for -- @.cabal@ files. findPackageDesc :: FilePath -- ^Where to look -> IO FilePath -- <pkgname>.cabal findPackageDesc p = do ls <- getDirectoryContents p let descs = filter matchesDescFile ls descriptionCheck descs -- |Optional auxiliary package information file (/pkgname/@.buildinfo@) defaultHookedPackageDesc :: IO (Maybe FilePath) defaultHookedPackageDesc = getCurrentDirectory >>= findHookedPackageDesc -- |Find auxiliary package information in the given directory. -- Looks for @.buildinfo@ files. findHookedPackageDesc :: FilePath -- ^Directory to search -> IO (Maybe FilePath) -- ^/dir/@\/@/pkgname/@.buildinfo@, if present findHookedPackageDesc dir = do ns <- getDirectoryContents dir case [dir `joinFileName` n | n <- ns, snd (splitFileExt n) == buildInfoExt] of [] -> return Nothing [f] -> return (Just f) _ -> die ("Multiple files with extension " ++ buildInfoExt) -- ------------------------------------------------------------ -- * Testing -- ------------------------------------------------------------ #ifdef DEBUG hunitTests :: [Test] hunitTests = let suffixes = ["hs", "lhs"] in [TestCase $ #if mingw32_HOST_OS || mingw32_TARGET_OS do mp1 <- moduleToFilePath [""] "Distribution.Simple.Build" suffixes --exists mp2 <- moduleToFilePath [""] "Foo.Bar" suffixes -- doesn't exist assertEqual "existing not found failed" ["Distribution\\Simple\\Build.hs"] mp1 assertEqual "not existing not nothing failed" [] mp2, "moduleToPossiblePaths 1" ~: "failed" ~: ["Foo\\Bar\\Bang.hs","Foo\\Bar\\Bang.lhs"] ~=? (moduleToPossiblePaths "" "Foo.Bar.Bang" suffixes), "moduleToPossiblePaths2 " ~: "failed" ~: (moduleToPossiblePaths "" "Foo" suffixes) ~=? ["Foo.hs", "Foo.lhs"], TestCase (do files <- filesWithExtensions "." "cabal" assertEqual "filesWithExtensions" "Cabal.cabal" (head files)) #else do mp1 <- moduleToFilePath [""] "Distribution.Simple.Build" suffixes --exists mp2 <- moduleToFilePath [""] "Foo.Bar" suffixes -- doesn't exist assertEqual "existing not found failed" ["Distribution/Simple/Build.hs"] mp1 assertEqual "not existing not nothing failed" [] mp2, "moduleToPossiblePaths 1" ~: "failed" ~: ["Foo/Bar/Bang.hs","Foo/Bar/Bang.lhs"] ~=? (moduleToPossiblePaths "" "Foo.Bar.Bang" suffixes), "moduleToPossiblePaths2 " ~: "failed" ~: (moduleToPossiblePaths "" "Foo" suffixes) ~=? ["Foo.hs", "Foo.lhs"], TestCase (do files <- filesWithExtensions "." "cabal" assertEqual "filesWithExtensions" "Cabal.cabal" (head files)) #endif ] -- |Might want to make this more generic some day, with regexps -- or something. filesWithExtensions :: FilePath -- ^Directory to look in -> String -- ^The extension -> IO [FilePath] {- ^The file names (not full path) of all the files with this extension in this directory. -} filesWithExtensions dir extension = do allFiles <- getDirectoryContents dir return $ filter hasExt allFiles where hasExt f = snd (splitFileExt f) == extension #endif
alekar/hugs
packages/Cabal/Distribution/Simple/Utils.hs
bsd-3-clause
19,695
51
26
4,880
3,754
1,968
1,786
282
5
-------------------------------------------------------------------------------- -- | -- Module : Network.OpenID.Normalization -- Copyright : (c) Trevor Elliott, 2008 -- License : BSD3 -- -- Maintainer : Trevor Elliott <[email protected]> -- Stability : -- Portability : -- module Network.OpenID.Normalization where -- Friends import Network.OpenID.Types -- Libraries import Control.Applicative import Control.Monad import Data.List import Network.URI hiding (scheme,path) -- | Normalize an identifier, discarding XRIs. normalizeIdentifier :: Identifier -> Maybe Identifier normalizeIdentifier = normalizeIdentifier' (const Nothing) -- | Normalize the user supplied identifier, using a supplied function to -- normalize an XRI. normalizeIdentifier' :: (String -> Maybe String) -> Identifier -> Maybe Identifier normalizeIdentifier' xri (Identifier str) | null str = Nothing | "xri://" `isPrefixOf` str = Identifier `fmap` xri str | head str `elem` "=@+$!" = Identifier `fmap` xri str | otherwise = fmt `fmap` (url >>= norm) where url = parseURI str <|> parseURI ("http://" ++ str) norm uri = validScheme >> return u where scheme = uriScheme uri validScheme = guard (scheme == "http:" || scheme == "https:") u = uri { uriFragment = "", uriPath = path } path | null (uriPath uri) = "/" | otherwise = uriPath uri fmt u = Identifier $ normalizePathSegments $ normalizeEscape $ normalizeCase $ uriToString (const "") u []
substack/hsopenid
src/Network/OpenID/Normalization.hs
bsd-3-clause
1,616
0
14
396
369
199
170
27
1
{-# LANGUAGE TypeSynonymInstances #-} {- | Module : $Header$ Description : A Haskell MathLink interface Copyright : (c) Ewaryst Schulz, DFKI Bremen 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : non-portable (see language extensions) A Haskell MathLink interface based on the Foreign.MathLink.Bindings module -} module Common.MathLink where import Foreign.C -- get the C types import Foreign.Marshal -- get the array marshalling utils import Foreign.Storable import Foreign.Ptr (Ptr, nullPtr) import Foreign.MathLink.Bindings import Control.Monad.Reader import System.Timeout import System.IO import Data.Maybe import Common.Utils (verbMsg, verbMsgLn, verbMsgIOLn) -- * Constants for the MathLink interface dfMLTKAEND, dfMLTKALL_DECODERS, dfMLTKAPCTEND, dfMLTKARRAY, dfMLTKARRAY_DECODER , dfMLTKCONT, dfMLTKDIM, dfMLTKELEN, dfMLTKEND, dfMLTKERR, dfMLTKERROR , dfMLTKFUNC, dfMLTKINT, dfMLTKMODERNCHARS_DECODER, dfMLTKNULL , dfMLTKNULLSEQUENCE_DECODER, dfMLTKOLDINT, dfMLTKOLDREAL, dfMLTKOLDSTR , dfMLTKOLDSYM, dfMLTKPACKED_DECODER, dfMLTKPACKED, dfMLTKPCTEND, dfMLTKREAL , dfMLTKSEND, dfMLTKSTR, dfMLTKSYM, dfILLEGALPKT, dfCALLPKT, dfEVALUATEPKT , dfRETURNPKT, dfINPUTNAMEPKT, dfENTERTEXTPKT, dfENTEREXPRPKT, dfOUTPUTNAMEPKT, dfRETURNTEXTPKT, dfRETURNEXPRPKT, dfDISPLAYPKT, dfDISPLAYENDPKT, dfMESSAGEPKT, dfTEXTPKT, dfINPUTPKT, dfINPUTSTRPKT, dfMENUPKT, dfSYNTAXPKT, dfSUSPENDPKT, dfRESUMEPKT, dfBEGINDLGPKT, dfENDDLGPKT, dfFIRSTUSERPKT, dfLASTUSERPKT :: CInt dfILLEGALPKT = 0 dfCALLPKT = 7 dfEVALUATEPKT = 13 dfRETURNPKT = 3 dfINPUTNAMEPKT = 8 dfENTERTEXTPKT = 14 dfENTEREXPRPKT = 15 dfOUTPUTNAMEPKT = 9 dfRETURNTEXTPKT = 4 dfRETURNEXPRPKT = 16 dfDISPLAYPKT = 11 dfDISPLAYENDPKT = 12 dfMESSAGEPKT = 5 dfTEXTPKT = 2 dfINPUTPKT = 1 dfINPUTSTRPKT = 21 dfMENUPKT = 6 dfSYNTAXPKT = 10 dfSUSPENDPKT = 17 dfRESUMEPKT = 18 dfBEGINDLGPKT = 19 dfENDDLGPKT = 20 dfFIRSTUSERPKT = 128 dfLASTUSERPKT = 255 dfMLTKAEND = 13 dfMLTKALL_DECODERS = 983040 dfMLTKAPCTEND = 10 dfMLTKARRAY = 65 dfMLTKARRAY_DECODER = 262144 dfMLTKCONT = 92 dfMLTKDIM = 68 dfMLTKELEN = 32 dfMLTKEND = 10 dfMLTKERR = 0 dfMLTKERROR = 0 dfMLTKFUNC = 70 dfMLTKINT = 43 dfMLTKMODERNCHARS_DECODER = 524288 dfMLTKNULL = 46 dfMLTKNULLSEQUENCE_DECODER = 0 dfMLTKOLDINT = 73 dfMLTKOLDREAL = 82 dfMLTKOLDSTR = 83 dfMLTKOLDSYM = 89 dfMLTKPACKED_DECODER = 131072 dfMLTKPACKED = 80 dfMLTKPCTEND = 93 dfMLTKREAL = 42 dfMLTKSEND = 44 dfMLTKSTR = 34 dfMLTKSYM = 35 showPKT :: CInt -> String showPKT i | i == dfILLEGALPKT = "ILLEGALPKT" | i == dfCALLPKT = "CALLPKT" | i == dfEVALUATEPKT = "EVALUATEPKT" | i == dfRETURNPKT = "RETURNPKT" | i == dfINPUTNAMEPKT = "INPUTNAMEPKT" | i == dfENTERTEXTPKT = "ENTERTEXTPKT" | i == dfENTEREXPRPKT = "ENTEREXPRPKT" | i == dfOUTPUTNAMEPKT = "OUTPUTNAMEPKT" | i == dfRETURNTEXTPKT = "RETURNTEXTPKT" | i == dfRETURNEXPRPKT = "RETURNEXPRPKT" | i == dfDISPLAYPKT = "DISPLAYPKT" | i == dfDISPLAYENDPKT = "DISPLAYENDPKT" | i == dfMESSAGEPKT = "MESSAGEPKT" | i == dfTEXTPKT = "TEXTPKT" | i == dfINPUTPKT = "INPUTPKT" | i == dfINPUTSTRPKT = "INPUTSTRPKT" | i == dfMENUPKT = "MENUPKT" | i == dfSYNTAXPKT = "SYNTAXPKT" | i == dfSUSPENDPKT = "SUSPENDPKT" | i == dfRESUMEPKT = "RESUMEPKT" | i == dfBEGINDLGPKT = "BEGINDLGPKT" | i == dfENDDLGPKT = "ENDDLGPKT" | i == dfFIRSTUSERPKT = "FIRSTUSERPKT" | i == dfLASTUSERPKT = "LASTUSERPKT" | otherwise = "UNRECOGNIZED PACKET" showTK :: CInt -> String showTK i | i == dfMLTKAEND = "MLTKAEND" | i == dfMLTKALL_DECODERS = "MLTKALL_DECODERS" | i == dfMLTKAPCTEND = "MLTKAPCTEND" | i == dfMLTKARRAY = "MLTKARRAY" | i == dfMLTKARRAY_DECODER = "MLTKARRAY_DECODER" | i == dfMLTKCONT = "MLTKCONT" | i == dfMLTKDIM = "MLTKDIM" | i == dfMLTKELEN = "MLTKELEN" | i == dfMLTKEND = "MLTKEND" | i == dfMLTKERR = "MLTKERR" | i == dfMLTKERROR = "MLTKERROR" | i == dfMLTKFUNC = "MLTKFUNC" | i == dfMLTKINT = "MLTKINT" | i == dfMLTKMODERNCHARS_DECODER = "MLTKMODERNCHARS_DECODER" | i == dfMLTKNULL = "MLTKNULL" | i == dfMLTKNULLSEQUENCE_DECODER = "MLTKNULLSEQUENCE_DECODER" | i == dfMLTKOLDINT = "MLTKOLDINT" | i == dfMLTKOLDREAL = "MLTKOLDREAL" | i == dfMLTKOLDSTR = "MLTKOLDSTR" | i == dfMLTKOLDSYM = "MLTKOLDSYM" | i == dfMLTKPACKED_DECODER = "MLTKPACKED_DECODER" | i == dfMLTKPACKED = "MLTKPACKED" | i == dfMLTKPCTEND = "MLTKPCTEND" | i == dfMLTKREAL = "MLTKREAL" | i == dfMLTKSEND = "MLTKSEND" | i == dfMLTKSTR = "MLTKSTR" | i == dfMLTKSYM = "MLTKSYM" | otherwise = "UNRECOGNIZED TK" -- * MathLink monad as Reader IO monad data MLState = MLState { mlink :: MLINK , menv :: MLEnvironment , mverbosity :: Int , logHdl :: Maybe Handle } type ML = ReaderT MLState IO -- | Prints a message dependent on the verbosity level verbMsgML :: Int -> String -> ML () verbMsgML lvl msg = do hdl <- getHandle v <- asks mverbosity liftIO $ verbMsg hdl v lvl msg -- | Prints a message dependent on the verbosity level verbMsgMLLn :: Int -> String -> ML () verbMsgMLLn lvl msg = do hdl <- getHandle v <- asks mverbosity liftIO $ verbMsgLn hdl v lvl msg getHandle :: ML Handle getHandle = liftM (fromMaybe stdout) $ asks logHdl mkState :: MLINK -> MLEnvironment -> Int -> MLState mkState mlp env v = MLState { mlink = mlp, menv = env, mverbosity = v , logHdl = Nothing } addLogging :: MLState -> Handle -> MLState addLogging st hdl = st { logHdl = Just hdl } askMLink :: ML MLINK askMLink = asks mlink liftMLIO :: (MLINK -> IO b) -> ML b liftMLIO f = askMLink >>= liftIO . f -- * MathLink connection handling -- | Open connection to MathLink or return error code on failure openLink :: Int -- ^ Verbosity -> Maybe String {- ^ Connection name (launches a new kernel if not specified) -} -> IO (Either Int MLState) openLink v mName = do env <- cMlInitialize nullPtr if env == nullPtr then return $ Left 1 else do verbMsgIOLn v 2 "Initialized" let (name, mode) = case mName of Just n -> (n, "connect") _ -> ("math -mathlink", "launch") let openargs = ["-linkname", name, "-linkmode", mode] lp <- mlOpen 4 openargs mB <- if lp == nullPtr then return Nothing -- else liftM Just $ connectLink lp else timeout 3000000 $ connectLink lp v case mB of Nothing -> return $ Left 2 Just False -> return $ Left 3 _ -> return $ Right $ mkState lp env v -- | Close connection to MathLink closeLink :: MLState -> IO () closeLink st = do mlClose $ mlink st cMlDeinitialize $ menv st -- | Run ML-program on an opened connection to MathLink withLink :: MLState -- ^ MathLink connection -> Maybe FilePath -- ^ Log low level messages into this file (or STDOUT) -> ML a -- ^ The program to run -> IO a withLink st mFp mlprog = case mFp of Just fp -> withFile fp WriteMode $ runReaderT mlprog . addLogging st Nothing -> runReaderT mlprog st {- | Run ML-program on a new connection to MathLink which is closed right after the execution and return the prgram result or error code on failure -} runLink :: Maybe FilePath -- ^ Log low level messages into this file (or STDOUT) -> Int -- ^ Verbosity -> Maybe String {- ^ Connection name (launches a new kernel if not specified) -} -> ML a -- ^ The program to run -> IO (Either Int a) runLink mFp v mName mlprog = do eSt <- openLink v mName case eSt of Left i -> return $ Left i Right st -> do verbMsgIOLn v 2 "Opened" x <- withLink st mFp mlprog closeLink st return $ Right x -- | Low level: open connection mlOpen :: CInt -> [String] -> IO MLINK mlOpen i l = withStringArray l $ cMlOpen i -- | Low level: check connection connectLink :: MLINK -> Int -- ^ Verbosity -> IO Bool connectLink lp v = do let p i j = do i' <- cMlReady lp if toBool i' || j > 3000 then return j else cMlFlush lp >> if i > 1000 then p 0 (j + 1) else p (i + 1) j p (0 :: Int) (0 :: Int) >>= verbMsgIOLn v 2 . ("ready after " ++) . show res <- cMlConnect lp return $ toBool res -- | Low level: close connection mlClose :: MLINK -> IO CInt mlClose = cMlClose -- * C to Haskell utilities withStringArray :: MonadIO m => [String] -> (Ptr CString -> IO b) -> m b withStringArray l f = liftIO $ mapM newCString l >>= flip withArray f mlGetA :: (Storable a, Show a, Show b) => (Ptr a -> IO b) -> IO a mlGetA f = let g ptr = f ptr >> peek ptr in alloca g -- TODO: maybe better via foreign pointer, check later mlGetCString :: Show b => (Ptr CString -> IO b) -> (CString -> IO ()) -> IO String mlGetCString f disownF = let g ptr = do cs <- f ptr >> peek ptr s <- peekCString cs disownF cs return s in alloca g -- * C Type conversions cintToInteger :: CInt -> Integer cintToInteger = fromIntegral intToCInt :: Int -> CInt intToCInt = fromIntegral -- | This function is unsafe, it may overflow... cintToInt :: CInt -> Int cintToInt = fromIntegral cdblToDbl :: CDouble -> Double cdblToDbl = realToFrac dblToCDbl :: Double -> CDouble dblToCDbl = realToFrac -- * MathLink interface using the ML monad, built on top of the raw bindings mlFlush :: ML CInt mlFlush = liftMLIO cMlFlush mlReady :: ML CInt mlReady = liftMLIO cMlReady mlConnect :: ML CInt mlConnect = liftMLIO cMlConnect mlEndPacket :: ML CInt mlEndPacket = liftMLIO cMlEndPacket mlNextPacket :: ML CInt mlNextPacket = liftMLIO cMlNextPacket mlNewPacket :: ML CInt mlNewPacket = liftMLIO cMlNewPacket mlGetNext :: ML CInt mlGetNext = liftMLIO cMlGetNext mlGetArgCount :: ML CInt mlGetArgCount = askMLink >>= liftIO . mlGetA . cMlGetArgCount mlGetArgCount' :: ML Int mlGetArgCount' = liftM cintToInt mlGetArgCount -- cMlGetSymbol :: MLINK -> Ptr CString -> IO CInt mlGetSymbol :: ML String mlGetSymbol = do ml <- askMLink liftIO $ mlGetCString (cMlGetSymbol ml) $ cMlDisownSymbol ml -- cMlGetString :: MLINK -> Ptr CString -> IO CInt mlGetString :: ML String -- mlGetString = askMLink >>= liftIO . mlGetCString . cMlGetString mlGetString = do ml <- askMLink liftIO $ mlGetCString (cMlGetString ml) $ cMlDisownString ml -- cMlGetReal :: MLINK -> Ptr CDouble -> IO CInt mlGetReal :: ML CDouble mlGetReal = askMLink >>= liftIO . mlGetA . cMlGetReal mlGetReal' :: ML Double mlGetReal' = liftM cdblToDbl mlGetReal -- cMlGetInteger :: MLINK -> Ptr CInt -> IO CInt mlGetInteger :: ML CInt mlGetInteger = askMLink >>= liftIO . mlGetA . cMlGetInteger mlGetInteger' :: ML Int mlGetInteger' = liftM cintToInt mlGetInteger {- | Integers are received as strings, because the interface supports only machine integers with fixed length not arbitrary sized integers. -} mlGetInteger'' :: ML Integer mlGetInteger'' = liftM read mlGetString mlPutString :: String -> ML CInt mlPutString s = liftMLIO f where f ml = withCString s $ cMlPutString ml mlPutSymbol :: String -> ML CInt mlPutSymbol s = liftMLIO f where f ml = withCString s $ cMlPutSymbol ml mlPutFunction :: String -> CInt -> ML CInt mlPutFunction s i = liftMLIO f where f ml = withCString s $ flip (cMlPutFunction ml) i mlPutFunction' :: String -> Int -> ML CInt mlPutFunction' s = mlPutFunction s . intToCInt mlPutInteger :: CInt -> ML CInt mlPutInteger = liftMLIO . flip cMlPutInteger mlPutInteger' :: Int -> ML CInt mlPutInteger' = mlPutInteger . intToCInt {- | Integers are sent as strings, because the interface supports only machine integers with fixed length not arbitrary sized integers. -} mlPutInteger'' :: Integer -> ML CInt mlPutInteger'' i = mlPutFunction' "ToExpression" 1 >> mlPutString (show i) mlPutReal :: CDouble -> ML CInt mlPutReal = liftMLIO . flip cMlPutReal mlPutReal' :: Double -> ML CInt mlPutReal' = mlPutReal . dblToCDbl mlError :: ML CInt mlError = liftMLIO cMlError mlErrorMessage :: ML String mlErrorMessage = liftMLIO (cMlErrorMessage >=> peekCString) -- * MathLink interface utils mlProcError :: ML a mlProcError = do eid <- mlError s <- if toBool eid then liftM ("Error detected by MathLink: " ++) mlErrorMessage else return "Error detected by Interface" verbMsgMLLn 1 s error $ "mlProcError: " ++ s sendEvalPacket :: ML a -> ML a sendEvalPacket ml = do mlPutFunction "EvaluatePacket" 1 res <- ml mlEndPacket return res sendTextPacket :: String -> ML () sendTextPacket s = do mlPutFunction "EvaluatePacket" 1 mlPutFunction "ToExpression" 1 mlPutString s mlEndPacket return () sendTextResultPacket :: String -> ML () sendTextResultPacket s = do mlPutFunction "EvaluatePacket" 1 mlPutFunction "ToString" 1 mlPutFunction "ToExpression" 1 mlPutString s mlEndPacket return () {- -- these variants does not work as expected sendTextPacket' :: String -> ML () sendTextPacket' s = do mlPutFunction "EnterTextPacket" 1 mlPutString s mlEndPacket return () sendTextPacket'' :: String -> ML () sendTextPacket'' s = do mlPutFunction "EnterExpressionPacket" 1 mlPutFunction "ToExpression" 1 mlPutString s mlEndPacket return () sendTextPacket3 :: String -> ML () sendTextPacket3 s = do mlPutFunction "EvaluatePacket" 1 mlPutFunction "ToString" 1 mlPutFunction "ToExpression" 1 mlPutString s mlEndPacket return () sendTextPacket4 :: String -> ML () sendTextPacket4 s = do mlPutFunction "EnterExpressionPacket" 1 mlPutFunction "ToString" 1 mlPutFunction "ToExpression" 1 mlPutString s mlEndPacket return () -} waitForAnswer :: ML CInt waitForAnswer = do -- skip any packets before the first ReturnPacket i <- waitUntilPacket (0 :: Int) [ dfRETURNPKT, dfRETURNEXPRPKT , dfRETURNTEXTPKT, dfILLEGALPKT] if elem i [dfILLEGALPKT, dfRETURNEXPRPKT, dfRETURNTEXTPKT] then error $ "waitForAnswer: encountered a " ++ showPKT i else return i -- wait for the answer and skip it skipAnswer :: ML CInt skipAnswer = waitForAnswer >> mlNewPacket waitUntilPacket :: Num a => a -> [CInt] -> ML CInt waitUntilPacket i l = do np <- mlNextPacket if elem np l then do verbMsgMLLn 2 $ "GotReturn after " ++ show i ++ " iterations" return np else verbMsgMLLn 2 ("wap: " ++ show np) >> mlNewPacket >> waitUntilPacket (i + 1) l
mariefarrell/Hets
Common/MathLink.hs
gpl-2.0
14,930
0
17
3,626
3,749
1,912
1,837
350
6
{-# language DeriveDataTypeable #-} module Graphics.Qt.Events ( QtEvent(..), Key(..), keyDescription, translateQtKey, modifyTextField, QKeyboardModifier(..), marshallKeyboardModifiers, ) where import Data.Map (Map, member, (!), fromList) import Data.Data import Data.Set (Set, fromList) import Data.Bits import Graphics.Qt.Types import System.Info import Utils data QtEvent = KeyPress Key String (Set QKeyboardModifier) | KeyRelease Key String (Set QKeyboardModifier) | FocusOut | CloseWindow deriving (Show) data Key -- characters = A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z -- international characters | AUmlaut | OUmlaut | UUmlaut | SZLigatur -- signs | Space | Comma | Dot | SemiColon | Slash | Plus | Minus | Equals | Tick | BackSlash | SquareBracketOpen | SquareBracketClose -- special keys | Return | Enter -- num pad | Escape | Tab | Delete | BackSpace -- arrow keys | UpArrow | DownArrow | LeftArrow | RightArrow -- modifiers | Meta | Shift | Ctrl | Alt | AltGr -- numbers | K1 | K2 | K3 | K4 | K5 | K6 | K7 | K8 | K9 | K0 -- function keys | F1 | F2 | F3 | F4 | F5 | F6 | F7 | F8 | F9 | F10 | F11 | F12 | CloseWindowKey | UnknownKey deriving (Eq, Ord, Enum, Bounded, Show, Read, Typeable, Data) -- | Converts a key and a given key text to a human readable description of the key. keyDescription :: Key -> String -> String keyDescription k text = case k of -- characters see below Space -> "Space" Return -> "⏎" Enter -> "⏎" -- num pad Escape -> "Esc" Tab -> "Tab" Delete -> "Delete" BackSpace -> "Backspace" UpArrow -> "↑" DownArrow -> "↓" LeftArrow -> "←" RightArrow -> "→" Meta -> "Meta" Shift -> "Shift" Ctrl -> "Ctrl" Alt -> "Alt" AltGr -> "Alt Gr" K1 -> "1" K2 -> "2" K3 -> "3" K4 -> "4" K5 -> "5" K6 -> "6" K7 -> "7" K8 -> "8" K9 -> "9" K0 -> "0" CloseWindowKey -> error "keyDescription: CloseWindowKey? Really?" UnknownKey -> "unknown key" k -> text -- | modifies the contents of a text field modifyTextField :: Key -> String -> String -> String modifyTextField BackSpace _ [] = [] modifyTextField BackSpace _ l = init l modifyTextField _ t l = l ++ t translateQtKey :: QtInt -> Key translateQtKey keyInt | keyInt `member` keyMap = keyMap ! keyInt translateQtKey x = trace ("warning: unknown key: " ++ show x) UnknownKey -- error ("translateQtKey: " ++ show x) keyMap :: Map QtInt Key keyMap = Data.Map.fromList keyMapping keyMapping :: [(QtInt, Key)] keyMapping = [ -- characters (65, A), (66, B), (67, C), (68, D), (69, E), (70, F), (71, G), (72, H), (73, I), (74, J), (75, K), (76, L), (77, M), (78, N), (79, O), (80, P), (81, Q), (82, R), (83, S), (84, T), (85, U), (86, V), (87, W), (88, X), (89, Y), (90, Z), -- international characters (196, AUmlaut), (214, OUmlaut), (220, UUmlaut), (223, SZLigatur), -- signs (32, Space), (44, Comma), (46, Dot), (59, SemiColon), (47, Slash), (45, Minus), (61, Equals), (91, SquareBracketOpen), (93, SquareBracketClose), (92, BackSlash), (180, Tick), (43, Plus), -- special keys (0x01000004, Return), (0x01000005, Enter), (0x01000000, Escape), (0x01000001, Tab), (0x01000007, Delete), (0x01000003, BackSpace), -- arrow keys (0x1000013, UpArrow), (0x1000015, DownArrow), (0x1000012, LeftArrow), (0x1000014, RightArrow), -- modifiers (0x1000022, realMeta), (0x1000020, Shift), (0x1000021, realCtrl), (0x1000023, Alt), (0x1001103, AltGr), -- numbers (49, K1), (50, K2), (51, K3), (52, K4), (53, K5), (54, K6), (55, K7), (56, K8), (57, K9), (48, K0), -- function keys (16777264, F1), (16777265, F2), (16777266, F3), (16777267, F4), (16777268, F5), (16777269, F6), (16777270, F7), (16777271, F8), (16777272, F9), (16777273, F10), (16777274, F11), (16777275, F12) ] -- stick with Ctrl on osx -- (Qt::AA_MacDontSwapCtrlAndMeta doesn't seem to work) -- | translates to Ctrl on osx, to Meta on all other platforms realMeta :: Key realMeta = case System.Info.os of "darwin" -> Ctrl _ -> Meta -- | translates to Meta on osx, to Ctrl on all other platforms realCtrl :: Key realCtrl = case System.Info.os of "darwin" -> Meta _ -> Ctrl -- * keyboard modifiers data QKeyboardModifier = ShiftModifier | ControlModifier | AltModifier | MetaModifier | KeypadModifier | GroupSwitchModifier deriving (Show, Eq, Ord, Enum, Bounded) marshallKeyboardModifiers :: QtInt -> Set QKeyboardModifier marshallKeyboardModifiers flags = Data.Set.fromList $ filter isInFlags allValues where isInFlags :: QKeyboardModifier -> Bool isInFlags mod = (toFlag mod .&. flags) > 0 toFlag m = case m of ShiftModifier -> 0x02000000 ControlModifier -> 0x04000000 AltModifier -> 0x08000000 MetaModifier -> 0x10000000 KeypadModifier -> 0x20000000 GroupSwitchModifier -> 0x40000000
geocurnoff/nikki
src/Graphics/Qt/Events.hs
lgpl-3.0
5,909
0
10
2,038
1,749
1,077
672
257
29
module Reddit.Types.SearchOptions ( Order(..) ) where import Network.API.Builder.Query data Order = Relevance | New | Hot | Top | MostComments deriving (Show, Read, Eq) instance ToQuery Order where toQuery k t = return $ (,) k $ case t of Relevance -> "relevance" New -> "new" Hot -> "hot" Top -> "top" MostComments -> "comments"
FranklinChen/reddit
src/Reddit/Types/SearchOptions.hs
bsd-2-clause
403
0
9
128
123
69
54
16
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module Complex ( Type(..) , OpenComplex(..) , CloseComplex(..) , Complex(..) , closeComplex ) where import Data.ByteString as B import Data.ByteString.Short as BS import Data.Typeable data Type = OpenType | CloseType data OpenComplex = OpenComplex { openComplexSource :: ByteString } data CloseComplex = CloseComplex { closeComplexHash :: ByteString , closeComplexSource :: !ByteString } data Complex (t :: Type) = Complex { complexInner :: !(ComplexFamily t) } type family ComplexFamily (t :: Type) where ComplexFamily 'OpenType = OpenComplex ComplexFamily 'CloseType = CloseComplex handleComplex :: forall t a. Typeable t => Complex t -> (Complex 'CloseType -> a) -> a handleComplex complex onClose = case toCloseComplex complex of Just receiveComplex -> onClose receiveComplex Nothing -> undefined toCloseComplex :: forall t. Typeable t => Complex t -> Maybe (Complex 'CloseType) toCloseComplex x = fmap (\Refl -> x) (eqT :: Maybe (t :~: 'CloseType)) closeComplex :: Typeable t => Complex t -> Close closeComplex complex = handleComplex complex receiveComplexToProtocolCloseComplex receiveComplexToProtocolCloseComplex :: Complex 'CloseType -> Close receiveComplexToProtocolCloseComplex Complex {complexInner = inner} = Close (hashToLink (closeComplexSource inner)) data Close = Close !ShortByteString hashToLink :: ByteString -> ShortByteString hashToLink bh = BS.toShort bh
sdiehl/ghc
testsuite/tests/simplCore/should_run/T16893/Complex.hs
bsd-3-clause
1,612
0
12
309
430
237
193
57
2
{-# LANGUAGE RankNTypes,ScopedTypeVariables #-} module HLearn.Evaluation.CrossValidation where -- import Control.Monad import Control.Monad.Random hiding (fromList) -- import Control.Monad.ST import Control.Monad.Trans (lift) import Data.Array.ST import qualified GHC.Arr as Arr import qualified Data.Foldable as F import qualified Data.Map as Map import qualified Data.Set as S import qualified Data.Vector as V -- import qualified Data.Vector as V import Debug.Trace import qualified Data.DList as D import Prelude (take,drop,map,filter,zip) import SubHask import SubHask.Monad import HLearn.History import HLearn.Models.Distributions.Common import HLearn.Models.Distributions.Univariate.Normal import HLearn.Models.Classifiers.Common -- import qualified Control.ConstraintKinds as CK ------------------------------------------------------------------------------- -- standard k-fold cross validation type MonadRandom_ m = (Monad Hask m, MonadRandom m) type SamplingMethod = forall dp r. (Eq dp, MonadRandom_ r) => [dp] -> r [([dp],[dp])] repeatExperiment :: Int -> SamplingMethod -> SamplingMethod repeatExperiment n f xs = liftM concat $ forM [1..n] $ \_ -> do xs' <- shuffle xs f xs' trainingPercent :: Double -> SamplingMethod trainingPercent percent xs = do xs' <- shuffle xs let n = round $ percent * fromIntegral (length xs') return [ (take n xs', drop n xs') ] setMaxDatapoints :: Int -> SamplingMethod -> SamplingMethod setMaxDatapoints n f xs = do xs' <- shuffle xs f $ take n xs' kfold :: Int -> SamplingMethod kfold k xs = do xs' <- shuffle xs let step = floor $ (fromIntegral $ length xs :: Double) / fromIntegral k trace ("step="++show step) $ return [ ( take ((i)*step) xs' ++ drop ((i+1)*step) xs' , take step $ drop (i*step) xs' ) | i <- [0..k-1] ] -- leaveOneOut :: SamplingMethod -- leaveOneOut xs = return $ map (\x -> [x]) xs -- -- withPercent :: Double -> SamplingMethod -> SamplingMethod -- withPercent p f xs = do -- xs' <- shuffle xs -- f $ take (floor $ (fromIntegral $ length xs') * p) xs' -- -- repeatExperiment :: Int -> SamplingMethod -> SamplingMethod -- repeatExperiment i f xs = do -- liftM concat $ forM [1..i] $ \i -> do -- f xs -- -- kfold :: Int -> SamplingMethod -- kfold k xs = do -- xs' <- shuffle xs -- return [takeEvery k $ drop j xs' | j<-[0..k-1]] -- where -- takeEvery n [] = [] -- takeEvery n xs = head xs : (takeEvery n $ drop n xs) -- -- numSamples :: Int -> SamplingMethod -> SamplingMethod -- numSamples n f dps = f $ take n dps -- | randomly shuffles a list in time O(n log n); see http://www.haskell.org/haskellwiki/Random_shuffle shuffle :: (Eq a, MonadRandom_ m) => [a] -> m [a] shuffle xs = do let l = length xs rands <- take l `liftM` getRandomRs (0, l-1) let ar = runSTArray ( do ar <- Arr.thawSTArray (Arr.listArray (0, l-1) xs) forM_ (zip [0..(l-1)] rands) $ \(i, j) -> do vi <- Arr.readSTArray ar i vj <- Arr.readSTArray ar j Arr.writeSTArray ar j vi Arr.writeSTArray ar i vj return ar ) return (Arr.elems ar) --------------------------------------- type LossFunction = forall model. ( Classifier model -- , HomTrainer model , Labeled (Datapoint model) , Eq (Label (Datapoint model)) , Eq (Datapoint model) ) => model -> [Datapoint model] -> Double accuracy :: LossFunction accuracy model dataL = (fromIntegral $ length $ filter (==False) resultsL) / (fromIntegral $ length dataL) where resultsL = map (\(l1,l2) -> l1/=l2) $ zip trueL classifyL trueL = map getLabel dataL classifyL = map (classify model . getAttributes) dataL errorRate :: LossFunction errorRate model dataL = 1 - accuracy model dataL --------------------------------------- validateM :: forall model g container m. -- ( HomTrainer model ( Classifier model , RandomGen g , Eq (Datapoint model) , Eq (Label (Datapoint model)) , Foldable (container (Datapoint model)) , Constructible (container (Datapoint model)) , Elem (container (Datapoint model)) ~ Datapoint model , HistoryMonad m ) => SamplingMethod -> LossFunction -> container (Datapoint model) -> (container (Datapoint model) -> m model) -> RandT g m (Normal Double) validateM samplingMethod loss xs trainM = do xs' <- samplingMethod $ toList xs lift $ collectReports $ fmap trainNormal $ forM xs' $ \(trainingset, testset) -> do model <- trainM (fromList trainingset) return $ loss model testset
mikeizbicki/HLearn
src/HLearn/Evaluation/CrossValidation.hs
bsd-3-clause
4,722
0
20
1,118
1,345
718
627
-1
-1
{-# LANGUAGE #
wxwxwwxxx/ghc
testsuite/tests/parser/should_fail/T3153.hs
bsd-3-clause
15
3
5
3
11
5
6
-1
-1
{-# htermination sequence :: [Maybe a] -> Maybe [a] #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_sequence_3.hs
mit
56
0
2
10
3
2
1
1
0
{-# htermination (toEnumRatio :: MyInt -> Ratio MyInt) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; data Ratio a = CnPc a a; fromIntMyInt :: MyInt -> MyInt fromIntMyInt x = x; intToRatio x = CnPc (fromIntMyInt x) (fromIntMyInt (Pos (Succ Zero))); fromIntRatio :: MyInt -> Ratio MyInt fromIntRatio = intToRatio; toEnumRatio :: MyInt -> Ratio MyInt toEnumRatio = fromIntRatio;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/toEnum_2.hs
mit
509
0
11
110
170
96
74
13
1
import System.Exit (exitFailure, exitSuccess) import Lib main :: IO () main = do let result = kleinberg [10,20,30,40,100,101,102,103,104,105,200] $ defOpts if result == [0,0,0,0,0,0,3,3,3,3,3,0] then exitSuccess else exitFailure
yasukun/bursts
test/Spec.hs
mit
236
0
12
35
132
79
53
7
2
{-# LANGUAGE CPP #-} {-# LANGUAGE MonadComprehensions #-} module Cabal where import Config (cProjectVersion) import Control.Applicative import Control.Lens import Control.Monad (guard) import Data.Char import Data.List import Data.Maybe (listToMaybe) import Data.Monoid import Data.Ord import Data.Version import Distribution.Compiler import qualified Distribution.ModuleName as MN import Distribution.Package (Dependency (..)) import Distribution.PackageDescription import Distribution.PackageDescription.Configuration (finalizePackageDescription) import Distribution.PackageDescription.Parse (ParseResult, parsePackageDescription) import Distribution.System (buildPlatform) import qualified Distribution.Text as CT import System.Directory import System.FilePath import Text.ParserCombinators.ReadP (readP_to_S) ghcVersion :: Version ghcVersion = fst $ head $ filter (null . snd) $ readP_to_S parseVersion cProjectVersion parseCabalConfig :: String -> ParseResult PackageDescription parseCabalConfig contents = v >>= \v' -> case v' of (Left _) -> error "This is a bug in parseCabalConfig" -- We said all packages are available (const True), so this should definitely not happen (Right r) -> return $ fst r where v = return . finalizePackageDescription [] (const True) buildPlatform (CompilerId GHC ghcVersion) [] =<< parsePackageDescription contents -- | This function tests whether a given path is a prefix of another path. It returns 'Nothing' if the path isn't a prefix, otherwise -- it returns 'Just' the number of directory components of the prefix. Note that while this function doesn't canonicalize paths, it recognizes -- @"."@ and ignores it, but doesn't handle @".."@. It's meant to be used in infix form, like the 'isPrefixOf' function from 'Data.List'. -- Examples: -- -- >>> "." `prefixPathOf` "abc/ad/def.txt" -- Just 0 -- -- >>> "../x" `prefixPathOf` "abc/ad/def" -- Nothing -- Always Nothing, even if the current directory is @x@. This function doesn't canonicalize paths! -- -- >>> "tests" `prefixPathOf` "tests/1213.hs" -- Just 1 -- @tests@ has one directory component -- -- prefixPathOf :: FilePath -> FilePath -> Maybe Int "." `prefixPathOf` _ = Just 0 dir `prefixPathOf` subdir = go dirParts subdirParts where dirParts = filter (/= ".") $ map (under reversed $ strip '\\' . strip '/') $ splitPath dir subdirParts = filter (/= ".") $ map (under reversed $ strip '\\' . strip '/') $ splitPath subdir strip c (a:x) = if c == a then x else a:x strip _ _ = [] go [] _ = Just 0 go _ [] = Nothing go (a:as) (b:bs) | a == b = succ <$> go as bs | otherwise = Nothing -- | Find all maxima in a given list. maximaBy :: (a -> a -> Ordering) -> [a] -> [a] maximaBy _ [] = [] maximaBy cmp (a:as) = go a as where go x (b:bs) = case bs' of (m:ms) -> case x `cmp` m of LT -> m:ms EQ -> x:m:ms GT -> [x] _ -> [x] where bs' = go b bs go x [] = [x] -- | Get ALL buildinfo, including disabled test-suites, benchmarks, etc ... -- We still exclude things that aren't buildable. reallyAllBuildInfo :: PackageDescription -> [BuildInfo] reallyAllBuildInfo pkg_descr = [ bi | Just lib <- [library pkg_descr] , let bi = libBuildInfo lib , buildable bi ] ++ [ bi | exe <- executables pkg_descr , let bi = buildInfo exe , buildable bi ] ++ [ bi | tst <- testSuites pkg_descr , let bi = testBuildInfo tst , buildable bi] ++ [ bi | tst <- benchmarks pkg_descr , let bi = benchmarkBuildInfo tst , buildable bi] findBuildInfoFile :: PackageDescription -> String -> Either String BuildInfo findBuildInfoFile d f = case buildInfos of (bi:_) -> if has (traverse . to (`prefixPathOf` f) . _Just) $ hsSourceDirs bi then Right bi else noMatching [] -> noMatching where buildInfos = maximaBy (comparing $ maximumOf $ to hsSourceDirs . traverse . to (`prefixPathOf` f) . traverse) $ reallyAllBuildInfo d sourceDirs = concatMap hsSourceDirs $ allBuildInfo d exitError msg = Left $ msg ++ " [Checked source directories: " ++ show sourceDirs ++ "]" noMatching = exitError "No matching build target (library, executable or benchmark) found" findBuildInfoModule :: PackageDescription -> String -> Maybe BuildInfo findBuildInfoModule d m = findLibrary <|> findExe <|> findTestSuite where findLibrary = library d >>= \x -> libBuildInfo x <$ guard (MN.fromString m `elem` libModules x) findExe = fmap buildInfo $ listToMaybe $ filter ((MN.fromString m `elem`) . exeModules) $ executables d findTestSuite = fmap testBuildInfo $ listToMaybe $ filter ((MN.fromString m `elem`) . testModules) $ testSuites d if' :: a -> a -> Bool -> a if' a _ False = a if' _ a True = a pureIfM :: (Functor m, Applicative f, Alternative f) => m Bool -> a -> m (f a) pureIfM w = ifM w . pure ifM :: (Functor m, Alternative f) => m Bool -> f a -> m (f a) ifM w v = if' empty v <$> w packageDBFlag :: String #if __GLASGLOW_HASKELL__ >= 706 packageDBFlag = "-package-db" #else packageDBFlag = "-package-conf" #endif cabalMiscOptions :: IO [String] cabalMiscOptions = fmap concat $ sequence [ pureIfM (doesFileExist localDB) $ packageDBFlag ++ " " ++ localDB , ifM (doesFileExist macros) ["-optP-include", "-optP" ++ macros] , doesFileExist sandboxConf >>= if' (return []) getSandboxDBs ] where localDB = "dist/package.conf.inplace" macros = "dist/build/autogen/cabal_macros.h" sandboxConf = "cabal.sandbox.config" getSandboxDBs = do s <- readFile "cabal.sandbox.config" return $ "-no-user-package-db" : [packageDBFlag ++ " " ++ db | l <- lines s, "package-db:" `isPrefixOf` l , let db = dropWhile isSpace $ drop (length "package-db:") l] getBuildInfoOptions :: BuildInfo -> [String] getBuildInfoOptions bi = concat [ concat ghcOpts , map (mappend "-i") $ hsSourceDirs bi , map (mappend "-X" . CT.display) $ defaultExtensions bi , map (mappend "-package" . CT.display . pkgName) $ targetBuildDepends bi , ["-hide-all-packages"] ] where pkgName (Dependency n _) = n ghcOpts = map snd $ filter ((== GHC) . fst) $ options bi
bennofs/hdevtools
src/Cabal.hs
mit
7,067
0
18
2,133
1,858
968
890
114
5
main = do line <- fmap reverse getLine putStrLn $ "You said " ++ line ++ " backwards" putStrLn $ "You said " ++ line ++ " backwards"
maxtangli/sonico
language/haskell/fmap.hs
mit
139
2
15
34
50
23
27
3
1
import Utils (isPerfectSquare) import Data.Ratio import Data.List import ContinuedFractions --import Primes --import qualified Data.List.Ordered as Ordered --factorsForX d y = primes `Ordered.minus` (Ordered.sort (factorsD ++ factorsY)) -- where factorsD = factorize d primes -- factorsY = factorize primes isSolution d (x,y) = (x^2 - d*y^2 == 1) pairs :: Integer -> [(Integer, Integer)] pairs d = [ (x,y) | n <- [1..], let app = nthApproximant n $ continuedFractionExpansionSqrt d, let x = numerator app, let y = denominator app ] ds = filter (not . isPerfectSquare) [1..1000] firstSolution :: Integer -> (Integer, Integer, Integer) firstSolution d = (x,y,d) where (x,y) = head $ filter (isSolution d) (pairs d) answer = sort $ map firstSolution ds main = print answer
arekfu/project_euler
p0066/p0066.hs
mit
829
0
11
179
272
149
123
15
1
{-# htermination (>>=) :: Monad m => m a -> (a -> m b) -> m b #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_GTGTEQ__1.hs
mit
67
0
2
19
3
2
1
1
0
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# LANGUAGE QuasiQuotes #-} module Grammar.Greek.Morph.Smyth.Conjunctions.Subordinating where import Grammar.Greek.Morph.QuasiQuoters -- Smyth 2770 causal = [accentedWords| ὅτι διότι διόπερ ἐπεί ἐπειδή ὅτε ὁπότε ὡς |] comparative = [accentedWords| ὡς ὥσπερ καθάπερ ὅπως ᾗ ὅπῃ ᾗπερ |] concessive = [accentedWords| κεἰ κἄν |] -- καὶ εἰ (κεἰ) -- καὶ ἐόν (κἄν) -- εἰ καί -- ἐὰν καί conditional = [accentedWords| εἰ ἐάν ἤν ἄν |] consecutive = [accentedWords| ὥστε ὡς |] declarative = [accentedWords| ὅτι διότι οὕνεκα ὁθούνεκα ὡς |] final = [accentedWords| ἵνα ὅπως ὡς μή |] local = [accentedWords| οὗ ὅπου οἷ ὅποι ἔνθα ὅθεν ὁπόθεν ᾗ ὅπῃ |] temporal = [accentedWords| ὅτε ὁπότε ἡνίκα ἐπεί ἐπειδή ὡς μέχρι ἔστε ἕως πρίν |]
ancientlanguage/haskell-analysis
greek-morph/src/Grammar/Greek/Morph/Smyth/Conjunctions/Subordinating.hs
mit
1,069
0
4
150
105
83
22
13
1
{-# LANGUAGE FlexibleContexts #-} module Sequentc (Jmt(..), Rule(..), apply, prove, derive, qed) where import Data.List import Control.Monad.State infix 4 :|-: data Jmt p = [p] :|-: p deriving (Eq) infix 3 :---: data Rule p = [Jmt p] :---: Jmt p deriving (Eq) -- if the goal rule's first precondition matches up with the step -- rule's conclusion, we get a rule with the first precondition -- removed and the step rule's preconditions added in place of it app :: (Eq p, Show (Rule p)) => Rule p -> Rule p -> Rule p app s@(step_precs :---: step_conc) g@(goal_precs :---: goal_conc) = if step_conc == head(goal_precs) then step_precs++(tail(goal_precs)) :---: goal_conc else error $ "couldn't apply \n" ++ show s ++ "\n\nto \n\n" ++ show g prove :: Jmt a -> Rule a prove j = [j] :---: j derive :: (Eq a, Show (Rule a)) => Rule a -> State (Rule a) () -> Rule a derive goal@(goal_prec :---: goal_conc) proof = let proved = snd (runState proof ([goal_conc] :---: goal_conc)) in if proved == goal then goal else error $ "derive not done yet: goal:\n" ++ show goal ++ "\n\n not equal to proved:\n\n" ++ show proved apply :: (Show (Rule a), Eq a) => Rule a -> State (Rule a) () apply r = do goal <- get put $ app r goal return () qed :: (Show (Rule a)) => State (Rule a) () qed = do rule@(goal_precs :---: _) <- get case goal_precs of [] -> return () _ -> error $ "proof not done yet:\n" ++ show rule
kaeluka/sequentc
sequentc.hs
mit
1,469
0
14
339
577
303
274
34
2
module Sublist (Sublist(..), sublist) where import Data.List (isInfixOf) data Sublist = Sublist | Superlist | Equal | Unequal deriving (Eq, Show) sublist :: Eq a => [a] -> [a] -> Sublist sublist xs ys | xs == ys = Equal | xs `isInfixOf` ys = Sublist | ys `isInfixOf` xs = Superlist | otherwise = Unequal
derekprior/exercism
haskell/sublist/Sublist.hs
mit
334
0
8
86
138
76
62
10
1
module Chess.Board where import qualified Data.Map as Map import Chess.Color import Chess.Figure import Chess.Field import Chess.Move type Board = Map.Map Field Figure -- | The board state when the game starts. startingBoard :: Board startingBoard = Map.fromList [ (Field 1 1, Figure Rook White), (Field 2 1, Figure Knight White), (Field 3 1, Figure Bishop White), (Field 4 1, Figure Queen White), (Field 5 1, Figure King White), (Field 6 1, Figure Bishop White), (Field 7 1, Figure Knight White), (Field 8 1, Figure Rook White), (Field 1 2, Figure Pawn White), (Field 2 2, Figure Pawn White), (Field 3 2, Figure Pawn White), (Field 4 2, Figure Pawn White), (Field 5 2, Figure Pawn White), (Field 6 2, Figure Pawn White), (Field 7 2, Figure Pawn White), (Field 8 2, Figure Pawn White), (Field 1 7, Figure Pawn Black), (Field 2 7, Figure Pawn Black), (Field 3 7, Figure Pawn Black), (Field 4 7, Figure Pawn Black), (Field 5 7, Figure Pawn Black), (Field 6 7, Figure Pawn Black), (Field 7 7, Figure Pawn Black), (Field 8 7, Figure Pawn Black), (Field 1 8, Figure Rook Black), (Field 2 8, Figure Knight Black), (Field 3 8, Figure Bishop Black), (Field 4 8, Figure Queen Black), (Field 5 8, Figure King Black), (Field 6 8, Figure Bishop Black), (Field 7 8, Figure Knight Black), (Field 8 8, Figure Rook Black)] -- | Shows the board. showBoard :: Board -> String showBoard board = " abcdefgh\n" ++ concat (map showRow [8,7..1]) ++ " abcdefgh\n" where showRow row = (show row) ++ concat (map (showField row) [1..8]) ++ (show row) ++ "\n" showField row col = case Map.lookup (Field col row) board of Just x -> show x Nothing -> "." -- | Returns a new board, updated with a move. updateBoard :: Board -> Move -> Board updateBoard board (RegularMove from to) = case Map.lookup from board of Just figure -> Map.insert to figure . Map.delete from $ board _ -> board updateBoard board (PromotionMove from to figure) = case Map.lookup from board of Just _ -> Map.insert to figure . Map.delete from $ board _ -> board updateBoard board (EnPassantMove from to captured) = case Map.lookup from board of Just figure -> Map.insert to figure . Map.delete from . Map.delete captured $ board _ -> board updateBoard board (CastlingMove fromKing toKing fromRook toRook) = case (Map.lookup fromKing board, Map.lookup fromRook board) of (Just king, Just rook) -> Map.insert toKing king . Map.insert toRook rook . Map.delete fromKing . Map.delete fromRook $ board _ -> board {- ghci :load Chess/Board.hs startingBoard showBoard startingBoard putStr $ showBoard startingBoard putStr $ showBoard $ updateBoard startingBoard (RegularMove (Field 2 2) (Field 2 3)) putStr $ showBoard $ updateBoard startingBoard (RegularMove (Field 3 3) (Field 2 3)) putStr $ showBoard $ updateBoard startingBoard (PromotionMove (Field 2 2) (Field 2 8) (Figure Queen White)) putStr $ showBoard $ updateBoard startingBoard (EnPassantMove (Field 2 2) (Field 3 3) (Field 3 7)) putStr $ showBoard $ updateBoard startingBoard (CastlingMove (Field 5 1) (Field 3 1) (Field 1 1) (Field 4 1)) :q -}
grzegorzbalcerek/chess-haskell
Chess/Board.hs
mit
3,397
0
14
870
1,149
590
559
71
5
module PPOL.Sat.Solver.DP ( solve ) where import qualified PPOL.Sat.Formula as F import qualified PPOL.Sat.Clause as C import qualified PPOL.Sat.Literal as L import qualified PPOL.Sat.Variable as V solve :: (Ord a) => Formula a -> Bool
vialette/PPOL
src/PPOL/Sat/Solver/DP.hs
mit
242
2
7
41
72
49
23
8
0
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeSynonymInstances #-} module Data.Tensor.Dense (SliceTo(..) ,GTensorGD ,GMatrix ) where import Prelude import Data.Foldable (foldlM) import Data.Sequence (Seq) import qualified Data.Sequence as SQ import qualified Data.Vector.Generic as GV import Data.Tensor import Data.Tensor.Scheme (shape) import Data.Tensor.Scheme.Dense2D import Data.Tensor.Scheme.DenseGD import Data.Tensor.Slice type GTensorGD = Tensor DenseGD type GMatrix = Tensor Dense2D type instance Slicer (GTensorGD v e) = Seq (InxSlice Int) instance (GV.Vector v e) => SliceTo (GTensorGD v e) (GTensorGD v e) where t .? sls' = case schemeMod of Just (offset, mtable) -> t { _scheme = oscheme { _sgdShape = shape' , _sgdMTable = mtable , _sgdOffset = offset } } Nothing -> generate (mkDefaultDenseGD shape') ((.!) t . SQ.zipWith fromSlInx sls') where oscheme = _scheme t shape' = SQ.zipWith slModShape sls' . shape . _scheme $ t schemeMod = foldlM (fmap . f) (0, SQ.empty) (SQ.zipWith slModScheme sls' (_sgdMTable . _scheme $ t)) where f (off, ms) (o, m) = (off + o, ms SQ.|> m)
lensky/hs-tensor
lib/Data/Tensor/Dense.hs
mit
1,504
0
13
482
405
233
172
34
0
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.RGBColor (js_getRed, getRed, js_getGreen, getGreen, js_getBlue, getBlue, RGBColor, castToRGBColor, gTypeRGBColor) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"red\"]" js_getRed :: RGBColor -> IO (Nullable CSSPrimitiveValue) -- | <https://developer.mozilla.org/en-US/docs/Web/API/RGBColor.red Mozilla RGBColor.red documentation> getRed :: (MonadIO m) => RGBColor -> m (Maybe CSSPrimitiveValue) getRed self = liftIO (nullableToMaybe <$> (js_getRed (self))) foreign import javascript unsafe "$1[\"green\"]" js_getGreen :: RGBColor -> IO (Nullable CSSPrimitiveValue) -- | <https://developer.mozilla.org/en-US/docs/Web/API/RGBColor.green Mozilla RGBColor.green documentation> getGreen :: (MonadIO m) => RGBColor -> m (Maybe CSSPrimitiveValue) getGreen self = liftIO (nullableToMaybe <$> (js_getGreen (self))) foreign import javascript unsafe "$1[\"blue\"]" js_getBlue :: RGBColor -> IO (Nullable CSSPrimitiveValue) -- | <https://developer.mozilla.org/en-US/docs/Web/API/RGBColor.blue Mozilla RGBColor.blue documentation> getBlue :: (MonadIO m) => RGBColor -> m (Maybe CSSPrimitiveValue) getBlue self = liftIO (nullableToMaybe <$> (js_getBlue (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/RGBColor.hs
mit
2,058
18
10
251
549
330
219
30
1