code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
module Beowulf.Style.Colors where import Beowulf.Style aliceBlue :: ColorT aliceBlue = Hex 0xF0F8FF antiqueWhite :: ColorT antiqueWhite = Hex 0xFAEBD7 aqua :: ColorT aqua = Hex 0x00FFFF aquamarine :: ColorT aquamarine = Hex 0x7FFFD4 azure :: ColorT azure = Hex 0xF0FFFF beige :: ColorT beige = Hex 0xF5F5DC bisque :: ColorT bisque = Hex 0xFFE4C4 black :: ColorT black = Hex 0x000000 blanchedAlmond :: ColorT blanchedAlmond = Hex 0xFFEBCD blue :: ColorT blue = Hex 0x0000FF blueViolet :: ColorT blueViolet = Hex 0x8A2BE2 brown :: ColorT brown = Hex 0xA52A2A burlyWood :: ColorT burlyWood = Hex 0xDEB887 cadetBlue :: ColorT cadetBlue = Hex 0x5F9EA0 chartreuse :: ColorT chartreuse = Hex 0x7FFF00 chocolate :: ColorT chocolate = Hex 0xD2691E coral :: ColorT coral = Hex 0xFF7F50 cornflowerBlue :: ColorT cornflowerBlue = Hex 0x6495ED cornsilk :: ColorT cornsilk = Hex 0xFFF8DC crimson :: ColorT crimson = Hex 0xDC143C cyan :: ColorT cyan = Hex 0x00FFFF darkBlue :: ColorT darkBlue = Hex 0x00008B darkCyan :: ColorT darkCyan = Hex 0x008B8B darkGoldenRod :: ColorT darkGoldenRod = Hex 0xB8860B darkGray :: ColorT darkGray = Hex 0xA9A9A9 darkGreen :: ColorT darkGreen = Hex 0x006400 darkKhaki :: ColorT darkKhaki = Hex 0xBDB76B darkMagenta :: ColorT darkMagenta = Hex 0x8B008B darkOliveGreen :: ColorT darkOliveGreen = Hex 0x556B2F darkOrange :: ColorT darkOrange = Hex 0xFF8C00 darkOrchid :: ColorT darkOrchid = Hex 0x9932CC darkRed :: ColorT darkRed = Hex 0x8B0000 darkSalmon :: ColorT darkSalmon = Hex 0xE9967A darkSeaGreen :: ColorT darkSeaGreen = Hex 0x8FBC8F darkSlateBlue :: ColorT darkSlateBlue = Hex 0x483D8B darkSlateGray :: ColorT darkSlateGray = Hex 0x2F4F4F darkTurquoise :: ColorT darkTurquoise = Hex 0x00CED1 darkViolet :: ColorT darkViolet = Hex 0x9400D3 deepPink :: ColorT deepPink = Hex 0xFF1493 deepSkyBlue :: ColorT deepSkyBlue = Hex 0x00BFFF dimGray :: ColorT dimGray = Hex 0x696969 dodgerBlue :: ColorT dodgerBlue = Hex 0x1E90FF fireBrick :: ColorT fireBrick = Hex 0xB22222 floralWhite :: ColorT floralWhite = Hex 0xFFFAF0 forestGreen :: ColorT forestGreen = Hex 0x228B22 fuchsia :: ColorT fuchsia = Hex 0xFF00FF gainsboro :: ColorT gainsboro = Hex 0xDCDCDC ghostWhite :: ColorT ghostWhite = Hex 0xF8F8FF gold :: ColorT gold = Hex 0xFFD700 goldenRod :: ColorT goldenRod = Hex 0xDAA520 gray :: ColorT gray = Hex 0x808080 green :: ColorT green = Hex 0x008000 greenYellow :: ColorT greenYellow = Hex 0xADFF2F honeyDew :: ColorT honeyDew = Hex 0xF0FFF0 hotPink :: ColorT hotPink = Hex 0xFF69B4 indianRed :: ColorT indianRed = Hex 0xCD5C5C indigo :: ColorT indigo = Hex 0x4B0082 ivory :: ColorT ivory = Hex 0xFFFFF0 khaki :: ColorT khaki = Hex 0xF0E68C lavender :: ColorT lavender = Hex 0xE6E6FA lavenderBlush :: ColorT lavenderBlush = Hex 0xFFF0F5 lawnGreen :: ColorT lawnGreen = Hex 0x7CFC00 lemonChiffon :: ColorT lemonChiffon = Hex 0xFFFACD lightBlue :: ColorT lightBlue = Hex 0xADD8E6 lightCoral :: ColorT lightCoral = Hex 0xF08080 lightCyan :: ColorT lightCyan = Hex 0xE0FFFF lightGoldenRodYellow :: ColorT lightGoldenRodYellow = Hex 0xFAFAD2 lightGray :: ColorT lightGray = Hex 0xD3D3D3 lightGreen :: ColorT lightGreen = Hex 0x90EE90 lightPink :: ColorT lightPink = Hex 0xFFB6C1 lightSalmon :: ColorT lightSalmon = Hex 0xFFA07A lightSeaGreen :: ColorT lightSeaGreen = Hex 0x20B2AA lightSkyBlue :: ColorT lightSkyBlue = Hex 0x87CEFA lightSlateGray :: ColorT lightSlateGray = Hex 0x778899 lightSteelBlue :: ColorT lightSteelBlue = Hex 0xB0C4DE lightYellow :: ColorT lightYellow = Hex 0xFFFFE0 lime :: ColorT lime = Hex 0x00FF00 limeGreen :: ColorT limeGreen = Hex 0x32CD32 linen :: ColorT linen = Hex 0xFAF0E6 magenta :: ColorT magenta = Hex 0xFF00FF maroon :: ColorT maroon = Hex 0x800000 mediumAquaMarine :: ColorT mediumAquaMarine = Hex 0x66CDAA mediumBlue :: ColorT mediumBlue = Hex 0x0000CD mediumOrchid :: ColorT mediumOrchid = Hex 0xBA55D3 mediumPurple :: ColorT mediumPurple = Hex 0x9370DB mediumSeaGreen :: ColorT mediumSeaGreen = Hex 0x3CB371 mediumSlateBlue :: ColorT mediumSlateBlue = Hex 0x7B68EE mediumSpringGreen :: ColorT mediumSpringGreen = Hex 0x00FA9A mediumTurquoise :: ColorT mediumTurquoise = Hex 0x48D1CC mediumVioletRed :: ColorT mediumVioletRed = Hex 0xC71585 midnightBlue :: ColorT midnightBlue = Hex 0x191970 mintCream :: ColorT mintCream = Hex 0xF5FFFA mistyRose :: ColorT mistyRose = Hex 0xFFE4E1 moccasin :: ColorT moccasin = Hex 0xFFE4B5 navajoWhite :: ColorT navajoWhite = Hex 0xFFDEAD navy :: ColorT navy = Hex 0x000080 oldLace :: ColorT oldLace = Hex 0xFDF5E6 olive :: ColorT olive = Hex 0x808000 oliveDrab :: ColorT oliveDrab = Hex 0x6B8E23 orange :: ColorT orange = Hex 0xFFA500 orangeRed :: ColorT orangeRed = Hex 0xFF4500 orchid :: ColorT orchid = Hex 0xDA70D6 paleGoldenRod :: ColorT paleGoldenRod = Hex 0xEEE8AA paleGreen :: ColorT paleGreen = Hex 0x98FB98 paleTurquoise :: ColorT paleTurquoise = Hex 0xAFEEEE paleVioletRed :: ColorT paleVioletRed = Hex 0xDB7093 papayaWhip :: ColorT papayaWhip = Hex 0xFFEFD5 peachPuff :: ColorT peachPuff = Hex 0xFFDAB9 peru :: ColorT peru = Hex 0xCD853F pink :: ColorT pink = Hex 0xFFC0CB plum :: ColorT plum = Hex 0xDDA0DD powderBlue :: ColorT powderBlue = Hex 0xB0E0E6 purple :: ColorT purple = Hex 0x800080 red :: ColorT red = Hex 0xFF0000 rosyBrown :: ColorT rosyBrown = Hex 0xBC8F8F royalBlue :: ColorT royalBlue = Hex 0x4169E1 saddleBrown :: ColorT saddleBrown = Hex 0x8B4513 salmon :: ColorT salmon = Hex 0xFA8072 sandyBrown :: ColorT sandyBrown = Hex 0xF4A460 seaGreen :: ColorT seaGreen = Hex 0x2E8B57 seaShell :: ColorT seaShell = Hex 0xFFF5EE sienna :: ColorT sienna = Hex 0xA0522D silver :: ColorT silver = Hex 0xC0C0C0 skyBlue :: ColorT skyBlue = Hex 0x87CEEB slateBlue :: ColorT slateBlue = Hex 0x6A5ACD slateGray :: ColorT slateGray = Hex 0x708090 snow :: ColorT snow = Hex 0xFFFAFA springGreen :: ColorT springGreen = Hex 0x00FF7F steelBlue :: ColorT steelBlue = Hex 0x4682B4 tan :: ColorT tan = Hex 0xD2B48C teal :: ColorT teal = Hex 0x008080 thistle :: ColorT thistle = Hex 0xD8BFD8 tomato :: ColorT tomato = Hex 0xFF6347 turquoise :: ColorT turquoise = Hex 0x40E0D0 violet :: ColorT violet = Hex 0xEE82EE wheat :: ColorT wheat = Hex 0xF5DEB3 white :: ColorT white = Hex 0xFFFFFF whiteSmoke :: ColorT whiteSmoke = Hex 0xF5F5F5 yellow :: ColorT yellow = Hex 0xFFFF00 yellowGreen :: ColorT yellowGreen = Hex 0x9ACD32
jrahm/Beowulf
Beowulf/Style/Colors.hs
Haskell
bsd-2-clause
6,332
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ViewPatterns #-} module Tests.Transform ( tests ) where import Data.Bits ((.&.), shiftL) import Data.Complex (Complex((:+))) import Data.Functor ((<$>)) import Statistics.Function (within) import Statistics.Transform import Test.Framework (Test, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.QuickCheck (Positive(..),Property,Arbitrary(..),Gen,choose,vectorOf, printTestCase, quickCheck) import Text.Printf import qualified Data.Vector.Generic as G import qualified Data.Vector.Unboxed as U import Tests.Helpers tests :: Test tests = testGroup "fft" [ testProperty "t_impulse" t_impulse , testProperty "t_impulse_offset" t_impulse_offset , testProperty "ifft . fft = id" (t_fftInverse $ ifft . fft) , testProperty "fft . ifft = id" (t_fftInverse $ fft . ifft) , testProperty "idct . dct = id [up to scale]" (t_fftInverse (\v -> U.map (/ (2 * fromIntegral (U.length v))) $ idct $ dct v)) , testProperty "dct . idct = id [up to scale]" (t_fftInverse (\v -> U.map (/ (2 * fromIntegral (U.length v))) $ idct $ dct v)) -- Exact small size DCT -- 2 , testDCT [1,0] $ map (*2) [1, cos (pi/4) ] , testDCT [0,1] $ map (*2) [1, cos (3*pi/4) ] -- 4 , testDCT [1,0,0,0] $ map (*2) [1, cos( pi/8), cos( 2*pi/8), cos( 3*pi/8)] , testDCT [0,1,0,0] $ map (*2) [1, cos(3*pi/8), cos( 6*pi/8), cos( 9*pi/8)] , testDCT [0,0,1,0] $ map (*2) [1, cos(5*pi/8), cos(10*pi/8), cos(15*pi/8)] , testDCT [0,0,0,1] $ map (*2) [1, cos(7*pi/8), cos(14*pi/8), cos(21*pi/8)] -- Exact small size IDCT -- 2 , testIDCT [1,0] [1, 1 ] , testIDCT [0,1] $ map (*2) [cos(pi/4), cos(3*pi/4)] -- 4 , testIDCT [1,0,0,0] [1, 1, 1, 1 ] , testIDCT [0,1,0,0] $ map (*2) [cos( pi/8), cos( 3*pi/8), cos( 5*pi/8), cos( 7*pi/8) ] , testIDCT [0,0,1,0] $ map (*2) [cos( 2*pi/8), cos( 6*pi/8), cos(10*pi/8), cos(14*pi/8) ] , testIDCT [0,0,0,1] $ map (*2) [cos( 3*pi/8), cos( 9*pi/8), cos(15*pi/8), cos(21*pi/8) ] ] -- A single real-valued impulse at the beginning of an otherwise zero -- vector should be replicated in every real component of the result, -- and all the imaginary components should be zero. t_impulse :: Double -> Positive Int -> Bool t_impulse k (Positive m) = G.all (c_near i) (fft v) where v = i `G.cons` G.replicate (n-1) 0 i = k :+ 0 n = 1 `shiftL` (m .&. 6) -- If a real-valued impulse is offset from the beginning of an -- otherwise zero vector, the sum-of-squares of each component of the -- result should equal the square of the impulse. t_impulse_offset :: Double -> Positive Int -> Positive Int -> Bool t_impulse_offset k (Positive x) (Positive m) = G.all ok (fft v) where v = G.concat [G.replicate xn 0, G.singleton i, G.replicate (n-xn-1) 0] ok (re :+ im) = within ulps (re*re + im*im) (k*k) i = k :+ 0 xn = x `rem` n n = 1 `shiftL` (m .&. 6) -- Test that (ifft . fft ≈ id) -- -- Approximate equality here is tricky. Smaller values of vector tend -- to have large relative error. Thus we should test that vectors as -- whole are approximate equal. t_fftInverse :: (HasNorm (U.Vector a), U.Unbox a, Num a, Show a, Arbitrary a) => (U.Vector a -> U.Vector a) -> Property t_fftInverse roundtrip = do x <- genFftVector let n = G.length x x' = roundtrip x d = G.zipWith (-) x x' nd = vectorNorm d nx = vectorNorm x id $ printTestCase "Original vector" $ printTestCase (show x ) $ printTestCase "Transformed one" $ printTestCase (show x') $ printTestCase (printf "Length = %i" n) $ printTestCase (printf "|x - x'| / |x| = %.6g" (nd / nx)) $ nd <= 3e-14 * nx -- Test discrete cosine transform testDCT :: [Double] -> [Double] -> Test testDCT (U.fromList -> vec) (U.fromList -> res) = testAssertion ("DCT test for " ++ show vec) $ vecEqual 3e-14 (dct vec) res -- Test inverse discrete cosine transform testIDCT :: [Double] -> [Double] -> Test testIDCT (U.fromList -> vec) (U.fromList -> res) = testAssertion ("IDCT test for " ++ show vec) $ vecEqual 3e-14 (idct vec) res ---------------------------------------------------------------- -- With an error tolerance of 8 ULPs, a million QuickCheck tests are -- likely to all succeed. With a tolerance of 7, we fail around the -- half million mark. ulps :: Int ulps = 8 c_near :: CD -> CD -> Bool c_near (a :+ b) (c :+ d) = within ulps a c && within ulps b d -- Arbitrary vector for FFT od DCT genFftVector :: (U.Unbox a, Arbitrary a) => Gen (U.Vector a) genFftVector = do n <- (2^) <$> choose (1,9::Int) -- Size of vector G.fromList <$> vectorOf n arbitrary -- Vector to transform -- Ad-hoc type class for calculation of vector norm class HasNorm a where vectorNorm :: a -> Double instance HasNorm (U.Vector Double) where vectorNorm = sqrt . U.sum . U.map (\x -> x*x) instance HasNorm (U.Vector CD) where vectorNorm = sqrt . U.sum . U.map (\(x :+ y) -> x*x + y*y) -- Approximate equality for vectors vecEqual :: Double -> U.Vector Double -> U.Vector Double -> Bool vecEqual ε v u = vectorNorm (U.zipWith (-) v u) < ε * vectorNorm v
00tau/statistics
tests/Tests/Transform.hs
Haskell
bsd-2-clause
5,615
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} module LiuMS where import Control.Monad import Control.Monad.Reader import Control.Monad.Trans.Except import Control.Monad.IO.Class import System.Directory import Data.ByteString.Lazy.Char8 (pack) import Text.Blaze.Html (Html) import Text.Blaze.Internal (unsafeByteString) import Text.Pandoc.Options import Text.Pandoc.Readers.Markdown import Text.Pandoc.Writers.HTML import Servant hiding (Handler) import Servant.Utils.StaticFiles import System.FilePath (addTrailingPathSeparator) import Network.Wai import Network.Wai.Application.Static (staticApp, defaultFileServerSettings) import Servant.ContentType.PlainHtml import Servant.ContentType.Processable import LiuMS.Template.Basic import LiuMS.Config import LiuMS.CacheManager type Gets = Get '[PlainHtml :<- Basic] Html type SiteAPI = ConfiglessAPI :<|> ConfigfulAPI type ConfiglessAPI = "static" :> Raw type ConfigfulAPI = Gets :<|> "about" :> Gets type PostsAPI = Capture "year" Integer :> Capture "month" Integer :> (Gets :<|> Raw) type ProjectsAPI = Capture "project" String :> (Gets :<|> Raw) hostPage :: FilePath -> Handler Html hostPage page = do root <- askContentPath let pageDir = root ++ "/contents/" ++ page ++ "/" let textPath = pageDir ++ "index.md" exists <- liftIO $ doesFileExist textPath unless exists $ lift $ throwE fileNotFoundErr textFile <- liftIO $ readFile textPath let (Right markdown) = readMarkdown def textFile return $ writeHtml def markdown where fileNotFoundErr = err404 { errBody = pack $ page ++ " not found." } configfulServer :: ServerT ConfigfulAPI Handler configfulServer = load "index" :<|> load "about" where load :: FilePath -> Handler Html load path = do manager <- askCacheManager result <- lift $ loadResource "md" manager path return $ unsafeByteString result server :: Config -> Server SiteAPI server config = serveDirectory (contentPath config ++ "/static") :<|> enter (runHandlerNat config) configfulServer type Handler = ReaderT Config (ExceptT ServantErr IO) runHandlerNat :: Config -> (Handler :~> ExceptT ServantErr IO) runHandlerNat config = Nat (flip runReaderT config)
notcome/liu-ms-adult
src/LiuMS.hs
Haskell
bsd-3-clause
2,373
----------------------------------------------------------------------------- -- -- Module : Code.Generating.Utils.Syntax.Exp -- Copyright : (c) 2011 Lars Corbijn -- License : BSD-style (see the file /LICENSE) -- -- Maintainer : -- Stability : -- Portability : -- -- | -- ----------------------------------------------------------------------------- module Code.Generating.Utils.Syntax.Exp ( var', con', errorExp, otherwiseExp, var, con, (@@), (\->), (.$.), (...), (=@=), (/@=), (+@+), infixAppS, ) where ----------------------------------------------------------------------------- import Language.Haskell.Exts.Syntax import Code.Generating.Utils.No import Code.Generating.Utils.Syntax.Names ----------------------------------------------------------------------------- infixl 9 @@ infixr 8 ... infixr 5 +@+ infix 4 =@=, /@= infixr 0 .$. var' :: String -> Exp var' = Var . unQual' var :: Name -> Exp var = Var . UnQual con' :: String -> Exp con' = Con . unQual' con :: Name -> Exp con = Con . UnQual errorExp :: String -> Exp errorExp = App (var' "error") . Lit . String otherwiseExp :: Exp otherwiseExp = var' "otherwise" -- Opperators (@@) :: Exp -> Exp -> Exp (@@) = App (.$.) :: Exp -> Exp -> Exp (.$.) = infixAppS "$" (...) :: Exp -> Exp -> Exp (...) = infixAppS "." (=@=), (/@=) :: Exp -> Exp -> Exp (=@=) = infixAppS "==" (/@=) = infixAppS "/=" (+@+) :: Exp -> Exp -> Exp (+@+) = infixAppS "++" (\->) :: [Pat] -> Exp -> Exp (\->) = Lambda noSrcLoc infixAppS :: String -> Exp -> Exp -> Exp infixAppS inf ex1 ex2 = InfixApp ex1 (QVarOp $ unQualSym' inf) ex2 -----------------------------------------------------------------------------
Laar/CodeGenerating
src/Code/Generating/Utils/Syntax/Exp.hs
Haskell
bsd-3-clause
1,715
module SMACCMPilot.GCS.Gateway.ByteString where import Data.ByteString (ByteString) import qualified Data.ByteString as B import Text.Printf import SMACCMPilot.GCS.Gateway.Monad bytestringPad :: Integer -> ByteString -> GW ByteString bytestringPad l bs = if B.length bs <= len then return $ bs `B.append` (B.pack $ replicate (len - B.length bs) 0) else writeErr "bytestringPad got oversized bytestring" >> return bs where len = fromInteger l bytestringDebugger :: String -> ByteString -> GW ByteString bytestringDebugger tag bs = writeDbg msg >> return bs where msg = printf "%s ByteString %d [%s]" tag (B.length bs) body body = fixup (unwords (map hexdig (B.unpack bs))) hexdig = printf "0x%0.2x," -- Drop last char because the above map/unwords is bad hack fixup = reverse . drop 1 . reverse bytestringDebugWhen :: (ByteString -> Bool) -> String -> ByteString -> GW ByteString bytestringDebugWhen p tag bs = case p bs of True -> writeDbg msg >> return bs False -> return bs where msg = printf "%s ByteString %d [%s]" tag (B.length bs) body body = fixup (unwords (map hexdig (B.unpack bs))) hexdig = printf "0x%0.2x," -- Drop last char because the above map/unwords is bad hack fixup = reverse . drop 1 . reverse
GaloisInc/smaccmpilot-gcs-gateway
SMACCMPilot/GCS/Gateway/ByteString.hs
Haskell
bsd-3-clause
1,323
{-# LANGUAGE OverloadedStrings #-} module HStyle.Block.Tests ( tests ) where import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (Assertion, (@?=)) import qualified Data.Text as T import HStyle.Block tests :: Test tests = testGroup "HStyle.Block.Tests" [ testCase "subBlock_01" subBlock_01 , testCase "updateSubBlock_01" updateSubBlock_01 ] subBlock_01 :: Assertion subBlock_01 = toLines (subBlock 2 3 poem) @?= ["A little man who wasn't there", "He wasn't there again today"] updateSubBlock_01 :: Assertion updateSubBlock_01 = toLines (updateSubBlock old new poem) @?= [ "Last night I saw upon the stair" , "A little man who wasn't there..." , "He wasn't there again today..." , "Oh, how I wish he'd go away" ] where old = subBlock 2 3 poem new = mapLines (`T.append` "...") old poem :: Block poem = fromText "Last night I saw upon the stair\n\ \A little man who wasn't there\n\ \He wasn't there again today\n\ \Oh, how I wish he'd go away"
mightybyte/hstyle
tests/HStyle/Block/Tests.hs
Haskell
bsd-3-clause
1,079
-------------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} module Main ( main ) where -------------------------------------------------------------------------------- import Control.Concurrent (forkIO) import Control.Monad (forever, unless) import Control.Monad.Trans (liftIO) import Data.Aeson import Network.Socket (withSocketsDo) import qualified Data.ByteString.Lazy as LBS import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import qualified Data.Text.IO as T import qualified Data.Set as S import qualified Network.WebSockets as WS -------------------------------------------------------------------------------- app :: WS.ClientApp () app conn = do putStrLn "Connected!" -- Fork a thread that writes WS data to stdout _ <- forkIO $ forever $ do msg <- WS.receiveData conn let msgLBS = LBS.fromStrict (encodeUtf8 msg) let eWorld = eitherDecode msgLBS :: Either String World liftIO $ T.putStrLn msg case eWorld of Left err -> liftIO $ print err Right world -> do liftIO $ print world let mDir = getNextMove world case mDir of Just dir -> do sendCommand conn DropBomb sendCommand conn (dirToCommand dir) Nothing -> return () sendCommand conn (SetName "Santa's Lazy Haskellers") -- Read from stdin and write to WS let loop = do line <- T.getLine let command = parseCommand line sendCommand conn command loop -- unless (T.null line) $ WS.sendTextData conn line >> loop loop WS.sendClose conn ("Bye!" :: Text) -------------------------------------------------------------------------------- main :: IO () main = withSocketsDo $ WS.runClient "10.112.155.244" 8080 "/" app data Command = Look | DropBomb | SetName String | MoveNorth | MoveSouth | MoveEast | MoveWest deriving Show instance ToJSON Command where toJSON com@(SetName name) = object ["command" .= ["SetName", name]] toJSON com = object ["command" .= show com] parseCommand :: T.Text -> Command parseCommand "h" = MoveWest parseCommand "j" = MoveSouth parseCommand "k" = MoveNorth parseCommand "l" = MoveEast parseCommand "b" = DropBomb parseCommand _ = Look sendCommand :: WS.Connection -> Command -> IO () sendCommand conn command = do let jsonCommand = encode command LBS.putStrLn jsonCommand WS.sendTextData conn jsonCommand data World = World { walls :: [Wall] , players :: [Player] , bombs :: [Bomb] } deriving Show instance FromJSON World where parseJSON (Object v) = World <$> v.: "walls" <*> v .: "players" <*> v .: "bombs" {- {"alive":true,"type":"Strong","position":{"x":0,"y":0} -} data Wall = Wall { wAlive :: Bool , wStrength :: WallStrength , wPosition :: Position } deriving Show instance FromJSON Wall where parseJSON (Object v) = Wall <$> v .: "alive" <*> v.: "type" <*> v.: "position" data WallStrength = Strong | Weak deriving Show instance FromJSON WallStrength where parseJSON (String s) = return $ toWallStrength s parseJSON e = error $ "wall strength error: " ++ show e toWallStrength :: T.Text -> WallStrength toWallStrength "Strong" = Strong toWallStrength "Weak" = Weak data Position = Position { posX :: Int , posY :: Int } deriving Show instance FromJSON Position where parseJSON (Object v) = Position <$> v .: "x" <*> v.: "y" {- {"alive":true,"score":-2,"name":"Pythonistas","id":"36242761-d09a-4010-8570-907798ae8945","position":{"x":1,"y":9}} -} data Player = Player { pAlive :: Bool , pScore :: Int , pName :: String , pID :: String , pPosition :: Position } deriving Show instance FromJSON Player where parseJSON (Object v) = Player <$> v .: "alive" <*> v .: "score" <*> v .: "name" <*> v .: "id" <*> v .: "position" {- {"blast":null,"position":{"x":1,"y":2}} -} data Bomb = Bomb { bBlast :: Maybe () , bPosition :: Position } deriving Show instance FromJSON Bomb where parseJSON (Object v) = Bomb <$> v .: "blast" <*> v .: "position" getMe :: [Player] -> Maybe Player getMe (p:ps) = if pName p == "Santa's Lazy Haskellers" then Just p else getMe ps getMe _ = Nothing dirToCommand :: Direction -> Command dirToCommand North = MoveNorth dirToCommand South = MoveSouth dirToCommand East = MoveEast dirToCommand West = MoveWest data Direction = North | East | South | West deriving (Eq, Ord, Show) getNextMove :: World -> Maybe Direction getNextMove world = case getMe (players world) of Nothing -> Nothing Just player -> Just $ nextMove player (walls world) nextMove :: Player -> [Wall] -> Direction nextMove player walls = head (S.toList (openMoves player walls)) openMoves :: Player -> [Wall] -> S.Set Direction openMoves player walls = S.fromList [North, East, South, West] `S.difference` closedDirs where closedDirs = closedMoves player walls closedMoves :: Player -> [Wall] -> S.Set Direction closedMoves _ [] = S.empty closedMoves player walls = go S.empty player walls where go dirs _ [] = dirs go dirs p (w:ws) = let newDirs = case p `nextTo` w of Just dir -> S.insert dir dirs Nothing -> dirs in go newDirs p ws nextTo :: Player -> Wall -> Maybe Direction nextTo player wall = let wX = posX (wPosition wall) wY = posY (wPosition wall) pX = posX (pPosition player) pY = posY (pPosition player) dX = pX - wX dY = pY - wY in dir dX dY where dir 1 0 = Just East dir (-1) 0 = Just West dir 0 1 = Just North dir 0 (-1) = Just South dir _ _ = Nothing
mattjbray/super-bomber-elf-haskell
app/Main.hs
Haskell
bsd-3-clause
5,885
-- | -- Navigable tree structure which allow a program to traverse -- up the tree as well as down. -- copied and modified from HXML (<http://www.flightlab.com/~joe/hxml/>) -- module Yuuko.Data.NavTree ( module Yuuko.Data.NavTree , module Yuuko.Data.Tree.NTree.TypeDefs ) where import Yuuko.Data.Tree.NTree.TypeDefs -- ----------------------------------------------------------------------------- -- NavTree -- -- | navigable tree with nodes of type node -- -- a navigable tree consists of a n-ary tree for the current fragment tree, -- a navigable tree for all ancestors, and two n-ary trees for -- the previous- and following siblings data NavTree a = NT (NTree a) -- self [NavTree a] -- ancestors [NTree a] -- previous siblings (in reverse order) [NTree a] -- following siblings deriving (Show, Eq, Ord) -- ----------------------------------------------------------------------------- -- | -- converts a n-ary tree in a navigable tree ntree :: NTree a -> NavTree a ntree nd = NT nd [] [] [] -- | -- converts a navigable tree in a n-ary tree subtreeNT :: NavTree a -> NTree a subtreeNT (NT nd _ _ _) = nd -- | -- function for selecting the value of the current fragment tree dataNT :: NavTree a -> a dataNT (NT (NTree a _) _ _ _) = a -- ----------------------------------------------------------------------------- -- functions for traversing up, down, left and right in a navigable tree upNT , downNT , leftNT , rightNT :: NavTree a -> Maybe (NavTree a) upNT (NT _ (p:_) _ _) = Just p upNT (NT _ [] _ _) = Nothing downNT t@(NT (NTree _ (c:cs)) u _ _) = Just (NT c (t:u) [] cs) downNT (NT (NTree _ [] ) _ _ _) = Nothing leftNT (NT s u (l:ls) r) = Just (NT l u ls (s:r)) leftNT (NT _ _ [] _) = Nothing rightNT (NT s u l (r:rs)) = Just (NT r u (s:l) rs) rightNT (NT _ _ _ [] ) = Nothing -- preorderNT t = t : concatMap preorderNT (children t) -- where children = maybe [] (maybeStar rightNT) . downNT preorderNT :: NavTree a -> [NavTree a] preorderNT = visit [] where visit k t = t : maybe k (visit' k) (downNT t) visit' k t = visit (maybe k (visit' k) (rightNT t)) t revPreorderNT :: NavTree a -> [NavTree a] revPreorderNT t = t : concatMap revPreorderNT (reverse (children t)) where children = maybe [] (maybeStar rightNT) . downNT getChildrenNT :: NavTree a -> [NavTree a] getChildrenNT node = maybe [] follow (downNT node) where follow n = n : maybe [] follow (rightNT n) -- ----------------------------------------------------------------------------- -- Miscellaneous useful combinators -- | -- Kleisli composition: o' :: (Monad m) => (b -> m c) -> (a -> m b) -> (a -> m c) f `o'` g = \x -> g x >>= f -- Some useful anamorphisms: maybeStar, maybePlus :: (a -> Maybe a) -> a -> [a] maybeStar f a = a : maybe [] (maybeStar f) (f a) maybePlus f a = maybe [] (maybeStar f) (f a) -- -----------------------------------------------------------------------------
nfjinjing/yuuko
src/Yuuko/Data/NavTree.hs
Haskell
bsd-3-clause
3,027
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} -- {-# LANGUAGE DataKinds #-} -- {-# LANGUAGE TypeOperators #-} module Ivory.Opts.CFG ( callGraphDot -- ** Generate a dot file of the control flow for a program. , SizeMap(..) -- ** Implementation-defined size map for stack elements. , defaultSizeMap , hasLoop -- ** Does the control-flow graph contain a loop? , WithTop , maxStack -- ** What is the maximum stack size of the program? ) where import qualified Ivory.Language.Array as I import qualified Ivory.Language.Syntax.AST as I import qualified Ivory.Language.Syntax.Type as I import qualified Data.Graph.Inductive as G import Prelude hiding (lookup) import Data.Monoid import System.FilePath import Data.Maybe import Data.List hiding (lookup) import Control.Applicative import qualified Data.IntMap as M import MonadLib (StateT, get, set, Id, StateM, runM) import MonadLib.Derive (derive_get, derive_set, Iso(..)) -- import Ivory.Language hiding (Top) -------------------------------------------------------------------------------- -- Types -- | Add Top to a type. data WithTop a = Top | Val a deriving (Eq, Functor) instance Show a => Show (WithTop a) where show Top = "Top" show (Val a) = show a instance Ord a => Ord (WithTop a) where compare Top (Val _) = GT compare (Val _) Top = LT compare Top Top = EQ compare (Val a) (Val b) = compare a b instance Applicative WithTop where pure a = Val a Val _ <*> Top = Top Val f <*> (Val a) = Val (f a) _ <*> _ = Top type Size = Integer type CallNm = String -- | We track those objects for which the size might be -- implementation-dependent. data StackType = TyStruct String -- ^ Name of struct | TyArr StackType Size -- ^ Array and size | Ptr -- ^ Pointer or ref type | TyVoid | TyInt IntSize | TyWord WordSize | TyBool | TyChar | TyFloat | TyDouble deriving (Show, Eq) data IntSize = Int8 | Int16 | Int32 | Int64 deriving (Show,Eq) data WordSize = Word8 | Word16 | Word32 | Word64 deriving (Show,Eq) data (Show a, Eq a) => Block a = Stmt a | Branch [Block a] [Block a] | Loop (Maybe Integer) [Block a] -- If we know how many loops we make, we -- store it. Otherwise, `Nothing`. deriving (Show, Eq) type Control = Block CallNm -- ^ Name of function being called type Alloc = Block StackType -- ^ Memory being allocated -- | Describes the CFG and memory usage for a single procedure. data ProcInfo = ProcInfo { procSym :: CallNm , params :: [StackType] -- ^ Parameters pushed onto the stack. , alloc :: [Alloc] -- ^ Allocated elements. , calls :: [Control] } deriving (Show, Eq) data ModuleInfo = ModuleInfo { modName :: String , procs :: [ProcInfo] } deriving (Show, Eq) -------------------------------------------------------------------------------- -- Procedure Analysis toStackTyped :: I.Typed a -> StackType toStackTyped ty = toStackType (I.tType ty) toStackType :: I.Type -> StackType toStackType ty = case ty of I.TyStruct nm -> TyStruct nm I.TyArr i t -> TyArr (toStackType t) (fromIntegral i) I.TyRef{} -> Ptr I.TyConstRef{} -> Ptr I.TyPtr{} -> Ptr I.TyVoid -> TyVoid I.TyInt i -> TyInt (toIntType i) I.TyWord w -> TyWord (toWordType w) I.TyIndex _n -> toStackType I.ixRep I.TyBool -> TyBool I.TyChar -> TyChar I.TyFloat -> TyFloat I.TyDouble -> TyDouble t -> error $ "Unhandled stack type: " ++ show t toIntType :: I.IntSize -> IntSize toIntType i = case i of I.Int8 -> Int8 I.Int16 -> Int16 I.Int32 -> Int32 I.Int64 -> Int64 toWordType :: I.WordSize -> WordSize toWordType i = case i of I.Word8 -> Word8 I.Word16 -> Word16 I.Word32 -> Word32 I.Word64 -> Word64 cfgProc :: I.Proc -> ProcInfo cfgProc proc = ProcInfo { procSym = I.procSym proc , params = map toStackTyped (I.procArgs proc) , alloc = concatMap toAlloc (I.procBody proc) , calls = concatMap toCall (I.procBody proc) } toAlloc :: I.Stmt -> [Alloc] toAlloc stmt = case stmt of I.Assign ty _ _ -> [Stmt $ toStackType ty] I.AllocRef ty _ _ -> [Stmt $ toStackType ty] I.Deref ty _ _ -> [Stmt $ toStackType ty] -- Descend into blocks I.IfTE _ blk0 blk1 -> [ Branch (concatMap toAlloc blk0) (concatMap toAlloc blk1) ] -- For the loop variable. I.Loop _ e _ blk -> let ty = I.ixRep in [Stmt (toStackType ty), Loop (getIdx e) (concatMap toAlloc blk)] I.Forever blk -> [Loop Nothing (concatMap toAlloc blk)] _ -> [] toCall :: I.Stmt -> [Control] toCall stmt = case stmt of I.IfTE _ blk0 blk1 -> [ Branch (concatMap toCall blk0) (concatMap toCall blk1) ] I.Call _ _ nm _ -> case nm of I.NameSym sym -> [Stmt sym] I.NameVar _ -> error $ "XXX need to implement function pointers." I.Loop _ e _ blk -> [Loop (getIdx e) (concatMap toCall blk)] _ -> [] getIdx :: I.Expr -> Maybe Integer getIdx e = case e of I.ExpLit (I.LitInteger i) -> Just i _ -> Nothing -------------------------------------------------------------------------------- -- Call-graph construction from a module. -- type Node = G.LNode ProcInfo -- | A call graph is a graph in which nodes are labeled by their procedure info -- and edges are unlabeled. type CFG = G.Gr ProcInfo () flattenControl :: Control -> [CallNm] flattenControl ctrl = case ctrl of Stmt str -> [str] Branch ctrl0 ctrl1 -> concatMap flattenControl ctrl0 ++ concatMap flattenControl ctrl1 Loop _ ctrl0 -> concatMap flattenControl ctrl0 cfgModule :: I.Module -> ModuleInfo cfgModule m = ModuleInfo { modName = I.modName m , procs = map cfgProc ps } where ps = I.public (I.modProcs m) ++ I.private (I.modProcs m) -- | Construct a control-flow graph from an Ivory module. cfg :: I.Module -> CFG cfg m = G.insEdges (concatMap go nodes) $ G.insNodes nodes G.empty where nodes :: [G.LNode ProcInfo] nodes = zip [0,1..] (procs $ cfgModule m) go :: (Int, ProcInfo) -> [G.LEdge ()] go (i,p) = let outCalls = concatMap flattenControl (calls p) in let outIdxs = catMaybes (map (lookup nodes) outCalls) in zip3 (repeat i) outIdxs (repeat ()) -- outboud edges lookup ls sym | [] <- ls = Nothing | ((i,p):_) <- ls , procSym p == sym = Just i | (_:ls') <- ls = lookup ls' sym | otherwise = error "Unreachable in cfg" -- To make GHC happy. -- | Just label the nodes with the function names. procSymGraph :: CFG -> G.Gr CallNm () procSymGraph = G.nmap procSym -- | Does the program have a loop in it? hasLoop :: CFG -> Bool hasLoop = G.hasLoop -------------------------------------------------------------------------------- -- Stack usage analysis. data SizeMap = SizeMap { stackElemMap :: StackType -> Size -- ^ Mapping from `StackType` to their -- implementation-dependent size. , retSize :: Size -- ^ Size of a return address. } -- | Maps everything to being size 1. Useful for testing. defaultSizeMap :: SizeMap defaultSizeMap = SizeMap { stackElemMap = const 1 , retSize = 1 } -- A mapping from `Node` (Ints) to the maximum stack usage for that function. type MaxMap = M.IntMap Size newtype MaxState a = MaxState { unSt :: StateT MaxMap Id a } deriving (Functor, Monad, Applicative) instance StateM MaxState MaxMap where get = derive_get (Iso MaxState unSt) set = derive_set (Iso MaxState unSt) emptyMaxSt :: MaxMap emptyMaxSt = M.empty getMaxMap :: MaxState MaxMap getMaxMap = return =<< get -- | Takes a procedure name, a control-flow graph, and a `SizeMap` and produces -- the maximum stack usage starting at the procedure give. Returns `Top` if -- there is an unanalyzable loop in the program (ie., non-constant loop) and -- @Val max@ otherwise. maxStack :: CallNm -> CFG -> SizeMap -> WithTop Size maxStack proc cf szmap = go proc where go p = fst $ runM (unSt (maxStack' cf szmap [] (findNode cf p))) emptyMaxSt -- Get the node from it's name. findNode :: CFG -> CallNm -> G.Node findNode cf proc = fst $ fromMaybe (error $ "Proc " ++ proc ++ " is not in the graph!") (find ((== proc) . procSym . snd) (G.labNodes cf)) maxStack' :: CFG -> SizeMap -> [G.Node] -> G.Node -> MaxState (WithTop Size) maxStack' cf szmap visited curr | curr `elem` visited = return Top -- A loop is detected. | otherwise = maxStackNode where -- Process the max stack for a single node. maxStackNode :: MaxState (WithTop Size) maxStackNode = do blkMax <- goBlks cf szmap visited curr alloc' calls' let sz = (topAllocSz + paramsSz + retSize szmap +) <$> blkMax return sz where cxt = G.context cf curr procInfo = G.lab' cxt alloc' = alloc procInfo calls' = calls procInfo -- Top-level allocation topAllocSz :: Size topAllocSz = getSize szmap (getBlock alloc') paramsSz :: Size paramsSz = getSize szmap (params procInfo) goBlks :: CFG -> SizeMap -> [G.Node] -> G.Node -> [Alloc] -> [Control] -> MaxState (WithTop Size) goBlks cf szmap visited curr acs cns = case (acs, cns) of -- Done with all blocks/statements in this function. ([] ,[]) -> return (Val 0) (Branch a0 a1:acs', Branch c0 c1:cns') -> do sz0 <- goBlks' a0 c0 sz1 <- goBlks' a1 c1 sz2 <- goBlks' acs' cns' return (liftA2 max sz0 sz1 <+> sz2) -- There's no new loop allocation, just assignments. So we assume that on -- each iteration, the stack usage doesn't change. (Loop _ a:acs', Loop _ c:cns') -> do sz0 <- goBlks' a c sz1 <- goBlks' acs' cns' return (sz0 <+> sz1) -- case idx of -- -- Unknown loop bound. -- Nothing -> if sz0 == Val 0 then return sz1 -- else return Top -- Did some allocation in the loop, so -- -- can't compute. -- Just _ -> -- There is either a straight-line call or assignment. _ -> do sz0 <- goBlk cf szmap visited curr (getBlock acs) (getBlock cns) sz1 <- goBlks' (nxtBlock acs) (nxtBlock cns) return (sz0 <+> sz1) where goBlks' = goBlks cf szmap visited curr goBlk :: CFG -> SizeMap -> [G.Node] -> G.Node -> [StackType] -> [CallNm] -> MaxState (WithTop Size) goBlk cf szmap visited curr acs cns = do maxMp <- getMaxMap let localAlloc = getSize szmap acs let callNodes = map (findNode cf) cns let allCalls = zip callNodes (map (flip M.lookup $ maxMp) callNodes) newMaxs <- mapM cachedCalls allCalls return $ Val localAlloc <+> if null newMaxs then Val 0 -- Depends on Top being >= all vals. else maximum newMaxs where cachedCalls :: (G.Node, Maybe Size) -> MaxState (WithTop Size) cachedCalls (n, msz) | Just sz <- msz = return (Val sz) | otherwise = maxStack' cf szmap (curr:visited) n (<+>) :: Num a => WithTop a -> WithTop a -> WithTop a (<+>) = liftA2 (+) -- Get the cumulative sizes of allocated things. getSize :: SizeMap -> [StackType] -> Size getSize szmap = sum . map (stackElemMap szmap) -- Get the prefix of a list of @[Block a] in the current block. getBlock :: (Show a, Eq a) => [Block a] -> [a] getBlock bls | (Stmt b:bs) <- bls = b : getBlock bs | otherwise = [] nxtBlock :: (Show a, Eq a) => [Block a] -> [Block a] nxtBlock bls | (Stmt _:bs) <- bls = nxtBlock bs | otherwise = bls -- | Call-graph output. Takes a start function foo, a filepath, and emits the -- graph named "foo.dot" in the filepath. callGraphDot :: CallNm -> FilePath -> [I.Module] -> IO CFG callGraphDot proc path mods = writeFile (path </> proc `addExtension` "dot") grOut >> return graph where m = mconcat mods grOut = graphviz filterG (I.modName m) filterG :: G.Gr CallNm () filterG = let closure = G.reachable (findNode graph proc) graph in G.delNodes (G.nodes graph \\ closure) (procSymGraph graph) graph = cfg m -------------------------------------------------------------------------------- -- Adapted from fgl (BSD3) to remove sizing info. graphviz :: (G.Graph g, Show a, Show b) => g a b -- ^ The graph to format -> String -- ^ The title of the graph -> String graphviz g t = let n = G.labNodes g e = G.labEdges g ns = concatMap sn n es = concatMap se e in "digraph "++t++" {\n" ++ ns ++ es ++"}" where sn (n, a) | sa == "" = "" | otherwise = '\t':(show n ++ sa ++ "\n") where sa = sl a se (n1, n2, b) = '\t':(show n1 ++ " -> " ++ show n2 ++ sl b ++ "\n") sl :: (Show a) => a -> String sl a = let l = sq (show a) in if (l /= "()") then (" [label = \""++l++"\"]") else "" sq :: String -> String sq s@[_] = s sq ('"':s) | last s == '"' = init s | otherwise = s sq ('\'':s) | last s == '\'' = init s | otherwise = s sq s = s -------------------------------------------------------------------------------- -- Testing {- fibCFG :: CFG fibCFG = cfg fibMod outGraph = writeFile "fib.dot" gr where gr = G.graphviz (procSymGraph fibCFG) "fib" (4,4) (4,4) G.Portrait ---------------------- fibMod :: Module fibMod = package "fib" $ do incl fib incl fib_aux fib :: Def ('[Uint32] :-> Uint64) fib = proc "fib" (\n -> body (ret =<< call fib_aux 0 1 n)) fib_aux :: Def ('[Uint32,Uint32,Uint32] :-> Uint64) fib_aux = proc "fib_aux" $ \ a b n -> body $ do ifte_ (n ==? 0) (ret (safeCast a)) (ret . safeCast =<< call fib_aux b (a + b) (n - 1)) fibSz = SizeMap { stackElemMap = \_ -> 1 , retSize = 1 } ------------------------------------- x :: G.Gr Int () x = G.insEdges edges gr where edges = [(0,1,()), (0,2,()), (2,1,()), (2,3,())] gr = G.insNodes nodes G.empty nodes = zip [0,1 ..] [2,3,4,1] y :: G.Gr Int () y = G.insEdges edges gr where edges = [(0,1,()), (0,2,()), (2,1,()), (1,3,())] gr = G.insNodes nodes G.empty nodes = zip [0,1 ..] [1,4,5,8] maxf :: G.Gr Int () -> G.Node -> Maybe Int maxf g n = maxf' [] n where maxf' :: [G.Node] -> G.Node -> Maybe Int maxf' visited curr | curr `elem` visited = Nothing -- We made a loop on this path! That's Top. | otherwise = liftA2 (+) (Just $ G.lab' cxt) go where cxt = G.context g curr res = map (maxf' (G.node' cxt : visited)) (G.suc' cxt) go | null (G.suc' cxt) = Just 0 -- No more successors to try | Nothing `elem` res = Nothing | otherwise = Just $ maximum (catMaybes res) -}
Hodapp87/ivory
ivory-opts/src/Ivory/Opts/CFG.hs
Haskell
bsd-3-clause
15,612
{- Implements the judgement freshTy given in Chapter 5. Also defines the monad Mfresh in which these judgements can be expressed -} module HOCHC.Fresh(freshVar, freshVarx,freshRel,freshTy,freshEnv, Mfresh, lift, runStateT, runFresh) where import HOCHC.DataTypes import Control.Monad (liftM, ap) import Control.Applicative import Control.Monad.State import Control.Monad.Except type Mfresh = StateT Int (Either String) freshVar :: Mfresh Variable freshVar = state (\n->("x_"++show n,n+1)) freshVarx :: Variable -> Mfresh Variable freshVarx x = state (\n->(x++"_"++show n,n+1)) runFresh :: Monad m => StateT Int m a -> m a runFresh = flip evalStateT 0 freshRel :: DeltaEnv -> Sort -> Mfresh (Term,(Variable,Sort)) freshRel d rho = do x<-freshVar return (foldl (\ t y -> Apply t (Variable y)) (Variable x) ys, (x,iterate (Arrow Int) rho !! length ys)) where ys = map fst $ filter ((==Int).snd) d freshTy :: DeltaEnv -> Sort -> Mfresh (MonoType,DeltaEnv) freshTy d Bool = do (t,d) <- freshRel d Bool return (BoolT t,[d]) freshTy d Int = return (IntT,[]) freshTy d (Arrow Int s) = do z <- freshVar (ty,ds)<-freshTy ((z,Int):d) s return $ (ArrowT z IntT ty ,ds) freshTy d (Arrow s1 s2) = do (ty1,d1) <- freshTy d s1 (ty2,d2) <- freshTy d s2 return (ArrowT "_" ty1 ty2,d2++d1) freshEnv :: DeltaEnv -> Mfresh (Gamma,DeltaEnv) freshEnv delta = do (tys,ds) <- unzip <$> (sequence $ map (freshTy [] . snd) delta) return (zip (map fst delta) tys, concat ds)
penteract/HigherOrderHornRefinement
HOCHC/Fresh.hs
Haskell
bsd-3-clause
1,553
-- The Compiler Toolkit: configuration switches -- -- Author : Manuel M. T. Chakravarty -- Created: 3 October 95 -- -- Version $Revision: 1.3 $ from $Date: 1999/09/27 08:44:42 $ -- -- Copyright (c) [1995...1999] Manuel M. T. Chakravarty -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Library General Public -- License as published by the Free Software Foundation; either -- version 2 of the License, or (at your option) any later version. -- -- This library 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 -- Library General Public License for more details. -- --- DESCRIPTION --------------------------------------------------------------- -- -- This modules is used to configure the toolkit. -- --- DOCU ---------------------------------------------------------------------- -- -- language: Haskell 98 -- -- * Must not import any other module. -- --- TODO ---------------------------------------------------------------------- -- module Text.CTK.Config (-- limits -- errorLimit, -- -- debuging -- assertEnabled) where -- compilation aborts with a fatal error, when the given number of errors -- has been raised (warnings do not count) -- errorLimit :: Int errorLimit = 20 -- specifies whether the internal consistency checks with `assert' should be -- made -- assertEnabled :: Bool assertEnabled = True
mwotton/ctkl
src/Text/CTK/Config.hs
Haskell
bsd-3-clause
1,591
module Protocol.PeerSpec (spec) where import Protocol.Peer -- import Protocol.Types import Test.Hspec import qualified Data.ByteString as B -- import qualified Data.ByteString.Char8 as B8 spec :: Spec spec = do describe "buildBitField" $ do it "should build bitfield" $ do -- 1100 1000 => buildBitField 5 [0, 1, 4] `shouldBe` B.pack [200] -- 0001 0100 0100 0000 => buildBitField 12 [3, 5, 9] `shouldBe` B.pack [20, 64]
artems/FlashBit
specs/Protocol/PeerSpec.hs
Haskell
bsd-3-clause
488
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-} {-| Binary instances for the core datatypes -} module Idris.Core.Binary where import Control.Applicative ((<*>), (<$>)) import Control.Monad (liftM2) import Control.DeepSeq (($!!)) import Data.Binary import Data.Vector.Binary import qualified Data.Text as T import qualified Data.Text.Encoding as E import Idris.Core.TT instance Binary ErrorReportPart where put (TextPart msg) = do putWord8 0 ; put msg put (NamePart n) = do putWord8 1 ; put n put (TermPart t) = do putWord8 2 ; put t put (SubReport ps) = do putWord8 3 ; put ps put (RawPart r) = do putWord8 4 ; put r get = do i <- getWord8 case i of 0 -> fmap TextPart get 1 -> fmap NamePart get 2 -> fmap TermPart get 3 -> fmap SubReport get 4 -> fmap RawPart get _ -> error "Corrupted binary data for ErrorReportPart" instance Binary Provenance where put ExpectedType = putWord8 0 put (SourceTerm t) = do putWord8 1 put t put InferredVal = putWord8 2 put GivenVal = putWord8 3 put (TooManyArgs t) = do putWord8 4 put t get = do i <- getWord8 case i of 0 -> return ExpectedType 1 -> do x1 <- get return (SourceTerm x1) 2 -> return InferredVal 3 -> return GivenVal 4 -> do x1 <- get return (TooManyArgs x1) _ -> error "Corrupted binary data for Provenance" instance Binary UConstraint where put (ULT x1 x2) = putWord8 0 >> put x1 >> put x2 put (ULE x1 x2) = putWord8 1 >> put x1 >> put x2 get = do i <- getWord8 case i of 0 -> ULT <$> get <*> get 1 -> ULE <$> get <*> get _ -> error "Corrupted binary data for UConstraint" instance Binary ConstraintFC where put (ConstraintFC x1 x2) = putWord8 0 >> put x1 >> put x2 get = do i <- getWord8 case i of 0 -> liftM2 ConstraintFC get get _ -> error "Corrupted binary data for ConstraintFC" instance Binary a => Binary (Err' a) where put (Msg str) = do putWord8 0 put str put (InternalMsg str) = do putWord8 1 put str put (CantUnify x y z e ctxt i) = do putWord8 2 put x put y put z put e put ctxt put i put (InfiniteUnify n t ctxt) = do putWord8 3 put n put t put ctxt put (CantConvert x y ctxt) = do putWord8 4 put x put y put ctxt put (CantSolveGoal x ctxt) = do putWord8 5 put x put ctxt put (UnifyScope n1 n2 x ctxt) = do putWord8 6 put n1 put n2 put x put ctxt put (CantInferType str) = do putWord8 7 put str put (NonFunctionType t1 t2) = do putWord8 8 put t1 put t2 put (NotEquality t1 t2) = do putWord8 9 put t1 put t2 put (TooManyArguments n) = do putWord8 10 put n put (CantIntroduce t) = do putWord8 11 put t put (NoSuchVariable n) = do putWord8 12 put n put (NoTypeDecl n) = do putWord8 13 put n put (NotInjective x y z) = do putWord8 14 put x put y put z put (CantResolve _ t) = do putWord8 15 put t put (CantResolveAlts ns) = do putWord8 16 put ns put (IncompleteTerm t) = do putWord8 17 put t put (UniverseError x1 x2 x3 x4 x5) = do putWord8 18 put x1 put x2 put x3 put x4 put x5 put (UniqueError u n) = do putWord8 19 put u put n put (UniqueKindError u n) = do putWord8 20 put u put n put ProgramLineComment = putWord8 21 put (Inaccessible n) = do putWord8 22 put n put (NonCollapsiblePostulate n) = do putWord8 23 put n put (AlreadyDefined n) = do putWord8 24 put n put (ProofSearchFail e) = do putWord8 25 put e put (NoRewriting t) = do putWord8 26 put t put (At fc e) = do putWord8 27 put fc put e put (Elaborating str n e) = do putWord8 28 put str put n put e put (ElaboratingArg n1 n2 ns e) = do putWord8 29 put n1 put n2 put ns put e put (ProviderError str) = do putWord8 30 put str put (LoadingFailed str e) = do putWord8 31 put str put e put (ReflectionError parts e) = do putWord8 32 put parts put e put (ReflectionFailed str e) = do putWord8 33 put str put e put (WithFnType t) = do putWord8 34 put t put (CantMatch t) = do putWord8 35 put t put (ElabScriptDebug x1 x2 x3) = do putWord8 36 put x1 put x2 put x3 put (NoEliminator s t) = do putWord8 37 put s put t put (InvalidTCArg n t) = do putWord8 38 put n put t put (ElabScriptStuck x1) = do putWord8 39 put x1 put (UnknownImplicit n f) = do putWord8 40 put n put f put (NoValidAlts ns) = do putWord8 41 put ns get = do i <- getWord8 case i of 0 -> fmap Msg get 1 -> fmap InternalMsg get 2 -> do x <- get ; y <- get ; z <- get ; e <- get ; ctxt <- get ; i <- get return $ CantUnify x y z e ctxt i 3 -> do x <- get ; y <- get ; z <- get return $ InfiniteUnify x y z 4 -> do x <- get ; y <- get ; z <- get return $ CantConvert x y z 5 -> do x <- get ; y <- get return $ CantSolveGoal x y 6 -> do w <- get ; x <- get ; y <- get ; z <- get return $ UnifyScope w x y z 7 -> fmap CantInferType get 8 -> do x <- get ; y <- get return $ NonFunctionType x y 9 -> do x <- get ; y <- get return $ NotEquality x y 10 -> fmap TooManyArguments get 11 -> fmap CantIntroduce get 12 -> fmap NoSuchVariable get 13 -> fmap NoTypeDecl get 14 -> do x <- get ; y <- get ; z <- get return $ NotInjective x y z 15 -> fmap (CantResolve False) get 16 -> fmap CantResolveAlts get 17 -> fmap IncompleteTerm get 18 -> UniverseError <$> get <*> get <*> get <*> get <*> get 19 -> do x <- get ; y <- get return $ UniqueError x y 20 -> do x <- get ; y <- get return $ UniqueKindError x y 21 -> return ProgramLineComment 22 -> fmap Inaccessible get 23 -> fmap NonCollapsiblePostulate get 24 -> fmap AlreadyDefined get 25 -> fmap ProofSearchFail get 26 -> fmap NoRewriting get 27 -> do x <- get ; y <- get return $ At x y 28 -> do x <- get ; y <- get ; z <- get return $ Elaborating x y z 29 -> do w <- get ; x <- get ; y <- get ; z <- get return $ ElaboratingArg w x y z 30 -> fmap ProviderError get 31 -> do x <- get ; y <- get return $ LoadingFailed x y 32 -> do x <- get ; y <- get return $ ReflectionError x y 33 -> do x <- get ; y <- get return $ ReflectionFailed x y 34 -> fmap WithFnType get 35 -> fmap CantMatch get 36 -> do x1 <- get x2 <- get x3 <- get return (ElabScriptDebug x1 x2 x3) 37 -> do x1 <- get x2 <- get return (NoEliminator x1 x2) 38 -> do x1 <- get x2 <- get return (InvalidTCArg x1 x2) 39 -> do x1 <- get return (ElabScriptStuck x1) 40 -> do x <- get ; y <- get return $ UnknownImplicit x y 41 -> fmap NoValidAlts get _ -> error "Corrupted binary data for Err'" ----- Generated by 'derive' instance Binary FC where put x = case x of (FC x1 (x2, x3) (x4, x5)) -> do putWord8 0 put x1 put (x2 * 65536 + x3) put (x4 * 65536 + x5) NoFC -> putWord8 1 FileFC x1 -> do putWord8 2 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get x2x3 <- get x4x5 <- get return (FC x1 (x2x3 `div` 65536, x2x3 `mod` 65536) (x4x5 `div` 65536, x4x5 `mod` 65536)) 1 -> return NoFC 2 -> do x1 <- get return (FileFC x1) _ -> error "Corrupted binary data for FC" instance Binary Name where put x = case x of UN x1 -> do putWord8 0 put x1 NS x1 x2 -> do putWord8 1 put x1 put x2 MN x1 x2 -> do putWord8 2 put x1 put x2 NErased -> putWord8 3 SN x1 -> do putWord8 4 put x1 SymRef x1 -> do putWord8 5 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (UN x1) 1 -> do x1 <- get x2 <- get return (NS x1 x2) 2 -> do x1 <- get x2 <- get return (MN x1 x2) 3 -> return NErased 4 -> do x1 <- get return (SN x1) 5 -> do x1 <- get return (SymRef x1) _ -> error "Corrupted binary data for Name" instance Binary SpecialName where put x = case x of WhereN x1 x2 x3 -> do putWord8 0 put x1 put x2 put x3 InstanceN x1 x2 -> do putWord8 1 put x1 put x2 ParentN x1 x2 -> do putWord8 2 put x1 put x2 MethodN x1 -> do putWord8 3 put x1 CaseN x1 -> do putWord8 4; put x1 ElimN x1 -> do putWord8 5; put x1 InstanceCtorN x1 -> do putWord8 6; put x1 WithN x1 x2 -> do putWord8 7 put x1 put x2 MetaN x1 x2 -> do putWord8 8 put x1 put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (WhereN x1 x2 x3) 1 -> do x1 <- get x2 <- get return (InstanceN x1 x2) 2 -> do x1 <- get x2 <- get return (ParentN x1 x2) 3 -> do x1 <- get return (MethodN x1) 4 -> do x1 <- get return (CaseN x1) 5 -> do x1 <- get return (ElimN x1) 6 -> do x1 <- get return (InstanceCtorN x1) 7 -> do x1 <- get x2 <- get return (WithN x1 x2) 8 -> do x1 <- get x2 <- get return (MetaN x1 x2) _ -> error "Corrupted binary data for SpecialName" instance Binary Const where put x = case x of I x1 -> do putWord8 0 put x1 BI x1 -> do putWord8 1 put x1 Fl x1 -> do putWord8 2 put x1 Ch x1 -> do putWord8 3 put x1 Str x1 -> do putWord8 4 put x1 B8 x1 -> putWord8 5 >> put x1 B16 x1 -> putWord8 6 >> put x1 B32 x1 -> putWord8 7 >> put x1 B64 x1 -> putWord8 8 >> put x1 (AType (ATInt ITNative)) -> putWord8 9 (AType (ATInt ITBig)) -> putWord8 10 (AType ATFloat) -> putWord8 11 (AType (ATInt ITChar)) -> putWord8 12 StrType -> putWord8 13 Forgot -> putWord8 15 (AType (ATInt (ITFixed ity))) -> putWord8 (fromIntegral (16 + fromEnum ity)) -- 16-19 inclusive VoidType -> putWord8 27 WorldType -> putWord8 28 TheWorld -> putWord8 29 get = do i <- getWord8 case i of 0 -> do x1 <- get return (I x1) 1 -> do x1 <- get return (BI x1) 2 -> do x1 <- get return (Fl x1) 3 -> do x1 <- get return (Ch x1) 4 -> do x1 <- get return (Str x1) 5 -> fmap B8 get 6 -> fmap B16 get 7 -> fmap B32 get 8 -> fmap B64 get 9 -> return (AType (ATInt ITNative)) 10 -> return (AType (ATInt ITBig)) 11 -> return (AType ATFloat) 12 -> return (AType (ATInt ITChar)) 13 -> return StrType 15 -> return Forgot 16 -> return (AType (ATInt (ITFixed IT8))) 17 -> return (AType (ATInt (ITFixed IT16))) 18 -> return (AType (ATInt (ITFixed IT32))) 19 -> return (AType (ATInt (ITFixed IT64))) 27 -> return VoidType 28 -> return WorldType 29 -> return TheWorld _ -> error "Corrupted binary data for Const" instance Binary Raw where put x = case x of Var x1 -> do putWord8 0 put x1 RBind x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 RApp x1 x2 -> do putWord8 2 put x1 put x2 RType -> putWord8 3 RConstant x1 -> do putWord8 4 put x1 RForce x1 -> do putWord8 5 put x1 RUType x1 -> do putWord8 6 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Var x1) 1 -> do x1 <- get x2 <- get x3 <- get return (RBind x1 x2 x3) 2 -> do x1 <- get x2 <- get return (RApp x1 x2) 3 -> return RType 4 -> do x1 <- get return (RConstant x1) 5 -> do x1 <- get return (RForce x1) 6 -> do x1 <- get return (RUType x1) _ -> error "Corrupted binary data for Raw" instance Binary ImplicitInfo where put x = case x of Impl x1 -> put x1 get = do x1 <- get return (Impl x1) instance (Binary b) => Binary (Binder b) where put x = case x of Lam x1 -> do putWord8 0 put x1 Pi x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 Let x1 x2 -> do putWord8 2 put x1 put x2 NLet x1 x2 -> do putWord8 3 put x1 put x2 Hole x1 -> do putWord8 4 put x1 GHole x1 x2 -> do putWord8 5 put x1 put x2 Guess x1 x2 -> do putWord8 6 put x1 put x2 PVar x1 -> do putWord8 7 put x1 PVTy x1 -> do putWord8 8 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Lam x1) 1 -> do x1 <- get x2 <- get x3 <- get return (Pi x1 x2 x3) 2 -> do x1 <- get x2 <- get return (Let x1 x2) 3 -> do x1 <- get x2 <- get return (NLet x1 x2) 4 -> do x1 <- get return (Hole x1) 5 -> do x1 <- get x2 <- get return (GHole x1 x2) 6 -> do x1 <- get x2 <- get return (Guess x1 x2) 7 -> do x1 <- get return (PVar x1) 8 -> do x1 <- get return (PVTy x1) _ -> error "Corrupted binary data for Binder" instance Binary Universe where put x = case x of UniqueType -> putWord8 0 AllTypes -> putWord8 1 NullType -> putWord8 2 get = do i <- getWord8 case i of 0 -> return UniqueType 1 -> return AllTypes 2 -> return NullType _ -> error "Corrupted binary data for Universe" instance Binary NameType where put x = case x of Bound -> putWord8 0 Ref -> putWord8 1 DCon x1 x2 x3 -> do putWord8 2 put (x1 * 65536 + x2) put x3 TCon x1 x2 -> do putWord8 3 put (x1 * 65536 + x2) get = do i <- getWord8 case i of 0 -> return Bound 1 -> return Ref 2 -> do x1x2 <- get x3 <- get return (DCon (x1x2 `div` 65536) (x1x2 `mod` 65536) x3) 3 -> do x1x2 <- get return (TCon (x1x2 `div` 65536) (x1x2 `mod` 65536)) _ -> error "Corrupted binary data for NameType" -- record concrete levels only, for now instance Binary UExp where put x = case x of UVar t -> do putWord8 0 put ((-1) :: Int) -- TMP HACK! UVal t -> do putWord8 1 put t get = do i <- getWord8 case i of 0 -> do x1 <- get return (UVar x1) 1 -> do x1 <- get return (UVal x1) _ -> error "Corrupted binary data for UExp" instance {- (Binary n) => -} Binary (TT Name) where put x = {-# SCC "putTT" #-} case x of P x1 x2 x3 -> do putWord8 0 put x1 put x2 -- put x3 V x1 -> if (x1 >= 0 && x1 < 256) then do putWord8 1 putWord8 (toEnum (x1 + 1)) else do putWord8 9 put x1 Bind x1 x2 x3 -> do putWord8 2 put x1 put x2 put x3 App _ x1 x2 -> do putWord8 3 put x1 put x2 Constant x1 -> do putWord8 4 put x1 Proj x1 x2 -> do putWord8 5 put x1 putWord8 (toEnum (x2 + 1)) Erased -> putWord8 6 TType x1 -> do putWord8 7 put x1 Impossible -> putWord8 8 UType x1 -> do putWord8 10 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get -- x3 <- get return (P x1 x2 Erased) 1 -> do x1 <- getWord8 return (V ((fromEnum x1) - 1)) 2 -> do x1 <- get x2 <- get x3 <- get return (Bind x1 x2 x3) 3 -> do x1 <- get x2 <- get return (App Complete x1 x2) 4 -> do x1 <- get return (Constant x1) 5 -> do x1 <- get x2 <- getWord8 return (Proj x1 ((fromEnum x2)-1)) 6 -> return Erased 7 -> do x1 <- get return (TType x1) 8 -> return Impossible 9 -> do x1 <- get return (V x1) 10 -> do x1 <- get return (UType x1) _ -> error "Corrupted binary data for TT"
athanclark/Idris-dev
src/Idris/Core/Binary.hs
Haskell
bsd-3-clause
25,274
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.ARB.VertexAttribBinding -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/ARB/vertex_attrib_binding.txt ARB_vertex_attrib_binding> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.ARB.VertexAttribBinding ( -- * Enums gl_MAX_VERTEX_ATTRIB_BINDINGS, gl_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET, gl_VERTEX_ATTRIB_BINDING, gl_VERTEX_ATTRIB_RELATIVE_OFFSET, gl_VERTEX_BINDING_DIVISOR, gl_VERTEX_BINDING_OFFSET, gl_VERTEX_BINDING_STRIDE, -- * Functions glBindVertexBuffer, glVertexAttribBinding, glVertexAttribFormat, glVertexAttribIFormat, glVertexAttribLFormat, glVertexBindingDivisor ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/ARB/VertexAttribBinding.hs
Haskell
bsd-3-clause
1,088
{-# LANGUAGE ViewPatterns, PatternGuards, TupleSections #-} module Input.Set(setStackage, setPlatform, setGHC) where import Control.Applicative import Data.List.Extra setStackage :: IO [String] setStackage = f . lines <$> readFile "input/stackage.txt" where f (x:xs) | Just x <- stripPrefix "constraints:" x = map (fst . word1) $ takeWhile (" " `isPrefixOf`) $ (' ':x) : xs | otherwise = f xs f [] = [] setPlatform :: IO [String] setPlatform = setPlatformWith ["incGHCLib","incLib"] setPlatformWith :: [String] -> IO [String] setPlatformWith names = do src <- lines <$> readFile "input/platform.txt" return [read lib | ",":name:lib:_ <- map words src, name `elem` names] setGHC :: IO [String] setGHC = setPlatformWith ["incGHCLib"]
ndmitchell/hogle-dead
src/Input/Set.hs
Haskell
bsd-3-clause
805
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Dense.TH -- Copyright : (c) Christopher Chalmers -- License : BSD3 -- -- Maintainer : Christopher Chalmers -- Stability : experimental -- Portability : non-portable -- -- Contains QuasiQuotes and TemplateHaskell utilities for creating dense -- arrays, stencils and fixed length vectors. -- -- The parser for the QuasiQuotes is still a work in progress. ----------------------------------------------------------------------------- module Data.Dense.TH ( -- * Creating dense arrays dense -- * Fixed length vector , v -- * Stencils , stencil -- ** Stencils from lists , ShapeLift (..) , mkStencilTH , mkStencilTHBy ) where import Control.Applicative hiding (many, empty) import Control.Lens import Control.Monad import Data.Char import Data.Foldable as F import Data.Function (on) import qualified Data.List as List import Data.Maybe import Data.Monoid (Endo) import qualified Data.Vector as Vector import Language.Haskell.TH import Language.Haskell.TH.Quote import Language.Haskell.TH.Syntax import Linear import qualified Linear.V as V import Text.ParserCombinators.ReadP import qualified Text.Read.Lex as Lex import Data.Dense.Generic (empty, fromListInto_) import Data.Dense.Index import Data.Dense.Stencil tupe :: [Exp] -> Exp #if __GLASGOW_HASKELL__ <= 808 tupe = TupE #else tupe = TupE . map Just #endif -- | QuasiQuoter for producing a dense arrays using a custom parser. -- Values are space separated, while also allowing infix expressions -- (like @5/7@). If you want to apply a function, it should be done in -- brackets. Supports 1D, 2D and 3D arrays. -- -- The number of rows/columns must be consistent thought out the -- array. -- -- === __Examples__ -- -- - 1D arrays are of the following form form. Note these can be -- used as 'V1', 'V2' or 'V3' arrays. -- -- @ -- ['dense'| 5 -3 1 -3 5 |] :: ('R1' f, 'Vector.Vector' v a, 'Num' a) => 'Data.Dense.Array' v f a -- @ -- -- -- - 2D arrays are of the following form. Note these can be used as -- 'V2' or 'V3' arrays. -- -- @ -- chars :: 'Data.Dense.UArray' 'V2' 'Char' -- chars :: ['dense'| -- \'a\' \'b\' \'c\' -- \'d\' \'e\' \'f\' -- \'g\' \'h\' \'i\' -- |] -- @ -- -- - 3D arrays are of the following form. Note the order in which -- 'dense' formats the array. The array @a@ is such that @a ! 'V3' -- x y z = "xyz"@ -- -- @ -- a :: 'Data.Dense.BArray' 'V3' 'String' -- a = ['dense'| -- "000" "100" "200" -- "010" "110" "210" -- "020" "120" "220" -- -- "001" "101" "201" -- "011" "111" "211" -- "021" "121" "221" -- -- "002" "102" "202" -- "012" "112" "212" -- "022" "122" "222" -- |] -- @ -- dense :: QuasiQuoter dense = QuasiQuoter { quoteExp = parseDense , quotePat = error "dense can't be used in pattern" , quoteType = error "dense can't be used in type" , quoteDec = error "dense can't be used in dec" } -- | List of expressions forming a stencil. To be either turned into -- either a real list or an unfolded stencil. parseDense :: String -> Q Exp parseDense str = case mapM (mapM parseLine) (map lines ps) of Left err -> fail err Right [] -> [| empty |] Right [[as]] -> uncurry mkArray $ parse1D as Right [ass] -> uncurry mkArray $ parse2D ass Right asss -> uncurry mkArray $ parse3D asss where ps = paragraphs str -- | Split a string up into paragraphs separated by a new line. Extra -- newlines inbetween paragraphs are stripped. paragraphs :: String -> [String] paragraphs = go [] . strip where go ps ('\n':'\n':xs) = [reverse ps] ++ go [] (strip xs) go ps (x:xs) = go (x:ps) xs go [] [] = [] go ps [] = [reverse $ strip ps] strip = dropWhile (\x -> x == '\n' || x == ' ') -- Creating arrays ----------------------------------------------------- mkArray :: ShapeLift f => Layout f -> [Exp] -> Q Exp mkArray l as = do lE <- liftShape' l let fromListE = AppE (VarE 'fromListInto_) lE pure $ AppE fromListE (ListE as) ------------------------------------------------------------------------ -- V n a ------------------------------------------------------------------------ -- | Type safe 'QuasiQuoter' for fixed length vectors 'V.V'. Values are -- space separated. Can be used as expressions or patterns. -- -- @ -- [v| x y z w q r |] :: 'V.V' 6 a -- @ -- -- Note this requires @DataKinds@. Also requires @ViewPatterns@ if 'v' -- is used as a pattern. -- -- === __Examples__ -- -- @ -- >>> let a = [v| 1 2 3 4 5 |] -- >>> :t a -- a :: Num a => V 5 a -- >>> a -- V {toVector = [1,2,3,4,5]} -- >>> let f [v| a b c d e |] = (a,b,c,d,e) -- >>> :t f -- f :: V 5 t -> (t, t, t, t, t) -- >>> f a -- (1,2,3,4,5) -- @ -- -- Variables and infix expressions are also allowed. Negative values can -- be expressed by a leading @-@ with a space before but no space -- after. -- -- @ -- >>> let b x = [v| 1\/x 2 \/ x (succ x)**2 x-2 x - 3 -x |] -- >>> b Debug.SimpleReflect.a -- V {toVector = [1 \/ a,2 \/ a,succ a**2,a - 2,a - 3,negate a]} -- @ v :: QuasiQuoter v = QuasiQuoter { quoteExp = parseV , quotePat = patternV , quoteType = error "v can't be used as type" , quoteDec = error "v can't be used as dec" } parseV :: String -> Q Exp parseV s = case parseLine s of Right as -> let e = pure $ ListE as n = pure . LitT $ NumTyLit (toInteger $ length as) in [| (V.V :: Vector.Vector a -> V.V $n a) (Vector.fromList $e) |] Left err -> fail $ "v: " ++ err ------------------------------------------------------------------------ -- Stencils ------------------------------------------------------------------------ parseStencilLine :: String -> Either String [Maybe Exp] parseStencilLine s = case List.sortBy (compare `on` (length . snd)) rs of (xs,"") : _ -> Right xs (_ , x) : _ -> Left $ "parse error on input " ++ head (words x) _ -> Left "no parse" where rs = readP_to_S (many $ mExp <* skipSpaces) s mExp = fmap Just noAppExpression <|> skip skip = do Lex.Ident "_" <- Lex.lex pure Nothing -- | List of expressions forming a stencil. To be either turned into -- either a real list or an unfolded stencil. parseStencil :: String -> Q Exp parseStencil str = case mapM (mapM parseStencilLine) (map lines ps) of Left err -> fail err Right [] -> [| mkStencil [] |] Right [[as]] -> uncurry mkStencilE $ parse1D as Right [ass] -> uncurry mkStencilE $ parse2D ass Right asss -> uncurry mkStencilE $ parse3D asss where ps = paragraphs str mkStencilE :: ShapeLift f => Layout f -> [Maybe Exp] -> Q Exp mkStencilE l as = do when (F.any even l) $ reportWarning "stencil has an even size in some dimension, the centre element may be incorrect" let ixes = map (^-^ fmap (`div` 2) l) (toListOf shapeIndexes l) -- indexes zipped with expressions, discarding 'Nothing's xs = mapMaybe (sequenceOf _2) (zip ixes as) mkStencilTHBy pure xs -- | QuasiQuoter for producing a static stencil definition. This is a -- versatile parser for 1D, 2D and 3D stencils. The parsing is similar -- to 'dense' but 'stencil' also supports @_@, which means ignore this -- element. Also, stencils should have an odd length in all dimensions -- so there is always a center element (which is used as 'zero'). -- -- === __Examples__ -- -- - 1D stencils are of the form -- -- @ -- ['stencil'| 5 -3 1 -3 5 |] :: 'Num' a => 'Stencil' 'V1' a -- @ -- -- - 2D stencils are of the form -- -- @ -- myStencil2 :: 'Num' a => 'Stencil' 'V2' a -- myStencil2 = ['stencil'| -- 0 1 0 -- 1 0 1 -- 0 1 0 -- |] -- @ -- -- - 3D stencils have gaps between planes. -- -- @ -- myStencil3 :: 'Fractional' a => 'Stencil' 'V3' a -- myStencil3 :: ['stencil'| -- 1\/20 3\/10 1\/20 -- 3\/10 1 3\/10 -- 1\/20 3\/10 1\/20 -- -- 3\/10 1 3\/10 -- 1 _ 1 -- 3\/10 1 3\/10 -- -- 1\/20 3\/10 1\/20 -- 3\/10 1 3\/10 -- 1\/20 3\/10 1\/20 -- |] -- @ -- -- Variables can also be used -- -- @ -- myStencil2' :: a -> a -> a -> 'Stencil' 'V2' a -- myStencil2' a b c = ['stencil'| -- c b c -- b a b -- c b c -- |] -- @ -- -- stencil :: QuasiQuoter stencil = QuasiQuoter { quoteExp = parseStencil , quotePat = error "stencil can't be used in pattern" , quoteType = error "stencil can't be used in type" , quoteDec = error "stencil can't be used in dec" } -- | Construct a 'Stencil' by unrolling the list at compile time. For -- example -- -- @ -- 'ifoldr' f b $('mkStencilTH' [('V1' (-1), 5), ('V1' 0, 3), ('V1' 1, 5)]) -- @ -- -- will be get turned into -- -- @ -- f ('V1' (-1)) 5 (f ('V1' 0) 3 (f ('V1' 1) 5 b)) -- @ -- -- at compile time. Since there are no loops and all target indexes -- are known at compile time, this can lead to more optimisations and -- faster execution times. This can lead to around a 2x speed up -- compared to folding over unboxed vectors. -- -- @ -- myStencil = $('mkStencilTH' (as :: [(f 'Int', a)])) :: 'Stencil' f a -- @ mkStencilTH :: (ShapeLift f, Lift a) => [(f Int, a)] -> Q Exp mkStencilTH = mkStencilTHBy lift -- | 'mkStencilTH' with a custom 'lift' function for @a@. mkStencilTHBy :: ShapeLift f => (a -> Q Exp) -> [(f Int, a)] -> Q Exp mkStencilTHBy aLift as = do -- See Note [mkName-capturing] f <- newName "mkStencilTHBy_f" b <- newName "mkStencilTHBy_b" let appF (i,a) e = do iE <- liftShape' i aE <- aLift a pure $ AppE (AppE (AppE (VarE f) iE) aE) e e <- foldrM appF (VarE b) as pure $ AppE (ConE 'Stencil) (LamE [VarP f,VarP b] e) {- ~~~~ Note [mkName-capturing] Since 'newName' will capture any other names below it with the same name. So if we simply used @newName "b"@, [stencil| a b c |] where a=1; b=2; c=3 would convert @b@ to @b_a5y0@ (or w/e the top level b is) and fail. To prevent this I've used a name that's unlikely conflict. Another solution would be to use lookupValueName on all variables. But this would either require traversing over all 'Name's in every 'Exp' (shown below) or parse in the Q monad. -- | Lookup and replace all names made with 'mkName' using -- 'lookupValueName'; failing if not in scope. replaceMkName :: Exp -> Q Exp replaceMkName = template f where f (Name (OccName s) NameS) = lookupValueName s >>= \case Just nm -> pure nm -- Sometimes a variable may not be in scope yet because it's -- generated in a TH splice that hasn't been run yet. Nothing -> fail $ "Not in scope: ‘" ++ s ++ "’" f nm = pure nm -} ------------------------------------------------------------------------ -- Parsing expressions ------------------------------------------------------------------------ parseLine :: String -> Either String [Exp] parseLine s = case List.sortBy (compare `on` (length . snd)) rs of (xs,"") : _ -> Right xs (_ , x) : _ -> Left $ "parse error on input " ++ head (words x) _ -> Left "no parse" where rs = readP_to_S (many noAppExpression <* skipSpaces) s -- | Fail the parser if the next non-space is a @-@ directly followed by -- a non-space. closeNegateFail :: ReadP () closeNegateFail = do s <- look case s of ' ' : s' -> case dropWhile isSpace s' of '-' : c : _ -> if isSpace c then pure () else pfail _ -> pure () _ -> pure () -- | If there is a space before but not after a @-@, it is treated as a -- separate expression. -- -- @ -- "1 2 -3 4" -> [1, 2, -3, 4] -- "1 2 - 3 4" -> [1, -1, 4] -- "1 2-3 4" -> [1, -1, 4] -- "11 -3/2 -3/2 4" -> [1, -1, 4] -- "1 -3/2 4" -> [1.0,-1.5,4.0] -- @ noAppExpression :: ReadP Exp noAppExpression = do aE <- anExpr True option aE $ do closeNegateFail i <- infixExp bE <- noAppExpression pure $ UInfixE aE i bE -- | Parse an express without any top level application. Infix functions -- are still permitted. -- -- This is only a small subset of the full haskell syntax. The -- following syntax is supported: -- -- - Variables/constructors: @a@, @'Just'@ etc. -- - Numbers: @3@, @-6@, @7.8@, @1e-6@, @0x583fa@ -- - Parenthesis/tuples: @()@ @(f a)@, @(a,b)@ -- - Lists -- - Strings -- - Function application -- - Infix operators: symbols (@+@, @/@ etc.) and blackticked (like @`mod`@) -- -- More advanced haskell syntax are not yet supported: -- -- - let bindings -- - lambdas -- - partial infix application (+) (1+) (+2) -- - type signatures -- - comments -- -- This could be replaced by haskell-src-meta but since I want a -- custom parser for 'noAppExpression' it doesn't seem worth the extra -- dependencies. expression :: ReadP Exp expression = do f <- anExpr True args <- many (anExpr False) let aE = F.foldl AppE f args option aE $ do -- if the next lex isn't a symbol, we move on to the next statement i <- infixExp bE <- expression pure $ UInfixE aE i bE -- | Parse an infix expression. Either a symbol or a name wrapped in @`@. infixExp :: ReadP Exp infixExp = do a <- Lex.lex case a of Lex.Symbol s -> pure $ symbol s Lex.Punc "`" -> do Lex.Ident x <- Lex.lex Lex.Punc "`" <- Lex.lex ident x _ -> pfail -- Lexing -------------------------------------------------------------- -- | Parse a single expression. anExpr :: Bool -- ^ Allow a leading @-@ to mean 'negate' -> ReadP Exp anExpr new = do a <- Lex.lex case a of Lex.Char c -> pure $ LitE (CharL c) Lex.String s -> pure $ LitE (StringL s) Lex.Punc s -> punc s Lex.Ident s -> ident s Lex.Symbol s -> if new then prefix s else pfail Lex.Number n -> pure $ LitE (number n) Lex.EOF -> pfail -- | Convert a name to an expression. ident :: String -> ReadP Exp ident "_" = pfail ident s@(x:_) | isUpper x = pure $ ConE (mkName s) ident s = pure $ VarE (mkName s) -- | Convert a symbol to an expression. symbol :: String -> Exp symbol s@(':':_) = ConE (mkName s) symbol s = VarE (mkName s) -- | Parse from some punctuation. punc :: String -> ReadP Exp punc = \case -- parenthesis / tuples "(" -> do as <- expression `sepBy` comma Lex.Punc ")" <- Lex.lex pure $ tupe as -- lists "[" -> do as <- expression `sepBy` comma Lex.Punc "]" <- Lex.lex pure $ ListE as _ -> pfail prefix :: String -> ReadP Exp prefix "-" = do e <- anExpr False pure $ AppE (VarE 'negate) e prefix _ = pfail comma :: ReadP () comma = do Lex.Punc "," <- Lex.lex pure () -- | Turn a 'Number' into a literal 'Integer' if possible, otherwise -- make a literal `Rational`. number :: Lex.Number -> Lit number n = maybe (RationalL $ Lex.numberToRational n) IntegerL (Lex.numberToInteger n) ------------------------------------------------------------------------ -- Parsing patterns ------------------------------------------------------------------------ patternV :: String -> Q Pat patternV s = do case parsePattern s of Left err -> fail err Right pats -> do fE <- vTuple (length pats) pure $ ViewP fE (TupP pats) parsePattern :: String -> Either String [Pat] parsePattern s = case List.sortBy (compare `on` (length . snd)) rs of (xs,"") : _ -> Right xs (_ , x) : _ -> Left $ "parse error on input " ++ head (words x) _ -> Left "no parse" where rs = readP_to_S (many pattern <* skipSpaces) s pattern :: ReadP Pat pattern = do a <- Lex.lex case a of Lex.Char c -> pure $ LitP (CharL c) Lex.String s -> pure $ LitP (StringL s) Lex.Punc s -> puncP s Lex.Ident n -> pure $ identP n Lex.Symbol s -> prefixP s Lex.Number n -> pure $ LitP (number n) Lex.EOF -> pfail -- | Convert a name to an expression. identP :: String -> Pat identP "_" = WildP identP s@(x:_) | isUpper x = ConP (mkName s) [] identP s = VarP (mkName s) -- | Parse from some punctuation. puncP :: String -> ReadP Pat puncP = \case "~" -> TildeP <$> pattern "(" -> do as <- pattern `sepBy` comma Lex.Punc ")" <- Lex.lex pure $ TupP as "[" -> do as <- pattern `sepBy` comma Lex.Punc "]" <- Lex.lex pure $ ListP as _ -> pfail prefixP :: String -> ReadP Pat prefixP "!" = do c:_ <- look when (isSpace c) pfail BangP <$> pattern prefixP "~" = TildeP <$> pattern prefixP _ = pfail -- | Create an expression for converting a (V n a) to an n-tuple. vTuple :: Int -> Q Exp vTuple n | n > 62 = error "max supported length is 62 for v pattern" | otherwise = do vN <- newName "v" let idx i = AppE (AppE (VarE 'Vector.unsafeIndex) (VarE vN)) (intE i) let xs = tupe $ map idx [0..n-1] a <- newName "a" let tup = iterate (\x -> AppT x (VarT a)) (TupleT n) !! n typ = ForallT [PlainTV a] [] (AppT (AppT ArrowT (AppT (AppT (ConT ''V.V) (intT n)) (VarT a))) tup) [| (\(V.V $(pure $ VarP vN)) -> $(pure xs)) :: $(pure typ) |] where intE = LitE . IntegerL . toInteger intT = LitT . NumTyLit . toInteger -- Parsing specific dimensions ----------------------------------------- -- | Parse a 1D list. If the system is not valid, return a string -- with error message. parse1D :: [a] -> (V1 Int, [a]) parse1D as = (V1 x, as) where x = length as -- | Parse a 2D list of lists. If the system is not valid, returns an -- error parse2D :: [[a]] -> (V2 Int, [a]) parse2D as | Just e <- badX = error ("parse2D: " ++ errMsg e) | otherwise = (V2 x y, F.concat $ List.transpose as) where x = head xs y = length as xs = map length as badX = ifind (const (/= x)) xs errMsg (i,j) = "row " ++ show i ++ " has " ++ show j ++ " columns but the first" ++ " row has " ++ show x ++ " columns" -- | Parse a 3D list of list of lists. If the system is not valid, -- return a string with error message. -- -- The element are reordered in the appropriate way for the array: -- -- @ -- >>> parse3D [["abc","def","ghi"],["jkl","mno","pqr"],["stu","vwx","yz!"]] -- ((V3 3 3 3), "ajsdmvgpybktenwhqzclufoxir!") -- @ -- parse3D :: [[[a]]] -> (V3 Int, [a]) parse3D as | nullOf (each.each.each) as = (zero, []) | Just e <- badX = error $ errorCol e | Just e <- badY = error $ errorRow e | otherwise = (V3 x y z, as') where z = length as y = length (head as) x = length (head (head as)) -- reorder and concatenate so it's the correct order for the array as' = F.concatMap F.concat (List.transpose $ map List.transpose $ List.transpose as) -- check for inconsistencies badY = ifind (const (/= y)) (map length as) badX = ifindOf' (traversed <.> traversed <. to length) (const (/= x)) as -- error messages for inconsistent rows/columns errorCol ((k,j),i) = "plane " ++ show k ++ ", row " ++ show j ++ " has " ++ show i ++ " columns" ++ ", but the first row has " ++ show x ++ " columns" errorRow (k,j) = "plane " ++ show k ++ " has " ++ show j ++ " rows but the first" ++ " plane has " ++ show x ++ " rows" -- | Version of ifindOf which is consistent with ifind (in that it also returns the index). ifindOf' :: IndexedGetting i (Endo (Maybe (i, a))) s a -> (i -> a -> Bool) -> s -> Maybe (i, a) ifindOf' l p = ifoldrOf l (\i a y -> if p i a then Just (i, a) else y) Nothing {-# INLINE ifindOf' #-} -- Shape lift class ---------------------------------------------------- -- | Class of shapes that can be 'lift'ed. -- -- This is to prevent orphans for the 'Lift' class. class Shape f => ShapeLift f where -- | 'lift' for 'Shape's. liftShape :: Lift a => f a -> Q Exp -- | Polymorphic 'lift' for a 'Shape's. liftShape' :: Lift a => f a -> Q Exp instance ShapeLift V1 where liftShape (V1 x) = [| V1 x |] liftShape' (V1 x) = [| v1 x |] instance ShapeLift V2 where liftShape (V2 x y) = [| V2 x y |] liftShape' (V2 x y) = [| v2 x y |] instance ShapeLift V3 where liftShape (V3 x y z) = [| V3 x y z |] liftShape' (V3 x y z) = [| v3 x y z |] instance ShapeLift V4 where liftShape (V4 x y z w) = [| V4 x y z w |] liftShape' (V4 x y z w) = [| v4 x y z w |] v1 :: (R1 f, Shape f, Num a) => a -> f a v1 x = set _x x one {-# INLINE [0] v1 #-} v2 :: (R2 f, Shape f, Num a) => a -> a -> f a v2 x y = set _xy (V2 x y) one {-# INLINE [0] v2 #-} v3 :: (R3 f, Shape f, Num a) => a -> a -> a -> f a v3 x y z = set _xyz (V3 x y z) one {-# INLINE [0] v3 #-} v4 :: (R4 f, Shape f, Num a) => a -> a -> a -> a -> f a v4 x y z w = set _xyzw (V4 x y z w) one {-# INLINE [0] v4 #-} one :: (Shape f, Num a) => f a one = 1 <$ (zero :: Additive f => f Int) -- are these nessesary? {-# RULES "v1/V1" v1 = V1; "v1/V2" forall a. v1 a = V2 a 1; "v1/V3" forall a. v1 a = V3 a 1 1; "v2/V2" v2 = V2; "v2/V3" forall a b. v2 a b = V3 a b 1; "v3/V3" v3 = V3; "v4/V4" v4 = V4 #-}
cchalmers/dense
src/Data/Dense/TH.hs
Haskell
bsd-3-clause
21,747
import Data.List (unfoldr, reverse) import Data.Char (chr, ord) decToBin :: Int -> String decToBin x = reverse $ unfoldr helper x where helper 0 = Nothing helper x = Just (chr ((ord '0') + (x `mod` 2)), x `div` 2) palindromic xs = xs == reverse xs main = print $ sum $ [ x | x <- [1 .. 999999], palindromic (show x), palindromic (decToBin x) ]
foreverbell/project-euler-solutions
src/36.hs
Haskell
bsd-3-clause
355
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module Main (main) where import Client.Connection import Control.Concurrent (forkIO, threadDelay) import Control.Concurrent.MVar (newEmptyMVar, takeMVar, putMVar, MVar) import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TChan (newTChan, readTChan) import Control.Concurrent.STM.TVar (newTVar, readTVar, writeTVar) import Control.Monad (when, forever) import Data.Binary import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 (putStrLn, getLine, pack, dropWhile, words, getLine) import qualified Data.ByteString.Lazy as L (toStrict, fromStrict, null, hGetContents) import Data.CertificateStore import Data.Char (isSpace) import qualified Data.Map as Map (empty) import Data.Maybe (fromMaybe, fromJust, isNothing) import Data.Monoid ((<>)) import Network.Simple.TCP.TLS import Network.TLS import Network.TLS.Extra (fileReadPrivateKey, fileReadCertificate) import System.Certificate.X509.Unix import System.Console.Haskeline (runInputT, getPassword, defaultSettings) import System.Environment (getArgs) import System.IO (hSetBuffering, BufferMode(..), IOMode(..), stdout, withFile) import Tools import Types import System.Exit (exitFailure) {- | hpt main function. Start the client and the server parts of hpt. -} main :: IO () main = getArgs >>= go where -- long options go ("--version":_) = putStrLn version go ("--help":_) = putStrLn usage go ("--start":hostname:_) = hpt hostname -- short options go ("-v":_) = go ["--version"] go ("-h":_) = go ["--help"] go ("-s":hostname:_) = go ["--start", hostname] go _ = putStrLn ("Wrong argument.\n" ++ usage) -- | Start client and server parts hpt :: String -> IO () hpt hostname = withSocketsDo $ do -- Construct credential information putStr "Loading certificate..." certificate <- fileReadCertificate "/home/nschoe/.hpt-dispatcher/cacert.pem" success "success\n" -- Get certificate store putStr "Getting client's system certificate store..." cStore <- getSystemCertificateStore success "success\n" -- TEMPORARY -- Create artificial certificate store to recognize dispatcher's certificate let certificateStore = makeCertificateStore [certificate] -- Create client SSL settings putStr "Creating client SSL settings..." let clientSettings = makeClientSettings [] (Just hostname) (certificateStore <> cStore) success "success.\n" -- Create internal state putStr "Initializing internal state..." conversations <- atomically $ newTVar (Map.empty) contactList <- atomically $ newTVar [] chanCommands <- atomically $ newTChan currentChat <- atomically $ newTVar Nothing contactListDb <- atomically $ newTVar "" let state = ClientState { csConversations = conversations , csContactList = contactList , csCommands = chanCommands , csCurrentChat = currentChat , csContactListDb = contactListDb } success "success\n" -- Connecting to the dispatcher hSetBuffering stdout NoBuffering -- for the output to appear in the correct order authSuccess <- newEmptyMVar -- create sync mvar : will be put to True when 'connect' successfully authenticated putStr "Connecting to dispatcher..." talkDispatcher_tId <- forkIO $ connect clientSettings hostname port (talkDispatcher state authSuccess) isAuthSuccessful <- takeMVar authSuccess -- When we successfully reached the Dispatcher and logged in, continue when isAuthSuccessful $ loop state -- Exit when auth was not successfull putStrLn "Authentification was not successful" putStrLn "\nClient exiting.\n" where loop state = do -- ask for a command putStr "Input command (try '/help') : " cmd <- (words . dropWhile isSpace) `fmap` getLine -- just remove leading spaces -- parse command case cmd of ("/help":_) -> do putStrLn ("Must display help") ("/list":_) -> do contactList <- atomically $ readTVar (csContactList state) let output1 = "\nContact list (" ++ show (length contactList) ++ " contacts) : [unread messages]\n" let output2 = output1 ++ (replicate (length output1 - 2) '=') ++ "\n" let list = map ((++ " [not implemented]") . contactUserName) contactList let output = output2 ++ (unlines list) putStrLn output loop state ("/start":who:_) -> do putStrLn ("Must start conversation with " ++ who) loop state ("/stop":"all":_) -> do putStrLn ("Must stop all conversations") loop state ("/stop":who:_) -> do putStrLn ("Must stop conversation with " ++ who) loop state ("/ping":who:_) -> do putStrLn ("Must ping " ++ who) loop state ("/add":who:_) -> do contactList <- atomically $ readTVar (csContactList state) let mContact = contactLookup who contactList if (isNothing mContact) then do -- create "empty" contact to be filled by the next Alive request let newContact = Contact { contactUserName = who , contactStatus = NotAvailable , contactIpAddr = "" } atomically $ writeTVar (csContactList state) (newContact : contactList) -- save contact list to file _ <- forkIO $ saveContactList state (newContact : contactList) putStrLn (who ++ " was added to contact list.") else putStrLn (who ++ " is already is your contact list !") loop state ("/del":who:_) -> do contactList <- atomically $ readTVar (csContactList state) let mContact = contactLookup who contactList if (isNothing mContact) then putStrLn (who ++ " is not in your contact list !") else do let newContactList = filter ((/= who) . contactUserName) contactList atomically $ writeTVar (csContactList state) newContactList _ <- forkIO $ saveContactList state newContactList putStrLn (who ++ " has been removed from your contact list !") loop state ("/switchto":who:_) -> do putStrLn ("Must switch active conversation to : " ++ who) loop state ("/quit":_) -> do putStrLn ("Must quit") loop state (('/':cmd'):_) -> do putStrLn ("Unknow command : \"/" ++ cmd' ++ "\"") loop state _ -> do putStrLn ("Must write message (check active conversation first) : " ++ unwords cmd) loop state talkDispatcher :: ClientState -> MVar Bool -> (Context, SockAddr) -> IO () talkDispatcher state authSuccess (context, servaddr) = do success "success\n\n" -- Sending Born request putStr "Please identify.\nUsername : " username <- getLine password <- (B8.pack . fromMaybe "") `fmap` runInputT defaultSettings (getPassword Nothing "Password : ") -- Parse contact list putStr "Reading contact list..." db <- getContactListDb username contactListDb <- case db of Left err -> do failed ("failed\n" ++ err ++ "\n") exitFailure Right file -> return file success "success\n" -- Creating contact list from file putStr "Building contact list..." raw <- withFile contactListDb ReadMode $ \h -> do !contents <- L.hGetContents h return contents let list = case L.null raw of True -> [] False -> decode raw :: ContactList -- Modifying state to take contact list into account atomically $ do writeTVar (csContactList state) list writeTVar (csContactListDb state) contactListDb success "success\n" putStrLn "\nIdentifying to dispatcher..." send context (L.toStrict $ encode (Born username password)) -- Parsing dispatcher's answer mbs <- recv context case mbs of Nothing -> failed "Lost contact with server.\n" Just bs -> do let answer = decode (L.fromStrict bs) :: DispatcherAnswer case answer of -- Auth was okay BornOK str -> -- Print success message do success "Identification successful.\n" when (not $ isNothing str) (putStrLn ("Dispatcher notice : " ++ fromJust str)) success "You are now connected !\n" -- Put sync variable to True so that 'main' can start listening on user's input putMVar authSuccess True -- fork thread to keep alive putStr "Starting keep-alive routine..." keepAlive_tId <- forkIO $ do threadDelay ((10^6) :: Int) forever $ do keepAlive context state threadDelay ((9 * 10^6) :: Int) success "success\n" -- loop to handle client's input (e.g. log out requests) loop state context -- Auth failed BornKO str -> do failed "Identification failed " when (not $ isNothing str) (putStrLn (": " ++ fromJust str)) putMVar authSuccess False -- put sync to False so the 'main' knows not to listen to user's input _ -> error "Error : disptacher returned wrong type of answer\n" where loop state context = do -- parse commands to send to the dispatcher command <- atomically $ readTChan (csCommands state) case command of ChangeStatus newStatus -> do putStrLn ("TODO : send dispatcher : " ++ show command) loop state context AddContact username -> do putStrLn ("TODO : send dispatcher : " ++ show command) loop state context Quit -> do putStrLn ("TODO : send dispatcher : " ++ show command) loop state context _ -> do failed ("Error : unknown command received : " ++ show command ++ "\n") loop state context
nschoe/hpt
src/Main.hs
Haskell
bsd-3-clause
12,318
module Ghazan.Speed ( ) where
Cortlandd/ConversionFormulas
src/Ghazan/Speed.hs
Haskell
bsd-3-clause
35
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} -- | Symbolic evaluation for the 'Numerical' subset of expressions of the -- 'Core' language shared by all three languages: 'Term', 'Prop', and -- 'Invariant'. module Pact.Analyze.Eval.Numerical where import Data.Coerce (Coercible) import Data.SBV (EqSymbolic ((.==)), complement, sDiv, sMod, shift, unliteral, xor, (.&.), (.<), (.|.)) import Pact.Analyze.Errors import Pact.Analyze.Types import Pact.Analyze.Types.Eval -- When doing binary arithmetic involving: -- * decimal x decimal -- * integer x decimal -- * decimal x integer -- -- We widen / downcast the integer to be a decimal. This just requires shifting -- the number left 255 decimal digits in the case of an integer. class DecimalRepresentable a where widenToDecimal :: S a -> S Decimal instance DecimalRepresentable Integer where widenToDecimal = lShift255D . coerceS instance DecimalRepresentable Decimal where widenToDecimal = id -- This module handles evaluation of unary and binary integers and decimals. -- Two tricky details to watch out for: -- -- 1. See Note [Rounding] -- -- 2. Errors. Division can fail if the denominator is 0. Rounding can fail if -- the precision is negative. In either case we mark failure via -- @markFailure@. Thus our codomain is extended with failure. -- -- Note [Rounding] -- -- The key is this quote from "Data.Decimal": -- -- "Decimal numbers are represented as m*10^(-e) where m and e are integers. The -- exponent e is an unsigned Word8. Hence the smallest value that can be -- represented is 10^-255." evalNumerical :: Analyzer m => Numerical (TermOf m) a -> m (S (Concrete a)) evalNumerical (IntArithOp op x y) = evalIntArithOp op x y evalNumerical (DecArithOp op x y) = evalDecArithOp op x y evalNumerical (IntDecArithOp op x y) = evalDecArithOp op x y evalNumerical (DecIntArithOp op x y) = evalDecArithOp op x y evalNumerical (IntUnaryArithOp op x) = evalUnaryArithOp op x evalNumerical (DecUnaryArithOp op x) = evalUnaryArithOp op x evalNumerical (ModOp x y) = evalModOp x y evalNumerical (RoundingLikeOp1 op x) = evalRoundingLikeOp1 op x evalNumerical (RoundingLikeOp2 op x p) = evalRoundingLikeOp2 op x p evalNumerical (BitwiseOp op args) = evalBitwiseOp op args -- In principle this could share an implementation with evalDecArithOp. In -- practice, evaluation can be slower because you're multiplying both inputs by -- (10 ^ 255), so we stick to this more efficient implementation. evalIntArithOp :: Analyzer m => ArithOp -> TermOf m 'TyInteger -> TermOf m 'TyInteger -> m (S Integer) evalIntArithOp op xT yT = do x <- eval xT y <- eval yT case op of Add -> pure $ x + y Sub -> pure $ x - y Mul -> pure $ x * y Div -> do markFailure $ y .== 0 pure $ x `sDiv` y Pow -> throwErrorNoLoc $ UnsupportedDecArithOp op Log -> throwErrorNoLoc $ UnsupportedDecArithOp op evalDecArithOp :: ( Analyzer m , SingI a , SingI b , DecimalRepresentable (Concrete a) , DecimalRepresentable (Concrete b) ) => ArithOp -> TermOf m a -> TermOf m b -> m (S Decimal) evalDecArithOp op xT yT = do x <- widenToDecimal <$> eval xT y <- widenToDecimal <$> eval yT coerceS <$> case op of Add -> pure $ x + y Sub -> pure $ x - y Mul -> pure $ x * y Div -> do markFailure $ y .== 0 pure $ x / y Pow -> throwErrorNoLoc $ UnsupportedDecArithOp op Log -> throwErrorNoLoc $ UnsupportedDecArithOp op -- In practice (a ~ Decimal) or (a ~ Integer). evalUnaryArithOp :: forall m a a' . ( Analyzer m , a' ~ Concrete a , Coercible a' Integer , SingI a ) => UnaryArithOp -> TermOf m a -> m (S a') evalUnaryArithOp op term = do x <- coerceS @a' @Integer <$> eval term coerceS @Integer @a' <$> case op of Negate -> pure $ negate x Sqrt -> throwErrorNoLoc $ UnsupportedUnaryOp op Ln -> throwErrorNoLoc $ UnsupportedUnaryOp op Exp -> throwErrorNoLoc $ UnsupportedUnaryOp op -- TODO: use svExp Abs -> pure $ abs x Signum -> pure $ signum x evalModOp :: Analyzer m => TermOf m 'TyInteger -> TermOf m 'TyInteger -> m (S Integer) evalModOp xT yT = do x <- eval xT y <- eval yT markFailure $ y .== 0 pure $ sMod x y evalRoundingLikeOp1 :: Analyzer m => RoundingLikeOp -> TermOf m 'TyDecimal -> m (S Integer) evalRoundingLikeOp1 op xT = do x <- eval xT pure $ case op of Floor -> floorD x -- For ceiling we use the identity: -- ceil(x) = -floor(-x) Ceiling -> negate (floorD (negate x)) -- Round is much more complicated because pact uses the banker's method, -- where a real exactly between two integers (_.5) is rounded to the -- nearest even. Round -> banker'sMethodS x -- In the decimal rounding operations we shift the number left by `precision` -- digits, round using the integer method, and shift back right. -- -- x: SReal := -100.15234 -- precision: SInteger := 2 -- return: SReal := -100.15 evalRoundingLikeOp2 :: forall m . Analyzer m => RoundingLikeOp -> TermOf m 'TyDecimal -> TermOf m 'TyInteger -> m (S Decimal) evalRoundingLikeOp2 op xT precisionT = do x <- eval @_ @'TyDecimal xT precision <- eval precisionT -- Precision must be >= 0 markFailure (precision .< 0) rShiftD' precision . fromInteger' <$> evalRoundingLikeOp1 op (inject' (lShiftD' precision x)) -- Round a real exactly between two integers (_.5) to the nearest even banker'sMethodS :: S Decimal -> S Integer banker'sMethodS (S prov x) = S prov $ banker'sMethod x evalBitwiseOp :: Analyzer m => BitwiseOp -> [TermOf m 'TyInteger] -> m (S Integer) evalBitwiseOp BitwiseAnd [xT, yT] = do S _ x <- eval xT S _ y <- eval yT pure $ sansProv $ x .&. y evalBitwiseOp BitwiseOr [xT, yT] = do S _ x <- eval xT S _ y <- eval yT pure $ sansProv $ x .|. y evalBitwiseOp Xor [xT, yT] = do S _ x <- eval xT S _ y <- eval yT pure $ sansProv $ x `xor` y evalBitwiseOp Complement [xT] = do S _ x <- eval xT pure $ sansProv $ complement x evalBitwiseOp Shift [xT, yT] = do S _ x <- eval xT S _ y <- eval yT case unliteral y of Just y' -> pure $ sansProv $ shift x $ fromIntegral y' Nothing -> throwErrorNoLoc $ UnhandledTerm "shift currently requires a statically determined shift size" evalBitwiseOp op terms = throwErrorNoLoc $ MalformedBitwiseOp op $ length terms
kadena-io/pact
src-tool/Pact/Analyze/Eval/Numerical.hs
Haskell
bsd-3-clause
6,973
{-- snippet lend --} lend amount balance = let reserve = 100 newBalance = balance - amount in if balance < reserve then Nothing else Just newBalance {-- /snippet lend --} {-- snippet lend2 --} lend2 amount balance = if amount < reserve * 0.5 then Just newBalance else Nothing where reserve = 100 newBalance = balance - amount {-- /snippet lend2 --} {-- snippet lend3 --} lend3 amount balance | amount <= 0 = Nothing | amount > reserve * 0.5 = Nothing | otherwise = Just newBalance where reserve = 100 newBalance = balance - amount {-- /snippet lend3 --}
binesiyu/ifl
examples/ch03/Lending.hs
Haskell
mit
776
{-# OPTIONS_GHC -Wno-missing-import-lists #-} -- | Optional parameters for actions. module Strive.Options ( module Strive.Options.Activities , module Strive.Options.Athletes , module Strive.Options.Authentication , module Strive.Options.Clubs , module Strive.Options.Comments , module Strive.Options.Friends , module Strive.Options.Kudos , module Strive.Options.Segments , module Strive.Options.Streams , module Strive.Options.Uploads ) where import Strive.Options.Activities import Strive.Options.Athletes import Strive.Options.Authentication import Strive.Options.Clubs import Strive.Options.Comments import Strive.Options.Friends import Strive.Options.Kudos import Strive.Options.Segments import Strive.Options.Streams import Strive.Options.Uploads
tfausak/strive
source/library/Strive/Options.hs
Haskell
mit
776
{-# LANGUAGE OverloadedStrings #-} module Ketchup.Auth ( basicAuth ) where import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Base64 as B64 import Ketchup.Httpd import Ketchup.Utils -- |Performs HTTP Basic Auth basicAuth :: [(B.ByteString, B.ByteString)] -- ^ List of (Username, Password) -> B.ByteString -- ^ Authentication Realm -> Handler -- ^ Success Handler -> Handler basicAuth couples realm success hnd req = case authHead of Nothing -> send401 Just x -> case authData `elem` couples of False -> send401 True -> success hnd req where authData = parseAuth $ x !! 0 where authHead = lookup "Authorization" $ headers req authField = B.concat ["Basic realm=\"",realm,"\""] send401 = sendReply hnd 401 [("WWW-Authenticate", [authField]) ,("Content-Type", ["text/html"])] "<h1>401 Unauthorized</h1>" parseAuth :: B.ByteString -> (B.ByteString, B.ByteString) parseAuth authStr = breakBS ":" $ B64.decodeLenient authData where authData = snd parts parts = breakBS " " authStr
silverweed/ketchup
Ketchup/Auth.hs
Haskell
mit
1,333
{-# LANGUAGE TemplateHaskell #-} {-| This module defines the type constraint closure operation. -} module Language.K3.TypeSystem.Closure ( calculateClosure ) where import Control.Monad import qualified Data.Map as Map import qualified Data.Set as Set import Language.K3.Utils.Pretty import Language.K3.TypeSystem.Data import Language.K3.TypeSystem.Utils import Language.K3.Utils.Logger $(loggingFunctions) -- * Closure routine -- |Performs transitive constraint closure on a given constraint set. calculateClosure :: ConstraintSet -> ConstraintSet calculateClosure cs = _debugI (boxToString $ ["Closing constraints: "] %$ indent 2 (prettyLines cs)) $ let (cs',cont) = calculateClosureStep cs in if cont then calculateClosure cs' else _debugIPretty "Finished closure: " cs' -- |Performs a single transitive constraint closure step on a given constraint -- set. Returns the resulting constraint set and a flag indicating whether or -- not any changes were made during this step. calculateClosureStep :: ConstraintSet -> (ConstraintSet, Bool) calculateClosureStep cs = let newCs = csUnions $ map applyClosureFunction closureFunctions in (cs `csUnion` newCs, not $ newCs `csSubset` cs) where closureFunctions = [ (closeTransitivity, "Transitivity") , (closeImmediate, "Immediate Type") , (closeLowerBoundingExtendedRecord, "Close Lower Ext. Record") , (closeUpperBoundingExtendedRecord, "Close Upper Ext. Record") , (closeQualifiedTransitivity, "Qual Transitivity") , (closeQualifiedRead, "Qualified Read") , (closeQualifiedWrite, "Qualified Write") , (closeMonomorphicTransitivity, "Monomorphic Transitivity") , (closeMonomorphicBounding, "Monomorphic Bounding") , (opaqueLowerBound, "Opaque Lower Bound") , (opaqueUpperBound, "Opaque Upper Bound") ] applyClosureFunction (fn, name) = let cs' = fn cs in let learned = csFromSet $ csToSet cs' Set.\\ csToSet cs in if csNull learned then cs' else flip _debugI cs' $ boxToString $ ["Constraint closure (" ++ name ++ ") learned: "] %$ indent 2 (prettyLines learned) -- * Closure rules -- Each of these functions generates a constraint set which represents the -- new additions to the constraint set *only*; the result does not necessarily -- include constraints from the original constraint set. -- |Performs closure for transitivity. closeTransitivity :: ConstraintSet -> ConstraintSet closeTransitivity cs = csFromList $ (do (t,sa) <- csQuery cs $ QueryAllTypesLowerBoundingAnyVars () bnd <- csQuery cs $ QueryTypeOrAnyVarByAnyVarLowerBound sa return $ case bnd of CLeft ta -> t <: ta CRight qa -> t <: qa ) ++ (do (sa,t) <- csQuery cs $ QueryAllTypesUpperBoundingAnyVars () bnd <- csQuery cs $ QueryTypeOrAnyVarByAnyVarUpperBound sa return $ case bnd of CLeft ta -> ta <: t CRight qa -> qa <: t ) -- |Performs immediate type closure. This routine calculates the closure for -- all immediate type-to-type constraints. closeImmediate :: ConstraintSet -> ConstraintSet closeImmediate cs = csUnions $ do (t1,t2) <- csQuery cs $ QueryAllTypesLowerBoundingTypes () case (t1,t2) of (SFunction a1 a2, SFunction a3 a4) -> give [a2 <: a4, a3 <: a1] (STrigger a1, STrigger a2) -> give [a2 <: a1] (SOption qa1, SOption qa2) -> give [qa1 <: qa2] (SIndirection qa1, SIndirection qa2) -> give [qa1 <: qa2] (STuple qas1, STuple qas2) | length qas1 == length qas2 -> give $ zipWith (<:) qas1 qas2 (SRecord m1 oas1 _, SRecord m2 oas2 _) | Set.null oas1 && Set.null oas2 && Map.keysSet m2 `Set.isSubsetOf` Map.keysSet m1 -> give $ Map.elems $ Map.intersectionWith (<:) m1 m2 _ -> mzero where give = return . csFromList -- |Performs closure for opaque-extended records in a lower-bounding position. closeLowerBoundingExtendedRecord :: ConstraintSet -> ConstraintSet closeLowerBoundingExtendedRecord cs = csUnions $ do (SRecord m oas ctOpt, t) <- csQuery cs $ QueryAllTypesLowerBoundingTypes () case t of SOpaque oa -> guard $ not $ oa `Set.member` oas _ -> return () oa' <- Set.toList oas (_, ta_U) <- csQuery cs $ QueryOpaqueBounds oa' t_U <- getUpperBoundsOf cs ta_U case recordConcat [t_U, SRecord m (Set.delete oa' oas) ctOpt] of Left _ -> -- In this situation, there is an inherent conflict in the record type. -- We'll detect this in inconsistency (to keep the closure function -- simple); for now, just bail on the rule. mzero Right t' -> return $ csSing $ t' <: t -- |Performs closure for opaque-extended records in an upper-bounding position. closeUpperBoundingExtendedRecord :: ConstraintSet -> ConstraintSet closeUpperBoundingExtendedRecord cs = csUnions $ do (t,SRecord m oas ctOpt) <- csQuery cs $ QueryAllTypesLowerBoundingTypes () moa <- Nothing : map Just (Set.toList oas) {- Nothing adds base record -} case moa of Nothing -> {-Default case-} return $ csSing $ t <: SRecord m Set.empty ctOpt Just oa -> {-Opaque case -} return $ csSing $ t <: SOpaque oa closeQualifiedTransitivity :: ConstraintSet -> ConstraintSet closeQualifiedTransitivity cs = csFromList $ do (qv1,qa2) <- csQuery cs $ QueryAllQualOrVarLowerBoundingQVar () qv3 <- csQuery cs $ QueryQualOrVarByQVarLowerBound qa2 return $ qv1 <: qv3 closeQualifiedRead :: ConstraintSet -> ConstraintSet closeQualifiedRead cs = csFromList $ do (ta,qa) <- csQuery cs $ QueryAllTypeOrVarLowerBoundingQVar () ta' <- csQuery cs $ QueryTypeOrVarByQVarLowerBound qa return $ ta <: ta' closeQualifiedWrite :: ConstraintSet -> ConstraintSet closeQualifiedWrite cs = csFromList $ do (qa1,qa2) <- csQuery cs $ QueryAllQVarLowerBoundingQVar () ta <- csQuery cs $ QueryTypeOrVarByQVarUpperBound qa2 return $ ta <: qa1 closeMonomorphicTransitivity :: ConstraintSet -> ConstraintSet closeMonomorphicTransitivity cs = csFromList $ do (qa2,qs) <- csQuery cs $ QueryAllMonomorphicQualifiedUpperConstraint () qa1 <- csQuery cs $ QueryPolyLineageByOrigin qa2 return $ MonomorphicQualifiedUpperConstraint qa1 qs closeMonomorphicBounding :: ConstraintSet -> ConstraintSet closeMonomorphicBounding cs = csFromList $ do (qa2,qs) <- csQuery cs $ QueryAllMonomorphicQualifiedUpperConstraint () return $ qa2 <: qs opaqueLowerBound :: ConstraintSet -> ConstraintSet opaqueLowerBound cs = csFromList $ do (oa,t) <- csQuery cs $ QueryAllOpaqueLowerBoundedConstraints () guard $ SOpaque oa /= t guard $ SRecord Map.empty (Set.singleton oa) Nothing /= t (_,ub) <- csQuery cs $ QueryOpaqueBounds oa t_U <- getUpperBoundsOf cs ub return $ t_U <: t opaqueUpperBound :: ConstraintSet -> ConstraintSet opaqueUpperBound cs = csFromList $ do (t,oa) <- csQuery cs $ QueryAllOpaqueUpperBoundedConstraints () guard $ SOpaque oa /= t case t of SRecord _ oas _ -> guard $ not $ Set.member oa oas _ -> return () (lb,_) <- csQuery cs $ QueryOpaqueBounds oa t_L <- getLowerBoundsOf cs lb return $ t <: t_L
DaMSL/K3
src/Language/K3/TypeSystem/Closure.hs
Haskell
apache-2.0
7,097
{- Copyright 2013 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# Language RecordWildCards #-} module Plush.Job.StdIO ( RunningIO(..), StdIOParts, makeStdIOParts, stdIOChildPrep, stdIOMasterPrep, stdIOLocalPrep, stdIOCloseMasters, ) where import Control.Applicative ((<$>), (<*>)) import Data.Aeson (Value) import System.Posix import qualified System.Posix.Missing as PM import Plush.Job.Output import Plush.Run.Posix (stdJsonOutput) -- | These are the parent side of the pipes and terminals to a running job. -- Note that the sense is inverted for the parent. That is: The parent writes -- to 'rioStdIn' to have the child read from 'stdInput'. The parent reads from -- 'rioStdOut' to read what the child has written to 'stdOutput'. data RunningIO = RIO { rioStdIn :: Fd , rioStdOut :: OutputStream Char , rioStdErr :: OutputStream Char , rioJsonOut :: OutputStream Value } -- | An opaque type holding the file descriptors used when setting up the -- standard IO environment for command execuction. data StdIOParts = StdIOParts { master1, master2, masterJ, slave1, slave2, slaveJ :: Fd } -- | Allocate the pieces needed for a standard IO execution environment. makeStdIOParts :: IO StdIOParts makeStdIOParts = do (m1, s1) <- openPseudoTerminal (m2, s2) <- openPseudoTerminal (mJ, sJ) <- createPipe mapM_ (\fd -> setFdOption fd CloseOnExec True) [m1, m2, mJ] return $ StdIOParts m1 m2 mJ s1 s2 sJ -- | Prepare a child process for standard IO. Note that this will also set up -- a the controlling terminal and session. Call this in the child side of a -- fork. stdIOChildPrep :: StdIOParts -> IO () stdIOChildPrep sp@StdIOParts {..} = do stdIOCloseMasters sp _ <- createSession PM.setControllingTerminal slave1 stdIOInstallSlaves sp -- | Prepare the master process for communicating with the child. Call this in -- the parent side of a fork. stdIOMasterPrep :: StdIOParts -> IO RunningIO stdIOMasterPrep sp@StdIOParts {..} = do stdIOCloseSlaves sp stdIOBuildRio sp -- | Prepare a standard IO environment for the master process itself. Unlike, -- 'stdIOChildPrep' the controlling terminal and session are not altered. stdIOLocalPrep :: StdIOParts -> IO RunningIO stdIOLocalPrep sp = do stdIOInstallSlaves sp stdIOBuildRio sp stdIOInstallSlaves :: StdIOParts -> IO () stdIOInstallSlaves sp@StdIOParts {..} = do _ <- dupTo slave1 stdInput _ <- dupTo slave1 stdOutput _ <- dupTo slave2 stdError _ <- dupTo slaveJ stdJsonOutput stdIOCloseSlaves sp stdIOBuildRio :: StdIOParts -> IO RunningIO stdIOBuildRio StdIOParts {..} = do RIO master1 <$> outputStreamUtf8 master1 <*> outputStreamUtf8 master2 <*> outputStreamJson masterJ stdIOCloseSlaves :: StdIOParts -> IO () stdIOCloseSlaves StdIOParts {..} = do closeFd slave1 closeFd slave2 closeFd slaveJ stdIOCloseMasters :: StdIOParts -> IO () stdIOCloseMasters StdIOParts {..} = do closeFd master1 closeFd master2 closeFd masterJ
mzero/plush
src/Plush/Job/StdIO.hs
Haskell
apache-2.0
3,591
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Program : ashellogl.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:43 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Main where import Qtc.Enums.Classes.Core import Qtc.Classes.Qccs import Qtc.Classes.Qccs_h import Qtc.Classes.Core import Qtc.Classes.Gui import Qtc.Classes.Opengl import Qtc.ClassTypes.Opengl import Qtc.ClassTypes.Gui import Qtc.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Enums.Gui.QSlider import Qtc.Core.Base import Qtc.Gui.Base import Qtc.Core.QCoreApplication import Qtc.Core.QSize import Qtc.Gui.QApplication import Qtc.Gui.QLayout import Qtc.Gui.QBoxLayout import Qtc.Gui.QHBoxLayout import Qtc.Gui.QVBoxLayout import Qtc.Gui.QLabel import Qtc.Gui.QWidget import Qtc.Gui.QGroupBox import Qtc.Gui.QColor import Qtc.Gui.QMouseEvent import Qtc.Gui.QAbstractSlider import Qtc.Gui.QSlider import Qtc.Opengl.QGLWidget import Qtc.Opengl.QGLWidget_h import Data.IORef import Data.List import Data.Bits import Array import Graphics.Rendering.OpenGL as GL import Qtc.Enums.Gui.QSizePolicy import Qt.Arthur.Style type MyQWidget = QWidgetSc (CMyQWidget) data CMyQWidget = CMyQWidget myQWidget :: IO (MyQWidget) myQWidget = qSubClass (qWidget ()) type GLWidget = QGLWidgetSc (CGLWidget) data CGLWidget = CGLWidget gLWidget :: IO (GLWidget) gLWidget = qSubClass (qGLWidget ()) trolltechGreen :: IO (QColor ()) trolltechGreen = qColorFromCmykF (0.40::Double, 0.0::Double, 1.0::Double, 0.0::Double) trolltechPurple :: IO (QColor ()) trolltechPurple = qColorFromCmykF (0.39::Double, 0.39::Double, 0.0::Double, 0.0::Double) main :: IO () main = do app <- qApplication () w <- myQWidget glw <- gLWidget rot <- newIORef (0, 0, 0) pos <- newIORef (0, 0) setHandler glw "initializeGL()" $ initgl rot setHandler glw "(QSize)minimumSizeHint()" $ minSizeHint setHandler glw "(QSize)sizeHint()" $ szHint setHandler glw "mousePressEvent(QMouseEvent*)" $ msPressEvent pos setHandler glw "mouseMoveEvent(QMouseEvent*)" $ msMoveEvent pos rot mainGroup <- qGroupBox w setTitle mainGroup "Controls" xSliderGroup <- qGroupBox mainGroup setAttribute xSliderGroup eWA_ContentsPropagated setTitle xSliderGroup "X" xSlider <- createSlider xSliderGroup ySliderGroup <- qGroupBox mainGroup setAttribute ySliderGroup eWA_ContentsPropagated setTitle ySliderGroup "Y" ySlider <- createSlider ySliderGroup zSliderGroup <- qGroupBox mainGroup setAttribute zSliderGroup eWA_ContentsPropagated setTitle zSliderGroup "Z" zSlider <- createSlider zSliderGroup setFixedWidth mainGroup 206 mainGroupLayout <- qHBoxLayout mainGroup addWidget mainGroupLayout xSliderGroup addWidget mainGroupLayout ySliderGroup addWidget mainGroupLayout zSliderGroup xSliderGroupLayout <- qHBoxLayout xSliderGroup addWidget xSliderGroupLayout xSlider ySliderGroupLayout <- qHBoxLayout ySliderGroup addWidget ySliderGroupLayout ySlider zSliderGroupLayout <- qHBoxLayout zSliderGroup addWidget zSliderGroupLayout zSlider connectSlot xSlider "valueChanged(int)" glw "setXRotation(int)" $ setXRotation rot connectSlot glw "xRotationChanged(int)" xSlider "setValue(int)" () connectSlot ySlider "valueChanged(int)" glw "setYRotation(int)" $ setYRotation rot connectSlot glw "yRotationChanged(int)" ySlider "setValue(int)" () connectSlot zSlider "valueChanged(int)" glw "setZRotation(int)" $ setZRotation rot connectSlot glw "zRotationChanged(int)" zSlider "setValue(int)" () glGroup <- qGroupBox w glGroupLayout <- qVBoxLayout glGroup addWidget glGroupLayout glw layout <- qHBoxLayout () addWidget layout glGroup addWidget layout mainGroup setLayout w layout setStyleChildren w =<< arthurStyle qshow w () ok <- qApplicationExec () returnGC msPressEvent :: IORef (Int, Int) -> GLWidget -> QMouseEvent () -> IO () msPressEvent pos this mev = do mx <- qx mev () my <- qy mev () modifyIORef pos (\(p_x, p_y) -> (mx, my)) msMoveEvent :: IORef (Int, Int) -> IORef (Int, Int, Int) -> GLWidget -> QMouseEvent () -> IO () msMoveEvent pos rot this mev = do mx <- qx mev () my <- qy mev () buttons <- buttons mev () (r_x, r_y) <- readIORef pos let mdx = r_x - mx let mdy = r_y - my let alb = (qFlags_toInt buttons) .&. (qFlags_toInt fLeftButton) let arb = (qFlags_toInt buttons) .&. (qFlags_toInt fRightButton) (r_x, r_y, r_z) <- readIORef rot do if (alb > 0) then do setXRotation rot this $ r_x + 8 * mdy setYRotation rot this $ r_y + 8 * mdx else return () if (arb > 0) then do setXRotation rot this $ r_x + 8 * mdy setZRotation rot this $ r_z + 8 * mdx else return () modifyIORef pos (\(p_x, p_y) -> (mx, my)) return () createSlider :: QGroupBox () -> IO (QSlider ()) createSlider gb = do slider <- qSlider (eVertical::QtOrientation, gb) setRange slider (0::Int, (360 * 16)::Int) setSingleStep slider (16::Int) setPageStep slider $ ((15 * 16)::Int) setTickInterval slider $ ((15 * 16)::Int) setTickPosition slider eTicksRight return slider initgl :: IORef (Int, Int, Int) -> GLWidget -> IO () initgl rot this = do tp <- trolltechPurple cd <- dark tp () qglClearColor this cd dl <- makeObject this shadeModel $= Flat depthFunc $= Just Less cullFace $= Just Back setHandler this "resizeGL(int,int)" rsz setHandler this "paintGL()" $ dsply rot dl return () setXRotation :: IORef (Int, Int, Int) -> GLWidget -> Int -> IO () setXRotation rot this angle = do nang <- normalizeAngle angle (r_x, r_y, r_z) <- readIORef rot return () if (nang /= r_x) then do modifyIORef rot (\(r_x, r_y, r_z) -> (nang, r_y , r_z)) emitSignal this "xRotationChanged(int)" nang updateGL this () else return () setYRotation :: IORef (Int, Int, Int) -> GLWidget -> Int -> IO () setYRotation rot this angle = do nang <- normalizeAngle angle (r_x, r_y, r_z) <- readIORef rot return () if (nang /= r_y) then do modifyIORef rot (\(r_x, r_y, r_z) -> (r_x, nang , r_z)) emitSignal this "yRotationChanged(int)" nang updateGL this () else return () setZRotation :: IORef (Int, Int, Int) -> GLWidget -> Int -> IO () setZRotation rot this angle = do nang <- normalizeAngle angle (r_x, r_y, r_z) <- readIORef rot return () if (nang /= r_z) then do modifyIORef rot (\(r_x, r_y, r_z) -> (r_x, r_y , nang)) emitSignal this "zRotationChanged(int)" nang updateGL this () else return () normalizeAngle :: Int -> IO (Int) normalizeAngle ang = do let a1 = normUp ang let a2 = normDown a1 return a2 normUp :: Int -> Int normUp a | a >= 0 = a normUp a = normUp $ a + (360 * 16) normDown :: Int -> Int normDown a | a <= (360 * 16) = a normDown a = normDown $ a - (360 * 16) minSizeHint :: GLWidget -> IO (QSize ()) minSizeHint this = do qSize (100::Int, 100::Int) szHint :: GLWidget -> IO (QSize ()) szHint this = do qSize (400::Int, 400::Int) dsply :: IORef (Int, Int, Int) -> DisplayList -> GLWidget -> IO () dsply rot dl this = do (r_x, r_y, r_z) <- readIORef rot GL.clear [ ColorBuffer, DepthBuffer ] loadIdentity GL.translate $ Vector3 0 0 (-10.0::GLdouble) GL.rotate ((fromIntegral r_x)/16.0) $ Vector3 (1.0::GLfloat) 0.0 0.0 GL.rotate ((fromIntegral r_y)/16.0) $ Vector3 (0.0::GLfloat) 1.0 0.0 GL.rotate ((fromIntegral r_z)/16.0) $ Vector3 (0.0::GLfloat) 0.0 1.0 callList dl returnGC rsz :: GLWidget -> Int -> Int -> IO () rsz this x y = do let side = min x y let p1 = round $ (fromIntegral $ x - side) / 2.0 let p2 = round $ (fromIntegral $ y - side) / 2.0 GL.viewport $= (Position (fromIntegral p1) (fromIntegral p2), GL.Size (fromIntegral side) (fromIntegral side)) matrixMode $= Projection loadIdentity ortho (-0.5::GLdouble) 0.5 0.5 (-0.5) 4.0 15.0 matrixMode $= Modelview 0 return () makeObject :: QGLWidget a -> IO (DisplayList) makeObject glw = defineNewList Compile $ do let x1 = 0.06 let y1 = -0.14 let x2 = 0.14 let y2 = -0.06 let x3 = 0.08 let y3 = 0.00 let x4 = 0.30 let y4 = 0.22 let pi = 3.14159265358979323846 renderPrimitive Quads $ do quad glw x1 y1 x2 y2 y2 x2 y1 x1 quad glw x3 y3 x4 y4 y4 x4 y3 x3 extrude glw x1 y1 x2 y2 extrude glw x2 y2 y2 x2 extrude glw y2 x2 y1 x1 extrude glw y1 x1 x1 y1 extrude glw x3 y3 x4 y4 extrude glw x4 y4 y4 x4 extrude glw y4 x4 y3 x3 do_NumSectors glw 0 pi 200 return () do_NumSectors :: QGLWidget a -> Int -> Double -> Int -> IO () do_NumSectors _ i _ ns | i >= ns = return () do_NumSectors glw i pi ns = do let fns = fromIntegral ns let angle1 = ((fromIntegral (i * 2)) * pi) / fns let x5 = realToFrac (0.30 * (sin angle1)) :: GLdouble let y5 = realToFrac (0.30 * (cos angle1)) :: GLdouble let x6 = realToFrac (0.20 * (sin angle1)) :: GLdouble let y6 = realToFrac (0.20 * (cos angle1)) :: GLdouble let angle2 = ((fromIntegral ((i + 1) * 2)) * pi) / fns let x7 = realToFrac (0.20 * sin(angle2)) :: GLdouble let y7 = realToFrac (0.20 * cos(angle2)) :: GLdouble let x8 = realToFrac (0.30 * sin(angle2)) :: GLdouble let y8 = realToFrac (0.30 * cos(angle2)) :: GLdouble quad glw x5 y5 x6 y6 x7 y7 x8 y8 extrude glw x6 y6 x7 y7 extrude glw x8 y8 x5 y5 do_NumSectors glw (i + 1) pi ns return () quad :: QGLWidget a -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO () quad glw x1 y1 x2 y2 x3 y3 x4 y4 = do qglColor glw =<< trolltechGreen vertex $ Vertex3 x1 y1 (-0.05) vertex $ Vertex3 x2 y2 (-0.05) vertex $ Vertex3 x3 y3 (-0.05) vertex $ Vertex3 x4 y4 (-0.05) vertex $ Vertex3 x4 y4 0.05 vertex $ Vertex3 x3 y3 0.05 vertex $ Vertex3 x2 y2 0.05 vertex $ Vertex3 x1 y1 0.05 return () extrude :: QGLWidget a -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO () extrude glw x1 y1 x2 y2 = do tg <- trolltechGreen let xrp = truncate $ x1 * 100.0 dc <- darker tg $ (xrp::Int) + 250 qglColor glw dc vertex $ Vertex3 x1 y1 0.05 vertex $ Vertex3 x2 y2 0.05 vertex $ Vertex3 x2 y2 (-0.05) vertex $ Vertex3 x1 y1 (-0.05) return ()
uduki/hsQt
examples/ashellogl.hs
Haskell
bsd-2-clause
10,811
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-} -- | -- Module : Statistics.Distribution.FDistribution -- Copyright : (c) 2011 Aleksey Khudyakov -- License : BSD3 -- -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : portable -- -- Fisher F distribution module Statistics.Distribution.FDistribution ( FDistribution , fDistribution , fDistributionNDF1 , fDistributionNDF2 ) where import Data.Aeson (FromJSON, ToJSON) import Data.Binary (Binary) import Data.Data (Data, Typeable) import Numeric.MathFunctions.Constants (m_neg_inf) import GHC.Generics (Generic) import qualified Statistics.Distribution as D import Statistics.Function (square) import Numeric.SpecFunctions ( logBeta, incompleteBeta, invIncompleteBeta, digamma) import Data.Binary (put, get) import Control.Applicative ((<$>), (<*>)) -- | F distribution data FDistribution = F { fDistributionNDF1 :: {-# UNPACK #-} !Double , fDistributionNDF2 :: {-# UNPACK #-} !Double , _pdfFactor :: {-# UNPACK #-} !Double } deriving (Eq, Show, Read, Typeable, Data, Generic) instance FromJSON FDistribution instance ToJSON FDistribution instance Binary FDistribution where get = F <$> get <*> get <*> get put (F x y z) = put x >> put y >> put z fDistribution :: Int -> Int -> FDistribution fDistribution n m | n > 0 && m > 0 = let n' = fromIntegral n m' = fromIntegral m f' = 0.5 * (log m' * m' + log n' * n') - logBeta (0.5*n') (0.5*m') in F n' m' f' | otherwise = error "Statistics.Distribution.FDistribution.fDistribution: non-positive number of degrees of freedom" instance D.Distribution FDistribution where cumulative = cumulative instance D.ContDistr FDistribution where density d x | x <= 0 = 0 | otherwise = exp $ logDensity d x logDensity d x | x <= 0 = m_neg_inf | otherwise = logDensity d x quantile = quantile cumulative :: FDistribution -> Double -> Double cumulative (F n m _) x | x <= 0 = 0 | isInfinite x = 1 -- Only matches +∞ | otherwise = let y = n*x in incompleteBeta (0.5 * n) (0.5 * m) (y / (m + y)) logDensity :: FDistribution -> Double -> Double logDensity (F n m fac) x = fac + log x * (0.5 * n - 1) - log(m + n*x) * 0.5 * (n + m) quantile :: FDistribution -> Double -> Double quantile (F n m _) p | p >= 0 && p <= 1 = let x = invIncompleteBeta (0.5 * n) (0.5 * m) p in m * x / (n * (1 - x)) | otherwise = error $ "Statistics.Distribution.Uniform.quantile: p must be in [0,1] range. Got: "++show p instance D.MaybeMean FDistribution where maybeMean (F _ m _) | m > 2 = Just $ m / (m - 2) | otherwise = Nothing instance D.MaybeVariance FDistribution where maybeStdDev (F n m _) | m > 4 = Just $ 2 * square m * (m + n - 2) / (n * square (m - 2) * (m - 4)) | otherwise = Nothing instance D.Entropy FDistribution where entropy (F n m _) = let nHalf = 0.5 * n mHalf = 0.5 * m in log (n/m) + logBeta nHalf mHalf + (1 - nHalf) * digamma nHalf - (1 + mHalf) * digamma mHalf + (nHalf + mHalf) * digamma (nHalf + mHalf) instance D.MaybeEntropy FDistribution where maybeEntropy = Just . D.entropy instance D.ContGen FDistribution where genContVar = D.genContinous
fpco/statistics
Statistics/Distribution/FDistribution.hs
Haskell
bsd-2-clause
3,389
{-# LANGUAGE DeriveDataTypeable #-} module Network.Bluetooth.Exception (BluetoothException(..)) where import Control.Exception import Data.Typeable import Network.Bluetooth.Protocol data BluetoothException = BluetoothPortException BluetoothProtocol BluetoothPort deriving Typeable instance Show BluetoothException where showsPrec _ (BluetoothPortException L2CAP port) = showString "L2CAP port " . shows port . showString " is not an odd number between 4,097 and 32,767." showsPrec _ (BluetoothPortException RFCOMM port) = showString "RFCOMM port " . shows port . showString " is not between 1 and 30." instance Exception BluetoothException
bneijt/bluetooth
src/Network/Bluetooth/Exception.hs
Haskell
bsd-3-clause
654
{-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | Server and client game state types and operations. module Game.LambdaHack.Client.State ( StateClient(..), defStateClient, defaultHistory , updateTarget, getTarget, updateLeader, sside , PathEtc, TgtMode(..), RunParams(..), LastRecord, EscAI(..) , toggleMarkVision, toggleMarkSmell, toggleMarkSuspect ) where import Control.Exception.Assert.Sugar import Data.Binary import qualified Data.EnumMap.Strict as EM import qualified Data.EnumSet as ES import Data.Text (Text) import qualified Data.Text as T import qualified NLP.Miniutter.English as MU import qualified System.Random as R import System.Time import Game.LambdaHack.Atomic import Game.LambdaHack.Client.Bfs import Game.LambdaHack.Client.ItemSlot import qualified Game.LambdaHack.Client.Key as K import Game.LambdaHack.Common.Actor import Game.LambdaHack.Common.ActorState import Game.LambdaHack.Common.ClientOptions import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.Item import Game.LambdaHack.Common.Level import Game.LambdaHack.Common.Misc import Game.LambdaHack.Common.Msg import Game.LambdaHack.Common.Perception import Game.LambdaHack.Common.Point import qualified Game.LambdaHack.Common.PointArray as PointArray import Game.LambdaHack.Common.State import Game.LambdaHack.Common.Time import Game.LambdaHack.Common.Vector -- | Client state, belonging to a single faction. -- Some of the data, e.g, the history, carries over -- from game to game, even across playing sessions. -- Data invariant: if @_sleader@ is @Nothing@ then so is @srunning@. data StateClient = StateClient { stgtMode :: !(Maybe TgtMode) -- ^ targeting mode , scursor :: !Target -- ^ the common, cursor target , seps :: !Int -- ^ a parameter of the tgt digital line , stargetD :: !(EM.EnumMap ActorId (Target, Maybe PathEtc)) -- ^ targets of our actors in the dungeon , sexplored :: !(ES.EnumSet LevelId) -- ^ the set of fully explored levels , sbfsD :: !(EM.EnumMap ActorId ( Bool, PointArray.Array BfsDistance , Point, Int, Maybe [Point]) ) -- ^ pathfinding distances for our actors -- and paths to their targets, if any , sselected :: !(ES.EnumSet ActorId) -- ^ the set of currently selected actors , srunning :: !(Maybe RunParams) -- ^ parameters of the current run, if any , sreport :: !Report -- ^ current messages , shistory :: !History -- ^ history of messages , sdisplayed :: !(EM.EnumMap LevelId Time) -- ^ moves are displayed up to this time , sundo :: ![CmdAtomic] -- ^ atomic commands performed to date , sdiscoKind :: !DiscoveryKind -- ^ remembered item discoveries , sdiscoEffect :: !DiscoveryEffect -- ^ remembered effects&Co of items , sfper :: !FactionPers -- ^ faction perception indexed by levels , srandom :: !R.StdGen -- ^ current random generator , slastKM :: !K.KM -- ^ last issued key command , slastRecord :: !LastRecord -- ^ state of key sequence recording , slastPlay :: ![K.KM] -- ^ state of key sequence playback , slastLost :: !(ES.EnumSet ActorId) -- ^ actors that just got out of sight , swaitTimes :: !Int -- ^ player just waited this many times , _sleader :: !(Maybe ActorId) -- ^ current picked party leader , _sside :: !FactionId -- ^ faction controlled by the client , squit :: !Bool -- ^ exit the game loop , sisAI :: !Bool -- ^ whether it's an AI client , smarkVision :: !Bool -- ^ mark leader and party FOV , smarkSmell :: !Bool -- ^ mark smell, if the leader can smell , smarkSuspect :: !Bool -- ^ mark suspect features , scurDiff :: !Int -- ^ current game difficulty level , snxtDiff :: !Int -- ^ next game difficulty level , sslots :: !ItemSlots -- ^ map from slots to items , slastSlot :: !SlotChar -- ^ last used slot , slastStore :: !CStore -- ^ last used store , sescAI :: !EscAI -- ^ just canceled AI control with ESC , sdebugCli :: !DebugModeCli -- ^ client debugging mode } deriving Show type PathEtc = ([Point], (Point, Int)) -- | Current targeting mode of a client. newtype TgtMode = TgtMode { tgtLevelId :: LevelId } deriving (Show, Eq, Binary) -- | Parameters of the current run. data RunParams = RunParams { runLeader :: !ActorId -- ^ the original leader from run start , runMembers :: ![ActorId] -- ^ the list of actors that take part , runInitial :: !Bool -- ^ initial run continuation by any -- run participant, including run leader , runStopMsg :: !(Maybe Text) -- ^ message with the next stop reason , runWaiting :: !Int -- ^ waiting for others to move out of the way } deriving (Show) type LastRecord = ( [K.KM] -- accumulated keys of the current command , [K.KM] -- keys of the rest of the recorded command batch , Int -- commands left to record for this batch ) data EscAI = EscAINothing | EscAIStarted | EscAIMenu | EscAIExited deriving (Show, Eq) -- | Initial game client state. defStateClient :: History -> Report -> FactionId -> Bool -> StateClient defStateClient shistory sreport _sside sisAI = StateClient { stgtMode = Nothing , scursor = if sisAI then TVector $ Vector 30000 30000 -- invalid else TVector $ Vector 1 1 -- a step south-east , seps = fromEnum _sside , stargetD = EM.empty , sexplored = ES.empty , sbfsD = EM.empty , sselected = ES.empty , srunning = Nothing , sreport , shistory , sdisplayed = EM.empty , sundo = [] , sdiscoKind = EM.empty , sdiscoEffect = EM.empty , sfper = EM.empty , srandom = R.mkStdGen 42 -- will be set later , slastKM = K.escKM , slastRecord = ([], [], 0) , slastPlay = [] , slastLost = ES.empty , swaitTimes = 0 , _sleader = Nothing -- no heroes yet alive , _sside , squit = False , sisAI , smarkVision = False , smarkSmell = True , smarkSuspect = False , scurDiff = difficultyDefault , snxtDiff = difficultyDefault , sslots = (EM.empty, EM.empty) , slastSlot = SlotChar 0 'Z' , slastStore = CInv , sescAI = EscAINothing , sdebugCli = defDebugModeCli } defaultHistory :: Int -> IO History defaultHistory configHistoryMax = do dateTime <- getClockTime let curDate = MU.Text $ T.pack $ calendarTimeToString $ toUTCTime dateTime let emptyHist = emptyHistory configHistoryMax return $! addReport emptyHist timeZero $! singletonReport $! makeSentence ["Human history log started on", curDate] -- | Update target parameters within client state. updateTarget :: ActorId -> (Maybe Target -> Maybe Target) -> StateClient -> StateClient updateTarget aid f cli = let f2 tp = case f $ fmap fst tp of Nothing -> Nothing Just tgt -> Just (tgt, Nothing) -- reset path in cli {stargetD = EM.alter f2 aid (stargetD cli)} -- | Get target parameters from client state. getTarget :: ActorId -> StateClient -> Maybe Target getTarget aid cli = fmap fst $ EM.lookup aid $ stargetD cli -- | Update picked leader within state. Verify actor's faction. updateLeader :: ActorId -> State -> StateClient -> StateClient updateLeader leader s cli = let side1 = bfid $ getActorBody leader s side2 = sside cli in assert (side1 == side2 `blame` "enemy actor becomes our leader" `twith` (side1, side2, leader, s)) $ cli {_sleader = Just leader} sside :: StateClient -> FactionId sside = _sside toggleMarkVision :: StateClient -> StateClient toggleMarkVision s@StateClient{smarkVision} = s {smarkVision = not smarkVision} toggleMarkSmell :: StateClient -> StateClient toggleMarkSmell s@StateClient{smarkSmell} = s {smarkSmell = not smarkSmell} toggleMarkSuspect :: StateClient -> StateClient toggleMarkSuspect s@StateClient{smarkSuspect} = s {smarkSuspect = not smarkSuspect} instance Binary StateClient where put StateClient{..} = do put stgtMode put scursor put seps put stargetD put sexplored put sselected put srunning put sreport put shistory put sundo put sdisplayed put sdiscoKind put sdiscoEffect put (show srandom) put _sleader put _sside put sisAI put smarkVision put smarkSmell put smarkSuspect put scurDiff put snxtDiff put sslots put slastSlot put slastStore put sdebugCli -- TODO: this is overwritten at once get = do stgtMode <- get scursor <- get seps <- get stargetD <- get sexplored <- get sselected <- get srunning <- get sreport <- get shistory <- get sundo <- get sdisplayed <- get sdiscoKind <- get sdiscoEffect <- get g <- get _sleader <- get _sside <- get sisAI <- get smarkVision <- get smarkSmell <- get smarkSuspect <- get scurDiff <- get snxtDiff <- get sslots <- get slastSlot <- get slastStore <- get sdebugCli <- get let sbfsD = EM.empty sfper = EM.empty srandom = read g slastKM = K.escKM slastRecord = ([], [], 0) slastPlay = [] slastLost = ES.empty swaitTimes = 0 squit = False sescAI = EscAINothing return $! StateClient{..} instance Binary RunParams where put RunParams{..} = do put runLeader put runMembers put runInitial put runStopMsg put runWaiting get = do runLeader <- get runMembers <- get runInitial <- get runStopMsg <- get runWaiting <- get return $! RunParams{..}
Concomitant/LambdaHack
Game/LambdaHack/Client/State.hs
Haskell
bsd-3-clause
10,273
-- Copyright (c) 2015 Eric McCorkle. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the name of the author nor the names of any contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS -- 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. {-# OPTIONS_GHC -funbox-strict-fields -Wall -Werror #-} {-# LANGUAGE MultiParamTypeClasses #-} -- | A class of monads for outputting compiler messages. module Control.Monad.TypeErrors.Class( MonadTypeErrors(..) ) where import Data.Pos import Language.Salt.Core.Syntax -- | Monad class representing the different kinds of compiler error -- messages that can be generated. class Monad m => MonadTypeErrors sym m where -- | Log a type mismatch error, when a term's actual type is not a -- subtype of its expected type. typeMismatch :: Term sym sym -- ^ The term from which this originates. -> Term sym sym -- ^ The expected type. -> Term sym sym -- ^ The actual type. -> m (Term sym sym) -- ^ A type to return instead of the expected type. -- | Log an error when a term with a particular type was expected, -- but the term wasn't of the right form. formMismatch :: Term sym sym -- ^ The term whose form is incorrect. -> Term sym sym -- ^ The term's expected type. -> m (Term sym sym) -- ^ A type to return instead of the expected type. -- | Log an error when term with a function type is expected, but -- the actual type is something else expectedFunction :: Term sym sym -- ^ The term from which this originates. -> Term sym sym -- ^ The term's actual type. -> m (Term sym sym) -- ^ A type to return instead of the expected type. -- | Log an error for an unbounded-rank type. infiniteType :: Term sym sym -- ^ The illegal type. -> Term sym sym -- ^ The term's actual type. -> m (Term sym sym) -- ^ A type to return instead of the expected type. -- | Log an undefined symbol error. undefSym :: sym -- ^ The symbol that is not defined. -> Pos -- ^ The position at which this occurred. -> m (Term sym sym) -- ^ A type representing the type of undefined symbols.
emc2/saltlang
src/salt/Control/Monad/TypeErrors/Class.hs
Haskell
bsd-3-clause
3,765
#if __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Safe #-} #endif -- | Produces XHTML 1.0 Frameset. module Text.XHtml.Frameset ( -- * Data types Html, HtmlAttr, -- * Classes HTML(..), ADDATTRS(..), CHANGEATTRS(..), -- * Primitives and basic combinators (<<), concatHtml, (+++), noHtml, isNoHtml, tag, itag, htmlAttrPair, emptyAttr, intAttr, strAttr, htmlAttr, primHtml, -- * Rendering showHtml, renderHtml, prettyHtml, showHtmlFragment, renderHtmlFragment, prettyHtmlFragment, module Text.XHtml.Strict.Elements, module Text.XHtml.Frameset.Elements, module Text.XHtml.Strict.Attributes, module Text.XHtml.Frameset.Attributes, module Text.XHtml.Extras ) where import Text.XHtml.Internals import Text.XHtml.Strict.Elements import Text.XHtml.Frameset.Elements import Text.XHtml.Strict.Attributes import Text.XHtml.Frameset.Attributes import Text.XHtml.Extras docType :: String docType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\"" ++ " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">" -- | Output the HTML without adding newlines or spaces within the markup. -- This should be the most time and space efficient way to -- render HTML, though the ouput is quite unreadable. showHtml :: HTML html => html -> String showHtml = showHtmlInternal docType -- | Outputs indented HTML. Because space matters in -- HTML, the output is quite messy. renderHtml :: HTML html => html -> String renderHtml = renderHtmlInternal docType -- | Outputs indented HTML, with indentation inside elements. -- This can change the meaning of the HTML document, and -- is mostly useful for debugging the HTML output. -- The implementation is inefficient, and you are normally -- better off using 'showHtml' or 'renderHtml'. prettyHtml :: HTML html => html -> String prettyHtml = prettyHtmlInternal docType
DavidAlphaFox/ghc
libraries/xhtml/Text/XHtml/Frameset.hs
Haskell
bsd-3-clause
1,920
-- | -- Module : $Header$ -- Copyright : (c) 2013-2015 Galois, Inc. -- License : BSD3 -- Maintainer : cryptol@galois.com -- Stability : provisional -- Portability : portable {-# LANGUAGE PatternGuards #-} module Cryptol.TypeCheck ( tcModule , tcExpr , tcDecls , InferInput(..) , InferOutput(..) , SolverConfig(..) , NameSeeds , nameSeeds , Error(..) , Warning(..) , ppWarning , ppError ) where import qualified Cryptol.Parser.AST as P import Cryptol.Parser.Position(Range) import Cryptol.TypeCheck.AST import Cryptol.TypeCheck.Depends (FromDecl) import Cryptol.TypeCheck.Monad ( runInferM , InferInput(..) , InferOutput(..) , NameSeeds , nameSeeds , lookupVar ) import Cryptol.TypeCheck.Infer (inferModule, inferBinds, inferDs) import Cryptol.TypeCheck.InferTypes(Error(..),Warning(..),VarType(..), SolverConfig(..)) import Cryptol.TypeCheck.Solve(simplifyAllConstraints) import Cryptol.Utils.PP import Cryptol.Utils.Panic(panic) tcModule :: P.Module -> InferInput -> IO (InferOutput Module) tcModule m inp = runInferM inp $ do x <- inferModule m simplifyAllConstraints return x tcExpr :: P.Expr -> InferInput -> IO (InferOutput (Expr,Schema)) tcExpr e0 inp = runInferM inp $ do x <- go e0 simplifyAllConstraints return x where go expr = case expr of P.ELocated e _ -> go e P.EVar x -> do res <- lookupVar x case res of ExtVar s -> return (EVar x, s) CurSCC e' t -> panic "Cryptol.TypeCheck.tcExpr" [ "CurSCC outside binder checkig:" , show e' , show t ] _ -> do res <- inferBinds True False [ P.Bind { P.bName = P.Located (inpRange inp) $ mkUnqual (P.mkName "(expression)") , P.bParams = [] , P.bDef = P.Located (inpRange inp) (P.DExpr expr) , P.bPragmas = [] , P.bSignature = Nothing , P.bMono = False , P.bInfix = False , P.bFixity = Nothing , P.bDoc = Nothing } ] case res of [d] | DExpr e <- dDefinition d -> return (e, dSignature d) | otherwise -> panic "Cryptol.TypeCheck.tcExpr" [ "Expected an expression in definition" , show d ] _ -> panic "Cryptol.TypeCheck.tcExpr" ( "Multiple declarations when check expression:" : map show res ) tcDecls :: FromDecl d => [d] -> InferInput -> IO (InferOutput [DeclGroup]) tcDecls ds inp = runInferM inp $ inferDs ds $ \dgs -> do simplifyAllConstraints return dgs ppWarning :: (Range,Warning) -> Doc ppWarning (r,w) = text "[warning] at" <+> pp r <> colon $$ nest 2 (pp w) ppError :: (Range,Error) -> Doc ppError (r,w) = text "[error] at" <+> pp r <> colon $$ nest 2 (pp w)
iblumenfeld/cryptol
src/Cryptol/TypeCheck.hs
Haskell
bsd-3-clause
3,563
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilyDependencies #-} {-# LANGUAGE DataKinds, PolyKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module T14369 where data family Sing (a :: k) data instance Sing (z :: Maybe a) where SNothing :: Sing Nothing SJust :: Sing x -> Sing (Just x) class SingKind k where type Demote k = r | r -> k fromSing :: Sing (a :: k) -> Demote k instance SingKind a => SingKind (Maybe a) where type Demote (Maybe a) = Maybe (Demote a) fromSing SNothing = Nothing fromSing (SJust x) = Just (fromSing x) f :: forall (x :: forall a. Maybe a) a. SingKind a => Sing x -> Maybe (Demote a) f = fromSing
sdiehl/ghc
testsuite/tests/indexed-types/should_fail/T14369.hs
Haskell
bsd-3-clause
808
-- (c) The University of Glasgow 2012 {-# LANGUAGE CPP, DataKinds, DeriveDataTypeable, GADTs, KindSignatures, ScopedTypeVariables, StandaloneDeriving #-} -- | Module for coercion axioms, used to represent type family instances -- and newtypes module CoAxiom ( BranchFlag, Branched, Unbranched, BranchIndex, BranchList(..), toBranchList, fromBranchList, toBranchedList, toUnbranchedList, brFromUnbranchedSingleton, brListLength, brListNth, brListMap, brListFoldr, brListMapM, brListFoldlM_, brListZipWith, CoAxiom(..), CoAxBranch(..), toBranchedAxiom, toUnbranchedAxiom, coAxiomName, coAxiomArity, coAxiomBranches, coAxiomTyCon, isImplicitCoAxiom, coAxiomNumPats, coAxiomNthBranch, coAxiomSingleBranch_maybe, coAxiomRole, coAxiomSingleBranch, coAxBranchTyVars, coAxBranchRoles, coAxBranchLHS, coAxBranchRHS, coAxBranchSpan, coAxBranchIncomps, placeHolderIncomps, Role(..), fsFromRole, CoAxiomRule(..), Eqn, BuiltInSynFamily(..), trivialBuiltInFamily ) where import {-# SOURCE #-} TypeRep ( Type ) import {-# SOURCE #-} TyCon ( TyCon ) import Outputable import FastString import Name import Unique import Var import Util import Binary import Pair import BasicTypes import Data.Typeable ( Typeable ) import SrcLoc import qualified Data.Data as Data #include "HsVersions.h" {- Note [Coercion axiom branches] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In order to allow type family instance groups, an axiom needs to contain an ordered list of alternatives, called branches. The kind of the coercion built from an axiom is determined by which index is used when building the coercion from the axiom. For example, consider the axiom derived from the following declaration: type family F a where F [Int] = Bool F [a] = Double F (a b) = Char This will give rise to this axiom: axF :: { F [Int] ~ Bool ; forall (a :: *). F [a] ~ Double ; forall (k :: BOX) (a :: k -> *) (b :: k). F (a b) ~ Char } The axiom is used with the AxiomInstCo constructor of Coercion. If we wish to have a coercion showing that F (Maybe Int) ~ Char, it will look like axF[2] <*> <Maybe> <Int> :: F (Maybe Int) ~ Char -- or, written using concrete-ish syntax -- AxiomInstCo axF 2 [Refl *, Refl Maybe, Refl Int] Note that the index is 0-based. For type-checking, it is also necessary to check that no previous pattern can unify with the supplied arguments. After all, it is possible that some of the type arguments are lambda-bound type variables whose instantiation may cause an earlier match among the branches. We wish to prohibit this behavior, so the type checker rules out the choice of a branch where a previous branch can unify. See also [Apartness] in FamInstEnv.hs. For example, the following is malformed, where 'a' is a lambda-bound type variable: axF[2] <*> <a> <Bool> :: F (a Bool) ~ Char Why? Because a might be instantiated with [], meaning that branch 1 should apply, not branch 2. This is a vital consistency check; without it, we could derive Int ~ Bool, and that is a Bad Thing. Note [Branched axioms] ~~~~~~~~~~~~~~~~~~~~~~ Although a CoAxiom has the capacity to store many branches, in certain cases, we want only one. These cases are in data/newtype family instances, newtype coercions, and type family instances declared with "type instance ...", not "type instance where". Furthermore, these unbranched axioms are used in a variety of places throughout GHC, and it would difficult to generalize all of that code to deal with branched axioms, especially when the code can be sure of the fact that an axiom is indeed a singleton. At the same time, it seems dangerous to assume singlehood in various places through GHC. The solution to this is to label a CoAxiom with a phantom type variable declaring whether it is known to be a singleton or not. The list of branches is stored using a special form of list, declared below, that ensures that the type variable is accurate. ************************************************************************ * * Branch lists * * ************************************************************************ -} type BranchIndex = Int -- The index of the branch in the list of branches -- Counting from zero -- promoted data type data BranchFlag = Branched | Unbranched type Branched = 'Branched deriving instance Typeable 'Branched type Unbranched = 'Unbranched deriving instance Typeable 'Unbranched -- By using type synonyms for the promoted constructors, we avoid needing -- DataKinds and the promotion quote in client modules. This also means that -- we don't need to export the term-level constructors, which should never be used. data BranchList a (br :: BranchFlag) where FirstBranch :: a -> BranchList a br NextBranch :: a -> BranchList a br -> BranchList a Branched deriving instance Typeable BranchList -- convert to/from lists toBranchList :: [a] -> BranchList a Branched toBranchList [] = pprPanic "toBranchList" empty toBranchList [b] = FirstBranch b toBranchList (h:t) = NextBranch h (toBranchList t) fromBranchList :: BranchList a br -> [a] fromBranchList (FirstBranch b) = [b] fromBranchList (NextBranch h t) = h : (fromBranchList t) -- convert from any BranchList to a Branched BranchList toBranchedList :: BranchList a br -> BranchList a Branched toBranchedList (FirstBranch b) = FirstBranch b toBranchedList (NextBranch h t) = NextBranch h t -- convert from any BranchList to an Unbranched BranchList toUnbranchedList :: BranchList a br -> BranchList a Unbranched toUnbranchedList (FirstBranch b) = FirstBranch b toUnbranchedList _ = pprPanic "toUnbranchedList" empty -- Extract a singleton axiom from Unbranched BranchList brFromUnbranchedSingleton :: BranchList a Unbranched -> a brFromUnbranchedSingleton (FirstBranch b) = b -- length brListLength :: BranchList a br -> Int brListLength (FirstBranch _) = 1 brListLength (NextBranch _ t) = 1 + brListLength t -- lookup brListNth :: BranchList a br -> BranchIndex -> a brListNth (FirstBranch b) 0 = b brListNth (NextBranch h _) 0 = h brListNth (NextBranch _ t) n = brListNth t (n-1) brListNth _ _ = pprPanic "brListNth" empty -- map, fold brListMap :: (a -> b) -> BranchList a br -> [b] brListMap f (FirstBranch b) = [f b] brListMap f (NextBranch h t) = f h : (brListMap f t) brListFoldr :: (a -> b -> b) -> b -> BranchList a br -> b brListFoldr f x (FirstBranch b) = f b x brListFoldr f x (NextBranch h t) = f h (brListFoldr f x t) brListMapM :: Monad m => (a -> m b) -> BranchList a br -> m [b] brListMapM f (FirstBranch b) = f b >>= \fb -> return [fb] brListMapM f (NextBranch h t) = do { fh <- f h ; ft <- brListMapM f t ; return (fh : ft) } brListFoldlM_ :: forall a b m br. Monad m => (a -> b -> m a) -> a -> BranchList b br -> m () brListFoldlM_ f z brs = do { _ <- go z brs ; return () } where go :: forall br'. a -> BranchList b br' -> m a go acc (FirstBranch b) = f acc b go acc (NextBranch h t) = do { fh <- f acc h ; go fh t } -- zipWith brListZipWith :: (a -> b -> c) -> BranchList a br1 -> BranchList b br2 -> [c] brListZipWith f (FirstBranch a) (FirstBranch b) = [f a b] brListZipWith f (FirstBranch a) (NextBranch b _) = [f a b] brListZipWith f (NextBranch a _) (FirstBranch b) = [f a b] brListZipWith f (NextBranch a ta) (NextBranch b tb) = f a b : brListZipWith f ta tb -- pretty-printing instance Outputable a => Outputable (BranchList a br) where ppr = ppr . fromBranchList {- ************************************************************************ * * Coercion axioms * * ************************************************************************ Note [Storing compatibility] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ During axiom application, we need to be aware of which branches are compatible with which others. The full explanation is in Note [Compatibility] in FamInstEnv. (The code is placed there to avoid a dependency from CoAxiom on the unification algorithm.) Although we could theoretically compute compatibility on the fly, this is silly, so we store it in a CoAxiom. Specifically, each branch refers to all other branches with which it is incompatible. This list might well be empty, and it will always be for the first branch of any axiom. CoAxBranches that do not (yet) belong to a CoAxiom should have a panic thunk stored in cab_incomps. The incompatibilities are properly a property of the axiom as a whole, and they are computed only when the final axiom is built. During serialization, the list is converted into a list of the indices of the branches. -} -- | A 'CoAxiom' is a \"coercion constructor\", i.e. a named equality axiom. -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data CoAxiom br = CoAxiom -- Type equality axiom. { co_ax_unique :: Unique -- unique identifier , co_ax_name :: Name -- name for pretty-printing , co_ax_role :: Role -- role of the axiom's equality , co_ax_tc :: TyCon -- the head of the LHS patterns , co_ax_branches :: BranchList CoAxBranch br -- the branches that form this axiom , co_ax_implicit :: Bool -- True <=> the axiom is "implicit" -- See Note [Implicit axioms] -- INVARIANT: co_ax_implicit == True implies length co_ax_branches == 1. } deriving Typeable data CoAxBranch = CoAxBranch { cab_loc :: SrcSpan -- Location of the defining equation -- See Note [CoAxiom locations] , cab_tvs :: [TyVar] -- Bound type variables; not necessarily fresh -- See Note [CoAxBranch type variables] , cab_roles :: [Role] -- See Note [CoAxBranch roles] , cab_lhs :: [Type] -- Type patterns to match against , cab_rhs :: Type -- Right-hand side of the equality , cab_incomps :: [CoAxBranch] -- The previous incompatible branches -- See Note [Storing compatibility] } deriving ( Data.Data, Data.Typeable ) toBranchedAxiom :: CoAxiom br -> CoAxiom Branched toBranchedAxiom (CoAxiom unique name role tc branches implicit) = CoAxiom unique name role tc (toBranchedList branches) implicit toUnbranchedAxiom :: CoAxiom br -> CoAxiom Unbranched toUnbranchedAxiom (CoAxiom unique name role tc branches implicit) = CoAxiom unique name role tc (toUnbranchedList branches) implicit coAxiomNumPats :: CoAxiom br -> Int coAxiomNumPats = length . coAxBranchLHS . (flip coAxiomNthBranch 0) coAxiomNthBranch :: CoAxiom br -> BranchIndex -> CoAxBranch coAxiomNthBranch (CoAxiom { co_ax_branches = bs }) index = brListNth bs index coAxiomArity :: CoAxiom br -> BranchIndex -> Arity coAxiomArity ax index = length $ cab_tvs $ coAxiomNthBranch ax index coAxiomName :: CoAxiom br -> Name coAxiomName = co_ax_name coAxiomRole :: CoAxiom br -> Role coAxiomRole = co_ax_role coAxiomBranches :: CoAxiom br -> BranchList CoAxBranch br coAxiomBranches = co_ax_branches coAxiomSingleBranch_maybe :: CoAxiom br -> Maybe CoAxBranch coAxiomSingleBranch_maybe (CoAxiom { co_ax_branches = branches }) | FirstBranch br <- branches = Just br | otherwise = Nothing coAxiomSingleBranch :: CoAxiom Unbranched -> CoAxBranch coAxiomSingleBranch (CoAxiom { co_ax_branches = FirstBranch br }) = br coAxiomTyCon :: CoAxiom br -> TyCon coAxiomTyCon = co_ax_tc coAxBranchTyVars :: CoAxBranch -> [TyVar] coAxBranchTyVars = cab_tvs coAxBranchLHS :: CoAxBranch -> [Type] coAxBranchLHS = cab_lhs coAxBranchRHS :: CoAxBranch -> Type coAxBranchRHS = cab_rhs coAxBranchRoles :: CoAxBranch -> [Role] coAxBranchRoles = cab_roles coAxBranchSpan :: CoAxBranch -> SrcSpan coAxBranchSpan = cab_loc isImplicitCoAxiom :: CoAxiom br -> Bool isImplicitCoAxiom = co_ax_implicit coAxBranchIncomps :: CoAxBranch -> [CoAxBranch] coAxBranchIncomps = cab_incomps -- See Note [Compatibility checking] in FamInstEnv placeHolderIncomps :: [CoAxBranch] placeHolderIncomps = panic "placeHolderIncomps" {- Note [CoAxBranch type variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the case of a CoAxBranch of an associated type-family instance, we use the *same* type variables (where possible) as the enclosing class or instance. Consider class C a b where type F x b type F [y] b = ... -- Second param must be b instance C Int [z] where type F Int [z] = ... -- Second param must be [z] In the CoAxBranch in the instance decl (F Int [z]) we use the same 'z', so that it's easy to check that that type is the same as that in the instance header. Similarly in the CoAxBranch for the default decl for F in the class decl, we use the same 'b' to make the same check easy. So, unlike FamInsts, there is no expectation that the cab_tvs are fresh wrt each other, or any other CoAxBranch. Note [CoAxBranch roles] ~~~~~~~~~~~~~~~~~~~~~~~ Consider this code: newtype Age = MkAge Int newtype Wrap a = MkWrap a convert :: Wrap Age -> Int convert (MkWrap (MkAge i)) = i We want this to compile to: NTCo:Wrap :: forall a. Wrap a ~R a NTCo:Age :: Age ~R Int convert = \x -> x |> (NTCo:Wrap[0] NTCo:Age[0]) But, note that NTCo:Age is at role R. Thus, we need to be able to pass coercions at role R into axioms. However, we don't *always* want to be able to do this, as it would be disastrous with type families. The solution is to annotate the arguments to the axiom with roles, much like we annotate tycon tyvars. Where do these roles get set? Newtype axioms inherit their roles from the newtype tycon; family axioms are all at role N. Note [CoAxiom locations] ~~~~~~~~~~~~~~~~~~~~~~~~ The source location of a CoAxiom is stored in two places in the datatype tree. * The first is in the location info buried in the Name of the CoAxiom. This span includes all of the branches of a branched CoAxiom. * The second is in the cab_loc fields of the CoAxBranches. In the case of a single branch, we can extract the source location of the branch from the name of the CoAxiom. In other cases, we need an explicit SrcSpan to correctly store the location of the equation giving rise to the FamInstBranch. Note [Implicit axioms] ~~~~~~~~~~~~~~~~~~~~~~ See also Note [Implicit TyThings] in HscTypes * A CoAxiom arising from data/type family instances is not "implicit". That is, it has its own IfaceAxiom declaration in an interface file * The CoAxiom arising from a newtype declaration *is* "implicit". That is, it does not have its own IfaceAxiom declaration in an interface file; instead the CoAxiom is generated by type-checking the newtype declaration -} instance Eq (CoAxiom br) where a == b = case (a `compare` b) of { EQ -> True; _ -> False } a /= b = case (a `compare` b) of { EQ -> False; _ -> True } instance Ord (CoAxiom br) where a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False } a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False } a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True } a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True } compare a b = getUnique a `compare` getUnique b instance Uniquable (CoAxiom br) where getUnique = co_ax_unique instance Outputable (CoAxiom br) where ppr = ppr . getName instance NamedThing (CoAxiom br) where getName = co_ax_name instance Typeable br => Data.Data (CoAxiom br) where -- don't traverse? toConstr _ = abstractConstr "CoAxiom" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "CoAxiom" {- ************************************************************************ * * Roles * * ************************************************************************ Roles are defined here to avoid circular dependencies. -} -- See Note [Roles] in Coercion -- defined here to avoid cyclic dependency with Coercion data Role = Nominal | Representational | Phantom deriving (Eq, Data.Data, Data.Typeable) -- These names are slurped into the parser code. Changing these strings -- will change the **surface syntax** that GHC accepts! If you want to -- change only the pretty-printing, do some replumbing. See -- mkRoleAnnotDecl in RdrHsSyn fsFromRole :: Role -> FastString fsFromRole Nominal = fsLit "nominal" fsFromRole Representational = fsLit "representational" fsFromRole Phantom = fsLit "phantom" instance Outputable Role where ppr = ftext . fsFromRole instance Binary Role where put_ bh Nominal = putByte bh 1 put_ bh Representational = putByte bh 2 put_ bh Phantom = putByte bh 3 get bh = do tag <- getByte bh case tag of 1 -> return Nominal 2 -> return Representational 3 -> return Phantom _ -> panic ("get Role " ++ show tag) {- ************************************************************************ * * CoAxiomRule Rules for building Evidence * * ************************************************************************ Conditional axioms. The general idea is that a `CoAxiomRule` looks like this: forall as. (r1 ~ r2, s1 ~ s2) => t1 ~ t2 My intention is to reuse these for both (~) and (~#). The short-term plan is to use this datatype to represent the type-nat axioms. In the longer run, it may be good to unify this and `CoAxiom`, as `CoAxiom` is the special case when there are no assumptions. -} -- | A more explicit representation for `t1 ~ t2`. type Eqn = Pair Type -- | For now, we work only with nominal equality. data CoAxiomRule = CoAxiomRule { coaxrName :: FastString , coaxrTypeArity :: Int -- number of type argumentInts , coaxrAsmpRoles :: [Role] -- roles of parameter equations , coaxrRole :: Role -- role of resulting equation , coaxrProves :: [Type] -> [Eqn] -> Maybe Eqn -- ^ coaxrProves returns @Nothing@ when it doesn't like -- the supplied arguments. When this happens in a coercion -- that means that the coercion is ill-formed, and Core Lint -- checks for that. } deriving Typeable instance Data.Data CoAxiomRule where -- don't traverse? toConstr _ = abstractConstr "CoAxiomRule" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "CoAxiomRule" instance Uniquable CoAxiomRule where getUnique = getUnique . coaxrName instance Eq CoAxiomRule where x == y = coaxrName x == coaxrName y instance Ord CoAxiomRule where compare x y = compare (coaxrName x) (coaxrName y) instance Outputable CoAxiomRule where ppr = ppr . coaxrName -- Type checking of built-in families data BuiltInSynFamily = BuiltInSynFamily { sfMatchFam :: [Type] -> Maybe (CoAxiomRule, [Type], Type) , sfInteractTop :: [Type] -> Type -> [Eqn] , sfInteractInert :: [Type] -> Type -> [Type] -> Type -> [Eqn] } -- Provides default implementations that do nothing. trivialBuiltInFamily :: BuiltInSynFamily trivialBuiltInFamily = BuiltInSynFamily { sfMatchFam = \_ -> Nothing , sfInteractTop = \_ _ -> [] , sfInteractInert = \_ _ _ _ -> [] }
anton-dessiatov/ghc
compiler/types/CoAxiom.hs
Haskell
bsd-3-clause
20,190
module Abs () where absN :: (Num a, Ord a) => a -> a absN x = if x > 0 then x else (-x) absI :: Int -> Int absI x = if x > 0 then x else (-x) --incI :: Int -> Int --incI = (+) 1 x0 = absN 4 x1 = absI (-5) --x2 = absI (incI 2) -- x3 = absI (-3)
mightymoose/liquidhaskell
tests/pos/Abs.hs
Haskell
bsd-3-clause
254
module Blank where {-@ LIQUID "--no-termination" @-} data Vec a = V (Int -> a) {-@ data Vec a < dom :: Int -> Prop, rng :: Int -> a -> Prop > = V {a :: i:Int<dom> -> a <rng i>} @-} {-@ empty :: forall <p :: Int -> a -> Prop>. Vec <{v:Int|0=1}, p> a @-} empty = V $ \_ -> error "empty vector!" {-@ set :: forall a <d :: Int -> Prop, r :: Int -> a -> Prop>. key: Int<d> -> val: a<r key> -> vec: Vec<{v:Int<d>| v /= key},r> a -> Vec <d, r> a @-} set key val (V f) = V $ \k -> if k == key then val else f k {- loop :: forall a <p :: Int -> a -> Prop>. lo:Int -> hi:{Int | lo <= hi} -> base:a<p lo> -> f:(i:Int -> a<p i> -> a<p (i+1)>) -> a<p hi> @-} -- loop :: Int -> Int -> a -> (Int -> a -> a) -> a -- loop lo hi base f = go lo base -- where -- go i acc -- | i < hi = go (i+1) (f i acc) -- | otherwise = acc {-@ loop :: forall a <p :: Int -> a -> Prop>. lo:Nat -> hi:{Nat | lo <= hi} -> base:Vec <{v:Nat | (v < lo)}, p> a -> f:(i:Nat -> Vec <{v:Nat | v < i}, p> a -> Vec <{v:Nat | v < i+1}, p> a) -> Vec <{v:Nat | v < hi}, p> a @-} loop :: Int -> Int -> Vec a -> (Int -> Vec a -> Vec a) -> Vec a loop lo hi base f = go lo base where go i acc | i < hi = go (i+1) (f i acc) | otherwise = acc {-@ predicate Seg V I J = (I <= V && V < J) @-} {-@ type IdVec N = Vec <{\v -> (Seg v 0 N)}, {\k v -> v=k}> Int @-} {-@ initUpto :: n:Nat -> (IdVec n) @-} initUpto n = loop 0 n empty (\i acc -> set i i acc) {-@ qualif Foo(v:Int): v < 0 @-}
mightymoose/liquidhaskell
tests/pos/vecloop.hs
Haskell
bsd-3-clause
1,844
-- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you 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. -- {-# OPTIONS_GHC -fno-warn-orphans #-} module Thrift.Types where import Data.ByteString.Lazy (ByteString) import Data.Foldable (foldl') import Data.Hashable ( Hashable, hashWithSalt ) import Data.Int import Test.QuickCheck.Arbitrary import Test.QuickCheck.Gen (elements) import Data.Text.Lazy (Text) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector instance (Hashable k, Hashable v) => Hashable (Map.HashMap k v) where hashWithSalt salt = foldl' hashWithSalt salt . Map.toList instance (Hashable a) => Hashable (Set.HashSet a) where hashWithSalt = foldl' hashWithSalt instance (Hashable a) => Hashable (Vector.Vector a) where hashWithSalt = Vector.foldl' hashWithSalt -- | Map from field key to field id and type in a Thrift Struct type TypeMap = Map.HashMap Text (Int16, ThriftType) -- | Definition of a generic Thrift value. This is the internal represention -- inside the Thrift library. The client sees the autogenerated record type and -- the Thrift Compiler generates code to convert between the record type and the -- more generic 'ThriftVal' data ThriftVal = TStruct (Map.HashMap Int16 (Text, ThriftVal)) | TMap ThriftType ThriftType [(ThriftVal, ThriftVal)] | TList ThriftType [ThriftVal] | TSet ThriftType [ThriftVal] | TBool Bool | TByte Int8 -- ^ 'TByte' is a signed integer for compatibility with other -- languages | TI16 Int16 | TI32 Int32 | TI64 Int64 | TString ByteString -- ^ 8-bit characters are sufficient since that is what other -- languages use | TFloat Float | TDouble Double deriving (Eq, Show) -- | Type information is needed for collection types (ie 'T_STRUCT', 'T_MAP', -- 'T_LIST', and 'T_SET') so that we know what types those collections are -- parameterized by. In most protocols, this cannot be discerned directly -- from the data being read. data ThriftType = T_STOP | T_VOID | T_BOOL | T_BYTE | T_DOUBLE | T_I16 | T_I32 | T_I64 | T_STRING | T_STRUCT TypeMap | T_MAP ThriftType ThriftType | T_SET ThriftType | T_LIST ThriftType | T_FLOAT deriving ( Eq, Show ) -- | NOTE: when using toEnum information about parametized types is NOT -- preserved. This design choice is consistent with the Thrift implementation -- in other languages instance Enum ThriftType where fromEnum T_STOP = 0 fromEnum T_VOID = 1 fromEnum T_BOOL = 2 fromEnum T_BYTE = 3 fromEnum T_DOUBLE = 4 fromEnum T_I16 = 6 fromEnum T_I32 = 8 fromEnum T_I64 = 10 fromEnum T_STRING = 11 fromEnum (T_STRUCT _) = 12 fromEnum (T_MAP _ _) = 13 fromEnum (T_SET _) = 14 fromEnum (T_LIST _) = 15 fromEnum T_FLOAT = 19 toEnum 0 = T_STOP toEnum 1 = T_VOID toEnum 2 = T_BOOL toEnum 3 = T_BYTE toEnum 4 = T_DOUBLE toEnum 6 = T_I16 toEnum 8 = T_I32 toEnum 10 = T_I64 toEnum 11 = T_STRING toEnum 12 = T_STRUCT Map.empty toEnum 13 = T_MAP T_VOID T_VOID toEnum 14 = T_SET T_VOID toEnum 15 = T_LIST T_VOID toEnum 19 = T_FLOAT toEnum t = error $ "Invalid ThriftType " ++ show t data MessageType = M_CALL | M_REPLY | M_EXCEPTION deriving ( Eq, Show ) instance Enum MessageType where fromEnum M_CALL = 1 fromEnum M_REPLY = 2 fromEnum M_EXCEPTION = 3 toEnum 1 = M_CALL toEnum 2 = M_REPLY toEnum 3 = M_EXCEPTION toEnum t = error $ "Invalid MessageType " ++ show t instance Arbitrary MessageType where arbitrary = elements [M_CALL, M_REPLY, M_EXCEPTION]
guker/fbthrift
thrift/lib/hs/Thrift/Types.hs
Haskell
apache-2.0
4,679
module Cmm.X86.InstrCore where import Cmm.LabelGenerator import Data.Int import Text.Printf -- | bypassing non exisiting module system of haskell data X86CodeGen = X86CodeGen data SizeDirective = BYTE | WORD | DWORD | QWORD -- 64 bit won't be supported for the time being deriving (Eq, Ord) instance Show SizeDirective where show BYTE = "BYTE" show WORD = "WORD" show DWORD = "DWORD PTR" show QWORD = "QWORD PTR" data UnaryInstr = PUSH | POP | NEG | NOT | INC | DEC | IDIV deriving (Eq, Ord) instance Show UnaryInstr where show PUSH = "push" show POP = "pop" show NEG = "neg" show NOT = "not" show INC = "inc" show DEC = "dec" show IDIV = "idiv" data BinayInstr = MOV | ADD | SUB | SHL | SHR | SAL | SAR | AND | OR | XOR | TEST | CMP | LEA | IMUL deriving (Eq, Ord) instance Show BinayInstr where show MOV = "mov" show ADD = "add" show SUB = "sub" show SHL = "shl" show SAL = "sal" show SAR = "sar" show AND = "and" show OR = "or" show XOR = "xor" show TEST = "test" show CMP = "cmp" show LEA = "lea" show IMUL = "imul" data Cond = E | NE | L | LE | G | GE | Z deriving (Eq, Ord) -- used with 'j' prefix instance Show Cond where show E = "e" show NE = "ne" show L = "l" show LE = "le" show G = "g" show GE = "ge" show Z = "z" data Scale = S2 | S4 | S8 -- possible scaling values for effective addressing deriving (Eq, Ord, Show) scaleToInt :: Scale -> Int32 scaleToInt S2 = 2 scaleToInt S4 = 4 scaleToInt S8 = 8 data EffectiveAddress = EffectiveAddress { base :: Maybe Temp , indexScale :: Maybe (Temp, Scale) , displacement :: Int32 } deriving (Eq, Ord) data Operand = Imm Int32 | Reg Temp | Mem EffectiveAddress deriving (Eq, Ord) data X86Instr = Unary UnaryInstr (Maybe SizeDirective, Operand) | Binary BinayInstr (Maybe SizeDirective, Operand) (Maybe SizeDirective, Operand) | LABEL Label | CDQ | JMP Label | J Cond Label | CALL Label | RET | NOP deriving (Eq, Ord) data X86Comment = X86Comment String deriving (Eq, Ord) comment :: String -> X86Comment comment = X86Comment emptyComment :: X86Comment emptyComment = comment "" instance Show X86Comment where show (X86Comment c) = "# " ++ c data X86Func = X86Func { x86functionName :: String , x86body :: [X86Instr] , x86comments :: [X86Comment] , x86spilledCount :: Int32 } deriving (Eq, Ord) data X86Prog = X86Prog { x86functions :: [X86Func] } deriving (Eq, Ord) instance Show X86Prog where show p = concat ["\t.intel_syntax noprefix\n\t", ".global Lmain\n"] ++ concatMap (\x -> show x ++ "\n") (x86functions p) instance Show X86Func where show f = x86functionName f ++ ":\n\t" ++ concatMap (\x -> x ++ "\n\t") body where body :: [String] body = zipWith (\x c -> printf "%-35s %s" (show x) (show c)) (x86body f) (x86comments f) instance Show X86Instr where show (Unary u (s,o)) = show u ++ maybe "" (\x -> ' ' : show x) s ++ ' ' : show o show (Binary b (s1, o1) (s2, o2)) = show b ++ maybe "" (\x -> ' ' : show x) s1 ++ ' ' : show o1 ++ ", "++ maybe "" (\x -> ' ' : show x) s2 ++ ' ' : show o2 show (LABEL l) = l ++ ":" show RET = "ret" show CDQ = "cdq" show (JMP l) = "jmp " ++ l show (J cond l) = "j" ++ show cond ++ " " ++ l show (CALL l) = "call " ++ l show NOP = "" instance Show Operand where show (Reg t) = show t show (Imm i32) = show i32 show (Mem ea) = show ea instance Show EffectiveAddress where show ea = let c = show (displacement ea) in case (base ea, indexScale ea) of (Just bt, Just (t, s)) -> "[" ++ show bt ++ " + " ++ show t ++ "*" ++ show s ++ " + " ++ c ++ "]" (_, Just (t, s)) -> "[" ++ show t ++ "*" ++ show s ++ " + " ++ c ++ "]" (Just bt, _) -> case displacement ea of 0 -> "[" ++ show bt ++ "]" _ -> "[" ++ show bt ++ " + " ++ c ++ "]" (_, _) -> "[" ++ c ++ "]" -- | Registers -- -- base pointer (register) ebp :: Operand ebp = Reg ebpT ebpT :: Temp ebpT = mkNamedTemp "%ebp" -- stack pointer (register) esp :: Operand esp = Reg espT espT :: Temp espT = mkNamedTemp "%esp" -- return register eax :: Operand eax = Reg eaxT eaxT :: Temp eaxT = mkNamedTemp "%eax" ebx :: Operand ebx = Reg ebxT ebxT :: Temp ebxT = mkNamedTemp "%ebx" -- math register (used for mathematic expressions) ecx :: Operand ecx = Reg ecxT ecxT :: Temp ecxT = mkNamedTemp "%ecx" -- used to move the first argument to edx if not already a register edx :: Operand edx = Reg edxT edxT :: Temp edxT = mkNamedTemp "%edx" edi :: Operand edi = Reg ediT ediT :: Temp ediT = mkNamedTemp "%edi" esi :: Operand esi = Reg esiT esiT :: Temp esiT = mkNamedTemp "%esi"
cirquit/hjc
src/Cmm/X86/InstrCore.hs
Haskell
mit
5,446
-- Part 1 module Session4.Recursion (test) where import Prelude ((+), (*), Bool(..), Double, IO, Int, return) -- | empty a.k.a. null -- Examples: -- >>> empty [] -- True -- >>> empty [1, 2, 3, 4] -- False empty :: [a] -> Bool empty [] = True empty _ = False -- | map -- Examples: -- >>> map (+100) [] -- [] -- >>> map (+100) [1, 2, 3, 4] -- [101,102,103,104] map :: (a -> b) -> [a] -> [b] map _ [] = [] map f (x : xs) = f x : map f xs -- | len a.k.a. length -- Examples: -- >>> len [] -- 0 -- >>> len [1, 2, 3, 4] -- 4 len :: [a] -> Int len [] = 0 len (_ : xs) = 1 + len xs -- | sum -- Examples: -- >>> sum [] -- 0 -- >>> sum [1, 2, 3, 4] -- 10 sum :: [Int] -> Int sum [] = 0 sum (x : xs) = (+) x (sum xs) -- | product -- Examples: -- >>> product [] -- 1.0 -- >>> product [1, 2, 3, 4] -- 24.0 product :: [Double] -> Double product [] = 1 product (x : xs) = (*) x (product xs) -- | foldr -- Examples: -- >>> foldr (+) 0 [1, 2, 3, 4] -- 10 -- >>> foldr (*) 1 [1, 2, 3, 4] -- 24 foldr :: (a -> b -> b) -> b -> [a] -> b foldr _ z [] = z foldr f z (x : xs) = f x (foldr f z xs) test :: IO () test = do let _ = foldr (+) (0 :: Int) [1, 2, 3, 4] _ = empty ([1, 2, 3, 4] :: [Int]) _ = len ([1, 2, 3, 4] :: [Int]) _ = map (+100) [] :: [Int] _ = sum [1, 2, 3, 4] _ = product [1, 2, 3, 4] return ()
seahug/pcph-scratch
src/Session4/Recursion.hs
Haskell
mit
1,346
module Latte.FrontEnd.Spec (main, spec) where import Test.Hspec import qualified Latte.FrontEnd.MainFunctionPresenceSpec import qualified Latte.FrontEnd.FunctionNameDuplicationSpec import qualified Latte.FrontEnd.TypeCheckSpec import qualified Latte.FrontEnd.VariableDeclaredSpec main :: IO () main = hspec spec spec :: Spec spec = do describe "Main function presence" Latte.FrontEnd.MainFunctionPresenceSpec.spec describe "Function name duplication" Latte.FrontEnd.FunctionNameDuplicationSpec.spec describe "Type check" Latte.FrontEnd.TypeCheckSpec.spec describe "Are variables/names declared" Latte.FrontEnd.VariableDeclaredSpec.spec
mpsk2/LatteCompiler
testsuite/tests/Latte/FrontEnd/Spec.hs
Haskell
mit
657
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE CPP #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} module Database.Persist.Sql.Types ( module Database.Persist.Sql.Types , SqlBackend (..), SqlReadBackend (..), SqlWriteBackend (..) , Statement (..), LogFunc, InsertSqlResult (..) , readToUnknown, readToWrite, writeToUnknown , SqlBackendCanRead, SqlBackendCanWrite, SqlReadT, SqlWriteT, IsSqlBackend ) where import Control.Exception (Exception) import Control.Monad.Trans.Resource (ResourceT) import Data.Acquire (Acquire) import Control.Monad.Logger (NoLoggingT) import Control.Monad.IO.Class (MonadIO (..)) import Control.Monad.Trans.Reader (ReaderT (..)) import Control.Monad.Trans.Writer (WriterT) import Data.Typeable (Typeable) import Database.Persist.Types import Database.Persist.Sql.Types.Internal import Data.IORef (IORef) import Data.Map (Map) import Data.Int (Int64) import Data.Conduit (Source) import Data.Pool (Pool) import Language.Haskell.TH.Syntax (Loc) import Control.Monad.Logger (LogSource, LogLevel) import System.Log.FastLogger (LogStr) import Data.Text (Text) -- | Deprecated synonym for @SqlBackend@. type Connection = SqlBackend {-# DEPRECATED Connection "Please use SqlBackend instead" #-} data Column = Column { cName :: !DBName , cNull :: !Bool , cSqlType :: !SqlType , cDefault :: !(Maybe Text) , cDefaultConstraintName :: !(Maybe DBName) , cMaxLen :: !(Maybe Integer) , cReference :: !(Maybe (DBName, DBName)) -- table name, constraint name } deriving (Eq, Ord, Show) data PersistentSqlException = StatementAlreadyFinalized Text | Couldn'tGetSQLConnection deriving (Typeable, Show) instance Exception PersistentSqlException type SqlPersistT = ReaderT SqlBackend type SqlPersist = SqlPersistT {-# DEPRECATED SqlPersist "Please use SqlPersistT instead" #-} type SqlPersistM = SqlPersistT (NoLoggingT (ResourceT IO)) type Sql = Text -- Bool indicates if the Sql is safe type CautiousMigration = [(Bool, Sql)] type Migration = WriterT [Text] (WriterT CautiousMigration (ReaderT SqlBackend IO)) () type ConnectionPool = Pool SqlBackend -- $rawSql -- -- Although it covers most of the useful cases, @persistent@'s -- API may not be enough for some of your tasks. May be you need -- some complex @JOIN@ query, or a database-specific command -- needs to be issued. -- -- To issue raw SQL queries, use 'rawSql'. It does all the hard work of -- automatically parsing the rows of the result. It may return: -- -- * An 'Entity', that which 'selectList' returns. -- All of your entity's fields are -- automatically parsed. -- -- * A @'Single' a@, which is a single, raw column of type @a@. -- You may use a Haskell type (such as in your entity -- definitions), for example @Single Text@ or @Single Int@, -- or you may get the raw column value with @Single -- 'PersistValue'@. -- -- * A tuple combining any of these (including other tuples). -- Using tuples allows you to return many entities in one -- query. -- -- The only difference between issuing SQL queries with 'rawSql' -- and using other means is that we have an /entity selection/ -- /placeholder/, the double question mark @??@. It /must/ be -- used whenever you want to @SELECT@ an 'Entity' from your -- query. Here's a sample SQL query @sampleStmt@ that may be -- issued: -- -- @ -- SELECT ??, ?? -- FROM \"Person\", \"Likes\", \"Object\" -- WHERE \"Person\".id = \"Likes\".\"personId\" -- AND \"Object\".id = \"Likes\".\"objectId\" -- AND \"Person\".name LIKE ? -- @ -- -- To use that query, you could say -- -- @ -- do results <- 'rawSql' sampleStmt [\"%Luke%\"] -- forM_ results $ -- \\( Entity personKey person -- , Entity objectKey object -- ) -> do ... -- @ -- -- Note that 'rawSql' knows how to replace the double question -- marks @??@ because of the type of the @results@. -- | A single column (see 'rawSql'). Any 'PersistField' may be -- used here, including 'PersistValue' (which does not do any -- processing). newtype Single a = Single {unSingle :: a} deriving (Eq, Ord, Show, Read)
pseudonom/persistent
persistent/Database/Persist/Sql/Types.hs
Haskell
mit
4,437
module Glucose.Codegen.JavaScript (codegen) where import Control.Comonad import Control.Lens import Control.Monad.RWS import Data.Foldable (toList) import Data.Set as Set (Set, fromList, empty, insert, delete, member) import Data.Text (Text, pack, unpack) import Glucose.Identifier import Glucose.IR data JSRaw = JSRaw Text instance Show JSRaw where show (JSRaw s) = unpack s type Codegen = RWS () Text (Set Identifier, Set Identifier) execCodegen :: Set Identifier -> Codegen a -> JSRaw execCodegen vars m = JSRaw . snd $ evalRWS m () (empty, vars) codegen :: Module Checked -> JSRaw codegen (Module defs) = execCodegen vars $ mapAttemptM_ attemptToDefine (map extract defs) where vars = Set.fromList $ map identifier (toList defs) attemptToDefine def = maybe (pure False) ((True <$) . tell) =<< definition def mapAttemptM_ :: Monad m => (a -> m Bool) -> [a] -> m () mapAttemptM_ _ [] = pure () mapAttemptM_ f as = deleteWhen f as >>= mapAttemptM_ f deleteWhen :: Monad m => (a -> m Bool) -> [a] -> m [a] deleteWhen _ [] = pure [] deleteWhen f as = go as where go [] = error "Recursive aliases in codegen?" go (a:as) = do shouldDelete <- f a if shouldDelete then pure as else (a:) <$> go as definition :: Definition Checked -> Codegen (Maybe Text) definition (Definition (extract -> Identifier name) (extract -> Reference Global (Identifier target) _)) = do targetUndefined <- uses _2 (Set.member $ Identifier target) if targetUndefined then pure Nothing else do _2 %= delete (Identifier name) pure . Just $ name <> " = " <> target <> "\n" definition (Definition (extract -> Identifier name) def) = do _2 %= delete (Identifier name) expr <- expression (extract def) pure . Just $ name <> " = " <> expr <> "\n" expression :: Expression Checked -> Codegen Text expression (Literal a) = pure . pack $ show a expression (Reference _ (Identifier a) _) = pure a expression (Constructor (extract -> typeName) _) = do typeDefined <- uses _1 (Set.member typeName) unless typeDefined $ do _1 %= Set.insert typeName tell $ typeDefinition typeName pure $ "new " <> identify typeName <> "()" typeDefinition :: Identifier -> Text typeDefinition (Identifier typeName) = typeName <> " = function() {}\n"
sardonicpresence/glucose
src/Glucose/Codegen/Javascript.hs
Haskell
mit
2,323
-- (Ready for) Prime Time -- http://www.codewars.com/kata/521ef596c106a935c0000519/ module PrimeTime where prime :: Int -> [Int] prime n = takeWhile (<= n) . sieve $ [2..] where sieve (n:ns) = n : sieve [n' | n' <- ns, n' `mod` n /= 0]
gafiatulin/codewars
src/5 kyu/PrimeTime.hs
Haskell
mit
242
import Data.Aeson import Test.Tasty import Test.Tasty.QuickCheck as QC import Pulmurice.Common.Message main :: IO () main = defaultMain qcProps requestMessageProp :: ReqMsg -> Property requestMessageProp msg = Just msg === decode (encode msg) responseMessageProp :: ResMsg -> Property responseMessageProp msg = Just msg === decode (encode msg) qcProps :: TestTree qcProps = testGroup "QuickCheck properties" [ QC.testProperty "ReqMsg: decode . encode = id" requestMessageProp , QC.testProperty "ResMsg: decode . encode = id" responseMessageProp ]
futurice/pulmurice-common
tests/Tests.hs
Haskell
mit
558
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.EventSource (js_newEventSource, newEventSource, js_close, close, pattern CONNECTING, pattern OPEN, pattern CLOSED, js_getUrl, getUrl, js_getWithCredentials, getWithCredentials, js_getReadyState, getReadyState, open, message, error, EventSource, castToEventSource, gTypeEventSource) 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[\"EventSource\"]($1,\n$2)" js_newEventSource :: JSString -> JSRef Dictionary -> IO (JSRef EventSource) -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource Mozilla EventSource documentation> newEventSource :: (MonadIO m, ToJSString url, IsDictionary eventSourceInit) => url -> Maybe eventSourceInit -> m EventSource newEventSource url eventSourceInit = liftIO (js_newEventSource (toJSString url) (maybe jsNull (unDictionary . toDictionary) eventSourceInit) >>= fromJSRefUnchecked) foreign import javascript unsafe "$1[\"close\"]()" js_close :: JSRef EventSource -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.close Mozilla EventSource.close documentation> close :: (MonadIO m) => EventSource -> m () close self = liftIO (js_close (unEventSource self)) pattern CONNECTING = 0 pattern OPEN = 1 pattern CLOSED = 2 foreign import javascript unsafe "$1[\"url\"]" js_getUrl :: JSRef EventSource -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.url Mozilla EventSource.url documentation> getUrl :: (MonadIO m, FromJSString result) => EventSource -> m result getUrl self = liftIO (fromJSString <$> (js_getUrl (unEventSource self))) foreign import javascript unsafe "($1[\"withCredentials\"] ? 1 : 0)" js_getWithCredentials :: JSRef EventSource -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.withCredentials Mozilla EventSource.withCredentials documentation> getWithCredentials :: (MonadIO m) => EventSource -> m Bool getWithCredentials self = liftIO (js_getWithCredentials (unEventSource self)) foreign import javascript unsafe "$1[\"readyState\"]" js_getReadyState :: JSRef EventSource -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.readyState Mozilla EventSource.readyState documentation> getReadyState :: (MonadIO m) => EventSource -> m Word getReadyState self = liftIO (js_getReadyState (unEventSource self)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.onopen Mozilla EventSource.onopen documentation> open :: EventName EventSource Event open = unsafeEventName (toJSString "open") -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.onmessage Mozilla EventSource.onmessage documentation> message :: EventName EventSource MessageEvent message = unsafeEventName (toJSString "message") -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.onerror Mozilla EventSource.onerror documentation> error :: EventName EventSource UIEvent error = unsafeEventName (toJSString "error")
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/EventSource.hs
Haskell
mit
3,934
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} import qualified Data.ByteString.Lazy as L import Data.ByteString.Builder import Database.Redis import Control.Monad.IO.Class (liftIO) import System.IO import Data.Monoid((<>)) import Data.Foldable import Data.List import qualified Text.ProtocolBuffers.Basic as P import qualified Text.ProtocolBuffers.TextMessage as P import qualified Text.ProtocolBuffers.WireMessage as P import Text.ProtocolBuffers (defaultValue) import Data.Test.Foo as Foo import Data.Test.Bar as Bar import Control.Concurrent import Control.Concurrent.Async connInfo :: ConnectInfo connInfo = defaultConnectInfo { connectPort = UnixSocket "/tmp/redis.sock" } renderString :: String -> Builder renderString cs = charUtf8 '"' <> foldMap escape cs <> charUtf8 '"' where escape '\\' = charUtf8 '\\' <> charUtf8 '\\' escape '\"' = charUtf8 '\\' <> charUtf8 '\"' escape c = charUtf8 c -- getData :: IO L.ByteString -- getData = do -- h <- openFile "data.txt" ReadMode -- r <- L.hGetContents h -- return r pub :: Connection -> IO () pub conn = runRedis conn $ do let b = defaultValue { Bar.wine = P.uFromString "Bubble", Bar.good = Just True } let bs = P.messagePut b r <- publish "testchan" (L.toStrict bs) liftIO $ putStrLn ("Sent: " ++ show r) liftIO $ threadDelay 1500000 publish "testchan" "quit" liftIO $ threadDelay 100000 main = do conn <- connect connInfo a1 <- async $ pub conn wait a1 -- return ()
hnfmr/test-hedis
src/Pub.hs
Haskell
mit
1,503
-- Copyright (c) 2016-present, SoundCloud Ltd. -- All rights reserved. -- -- This source code is distributed under the terms of a MIT license, -- found in the LICENSE file. {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} module Kubernetes.Model.V1.GCEPersistentDiskVolumeSource ( GCEPersistentDiskVolumeSource (..) , pdName , fsType , partition , readOnly , mkGCEPersistentDiskVolumeSource ) where import Control.Lens.TH (makeLenses) import Data.Aeson.TH (defaultOptions, deriveJSON, fieldLabelModifier) import Data.Text (Text) import GHC.Generics (Generic) import Prelude hiding (drop, error, max, min) import qualified Prelude as P import Test.QuickCheck (Arbitrary, arbitrary) import Test.QuickCheck.Instances () -- | Represents a Persistent Disk resource in Google Compute Engine.\n\nA GCE PD must exist and be formatted before mounting to a container. The disk must also be in the same GCE project and zone as the kubelet. A GCE PD can only be mounted as read/write once. GCE PDs support ownership management and SELinux relabeling. data GCEPersistentDiskVolumeSource = GCEPersistentDiskVolumeSource { _pdName :: !(Text) , _fsType :: !(Text) , _partition :: !(Maybe Integer) , _readOnly :: !(Maybe Bool) } deriving (Show, Eq, Generic) makeLenses ''GCEPersistentDiskVolumeSource $(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''GCEPersistentDiskVolumeSource) instance Arbitrary GCEPersistentDiskVolumeSource where arbitrary = GCEPersistentDiskVolumeSource <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary -- | Use this method to build a GCEPersistentDiskVolumeSource mkGCEPersistentDiskVolumeSource :: Text -> Text -> GCEPersistentDiskVolumeSource mkGCEPersistentDiskVolumeSource xpdNamex xfsTypex = GCEPersistentDiskVolumeSource xpdNamex xfsTypex Nothing Nothing
soundcloud/haskell-kubernetes
lib/Kubernetes/Model/V1/GCEPersistentDiskVolumeSource.hs
Haskell
mit
2,193
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} module Tests.Sodium.Stream.Common where import Tests.Sodium.Common () import Crypto.Sodium.SecureMem import Crypto.Sodium.Stream.Internal import Data.Bits import qualified Data.ByteString as B import Data.Maybe import Test.QuickCheck.Monadic as QM import Test.Tasty import Test.Tasty.QuickCheck mkTests :: forall t. StreamCipher t -> [TestTree] mkTests StreamCipher {..} = [ testProperty "encrypt decrypt" prop_EncryptDecrypt , testProperty "stream xor" prop_StreamXor , testProperty "mkKey" prop_mkKey , testProperty "mkNonce" prop_mkNonce , testProperty "randomKey" prop_randomKey ] where arbitraryKey :: Gen (Key t) arbitraryKey = fromJust . mkKey . fromByteString . B.pack <$> vector keyBytes arbitraryNonce :: Gen (Nonce t) arbitraryNonce = fromJust . mkNonce . B.pack <$> vector nonceBytes prop_EncryptDecrypt m = forAll arbitraryKey $ \k -> forAll arbitraryNonce $ \n -> m == streamXor k n (streamXor k n m) prop_StreamXor m = forAll arbitraryKey $ \k -> forAll arbitraryNonce $ \n -> streamXor k n m == B.pack (B.zipWith xor m $ stream k n $ B.length m) prop_mkKey = forAll arbitraryKey $ \k -> k == fromJust (mkKey $ unKey k) prop_mkNonce = forAll arbitraryNonce $ \n -> n == fromJust (mkNonce $ unNonce n) prop_randomKey = monadicIO $ do k <- run randomKey n <- pick arbitraryNonce m <- pick arbitrary QM.assert $ m == streamXor k n (streamXor k n m)
dnaq/crypto-sodium
test/Tests/Sodium/Stream/Common.hs
Haskell
mit
1,783
-- | -- Module : Data.Edison.Seq.BankersQueue -- Copyright : Copyright (c) 1998-1999, 2008 Chris Okasaki -- License : MIT; see COPYRIGHT file for terms and conditions -- -- Maintainer : robdockins AT fastmail DOT fm -- Stability : stable -- Portability : GHC, Hugs (MPTC and FD) -- -- This module implements Banker's Queues. It has the standard running -- times from "Data.Edison.Seq" except for the following: -- -- * rcons, size, inBounds @O( 1 )@ -- -- /References:/ -- -- * Chris Okasaki, /Purely Functional Data Structures/, -- 1998, sections 6.3.2 and 8.4.1. -- -- * Chris Okasaki, \"Simple and efficient purely functional -- queues and deques\", /Journal of Function Programming/ -- 5(4):583-592, October 1995. module Data.Edison.Seq.BankersQueue ( -- * Sequence Type Seq, -- instance of Sequence, Functor, Monad, MonadPlus -- * Sequence operations empty,singleton,lcons,rcons,append,lview,lhead,ltail,rview,rhead,rtail, lheadM,ltailM,rheadM,rtailM, null,size,concat,reverse,reverseOnto,fromList,toList,map,concatMap, fold,fold',fold1,fold1',foldr,foldr',foldl,foldl',foldr1,foldr1',foldl1,foldl1', reducer,reducer',reducel,reducel',reduce1,reduce1', copy,inBounds,lookup,lookupM,lookupWithDefault,update,adjust, mapWithIndex,foldrWithIndex,foldrWithIndex',foldlWithIndex,foldlWithIndex', take,drop,splitAt,subseq,filter,partition,takeWhile,dropWhile,splitWhile, zip,zip3,zipWith,zipWith3,unzip,unzip3,unzipWith,unzipWith3, strict, strictWith, -- * Unit testing structuralInvariant, -- * Documentation moduleName ) where import Prelude hiding (concat,reverse,map,concatMap,foldr,foldl,foldr1,foldl1, filter,takeWhile,dropWhile,lookup,take,drop,splitAt, zip,zip3,zipWith,zipWith3,unzip,unzip3,null) import qualified Control.Applicative as App import qualified Data.Edison.Seq as S ( Sequence(..) ) import Data.Edison.Seq.Defaults import qualified Data.Edison.Seq.ListSeq as L import Data.Monoid import Data.Semigroup as SG import Control.Monad.Identity import Test.QuickCheck -- signatures for exported functions moduleName :: String empty :: Seq a singleton :: a -> Seq a lcons :: a -> Seq a -> Seq a rcons :: a -> Seq a -> Seq a append :: Seq a -> Seq a -> Seq a lview :: (Monad m) => Seq a -> m (a, Seq a) lhead :: Seq a -> a lheadM :: (Monad m) => Seq a -> m a ltail :: Seq a -> Seq a ltailM :: (Monad m) => Seq a -> m (Seq a) rview :: (Monad m) => Seq a -> m (a, Seq a) rhead :: Seq a -> a rheadM :: (Monad m) => Seq a -> m a rtail :: Seq a -> Seq a rtailM :: (Monad m) => Seq a -> m (Seq a) null :: Seq a -> Bool size :: Seq a -> Int concat :: Seq (Seq a) -> Seq a reverse :: Seq a -> Seq a reverseOnto :: Seq a -> Seq a -> Seq a fromList :: [a] -> Seq a toList :: Seq a -> [a] map :: (a -> b) -> Seq a -> Seq b concatMap :: (a -> Seq b) -> Seq a -> Seq b fold :: (a -> b -> b) -> b -> Seq a -> b fold' :: (a -> b -> b) -> b -> Seq a -> b fold1 :: (a -> a -> a) -> Seq a -> a fold1' :: (a -> a -> a) -> Seq a -> a foldr :: (a -> b -> b) -> b -> Seq a -> b foldl :: (b -> a -> b) -> b -> Seq a -> b foldr1 :: (a -> a -> a) -> Seq a -> a foldl1 :: (a -> a -> a) -> Seq a -> a reducer :: (a -> a -> a) -> a -> Seq a -> a reducel :: (a -> a -> a) -> a -> Seq a -> a reduce1 :: (a -> a -> a) -> Seq a -> a foldr' :: (a -> b -> b) -> b -> Seq a -> b foldl' :: (b -> a -> b) -> b -> Seq a -> b foldr1' :: (a -> a -> a) -> Seq a -> a foldl1' :: (a -> a -> a) -> Seq a -> a reducer' :: (a -> a -> a) -> a -> Seq a -> a reducel' :: (a -> a -> a) -> a -> Seq a -> a reduce1' :: (a -> a -> a) -> Seq a -> a copy :: Int -> a -> Seq a inBounds :: Int -> Seq a -> Bool lookup :: Int -> Seq a -> a lookupM :: (Monad m) => Int -> Seq a -> m a lookupWithDefault :: a -> Int -> Seq a -> a update :: Int -> a -> Seq a -> Seq a adjust :: (a -> a) -> Int -> Seq a -> Seq a mapWithIndex :: (Int -> a -> b) -> Seq a -> Seq b foldrWithIndex :: (Int -> a -> b -> b) -> b -> Seq a -> b foldlWithIndex :: (b -> Int -> a -> b) -> b -> Seq a -> b foldrWithIndex' :: (Int -> a -> b -> b) -> b -> Seq a -> b foldlWithIndex' :: (b -> Int -> a -> b) -> b -> Seq a -> b take :: Int -> Seq a -> Seq a drop :: Int -> Seq a -> Seq a splitAt :: Int -> Seq a -> (Seq a, Seq a) subseq :: Int -> Int -> Seq a -> Seq a filter :: (a -> Bool) -> Seq a -> Seq a partition :: (a -> Bool) -> Seq a -> (Seq a, Seq a) takeWhile :: (a -> Bool) -> Seq a -> Seq a dropWhile :: (a -> Bool) -> Seq a -> Seq a splitWhile :: (a -> Bool) -> Seq a -> (Seq a, Seq a) zip :: Seq a -> Seq b -> Seq (a,b) zip3 :: Seq a -> Seq b -> Seq c -> Seq (a,b,c) zipWith :: (a -> b -> c) -> Seq a -> Seq b -> Seq c zipWith3 :: (a -> b -> c -> d) -> Seq a -> Seq b -> Seq c -> Seq d unzip :: Seq (a,b) -> (Seq a, Seq b) unzip3 :: Seq (a,b,c) -> (Seq a, Seq b, Seq c) unzipWith :: (a -> b) -> (a -> c) -> Seq a -> (Seq b, Seq c) unzipWith3 :: (a -> b) -> (a -> c) -> (a -> d) -> Seq a -> (Seq b, Seq c, Seq d) strict :: Seq a -> Seq a strictWith :: (a -> b) -> Seq a -> Seq a structuralInvariant :: Seq a -> Bool moduleName = "Data.Edison.Seq.BankersQueue" data Seq a = Q !Int [a] [a] !Int -- invariant: front at least as long as rear structuralInvariant (Q x f r y) = length f == x && length r == y && x >= y -- not exported makeQ :: Int -> [a] -> [a] -> Int -> Seq a makeQ i xs ys j | j > i = Q (i + j) (xs ++ L.reverse ys) [] 0 | otherwise = Q i xs ys j empty = Q 0 [] [] 0 singleton x = Q 1 [x] [] 0 lcons x (Q i xs ys j) = Q (i+1) (x:xs) ys j rcons y (Q i xs ys j) = makeQ i xs (y:ys) (j+1) append (Q i1 xs1 ys1 j1) (Q i2 xs2 ys2 j2) = Q (i1 + j1 + i2) (xs1 ++ L.reverseOnto ys1 xs2) ys2 j2 lview (Q _ [] _ _) = fail "BankersQueue.lview: empty sequence" lview (Q i (x:xs) ys j) = return (x, makeQ (i-1) xs ys j) lhead (Q _ [] _ _) = error "BankersQueue.lhead: empty sequence" lhead (Q _ (x:_) _ _) = x lheadM (Q _ [] _ _) = fail "BankersQueue.lheadM: empty sequence" lheadM (Q _ (x:_) _ _) = return x ltail (Q i (_:xs) ys j) = makeQ (i-1) xs ys j ltail _ = error "BankersQueue.ltail: empty sequence" ltailM (Q i (_:xs) ys j) = return (makeQ (i-1) xs ys j) ltailM _ = fail "BankersQueue.ltail: empty sequence" rview (Q i xs (y:ys) j) = return (y, Q i xs ys (j-1)) rview (Q i xs [] _) = case L.rview xs of Nothing -> fail "BankersQueue.rview: empty sequence" Just (x,xs') -> return (x, Q (i-1) xs' [] 0) rhead (Q _ _ (y:_) _) = y rhead (Q _ [] [] _) = error "BankersQueue.rhead: empty sequence" rhead (Q _ xs [] _) = L.rhead xs rheadM (Q _ _ (y:_) _) = return y rheadM (Q _ [] [] _) = fail "BankersQueue.rheadM: empty sequence" rheadM (Q _ xs [] _) = return (L.rhead xs) rtail (Q i xs (_:ys) j) = Q i xs ys (j-1) rtail (Q _ [] [] _) = error "BankersQueue.rtail: empty sequence" rtail (Q i xs [] _) = Q (i-1) (L.rtail xs) [] 0 rtailM (Q i xs (_:ys) j) = return (Q i xs ys (j-1)) rtailM (Q _ [] [] _) = fail "BankersQueue.rtailM: empty sequence" rtailM (Q i xs [] _) = return (Q (i-1) (L.rtail xs) [] 0) null (Q i _ _ _) = (i == 0) size (Q i _ _ j) = i + j reverse (Q i xs ys j) = makeQ j ys xs i reverseOnto (Q i1 xs1 ys1 j1) (Q i2 xs2 ys2 j2) = Q (i1 + j1 + i2) (ys1 ++ L.reverseOnto xs1 xs2) ys2 j2 fromList xs = Q (length xs) xs [] 0 toList (Q _ xs ys j) | j == 0 = xs | otherwise = xs ++ L.reverse ys map f (Q i xs ys j) = Q i (L.map f xs) (L.map f ys) j -- local fn on lists revfoldr :: (t -> t1 -> t1) -> t1 -> [t] -> t1 revfoldr _ e [] = e revfoldr f e (x:xs) = revfoldr f (f x e) xs revfoldr' :: (t -> a -> a) -> a -> [t] -> a revfoldr' _ e [] = e revfoldr' f e (x:xs) = e `seq` revfoldr' f (f x e) xs -- local fn on lists revfoldl :: (t -> t1 -> t) -> t -> [t1] -> t revfoldl _ e [] = e revfoldl f e (x:xs) = f (revfoldl f e xs) x revfoldl' :: (b -> t -> b) -> b -> [t] -> b revfoldl' _ e [] = e revfoldl' f e (x:xs) = (\z -> f z x) $! (revfoldl f e xs) fold f e (Q _ xs ys _) = L.foldr f (L.foldr f e ys) xs fold' f e (Q _ xs ys _) = (L.foldl' (flip f) $! (L.foldl' (flip f) e ys)) xs fold1 = fold1UsingFold fold1' = fold1'UsingFold' foldr f e (Q _ xs ys _) = L.foldr f (revfoldr f e ys) xs foldr' f e (Q _ xs ys _) = L.foldr' f (revfoldr' f e ys) xs foldl f e (Q _ xs ys _) = revfoldl f (L.foldl f e xs) ys foldl' f e (Q _ xs ys _) = revfoldl' f (L.foldl' f e xs) ys foldr1 f (Q _ xs (y:ys) _) = L.foldr f (revfoldr f y ys) xs foldr1 f (Q i xs [] _) | i == 0 = error "BankersQueue.foldr1: empty sequence" | otherwise = L.foldr1 f xs foldr1' f (Q _ xs (y:ys) _) = L.foldr' f (revfoldr' f y ys) xs foldr1' f (Q i xs [] _) | i == 0 = error "BankersQueue.foldr1': empty sequence" | otherwise = L.foldr1' f xs foldl1 f (Q _ (x:xs) ys _) = revfoldl f (L.foldl f x xs) ys foldl1 _ _ = error "BankersQueue.foldl1: empty sequence" foldl1' f (Q _ (x:xs) ys _) = revfoldl' f (L.foldl' f x xs) ys foldl1' _ _ = error "BankersQueue.foldl1': empty sequence" copy n x | n < 0 = empty | otherwise = Q n (L.copy n x) [] 0 -- reduce1: given sizes could do more effective job of dividing evenly! lookup idx q = runIdentity (lookupM idx q) lookupM idx (Q i xs ys j) | idx < i = L.lookupM idx xs | otherwise = L.lookupM (j - (idx - i) - 1) ys lookupWithDefault d idx (Q i xs ys j) | idx < i = L.lookupWithDefault d idx xs | otherwise = L.lookupWithDefault d (j - (idx - i) - 1) ys update idx e q@(Q i xs ys j) | idx < i = if idx < 0 then q else Q i (L.update idx e xs) ys j | otherwise = let k' = j - (idx - i) - 1 in if k' < 0 then q else Q i xs (L.update k' e ys) j adjust f idx q@(Q i xs ys j) | idx < i = if idx < 0 then q else Q i (L.adjust f idx xs) ys j | otherwise = let k' = j - (idx - i) - 1 in if k' < 0 then q else Q i xs (L.adjust f k' ys) j {- could do mapWithIndex :: (Int -> a -> b) -> s a -> s b foldrWithIndex :: (Int -> a -> b -> b) -> b -> s a -> b foldlWithIndex :: (b -> Int -> a -> b) -> b -> s a -> b but don't bother for now -} take len q@(Q i xs ys j) = if len <= i then if len <= 0 then empty else Q len (L.take len xs) [] 0 else let len' = len - i in if len' >= j then q else Q i xs (L.drop (j - len') ys) len' drop len q@(Q i xs ys j) = if len <= i then if len <= 0 then q else makeQ (i - len) (L.drop len xs) ys j else let len' = len - i in if len' >= j then empty else Q (j - len') (L.reverse (L.take (j - len') ys)) [] 0 -- could write more efficient version of reverse (take ...) splitAt idx q@(Q i xs ys j) = if idx <= i then if idx <= 0 then (empty, q) else let (xs',xs'') = L.splitAt idx xs in (Q idx xs' [] 0, makeQ (i - idx) xs'' ys j) else let idx' = idx - i in if idx' >= j then (q, empty) else let (ys', ys'') = L.splitAt (j - idx') ys in (Q i xs ys'' idx', Q (j - idx') (L.reverse ys') [] 0) -- could do splitAt followed by reverse more efficiently... strict l@(Q _ xs ys _) = L.strict xs `seq` L.strict ys `seq` l strictWith f l@(Q _ xs ys _) = L.strictWith f xs `seq` L.strictWith f ys `seq` l -- the remaining functions all use defaults concat = concatUsingFoldr concatMap = concatMapUsingFoldr reducer = reducerUsingReduce1 reducel = reducelUsingReduce1 reduce1 = reduce1UsingLists reducer' = reducer'UsingReduce1' reducel' = reducel'UsingReduce1' reduce1' = reduce1'UsingLists inBounds = inBoundsUsingSize mapWithIndex = mapWithIndexUsingLists foldrWithIndex = foldrWithIndexUsingLists foldrWithIndex' = foldrWithIndex'UsingLists foldlWithIndex = foldlWithIndexUsingLists foldlWithIndex' = foldlWithIndex'UsingLists subseq = subseqDefault filter = filterUsingLists partition = partitionUsingLists takeWhile = takeWhileUsingLview dropWhile = dropWhileUsingLview splitWhile = splitWhileUsingLview zip = zipUsingLists zip3 = zip3UsingLists zipWith = zipWithUsingLists zipWith3 = zipWith3UsingLists unzip = unzipUsingLists unzip3 = unzip3UsingLists unzipWith = unzipWithUsingLists unzipWith3 = unzipWith3UsingLists -- instances instance S.Sequence Seq where {lcons = lcons; rcons = rcons; lview = lview; lhead = lhead; ltail = ltail; lheadM = lheadM; ltailM = ltailM; rheadM = rheadM; rtailM = rtailM; rview = rview; rhead = rhead; rtail = rtail; null = null; size = size; concat = concat; reverse = reverse; reverseOnto = reverseOnto; fromList = fromList; toList = toList; fold = fold; fold' = fold'; fold1 = fold1; fold1' = fold1'; foldr = foldr; foldr' = foldr'; foldl = foldl; foldl' = foldl'; foldr1 = foldr1; foldr1' = foldr1'; foldl1 = foldl1; foldl1' = foldl1'; reducer = reducer; reducer' = reducer'; reducel = reducel; reducel' = reducel'; reduce1 = reduce1; reduce1' = reduce1'; copy = copy; inBounds = inBounds; lookup = lookup; lookupM = lookupM; lookupWithDefault = lookupWithDefault; update = update; adjust = adjust; mapWithIndex = mapWithIndex; foldrWithIndex = foldrWithIndex; foldlWithIndex = foldlWithIndex; foldrWithIndex' = foldrWithIndex'; foldlWithIndex' = foldlWithIndex'; take = take; drop = drop; splitAt = splitAt; subseq = subseq; filter = filter; partition = partition; takeWhile = takeWhile; dropWhile = dropWhile; splitWhile = splitWhile; zip = zip; zip3 = zip3; zipWith = zipWith; zipWith3 = zipWith3; unzip = unzip; unzip3 = unzip3; unzipWith = unzipWith; unzipWith3 = unzipWith3; strict = strict; strictWith = strictWith; structuralInvariant = structuralInvariant; instanceName _ = moduleName} instance Functor Seq where fmap = map instance App.Alternative Seq where empty = empty (<|>) = append instance App.Applicative Seq where pure = return x <*> y = do x' <- x y' <- y return (x' y') instance Monad Seq where return = singleton xs >>= k = concatMap k xs instance MonadPlus Seq where mplus = append mzero = empty instance Eq a => Eq (Seq a) where q1 == q2 = (size q1 == size q2) && (toList q1 == toList q2) instance Ord a => Ord (Seq a) where compare = defaultCompare instance Show a => Show (Seq a) where showsPrec = showsPrecUsingToList instance Read a => Read (Seq a) where readsPrec = readsPrecUsingFromList instance Arbitrary a => Arbitrary (Seq a) where arbitrary = do xs <- arbitrary ys <- arbitrary return (let i = L.size xs j = L.size ys in if i >= j then Q i xs ys j else Q j ys xs i) instance CoArbitrary a => CoArbitrary (Seq a) where coarbitrary (Q _ xs ys _) = coarbitrary xs . coarbitrary ys instance Semigroup (Seq a) where (<>) = append instance Monoid (Seq a) where mempty = empty mappend = (SG.<>)
robdockins/edison
edison-core/src/Data/Edison/Seq/BankersQueue.hs
Haskell
mit
15,242
module HJS.Parser.ParserMonad where import Control.Monad.Identity import Control.Monad.Error import Control.Monad.State import HJS.Parser.Lexer data ParseResult a = Ok a | Failed String deriving Show data LexerMode = Normal | InComment | InRegex deriving Show data LexerState = LS { rest::String,lineno::Int,mode::LexerMode,tr:: [String], nl:: Bool, rest2 :: String, expectRegex :: Bool, lastToken::(Maybe Token)} deriving Show startState str = LS { rest=str, lineno=1, mode =Normal, tr=[], nl = False, rest2 = "", expectRegex = False,lastToken=Nothing} type P = StateT LexerState (ErrorT String Identity) getLineNo :: P Int getLineNo = do s <- get return $ lineno s putLineNo :: Int -> P () putLineNo l = do s <- get put s { lineno = l } trace :: String -> P () trace ts = do s <- get put s { tr = ts : (tr s) } ifM a b c = do case a of True -> b False -> c
nbrunt/JSHOP
res/hjs-0.1/src/HJS/Parser/ParserMonad.hs
Haskell
mit
1,053
import Data.List import Data.Ord data Graph a = Graph [a] [(a, a)] deriving (Show, Eq) data Adjacency a = Adj [(a, [a])] deriving (Show, Eq) data Friendly a = Edge [(a, a)] deriving (Show, Eq) -- Problem 80 -- Conversions -- graphToAdj, adjToGraph, graphToFri, friToGraph, adjToFri, friToAdj graphToAdj :: Eq a => Graph a -> Adjacency a graphToAdj (Graph [] _) = Adj [] graphToAdj (Graph (x:xs) edges) = Adj ((x, connectedWithX):remainingAdjacencies) where f (a, b) = if a == x then [b] else if b == x then [a] else [] connectedWithX = concatMap f edges Adj remainingAdjacencies = graphToAdj (Graph xs edges) adjToGraph :: Eq a => Adjacency a -> Graph a adjToGraph (Adj []) = Graph [] [] adjToGraph (Adj ((x, ys):rest)) = Graph (x:xs) (edgesWithX ++ remainingEdges) where Graph xs remainingEdges = adjToGraph (Adj rest) f y = if elem (x, y) remainingEdges || elem (y, x) remainingEdges then [] else [(x, y)] edgesWithX = concatMap f ys graphToFri :: Eq a => Graph a -> Friendly a graphToFri (Graph xs edges) = Edge (edges ++ lonelies) where lonelies = [(x, x)| x <- xs, not (x `elem` (map fst edges) || x `elem` (map snd edges))] friToGraph :: Eq a => Friendly a -> Graph a friToGraph (Edge []) = Graph [] [] friToGraph (Edge ((x, y):rest)) = Graph nodes edges where Graph remainingNodes remainingEdges = friToGraph (Edge rest) nodesWithX = if x `elem` remainingNodes then remainingNodes else (x:remainingNodes) nodes = if y `elem` nodesWithX then nodesWithX else (y:nodesWithX) edges = if x == y then remainingEdges else (x,y):remainingEdges adjToFri :: Eq a => Adjacency a -> Friendly a adjToFri = graphToFri . adjToGraph friToAdj :: Eq a => Friendly a -> Adjacency a friToAdj = graphToAdj . friToGraph -- Problem 81 -- paths -- Paths from one node to another one paths :: Eq a => a -> a -> [(a, a)] -> [[a]] paths x y zs = _paths [y] x zs where _paths ys@(y:_) x zs = if x == y then [ys] else concatMap f zs where f (x1, y1) = if y1 == y && not (x1 `elem` ys) then _paths (x1:ys) x zs else [] -- Problem 82 -- cycle -- Cycle from a given node cycle :: Eq a => a -> [(a, a)] -> [[a]] cycle x es = _cycle [x] es where _cycle xs es = concatMap f es where last = xs !! (length xs - 1) first = xs !! 0 f (x, y) = if x == last && y == first then [xs ++ [y]] else if x == last && not (y `elem` xs) then _cycle (xs ++ [y]) es else [] -- Problem 83 -- spantrees -- Construct all spanning trees spantrees :: (Eq a, Ord a) => Graph a -> [Graph a] spantrees (Graph [] _) = [] spantrees (Graph [x] _) = [Graph [x] []] spantrees (Graph xs es) = nubBy (\(Graph _ es1) (Graph _ es2) -> sort es1 == sort es2) $ concat [concatMap (f x) (gs x) | x <- xs] where without x (a, b) = a /= x && b /= x gs x = spantrees (Graph (filter (/= x) xs) (filter (without x) es)) f v (Graph vs es2) = [Graph (v:vs) (e2:es2) | e2<-es, not (without v e2)] k4 = Graph ['a', 'b', 'c', 'd'] [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'), ('a', 'c'), ('b', 'd')] -- Problem 84 -- prim -- Construct the minimum spanning tree prim :: (Eq a, Ord b) => [a] -> [(a, a, b)] -> [(a, a, b)] prim [] _ = [] prim xs@(x:_) es = prim' xs es [x] where contains x (a, b, _) = x == a || x == b prim' xs es seen = if length seen == length xs then [] else (nextEdge: prim' xs es (seen ++ [next])) where trd (_,_,w) = w xor a b = (a || b) && (not (a && b)) f (a, b, _) = (a `elem` seen) `xor` (b `elem` seen) possibs = filter f es nextEdge = minimumBy (comparing trd) possibs g (a, b, _) = if a `elem` seen then b else a next = g nextEdge -- Problem 85 -- iso -- Graph isomorphism iso :: (Eq a, Ord a, Eq b, Ord b) => Graph a -> Graph b -> Bool iso g1 g2 = any (\f -> graphEqual (f g1) g2) (makeMappings g1 g2) where matching [] x = error "No matching element found" matching ((a,b):ys) x = if a == x then b else matching ys x g mapping (Graph xs es) = Graph (map (matching mapping) xs) [(matching mapping a, matching mapping b) | (a,b)<-es] makeMappings (Graph xs1 _) (Graph xs2 _) = if length xs1 /= length xs2 then [] else [g (zip perm xs2) | perm <- permutations xs1] graphEqual (Graph xs1 es1) (Graph xs2 es2) = sort xs1 == sort xs2 && sort es1 == sort es2 -- Problem 86 -- degree, sortedDegrees, kcolor -- Write a function that determines the degree of a given node. -- Write a function that generates a list of all nodes of a graph -- sorted according to decreasing degree. -- Use Welch-Powell's algorithm to paint the nodes of a graph in such -- a way that adjacent nodes have different colors. degree :: Eq a => Graph a -> a -> Int degree (Graph _ es) x = length $ filter (\(a, b) -> x == a || x == b) es sortedDegrees :: Eq a => Graph a -> [a] sortedDegrees g@(Graph xs es) = reverse $ sortBy (comparing (degree g)) xs kcolor :: (Eq a, Ord a) => Graph a -> [(a, Int)] kcolor g = kcolor' adj 1 [] where adj = sortByDegrees g sortByDegrees g = sortBy (comparing (length . snd)) adj' where Adj adj' = graphToAdj g kcolor' [] _ acc = acc kcolor' xs n acc = kcolor' newxs (n+1) acc' where newxs = [x | x <- xs, notElem (fst x, n) acc'] acc' = color xs n acc color [] _ acc = acc color ((v,e):xs) n acc = if any (\x -> (x, n) `elem` acc) e then color xs n acc else color xs n ((v, n):acc) -- Problem 87 -- depthfirst -- Depth first order graph traversal (alternative solution) depthfirst :: Eq a => Graph a -> a -> [a] depthfirst g x = reverse $ search g x [] where search (Graph xs _) _ seen | length seen == length xs = seen search (Graph xs es) x seen = foldl' combine (x:seen) next where combine sofar node = if notElem node sofar then search g node sofar else sofar next = [y | y <- xs, y `notElem` seen && ((x, y) `elem` es || (y, x) `elem` es)] -- Problem 88 -- connectedComponents -- Write a function that splits a graph into its connected components connectedComponents :: Eq a => Graph a -> [[a]] connectedComponents (Graph [] _) = [] connectedComponents g@(Graph xs@(x:_) es) = connectedToX : rest where connectedToX = depthfirst g x rest = connectedComponents (Graph (xs \\ connectedToX) es) -- Problem 89 -- bipartite -- Write a function that finds out if the given graph is bipartite bipartite :: (Eq a, Ord a) => Graph a -> Bool bipartite g = length (nub (map snd (kcolor g))) == 2
CrazyMerlyn/99problems-haskell
80-89.hs
Haskell
mit
7,593
ans [a,b] = a + b main = do l <- getLine let i = map read $ words l :: [Integer] o = ans i print o
a143753/AOJ
NTL_2_A.hs
Haskell
apache-2.0
119
module Arrays where import Data.Array.IArray type ArrayLength = Int createNewEmptyArray :: ArrayLength -> Array Int a createNewEmptyArray = undefined fromList :: [a] -> Array Int a fromList xs = listArray (0, l - 1) xs where l = length xs buildPair :: (Int, Int) buildPair = let arr = listArray (1,10) (repeat 37) :: Array Int Int arr' = arr // [(1, 64)] in (arr ! 1, arr' ! 1)
songpp/my-haskell-playground
src/Arrays.hs
Haskell
apache-2.0
417
module External.A137735 (a137735) where a137735 :: Int -> Integer a137735 n = a137735_list !! n a137735_list :: [Integer] a137735_list = 1 : remaining 1 1 where remaining n maxTerm = nextTerm : remaining (n + 1) (max nextTerm maxTerm) where nextTerm = floor $ toRational n / toRational maxTerm
peterokagey/haskellOEIS
src/External/A137735.hs
Haskell
apache-2.0
302
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE RecordWildCards #-} -- | The module provides functionality for manipulating PoliMorf, the -- morphological dictionary for Polish. module Data.PoliMorf ( -- * Types Form , Base , POS , MSD , Tag , Cat , Entry (..) , split , pos , msd , atomic -- * Parsing , readPoliMorf , parsePoliMorf ) where import Control.Applicative ((<$>)) import Control.Arrow (second) import qualified Data.Text as T import qualified Data.Text.Lazy as L import qualified Data.Text.Lazy.IO as L -- | A word form. type Form = T.Text -- | A base form. type Base = T.Text -- | A part of speech. type POS = T.Text -- | A morphosyntactic description type MSD = T.Text -- | A morphosyntactic tag. (Tag = POS + MSD) type Tag = T.Text -- | A semantic category. It will be set to "" when there is -- no category assigned to a particular PoliMorf entry. type Cat = T.Text -- | An entry from the PoliMorf dictionary. data Entry = Entry { form :: !Form , base :: !Base , tag :: !Tag , cat :: !Cat } deriving (Eq, Ord, Show, Read) -- | Split tag. split :: Tag -> (POS, MSD) split = second (T.drop 1) . T.break (==':') -- | Entry POS. pos :: Entry -> POS pos = fst . split . tag -- | Entry MSD. msd :: Entry -> MSD msd = snd . split . tag -- | Is the entry an atomic one? More precisely, we treat all negative -- forms starting with ''nie'' and all superlatives starting with ''naj'' -- as non-atomic entries. atomic :: Entry -> Bool atomic x | "sup" `T.isInfixOf` tag x && "naj" `T.isPrefixOf` form x = False | "neg" `T.isInfixOf` tag x && "nie" `T.isPrefixOf` form x = False | otherwise = True -- | Read the PoliMorf from the file. readPoliMorf :: FilePath -> IO [Entry] readPoliMorf path = parsePoliMorf <$> L.readFile path -- | Parse the PoliMorf into a list of entries. parsePoliMorf :: L.Text -> [Entry] parsePoliMorf = map parsePoliRow . L.lines -- | Get an entry pair from a PoliMorf row. parsePoliRow :: L.Text -> Entry parsePoliRow row = case map L.toStrict (L.split (=='\t') row) of _form : _base : _tag : rest -> Entry _form _base _tag $ case rest of [] -> "" (_cat:_) -> _cat _ -> error $ "parsePoliRow: invalid row \"" ++ L.unpack row ++ "\""
kawu/polimorf
src/Data/PoliMorf.hs
Haskell
bsd-2-clause
2,320
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} -- | -- -- Generic OAuth2 plugin for Yesod -- -- * See Yesod.Auth.OAuth2.GitHub for example usage. -- module Yesod.Auth.OAuth2 ( authOAuth2 , authOAuth2Widget , oauth2Url , fromProfileURL , YesodOAuth2Exception(..) , module Network.OAuth.OAuth2 ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) #endif import Control.Exception.Lifted import Control.Monad.IO.Class import Data.ByteString (ByteString) import Data.Monoid ((<>)) import Data.Text (Text, pack) import Data.Text.Encoding (decodeUtf8With, encodeUtf8) import Data.Text.Encoding.Error (lenientDecode) import Data.Typeable import Network.HTTP.Conduit (Manager) import Network.OAuth.OAuth2 import System.Random import Yesod.Auth import Yesod.Core import Yesod.Form import qualified Data.ByteString.Lazy as BL -- | Provider name and Aeson parse error data YesodOAuth2Exception = InvalidProfileResponse Text BL.ByteString deriving (Show, Typeable) instance Exception YesodOAuth2Exception oauth2Url :: Text -> AuthRoute oauth2Url name = PluginR name ["forward"] -- | Create an @'AuthPlugin'@ for the given OAuth2 provider -- -- Presents a generic @"Login via name"@ link -- authOAuth2 :: YesodAuth m => Text -- ^ Service name -> OAuth2 -- ^ Service details -> (Manager -> AccessToken -> IO (Creds m)) -- ^ This function defines how to take an @'AccessToken'@ and -- retrieve additional information about the user, to be -- set in the session as @'Creds'@. Usually this means a -- second authorized request to @api/me.json@. -- -- See @'fromProfileURL'@ for an example. -> AuthPlugin m authOAuth2 name = authOAuth2Widget [whamlet|Login via #{name}|] name -- | Create an @'AuthPlugin'@ for the given OAuth2 provider -- -- Allows passing a custom widget for the login link. See @'oauth2Eve'@ for an -- example. -- authOAuth2Widget :: YesodAuth m => WidgetT m IO () -> Text -> OAuth2 -> (Manager -> AccessToken -> IO (Creds m)) -> AuthPlugin m authOAuth2Widget widget name oauth getCreds = AuthPlugin name dispatch login where url = PluginR name ["callback"] withCallback csrfToken = do tm <- getRouteToParent render <- lift getUrlRender return oauth { oauthCallback = Just $ encodeUtf8 $ render $ tm url , oauthOAuthorizeEndpoint = oauthOAuthorizeEndpoint oauth <> "&state=" <> encodeUtf8 csrfToken } dispatch "GET" ["forward"] = do csrfToken <- liftIO generateToken setSession tokenSessionKey csrfToken authUrl <- bsToText . authorizationUrl <$> withCallback csrfToken lift $ redirect authUrl dispatch "GET" ["callback"] = do newToken <- lookupGetParam "state" oldToken <- lookupSession tokenSessionKey deleteSession tokenSessionKey case newToken of Just csrfToken | newToken == oldToken -> do code <- lift $ runInputGet $ ireq textField "code" oauth' <- withCallback csrfToken master <- lift getYesod result <- liftIO $ fetchAccessToken (authHttpManager master) oauth' (encodeUtf8 code) case result of Left _ -> permissionDenied "Unable to retreive OAuth2 token" Right token -> do creds <- liftIO $ getCreds (authHttpManager master) token lift $ setCredsRedirect creds _ -> permissionDenied "Invalid OAuth2 state token" dispatch _ _ = notFound generateToken = pack . take 30 . randomRs ('a', 'z') <$> newStdGen tokenSessionKey :: Text tokenSessionKey = "_yesod_oauth2_" <> name login tm = [whamlet|<a href=@{tm $ oauth2Url name}>^{widget}|] -- | Handle the common case of fetching Profile information from a JSON endpoint -- -- Throws @'InvalidProfileResponse'@ if JSON parsing fails -- fromProfileURL :: FromJSON a => Text -- ^ Plugin name -> URI -- ^ Profile URI -> (a -> Creds m) -- ^ Conversion to Creds -> Manager -> AccessToken -> IO (Creds m) fromProfileURL name url toCreds manager token = do result <- authGetJSON manager token url case result of Right profile -> return $ toCreds profile Left err -> throwIO $ InvalidProfileResponse name err bsToText :: ByteString -> Text bsToText = decodeUtf8With lenientDecode
jasonzoladz/yesod-auth-oauth2
Yesod/Auth/OAuth2.hs
Haskell
bsd-2-clause
4,800
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} ------------------------------------------------------------------------------ -- | Pre-packaged Handlers that deal with form submissions and standard -- use-cases involving authentication. module Snap.Snaplet.Auth.Handlers where ------------------------------------------------------------------------------ import Control.Applicative import Control.Monad.State import Control.Monad.Trans.Either import Control.Monad.Trans.Maybe import Data.ByteString (ByteString) import Data.Maybe import Data.Serialize hiding (get) import Data.Time import Data.Text.Encoding (decodeUtf8) import Data.Text (Text, null, strip) import Prelude hiding (null) import Web.ClientSession ------------------------------------------------------------------------------ import Snap.Core import Snap.Snaplet import Snap.Snaplet.Auth.AuthManager import Snap.Snaplet.Auth.Handlers.Errors import Snap.Snaplet.Auth.Types import Snap.Snaplet.Session ------------------------------------------------------------------------------ ---------------------------- -- Higher level functions -- ---------------------------- ------------------------------------------------------------------------------ -- | Create a new user from just a username and password -- createUser :: Text -- ^ Username -> ByteString -- ^ Password -> Handler b (AuthManager b) (Either AuthFailure AuthUser) createUser unm pwd | null $ strip unm = return $ Left UsernameMissing | otherwise = do uExists <- usernameExists unm if uExists then return $ Left DuplicateLogin else withBackend $ \r -> liftIO $ buildAuthUser r unm pwd ------------------------------------------------------------------------------ -- | Check whether a user with the given username exists. -- usernameExists :: Text -- ^ The username to be checked -> Handler b (AuthManager b) Bool usernameExists username = withBackend $ \r -> liftIO $ isJust <$> lookupByLogin r username ------------------------------------------------------------------------------ -- | Lookup a user by her username, check given password and perform login -- loginByUsername :: Text -- ^ Username/login for user -> Password -- ^ Should be ClearText -> Bool -- ^ Set remember token? -> Handler b (AuthManager b) (Either AuthFailure AuthUser) loginByUsername _ (Encrypted _) _ = return $ Left EncryptedPassword loginByUsername unm pwd shouldRemember = do sk <- gets siteKey cn <- gets rememberCookieName cd <- gets rememberCookieDomain rp <- gets rememberPeriod withBackend $ loginByUsername' sk cn cd rp where -------------------------------------------------------------------------- loginByUsername' :: (IAuthBackend t) => Key -> ByteString -> Maybe ByteString -> Maybe Int -> t -> Handler b (AuthManager b) (Either AuthFailure AuthUser) loginByUsername' sk cn cd rp r = liftIO (lookupByLogin r unm) >>= maybe (return $! Left UserNotFound) found where ---------------------------------------------------------------------- found user = checkPasswordAndLogin user pwd >>= either (return . Left) matched ---------------------------------------------------------------------- matched user | shouldRemember = do token <- gets randomNumberGenerator >>= liftIO . randomToken 64 setRememberToken sk cn cd rp token let user' = user { userRememberToken = Just (decodeUtf8 token) } saveUser user' return $! Right user' | otherwise = return $ Right user ------------------------------------------------------------------------------ -- | Remember user from the remember token if possible and perform login -- loginByRememberToken :: Handler b (AuthManager b) (Either AuthFailure AuthUser) loginByRememberToken = withBackend $ \impl -> do key <- gets siteKey cookieName_ <- gets rememberCookieName period <- gets rememberPeriod runEitherT $ do token <- noteT (AuthError "loginByRememberToken: no remember token") $ MaybeT $ getRememberToken key cookieName_ period user <- noteT (AuthError "loginByRememberToken: no remember token") $ MaybeT $ liftIO $ lookupByRememberToken impl $ decodeUtf8 token lift $ forceLogin user return user ------------------------------------------------------------------------------ -- | Logout the active user -- logout :: Handler b (AuthManager b) () logout = do s <- gets session withTop s $ withSession s removeSessionUserId rc <- gets rememberCookieName rd <- gets rememberCookieDomain expireSecureCookie rc rd modify $ \mgr -> mgr { activeUser = Nothing } ------------------------------------------------------------------------------ -- | Return the current user; trying to remember from cookie if possible. -- currentUser :: Handler b (AuthManager b) (Maybe AuthUser) currentUser = cacheOrLookup $ withBackend $ \r -> do s <- gets session uid <- withTop s getSessionUserId case uid of Nothing -> hush <$> loginByRememberToken Just uid' -> liftIO $ lookupByUserId r uid' ------------------------------------------------------------------------------ -- | Convenience wrapper around 'rememberUser' that returns a bool result -- isLoggedIn :: Handler b (AuthManager b) Bool isLoggedIn = isJust <$> currentUser ------------------------------------------------------------------------------ -- | Create or update a given user -- saveUser :: AuthUser -> Handler b (AuthManager b) (Either AuthFailure AuthUser) saveUser u | null $ userLogin u = return $ Left UsernameMissing | otherwise = withBackend $ \r -> liftIO $ save r u ------------------------------------------------------------------------------ -- | Destroy the given user -- destroyUser :: AuthUser -> Handler b (AuthManager b) () destroyUser u = withBackend $ liftIO . flip destroy u ----------------------------------- -- Lower level helper functions -- ----------------------------------- ------------------------------------------------------------------------------ -- | Mutate an 'AuthUser', marking failed authentication -- -- This will save the user to the backend. -- markAuthFail :: AuthUser -> Handler b (AuthManager b) (Either AuthFailure AuthUser) markAuthFail u = withBackend $ \r -> do lo <- gets lockout incFailCtr u >>= checkLockout lo >>= liftIO . save r where -------------------------------------------------------------------------- incFailCtr u' = return $ u' { userFailedLoginCount = userFailedLoginCount u' + 1 } -------------------------------------------------------------------------- checkLockout lo u' = case lo of Nothing -> return u' Just (mx, wait) -> if userFailedLoginCount u' >= mx then do now <- liftIO getCurrentTime let reopen = addUTCTime wait now return $! u' { userLockedOutUntil = Just reopen } else return u' ------------------------------------------------------------------------------ -- | Mutate an 'AuthUser', marking successful authentication -- -- This will save the user to the backend. -- markAuthSuccess :: AuthUser -> Handler b (AuthManager b) (Either AuthFailure AuthUser) markAuthSuccess u = withBackend $ \r -> incLoginCtr u >>= updateIp >>= updateLoginTS >>= resetFailCtr >>= liftIO . save r where -------------------------------------------------------------------------- incLoginCtr u' = return $ u' { userLoginCount = userLoginCount u' + 1 } -------------------------------------------------------------------------- updateIp u' = do ip <- rqClientAddr <$> getRequest return $ u' { userLastLoginIp = userCurrentLoginIp u' , userCurrentLoginIp = Just ip } -------------------------------------------------------------------------- updateLoginTS u' = do now <- liftIO getCurrentTime return $ u' { userCurrentLoginAt = Just now , userLastLoginAt = userCurrentLoginAt u' } -------------------------------------------------------------------------- resetFailCtr u' = return $ u' { userFailedLoginCount = 0 , userLockedOutUntil = Nothing } ------------------------------------------------------------------------------ -- | Authenticate and log the user into the current session if successful. -- -- This is a mid-level function exposed to allow roll-your-own ways of looking -- up a user from the database. -- -- This function will: -- -- 1. Check the password -- -- 2. Login the user into the current session -- -- 3. Mark success/failure of the authentication trial on the user record -- checkPasswordAndLogin :: AuthUser -- ^ An existing user, somehow looked up from db -> Password -- ^ A ClearText password -> Handler b (AuthManager b) (Either AuthFailure AuthUser) checkPasswordAndLogin u pw = case userLockedOutUntil u of Just x -> do now <- liftIO getCurrentTime if now > x then auth u else return . Left $ LockedOut x Nothing -> auth u where auth :: AuthUser -> Handler b (AuthManager b) (Either AuthFailure AuthUser) auth user = case authenticatePassword user pw of Just e -> do markAuthFail user return $ Left e Nothing -> do forceLogin user modify (\mgr -> mgr { activeUser = Just user }) markAuthSuccess user ------------------------------------------------------------------------------ -- | Login and persist the given 'AuthUser' in the active session -- -- Meant to be used if you have other means of being sure that the person is -- who she says she is. -- forceLogin :: AuthUser -- ^ An existing user, somehow looked up from db -> Handler b (AuthManager b) (Either AuthFailure ()) forceLogin u = do s <- gets session withSession s $ case userId u of Just x -> do withTop s (setSessionUserId x) return $ Right () Nothing -> return . Left $ AuthError $ "forceLogin: Can't force the login of a user " ++ "without userId" ------------------------------------ -- Internal, non-exported helpers -- ------------------------------------ ------------------------------------------------------------------------------ getRememberToken :: (Serialize t, MonadSnap m) => Key -> ByteString -> Maybe Int -> m (Maybe t) getRememberToken sk rc rp = getSecureCookie rc sk rp ------------------------------------------------------------------------------ setRememberToken :: (Serialize t, MonadSnap m) => Key -> ByteString -> Maybe ByteString -> Maybe Int -> t -> m () setRememberToken sk rc rd rp token = setSecureCookie rc rd sk rp token ------------------------------------------------------------------------------ -- | Set the current user's 'UserId' in the active session -- setSessionUserId :: UserId -> Handler b SessionManager () setSessionUserId (UserId t) = setInSession "__user_id" t ------------------------------------------------------------------------------ -- | Remove 'UserId' from active session, effectively logging the user out. removeSessionUserId :: Handler b SessionManager () removeSessionUserId = deleteFromSession "__user_id" ------------------------------------------------------------------------------ -- | Get the current user's 'UserId' from the active session -- getSessionUserId :: Handler b SessionManager (Maybe UserId) getSessionUserId = do uid <- getFromSession "__user_id" return $ liftM UserId uid ------------------------------------------------------------------------------ -- | Check password for a given user. -- -- Returns "Nothing" if check is successful and an "IncorrectPassword" error -- otherwise -- authenticatePassword :: AuthUser -- ^ Looked up from the back-end -> Password -- ^ Check against this password -> Maybe AuthFailure authenticatePassword u pw = auth where auth = case userPassword u of Nothing -> Just PasswordMissing Just upw -> check $ checkPassword pw upw check b = if b then Nothing else Just IncorrectPassword ------------------------------------------------------------------------------ -- | Wrap lookups around request-local cache -- cacheOrLookup :: Handler b (AuthManager b) (Maybe AuthUser) -- ^ Lookup action to perform if request local cache is empty -> Handler b (AuthManager b) (Maybe AuthUser) cacheOrLookup f = do au <- gets activeUser if isJust au then return au else do au' <- f modify (\mgr -> mgr { activeUser = au' }) return au' ------------------------------------------------------------------------------ -- | Register a new user by specifying login and password 'Param' fields -- registerUser :: ByteString -- ^ Login field -> ByteString -- ^ Password field -> Handler b (AuthManager b) (Either AuthFailure AuthUser) registerUser lf pf = do l <- fmap decodeUtf8 <$> getParam lf p <- getParam pf let l' = note UsernameMissing l let p' = note PasswordMissing p -- In case of multiple AuthFailure, the first available one -- will be propagated. case liftM2 (,) l' p' of Left e -> return $ Left e Right (lgn, pwd) -> createUser lgn pwd ------------------------------------------------------------------------------ -- | A 'MonadSnap' handler that processes a login form. -- -- The request paremeters are passed to 'performLogin' -- -- To make your users stay logged in for longer than the session replay -- prevention timeout, you must pass a field name as the third parameter and -- that field must be set to a value of \"1\" by the submitting form. This -- lets you use a user selectable check box. Or if you want user remembering -- always turned on, you can use a hidden form field. loginUser :: ByteString -- ^ Username field -> ByteString -- ^ Password field -> Maybe ByteString -- ^ Remember field; Nothing if you want no remember function. -> (AuthFailure -> Handler b (AuthManager b) ()) -- ^ Upon failure -> Handler b (AuthManager b) () -- ^ Upon success -> Handler b (AuthManager b) () loginUser unf pwdf remf loginFail loginSucc = runEitherT (loginUser' unf pwdf remf) >>= either loginFail (const loginSucc) ------------------------------------------------------------------------------ loginUser' :: ByteString -> ByteString -> Maybe ByteString -> EitherT AuthFailure (Handler b (AuthManager b)) AuthUser loginUser' unf pwdf remf = do mbUsername <- lift $ getParam unf mbPassword <- lift $ getParam pwdf remember <- lift $ liftM (fromMaybe False) (runMaybeT $ do field <- MaybeT $ return remf value <- MaybeT $ getParam field return $ value == "1" || value == "on") password <- noteT PasswordMissing $ hoistMaybe mbPassword username <- noteT UsernameMissing $ hoistMaybe mbUsername EitherT $ loginByUsername (decodeUtf8 username) (ClearText password) remember ------------------------------------------------------------------------------ -- | Simple handler to log the user out. Deletes user from session. -- logoutUser :: Handler b (AuthManager b) () -- ^ What to do after logging out -> Handler b (AuthManager b) () logoutUser target = logout >> target ------------------------------------------------------------------------------ -- | Require that an authenticated 'AuthUser' is present in the current -- session. -- -- This function has no DB cost - only checks to see if a user_id is present -- in the current session. -- requireUser :: SnapletLens b (AuthManager b) -- ^ Lens reference to an "AuthManager" -> Handler b v a -- ^ Do this if no authenticated user is present. -> Handler b v a -- ^ Do this if an authenticated user is present. -> Handler b v a requireUser auth bad good = do loggedIn <- withTop auth isLoggedIn if loggedIn then good else bad ------------------------------------------------------------------------------ -- | Run a function on the backend, and return the result. -- -- This uses an existential type so that the backend type doesn't -- 'escape' AuthManager. The reason that the type is Handler b -- (AuthManager v) a and not a is because anything that uses the -- backend will return an IO something, which you can liftIO, or a -- Handler b (AuthManager v) a if it uses other handler things. -- withBackend :: (forall r. (IAuthBackend r) => r -> Handler b (AuthManager v) a) -- ^ The function to run with the handler. -> Handler b (AuthManager v) a withBackend f = join $ do (AuthManager backend_ _ _ _ _ _ _ _ _ _) <- get return $ f backend_ ------------------------------------------------------------------------------ -- | This function generates a random password reset token and stores it in -- the database for the user. Call this function when a user forgets their -- password. Then use the token to autogenerate a link that the user can -- visit to reset their password. This function also sets a timestamp so the -- reset token can be expired. setPasswordResetToken :: Text -> Handler b (AuthManager b) (Maybe Text) setPasswordResetToken login = do tokBS <- liftIO . randomToken 40 =<< gets randomNumberGenerator let token = decodeUtf8 tokBS now <- liftIO getCurrentTime success <- modPasswordResetToken login (Just token) (Just now) return $ if success then Just token else Nothing ------------------------------------------------------------------------------ -- | Clears a user's password reset token. Call this when the user -- successfully changes their password to ensure that the password reset link -- cannot be used again. clearPasswordResetToken :: Text -> Handler b (AuthManager b) Bool clearPasswordResetToken login = modPasswordResetToken login Nothing Nothing ------------------------------------------------------------------------------ -- | Helper function used for setting and clearing the password reset token -- and associated timestamp. modPasswordResetToken :: Text -> Maybe Text -> Maybe UTCTime -> Handler v (AuthManager v) Bool modPasswordResetToken login token timestamp = do res <- runMaybeT $ do u <- MaybeT $ withBackend $ \b -> liftIO $ lookupByLogin b login lift $ saveUser $ u { userResetToken = token , userResetRequestedAt = timestamp } return () return $ maybe False (\_ -> True) res
23Skidoo/snap
src/Snap/Snaplet/Auth/Handlers.hs
Haskell
bsd-3-clause
20,449
import Data.Accessor import Graphics.Rendering.Chart.Plot.Image import Graphics.Rendering.Chart import Graphics.Rendering.Chart.Gtk import Data.Array.Repa ((:.)(..)) import qualified Data.Array.Repa as A size = 100 image :: A.Array A.U A.DIM2 (Double,Double,Double) image = A.computeS $ A.fromFunction (A.ix2 size size) $ \(A.Z :. x :. y)->( realToFrac y / realToFrac size , realToFrac x / realToFrac size , realToFrac (x+y) / realToFrac (2*size) ) chart :: Layout1 Double Double chart = layout where layout = layout1_title ^= "Hello World" $ layout1_plots ^= [Left (toPlot hi)] $ defaultLayout1 hi = image_data ^= image $ image_extent ^= ((0,0), (2,2)) $ defaultImage main = renderableToWindow (toRenderable chart) 640 480
bgamari/chart-image
Test.hs
Haskell
bsd-3-clause
898
import System.Hardware.Sump as Sump import I2c import Data.Machine parseLevel '0' = Low parseLevel '1' = High signals = let sda = map parseLevel "1110001110001111" scl = map parseLevel "1111100100111111" in zipWith I2cSignals scl sda main = mapM_ print $ Data.Machine.run $ supply signals (auto decode)
bgamari/sump
TestI2c.hs
Haskell
bsd-3-clause
323
{-# LANGUAGE GADTs #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ViewPatterns #-} -- | -- Module : Data.Array.Accelerate.Trafo.Algebra -- Copyright : [2012] Manuel M T Chakravarty, Gabriele Keller, Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <chak@cse.unsw.edu.au> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Algebraic simplifications of scalar expressions, including constant folding -- and using algebraic properties of particular operator-operand combinations. -- module Data.Array.Accelerate.Trafo.Algebra ( evalPrimApp ) where import Prelude hiding ( exp ) import Data.Maybe ( fromMaybe ) import Data.Bits import Data.Char import qualified Prelude as P -- friends import Data.Array.Accelerate.AST import Data.Array.Accelerate.Type import Data.Array.Accelerate.Tuple import Data.Array.Accelerate.Array.Sugar ( Elt, toElt, fromElt ) import Data.Array.Accelerate.Analysis.Match import Data.Array.Accelerate.Trafo.Common -- Propagate constant expressions, which are either constant valued expressions -- or constant let bindings. Be careful not to follow self-cycles. -- propagate :: forall env aenv exp. Gamma env env aenv -> OpenExp env aenv exp -> Maybe exp propagate env = cvtE where cvtE :: OpenExp env aenv e -> Maybe e cvtE exp = case exp of Const c -> Just (toElt c) PrimConst c -> Just (evalPrimConst c) Prj ix (Var v) | Tuple t <- prjExp v env -> cvtT ix t Prj ix e | Just c <- cvtE e -> cvtP ix (fromTuple c) Var ix | e <- prjExp ix env , Nothing <- matchOpenExp exp e -> cvtE e -- _ -> Nothing cvtP :: TupleIdx t e -> t -> Maybe e cvtP ZeroTupIdx (_, v) = Just v cvtP (SuccTupIdx idx) (tup, _) = cvtP idx tup cvtT :: TupleIdx t e -> Tuple (OpenExp env aenv) t -> Maybe e cvtT ZeroTupIdx (SnocTup _ e) = cvtE e cvtT (SuccTupIdx idx) (SnocTup tup _) = cvtT idx tup cvtT _ _ = error "hey what's the head angle on that thing?" -- Attempt to evaluate primitive function applications -- evalPrimApp :: forall env aenv a r. (Elt a, Elt r) => Gamma env env aenv -> PrimFun (a -> r) -> OpenExp env aenv a -> OpenExp env aenv r evalPrimApp env f x -- First attempt to move constant values towards the left | Just r <- commutes f x env = evalPrimApp env f r | Just r <- associates f x = r -- Now attempt to evaluate any expressions | otherwise = fromMaybe (PrimApp f x) $ case f of PrimAdd ty -> evalAdd ty x env PrimSub ty -> evalSub ty x env PrimMul ty -> evalMul ty x env PrimNeg ty -> evalNeg ty x env PrimAbs ty -> evalAbs ty x env PrimSig ty -> evalSig ty x env PrimQuot ty -> evalQuot ty x env PrimRem ty -> evalRem ty x env PrimIDiv ty -> evalIDiv ty x env PrimMod ty -> evalMod ty x env PrimBAnd ty -> evalBAnd ty x env PrimBOr ty -> evalBOr ty x env PrimBXor ty -> evalBXor ty x env PrimBNot ty -> evalBNot ty x env PrimBShiftL ty -> evalBShiftL ty x env PrimBShiftR ty -> evalBShiftR ty x env PrimBRotateL ty -> evalBRotateL ty x env PrimBRotateR ty -> evalBRotateR ty x env PrimFDiv ty -> evalFDiv ty x env PrimRecip ty -> evalRecip ty x env PrimSin ty -> evalSin ty x env PrimCos ty -> evalCos ty x env PrimTan ty -> evalTan ty x env PrimAsin ty -> evalAsin ty x env PrimAcos ty -> evalAcos ty x env PrimAtan ty -> evalAtan ty x env PrimAsinh ty -> evalAsinh ty x env PrimAcosh ty -> evalAcosh ty x env PrimAtanh ty -> evalAtanh ty x env PrimExpFloating ty -> evalExpFloating ty x env PrimSqrt ty -> evalSqrt ty x env PrimLog ty -> evalLog ty x env PrimFPow ty -> evalFPow ty x env PrimLogBase ty -> evalLogBase ty x env PrimAtan2 ty -> evalAtan2 ty x env PrimTruncate ta tb -> evalTruncate ta tb x env PrimRound ta tb -> evalRound ta tb x env PrimFloor ta tb -> evalFloor ta tb x env PrimCeiling ta tb -> evalCeiling ta tb x env PrimLt ty -> evalLt ty x env PrimGt ty -> evalGt ty x env PrimLtEq ty -> evalLtEq ty x env PrimGtEq ty -> evalGtEq ty x env PrimEq ty -> evalEq ty x env PrimNEq ty -> evalNEq ty x env PrimMax ty -> evalMax ty x env PrimMin ty -> evalMin ty x env PrimLAnd -> evalLAnd x env PrimLOr -> evalLOr x env PrimLNot -> evalLNot x env PrimOrd -> evalOrd x env PrimChr -> evalChr x env PrimBoolToInt -> evalBoolToInt x env PrimFromIntegral ta tb -> evalFromIntegral ta tb x env -- Discriminate binary functions that commute, and if so return the operands in -- a stable ordering. If only one of the arguments is a constant, this is placed -- to the left of the operator. Returning Nothing indicates no change is made. -- commutes :: forall env aenv a r. (Elt a, Elt r) => PrimFun (a -> r) -> OpenExp env aenv a -> Gamma env env aenv -> Maybe (OpenExp env aenv a) commutes f x env = case f of PrimAdd _ -> swizzle x PrimMul _ -> swizzle x PrimBAnd _ -> swizzle x PrimBOr _ -> swizzle x PrimBXor _ -> swizzle x PrimEq _ -> swizzle x PrimNEq _ -> swizzle x PrimMax _ -> swizzle x PrimMin _ -> swizzle x PrimLAnd -> swizzle x PrimLOr -> swizzle x _ -> Nothing where swizzle :: OpenExp env aenv (b,b) -> Maybe (OpenExp env aenv (b,b)) swizzle (Tuple (NilTup `SnocTup` a `SnocTup` b)) | Nothing <- propagate env a , Just _ <- propagate env b = Just $ Tuple (NilTup `SnocTup` b `SnocTup` a) -- TLM: changing the ordering here when neither term can be reduced can be -- disadvantageous: for example in (x &&* y), the user might have put a -- simpler condition first that is designed to fail fast. -- -- | Nothing <- propagate env a -- , Nothing <- propagate env b -- , hashOpenExp a > hashOpenExp b -- = Just $ Tuple (NilTup `SnocTup` b `SnocTup` a) swizzle _ = Nothing -- Determine if successive applications of a binary operator will associate, and -- if so move them to the left. That is: -- -- a + (b + c) --> (a + b) + c -- -- Returning Nothing indicates no change is made. -- -- TLM: we might get into trouble here, as we've lost track of where the user -- has explicitly put parenthesis. -- associates :: (Elt a, Elt r) => PrimFun (a -> r) -> OpenExp env aenv a -> Maybe (OpenExp env aenv r) associates fun exp = case fun of PrimAdd _ -> swizzle fun exp [PrimAdd ty, PrimSub ty] PrimSub _ -> swizzle fun exp [PrimAdd ty, PrimSub ty] PrimLAnd -> swizzle fun exp [fun] PrimLOr -> swizzle fun exp [fun] _ -> swizzle fun exp [fun] where -- TODO: check the list of ops is complete (and correct) ty = undefined ops = [ PrimMul ty, PrimFDiv ty, PrimAdd ty, PrimSub ty, PrimBAnd ty, PrimBOr ty, PrimBXor ty ] swizzle :: (Elt a, Elt r) => PrimFun (a -> r) -> OpenExp env aenv a -> [PrimFun (a -> r)] -> Maybe (OpenExp env aenv r) swizzle f x lvl | Just REFL <- matches f ops , Just (a,bc) <- untup2 x , PrimApp g y <- bc , Just REFL <- matches g lvl , Just (b,c) <- untup2 y = Just $ PrimApp g (tup2 (PrimApp f (tup2 (a,b)), c)) swizzle _ _ _ = Nothing matches :: (Elt s, Elt t) => PrimFun (s -> a) -> [PrimFun (t -> a)] -> Maybe (s :=: t) matches _ [] = Nothing matches f (x:xs) | Just REFL <- matchPrimFun' f x = Just REFL | otherwise = matches f xs -- Helper functions -- ---------------- type a :-> b = forall env aenv. OpenExp env aenv a -> Gamma env env aenv -> Maybe (OpenExp env aenv b) eval1 :: Elt b => (a -> b) -> a :-> b eval1 f x env | Just a <- propagate env x = Just $ Const (fromElt (f a)) | otherwise = Nothing eval2 :: Elt c => (a -> b -> c) -> (a,b) :-> c eval2 f (untup2 -> Just (x,y)) env | Just a <- propagate env x , Just b <- propagate env y = Just $ Const (fromElt (f a b)) eval2 _ _ _ = Nothing tup2 :: (Elt a, Elt b) => (OpenExp env aenv a, OpenExp env aenv b) -> OpenExp env aenv (a, b) tup2 (a,b) = Tuple (NilTup `SnocTup` a `SnocTup` b) untup2 :: OpenExp env aenv (a, b) -> Maybe (OpenExp env aenv a, OpenExp env aenv b) untup2 exp | Tuple (NilTup `SnocTup` a `SnocTup` b) <- exp = Just (a, b) | otherwise = Nothing -- Methods of Num -- -------------- evalAdd :: Elt a => NumType a -> (a,a) :-> a evalAdd (IntegralNumType ty) | IntegralDict <- integralDict ty = evalAdd' evalAdd (FloatingNumType ty) | FloatingDict <- floatingDict ty = evalAdd' evalAdd' :: (Elt a, Eq a, Num a) => (a,a) :-> a evalAdd' (untup2 -> Just (x,y)) env | Just a <- propagate env x , a == 0 = Just y evalAdd' arg env = eval2 (+) arg env evalSub :: Elt a => NumType a -> (a,a) :-> a evalSub ty@(IntegralNumType ty') | IntegralDict <- integralDict ty' = evalSub' ty evalSub ty@(FloatingNumType ty') | FloatingDict <- floatingDict ty' = evalSub' ty evalSub' :: forall a. (Elt a, Eq a, Num a) => NumType a -> (a,a) :-> a evalSub' ty (untup2 -> Just (x,y)) env | Just b <- propagate env y , b == 0 = Just x | Nothing <- propagate env x , Just b <- propagate env y = Just $ evalPrimApp env (PrimAdd ty) (Tuple $ NilTup `SnocTup` Const (fromElt (-b)) `SnocTup` x) | Just REFL <- matchOpenExp x y = Just $ Const (fromElt (0::a)) -- TLM: definitely the purview of rewrite rules evalSub' _ arg env = eval2 (-) arg env evalMul :: Elt a => NumType a -> (a,a) :-> a evalMul (IntegralNumType ty) | IntegralDict <- integralDict ty = evalMul' evalMul (FloatingNumType ty) | FloatingDict <- floatingDict ty = evalMul' evalMul' :: (Elt a, Eq a, Num a) => (a,a) :-> a evalMul' (untup2 -> Just (x,y)) env | Just a <- propagate env x , Nothing <- propagate env y = case a of 0 -> Just x 1 -> Just y _ -> Nothing evalMul' arg env = eval2 (*) arg env evalNeg :: Elt a => NumType a -> a :-> a evalNeg (IntegralNumType ty) | IntegralDict <- integralDict ty = eval1 negate evalNeg (FloatingNumType ty) | FloatingDict <- floatingDict ty = eval1 negate evalAbs :: Elt a => NumType a -> a :-> a evalAbs (IntegralNumType ty) | IntegralDict <- integralDict ty = eval1 abs evalAbs (FloatingNumType ty) | FloatingDict <- floatingDict ty = eval1 abs evalSig :: Elt a => NumType a -> a :-> a evalSig (IntegralNumType ty) | IntegralDict <- integralDict ty = eval1 signum evalSig (FloatingNumType ty) | FloatingDict <- floatingDict ty = eval1 signum -- Methods of Integral & Bits -- -------------------------- evalQuot :: Elt a => IntegralType a -> (a,a) :-> a evalQuot ty | IntegralDict <- integralDict ty = eval2 quot evalRem :: Elt a => IntegralType a -> (a,a) :-> a evalRem ty | IntegralDict <- integralDict ty = eval2 rem evalIDiv :: Elt a => IntegralType a -> (a,a) :-> a evalIDiv ty | IntegralDict <- integralDict ty = evalIDiv' evalIDiv' :: (Elt a, Integral a, Eq a) => (a,a) :-> a evalIDiv' (untup2 -> Just (x,y)) env | Just 1 <- propagate env y = Just x evalIDiv' arg env = eval2 div arg env evalMod :: Elt a => IntegralType a -> (a,a) :-> a evalMod ty | IntegralDict <- integralDict ty = eval2 mod evalBAnd :: Elt a => IntegralType a -> (a,a) :-> a evalBAnd ty | IntegralDict <- integralDict ty = eval2 (.&.) evalBOr :: Elt a => IntegralType a -> (a,a) :-> a evalBOr ty | IntegralDict <- integralDict ty = eval2 (.|.) evalBXor :: Elt a => IntegralType a -> (a,a) :-> a evalBXor ty | IntegralDict <- integralDict ty = eval2 xor evalBNot :: Elt a => IntegralType a -> a :-> a evalBNot ty | IntegralDict <- integralDict ty = eval1 complement evalBShiftL :: Elt a => IntegralType a -> (a,Int) :-> a evalBShiftL ty | IntegralDict <- integralDict ty = eval2 shiftL evalBShiftR :: Elt a => IntegralType a -> (a,Int) :-> a evalBShiftR ty | IntegralDict <- integralDict ty = eval2 shiftR evalBRotateL :: Elt a => IntegralType a -> (a,Int) :-> a evalBRotateL ty | IntegralDict <- integralDict ty = eval2 rotateL evalBRotateR :: Elt a => IntegralType a -> (a,Int) :-> a evalBRotateR ty | IntegralDict <- integralDict ty = eval2 rotateR -- Methods of Fractional & Floating -- -------------------------------- evalFDiv :: Elt a => FloatingType a -> (a,a) :-> a evalFDiv ty | FloatingDict <- floatingDict ty = evalFDiv' evalFDiv' :: (Elt a, Fractional a, Eq a) => (a,a) :-> a evalFDiv' (untup2 -> Just (x,y)) env | Just 1 <- propagate env y = Just x evalFDiv' arg env = eval2 (/) arg env evalRecip :: Elt a => FloatingType a -> a :-> a evalRecip ty | FloatingDict <- floatingDict ty = eval1 recip evalSin :: Elt a => FloatingType a -> a :-> a evalSin ty | FloatingDict <- floatingDict ty = eval1 sin evalCos :: Elt a => FloatingType a -> a :-> a evalCos ty | FloatingDict <- floatingDict ty = eval1 cos evalTan :: Elt a => FloatingType a -> a :-> a evalTan ty | FloatingDict <- floatingDict ty = eval1 tan evalAsin :: Elt a => FloatingType a -> a :-> a evalAsin ty | FloatingDict <- floatingDict ty = eval1 asin evalAcos :: Elt a => FloatingType a -> a :-> a evalAcos ty | FloatingDict <- floatingDict ty = eval1 acos evalAtan :: Elt a => FloatingType a -> a :-> a evalAtan ty | FloatingDict <- floatingDict ty = eval1 atan evalAsinh :: Elt a => FloatingType a -> a :-> a evalAsinh ty | FloatingDict <- floatingDict ty = eval1 asinh evalAcosh :: Elt a => FloatingType a -> a :-> a evalAcosh ty | FloatingDict <- floatingDict ty = eval1 acosh evalAtanh :: Elt a => FloatingType a -> a :-> a evalAtanh ty | FloatingDict <- floatingDict ty = eval1 atanh evalExpFloating :: Elt a => FloatingType a -> a :-> a evalExpFloating ty | FloatingDict <- floatingDict ty = eval1 P.exp evalSqrt :: Elt a => FloatingType a -> a :-> a evalSqrt ty | FloatingDict <- floatingDict ty = eval1 sqrt evalLog :: Elt a => FloatingType a -> a :-> a evalLog ty | FloatingDict <- floatingDict ty = eval1 log evalFPow :: Elt a => FloatingType a -> (a,a) :-> a evalFPow ty | FloatingDict <- floatingDict ty = eval2 (**) evalLogBase :: Elt a => FloatingType a -> (a,a) :-> a evalLogBase ty | FloatingDict <- floatingDict ty = eval2 logBase evalAtan2 :: Elt a => FloatingType a -> (a,a) :-> a evalAtan2 ty | FloatingDict <- floatingDict ty = eval2 atan2 evalTruncate :: (Elt a, Elt b) => FloatingType a -> IntegralType b -> a :-> b evalTruncate ta tb | FloatingDict <- floatingDict ta , IntegralDict <- integralDict tb = eval1 truncate evalRound :: (Elt a, Elt b) => FloatingType a -> IntegralType b -> a :-> b evalRound ta tb | FloatingDict <- floatingDict ta , IntegralDict <- integralDict tb = eval1 round evalFloor :: (Elt a, Elt b) => FloatingType a -> IntegralType b -> a :-> b evalFloor ta tb | FloatingDict <- floatingDict ta , IntegralDict <- integralDict tb = eval1 floor evalCeiling :: (Elt a, Elt b) => FloatingType a -> IntegralType b -> a :-> b evalCeiling ta tb | FloatingDict <- floatingDict ta , IntegralDict <- integralDict tb = eval1 ceiling -- Relational & Equality -- --------------------- evalLt :: ScalarType a -> (a,a) :-> Bool evalLt (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 (<) evalLt (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 (<) evalLt (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 (<) evalGt :: ScalarType a -> (a,a) :-> Bool evalGt (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 (>) evalGt (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 (>) evalGt (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 (>) evalLtEq :: ScalarType a -> (a,a) :-> Bool evalLtEq (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 (<=) evalLtEq (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 (<=) evalLtEq (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 (<=) evalGtEq :: ScalarType a -> (a,a) :-> Bool evalGtEq (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 (>=) evalGtEq (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 (>=) evalGtEq (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 (>=) evalEq :: ScalarType a -> (a,a) :-> Bool evalEq (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 (==) evalEq (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 (==) evalEq (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 (==) evalNEq :: ScalarType a -> (a,a) :-> Bool evalNEq (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 (/=) evalNEq (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 (/=) evalNEq (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 (/=) evalMax :: Elt a => ScalarType a -> (a,a) :-> a evalMax (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 max evalMax (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 max evalMax (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 max evalMin :: Elt a => ScalarType a -> (a,a) :-> a evalMin (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 min evalMin (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 min evalMin (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 min -- Logical operators -- ----------------- evalLAnd :: (Bool,Bool) :-> Bool evalLAnd (untup2 -> Just (x,y)) env | Just a <- propagate env x = Just $ if a then y else Const (fromElt False) evalLAnd _ _ = Nothing evalLOr :: (Bool,Bool) :-> Bool evalLOr (untup2 -> Just (x,y)) env | Just a <- propagate env x = Just $ if a then Const (fromElt True) else y evalLOr _ _ = Nothing evalLNot :: Bool :-> Bool evalLNot = eval1 not evalOrd :: Char :-> Int evalOrd = eval1 ord evalChr :: Int :-> Char evalChr = eval1 chr evalBoolToInt :: Bool :-> Int evalBoolToInt = eval1 fromEnum evalFromIntegral :: Elt b => IntegralType a -> NumType b -> a :-> b evalFromIntegral ta (IntegralNumType tb) | IntegralDict <- integralDict ta , IntegralDict <- integralDict tb = eval1 fromIntegral evalFromIntegral ta (FloatingNumType tb) | IntegralDict <- integralDict ta , FloatingDict <- floatingDict tb = eval1 fromIntegral -- Scalar primitives -- ----------------- evalPrimConst :: PrimConst a -> a evalPrimConst (PrimMinBound ty) = evalMinBound ty evalPrimConst (PrimMaxBound ty) = evalMaxBound ty evalPrimConst (PrimPi ty) = evalPi ty evalMinBound :: BoundedType a -> a evalMinBound (IntegralBoundedType ty) | IntegralDict <- integralDict ty = minBound evalMinBound (NonNumBoundedType ty) | NonNumDict <- nonNumDict ty = minBound evalMaxBound :: BoundedType a -> a evalMaxBound (IntegralBoundedType ty) | IntegralDict <- integralDict ty = maxBound evalMaxBound (NonNumBoundedType ty) | NonNumDict <- nonNumDict ty = maxBound evalPi :: FloatingType a -> a evalPi ty | FloatingDict <- floatingDict ty = pi
robeverest/accelerate
Data/Array/Accelerate/Trafo/Algebra.hs
Haskell
bsd-3-clause
20,751
module Lib.Task2 where import qualified Data.List as List task2 = sum $ filter isEven $ takeWhile (<4000000) fibs where fibs = List.unfoldr (\(a,b) -> Just (a,(b,a+b))) (0,1) isEven x = x `mod` 2 ==0
Austrotaxus/EulerProj
src/Lib/Task2.hs
Haskell
bsd-3-clause
221
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module Y.String ( YiString , Position , Size(..) , fromString, toString , toReverseString , fromLazyText, toLazyText , empty , singleton, null, length , append, concat , reverse , take, drop , takeScreenful , coordsOfPosition , coordsOfPositionWrappingToWidth , positionForCoords , cons, snoc , splitAt , splitAtLine , splitOnNewLines , wrappedLinesForWidth , countNewLines , insertAt , deleteAt , readFile, writeFile ) where import Prelude hiding (null, length, concat, splitAt, reverse, take, drop, lines , foldr, foldl , readFile, writeFile) import Control.Applicative hiding (empty) import Control.DeepSeq import Control.Lens hiding (cons, snoc, index) import Data.Binary import Data.Default import Data.Foldable (foldr, foldMap, toList) import Data.Int import Data.Monoid import qualified Data.Sequence as S import Data.String hiding (lines) import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.IO as TIO import qualified Data.Text.Lazy.Encoding as TE maxShortLineLength :: Int64 maxShortLineLength = 128 data Line = ShortLine TL.Text !Size | LongLine (S.Seq TL.Text) !Size deriving Show data YiString = YiString { fromYiString :: S.Seq Line , stringSize :: !Size } deriving Show mkLine :: TL.Text -> Line mkLine t = mkLine' t (Size (TL.length t)) mkLine' :: TL.Text -> Size -> Line mkLine' t (Size n) | n < maxShortLineLength = ShortLine t (Size n) mkLine' t size = LongLine (S.fromList $ map TL.fromStrict $ TL.toChunks t) size instance Monoid Line where mempty = ShortLine "" (Size 0) mappend (ShortLine l (Size lsize)) (ShortLine r (Size rsize)) | lsize + rsize <= maxShortLineLength = ShortLine (l <> r) (Size (lsize + rsize)) mappend (ShortLine l lsize) (ShortLine r rsize) = LongLine (S.fromList [l, r]) (lsize <> rsize) mappend (ShortLine l lsize) (LongLine rs rsize) = LongLine (l <| rs) (lsize <> rsize) mappend (LongLine ls lsize) (ShortLine r rsize) = LongLine (ls |> r) (lsize <> rsize) mappend (LongLine ls lsize) (LongLine rs rsize) = LongLine (ls <> rs) (lsize <> rsize) instance NFData Line where rnf (ShortLine t _) = rnf t rnf (LongLine chunks _) = rnf chunks instance NFData Size where rnf (Size i) = rnf i lineToLazyText :: Line -> TL.Text lineToLazyText (ShortLine t _) = t lineToLazyText (LongLine chunks _) = foldr mappend "" chunks instance Monoid YiString where mempty = "" mappend s (YiString _ (Size 0)) = s mappend (YiString _ (Size 0)) s = s mappend (YiString l sl) (YiString r sr) = YiString ((l' S.|> (lend <> rbegin)) <> r') (sl <> sr) where l' S.:> lend = S.viewr l rbegin S.:< r' = S.viewl r fromLazyText :: TL.Text -> YiString fromLazyText t = YiString (S.fromList $ map mkLine $ TL.splitOn "\n" t) (Size $ TL.length t) instance IsString YiString where fromString = fromLazyText . TL.pack instance Default YiString where def = mempty instance Eq YiString where lhs == rhs = stringSize lhs == stringSize rhs && toLazyText lhs == toLazyText rhs instance NFData YiString where rnf (YiString lines _) = rnf lines toLazyText :: YiString -> TL.Text toLazyText = TL.intercalate "\n" . foldr (mappend . return . lineToLazyText) [] . fromYiString toString :: YiString -> String toString = TL.unpack . toLazyText toReverseString :: YiString -> String toReverseString = toString . reverse type Position = Int64 -- | Size measured in characters, not bytes. newtype Size = Size { fromSize :: Int64 } deriving (Eq, Show, Ord) instance Monoid Size where mempty = Size 0 mappend (Size a) (Size b) = Size (a + b) singleton :: Char -> YiString singleton '\n' = YiString (S.fromList [mempty, mempty]) (Size 1) singleton c = YiString (S.singleton (ShortLine (TL.singleton c) (Size 1))) (Size 1) null :: YiString -> Bool null = TL.null . toLazyText empty :: YiString empty = mempty append :: YiString -> YiString -> YiString append = mappend concat :: [YiString] -> YiString concat = mconcat length :: YiString -> Size length (YiString _lines size) = size oneliner :: Line -> YiString oneliner l = YiString (S.singleton l) (lineSize l) findSplitBoundary :: Int64 -> S.Seq Line -> (Int64, Int) findSplitBoundary n64 = go 0 0 . toList where go !lengthAcc !index [] = (lengthAcc, index) go !lengthAcc !index (l:_) | lengthAcc + 1 + fromSize (lineSize l) > n64 = (lengthAcc, index) go !lengthAcc !index (l:ls) = go (lengthAcc + 1 + fromSize (lineSize l)) (succ index) ls splitAt :: Position -> YiString -> (YiString, YiString) splitAt n s | n <= 0 = (mempty, s) splitAt n s@(YiString _lines (Size size)) | fromIntegral n >= size = (s, mempty) splitAt n (YiString lines (Size size)) = (YiString leftLines (Size n64), YiString rightLines (Size (size - n64))) where n64 = fromIntegral n :: Int64 (positionAtStartOfBoundaryLine, boundaryLineIndex) = findSplitBoundary n64 lines mostlyLeftPart = S.take (succ boundaryLineIndex) lines strictlyRightPart = S.drop (succ boundaryLineIndex) lines strictlyLeftPart S.:> lastLeftLine = S.viewr mostlyLeftPart (leftLines, rightLines) = (strictlyLeftPart |> lineTake (n64 - positionAtStartOfBoundaryLine) lastLeftLine, lineDrop (n64 - positionAtStartOfBoundaryLine) lastLeftLine <| strictlyRightPart) splitAtLine :: Int64 -> YiString -> (YiString, YiString) splitAtLine 0 s = (mempty, s) splitAtLine i s@(YiString lines _) | fromIntegral i >= S.length lines = (s, mempty) splitAtLine i (YiString lines _) = ( YiString ls' (Size (fromIntegral i) <> foldMap lineSize ls') , YiString rs (Size (fromIntegral (S.length rs - 1)) <> foldMap lineSize rs) ) where ls = S.take (fromIntegral i) lines rs = S.drop (fromIntegral i) lines ls' = if S.length rs >= 1 || lineSize (ls ^. _last) > Size 0 then ls |> mempty else ls splitOnNewLines :: (Applicative f, Monoid (f YiString)) => YiString -> f YiString splitOnNewLines (YiString lines _) = foldMap go lines where go line = pure (YiString (S.singleton line) (lineSize line)) wrappedLinesForWidth :: (Applicative f, Monoid (f Line)) => Int64 -> YiString -> f YiString wrappedLinesForWidth w (YiString lines _) = oneliner <$> foldMap (lineSplitAtEvery w) lines countNewLines :: YiString -> Int64 countNewLines = pred . fromIntegral . S.length . fromYiString reverseLine :: Line -> Line reverseLine (ShortLine t size) = ShortLine (TL.reverse t) size reverseLine (LongLine chunks size) = LongLine (fmap TL.reverse (S.reverse chunks)) size reverse :: YiString -> YiString reverse (YiString lines size) = YiString (reverseLine <$> S.reverse lines) size take :: Int64 -> YiString -> YiString take n = fst . splitAt n takeScreenful :: Int64 -> Int64 -> YiString -> YiString takeScreenful w h (YiString _lines (Size size)) | w == 0 || h == 0 || size == 0 = mempty takeScreenful w h (YiString lines (Size size)) | headLineLength >= w * h = YiString (S.singleton (lineTake (w * h) headLine)) (Size (fromIntegral (w * h))) | h - headLineHeight > 0 = YiString (S.fromList [headLine, mempty]) (Size (fromIntegral (succ headLineLength))) <> takeScreenful w (h - headLineHeight) tailString | otherwise = YiString (S.singleton headLine) headLineSize where headLineHeight = max 1 (headLineLength `div` w + signum (headLineLength `rem` w)) headLineLength = fromIntegral $ fromSize headLineSize headLineSize = lineSize headLine (headLine, tailString) = case S.viewl lines of l S.:< tailLines -> (l, YiString tailLines (Size (size - 1 - fromIntegral headLineLength))) S.EmptyL -> error "lines can't be empty sequence." lineDrop :: Int64 -> Line -> Line lineDrop 0 l = l lineDrop n l | fromIntegral n >= fromSize (lineSize l) = mempty lineDrop n (ShortLine t (Size size)) = ShortLine (TL.drop (fromIntegral n) t) (Size (size - fromIntegral n)) lineDrop n l@(LongLine _chunks (Size size)) | size - fromIntegral n < maxShortLineLength = ShortLine (TL.drop (fromIntegral n) (lineToLazyText l)) (Size (size - fromIntegral n)) lineDrop n l@(LongLine _chunks (Size size)) = mkLine' (TL.drop (fromIntegral n) (lineToLazyText l)) (Size (size - fromIntegral n)) lineTake :: Int64 -> Line -> Line lineTake 0 _ = mempty lineTake n l | fromSize (lineSize l) < fromIntegral n = l lineTake n l = mkLine' (TL.take (fromIntegral n) (lineToLazyText l)) (Size (fromIntegral n)) lineSplitAtEvery :: (Applicative f, Monoid (f Line)) => Int64 -> Line -> f Line lineSplitAtEvery i l | fromSize (lineSize l) <= fromIntegral i = pure l lineSplitAtEvery i l = pure (lineTake i l) <> lineSplitAtEvery i (lineDrop i l) drop :: Int64 -> YiString -> YiString drop n = snd . splitAt n coordsOfPosition :: Position -> YiString -> (Int64, Int64) coordsOfPosition p s = coordsOfPositionWrappingToWidth p (fromSize (length s)) s coordsOfPositionWrappingToWidth :: Position -> Int64 -> YiString -> (Int64, Int64) coordsOfPositionWrappingToWidth pos w (YiString lines _) = go 0 (fromIntegral pos) (toList lines) where go !topOffset _p [] = (topOffset, 0) go !topOffset p (line : rest) = let lineLength = fromIntegral (fromSize (lineSize line)) in if p <= lineLength && p < w then (topOffset, p) else if p > lineLength then go (topOffset + max 1 (lineLength `div` w + signum (lineLength `rem` w))) (p - lineLength - 1) rest else (topOffset + p `div` w, p `rem` w) positionForCoords :: (Int64, Int64) -> YiString -> Position positionForCoords (y, x) s = fromIntegral x + fromSize (length (fst (splitAtLine y s))) lineSnoc :: Line -> Char -> Line lineSnoc (ShortLine t (Size size)) c | size > maxShortLineLength = LongLine (S.fromList [t, TL.singleton c]) (Size (succ size)) lineSnoc (ShortLine t (Size size)) c = ShortLine (t `TL.snoc` c) (Size (succ size)) lineSnoc (LongLine chunks (Size size)) c | TL.length (chunks ^. _last) >= maxShortLineLength = LongLine (chunks |> TL.singleton c) (Size (succ size)) lineSnoc (LongLine chunks (Size size)) c = LongLine (chunks & over _last (`TL.snoc` c)) (Size (succ size)) lineCons :: Char -> Line -> Line lineCons c (ShortLine t (Size size)) | size > maxShortLineLength = LongLine (S.fromList [TL.singleton c, t]) (Size (succ size)) lineCons c (ShortLine t (Size size)) = ShortLine (c `TL.cons` t) (Size (succ size)) lineCons c (LongLine chunks (Size size)) | TL.length (chunks ^. _head) >= maxShortLineLength = LongLine (TL.singleton c <| chunks) (Size (succ size)) lineCons c (LongLine chunks (Size size)) = LongLine (chunks & over _head (c `TL.cons`)) (Size (succ size)) lineSize :: Line -> Size lineSize (ShortLine _t size) = size lineSize (LongLine _chunks size) = size snoc :: YiString -> Char -> YiString snoc (YiString lines (Size size)) '\n' = YiString (lines |> mempty) (Size (succ size)) snoc (YiString lines (Size size)) c = YiString (lines & over _last (`lineSnoc` c)) (Size (succ size)) cons :: Char -> YiString -> YiString cons '\n' (YiString lines (Size size)) = YiString (mempty <| lines) (Size (succ size)) cons c (YiString lines (Size size)) = YiString (lines & over _head (c `lineCons`)) (Size (succ size)) insertAt :: YiString -> Position -> YiString -> YiString insertAt new pos old = oldLeft <> new <> oldRight where (oldLeft, oldRight) = splitAt pos old deleteAt :: Position -> Size -> YiString -> YiString deleteAt index (Size size) old = left <> right where (left, (_middle, right)) = splitAt size <$> splitAt index old readFile :: FilePath -> IO YiString readFile f = fromLazyText <$> TIO.readFile f writeFile :: FilePath -> YiString -> IO () writeFile f = TIO.writeFile f . toLazyText instance Binary YiString where get = fromLazyText . TE.decodeUtf8 <$> get put = put . TE.encodeUtf8 . toLazyText
ethercrow/y
src/Y/String.hs
Haskell
bsd-3-clause
12,497
{-# LANGUAGE TemplateHaskell #-} module WithArity (main) where import Criterion.Main import Criterion.Types import Data.Monoid import Data.Syntactic hiding (E) import Data.Syntactic.Functional main :: IO () main = defaultMainWith (defaultConfig {csvFile = Just "bench-results/withArity.csv"}) [ bgroup "eval 5" [ bench "gadt" $ nf evl (gExpr 5) , bench "Syntactic" $ nf evalDen (sExpr 5) ] , bgroup "eval 6" [ bench "gadt" $ nf evl (gExpr 6) , bench "Syntactic" $ nf evalDen (sExpr 6) ] , bgroup "eval 7" [ bench "gadt" $ nf evl (gExpr 7) , bench "Syntactic" $ nf evalDen (sExpr 7) ] , bgroup "size 5" [ bench "gadt" $ nf gSize (gExpr 5) , bench "Syntactic" $ nf size (sExpr 5) ] , bgroup "size 6" [ bench "gadt" $ nf gSize (gExpr 6) , bench "Syntactic" $ nf size (sExpr 6) ] , bgroup "size 7" [ bench "gadt" $ nf gSize (gExpr 7) , bench "Syntactic" $ nf size (sExpr 7) ]] -- Expressions gExpr :: Int -> E Int gExpr 0 = E0 1 gExpr 1 = E2 (E2 (E0 1) (E0 1)) (E1 (E0 1)) gExpr n = E10 (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) sExpr :: Int -> T' Int sExpr 0 = t0 1 sExpr 1 = t2 (t2 (t0 1) (t0 1)) (t1 (t0 1)) sExpr n = t10 (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) gSize :: E a -> Int gSize (E0 _) = 1 gSize (E1 a) = gSize a gSize (E2 a b) = gSize a + gSize b gSize (E3 a b c) = gSize a + gSize b + gSize c gSize (E5 a b c d e) = gSize a + gSize b + gSize c + gSize d + gSize e gSize (E10 a b c d e f g h i j) = gSize a + gSize b + gSize c + gSize d + gSize e + gSize f + gSize g + gSize h + gSize i + gSize j -- Comparing Syntactic with GADTs -- GADTs data E a where E0 :: a -> E a E1 :: E a -> E a E2 :: E a -> E a -> E a E3 :: E a -> E a -> E a -> E a E5 :: E a -> E a -> E a -> E a -> E a -> E a E10 :: E a -> E a -> E a -> E a -> E a -> E a -> E a -> E a -> E a -> E a -> E a evl :: E Int -> Int evl (E0 n) = n evl (E1 a) = evl a evl (E2 a b) = evl a + evl b evl (E3 a b c) = evl a + evl b + evl c evl (E5 a b c d e) = evl a + evl b + evl c + evl d + evl e evl (E10 a b c d e f g h i j) = evl a + evl b + evl c + evl d + evl e + evl f + evl g + evl h + evl i + evl j -- Syntactic data T a where T0 :: Num a => a -> T (Full a) T1 :: Num a => T (a :-> Full a) T2 :: Num a => T (a :-> a :-> Full a) T3 :: Num a => T (a :-> a :-> a :-> Full a) T5 :: Num a => T (a :-> a :-> a :-> a :-> a :-> Full a) T10 :: Num a => T (a :-> a :-> a :-> a :-> a :-> a :-> a :-> a :-> a :-> a :-> Full a) type T' a = AST T (Full a) t0 :: Num a => a -> T' a t0 = Sym . T0 t1 :: Num a => T' a -> T' a t1 a = Sym T1 :$ a t2 :: Num a => T' a -> T' a -> T' a t2 a b = Sym T2 :$ a :$ b t3 :: Num a => T' a -> T' a -> T' a -> T' a t3 a b c = Sym T3 :$ a :$ b :$ c t5 :: Num a => T' a -> T' a -> T' a -> T' a -> T' a -> T' a t5 a b c d e = Sym T5 :$ a :$ b :$ c :$ d :$ e t10 :: Num a => T' a -> T' a -> T' a -> T' a -> T' a -> T' a -> T' a -> T' a -> T' a -> T' a -> T' a t10 a b c d e f g h i j = Sym T10 :$ a :$ b :$ c :$ d :$ e :$ f :$ g :$ h :$ i:$ j instance Render T where renderSym (T0 a) = "T0" renderSym T1 = "T1" renderSym T2 = "T2" renderSym T3 = "T3" renderSym T5 = "T5" renderSym T10 = "T10" interpretationInstances ''T instance Eval T where evalSym (T0 a) = a evalSym T1 = id evalSym T2 = (+) evalSym T3 = \a b c -> a + b + c evalSym T5 = \a b c d e -> a + b + c + d + e evalSym T10 = \a b c d e f g h i j -> a + b + c + d + e + f + g + h + i + j instance EvalEnv T env where compileSym p (T0 a) = compileSymDefault p (T0 a) compileSym p T1 = compileSymDefault p T1 compileSym p T2 = compileSymDefault p T2 compileSym p T3 = compileSymDefault p T3 compileSym p T5 = compileSymDefault p T5 compileSym p T10 = compileSymDefault p T10
emwap/syntactic
benchmarks/WithArity.hs
Haskell
bsd-3-clause
4,415
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoStarIsType #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilyDependencies #-} {-# LANGUAGE TypeInType #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-} module Numeric.Wavelet.Continuous ( -- * Continuous Wavelet Transform CWD(..), mapCWD , CWDLine(..), mapCWDLine , LNorm(..), CWDOpts(..), defaultCWDO , cwd , cwdReal -- * Wavelets , AWavelet(..), mapAWavelet , morlet, morletFunc , meyer, meyerFunc , fbsp, fbspFunc ) where import Data.Complex import Data.Finite import Data.Foldable import Data.Maybe import Data.Ord import Data.Proxy import Data.Type.Equality import Data.Vector.Generic.Sized (Vector) import GHC.Generics (Generic) import GHC.TypeLits.Compare import GHC.TypeNats import Math.FFT.Base import Numeric.Wavelet.Internal.FFT import qualified Data.Vector.Generic as UVG import qualified Data.Vector.Generic.Sized as VG import qualified Data.Vector.Sized as V newtype CWD v n m a b = CWD { cwdLines :: V.Vector m (CWDLine v n a b) } deriving (Show, Functor) data CWDLine v n a b = CWDLine { cwdlData :: Vector v n b , cwdlScale :: Finite (n `Div` 2 + 1) -- ^ Scale factor, in number of ticks. , cwdlFreq :: a -- ^ The frequency associated with this scale, in inverse tick , cwdlCoI :: Finite (n `Div` 2 + 1) -- ^ How many items are /outside/ of the Cone of Influence, on each side. } deriving (Show, Functor) mapCWDLine :: (UVG.Vector v b, UVG.Vector v c) => (b -> c) -> CWDLine v n a b -> CWDLine v n a c mapCWDLine f (CWDLine d s q c) = CWDLine (VG.map f d) s q c mapCWD :: (UVG.Vector v b, UVG.Vector v c) => (b -> c) -> CWD v n m a b -> CWD v n m a c mapCWD f (CWD l) = CWD (mapCWDLine f <$> l) data LNorm = L1 | L2 deriving (Show, Eq, Ord, Enum, Bounded, Generic) data CWDOpts n = CWDO { cwdoNorm :: LNorm -- ^ wavelet normalization , cwdoMinScale :: Finite (n `Div` 2 + 1) -- ^ min scale (period) , cwdoMaxScale :: Finite (n `Div` 2 + 1) -- ^ max scale (period) } deriving (Show, Eq, Ord, Generic) defaultCWDO :: KnownNat n => CWDOpts n defaultCWDO = CWDO { cwdoNorm = L2 , cwdoMinScale = minBound , cwdoMaxScale = maxBound } -- | 'cwd' for complex-valued analytic wavelets. cwd :: forall v n m a b. ( UVG.Vector v (Complex b) , KnownNat n , KnownNat m , FFTWReal b , 1 <= n , RealFloat a ) => AWavelet v a (Complex b) -> CWDOpts n -> Vector v n (Complex b) -> CWD v n m a (Complex b) cwd AW{..} CWDO{..} xs = CWD . VG.generate $ \i -> let s = scaleOf i dt = 1/s in case awVector dt of VG.SomeSized (wv :: Vector v q (Complex b)) | Just Refl <- isLE (Proxy @1) (Proxy @q) , Just Refl <- isLE (Proxy @((q-1)`Div`2)) (Proxy @(q-1)) -> let ys :: Vector v (n + q - 1) (Complex b) ys = (* (realToFrac (normie dt) :+ 0)) `VG.map` convolve xs wv coi = fromMaybe maxBound . packFinite . round @a @Integer $ sqrt 2 * s s' = fromMaybe maxBound . packFinite . round @a @Integer $ s ys' :: Vector v n (Complex b) ys' = VG.slice @_ @((q - 1)`Div`2) @n @((q-1)-((q-1)`Div`2)) Proxy ys in CWDLine ys' s' (awFreq / s) coi _ -> error "Bad scale: wavelet vector is empty?" where n = natVal (Proxy @n) m = natVal (Proxy @m) normie :: a -> a normie = case cwdoNorm of L1 -> sqrt L2 -> id minScale = fromIntegral cwdoMinScale `max` 1 maxScale = (fromIntegral cwdoMaxScale `min` (fromIntegral n / (2 * sqrt 2))) `max` (minScale + 1) scaleStep = (log maxScale - log minScale) / (fromIntegral m - 1) scaleOf :: Finite m -> a scaleOf i = exp $ log minScale + fromIntegral i * scaleStep -- | 'cwd' for real-valued analytic wavelets. cwdReal :: forall v n m a b. ( UVG.Vector v b , UVG.Vector v (Complex b) , KnownNat n , KnownNat m , FFTWReal b , 1 <= n , RealFloat a ) => AWavelet v a b -> CWDOpts n -> Vector v n b -> CWD v n m a b cwdReal aw cwdo = mapCWD realPart . cwd (mapAWavelet (:+ 0) aw) cwdo . VG.map (:+ 0) -- | Analytical Wavelet data AWavelet v a b = AW { awVector :: a -> v b -- ^ generate a vector within awRange with a given dt , awFreq :: a -- ^ Dominant frequency component , awRange :: a -- ^ range away from zero outside of which wavelet can be considered negligible } deriving Functor mapAWavelet :: (UVG.Vector v b, UVG.Vector v c) => (b -> c) -> AWavelet v a b -> AWavelet v a c mapAWavelet f (AW v q r) = AW (UVG.map f . v) q r morlet :: (UVG.Vector v (Complex a), RealFloat a) => a -> AWavelet v a (Complex a) morlet σ = AW{..} where awRange = 4 (!awFreq, mf) = morletFunc_ σ awVector = renderFunc awRange mf morletFunc :: RealFloat a => a -> a -> Complex a morletFunc = snd . morletFunc_ morletFunc_ :: RealFloat a => a -> (a, a -> Complex a) morletFunc_ σ = (q, f) where f t = (c * exp(-t*t/2) :+ 0) * (exp (0 :+ (σ * t)) - (exp (-σ2/2) :+ 0)) !c = pi ** (-1/4) * (1 + exp (-σ2) - 2 * exp (-3/4*σ2)) ** (-1/2) !σ2 = σ * σ !q = converge 20 iter σ / (2 * pi) iter w = σ / (1 - exp (-σ * w)) meyer :: (UVG.Vector v a, RealFloat a) => AWavelet v a a meyer = AW{..} where awRange = 6 awVector = renderFunc awRange meyerFunc awFreq = 4 * pi / 3 meyerFunc :: RealFloat a => a -> a meyerFunc t | isNaN ψ || isInfinite ψ = 0 | otherwise = ψ where t' = t - 0.5 t'3 = t'**3 sinTerm = sin(4*pi/3*t') / pi ψ1 = (4/3/pi*t'*cos(2*pi/3*t') - sinTerm) / (t' - 16/9 * t'3) ψ2 = (8/3/pi*t'*cos(8*pi/3*t') + sinTerm) / (t' - 64/9 * t'3) ψ = ψ1 + ψ2 fbsp :: (UVG.Vector v (Complex a), FFTWReal a) => Int -- ^ m, >= 1 -> a -- ^ f_b, bandwidth -> a -- ^ f_c, wavelet center frequency -> AWavelet v a (Complex a) fbsp m fb fc = AW{..} where awRange = 4/fb awVector = renderFunc awRange (fbspFunc m fb fc) awFreq = autoDeriveFreq awRange awVector autoDeriveFreq :: (UVG.Vector v (Complex a), FFTWReal a) => a -> (a -> v (Complex a)) -> a autoDeriveFreq r fv = case fv 0.001 of VG.SomeSized v -> let vv = zip [1..] . map magnitude . VG.toList $ fft v (i,_) = maximumBy (comparing snd) vv in fromInteger i / (r * 2) _ -> error "bad vector" fbspFunc :: RealFloat a => Int -> a -> a -> a -> Complex a fbspFunc m fb fc t = ((sqrt fb * sinc (fb * t / fromIntegral m))^m :+ 0) * exp (0 :+ (2 * pi * fc * t)) where sinc x = sin x / x -- | Render the effective range of a wavelet (based on 'awRange'), centered -- around zero. Takes a timestep. renderFunc :: (UVG.Vector v b, RealFrac a) => a -- ^ range about zero -> (a -> b) -- ^ func -> a -- ^ dt -> v b renderFunc r f dt = UVG.generate (round n) $ \i -> f (fromIntegral i * dt - r) where n = r * 2 / dt converge :: (Fractional a, Ord a) => Int -- ^ maximum iterations -> (a -> a) -- ^ function to find the fixed point convergence -> a -- ^ starting value -> a converge n f = go 0 where go !i !x | i >= n = 0 | abs (x - y) < 0.00001 = x | otherwise = go (i + 1) y where !y = f x
mstksg/wavelets
src/Numeric/Wavelet/Continuous.hs
Haskell
bsd-3-clause
8,823
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module VForth.GameTextSpec ( TestableTitle(..) , TestableDescription(..) , unsafeRight , spec ) where import Test.Hspec import Test.QuickCheck.Gen import Test.QuickCheck import Data.Monoid ((<>)) import Data.Text.Arbitrary () import Data.Text (Text) import qualified Data.Text as Text import Control.Monad import VForth.GameText import Data.Text.Validation unsafeRight :: Show l => Either l r -> r unsafeRight (Right r) = r unsafeRight (Left l) = error ("Unexpectedly encountered left-value " <> show l) -- | Creates a generator for wrapped text-types that fulfills its constraints arbitraryFromConstraints :: ValidationConstraints -- ^ Provide minimum and maximum length, and regex -> Maybe String -- ^ Provides the list of valid chars. All are valid if Nothing -> (Text -> a) -- ^ A function to wrap the generated text in a newtype -> Gen a arbitraryFromConstraints ValidationConstraints{..} validChars makeFn = let validCharsGen = maybe arbitrary elements validChars validSubSeqGen = choose (vconsMinLength, vconsMaxLength) >>= \count -> replicateM count validCharsGen validTextGen = Text.pack <$> validSubSeqGen in makeFn <$> validTextGen newtype TestableTitle = TestableTitle Title deriving Show instance Arbitrary TestableTitle where arbitrary = arbitraryFromConstraints titleConstraints (Just titleChars) (TestableTitle . unsafeRight . title) newtype TestableDescription = TestableDescription Description deriving Show instance Arbitrary TestableDescription where arbitrary = arbitraryFromConstraints descriptionConstraints (Just descriptionChars) (TestableDescription . unsafeRight . description) spec :: Spec spec = return ()
budgefeeney/ventureforth
chap6/test/VForth/GameTextSpec.hs
Haskell
bsd-3-clause
1,846
{-# LANGUAGE GADTs, NoImplicitPrelude, UnicodeSyntax #-} module Data.Nested.Tree ( -- * Tree type Tree (..) -- * Query , fruit, forest , null, size , lookup, member -- * Construction , empty , singleton , fromFoldable , fromList -- * List , toList -- * Utils , unionTree , unionTreeWithKey , unionTreeWithKey' , unionTreeWith , apTree , foldrTreeWithAncestors1 , foldrTreeWithAncestorsAndLeafMarker1 ) where import Data.Function (flip) import Data.Maybe (Maybe) import Data.Ord (Ord) import Data.Int (Int) import Data.Bool (Bool) import Data.Foldable (Foldable) import Data.Traversable (Traversable) import Data.Nested.Internal ( Tree (..) , nullTree, fruit, forest , sizeTree , emptyTree , singletonTree , fromFoldableTree , fromListTree , toListTree , lookupTree , memberTree , unionTree , unionTreeWithKey , unionTreeWithKey' , unionTreeWith , apTree , foldrTreeWithAncestors1 , foldrTreeWithAncestorsAndLeafMarker1 ) empty ∷ α → Tree κ α empty = emptyTree null ∷ Tree κ α → Bool null = nullTree size ∷ Tree κ α → Int size = sizeTree lookup ∷ (Traversable φ, Ord κ) ⇒ φ κ → Tree κ α → (α, φ (Maybe α)) lookup = flip lookupTree member ∷ (Traversable φ, Ord κ) ⇒ φ κ → Tree κ α → φ Bool member = flip memberTree singleton ∷ Foldable φ ⇒ α → φ (κ,α) → Tree κ α singleton = singletonTree fromFoldable ∷ (Foldable φ, Foldable ψ, Ord κ) ⇒ α → ψ (φ (κ, α)) → Tree κ α fromFoldable = fromFoldableTree fromList ∷ (Ord κ) ⇒ α → [[(κ, α)]] → Tree κ α fromList = fromListTree toList ∷ Tree κ α → (α, [[(κ, α)]]) toList = toListTree
sheganinans/applicative-nestedmap
src/Data/Nested/Tree.hs
Haskell
bsd-3-clause
2,283
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ImplicitParams #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ConstrainedClassMethods #-} {-# LANGUAGE OverloadedStrings #-} -- We can do better syntactically! module MLModulesWithFunctors2 where import Prelude hiding (Monoid, mempty) import GHC.TypeLits class Module m where proof :: m data M (x :: Symbol) = M instance Module (M a) where proof = M class Module m => Monoid m where type T m :: * (<>) :: (?m :: m) => T m -> T m -> T m mempty :: (?m :: m) => T m instance Monoid (M "Add") where type T (M "Add") = Int (<>) = (+) mempty = 0 instance Monoid (M "Mul") where type T (M "Mul") = Int (<>) = (*) mempty = 1 class (Monoid (Additive m), Monoid (Multiplicative m)) => Semiring m where type Additive m type Multiplicative m plus :: (?m :: m) => T (Additive m) -> T (Additive m) -> T (Additive m) plus = (<>) where ?m = proof :: Additive m mul :: (?m :: m) => T (Multiplicative m) -> T (Multiplicative m) -> T (Multiplicative m) mul = (<>) where ?m = proof :: Multiplicative m zero :: (?m :: m) => T (Additive m) zero = (mempty) where ?m = proof :: Additive m one :: (?m :: m) => T (Multiplicative m) one = (mempty) where ?m = proof :: Multiplicative m instance Semiring (M "Natural")where type Additive (M "Natural") = M "Add" type Multiplicative (M "Natural") = M "Mul" foo :: Int foo = plus (mul 10 10) 100 where ?m = M @ "Natural"
sleexyz/haskell-fun
MLModulesWithFunctors2.hs
Haskell
bsd-3-clause
1,635
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} module Foreign.HPX.Types where import Bindings.HPX import Control.Applicative (Alternative) import Control.Monad (MonadPlus) import Control.Monad.Fix (MonadFix) import Control.Monad.IO.Class (MonadIO) import Control.Monad.Reader (ReaderT(..), ask, asks) import Data.Binary (Binary) import Data.Ix (Ix) import Data.Map (Map) import Data.Proxy (Proxy(..)) import Foreign import GHC.Show (appPrec, appPrec1) import GHC.StaticPtr (StaticKey, StaticPtr, staticKey, staticPtrInfo) import System.IO.Unsafe (unsafePerformIO) import Text.Printf (PrintfArg) class C c h where fromC :: c -> h toC :: h -> c newtype HPX a = HPX { unHPX :: ReaderT ActionEnv IO a } deriving ( Alternative , Applicative , Functor , Monad , MonadFix , MonadIO , MonadPlus ) askHPX :: HPX ActionEnv askHPX = HPX ask asksHPX :: (ActionEnv -> a) -> HPX a asksHPX = HPX . asks -- Unsafe runHPX :: ActionEnv -> HPX a -> IO a runHPX env (HPX hpx) = runReaderT hpx env newtype ActionEnv = ActionEnv { unActionEnv :: Map StaticKey (Ptr Action) } deriving ( Eq , Ord , Show ) newtype Action = Action { unAction :: C'hpx_action_t } deriving ( Bits , Bounded , Enum , Eq , FiniteBits , Integral , Ix , Num , Ord , PrintfArg , Read , Real , Show , Storable ) data ActionSpec where ActionSpec :: Binary a => ActionType -> StaticPtr (a -> HPX r) -> ActionSpec instance Eq ActionSpec where ActionSpec _ sp1 == ActionSpec _ sp2 = staticKey sp1 == staticKey sp2 instance Ord ActionSpec where compare (ActionSpec _ sp1) (ActionSpec _ sp2) = compare (staticKey sp1) (staticKey sp2) instance Show ActionSpec where showsPrec p (ActionSpec _ sp) = showParen (p > appPrec) $ showString "ActionSpec " . showsPrec appPrec1 (staticPtrInfo sp) data ActionType = Default | Task | Interrupt | Function | OpenCL deriving ( Bounded , Enum , Eq , Ix , Ord , Read , Show ) instance C C'hpx_action_type_t ActionType where fromC v | v == C'HPX_DEFAULT = Default | v == C'HPX_TASK = Task | v == C'HPX_INTERRUPT = Interrupt | v == C'HPX_FUNCTION = Function | v == C'HPX_OPENCL = OpenCL | otherwise = error $ "C C'hpx_action_type_t ActionType error fromC: " ++ show v toC Default = C'HPX_DEFAULT toC Task = C'HPX_TASK toC Interrupt = C'HPX_INTERRUPT toC Function = C'HPX_FUNCTION toC OpenCL = C'HPX_OPENCL type ActionAttribute = Word32 pattern NoAttribute :: ActionAttribute pattern NoAttribute = C'HPX_ATTR_NONE pattern Marshalled :: ActionAttribute pattern Marshalled = C'HPX_MARSHALLED pattern Pinned :: ActionAttribute pattern Pinned = C'HPX_PINNED pattern Internal :: ActionAttribute pattern Internal = C'HPX_INTERNAL pattern Vectored :: ActionAttribute pattern Vectored = C'HPX_VECTORED pattern Coalesced :: ActionAttribute pattern Coalesced = C'HPX_COALESCED pattern Compressed :: ActionAttribute pattern Compressed = C'HPX_COMPRESSED pattern NullAction :: Action pattern NullAction <- ((== Action c'HPX_ACTION_NULL) -> True) where NullAction = Action c'HPX_ACTION_NULL pattern Invalid :: Action pattern Invalid <- ((== Action c'HPX_ACTION_INVALID) -> True) where Invalid = Action c'HPX_ACTION_INVALID newtype Address = Address { unAddress :: C'hpx_addr_t } deriving ( Bits , Bounded , Enum , Eq , FiniteBits , Integral , Ix , Num , Ord , PrintfArg , Read , Real , Show , Storable ) here :: Address here = unsafePerformIO (Address <$> peek p'HPX_HERE) {-# NOINLINE here #-} pattern Here :: Address pattern Here <- ((== here) -> True) where Here = here newtype LCO r = LCO { unLCO :: C'hpx_addr_t } deriving ( Bits , Bounded , Enum , Eq , FiniteBits , Integral , Ix , Num , Ord , PrintfArg , Read , Real , Show , Storable ) pattern NullLCO :: LCO r pattern NullLCO <- ((== LCO c'HPX_NULL) -> True) where NullLCO = LCO c'HPX_NULL newtype Status = Status { unStatus :: C'hpx_status_t } deriving ( Bits , Bounded , Enum , Eq , FiniteBits , Integral , Ix , Num , Ord , PrintfArg , Read , Real , Show , Storable ) pattern Error :: Status pattern Error <- ((== Status c'HPX_ERROR) -> True) where Error = Status c'HPX_ERROR pattern Success :: Status pattern Success <- ((== Status c'HPX_SUCCESS) -> True) where Success = Status c'HPX_SUCCESS pattern Resend :: Status pattern Resend <- ((== Status c'HPX_RESEND) -> True) where Resend = Status c'HPX_RESEND pattern LCOError :: Status pattern LCOError <- ((== Status c'HPX_LCO_ERROR) -> True) where LCOError = Status c'HPX_LCO_ERROR pattern LCOChanEmpty :: Status pattern LCOChanEmpty <- ((== Status c'HPX_LCO_CHAN_EMPTY) -> True) where LCOChanEmpty = Status c'HPX_LCO_CHAN_EMPTY pattern LCOTimeout :: Status pattern LCOTimeout <- ((== Status c'HPX_LCO_TIMEOUT) -> True) where LCOTimeout = Status c'HPX_LCO_TIMEOUT pattern LCOReset :: Status pattern LCOReset <- ((== Status c'HPX_LCO_RESET) -> True) where LCOReset = Status c'HPX_LCO_RESET pattern ENoMem :: Status pattern ENoMem <- ((== Status c'HPX_ENOMEM) -> True) where ENoMem = Status c'HPX_ENOMEM pattern User :: Status pattern User <- ((== Status c'HPX_USER) -> True) where User = Status c'HPX_USER newtype Time = Time { unTime :: C'hpx_time_t } deriving ( Eq , Num , Ord , Read , Show , Storable ) type Promise = Proxy pattern Promise :: Promise a pattern Promise = Proxy
iu-parfunc/haskell-hpx
src/Foreign/HPX/Types.hs
Haskell
bsd-3-clause
6,488
-- | Let's experiment with HUnit some more -- basicaly : <https://wiki.haskell.org/HUnit_1.0_User's_Guide> module TestStuff where import Test.HUnit import Stuff
emaphis/Haskell-Practice
testing-project/test/TestStuff.hs
Haskell
bsd-3-clause
166
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} module Main (main) where import Control.Lens import Halytics.Metric import Halytics.Monitor import Test.Tasty import Test.Tasty.HUnit (testCase, (@=?)) main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [lastFive, periodOfThree, lens1] lastFive :: TestTree lastFive = testCase "Max |^ Last 5" $ Just 5 @=? res where monitor = generate :: Monitor (Max |^ Last 5) monitor' = foldl notify monitor entries entries = [32.0, 45, 33, 1, 2, 3, 4, 5] :: [Double] res = result monitor' :: Maybe Double periodOfThree :: TestTree periodOfThree = testCase "Max |^ PeriodOf 3" $ Just <$> [45, 3, 5] @=? res where monitor = generate :: Monitor (Max |^ PeriodOf 3) monitor' = foldl notify monitor entries entries = [32.0, 45, 33, 1, 2, 3, 4, 5] :: [Double] res = result monitor' :: [Maybe Double] -- lens1 :: TestTree lens1 = testCase "_1" $ Just 100 @=? res where monitor = generate :: Monitor TestC monitor' = foldl notify monitor entries monitor'' = monitor' & _1 %~ (`notify` 100) entries = [32.0, 45, 33, 1, 2, 3, 4, 5] :: [Double] res = monitor'' ^. _1 & result :: Maybe Double -- Test Monitor generation type TestA = Max type TestC = (Max, Max) type TestE = TestC type TestF = (TestE, TestC) _testA = generate :: Monitor TestA _testE = generate :: Monitor TestE _testF = generate :: Monitor TestF
nmattia/halytics
test/Test/Spec.hs
Haskell
bsd-3-clause
1,502
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Zero.KeyFetchToken.Client where import GHC.TypeLits import GHCJS.Types (JSVal) import Control.Applicative import Data.Monoid ((<>)) import Data.Proxy import qualified Data.Text as T import Data.Text (Text) import Data.Maybe (isJust, fromJust) import Data.Either.Extra (eitherToMaybe) import Reflex.Dom.Core import Servant.Reflex import Servant.API hiding (addHeader) import Zero.KeyFetchToken.Internal import Zero.Token import Zero.Hawk (rawHeaderField, rawHeader) -- For clients with KeyFetchToken routes -- KnownSymbol path, instance (HasClient t m api tag, Reflex t) => HasClient t m (KeyFetchToken :> api) tag where -- The client passes a HeaderOptions encoded as a raw JSVal in -- order to bypass MonadIO. Not the nicest type for a Dynamically -- varying stream... type Client t m (KeyFetchToken :> api) tag = Dynamic t (Either Text (Text, Text, JSVal)) -> Client t m api tag clientWithRoute Proxy q t req baseUrl hawkOpts = do let opts = fmap fromJust $ fmap eitherToMaybe hawkOpts let params = zipDynWith (\url (path, method, opts) -> (url `T.append` path, method, opts)) (showBaseUrl <$> baseUrl) opts let field = fmap Right $ fmap rawHeaderField params clientWithRoute (Proxy :: Proxy api) q t (req' field) baseUrl where req' field = addHeader "Authorization" field req
et4te/zero
src/Zero/KeyFetchToken/Client.hs
Haskell
bsd-3-clause
2,139
{-# LANGUAGE UndecidableInstances, FunctionalDependencies #-} module Feldspar.Multicore.Channel.Frontend where import Control.Monad.Operational.Higher import Control.Monad.Trans import Data.Ix import Data.Proxy import Data.Typeable import Feldspar hiding ((==)) import Feldspar.Data.Storable import Feldspar.Data.Vector hiding (ofLength, VecChanSizeSpec) import Feldspar.Multicore.CoreId import qualified Feldspar.Multicore.Channel.Representation as Rep import Feldspar.Multicore.Frontend import Feldspar.Multicore.Representation hiding (CoreId) import Feldspar.Representation import qualified Language.Embedded.Concurrent.CMD as Imp import qualified Language.Embedded.Expression as Imp import qualified Language.Embedded.Imperative as Imp -------------------------------------------------------------------------------- -- Channel interface -------------------------------------------------------------------------------- data CoreChan a where CoreChan :: CoreChanType a => SizeSpec a -> Rep.CoreChan (ElemType a) -> CoreChan a class PrimType (ElemType a) => CoreChanType a where type ElemType a :: * type SizeSpec a :: * newChan :: CoreId -> CoreId -> SizeSpec a -> Multicore (CoreChan a) class CoreChanType a => CoreTransferable' m a where type Slot a :: * newSlot :: CoreChan a -> m (Slot a) getSlot :: Slot a -> m a readChan :: CoreChan a -> Slot a -> m (Data Bool) writeChan :: CoreChan a -> a -> m (Data Bool) closeChan :: CoreChan a -> m () class CoreTransferType m a t | a -> t where toTransfer :: a -> m t fromTransfer :: t -> m a class (CoreTransferable' Host a, CoreTransferable' CoreComp a) => CoreTransferable a instance (CoreTransferable' Host a, CoreTransferable' CoreComp a) => CoreTransferable a one :: SizeSpec (Data a) one = () -------------------------------------------------------------------------------- -- Instances -------------------------------------------------------------------------------- instance PrimType a => CoreChanType (Data a) where type ElemType (Data a) = a type SizeSpec (Data a) = () newChan f t sz = Multicore $ fmap (CoreChan sz) $ singleInj $ Rep.NewChan f t 1 instance PrimType a => CoreTransferable' Host (Data a) where type Slot (Data a) = DArr a newSlot _ = newArr 1 getSlot s = getArr s 0 readChan (CoreChan _ c) = Host . readChanBuf' c 0 1 writeChan (CoreChan _ c) = lift . force >=> Host . writeChan' c closeChan (CoreChan _ c) = Host $ closeChan' c instance PrimType a => CoreTransferable' CoreComp (Data a) where type Slot (Data a) = DArr a newSlot _ = newArr 1 getSlot s = getArr s 0 readChan (CoreChan _ c) = CoreComp . readChanBuf' c 0 1 writeChan (CoreChan _ c) = lift . force >=> CoreComp . writeChan' c closeChan (CoreChan _ c) = CoreComp $ closeChan' c instance (Monad m, PrimType a) => CoreTransferType m (Data a) (Data a) where toTransfer = return fromTransfer = return instance PrimType a => CoreChanType (Store (DPull a)) where type ElemType (Store (DPull a)) = a type SizeSpec (Store (DPull a)) = Length newChan f t sz = Multicore $ fmap (CoreChan sz) $ singleInj $ Rep.NewChan f t sz instance PrimType a => CoreTransferable' Host (Store (DPull a)) where type Slot (Store (DPull a)) = Store (DPull a) newSlot (CoreChan l _) = newStore $ value l getSlot = return readChan (CoreChan _ c) s@(Store (lenRef, arr)) = do l :: Data Length <- unsafeFreezeRef lenRef Host $ readChanBuf' c 0 l arr writeChan (CoreChan _ c) s@(Store (lenRef, arr)) = do l :: Data Length <- unsafeFreezeRef lenRef Host $ writeChanBuf' c 0 l arr closeChan (CoreChan _ c) = Host $ closeChan' c instance PrimType a => CoreTransferable' CoreComp (Store (DPull a)) where type Slot (Store (DPull a)) = Store (DPull a) newSlot (CoreChan l _) = newStore $ value l getSlot = return readChan (CoreChan _ c) s@(Store (lenRef, arr)) = do l :: Data Length <- unsafeFreezeRef lenRef CoreComp $ readChanBuf' c 0 l arr writeChan (CoreChan _ c) s@(Store (lenRef, arr)) = do l :: Data Length <- unsafeFreezeRef lenRef CoreComp $ writeChanBuf' c 0 l arr closeChan (CoreChan _ c) = CoreComp $ closeChan' c instance (Monad m, PrimType a) => CoreTransferType m (Store (DPull a)) (Store (DPull a)) where toTransfer = return fromTransfer = return instance (MonadComp m, PrimType a) => CoreTransferType m (DPull a) (Store (DPull a)) where toTransfer = initStore fromTransfer = unsafeFreezeStore instance (MonadComp m, PrimType a) => CoreTransferType m (DPush m a) (Store (DPull a)) where toTransfer (Push len dump) = do s@(Store (_, arr)) <- newStore len let write i v = setArr arr i v dump write return s fromTransfer (Store (lenRef, arr)) = do len <- getRef lenRef return $ Push len $ \write -> for (0, 1, Excl len) $ \i -> do v <- getArr arr i write i v instance (MonadComp m, PrimType a) => CoreTransferType m (DArr a) (Store (DPull a)) where toTransfer x = do lenRef <- initRef $ Feldspar.length x return $ Store (lenRef, x) fromTransfer (Store (_, arr)) = return arr -------------------------------------------------------------------------------- -- Representation wrappers -------------------------------------------------------------------------------- readChanBuf' :: ( Typeable a, pred a , Imp.FreeExp exp, Imp.FreePred exp Bool , Rep.CoreChanCMD :<: instr, Monad m ) => Rep.CoreChan a -> exp Index -- ^ Offset in array to start writing -> exp Index -- ^ Elements to read -> DArr a -> ProgramT instr (Param2 exp pred) m (exp Bool) readChanBuf' ch off sz arr = singleInj $ Rep.ReadChan ch off sz arr writeChan' :: ( Typeable a, pred a , Imp.FreeExp exp, Imp.FreePred exp Bool , Rep.CoreChanCMD :<: instr, Monad m ) => Rep.CoreChan a -> exp a -> ProgramT instr (Param2 exp pred) m (exp Bool) writeChan' c = singleInj . Rep.WriteOne c writeChanBuf' :: ( Typeable a, pred a , Imp.FreeExp exp, Imp.FreePred exp Bool , Rep.CoreChanCMD :<: instr, Monad m ) => Rep.CoreChan a -> exp Index -- ^ Offset in array to start reading -> exp Index -- ^ Elements to write -> DArr a -> ProgramT instr (Param2 exp pred) m (exp Bool) writeChanBuf' ch off sz arr = singleInj $ Rep.WriteChan ch off sz arr closeChan' :: (Rep.CoreChanCMD :<: instr) => Rep.CoreChan a -> ProgramT instr (Param2 exp pred) m () closeChan' = singleInj . Rep.CloseChan
kmate/raw-feldspar-mcs
src/Feldspar/Multicore/Channel/Frontend.hs
Haskell
bsd-3-clause
6,955
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE ImpredicativeTypes #-} module Hack.Handler.Hyena (run, runWithConfig, ServerConf(..)) where import qualified Hack as Hack import Hyena.Server import Network.Wai as Wai import Prelude hiding ((.), (^)) import System.IO import Control.Monad import Data.Default import Data.Maybe import Data.Char import Control.Applicative ((<$>)) import qualified Data.ByteString.Char8 as C import qualified Data.ByteString as S import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.Map as M import Control.Concurrent (forkIO) import Control.Concurrent.Chan (newChan,writeChan,getChanContents) (.) :: a -> (a -> b) -> b a . f = f a infixl 9 . -- | this won't change the port or servername for hyena, use -- ./main -p 3000 to configure port -- this just make sure port and serverName are presented in Env data ServerConf = ServerConf { port :: Int, serverName :: String } instance Default ServerConf where def = ServerConf { port = 3000, serverName = "localhost" } to_s :: S.ByteString -> String to_s = C.unpack to_b :: String -> S.ByteString to_b = C.pack both_to_s :: (S.ByteString, S.ByteString) -> (String, String) both_to_s (x,y) = (to_s x, to_s y) both_to_b :: (String, String) -> (S.ByteString, S.ByteString) both_to_b (x,y) = (to_b x, to_b y) hyena_env_to_hack_env :: ServerConf -> Environment -> IO Hack.Env hyena_env_to_hack_env conf e = do -- i <- (L.fromChunks <$> e.Wai.input .enumToList) return def { Hack.requestMethod = convertRequestMethod (e.requestMethod) , Hack.scriptName = e.scriptName.to_s , Hack.pathInfo = e.pathInfo.to_s , Hack.queryString = e.queryString .fromMaybe (to_b "") .to_s , Hack.http = e.Wai.headers .map both_to_s , Hack.hackErrors = e.errors , Hack.serverPort = conf.port , Hack.serverName = conf.serverName -- , Hack.hackInput = i } where convertRequestMethod Wai.Options = Hack.OPTIONS convertRequestMethod Wai.Get = Hack.GET convertRequestMethod Wai.Head = Hack.HEAD convertRequestMethod Wai.Post = Hack.POST convertRequestMethod Wai.Put = Hack.PUT convertRequestMethod Wai.Delete = Hack.DELETE convertRequestMethod Wai.Trace = Hack.TRACE convertRequestMethod Wai.Connect = Hack.CONNECT enumToList enum = do ch <- newChan _ <- forkIO $ enum (writer ch) () getChanContents ch where writer ch () chunk = do writeChan ch chunk return (Right ()) enum_string :: L.ByteString -> IO Enumerator enum_string msg = do let s = msg.L.unpack.to_b let yieldBlock f z = do z' <- f z s case z' of Left z'' -> return z'' Right z'' -> return z'' return yieldBlock type WaiResponse = (Int, S.ByteString, Wai.Headers, Enumerator) hack_response_to_hyena_response :: Enumerator -> Hack.Response -> WaiResponse hack_response_to_hyena_response e r = ( r.Hack.status , r.Hack.status.show_status_message.fromMaybe "OK" .to_b , r.Hack.headers.map both_to_b , e ) hack_to_wai_with_config :: ServerConf -> Hack.Application -> Wai.Application hack_to_wai_with_config conf app env = do hack_env <- env.hyena_env_to_hack_env conf r <- app hack_env enum <- r.Hack.body.enum_string let hyena_response = r.hack_response_to_hyena_response enum return hyena_response run :: Hack.Application -> IO () run app = runWithConfig def app runWithConfig :: ServerConf -> Hack.Application -> IO () runWithConfig conf app = app.hack_to_wai_with_config conf .serve show_status_message :: Int -> Maybe String show_status_message x = status_code.M.lookup x status_code :: M.Map Int String status_code = [ x 100 "Continue" , x 101 "Switching Protocols" , x 200 "OK" , x 201 "Created" , x 202 "Accepted" , x 203 "Non-Authoritative Information" , x 204 "No Content" , x 205 "Reset Content" , x 206 "Partial Content" , x 300 "Multiple Choices" , x 301 "Moved Permanently" , x 302 "Found" , x 303 "See Other" , x 304 "Not Modified" , x 305 "Use Proxy" , x 307 "Temporary Redirect" , x 400 "Bad Request" , x 401 "Unauthorized" , x 402 "Payment Required" , x 403 "Forbidden" , x 404 "Not Found" , x 405 "Method Not Allowed" , x 406 "Not Acceptable" , x 407 "Proxy Authentication Required" , x 408 "Request Timeout" , x 409 "Conflict" , x 410 "Gone" , x 411 "Length Required" , x 412 "Precondition Failed" , x 413 "Request Entity Too Large" , x 414 "Request-URI Too Large" , x 415 "Unsupported Media Type" , x 416 "Requested Range Not Satisfiable" , x 417 "Expectation Failed" , x 500 "Internal Server Error" , x 501 "Not Implemented" , x 502 "Bad Gateway" , x 503 "Service Unavailable" , x 504 "Gateway Timeout" , x 505 "HTTP Version Not Supported" ] .M.fromList where x a b = (a, b)
np/hack-handler-hyena
src/Hack/Handler/Hyena.hs
Haskell
bsd-3-clause
5,627
{-# LANGUAGE BangPatterns #-} module LRUCache where import Control.Applicative ((<$>)) import Data.Hashable (Hashable, hash) import qualified Data.HashPSQ as HashPSQ import Data.IORef (IORef, newIORef, atomicModifyIORef') import Data.Int (Int64) import Data.Maybe (isNothing) import qualified Data.Vector as V import Prelude hiding (lookup) type Priority = Int64 data Cache k v = Cache { cCapacity :: !Int -- ^ The maximum number of elements in the queue , cSize :: !Int -- ^ The current number of elements in the queue , cTick :: !Priority -- ^ The next logical time , cQueue :: !(HashPSQ.HashPSQ k Priority v) } deriving (Eq, Show) empty :: Int -> Cache k v empty capacity | capacity < 1 = error "Cache.empty: capacity < 1" | otherwise = Cache { cCapacity = capacity , cSize = 0 , cTick = 0 , cQueue = HashPSQ.empty } trim :: (Hashable k, Ord k) => Cache k v -> Cache k v trim c | cTick c == maxBound = empty (cCapacity c) | cSize c > cCapacity c = c { cSize = cSize c - 1 , cQueue = HashPSQ.deleteMin (cQueue c) } | otherwise = c insert :: (Hashable k, Ord k) => k -> v -> Cache k v -> Cache k v insert key val c = trim $! let (mbOldVal, queue) = HashPSQ.insertView key (cTick c) val (cQueue c) in c { cSize = if isNothing mbOldVal then cSize c + 1 else cSize c , cTick = cTick c + 1 , cQueue = queue } lookup :: (Hashable k, Ord k) => k -> Cache k v -> Maybe (v, Cache k v) lookup k c = case HashPSQ.alter lookupAndBump k (cQueue c) of (Nothing, _) -> Nothing (Just x, q) -> let !c' = trim $ c {cTick = cTick c + 1, cQueue = q} in Just (x, c') where lookupAndBump Nothing = (Nothing, Nothing) lookupAndBump (Just (_, x)) = (Just x, Just ((cTick c), x))
Garygunn94/DFS
.stack-work/intero/intero2956XM1.hs
Haskell
bsd-3-clause
1,997
{-# LANGUAGE OverloadedStrings #-} module Main ( main ) where import Control.Error.Util (hush) import Control.Monad (void, when) import Control.Monad.State (StateT, liftIO, get, runStateT, modify) import Data.Aeson (decode) import qualified Data.Char as Char import qualified Data.Configurator as Conf import Data.Maybe (mapMaybe) import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.Encoding as T import qualified Data.Text.Lazy.IO as T import qualified Database.SQLite.Simple as DB import Database.SQLite.Simple (NamedParam((:=))) import Paths_Dikunt import Prelude hiding (Word, words) import System.Environment (getArgs) import System.IO (stdout, stdin, hSetBuffering, BufferMode(..)) import System.Random (randomRs, newStdGen) import qualified Text.Parsec as P import qualified Text.Parsec.Number as P import qualified Types.BotTypes as BT {- | The type replacements are stored under in the database. -} data Replacement = Replacement Int T.Text T.Text deriving (Show) instance DB.FromRow Replacement where fromRow = Replacement <$> DB.field <*> DB.field <*> DB.field instance DB.ToRow Replacement where toRow (Replacement id_ word replacement) = DB.toRow (id_, word, replacement) type BotNick = String type Word = String type Probability = Double {- | Lines from stdin are parsed to this structure which represents a request to - the plugin. -} data Request = HelpRequest BotNick | AddReplacement BotNick Word String | SetProbability Probability | WordSequence [Word] main :: IO () main = do (botnick:_) <- getArgs hSetBuffering stdout LineBuffering hSetBuffering stdin LineBuffering -- Load configuration. configName <- getDataFileName "data/dikunt.config" config <- Conf.load [ Conf.Required configName ] replacerProb <- Conf.require config "wordreplacer-probability" randoms <- randomRs (0.0, 1.0) <$> newStdGen requests <- parseRequests botnick <$> T.hGetContents stdin dbFile <- getDataFileName "data/WordReplacerData.db" DB.withConnection dbFile (\c -> do initDatabase c handleRequests c replacerProb (zip randoms requests)) {- | Handle a list of requests by performing the action requested. -} handleRequests :: DB.Connection -- ^ Database connection. -> Probability -- ^ Initial probability of replacing. -> [(Probability, Request)] -- ^ Connections together with the probability of writing message. -> IO () handleRequests conn initProb reqs = void $ runStateT (mapM_ handleRequest reqs) initialState where initialState = (initProb, conn) {- | State we run the wordreplacer in. The state contains a database connection - and the current probability. Words are only replaced if a generated number is - lower than the current probability. -} type WordReplacerState a = StateT (Probability, DB.Connection) IO a {- | Handle a single request. -} handleRequest :: (Probability, Request) -- ^ The request and the probability that the request should be served. -> WordReplacerState () handleRequest (_, HelpRequest botnick) = handleHelp botnick handleRequest (_, AddReplacement botnick word withString) = handleAdd botnick word withString handleRequest (_, SetProbability newProb) = handleSetProbability newProb handleRequest (prob , WordSequence words) = handleWordReplacement words prob {- | Add a replacement to the database if the word is not the nickname of the - bot. -} handleAdd :: BotNick -- ^ Nickname of bot. -> Word -- ^ Word to replace. -> String -- ^ String to replace with. -> WordReplacerState () handleAdd botnick word replacement | map Char.toLower botnick == map Char.toLower word = liftIO $ putStrLn "Din naughty dreng" | otherwise = do conn <- getConnection liftIO $ insertReplacement conn word replacement liftIO $ putStrLn ("Fra nu af ved jeg at " ++ word ++ " er det samme som " ++ replacement) {- | Print help message. -} handleHelp :: BotNick -- ^ Nickname of Dikunt bot. -> WordReplacerState () handleHelp nick = liftIO $ sequence_ [ putStrLn $ nick ++ ": wordreplacer add <word1>=<word2> - add word1=word2 " ++ "to database" , putStrLn $ nick ++ ": wordreplacer set probability <d> - set the " ++ "probability of writing replacements" , putStrLn $ nick ++ ": wordreplacer help - display this message" , putStrLn "otherwise replaces words from database in messages" ] {- | Set the current probability in the state. -} handleSetProbability :: Probability -- ^ The new probability. -> WordReplacerState () handleSetProbability newprob = do setProbability newprob liftIO $ putStrLn "Sandsynlighed er sat!" {- | Look up each word in the database and find replacements. -} handleWordReplacement :: [Word] -- ^ Words to find and output replacements for. -> Probability -- ^ The probability of printing the replacements. -> WordReplacerState () handleWordReplacement words prob = do threshold <- getCurrentProbability conn <- getConnection replacements <- liftIO $ getReplacements conn words when ((not . null) replacements && prob < threshold) $ liftIO (T.putStrLn $ replacementString (head replacements)) where replacementString (Replacement _ w rep) = T.concat ["Jeg tror ikke du mener " , w , " men " , rep] {- | Parse requests to the plugin from a text string. A new potential request - is assumed to be on each line. -} parseRequests :: BotNick -- ^ The nickname of the bot. -> T.Text -- ^ The text to parse requests from. -> [Request] parseRequests botnick = mapMaybe parseRequest . mapMaybe (decode . T.encodeUtf8) . T.lines where parseRequest (BT.ServerPrivMsg _ _ msg) = hush $ P.parse (request botnick) "" (BT.getMessage msg) parseRequest _ = Nothing {- | Type to use when parsing requests. -} type RequestParser a = P.Parsec String () a {- | Parse a request from a line of text. A request is one of HelpRequest, - AddReplacement, SetProbability or WordSequence. -} request :: BotNick -- ^ The nickname of the bot. -> RequestParser Request request botnick = P.choice requestTypes <* P.eof where requestTypes = map P.try [ helpRequest botnick , addReplacementRequest botnick , setProbabilityRequest botnick , wordListRequest ] {- | Parse a help request. -} helpRequest :: BotNick -- ^ Nickname of the bot. -> RequestParser Request helpRequest botnick = stringToken (botnick ++ ": ") *> stringToken "wordreplacer " *> stringToken "help" *> return (HelpRequest botnick) {- | Parse a request to add a replacement. -} addReplacementRequest :: BotNick -- ^ Nickname of the bot. -> RequestParser Request addReplacementRequest botnick = do void $ stringToken (botnick ++ ": ") void $ stringToken "wordreplacer " void $ stringToken "add " word <- P.many1 (P.noneOf " \n\t=") replacement <- trim <$> (P.char '=' *> P.many1 P.anyChar) return $ AddReplacement botnick word replacement {- | Parse a request to set the current probability. -} setProbabilityRequest :: BotNick -- ^ Nickname of the bot. -> RequestParser Request setProbabilityRequest botnick = do void $ stringToken (botnick ++ ": ") void $ stringToken "wordreplacer " void $ stringToken "set " void $ stringToken "probability " newprob <- P.floating if newprob >= 0.0 && newprob <= 1.0 then return $ SetProbability newprob else P.unexpected "Probability should be between 0 and 1" {- | Parses anything to a list of words separated by spaces and special - characters. -} wordListRequest :: RequestParser Request wordListRequest = WordSequence <$> token (word `P.sepBy` separator) where word = P.many1 $ P.noneOf " \n\t.:?!()[]{}," separator = P.many1 $ P.oneOf " \n\t.:?!()[]{}," {- | Initialize a database by creating it if it does not exist. -} initDatabase :: DB.Connection -- ^ Connection to database to initialize. -> IO () initDatabase conn = DB.execute_ conn "CREATE TABLE IF NOT EXISTS replacements \ \(id INTEGER PRIMARY KEY, word TEXT UNIQUE, replacement TEXT)" {- | Insert or replace a replacement in the database of replacements. -} insertReplacement :: DB.Connection -- ^ Database connection. -> Word -- ^ Word to replace. -> String -- ^ String to replace with. -> IO () insertReplacement conn word replacement = DB.executeNamed conn "INSERT OR REPLACE INTO replacements \ \(word, replacement) VALUES (:word, :replacement)" [":word" := map Char.toLower word, ":replacement" := replacement] {- | Get list of all replacements for words given. The function looks up each - word in the database and concatenates the result. -} getReplacements :: DB.Connection -- ^ Database connection. -> [Word] -- ^ List of words to find replacements for. -> IO [Replacement] getReplacements conn words = concat <$> mapM getReplacement words where getReplacement word = DB.queryNamed conn "SELECT id, word, replacement \ \FROM replacements WHERE word = :word COLLATE NOCASE" [":word" := word] :: IO [Replacement] {- | Get the current probability from the state. -} getCurrentProbability :: WordReplacerState Probability getCurrentProbability = fst <$> get {- | Get the database connection from the state. -} getConnection :: WordReplacerState DB.Connection getConnection = snd <$> get {- | Set the probability in the state. -} setProbability :: Probability -- ^ The new probability. -> WordReplacerState () setProbability newprob = modify (\(_, conn) -> (newprob, conn)) {- | Skips space on both sides of the parser. -} token :: RequestParser a -- ^ Parser to skip spaces around. -> RequestParser a token tok = P.spaces *> tok <* P.spaces {- | Parses the string given and skips all whitespace around it. -} stringToken :: String -- ^ String to parse. -> RequestParser String stringToken = token . P.string {- | Remove trailing whitespace and whitespace before string. -} trim :: String -- ^ String to trim. -> String trim = f . f where f = reverse . dropWhile Char.isSpace
bus000/Dikunt
plugins/WordReplacer/Main.hs
Haskell
bsd-3-clause
10,292
{-# LANGUAGE NamedFieldPuns #-} {- | Module : Mongo.Pid.Removal Description : Get Pid from Name Copyright : (c) Plow Technology 2014 License : MIT Maintainer : brent.phillips@plowtech.net Stability : unstable Portability : portable <Uses a name to grab the pid to remove old pid alarms from mongo> -} {-# LANGUAGE OverloadedStrings, NoImplicitPrelude ,RecordWildCards #-} module Mongo.Pid.Removal (removeMissingAlarms) where import BasicPrelude hiding (delete) import Persist.Mongo.Settings import Database.Persist import Data.Aeson import Data.Traversable import qualified Data.Set as S removeMissingAlarms :: Either String MongoDBConf -> IO () removeMissingAlarms (Left st) = putStrLn "Missing mongo config" >> print st removeMissingAlarms (Right mdbc) = do (joinKeys,alarmEntityKeys,alarmnames,locationNames) <- runDBConf mdbc $ do alarms <- selectList [] [] let pidlist = concat $ alarmPids.entityVal <$> alarms otclist <- selectList [OnpingTagCombinedPid <-. (Just <$> pidlist)] [] let badPidSet = makeCheckSets pidlist (catMaybes $ (onpingTagCombinedPid.entityVal <$> otclist)) let badPidLst = S.toList badPidSet let filteredAlarms = filterAlarmByPids badPidLst <$> alarms let filteredAlarmEntities = (catMaybes filteredAlarms) let alarmentitykeys = entityKey <$> filteredAlarmEntities joinkeys <- selectKeysList [AlarmJoinsAlarmId <-. alarmentitykeys] [] let alarmnames = alarmName.entityVal <$> filteredAlarmEntities alarmjoins <- selectList [AlarmJoinsId <-. joinkeys] [] let locationids = alarmJoinsLocationId.entityVal <$> alarmjoins locationentitys <- selectList [LocationId <-. locationids] [] let locationNames = locationName.entityVal <$> locationentitys --void $ traverse (delete.entityKey) (filteredAlarmEntities) --void $ traverse delete joinkeys return(joinkeys,alarmentitykeys,alarmnames,locationNames) --putStrLn $ show.encode $ joinKeys --putStrLn $ show.encode $ alarmEntityKeys putStrLn $ "Alarm Names Below:" putStrLn $ show.encode $ alarmnames putStrLn $ " " putStrLn $ "Location Names Below:" putStrLn $ show.encode $ locationNames filterAlarmByPids :: [Int] -> (Entity Alarm) -> Maybe (Entity Alarm) filterAlarmByPids pids a@(Entity _ (Alarm { alarmPids })) = const a <$> listToMaybe [p2 | p1 <- pids, p2 <- alarmPids, p1 == p2] makeCheckSets ::(Eq a, Ord a) => [a] -> [a] -> (S.Set a) makeCheckSets l1 l2 = let s1 = S.fromList l1 s2 = S.fromList l2 in (S.difference s1 s2)
plow-technologies/mongo-pid-removal
src/Mongo/Pid/Removal.hs
Haskell
bsd-3-clause
3,380
{-# LANGUAGE FlexibleContexts, DeriveDataTypeable #-} {-- | Parser for the lambda AST built of parsec. Converts to an intermediate format for antiexpressions -} module Language.Lambda.Untyped.Parser where import Text.Parsec import Text.Parsec.Language import Text.Parsec.Token import Language.Lambda.Untyped.Syntax import Data.Functor.Identity import Data.List import Data.Data type M = Identity data MetaExpr s = MVar (MetaSym s) | MApp (MetaExpr s) (MetaExpr s) | MLam (MetaSym s) (MetaExpr s) | AntiExpr String | AntiVar String deriving(Show, Eq, Data, Typeable) data MetaSym s = S s | AntiSym String deriving(Show, Eq, Data, Typeable) type Output s = MetaExpr s type SymParser u s = ParsecT String u M s top_expr :: SymParser u s -> ParsecT String u M (Output s) top_expr sp = do spaces e <- parse_expr sp spaces eof return e parse_expr :: SymParser u s -> ParsecT String u M (Output s) parse_expr sp = try (parse_aexpr sp) <|> try (parse_lambda sp) <|> try parse_anti_expr parse_aexpr :: SymParser u s -> ParsecT String u M (Output s) parse_aexpr sp = try (parse_app sp) <|> try (parse_atom sp) parse_anti_expr :: ParsecT String u M (Output s) parse_anti_expr = do _ <- string "$" i <- (identifier haskell) return $ AntiExpr i parse_lambda :: SymParser u s -> ParsecT String u M (Output s) parse_lambda sp = do _ <- char '\\' spaces sym <- (p_sym sp) <?> "lambda argument" _ <- char '.' spaces expr <- (parse_expr sp) <?> "lambda expression" return $ MLam sym expr parse_app :: SymParser u s -> ParsecT String u M (Output s) parse_app sp = do expr_0 <- (parse_atom sp) <?> "first apply argument" spaces as <- sepBy1 (parse_atom sp) spaces <?> "other apply arguments" return $ foldl' MApp expr_0 as parse_atom :: SymParser u s -> ParsecT String u M (Output s) parse_atom sp = try (parens' (parse_expr sp)) <|> try (parse_var sp) <|> try parse_anti_expr parse_var sp = try (parse_var' sp) <|> parse_anti_var parse_var' :: SymParser u s -> ParsecT String u M (Output s) parse_var' sp = do spaces sym <- (p_sym sp) <?> "Var symbol" return $ MVar sym parse_anti_var = do spaces _ <- string "*" i <- (identifier haskell) return $ AntiVar i p_sym :: SymParser u s -> ParsecT String u M (MetaSym s) p_sym sp = try (S `fmap` sp) <|> try parse_anti_sym parse_anti_sym :: ParsecT String u M (MetaSym s) parse_anti_sym = do _ <- string "^" i <- (identifier haskell) return $ AntiSym i parse_sym :: ParsecT String u M Sym parse_sym = many1 (alphaNum <|> char '_') <?> "symbol" parens' :: Stream s m Char => ParsecT s u m b -> ParsecT s u m b parens' p = do _ <- char '(' e <- p _ <- char ')' return e meta_to_expr :: MetaExpr s -> GExpr s meta_to_expr (MVar (S x)) = Var x meta_to_expr (MApp x y) = App (meta_to_expr x) (meta_to_expr y) meta_to_expr (MLam (S x) y) = Lam x (meta_to_expr y) meta_to_expr _ = error "meta_to_expr should not be used if the MetaExpr tree has AntiExpr" to_meta :: GExpr s -> MetaExpr s to_meta (Var x) = MVar (S x) to_meta (App x y) = MApp (to_meta x) (to_meta y) to_meta (Lam x y) = MLam (S x) (to_meta y)
jfischoff/LambdaPrettyQuote
src/Language/Lambda/Untyped/Parser.hs
Haskell
bsd-3-clause
3,423
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RankNTypes #-} -- | UPDATE operations on the wallet-spec state module Cardano.Wallet.Kernel.DB.Spec.Update ( -- * Errors NewPendingFailed(..) , NewForeignFailed(..) , ApplyBlockFailed(..) -- * Updates , newPending , newForeign , cancelPending , applyBlock , applyBlockPartial , switchToFork -- * Testing , observableRollbackUseInTestsOnly ) where import Universum hiding ((:|)) import Control.Lens (lazy, _Just) import qualified Data.Map.Strict as Map import Data.SafeCopy (base, deriveSafeCopy) import qualified Data.Set as Set import Formatting (bprint, build, (%)) import qualified Formatting.Buildable import Serokell.Util (listJsonIndent) import Serokell.Util.Text (listBuilderJSON) import Test.QuickCheck (Arbitrary (..), elements) import qualified Pos.Chain.Block as Core import Pos.Chain.Txp (TxIn, Utxo) import qualified Pos.Chain.Txp as Txp import qualified Pos.Core as Core import Pos.Core.Chrono (NewestFirst (..), OldestFirst (..)) import Cardano.Wallet.Kernel.DB.BlockContext import Cardano.Wallet.Kernel.DB.BlockMeta import Cardano.Wallet.Kernel.DB.InDb import Cardano.Wallet.Kernel.DB.Spec import Cardano.Wallet.Kernel.DB.Spec.Pending (Pending) import qualified Cardano.Wallet.Kernel.DB.Spec.Pending as Pending import Cardano.Wallet.Kernel.DB.Spec.Read import Cardano.Wallet.Kernel.DB.Util.AcidState import Cardano.Wallet.Kernel.NodeStateAdaptor (SecurityParameter (..)) import Cardano.Wallet.Kernel.PrefilterTx (PrefilteredBlock (..)) import qualified Cardano.Wallet.Kernel.Util.Core as Core import qualified Cardano.Wallet.Kernel.Util.Strict as Strict 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) {------------------------------------------------------------------------------- Errors -------------------------------------------------------------------------------} -- | Errors thrown by 'newPending' data NewPendingFailed = -- | Some inputs are not in the wallet utxo NewPendingInputsUnavailable (InDb (Set Txp.TxIn)) deriveSafeCopy 1 'base ''NewPendingFailed instance Buildable NewPendingFailed where build (NewPendingInputsUnavailable (InDb inputs)) = bprint ("NewPendingInputsUnavailable { inputs = " % listJsonIndent 4 % " }") (Set.toList inputs) -- NOTE(adn) Short-circuiting the rabbit-hole with this instance by generating -- an empty set, thus avoiding the extra dependency on @cardano-sl-core-test@. instance Arbitrary NewPendingFailed where arbitrary = pure . NewPendingInputsUnavailable . InDb $ mempty data NewForeignFailed = -- | Foreign transactions are not allowed spend from this wallet NewForeignInputsAvailable (InDb (Set Txp.TxIn)) deriveSafeCopy 1 'base ''NewForeignFailed instance Buildable NewForeignFailed where build (NewForeignInputsAvailable (InDb inputs)) = bprint ("NewForeignInputsAvailable { inputs = " % listJsonIndent 4 % " }") (Set.toList inputs) -- TODO: See comments for the 'Arbitrary' instance for 'NewPendingFailed' instance Arbitrary NewForeignFailed where arbitrary = pure . NewForeignInputsAvailable . InDb $ mempty -- | Errors thrown by 'applyBlock' data ApplyBlockFailed = -- | The block we're trying to apply does not fit onto the previous -- -- This indicates that the wallet has fallen behind the node (for example, -- when the node informs the wallet of a block but the wallet gets -- shut down before it gets a chance to process it). -- -- We record the context of the block we're trying to apply and the -- context of the most recent checkpoint. ApplyBlockNotSuccessor BlockContext (Maybe BlockContext) deriveSafeCopy 1 'base ''ApplyBlockFailed instance Buildable ApplyBlockFailed where build (ApplyBlockNotSuccessor context checkpoint) = bprint ("ApplyBlockNotSuccessor " % "{ context: " % build % ", checkpoint: " % build % "}" ) context checkpoint instance Buildable [ApplyBlockFailed] where build = listBuilderJSON instance Arbitrary ApplyBlockFailed where arbitrary = elements [] {------------------------------------------------------------------------------- Wallet spec mandated updates -------------------------------------------------------------------------------} -- | Insert new pending transaction into the specified wallet -- -- NOTE: Transactions to be inserted must be fully constructed and signed; we do -- not offer input selection at this layer. Instead, callers must get a snapshot -- of the database, construct a transaction asynchronously, and then finally -- submit the transaction. It is of course possible that the state of the -- database has changed at this point, possibly making the generated transaction -- invalid; 'newPending' therefore returns whether or not the transaction could -- be inserted. If this fails, the process must be started again. This is -- important for a number of reasons: -- -- * Input selection may be an expensive computation, and we don't want to -- lock the database while input selection is ongoing. -- * Transactions may be signed off-site (on a different machine or on a -- a specialized hardware device). -- * We do not actually have access to the key storage inside the DB layer -- (and do not store private keys) so we cannot actually sign transactions. newPending :: forall c. IsCheckpoint c => InDb Txp.TxAux -> Update' NewPendingFailed (Checkpoints c) () newPending (InDb tx) = do checkpoints <- get let (_available, unavailable) = cpCheckAvailable (Core.txIns tx) (checkpoints ^. currentCheckpoint) if Set.null unavailable then put $ insertPending checkpoints else throwError $ NewPendingInputsUnavailable (InDb unavailable) where insertPending :: Checkpoints c -> Checkpoints c insertPending = currentPending %~ Pending.insert tx -- | Insert new foreign transaction -- -- For foreign transactions we expect /none/ of the inputs to belong to the -- wallet. We may wish to relax this requirement later (or indeed get rid of -- the difference between these two pending sets altogether), but for now this -- strict separation makes it easier to see what's going on and limits the -- impact this has on the reasoning in the wallet spec. newForeign :: forall c. IsCheckpoint c => InDb Txp.TxAux -> Update' NewForeignFailed (Checkpoints c) () newForeign (InDb tx) = do checkpoints <- get let (available, _unavailable) = cpCheckAvailable (Core.txIns tx) (checkpoints ^. currentCheckpoint) if Set.null available then put $ insertForeign checkpoints else throwError $ NewForeignInputsAvailable (InDb available) where insertForeign :: Checkpoints c -> Checkpoints c insertForeign = currentForeign %~ Pending.insert tx -- | Cancel the input set of cancelled transactions from @all@ the 'Checkpoints' -- of an 'Account'. cancelPending :: forall c. IsCheckpoint c => Set Txp.TxId -> Checkpoints c -> Checkpoints c cancelPending txids = liftCheckpoints $ map (cpPending %~ Pending.delete txids) -- | Apply the prefiltered block to the specified wallet -- -- Additionally returns the set of transactions removed from pending. applyBlock :: SecurityParameter -> PrefilteredBlock -> Update' ApplyBlockFailed (Checkpoints Checkpoint) (Set Txp.TxId) applyBlock (SecurityParameter k) pb = do checkpoints@(Checkpoints ls) <- get let current = checkpoints ^. currentCheckpoint utxo = current ^. checkpointUtxo . fromDb balance = current ^. checkpointUtxoBalance . fromDb (utxo', balance') = updateUtxo pb (utxo, balance) (pending', rem1) = updatePending (pfbInputs pb) (current ^. checkpointPending) blockMeta' = updateBlockMeta pb (current ^. checkpointBlockMeta) (foreign', rem2) = updatePending (pfbForeignInputs pb) (current ^. checkpointForeign) if (pfbContext pb) `blockContextSucceeds` (current ^. checkpointContext . lazy) then do put $ Checkpoints . takeNewest k . NewestFirst $ Checkpoint { _checkpointUtxo = InDb utxo' , _checkpointUtxoBalance = InDb balance' , _checkpointPending = pending' , _checkpointBlockMeta = blockMeta' , _checkpointForeign = foreign' , _checkpointContext = Strict.Just $ pfbContext pb } SNE.<| getNewestFirst ls return $ Set.unions [rem1, rem2] else throwError $ ApplyBlockNotSuccessor (pfbContext pb) (current ^. checkpointContext . lazy) -- | Like 'applyBlock', but to a list of partial checkpoints instead -- -- NOTE: Unlike 'applyBlock', we do /NOT/ throw away partial checkpoints. If -- we did, it might be impossible for the historical checkpoints to ever -- catch up with the current ones. applyBlockPartial :: PrefilteredBlock -> Update' ApplyBlockFailed (Checkpoints PartialCheckpoint) (Set Txp.TxId) applyBlockPartial pb = do checkpoints@(Checkpoints ls) <- get let current = checkpoints ^. currentCheckpoint utxo = current ^. pcheckpointUtxo . fromDb balance = current ^. pcheckpointUtxoBalance . fromDb (utxo', balance') = updateUtxo pb (utxo, balance) (pending', rem1) = updatePending (pfbInputs pb) (current ^. pcheckpointPending) blockMeta' = updateLocalBlockMeta pb (current ^. pcheckpointBlockMeta) (foreign', rem2) = updatePending (pfbForeignInputs pb) (current ^. pcheckpointForeign) if (pfbContext pb) `blockContextSucceeds` (current ^. cpContext . lazy) then do put $ Checkpoints $ NewestFirst $ PartialCheckpoint { _pcheckpointUtxo = InDb utxo' , _pcheckpointUtxoBalance = InDb balance' , _pcheckpointPending = pending' , _pcheckpointBlockMeta = blockMeta' , _pcheckpointForeign = foreign' , _pcheckpointContext = pfbContext pb } SNE.<| getNewestFirst ls return $ Set.unions [rem1, rem2] else throwError $ ApplyBlockNotSuccessor (pfbContext pb) (current ^. cpContext . lazy) -- | Rollback -- -- For the base case, see section "Rollback -- Omitting checkpoints" in the -- formal specification. -- -- NOTE: Rollback is currently only supported for wallets that are fully up -- to date. Hence, we only support full checkpoints here. -- -- Additionally returns the set of pending transactions that got reintroduced, -- so that the submission layer can start sending those out again. -- -- This is an internal function only, and not exported. See 'switchToFork'. rollback :: Update' e (Checkpoints Checkpoint) Pending rollback = state $ \case Checkpoints (NewestFirst (c :| SL.Nil)) -> (Pending.empty, Checkpoints . NewestFirst $ c :| SL.Nil) Checkpoints (NewestFirst (c :| SL.Cons c' cs)) -> (Pending.union ((c' ^. cpPending) Pending.\\ (c ^. cpPending)) ((c' ^. cpForeign) Pending.\\ (c ^. cpForeign)), Checkpoints . NewestFirst $ (c' & cpPending %~ Pending.union (c ^. cpPending) & cpForeign %~ Pending.union (c ^. cpForeign)) :| cs) -- | Observable rollback, used in testing only -- -- See 'switchToFork' for production use. observableRollbackUseInTestsOnly :: Update' e (Checkpoints Checkpoint) Pending observableRollbackUseInTestsOnly = rollback -- | Switch to a fork -- -- Since rollback is only supported on wallets that are up to date wrt to -- the underlying node, the same goes for 'switchToFork'. -- -- Additionally returns the set of transactions that got introduced reintroduced -- (to the rollback) and the transactions that got removed from pending -- (since they are new confirmed). switchToFork :: SecurityParameter -> Maybe Core.HeaderHash -- ^ Roll back until we meet this block. -> OldestFirst [] PrefilteredBlock -- ^ Blocks to apply -> Update' ApplyBlockFailed (Checkpoints Checkpoint) (Pending, Set Txp.TxId) switchToFork k oldest blocksToApply = do -- Unless we are already at 'oldest', roll back until we find it. curCtx <- use currentContext reintroduced <- if curCtx ^? _Just . bcHash . fromDb /= oldest then rollbacks Pending.empty else return Pending.empty -- Now apply the blocks for new fork. applyBlocks reintroduced Set.empty (getOldestFirst blocksToApply) where rollbacks :: Pending -- Accumulator: reintroduced pending transactions -> Update' e (Checkpoints Checkpoint) Pending rollbacks !accNew = do curCtx <- use currentContext reintroduced <- rollback let acc = Pending.union accNew reintroduced prev = do ctx <- curCtx prevMain <- ctx ^. bcPrevMain . lazy return $ prevMain ^. fromDb case (prev == oldest, prev) of (True, _) -> return acc -- We rolled back everything we needed to. (False, Nothing) -> return acc -- The checkpoints began after the fork point. (False, Just _) -> rollbacks acc -- Keep going applyBlocks :: Pending -- Accumulator: reintroduced pending transactions -> Set Txp.TxId -- Accumulator: removed pending transactions -> [PrefilteredBlock] -> Update' ApplyBlockFailed (Checkpoints Checkpoint) (Pending, Set Txp.TxId) applyBlocks !accNew !accRem [] = return (accNew, accRem) applyBlocks !accNew !accRem (b:bs) = do removed <- applyBlock k b applyBlocks (Pending.delete removed accNew) (Set.union removed accRem) bs {------------------------------------------------------------------------------- Internal auxiliary -------------------------------------------------------------------------------} updateBlockMeta :: PrefilteredBlock -> BlockMeta -> BlockMeta updateBlockMeta = flip appendBlockMeta . pfbMeta updateLocalBlockMeta :: PrefilteredBlock -> LocalBlockMeta -> LocalBlockMeta updateLocalBlockMeta = flip appendLocalBlockMeta . pfbMeta -- | Update (utxo,balance) with the given prefiltered block updateUtxo :: PrefilteredBlock -> (Utxo, Core.Coin) -> (Utxo, Core.Coin) updateUtxo PrefilteredBlock{..} (utxo, balance) = (utxo', balance') where -- See wallet spec figure 6 (Wallet with prefiltering): -- -- * pfbOutputs corresponds to what the spec calls utxo^+ / txouts_b -- * pfbInputs corresponds to what the spec calls txins_b extendedInputs = Set.union pfbInputs pfbForeignInputs utxoUnion = Map.union utxo pfbOutputs utxoMin = utxoUnion `Core.utxoRestrictToInputs` extendedInputs utxo' = utxoUnion `Core.utxoRemoveInputs` extendedInputs balance' = Core.unsafeIntegerToCoin $ Core.coinToInteger balance + Core.utxoBalance pfbOutputs - Core.utxoBalance utxoMin -- | Update the pending transactions with the given prefiltered block -- -- Returns the set of transactions that got removed from the pending set. updatePending :: Set TxIn -> Pending -> (Pending, Set Txp.TxId) updatePending inputs = Pending.removeInputs inputs takeNewest :: Int -> NewestFirst StrictNonEmpty a -> NewestFirst StrictNonEmpty a takeNewest = liftNewestFirst . SNE.take
input-output-hk/pos-haskell-prototype
wallet/src/Cardano/Wallet/Kernel/DB/Spec/Update.hs
Haskell
mit
16,318
{-| PyValue contains instances for the 'PyValue' typeclass. The typeclass 'PyValue' converts Haskell values to Python values. This module contains instances of this typeclass for several generic types. These instances are used in the Haskell to Python generation of opcodes and constants, for example. -} {- Copyright (C) 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} {-# LANGUAGE ExistentialQuantification #-} module Ganeti.PyValue ( PyValue(..) , PyValueEx(..) ) where import Data.Char (isAscii, isPrint, ord) import Data.List (intercalate) import Data.Map (Map) import Data.ByteString (ByteString) import Text.Printf (printf) import qualified Data.ByteString.Char8 as BC8 (foldr) import qualified Data.Map as Map import qualified Data.Set as Set (toList) import Ganeti.BasicTypes -- * PyValue represents data types convertible to Python -- | Converts Haskell values into Python values -- -- This is necessary for the default values of opcode parameters and -- return values. For example, if a default value or return type is a -- Data.Map, then it must be shown as a Python dictioanry. class PyValue a where showValue :: a -> String showValueList :: [a] -> String showValueList xs = "[" ++ intercalate "," (map showValue xs) ++ "]" instance PyValue Bool where showValue = show instance PyValue Int where showValue = show instance PyValue Integer where showValue = show instance PyValue Double where showValue = show instance PyValue Char where showValue = show showValueList = show -- (Byte)String show output does not work out of the box as a Python -- string/bytes literal, especially when special characters are involved. -- For instance, show ByteString.Char8.pack "\x03" yields "\ETX", which means -- something completely different in Python. Thus, we need to implement our own -- showValue, which does the following: -- * escapes double quotes -- * leaves all printable ASCII characters intact -- * encodes all other characters in \xYZ form instance PyValue ByteString where showValue bs = "b'" ++ (BC8.foldr (\c acc -> formatChar c ++ acc) "" bs) ++ "'" where formatChar x | x == '\\' = "\\\\" | x == '\'' = "\\\'" | isAscii x && isPrint x = [x] | otherwise = (printf "\\x%02x" $ ord x) instance (PyValue a, PyValue b) => PyValue (a, b) where showValue (x, y) = "(" ++ showValue x ++ "," ++ showValue y ++ ")" instance (PyValue a, PyValue b, PyValue c) => PyValue (a, b, c) where showValue (x, y, z) = "(" ++ showValue x ++ "," ++ showValue y ++ "," ++ showValue z ++ ")" instance PyValue a => PyValue [a] where showValue = showValueList instance (PyValue k, PyValue a) => PyValue (Map k a) where showValue mp = "{" ++ intercalate ", " (map showPair (Map.assocs mp)) ++ "}" where showPair (k, x) = showValue k ++ ":" ++ showValue x instance PyValue a => PyValue (ListSet a) where showValue = showValue . Set.toList . unListSet -- * PyValue represents an unspecified value convertible to Python -- | Encapsulates Python default values data PyValueEx = forall a. PyValue a => PyValueEx a instance PyValue PyValueEx where showValue (PyValueEx x) = showValue x
ganeti/ganeti
src/Ganeti/PyValue.hs
Haskell
bsd-2-clause
4,431
{-# LANGUAGE PatternGuards, ViewPatterns #-} module Idris.Elab.Record(elabRecord) where import Idris.AbsSyntax import Idris.Docstrings import Idris.Error import Idris.Delaborate import Idris.Imports import Idris.Elab.Term import Idris.Coverage import Idris.DataOpts import Idris.Providers import Idris.Primitives import Idris.Inliner import Idris.PartialEval import Idris.DeepSeq import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting) import IRTS.Lang import Idris.ParseExpr (tryFullExpr) import Idris.Elab.Type import Idris.Elab.Data import Idris.Elab.Utils import Idris.Core.TT import Idris.Core.Evaluate import Idris.Elab.Data import Data.Maybe import Data.List import Control.Monad -- | Elaborate a record declaration elabRecord :: ElabInfo -> ElabWhat -> (Docstring (Either Err PTerm)) -- ^ The documentation for the whole declaration -> SyntaxInfo -> FC -> DataOpts -> Name -- ^ The name of the type being defined -> FC -- ^ The precise source location of the tycon name -> [(Name, FC, Plicity, PTerm)] -- ^ Parameters -> [(Name, Docstring (Either Err PTerm))] -- ^ Parameter Docs -> [(Maybe (Name, FC), Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] -- ^ Fields -> Maybe (Name, FC) -- ^ Constructor Name -> (Docstring (Either Err PTerm)) -- ^ Constructor Doc -> SyntaxInfo -- ^ Constructor SyntaxInfo -> Idris () elabRecord info what doc rsyn fc opts tyn nfc params paramDocs fields cname cdoc csyn = do logElab 1 $ "Building data declaration for " ++ show tyn -- Type constructor let tycon = generateTyConType params logElab 1 $ "Type constructor " ++ showTmImpls tycon -- Data constructor dconName <- generateDConName (fmap fst cname) let dconTy = generateDConType params fieldsWithNameAndDoc logElab 1 $ "Data constructor: " ++ showTmImpls dconTy -- Build data declaration for elaboration logElab 1 $ foldr (++) "" $ intersperse "\n" (map show dconsArgDocs) let datadecl = case what of ETypes -> PLaterdecl tyn NoFC tycon _ -> PDatadecl tyn NoFC tycon [(cdoc, dconsArgDocs, dconName, NoFC, dconTy, fc, [])] elabData info rsyn doc paramDocs fc opts datadecl -- Keep track of the record let parameters = [(n,pt) | (n, _, _, pt) <- params] let projections = [n | (n, _, _, _, _) <- fieldsWithName] addRecord tyn (RI parameters dconName projections) addIBC (IBCRecord tyn) when (what /= ETypes) $ do logElab 1 $ "fieldsWithName " ++ show fieldsWithName logElab 1 $ "fieldsWIthNameAndDoc " ++ show fieldsWithNameAndDoc elabRecordFunctions info rsyn fc tyn paramsAndDoc fieldsWithNameAndDoc dconName target sendHighlighting $ [(nfc, AnnName tyn Nothing Nothing Nothing)] ++ maybe [] (\(_, cnfc) -> [(cnfc, AnnName dconName Nothing Nothing Nothing)]) cname ++ [(ffc, AnnBoundName fn False) | (fn, ffc, _, _, _) <- fieldsWithName] where -- | Generates a type constructor. generateTyConType :: [(Name, FC, Plicity, PTerm)] -> PTerm generateTyConType ((n, nfc, p, t) : rest) = PPi p (nsroot n) nfc t (generateTyConType rest) generateTyConType [] = (PType fc) -- | Generates a name for the data constructor if none was specified. generateDConName :: Maybe Name -> Idris Name generateDConName (Just n) = return $ expandNS csyn n generateDConName Nothing = uniqueName (expandNS csyn $ sMN 0 ("Mk" ++ (show (nsroot tyn)))) where uniqueName :: Name -> Idris Name uniqueName n = do i <- getIState case lookupTyNameExact n (tt_ctxt i) of Just _ -> uniqueName (nextName n) Nothing -> return n -- | Generates the data constructor type. generateDConType :: [(Name, FC, Plicity, PTerm)] -> [(Name, FC, Plicity, PTerm, a)] -> PTerm generateDConType ((n, nfc, _, t) : ps) as = PPi impl (nsroot n) NoFC t (generateDConType ps as) generateDConType [] ((n, _, p, t, _) : as) = PPi p (nsroot n) NoFC t (generateDConType [] as) generateDConType [] [] = target -- | The target for the constructor and projection functions. Also the source of the update functions. target :: PTerm target = PApp fc (PRef fc [] tyn) $ map (uncurry asPRefArg) [(p, n) | (n, _, p, _) <- params] paramsAndDoc :: [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] paramsAndDoc = pad params paramDocs where pad :: [(Name, FC, Plicity, PTerm)] -> [(Name, Docstring (Either Err PTerm))] -> [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] pad ((n, fc, p, t) : rest) docs = let d = case lookup n docs of Just d' -> d Nothing -> emptyDocstring in (n, fc, p, t, d) : (pad rest docs) pad _ _ = [] dconsArgDocs :: [(Name, Docstring (Either Err PTerm))] dconsArgDocs = paramDocs ++ (dcad fieldsWithName) where dcad :: [(Name, FC, Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] -> [(Name, Docstring (Either Err PTerm))] dcad ((n, _, _, _, (Just d)) : rest) = ((nsroot n), d) : (dcad rest) dcad (_ : rest) = dcad rest dcad [] = [] fieldsWithName :: [(Name, FC, Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] fieldsWithName = fwn [] fields where fwn :: [Name] -> [(Maybe (Name, FC), Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] -> [(Name, FC, Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] fwn ns ((n, p, t, d) : rest) = let nn = case n of Just n' -> n' Nothing -> newName ns baseName withNS = expandNS rsyn (fst nn) in (withNS, snd nn, p, t, d) : (fwn (fst nn : ns) rest) fwn _ _ = [] baseName = (sUN "__pi_arg", NoFC) newName :: [Name] -> (Name, FC) -> (Name, FC) newName ns (n, nfc) | n `elem` ns = newName ns (nextName n, nfc) | otherwise = (n, nfc) fieldsWithNameAndDoc :: [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] fieldsWithNameAndDoc = fwnad fieldsWithName where fwnad :: [(Name, FC, Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] -> [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] fwnad ((n, nfc, p, t, d) : rest) = let doc = fromMaybe emptyDocstring d in (n, nfc, p, t, doc) : (fwnad rest) fwnad [] = [] elabRecordFunctions :: ElabInfo -> SyntaxInfo -> FC -> Name -- ^ Record type name -> [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] -- ^ Parameters -> [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] -- ^ Fields -> Name -- ^ Constructor Name -> PTerm -- ^ Target type -> Idris () elabRecordFunctions info rsyn fc tyn params fields dconName target = do logElab 1 $ "Elaborating helper functions for record " ++ show tyn logElab 1 $ "Fields: " ++ show fieldNames logElab 1 $ "Params: " ++ show paramNames -- The elaborated constructor type for the data declaration i <- getIState ttConsTy <- case lookupTyExact dconName (tt_ctxt i) of Just as -> return as Nothing -> tclift $ tfail $ At fc (Elaborating "record " tyn Nothing (InternalMsg "It seems like the constructor for this record has disappeared. :( \n This is a bug. Please report.")) -- The arguments to the constructor let constructorArgs = getArgTys ttConsTy logElab 1 $ "Cons args: " ++ show constructorArgs logElab 1 $ "Free fields: " ++ show (filter (not . isFieldOrParam') constructorArgs) -- If elaborating the constructor has resulted in some new implicit fields we make projection functions for them. let freeFieldsForElab = map (freeField i) (filter (not . isFieldOrParam') constructorArgs) -- The parameters for elaboration with their documentation -- Parameter functions are all prefixed with "param_". let paramsForElab = [((nsroot n), (paramName n), impl, t, d) | (n, _, _, t, d) <- params] -- zipParams i params paramDocs] -- The fields (written by the user) with their documentation. let userFieldsForElab = [((nsroot n), n, p, t, d) | (n, nfc, p, t, d) <- fields] -- All things we need to elaborate projection functions for, together with a number denoting their position in the constructor. let projectors = [(n, n', p, t, d, i) | ((n, n', p, t, d), i) <- zip (freeFieldsForElab ++ paramsForElab ++ userFieldsForElab) [0..]] -- Build and elaborate projection functions elabProj dconName projectors logElab 1 $ "Dependencies: " ++ show fieldDependencies logElab 1 $ "Depended on: " ++ show dependedOn -- All things we need to elaborate update functions for, together with a number denoting their position in the constructor. let updaters = [(n, n', p, t, d, i) | ((n, n', p, t, d), i) <- zip (paramsForElab ++ userFieldsForElab) [0..]] -- Build and elaborate update functions elabUp dconName updaters where -- | Creates a PArg from a plicity and a name where the term is a Placeholder. placeholderArg :: Plicity -> Name -> PArg placeholderArg p n = asArg p (nsroot n) Placeholder -- | Root names of all fields in the current record declarations fieldNames :: [Name] fieldNames = [nsroot n | (n, _, _, _, _) <- fields] paramNames :: [Name] paramNames = [nsroot n | (n, _, _, _, _) <- params] isFieldOrParam :: Name -> Bool isFieldOrParam n = n `elem` (fieldNames ++ paramNames) isFieldOrParam' :: (Name, a) -> Bool isFieldOrParam' = isFieldOrParam . fst isField :: Name -> Bool isField = flip elem fieldNames isField' :: (Name, a, b, c, d, f) -> Bool isField' (n, _, _, _, _, _) = isField n fieldTerms :: [PTerm] fieldTerms = [t | (_, _, _, t, _) <- fields] -- Delabs the TT to PTerm -- This is not good. -- However, for machine generated implicits, there seems to be no PTerm available. -- Is there a better way to do this without building the setters and getters as TT? freeField :: IState -> (Name, TT Name) -> (Name, Name, Plicity, PTerm, Docstring (Either Err PTerm)) freeField i arg = let nameInCons = fst arg -- The name as it appears in the constructor nameFree = expandNS rsyn (freeName $ fst arg) -- The name prefixed with "free_" plicity = impl -- All free fields are implicit as they are machine generated fieldType = delab i (snd arg) -- The type of the field doc = emptyDocstring -- No docmentation for machine generated fields in (nameInCons, nameFree, plicity, fieldType, doc) freeName :: Name -> Name freeName (UN n) = sUN ("free_" ++ str n) freeName (MN i n) = sMN i ("free_" ++ str n) freeName (NS n s) = NS (freeName n) s freeName n = n -- | Zips together parameters with their documentation. If no documentation for a given field exists, an empty docstring is used. zipParams :: IState -> [(Name, Plicity, PTerm)] -> [(Name, Docstring (Either Err PTerm))] -> [(Name, PTerm, Docstring (Either Err PTerm))] zipParams i ((n, _, t) : rest) ((_, d) : rest') = (n, t, d) : (zipParams i rest rest') zipParams i ((n, _, t) : rest) [] = (n, t, emptyDoc) : (zipParams i rest []) where emptyDoc = annotCode (tryFullExpr rsyn i) emptyDocstring zipParams _ [] [] = [] paramName :: Name -> Name paramName (UN n) = sUN ("param_" ++ str n) paramName (MN i n) = sMN i ("param_" ++ str n) paramName (NS n s) = NS (paramName n) s paramName n = n -- | Elaborate the projection functions. elabProj :: Name -> [(Name, Name, Plicity, PTerm, Docstring (Either Err PTerm), Int)] -> Idris () elabProj cn fs = let phArgs = map (uncurry placeholderArg) [(p, n) | (n, _, p, _, _, _) <- fs] elab = \(n, n', p, t, doc, i) -> -- Use projections in types do let t' = projectInType [(m, m') | (m, m', _, _, _, _) <- fs -- Parameters are already in scope, so just use them , not (m `elem` paramNames)] t elabProjection info n n' p t' doc rsyn fc target cn phArgs fieldNames i in mapM_ elab fs -- | Elaborate the update functions. elabUp :: Name -> [(Name, Name, Plicity, PTerm, Docstring (Either Err PTerm), Int)] -> Idris () elabUp cn fs = let args = map (uncurry asPRefArg) [(p, n) | (n, _, p, _, _, _) <- fs] elab = \(n, n', p, t, doc, i) -> elabUpdate info n n' p t doc rsyn fc target cn args fieldNames i (optionalSetter n) in mapM_ elab fs -- | Decides whether a setter should be generated for a field or not. optionalSetter :: Name -> Bool optionalSetter n = n `elem` dependedOn -- | A map from a field name to the other fields it depends on. fieldDependencies :: [(Name, [Name])] fieldDependencies = map (uncurry fieldDep) [(n, t) | (n, _, _, t, _) <- fields ++ params] where fieldDep :: Name -> PTerm -> (Name, [Name]) fieldDep n t = ((nsroot n), paramNames ++ fieldNames `intersect` allNamesIn t) -- | A list of fields depending on another field. dependentFields :: [Name] dependentFields = filter depends fieldNames where depends :: Name -> Bool depends n = case lookup n fieldDependencies of Just xs -> not $ null xs Nothing -> False -- | A list of fields depended on by other fields. dependedOn :: [Name] dependedOn = concat ((catMaybes (map (\x -> lookup x fieldDependencies) fieldNames))) -- | Creates and elaborates a projection function. elabProjection :: ElabInfo -> Name -- ^ Name of the argument in the constructor -> Name -- ^ Projection Name -> Plicity -- ^ Projection Plicity -> PTerm -- ^ Projection Type -> (Docstring (Either Err PTerm)) -- ^ Projection Documentation -> SyntaxInfo -- ^ Projection SyntaxInfo -> FC -> PTerm -- ^ Projection target type -> Name -- ^ Data constructor tame -> [PArg] -- ^ Placeholder Arguments to constructor -> [Name] -- ^ All Field Names -> Int -- ^ Argument Index -> Idris () elabProjection info cname pname plicity projTy pdoc psyn fc targetTy cn phArgs fnames index = do logElab 1 $ "Generating Projection for " ++ show pname let ty = generateTy logElab 1 $ "Type of " ++ show pname ++ ": " ++ show ty let lhs = generateLhs logElab 1 $ "LHS of " ++ show pname ++ ": " ++ showTmImpls lhs let rhs = generateRhs logElab 1 $ "RHS of " ++ show pname ++ ": " ++ showTmImpls rhs rec_elabDecl info EAll info ty let clause = PClause fc pname lhs [] rhs [] rec_elabDecl info EAll info $ PClauses fc [] pname [clause] where -- | The type of the projection function. generateTy :: PDecl generateTy = PTy pdoc [] psyn fc [] pname NoFC $ PPi expl recName NoFC targetTy projTy -- | The left hand side of the projection function. generateLhs :: PTerm generateLhs = let args = lhsArgs index phArgs in PApp fc (PRef fc [] pname) [pexp (PApp fc (PRef fc [] cn) args)] where lhsArgs :: Int -> [PArg] -> [PArg] lhsArgs 0 (_ : rest) = (asArg plicity (nsroot cname) (PRef fc [] pname_in)) : rest lhsArgs i (x : rest) = x : (lhsArgs (i-1) rest) lhsArgs _ [] = [] -- | The "_in" name. Used for the lhs. pname_in :: Name pname_in = rootname -- in_name rootname rootname :: Name rootname = nsroot cname -- | The right hand side of the projection function. generateRhs :: PTerm generateRhs = PRef fc [] pname_in -- | Creates and elaborates an update function. -- If 'optional' is true, we will not fail if we can't elaborate the update function. elabUpdate :: ElabInfo -> Name -- ^ Name of the argument in the constructor -> Name -- ^ Field Name -> Plicity -- ^ Field Plicity -> PTerm -- ^ Field Type -> (Docstring (Either Err PTerm)) -- ^ Field Documentation -> SyntaxInfo -- ^ Field SyntaxInfo -> FC -> PTerm -- ^ Projection Source Type -> Name -- ^ Data Constructor Name -> [PArg] -- ^ Arguments to constructor -> [Name] -- ^ All fields -> Int -- ^ Argument Index -> Bool -- ^ Optional -> Idris () elabUpdate info cname pname plicity pty pdoc psyn fc sty cn args fnames i optional = do logElab 1 $ "Generating Update for " ++ show pname let ty = generateTy logElab 1 $ "Type of " ++ show set_pname ++ ": " ++ show ty let lhs = generateLhs logElab 1 $ "LHS of " ++ show set_pname ++ ": " ++ showTmImpls lhs let rhs = generateRhs logElab 1 $ "RHS of " ++ show set_pname ++ ": " ++ showTmImpls rhs let clause = PClause fc set_pname lhs [] rhs [] idrisCatch (do rec_elabDecl info EAll info ty rec_elabDecl info EAll info $ PClauses fc [] set_pname [clause]) (\err -> logElab 1 $ "Could not generate update function for " ++ show pname) {-if optional then logElab 1 $ "Could not generate update function for " ++ show pname else tclift $ tfail $ At fc (Elaborating "record update function " pname err)) -} where -- | The type of the update function. generateTy :: PDecl generateTy = PTy pdoc [] psyn fc [] set_pname NoFC $ PPi expl (nsroot pname) NoFC pty $ PPi expl recName NoFC sty (substInput sty) where substInput = substMatches [(cname, PRef fc [] (nsroot pname))] -- | The "_set" name. set_pname :: Name set_pname = set_name pname set_name :: Name -> Name set_name (UN n) = sUN ("set_" ++ str n) set_name (MN i n) = sMN i ("set_" ++ str n) set_name (NS n s) = NS (set_name n) s set_name n = n -- | The left-hand side of the update function. generateLhs :: PTerm generateLhs = PApp fc (PRef fc [] set_pname) [pexp $ PRef fc [] pname_in, pexp constructorPattern] where constructorPattern :: PTerm constructorPattern = PApp fc (PRef fc [] cn) args -- | The "_in" name. pname_in :: Name pname_in = in_name rootname rootname :: Name rootname = nsroot pname -- | The right-hand side of the update function. generateRhs :: PTerm generateRhs = PApp fc (PRef fc [] cn) (newArgs i args) where newArgs :: Int -> [PArg] -> [PArg] newArgs 0 (_ : rest) = (asArg plicity (nsroot cname) (PRef fc [] pname_in)) : rest newArgs i (x : rest) = x : (newArgs (i-1) rest) newArgs _ [] = [] -- | Post-fixes a name with "_in". in_name :: Name -> Name in_name (UN n) = sMN 0 (str n ++ "_in") in_name (MN i n) = sMN i (str n ++ "_in") in_name (NS n s) = NS (in_name n) s in_name n = n -- | Creates a PArg with a given plicity, name, and term. asArg :: Plicity -> Name -> PTerm -> PArg asArg (Imp os _ _ _) n t = PImp 0 False os n t asArg (Exp os _ _) n t = PExp 0 os n t asArg (Constraint os _) n t = PConstraint 0 os n t asArg (TacImp os _ s) n t = PTacImplicit 0 os n s t -- | Machine name "rec". recName :: Name recName = sMN 0 "rec" recRef = PRef emptyFC [] recName projectInType :: [(Name, Name)] -> PTerm -> PTerm projectInType xs = mapPT st where st :: PTerm -> PTerm st (PRef fc hls n) | Just pn <- lookup n xs = PApp fc (PRef fc hls pn) [pexp recRef] st t = t -- | Creates an PArg from a plicity and a name where the term is a PRef. asPRefArg :: Plicity -> Name -> PArg asPRefArg p n = asArg p (nsroot n) $ PRef emptyFC [] (nsroot n)
aaronc/Idris-dev
src/Idris/Elab/Record.hs
Haskell
bsd-3-clause
20,611
----------------------------------------------------------------------------- -- | -- License : BSD-3-Clause -- Maintainer : Oleg Grenrus <oleg.grenrus@iki.fi> -- -- The Github Repo Contents API, as documented at -- <https://developer.github.com/v3/repos/contents/> module GitHub.Endpoints.Repos.Contents ( -- * Querying contents contentsForR, readmeForR, archiveForR, -- ** Create createFileR, -- ** Update updateFileR, -- ** Delete deleteFileR, module GitHub.Data ) where import GitHub.Data import GitHub.Internal.Prelude import Prelude () import Data.Maybe (maybeToList) import qualified Data.Text.Encoding as TE import Network.URI (URI) contentsForR :: Name Owner -> Name Repo -> Text -- ^ file or directory -> Maybe Text -- ^ Git commit -> Request k Content contentsForR user repo path ref = query ["repos", toPathPart user, toPathPart repo, "contents", path] qs where qs = maybe [] (\r -> [("ref", Just . TE.encodeUtf8 $ r)]) ref readmeForR :: Name Owner -> Name Repo -> Request k Content readmeForR user repo = query ["repos", toPathPart user, toPathPart repo, "readme"] [] -- | Get archive link. -- See <https://developer.github.com/v3/repos/contents/#get-archive-link> archiveForR :: Name Owner -> Name Repo -> ArchiveFormat -- ^ The type of archive to retrieve -> Maybe Text -- ^ Git commit -> GenRequest 'MtRedirect rw URI archiveForR user repo format ref = Query path [] where path = ["repos", toPathPart user, toPathPart repo, toPathPart format] <> maybeToList ref -- | Create a file. -- See <https://developer.github.com/v3/repos/contents/#create-a-file> createFileR :: Name Owner -> Name Repo -> CreateFile -> Request 'RW ContentResult createFileR user repo body = command Put ["repos", toPathPart user, toPathPart repo, "contents", createFilePath body] (encode body) -- | Update a file. -- See <https://developer.github.com/v3/repos/contents/#update-a-file> updateFileR :: Name Owner -> Name Repo -> UpdateFile -> Request 'RW ContentResult updateFileR user repo body = command Put ["repos", toPathPart user, toPathPart repo, "contents", updateFilePath body] (encode body) -- | Delete a file. -- See <https://developer.github.com/v3/repos/contents/#delete-a-file> deleteFileR :: Name Owner -> Name Repo -> DeleteFile -> GenRequest 'MtUnit 'RW () deleteFileR user repo body = Command Delete ["repos", toPathPart user, toPathPart repo, "contents", deleteFilePath body] (encode body)
jwiegley/github
src/GitHub/Endpoints/Repos/Contents.hs
Haskell
bsd-3-clause
2,607
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE StandaloneDeriving #-} ----------------------------------------------------------------------------- -- | -- Module : DieHard -- Copyright : (C) 2017, ATS Advanced Telematic Systems GmbH -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Stevan Andjelkovic <stevan.andjelkovic@strath.ac.uk> -- Stability : provisional -- Portability : non-portable (GHC extensions) -- -- This module contains a solution to the water jug puzzle featured in -- /Die Hard 3/. -- ----------------------------------------------------------------------------- module DieHard ( Command(..) , Model(..) , initModel , transitions , prop_dieHard ) where import Data.Kind (Type) import GHC.Generics (Generic, Generic1) import Prelude import Test.QuickCheck (Gen, Property, oneof, (===)) import Test.QuickCheck.Monadic (monadicIO) import Test.StateMachine import qualified Test.StateMachine.Types.Rank2 as Rank2 ------------------------------------------------------------------------ -- The problem is to measure exactly 4 liters of water given a 3- and -- 5-liter jug. -- We start of defining the different actions that are allowed: data Command (r :: Type -> Type) = FillBig -- Fill the 5-liter jug. | FillSmall -- Fill the 3-liter jug. | EmptyBig -- Empty the 5-liter jug. | EmptySmall | SmallIntoBig -- Pour the contents of the 3-liter jug -- into 5-liter jug. | BigIntoSmall deriving stock (Eq, Show, Generic1) deriving anyclass (Rank2.Functor, Rank2.Foldable, Rank2.Traversable, CommandNames) data Response (r :: Type -> Type) = Done deriving stock (Show, Generic1) deriving anyclass (Rank2.Foldable) ------------------------------------------------------------------------ -- The model (or state) keeps track of what amount of water is in the -- two jugs. data Model (r :: Type -> Type) = Model { bigJug :: Int , smallJug :: Int } deriving stock (Show, Eq, Generic) deriving anyclass instance ToExpr (Model Concrete) initModel :: Model r initModel = Model 0 0 ------------------------------------------------------------------------ -- There are no pre-conditions for our actions. That simply means that -- any action can happen at any state. preconditions :: Model Symbolic -> Command Symbolic -> Logic preconditions _ _ = Top -- The transitions describe how the actions change the state. transitions :: Model r -> Command r -> Response r -> Model r transitions m FillBig _ = m { bigJug = 5 } transitions m FillSmall _ = m { smallJug = 3 } transitions m EmptyBig _ = m { bigJug = 0 } transitions m EmptySmall _ = m { smallJug = 0 } transitions (Model big small) SmallIntoBig _ = let big' = min 5 (big + small) in Model { bigJug = big' , smallJug = small - (big' - big) } transitions (Model big small) BigIntoSmall _ = let small' = min 3 (big + small) in Model { bigJug = big - (small' - small) , smallJug = small' } -- The post-condition is used in a bit of a funny way. Recall that we -- want to find a series of actions that leads to the big jug containing -- 4 liters. So the idea is to state an invariant saying that the big -- jug is NOT equal to 4 after we performed any action. If we happen to -- find a series of actions where this is not true, i.e. the big jug -- actually does contain 4 liters, then a minimal counter example will -- be presented -- this will be our solution. postconditions :: Model Concrete -> Command Concrete -> Response Concrete -> Logic postconditions s c r = bigJug (transitions s c r) ./= 4 ------------------------------------------------------------------------ -- The generator of actions is simple, with equal distribution pick an -- action. generator :: Model Symbolic -> Maybe (Gen (Command Symbolic)) generator _ = Just $ oneof [ return FillBig , return FillSmall , return EmptyBig , return EmptySmall , return SmallIntoBig , return BigIntoSmall ] -- There's nothing to shrink. shrinker :: Model r -> Command r -> [Command r] shrinker _ _ = [] ------------------------------------------------------------------------ -- We are not modelling an actual program here, so there's no semantics -- for our actions. We are merely doing model checking. semantics :: Command Concrete -> IO (Response Concrete) semantics _ = return Done mock :: Model Symbolic -> Command Symbolic -> GenSym (Response Symbolic) mock _ _ = return Done ------------------------------------------------------------------------ -- Finally we have all the pieces needed to get the sequential property! -- To make the code fit on a line, we first group all things related to -- generation and execution of programs respectively. sm :: StateMachine Model Command IO Response sm = StateMachine initModel transitions preconditions postconditions Nothing generator shrinker semantics mock noCleanup prop_dieHard :: Property prop_dieHard = forAllCommands sm Nothing $ \cmds -> monadicIO $ do (hist, _model, res) <- runCommands sm cmds prettyCommands sm hist (checkCommandNames cmds (res === Ok)) -- If we run @quickCheck prop_dieHard@ we get: -- -- @ -- *** Failed! Falsifiable (after 43 tests and 4 shrinks): -- Commands -- { unCommands = -- [ Command FillBig (fromList []) -- , Command BigIntoSmall (fromList []) -- , Command EmptySmall (fromList []) -- , Command BigIntoSmall (fromList []) -- , Command FillBig (fromList []) -- , Command BigIntoSmall (fromList []) -- ] -- } -- -- Model {bigJug = 0,smallJug = 0} -- -- == FillBig ==> Done [ 0 ] -- -- Model {bigJug = -0 +5 -- ,smallJug = 0} -- -- == BigIntoSmall ==> Done [ 0 ] -- -- Model {bigJug = -5 +2 -- ,smallJug = -0 +3} -- -- == EmptySmall ==> Done [ 0 ] -- -- Model {bigJug = 2 -- ,smallJug = -3 +0} -- -- == BigIntoSmall ==> Done [ 0 ] -- -- Model {bigJug = -2 +0 -- ,smallJug = -0 +2} -- -- == FillBig ==> Done [ 0 ] -- -- Model {bigJug = -0 +5 -- ,smallJug = 2} -- -- == BigIntoSmall ==> Done [ 0 ] -- -- Model {bigJug = -5 +4 -- ,smallJug = -2 +3} -- -- PostconditionFailed "PredicateC (4 :== 4)" /= Ok -- @ -- -- The counterexample is our solution.
advancedtelematic/quickcheck-state-machine-model
test/DieHard.hs
Haskell
bsd-3-clause
6,644
{-# LANGUAGE NamedFieldPuns, RecordWildCards #-} -- | The tar index cache provides generic support for caching a tarball's -- TarIndex; this is used by various other modules. module Distribution.Server.Features.TarIndexCache ( TarIndexCacheFeature(..) , initTarIndexCacheFeature ) where import Control.Exception (throwIO) import Data.Serialize (runGetLazy, runPutLazy) import Data.SafeCopy (safeGet, safePut) import Distribution.Server.Framework import Distribution.Server.Framework.BlobStorage import Distribution.Server.Framework.BackupRestore import Distribution.Server.Features.TarIndexCache.State import Distribution.Server.Features.Users import Distribution.Server.Packages.Types (PkgTarball(..)) import Data.TarIndex import Distribution.Server.Util.ServeTarball (constructTarIndex) import qualified Data.Map as Map import Data.Aeson (toJSON) data TarIndexCacheFeature = TarIndexCacheFeature { tarIndexCacheFeatureInterface :: HackageFeature , cachedTarIndex :: BlobId -> IO TarIndex , cachedPackageTarIndex :: PkgTarball -> IO TarIndex } instance IsHackageFeature TarIndexCacheFeature where getFeatureInterface = tarIndexCacheFeatureInterface initTarIndexCacheFeature :: ServerEnv -> IO (UserFeature -> IO TarIndexCacheFeature) initTarIndexCacheFeature env@ServerEnv{serverStateDir} = do tarIndexCache <- tarIndexCacheStateComponent serverStateDir return $ \users -> do let feature = tarIndexCacheFeature env users tarIndexCache return feature tarIndexCacheStateComponent :: FilePath -> IO (StateComponent AcidState TarIndexCache) tarIndexCacheStateComponent stateDir = do st <- openLocalStateFrom (stateDir </> "db" </> "TarIndexCache") initialTarIndexCache return StateComponent { stateDesc = "Mapping from tarball blob IDs to tarindex blob IDs" , stateHandle = st , getState = query st GetTarIndexCache , putState = update st . ReplaceTarIndexCache , resetState = tarIndexCacheStateComponent -- We don't backup the tar indices, but reconstruct them on demand , backupState = \_ _ -> [] , restoreState = RestoreBackup { restoreEntry = error "The impossible happened" , restoreFinalize = return initialTarIndexCache } } tarIndexCacheFeature :: ServerEnv -> UserFeature -> StateComponent AcidState TarIndexCache -> TarIndexCacheFeature tarIndexCacheFeature ServerEnv{serverBlobStore = store} UserFeature{..} tarIndexCache = TarIndexCacheFeature{..} where tarIndexCacheFeatureInterface :: HackageFeature tarIndexCacheFeatureInterface = (emptyHackageFeature "tarIndexCache") { featureDesc = "Generic cache for tarball indices" -- We don't want to compare blob IDs -- (TODO: We could potentially check that if a package occurs in both -- packages then both caches point to identical tar indices, but for -- that we would need to be in IO) , featureState = [abstractAcidStateComponent' (\_ _ -> []) tarIndexCache] , featureResources = [ (resourceAt "/server-status/tarindices.:format") { resourceDesc = [ (GET, "Which tar indices have been generated?") , (DELETE, "Delete all tar indices (will be regenerated on the fly)") ] , resourceGet = [ ("json", \_ -> serveTarIndicesStatus) ] , resourceDelete = [ ("", \_ -> deleteTarIndices) ] } ] } -- This is the heart of this feature cachedTarIndex :: BlobId -> IO TarIndex cachedTarIndex tarBallBlobId = do mTarIndexBlobId <- queryState tarIndexCache (FindTarIndex tarBallBlobId) case mTarIndexBlobId of Just tarIndexBlobId -> do serializedTarIndex <- fetch store tarIndexBlobId case runGetLazy safeGet serializedTarIndex of Left err -> throwIO (userError err) Right tarIndex -> return tarIndex Nothing -> do tarBall <- fetch store tarBallBlobId tarIndex <- case constructTarIndex tarBall of Left err -> throwIO (userError err) Right tarIndex -> return tarIndex tarIndexBlobId <- add store (runPutLazy (safePut tarIndex)) updateState tarIndexCache (SetTarIndex tarBallBlobId tarIndexBlobId) return tarIndex cachedPackageTarIndex :: PkgTarball -> IO TarIndex cachedPackageTarIndex = cachedTarIndex . pkgTarballNoGz serveTarIndicesStatus :: ServerPartE Response serveTarIndicesStatus = do TarIndexCache state <- liftIO $ getState tarIndexCache return . toResponse . toJSON . Map.toList $ state -- | With curl: -- -- > curl -X DELETE http://admin:admin@localhost:8080/server-status/tarindices deleteTarIndices :: ServerPartE Response deleteTarIndices = do guardAuthorised_ [InGroup adminGroup] -- TODO: This resets the tar indices _state_ only, we don't actually -- remove any blobs liftIO $ putState tarIndexCache initialTarIndexCache ok $ toResponse "Ok!"
haskell-infra/hackage-server
Distribution/Server/Features/TarIndexCache.hs
Haskell
bsd-3-clause
5,380
module HpcLexer where import Data.Char data Token = ID String | SYM Char | INT Int | STR String | CAT String deriving (Eq,Show) initLexer :: String -> [Token] initLexer str = [ t | (_,_,t) <- lexer str 1 1 ] lexer :: String -> Int -> Int -> [(Int,Int,Token)] lexer (c:cs) line column | c == '\n' = lexer cs (succ line) 1 | c == '\"' = lexerSTR cs line (succ column) | c == '[' = lexerCAT cs "" line (succ column) | c `elem` "{};-:" = (line,column,SYM c) : lexer cs line (succ column) | isSpace c = lexer cs line (succ column) | isAlpha c = lexerKW cs [c] line (succ column) | isDigit c = lexerINT cs [c] line (succ column) | otherwise = error "lexer failure" lexer [] _ _ = [] lexerKW :: String -> String -> Int -> Int -> [(Int,Int,Token)] lexerKW (c:cs) s line column | isAlpha c = lexerKW cs (s ++ [c]) line (succ column) lexerKW other s line column = (line,column,ID s) : lexer other line column lexerINT :: String -> String -> Int -> Int -> [(Int,Int,Token)] lexerINT (c:cs) s line column | isDigit c = lexerINT cs (s ++ [c]) line (succ column) lexerINT other s line column = (line,column,INT (read s)) : lexer other line column -- not technically correct for the new column count, but a good approximation. lexerSTR :: String -> Int -> Int -> [(Int,Int,Token)] lexerSTR cs line column = case lex ('"' : cs) of [(str,rest)] -> (line,succ column,STR (read str)) : lexer rest line (length (show str) + column + 1) _ -> error "bad string" lexerCAT :: String -> String -> Int -> Int -> [(Int,Int,Token)] lexerCAT (c:cs) s line column | c == ']' = (line,column,CAT s) : lexer cs line (succ column) | otherwise = lexerCAT cs (s ++ [c]) line (succ column) lexerCAT [] _ _ _ = error "lexer failure in CAT" test :: IO () test = do t <- readFile "EXAMPLE.tc" print (initLexer t)
nomeata/ghc
utils/hpc/HpcLexer.hs
Haskell
bsd-3-clause
1,929
module Canonicalize.Port (check) where import qualified Data.Foldable as Foldable import qualified AST.Declaration as D import qualified AST.Expression.General as E import qualified AST.Expression.Canonical as Canonical import qualified AST.Type as T import qualified AST.Variable as Var import qualified Reporting.Annotation as A import qualified Reporting.Error.Canonicalize as Error import qualified Reporting.Region as R import qualified Canonicalize.Result as Result -- CHECK FOR PORT check :: R.Region -> String -> Maybe Canonical.Expr -> T.Canonical -> Result.ResultErr D.CanonicalPort check region name maybeExpr rootType = D.CanonicalPort <$> checkHelp region name maybeExpr rootType rootType checkHelp :: R.Region -> String -> Maybe Canonical.Expr -> T.Canonical -> T.Canonical -> Result.ResultErr (E.PortImpl Canonical.Expr T.Canonical) checkHelp region name maybeExpr rootType tipe = case (maybeExpr, tipe) of (_, T.Aliased _ args t) -> checkHelp region name maybeExpr rootType (T.dealias args t) (Just expr, T.App (T.Type task) [ _x, _a ]) | Var.isTask task -> Result.ok (E.Task name expr (T.Normal tipe)) (Just expr, T.App (T.Type signal) [ arg@(T.App (T.Type task) [ _x, _a ]) ]) | Var.isSignal signal && Var.isTask task -> Result.ok (E.Task name expr (T.Signal tipe arg)) (_, T.App (T.Type signal) [arg]) | Var.isSignal signal -> case maybeExpr of Nothing -> const (E.In name (T.Signal rootType arg)) <$> validForeignType region name True arg arg Just expr -> const (E.Out name expr (T.Signal rootType arg)) <$> validForeignType region name False arg arg _ -> case maybeExpr of Nothing -> const (E.In name (T.Normal rootType)) <$> validForeignType region name True rootType tipe Just expr -> const (E.Out name expr (T.Normal rootType)) <$> validForeignType region name False rootType tipe -- CHECK INBOUND AND OUTBOUND TYPES validForeignType :: R.Region -> String -> Bool -> T.Canonical -> T.Canonical -> Result.ResultErr () validForeignType region name isInbound rootType tipe = let valid localType = validForeignType region name isInbound rootType localType err problem = Result.err $ A.A region $ Error.port name isInbound rootType tipe problem in case tipe of T.Aliased _ args t -> valid (T.dealias args t) T.Type v -> case any ($ v) [ Var.isJson, Var.isPrimitive, Var.isTuple ] of True -> Result.ok () False -> err Nothing T.App t [] -> valid t T.App (T.Type v) [t] | Var.isMaybe v -> valid t | Var.isArray v -> valid t | Var.isList v -> valid t T.App (T.Type v) ts | Var.isTuple v -> Foldable.traverse_ valid ts T.App _ _ -> err Nothing T.Var _ -> err (Just "a free type variable") T.Lambda _ _ -> err (Just "a function") T.Record _ (Just _) -> err (Just "an extended record") T.Record fields Nothing -> Foldable.traverse_ (\(k,v) -> (,) k <$> valid v) fields
laszlopandy/elm-compiler
src/Canonicalize/Port.hs
Haskell
bsd-3-clause
3,449
{-# LANGUAGE CPP #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} module Language.Haskell.Refact.Refactoring.MoveDef ( liftToTopLevel , compLiftToTopLevel , liftOneLevel , compLiftOneLevel , demote , compDemote -- ,liftingInClientMod ) where import qualified Data.Generics as SYB import qualified GHC.SYB.Utils as SYB import qualified Data.Generics.Zipper as Z import qualified Exception as GHC import qualified GHC as GHC import qualified Name as GHC import qualified RdrName as GHC import Control.Exception import Control.Monad.State import Data.Foldable import Data.List import Data.Maybe import qualified GhcMod as GM import Language.Haskell.Refact.API import Language.Haskell.GHC.ExactPrint.Types import Language.Haskell.GHC.ExactPrint import Data.Generics.Strafunski.StrategyLib.StrategyLib import System.Directory -- import Debug.Trace -- --------------------------------------------------------------------- -- data Direction = UptoTopLevel | UpOneLevel | Down {--------This function handles refactorings involving moving a definition-------- According to the Haskell's syntax, a declaration may occur in one of the following six contexts: 1. A top level declaration in the module: old: HsModule SrcLoc ModuleName (Maybe [HsExportSpecI i]) [HsImportDeclI i] ds new: (HsGroup Name, [LImportDecl Name], Maybe [LIE Name], Maybe LHsDocString) HsGroup hs_valds :: HsValBinds id ... 2. A local declaration in a Match: (of a FunBind) old: HsMatch SrcLoc i [p] (HsRhs e) ds new: Match [LPat id] (Maybe (LHsType id)) (GRHSs id) 3. A local declaration in a pattern binding: old: HsPatBind SrcLoc p (HsRhs e) ds new: PatBind (LPat idL) (GRHSs idR) PostTcType NameSet (Maybe tickish) 4. A local declaration in a Let expression: old: HsLet ds e new: HsLet (HsLocalBinds id) (LHsExpr id) 5. A local declaration in a Case alternative: old: HsAlt SrcLoc p (HsRhs e) ds new: HsCase (LHsExpr id) (MatchGroup id) new is same as in a FunBind. 6. A local declaration in a Do statement: old: HsLetStmt ds (HsStmt e p ds) new: LetStmt (HsLocalBindsLR idL idR) in context GRHS [LStmt id] (LHsExpr id) -} -- | Lift a definition to the top level liftToTopLevel :: RefactSettings -> GM.Options -> FilePath -> SimpPos -> IO [FilePath] liftToTopLevel settings opts fileName (row,col) = do absFileName <- canonicalizePath fileName runRefacSession settings opts (compLiftToTopLevel absFileName (row,col)) compLiftToTopLevel :: FilePath -> SimpPos -> RefactGhc [ApplyRefacResult] compLiftToTopLevel fileName (row,col) = do parseSourceFileGhc fileName logParsedSource "liftToMod orig:" parsed <- getRefactParsed nm <- getRefactNameMap let (Just (modName,_)) = getModuleName parsed let maybePn = locToRdrName (row, col) parsed case maybePn of Just ln@(GHC.L l _) -> liftToTopLevel' modName (GHC.L l (rdrName2NamePure nm ln)) _ -> error "\nInvalid cursor position!\n" {- Refactoring Names: 'liftToTopLevel' This refactoring lifts a local function/pattern binding to the top level of the module, so as to make it accessible to other functions in the current module, and those modules that import current module. In the current implementation, a definition will be lifted only if none of the identifiers defined in this definition will cause name clash/capture problems in the current module after lifting. In the case that the whole current module is exported implicitly, the lifted identifier will be exported automatically after lifting. If the identifier will cause name clash/ambiguous occurrence problem in a client module, it will be hided in the import declaration of the client module (Note: this might not be the best solution, we prefer hiding it in the server module instead of in the client module in the final version). In the case of indirect importing, it might be time-consuming to trace whether the lifted identifier will cause any problem in a client module that indirectly imports the current module. The current solution is: suppose a defintion is lifted to top level in module A, and module A is imported and exported by module B, then the lifted identifier will be hided in the import declaration of B no matter whether it causes problems in module B or not. Function name: liftToTopLevel parameters: fileName--current file name. mod -- the scoped abstract syntax tree of the module. pn -- the function/pattern name to be lifted. -} liftToTopLevel' :: GHC.ModuleName -> GHC.Located GHC.Name -> RefactGhc [ApplyRefacResult] liftToTopLevel' modName pn@(GHC.L _ n) = do renamed <- getRefactRenamed parsed <- getRefactParsed nm <- getRefactNameMap targetModule <- getRefactTargetModule logm $ "liftToTopLevel':pn=" ++ (showGhc pn) if isLocalFunOrPatName nm n parsed then do (refactoredMod,declPns) <- applyRefac liftToMod RSAlreadyLoaded logm $ "liftToTopLevel' applyRefac done " if modIsExported modName renamed then do clients <- clientModsAndFiles targetModule logm $ "liftToTopLevel':(clients,declPns)=" ++ (showGhc (clients,declPns)) refactoredClients <- mapM (liftingInClientMod modName declPns) clients return (refactoredMod:(concat refactoredClients)) else do return [refactoredMod] else error "\nThe identifier is not a local function/pattern name!" where {-step1: divide the module's top level declaration list into three parts: 'parent' is the top level declaration containing the lifted declaration, 'before' and `after` are those declarations before and after 'parent'. step2: get the declarations to be lifted from parent, bind it to liftedDecls step3: remove the lifted declarations from parent and extra arguments may be introduced. step4. test whether there are any names need to be renamed. -} liftToMod = do parsed' <- getRefactParsed parsed <- liftT $ balanceAllComments parsed' nm <- getRefactNameMap -- logDataWithAnns "parsed after balanceAllComments" parsed declsp <- liftT $ hsDecls parsed (before,parent,after) <- divideDecls declsp pn {- ++AZ++TODO: reinstate this, hsDecls does : hsBinds does not return class or instance definitions when (isClassDecl $ ghead "liftToMod" parent) $ error "Sorry, the refactorer cannot lift a definition from a class declaration!" when (isInstDecl $ ghead "liftToMod" parent) $ error "Sorry, the refactorer cannot lift a definition from an instance declaration!" -} -- declsParent <- liftT $ hsDecls (ghead "liftToMod" parent) -- logm $ "liftToMod:(declsParent)=" ++ (showGhc declsParent) let liftedDecls = definingDeclsRdrNames nm [n] parent True True declaredPns = nub $ concatMap (definedNamesRdr nm) liftedDecls liftedSigs = definingSigsRdrNames nm declaredPns parent mLiftedSigs = liftedSigs -- logDataWithAnns "liftedDecls" liftedDecls -- Check that the lifted declaration does not include a tuple pattern on the lhs when (any isTupleDecl liftedDecls) $ do error "Cannot lift a declaration assigning to a tuple pattern" -- TODO: what about declarations between this -- one and the top level that are used in this one? pns <- pnsNeedRenaming parsed parent liftedDecls declaredPns logm $ "liftToMod:(pns needing renaming)=" ++ (showGhc pns) decls <- liftT $ hsDecls parsed' let dd = getDeclaredVarsRdr nm decls logm $ "liftToMod:(ddd)=" ++ (showGhc dd) if null pns then do (parent',liftedDecls',mLiftedSigs') <- addParamsToParentAndLiftedDecl n dd parent liftedDecls mLiftedSigs let defName = ghead "liftToMod" (definedNamesRdr nm (ghead "liftToMod2" parent')) parsed1 <- liftT $ replaceDecls parsed (before++parent'++after) parsed2 <- moveDecl1 parsed1 (Just defName) [GHC.unLoc pn] liftedDecls' declaredPns mLiftedSigs' putRefactParsed parsed2 emptyAnns logParsedSource "liftToMod done:" return declaredPns else askRenamingMsg pns "lifting" isTupleDecl :: GHC.LHsDecl GHC.RdrName -> Bool isTupleDecl (GHC.L _ (GHC.ValD (GHC.PatBind (GHC.L _ GHC.TuplePat {}) _ _ _ _))) = True isTupleDecl (GHC.L _ (GHC.ValD (GHC.PatBind (GHC.L _ (GHC.AsPat _ (GHC.L _ GHC.TuplePat {}))) _ _ _ _))) = True isTupleDecl _ = False -- --------------------------------------------------------------------- -- | Move a definition one level up from where it is now liftOneLevel :: RefactSettings -> GM.Options -> FilePath -> SimpPos -> IO [FilePath] liftOneLevel settings opts fileName (row,col) = do absFileName <- canonicalizePath fileName runRefacSession settings opts (compLiftOneLevel absFileName (row,col)) compLiftOneLevel :: FilePath -> SimpPos -> RefactGhc [ApplyRefacResult] compLiftOneLevel fileName (row,col) = do parseSourceFileGhc fileName parsed <- getRefactParsed nm <- getRefactNameMap let (Just (modName,_)) = getModuleName parsed let maybePn = locToRdrName (row, col) parsed case maybePn of Just ln@(GHC.L l _) -> do rs <- liftOneLevel' modName (GHC.L l (rdrName2NamePure nm ln)) logm $ "compLiftOneLevel:rs=" ++ (show $ (refactDone rs,map (\((_,d),_) -> d) rs)) if (refactDone rs) then return rs else error ( "Lifting this definition failed. "++ " This might be because that the definition to be "++ "lifted is defined in a class/instance declaration.") _ -> error "\nInvalid cursor position!\n" {- Refactoring Names: 'liftOneLevel' Description: this refactoring lifts a local function/pattern binding only one level up. By 'lifting one-level up' , I mean: case1: In a module (HsModule SrcLoc ModuleName (Maybe [HsExportSpecI i]) [HsImportDeclI i] ds): A local declaration D will be lifted to the same level as the 'ds', if D is in the where clause of one of ds's element declaration. new: (HsModule mmn mexp imps ds mdepr _haddock) In pactice this means processing a. Matches in a FunBind (Match mln pats _typ (GRHSs grhs ds)) b. A PatBind (PatBind lhs (GRHSs grhs ds) _typ _fvs _ticks) and lifting a decl D from ds to the top. VarBinds and AbsBinds are introduced by the type checker, so can be ignored here. A PatSynBind does not have decls in it, so is ignored. case2: In a match ( HsMatch SrcLoc i [p] (HsRhs e) ds) : A local declaration D will be lifted to the same level as the 'ds', if D is in the where clause of one of ds's element declaration. A declaration D,say,in the rhs expression 'e' will be lifted to 'ds' if D is Not local to other declaration list in 'e' (in a FunBind) new: (Match mln pats _typ (GRHSs grhs lb)) case3: In a pattern binding (HsPatBind SrcLoc p (HsRhs e) ds): A local declaration D will be lifted to the same level as the 'ds', if D is in the where clause of one of ds's element declaration. A declaration D,say,in the rhs expression 'e' will be lifted to 'ds' if D is Not local to other declaration list in 'e' new: (PatBind lhs (GRHSs grhs ds) _typ _fvs _ticks) case4: In the Let expression (Exp (HsLet ds e): A local declaration D will be lifted to the same level as the 'ds', if D is in the where clause of one of ds's element declaration. A declaration D, say, in the expression 'e' will be lifted to 'ds' if D is not local to other declaration list in 'e' new: HsLet ds e case5: In the case Alternative expression:(HsAlt loc p rhs ds) A local declaration D will be lifted to the same level as the 'ds', if D is in the where clause of one of ds's element declaration. A declaration D in 'rhs' will be lifted to 'ds' if D is not local to other declaration list in 'rhs'. new: HsCase (LHsExpr id) (MatchGroup id) new is same as in a FunBind. case6: In the do statement expression:(HsLetStmt ds stmts) A local declaration D will be lifted to the same level as the 'ds', if D is in the where clause of one of ds's element declaration. A declaration D in 'stmts' will be lifted to 'ds' if D is not local to other declaration list in 'stmts'. new: LetStmt (HsLocalBindsLR idL idR) in context GRHS [LStmt id] (LHsExpr id) Function name: liftOneLevel parameters: fileName--current file name. mod -- the scoped abstract syntax tree of the module. pn -- the function/pattern name to be lifted. -} liftOneLevel' :: GHC.ModuleName -> GHC.Located GHC.Name -> RefactGhc [ApplyRefacResult] liftOneLevel' modName pn@(GHC.L _ n) = do renamed <- getRefactRenamed parsed <- getRefactParsed nm <- getRefactNameMap targetModule <- getRefactTargetModule if isLocalFunOrPatName nm n parsed then do (refactoredMod,(b,pns)) <- applyRefac doLiftOneLevel RSAlreadyLoaded logm $ "liftOneLevel':main refactoring done:(p,pns)=" ++ showGhc (b,pns) if b && modIsExported modName renamed then do logm $ "liftOneLevel':looking for clients" clients <- clientModsAndFiles targetModule logm $ "liftOneLevel':(clients,pns)=" ++ (showGhc (clients,pns)) refactoredClients <- mapM (liftingInClientMod modName pns) clients return (refactoredMod:concat refactoredClients) else do return [refactoredMod] else error "\nThe identifer is not a function/pattern name!" where doLiftOneLevel = do logm $ "in doLiftOneLevel" parsed <- getRefactParsed logDataWithAnns "doLiftOneLevel:parsed" parsed nm <- getRefactNameMap ans <- liftT getAnnsT zp <- ztransformStagedM SYB.Parser (Nothing `SYB.mkQ` (liftToModQ nm ans) `SYB.extQ` (liftToMatchQ nm ans) `SYB.extQ` (liftToLetQ nm ans) ) (Z.toZipper parsed) let parsed' = Z.fromZipper zp putRefactParsed parsed' emptyAnns liftedToTopLevel pn parsed' where isMatch :: GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> Bool isMatch _ = True isHsLet :: GHC.LHsExpr GHC.RdrName -> Bool isHsLet (GHC.L _ (GHC.HsLet _ _)) = True isHsLet _ = False -- ------------------------ liftToModQ :: NameMap -> Anns -> GHC.ParsedSource -> Maybe (SYB.Stage -> Z.Zipper GHC.ParsedSource -> RefactGhc (Z.Zipper GHC.ParsedSource)) liftToModQ nm ans (p :: GHC.ParsedSource) | nonEmptyList candidateBinds = Just (doLiftZ p declsp) | otherwise = Nothing where (declsp ,_,_) = runTransform ans (hsDecls p) doOne bs = (definingDeclsRdrNames nm [n] declsbs False False,bs) where (declsbs,_,_) = runTransform ans (hsDeclsGeneric bs) candidateBinds = map snd $ filter (\(l,_bs) -> nonEmptyList l) $ map doOne $ declsp getHsDecls ans t = decls where (decls,_,_) = runTransform ans (hsDeclsGeneric t) -- ------------------------ liftToMatchQ :: (SYB.Data a) => NameMap -> Anns -> GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> Maybe (SYB.Stage -> Z.Zipper a -> RefactGhc (Z.Zipper a)) liftToMatchQ nm ans (m@(GHC.L _ (GHC.Match _ _pats _mtyp (GHC.GRHSs _rhs ds)))::GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) | (nonEmptyList (definingDeclsRdrNames nm [n] (getHsDecls ans ds) False False)) = Just (doLiftZ m (getHsDecls ans ds)) | otherwise = Nothing -- ------------------------ liftToLetQ :: SYB.Data a => NameMap -> Anns -> GHC.LHsExpr GHC.RdrName -> Maybe (SYB.Stage -> Z.Zipper a -> RefactGhc (Z.Zipper a)) liftToLetQ nm ans ll@(GHC.L _ (GHC.HsLet ds _e)) | nonEmptyList (definingDeclsRdrNames nm [n] (getHsDecls ans ds) False False) = Just (doLiftZ ll (getHsDecls ans ll)) | otherwise = Nothing liftToLetQ _ _ _ = Nothing -- ------------------------ doLiftZ :: (SYB.Data t,SYB.Data a) => t -- ^Item containing the decls which contain the ones to be lifted -> [GHC.LHsDecl GHC.RdrName] -- ^decls containing the ones to be lifted. -- ++AZ++:TODO: these are redundant, can be pulled out of t -> SYB.Stage -- ++AZ++:TODO: get rid of this -> Z.Zipper a -> RefactGhc (Z.Zipper a) doLiftZ ds decls _stage z = do logm $ "doLiftZ entered" logDataWithAnns "doLiftZ:ds" ds logDataWithAnns "doLiftZ:decls" decls let zu = case (Z.up z) of Just zz -> fromMaybe (error $ "MoveDef.liftToLet.1" ++ SYB.showData SYB.Parser 0 decls) $ upUntil (False `SYB.mkQ` isMatch `SYB.extQ` isHsLet ) zz Nothing -> z let wtop (ren::GHC.ParsedSource) = do logm $ "wtop entered" nm <- getRefactNameMap let (_,DN dd) = (hsFreeAndDeclaredRdr nm ren) -- ++AZ++ : TODO: get rid of worker in favour of -- workerTop worker ren decls pn dd -- workerTop ren decls dd wmatch :: GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> RefactGhc (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) wmatch (m@(GHC.L _ (GHC.Match _mln _pats _typ grhss))) = do logm $ "wmatch entered:" ++ SYB.showData SYB.Parser 0 m nm <- getRefactNameMap let (_,DN dd) = hsFreeAndDeclaredRdr nm grhss decls' <- liftT $ hsDecls m workerTop m decls' dd wlet :: GHC.LHsExpr GHC.RdrName -> RefactGhc (GHC.LHsExpr GHC.RdrName) wlet l@(GHC.L _ (GHC.HsLet dsl _e)) = do logm $ "wlet entered " nm <- getRefactNameMap let (_,DN dd) = hsFreeAndDeclaredRdr nm dsl dsl' <- workerTop l decls dd return dsl' wlet x = return x ds' <- Z.transM ( SYB.mkM wtop `SYB.extM` wmatch `SYB.extM` wlet ) zu return ds' -- ---------------------------------------- -- This is currently used for everything but the top level workerTop :: (HasDecls t) => t -- ^The destination of the lift operation -> [GHC.LHsDecl GHC.RdrName] -- ^ list containing the decl to be -- lifted -> [GHC.Name] -- ^Declared variables in the destination -> RefactGhc t workerTop dest ds dd =do logm $ "MoveDef.worker: dest" ++ SYB.showData SYB.Parser 0 dest logm $ "MoveDef.workerTop: ds=" ++ (showGhc ds) done <- getRefactDone if done then return dest else do setRefactDone let parent = dest nm <- getRefactNameMap let liftedDecls = definingDeclsRdrNames' nm [n] parent declaredPns = nub $ concatMap (definedNamesRdr nm) liftedDecls logm $ "MoveDef.workerTop: n=" ++ (showGhc n) logm $ "MoveDef.workerTop: liftedDecls=" ++ (showGhc liftedDecls) pns <- pnsNeedRenaming dest parent liftedDecls declaredPns logm $ "MoveDef.workerTop: pns=" ++ (showGhc pns) if pns==[] then do (parent',liftedDecls',mLiftedSigs')<-addParamsToParentAndLiftedDecl n dd parent liftedDecls [] logm $ "MoveDef.workerTop: liftedDecls'=" ++ (showGhc liftedDecls') --True means the new decl will be at the same level with its parant. let toMove = parent' pdecls <- liftT $ hsDecls toMove -- logm $ "MoveDef.workerTop:toMove=" ++ SYB.showData SYB.Parser 0 toMove -- logm $ "MoveDef.workerTop:pdecls=" ++ (showGhc pdecls) let mAfter = case pdecls of [] -> Nothing _ -> (Just (ghead "worker" (definedNamesRdr nm (glast "workerTop" ds)))) dest' <- moveDecl1 toMove mAfter [n] liftedDecls' declaredPns mLiftedSigs' return dest' else askRenamingMsg pns "lifting" -- ---------------------------------------- -- TODO: get rid of this in favour of workerTop worker :: (HasDecls t) => t -- ^The destination of the lift operation -> [GHC.LHsDecl GHC.RdrName] -- ^ list containing the decl to be -- lifted -> GHC.Located GHC.Name -- ^ The name of the decl to be lifted -> [GHC.Name] -- ^Declared variables in the destination -> RefactGhc t worker dest ds pnn dd =do -- logm $ "MoveDef.worker: dest" ++ (showGhc dest) logm $ "MoveDef.worker: ds=" ++ (showGhc ds) done <- getRefactDone if done then return dest else do setRefactDone (before,parent,after) <- divideDecls ds pnn -- parent is misnomer, it is the decl to be moved logm $ "MoveDef.worker:(before,parent,after)" ++ showGhc (before,parent,after) nm <- getRefactNameMap let liftedDecls = definingDeclsRdrNames nm [n] parent True True declaredPns = nub $ concatMap (definedNamesRdr nm) liftedDecls pns <- pnsNeedRenaming dest parent liftedDecls declaredPns logm $ "MoveDef.worker: pns=" ++ (showGhc pns) if pns==[] then do (parent',liftedDecls',mLiftedSigs')<-addParamsToParentAndLiftedDecl n dd parent liftedDecls [] --True means the new decl will be at the same level with its parant. toMove <- liftT $ replaceDecls dest (before++parent'++after) dest' <- moveDecl1 toMove (Just (ghead "worker" (definedNamesRdr nm (ghead "worker" parent')))) [n] liftedDecls' declaredPns mLiftedSigs' return dest' else askRenamingMsg pns "lifting" -- --------------------------------------------------------------------- -- | Move a definition one level down demote :: RefactSettings -> GM.Options -> FilePath -> SimpPos -> IO [FilePath] demote settings opts fileName (row,col) = do absFileName <- canonicalizePath fileName runRefacSession settings opts (compDemote absFileName (row,col)) compDemote ::FilePath -> SimpPos -> RefactGhc [ApplyRefacResult] compDemote fileName (row,col) = do parseSourceFileGhc fileName parsed <- getRefactParsed nm <- getRefactNameMap -- TODO: make the next one an API call, that also gets the -- parsed source let (Just (modName,_)) = getModuleName parsed let maybePn = locToRdrName (row, col) parsed case maybePn of Just pn@(GHC.L l _) -> demote' modName (GHC.L l (rdrName2NamePure nm pn)) _ -> error "\nInvalid cursor position!\n" -- --------------------------------------------------------------------- moveDecl1 :: (SYB.Data t) => t -- ^ The syntax element to update -> Maybe GHC.Name -- ^ If specified, add defn after this one -> [GHC.Name] -- ^ The first one is the decl to move -> [GHC.LHsDecl GHC.RdrName] -> [GHC.Name] -- ^ The signatures to remove. May be multiple if -- decl being moved has a patbind. -> [GHC.LSig GHC.RdrName] -- ^ lifted decls signature if present -> RefactGhc t -- ^ The updated syntax element (and tokens in monad) moveDecl1 t defName ns mliftedDecls sigNames mliftedSigs = do logm $ "moveDecl1:(defName,ns,sigNames,mliftedDecls)=" ++ showGhc (defName,ns,sigNames,mliftedDecls) -- logm $ "moveDecl1:(t)=" ++ SYB.showData SYB.Parser 0 (t) -- TODO: rmDecl can now remove the sig at the same time. (t'',_sigsRemoved) <- rmTypeSigs sigNames t -- logm $ "moveDecl1:after rmTypeSigs:t''" ++ SYB.showData SYB.Parser 0 t'' logm $ "moveDecl1:mliftedSigs=" ++ showGhc mliftedSigs (t',_declRemoved,_sigRemoved) <- rmDecl (ghead "moveDecl3.1" ns) False t'' -- logm $ "moveDecl1:after rmDecl:t'" ++ SYB.showData SYB.Parser 0 t' let sigs = map wrapSig mliftedSigs r <- addDecl t' defName (sigs++mliftedDecls,Nothing) return r -- --------------------------------------------------------------------- askRenamingMsg :: [GHC.Name] -> String -> t askRenamingMsg pns str = error ("The identifier(s): " ++ (intercalate "," $ map showPN pns) ++ " will cause name clash/capture or ambiguity occurrence problem after " ++ str ++", please do renaming first!") where showPN pn = showGhc (pn,GHC.nameSrcLoc pn) -- |Get the subset of 'pns' that need to be renamed before lifting. pnsNeedRenaming :: (SYB.Data t1,SYB.Data t2) => t1 -> t2 -> t3 -> [GHC.Name] -> RefactGhc [GHC.Name] pnsNeedRenaming dest parent _liftedDecls pns = do logm $ "MoveDef.pnsNeedRenaming entered:pns=" ++ showGhc pns r <- mapM pnsNeedRenaming' pns return (concat r) where pnsNeedRenaming' pn = do logm $ "MoveDef.pnsNeedRenaming' entered" nm <- getRefactNameMap let (FN f,DN d) = hsFDsFromInsideRdr nm dest --f: free variable names that may be shadowed by pn --d: declaread variables names that may clash with pn logm $ "MoveDef.pnsNeedRenaming':(f,d)=" ++ showGhc (f,d) DN vs <- hsVisibleDsRdr nm pn parent --vs: declarad variables that may shadow pn logm $ "MoveDef.pnsNeedRenaming':vs=" ++ showGhc vs let vars = map pNtoName (nub (f `union` d `union` vs) \\ [pn]) -- `union` inscpNames isInScope <- isInScopeAndUnqualifiedGhc (pNtoName pn) Nothing logm $ "MoveDef.pnsNeedRenaming:(f,d,vs,vars,isInScope)=" ++ (showGhc (f,d,vs,vars,isInScope)) -- if elem (pNtoName pn) vars || isInScope && findEntity pn dest if elem (pNtoName pn) vars || isInScope && findNameInRdr nm pn dest then return [pn] else return [] pNtoName = showGhc -- --------------------------------------------------------------------- addParamsToParent :: (SYB.Data t) => GHC.Name -> [GHC.RdrName] -> t -> RefactGhc t addParamsToParent _pn [] t = return t addParamsToParent pn params t = do logm $ "addParamsToParent:(pn,params)" ++ (showGhc (pn,params)) nm <- getRefactNameMap applyTP (full_buTP (idTP `adhocTP` (inExp nm))) t where #if __GLASGOW_HASKELL__ <= 710 inExp nm (e@(GHC.L l (GHC.HsVar n)) :: GHC.LHsExpr GHC.RdrName) = do #else inExp nm (e@(GHC.L l (GHC.HsVar (GHC.L _ n))) :: GHC.LHsExpr GHC.RdrName) = do #endif let ne = rdrName2NamePure nm (GHC.L l n) if GHC.nameUnique ne == GHC.nameUnique pn then addActualParamsToRhs pn params e else return e inExp _ e = return e -- addActualParamsToRhs pn params t -- |Do refactoring in the client module. that is to hide the identifer -- in the import declaration if it will cause any problem in the -- client module. liftingInClientMod :: GHC.ModuleName -> [GHC.Name] -> TargetModule -> RefactGhc [ApplyRefacResult] liftingInClientMod serverModName pns targetModule = do logm $ "liftingInClientMod:targetModule=" ++ (show targetModule) getTargetGhc targetModule parsed <- getRefactParsed clientModule <- getRefactModule logm $ "liftingInClientMod:clientModule=" ++ (showGhc clientModule) modNames <- willBeUnQualImportedBy serverModName logm $ "liftingInClientMod:modNames=" ++ (showGhc modNames) if isJust modNames then do pns' <- namesNeedToBeHided clientModule (gfromJust "liftingInClientMod" modNames) pns let pnsRdr' = map GHC.nameRdrName pns' logm $ "liftingInClientMod:pns'=" ++ (showGhc pns') if (nonEmptyList pns') then do (refactoredMod,_) <- applyRefac (addHiding serverModName parsed pnsRdr') RSAlreadyLoaded return [refactoredMod] else return [] else return [] -- --------------------------------------------------------------------- -- |Test whether an identifier defined in the modules specified by -- 'names' will be exported by current module. willBeExportedByClientMod :: [GHC.ModuleName] -> GHC.RenamedSource -> Bool willBeExportedByClientMod names renamed = let (_,_,exps,_) = renamed in if isNothing exps then False else any isJust $ map (\y-> (find (\x-> (simpModule x==Just y)) (gfromJust "willBeExportedByClientMod" exps))) names where simpModule (GHC.L _ (GHC.IEModuleContents (GHC.L _ m))) = Just m simpModule _ = Nothing -- |get the module name or alias name by which the lifted identifier -- will be imported automatically. -- TODO: maybe move this into TypeUtils -- willBeUnQualImportedBy::HsName.ModuleName->HsModuleP->Maybe [HsName.ModuleName] willBeUnQualImportedBy :: GHC.ModuleName -> RefactGhc (Maybe [GHC.ModuleName]) willBeUnQualImportedBy modName = do (_,imps,_,_) <- getRefactRenamed let ms = filter (\(GHC.L _ (GHC.ImportDecl _ (GHC.L _ modName1) _qualify _source _safe isQualified _isImplicit _as h)) -> modName == modName1 && (not isQualified) && (isNothing h || (isJust h && ((fst (fromJust h)) == True)))) imps res = if (emptyList ms) then Nothing else Just $ nub $ map getModName ms getModName (GHC.L _ (GHC.ImportDecl _ (GHC.L _ modName2) _qualify _source _safe _isQualified _isImplicit as _h)) = if isJust as then simpModName (fromJust as) else modName2 simpModName m = m logm $ "willBeUnQualImportedBy:(ms,res)=" ++ (showGhc (ms,res)) return res -- --------------------------------------------------------------------- -- |get the subset of 'pns', which need to be hided in the import -- declaration in module 'mod' -- Note: these are newly exported from the module, so we cannot use -- the GHC name resolution in this case. namesNeedToBeHided :: GHC.Module -> [GHC.ModuleName] -> [GHC.Name] -> RefactGhc [GHC.Name] namesNeedToBeHided clientModule modNames pns = do renamed <- getRefactRenamed parsed <- getRefactParsed logm $ "namesNeedToBeHided:willBeExportedByClientMod=" ++ (show $ willBeExportedByClientMod modNames renamed) gnames <- GHC.getNamesInScope let clientInscopes = filter (\n -> clientModule == GHC.nameModule n) gnames logm $ "namesNeedToBeHided:(clientInscopes)=" ++ (showGhc (clientInscopes)) pnsMapped <- mapM getLocalEquiv pns logm $ "namesNeedToBeHided:pnsMapped=" ++ (showGhc pnsMapped) let pnsMapped' = filter (\(_,_,ns) -> not $ emptyList ns) pnsMapped if willBeExportedByClientMod modNames renamed then return pns else do ff <- mapM (needToBeHided parsed) pnsMapped' return $ concat ff where -- | Strip the package prefix from the name and return the -- stripped name together with any names in the local module that -- may match the stripped one getLocalEquiv :: GHC.Name -> RefactGhc (GHC.Name,String,[GHC.Name]) getLocalEquiv pn = do let pnStr = stripPackage $ showGhc pn logm $ "MoveDef getLocalEquiv: about to parseName:" ++ (show pnStr) ecns <- GHC.gtry $ GHC.parseName pnStr let cns = case ecns of Left (_e::SomeException) -> [] Right v -> v logm $ "MoveDef getLocalEquiv: cns:" ++ (showGhc cns) return (pn,pnStr,cns) stripPackage :: String -> String stripPackage str = reverse s where (s,_) = break (== '.') $ reverse str needToBeHided :: GHC.ParsedSource -> (GHC.Name,String,[GHC.Name]) -> RefactGhc [GHC.Name] needToBeHided parsed (pn,_pnStr,pnsLocal) = do let uwoq = map (\n -> usedWithoutQualR n parsed) pnsLocal -- logm $ "needToBeHided:(hsBinds renamed)=" ++ (showGhc (hsBinds renamed)) logm $ "needToBeHided:(pn,uwoq)=" ++ (showGhc (pn,uwoq)) if (any (== True) uwoq --the same name is used in the module unqualifiedly or --is exported unqualifiedly by an Ent decl -- TODO: ++AZ++ check if next line needs to be reinstated -- was || any (\m -> causeNameClashInExports oldPN pn m renamed) modNames) || False) then return [pn] else return [] -- **************************************************************************************************************-- -- --------------------------------------------------------------------- -- |When liftOneLevel is complete, identify whether any new declarations have -- been put at the top level liftedToTopLevel :: GHC.Located GHC.Name -> GHC.ParsedSource -> RefactGhc (Bool,[GHC.Name]) liftedToTopLevel (GHC.L _ pn) parsed = do logm $ "liftedToTopLevel entered:pn=" ++ showGhc pn nm <- getRefactNameMap decls <- liftT $ hsDecls parsed let topDecs = definingDeclsRdrNames nm [pn] decls False False -- ++AZ++ :TODO: we are not updating the nameMap to reflect moved decls if nonEmptyList topDecs then do let liftedDecls = definingDeclsRdrNames nm [pn] topDecs False False declaredPns = nub $ concatMap (definedNamesRdr nm) liftedDecls return (True, declaredPns) else return (False, []) -- --------------------------------------------------------------------- addParamsToParentAndLiftedDecl :: (SYB.Data t) => GHC.Name -- ^name of decl being lifted -> [GHC.Name] -- ^Declared names in parent -> t -- ^parent -> [GHC.LHsDecl GHC.RdrName] -- ^ decls being lifted -> [GHC.LSig GHC.RdrName] -- ^ lifted decls signature if present -> RefactGhc (t, [GHC.LHsDecl GHC.RdrName], [GHC.LSig GHC.RdrName]) addParamsToParentAndLiftedDecl pn dd parent liftedDecls mLiftedSigs =do logm $ "addParamsToParentAndLiftedDecl:liftedDecls=" ++ (showGhc liftedDecls) nm <- getRefactNameMap let (FN ef,_) = hsFreeAndDeclaredRdr nm parent let (FN lf,_) = hsFreeAndDeclaredRdr nm liftedDecls logm $ "addParamsToParentAndLiftedDecl:(ef,lf)=" ++ showGhc (ef,lf) -- parameters to be added to pn because of lifting let newParamsNames = ((nub lf) \\ (nub ef)) \\ dd newParams = map GHC.nameRdrName newParamsNames logm $ "addParamsToParentAndLiftedDecl:(newParams,ef,lf,dd)=" ++ (showGhc (newParams,ef,lf,dd)) if newParams /= [] then if (any isComplexPatDecl liftedDecls) then error "This pattern binding cannot be lifted, as it uses some other local bindings!" else do -- first remove the decls to be lifted, so they are not disturbed (parent'',liftedDecls'',_msig) <- rmDecl pn False parent parent' <- addParamsToParent pn newParams parent'' liftedDecls' <- addParamsToDecls [liftedDecls''] pn newParams mLiftedSigs' <- mapM (addParamsToSigs newParamsNames) mLiftedSigs logm $ "addParamsToParentAndLiftedDecl:mLiftedSigs'=" ++ showGhc mLiftedSigs' return (parent',liftedDecls', mLiftedSigs') else return (parent,liftedDecls,mLiftedSigs) -- --------------------------------------------------------------------- {- -- TODO: perhaps move this to TypeUtils addParamsToSigs :: [GHC.Name] -> GHC.LSig GHC.RdrName -> RefactGhc (GHC.LSig GHC.RdrName) addParamsToSigs [] ms = return ms addParamsToSigs newParams (GHC.L l (GHC.TypeSig lns ltyp pns)) = do mts <- mapM getTypeForName newParams let ts = catMaybes mts logm $ "addParamsToSigs:ts=" ++ showGhc ts logDataWithAnns "addParamsToSigs:ts=" ts let newStr = ":: " ++ (intercalate " -> " $ map printSigComponent ts) ++ " -> " logm $ "addParamsToSigs:newStr=[" ++ newStr ++ "]" typ' <- liftT $ foldlM addOneType ltyp (reverse ts) sigOk <- isNewSignatureOk ts logm $ "addParamsToSigs:(sigOk,newStr)=" ++ show (sigOk,newStr) if sigOk then return (GHC.L l (GHC.TypeSig lns typ' pns)) else error $ "\nNew type signature may fail type checking: " ++ newStr ++ "\n" where addOneType :: GHC.LHsType GHC.RdrName -> GHC.Type -> Transform (GHC.LHsType GHC.RdrName) addOneType et t = do hst <- typeToLHsType t ss1 <- uniqueSrcSpanT hst1 <- case t of (GHC.FunTy _ _) -> do ss <- uniqueSrcSpanT let t1 = GHC.L ss (GHC.HsParTy hst) setEntryDPT hst (DP (0,0)) addSimpleAnnT t1 (DP (0,0)) [((G GHC.AnnOpenP),DP (0,1)),((G GHC.AnnCloseP),DP (0,0))] return t1 _ -> return hst let typ = GHC.L ss1 (GHC.HsFunTy hst1 et) addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnRarrow),DP (0,1))] return typ addParamsToSigs np ls = error $ "addParamsToSigs: no match for:" ++ showGhc (np,ls) -- --------------------------------------------------------------------- printSigComponent :: GHC.Type -> String printSigComponent x = ppType x -- --------------------------------------------------------------------- -- |Fail any signature having a forall in it. -- TODO: this is unnecesarily restrictive, but needs -- a) proper reversing of GHC.Type to GHC.LhsType -- b) some serious reverse type inference to ensure that the -- constraints are modified properly to merge the old signature -- part and the new. isNewSignatureOk :: [GHC.Type] -> RefactGhc Bool isNewSignatureOk types = do -- NOTE: under some circumstances enabling Rank2Types or RankNTypes -- can resolve the type conflict, this can potentially be checked -- for. -- NOTE2: perhaps proceed and reload the tentative refactoring into -- the GHC session and accept it only if it type checks let r = SYB.everythingStaged SYB.TypeChecker (++) [] ([] `SYB.mkQ` usesForAll) types usesForAll (GHC.ForAllTy _ _) = [1::Int] usesForAll _ = [] return $ emptyList r -- --------------------------------------------------------------------- -- TODO: perhaps move this to TypeUtils -- TODO: complete this typeToLHsType :: GHC.Type -> Transform (GHC.LHsType GHC.RdrName) typeToLHsType (GHC.TyVarTy v) = do ss <- uniqueSrcSpanT let typ = GHC.L ss (GHC.HsTyVar (GHC.nameRdrName $ Var.varName v)) addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnVal),DP (0,0))] return typ typeToLHsType (GHC.AppTy t1 t2) = do t1' <- typeToLHsType t1 t2' <- typeToLHsType t2 ss <- uniqueSrcSpanT return $ GHC.L ss (GHC.HsAppTy t1' t2') typeToLHsType t@(GHC.TyConApp _tc _ts) = tyConAppToHsType t typeToLHsType (GHC.FunTy t1 t2) = do t1' <- typeToLHsType t1 t2' <- typeToLHsType t2 ss <- uniqueSrcSpanT let typ = GHC.L ss (GHC.HsFunTy t1' t2') addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnRarrow),DP (0,1))] return typ typeToLHsType (GHC.ForAllTy _v t) = do t' <- typeToLHsType t ss1 <- uniqueSrcSpanT ss2 <- uniqueSrcSpanT return $ GHC.L ss1 (GHC.HsForAllTy GHC.Explicit Nothing (GHC.HsQTvs [] []) (GHC.L ss2 []) t') typeToLHsType (GHC.LitTy (GHC.NumTyLit i)) = do ss <- uniqueSrcSpanT let typ = GHC.L ss (GHC.HsTyLit (GHC.HsNumTy (show i) i)) :: GHC.LHsType GHC.RdrName addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnVal),DP (0,0))] return typ typeToLHsType (GHC.LitTy (GHC.StrTyLit s)) = do ss <- uniqueSrcSpanT let typ = GHC.L ss (GHC.HsTyLit (GHC.HsStrTy "" s)) :: GHC.LHsType GHC.RdrName addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnVal),DP (0,0))] return typ {- data Type = TyVarTy Var -- ^ Vanilla type or kind variable (*never* a coercion variable) | AppTy -- See Note [AppTy invariant] Type Type -- ^ Type application to something other than a 'TyCon'. Parameters: -- -- 1) Function: must /not/ be a 'TyConApp', -- must be another 'AppTy', or 'TyVarTy' -- -- 2) Argument type | TyConApp -- See Note [AppTy invariant] TyCon [KindOrType] -- ^ Application of a 'TyCon', including newtypes /and/ synonyms. -- Invariant: saturated appliations of 'FunTyCon' must -- use 'FunTy' and saturated synonyms must use their own -- constructors. However, /unsaturated/ 'FunTyCon's -- do appear as 'TyConApp's. -- Parameters: -- -- 1) Type constructor being applied to. -- -- 2) Type arguments. Might not have enough type arguments -- here to saturate the constructor. -- Even type synonyms are not necessarily saturated; -- for example unsaturated type synonyms -- can appear as the right hand side of a type synonym. | FunTy Type Type -- ^ Special case of 'TyConApp': @TyConApp FunTyCon [t1, t2]@ -- See Note [Equality-constrained types] | ForAllTy Var -- Type or kind variable Type -- ^ A polymorphic type | LitTy TyLit -- ^ Type literals are simillar to type constructors. -} tyConAppToHsType :: GHC.Type -> Transform (GHC.LHsType GHC.RdrName) tyConAppToHsType (GHC.TyConApp tc _ts) = r (show $ GHC.tyConName tc) where r str = do ss <- uniqueSrcSpanT let typ = GHC.L ss (GHC.HsTyLit (GHC.HsStrTy str $ GHC.mkFastString str)) :: GHC.LHsType GHC.RdrName addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnVal),DP (0,1))] return typ -- tyConAppToHsType t@(GHC.TyConApp _tc _ts) -- = error $ "tyConAppToHsType: unexpected:" ++ (SYB.showData SYB.TypeChecker 0 t) {- HsType HsForAllTy HsExplicitFlag (LHsTyVarBndrs name) (LHsContext name) (LHsType name) HsTyVar name HsAppTy (LHsType name) (LHsType name) HsFunTy (LHsType name) (LHsType name) HsListTy (LHsType name) HsPArrTy (LHsType name) HsTupleTy HsTupleSort [LHsType name] HsOpTy (LHsType name) (LHsTyOp name) (LHsType name) HsParTy (LHsType name) HsIParamTy HsIPName (LHsType name) HsEqTy (LHsType name) (LHsType name) HsKindSig (LHsType name) (LHsKind name) HsQuasiQuoteTy (HsQuasiQuote name) HsSpliceTy (HsSplice name) FreeVars PostTcKind HsDocTy (LHsType name) LHsDocString HsBangTy HsBang (LHsType name) HsRecTy [ConDeclField name] HsCoreTy Type HsExplicitListTy PostTcKind [LHsType name] HsExplicitTupleTy [PostTcKind] [LHsType name] HsTyLit HsTyLit HsWrapTy HsTyWrapper (HsType name) -} -} --------------------------------End of Lifting----------------------------------------- {-Refactoring : demote a function/pattern binding(simpe or complex) to the declaration where it is used. Descritption: if a declaration D, say, is only used by another declaration F,say, then D can be demoted into the local declaration list (where clause) in F. So currently, D can not be demoted if more than one declaration use it. In a multi-module context, a top-level definition can not be demoted if it is used by other modules. In the case that the demoted identifer is in the hiding list of import declaration in a client module, it should be removed from the hiding list. Function name:demote parameters: fileName--current file name. mod -- the scoped abstract syntax tree of the module. pn -- the function/pattern name to be demoted. -} demote' :: GHC.ModuleName -- -> FilePath -- -> (ParseResult,[PosToken]) -> GHC.Located GHC.Name -> RefactGhc [ApplyRefacResult] demote' modName (GHC.L _ pn) = do renamed <- getRefactRenamed parsed <- getRefactParsed nm <- getRefactNameMap targetModule <- getRefactTargetModule if isFunOrPatName nm pn parsed then do isTl <- isTopLevelPN pn if isTl && isExplicitlyExported nm pn parsed then error "This definition can not be demoted, as it is explicitly exported by the current module!" else do (refactoredMod,declaredPns) <- applyRefac (doDemoting pn) RSAlreadyLoaded if isTl && modIsExported modName renamed then do logm $ "demote':isTl && isExported" clients <- clientModsAndFiles targetModule logm $ "demote':clients=" ++ (showGhc clients) refactoredClients <-mapM (demotingInClientMod declaredPns) clients return (refactoredMod:refactoredClients) else do return [refactoredMod] else error "\nInvalid cursor position!" -- |Do refactoring in the client module, that is: -- a) Check whether the identifier is used in the module body -- b) If the identifier is not used but is hided by the import -- declaration, then remove it from the hiding. demotingInClientMod :: [GHC.Name] -> TargetModule -> RefactGhc ApplyRefacResult demotingInClientMod pns targetModule = do logm $ "demotingInClientMod:(pns,targetModule)=" ++ showGhc (pns,targetModule) getTargetGhc targetModule modu <- getRefactModule (refactoredMod,_) <- applyRefac (doDemotingInClientMod pns modu) RSAlreadyLoaded return refactoredMod doDemotingInClientMod :: [GHC.Name] -> GHC.Module -> RefactGhc () doDemotingInClientMod pns modName = do logm $ "doDemotingInClientMod:(pns,modName)=" ++ showGhc (pns,modName) (GHC.L _ p) <- getRefactParsed nm <- getRefactNameMap if any (\pn -> findNameInRdr nm pn (GHC.hsmodDecls p) || findNameInRdr nm pn (GHC.hsmodExports p)) pns then error $ "This definition can not be demoted, as it is used in the client module '"++(showGhc modName)++"'!" else if any (\pn->findNameInRdr nm pn (GHC.hsmodImports p)) pns -- TODO: reinstate this then do -- (mod',((ts',m),_))<-runStateT (rmItemsFromImport mod pns) ((ts,unmodified),(-1000,0)) return () else return () -- --------------------------------------------------------------------- doDemoting :: GHC.Name -> RefactGhc [GHC.Name] doDemoting pn = do clearRefactDone -- Only do this action once parsed <- getRefactParsed parsed' <- everywhereMStaged' SYB.Parser (SYB.mkM demoteInMod `SYB.extM` demoteInMatch `SYB.extM` demoteInPat `SYB.extM` demoteInLet `SYB.extM` demoteInStmt ) parsed putRefactParsed parsed' emptyAnns nm <- getRefactNameMap decls <- liftT $ hsDecls parsed let demotedDecls'= definingDeclsRdrNames nm [pn] decls True False declaredPnsRdr = nub $ concatMap definedPNsRdr demotedDecls' declaredPns = map (rdrName2NamePure nm) declaredPnsRdr return declaredPns where --1. demote from top level demoteInMod x@(parsed :: GHC.ParsedSource) = do decls <- liftT $ hsDecls parsed nm <- getRefactNameMap if not $ emptyList (definingDeclsRdrNames nm [pn] decls False False) then do logm "MoveDef:demoteInMod" -- ++AZ++ demoted <- doDemoting' parsed pn return demoted else return x --2. The demoted definition is a local decl in a match demoteInMatch match@(GHC.L _ (GHC.Match _ _pats _mt (GHC.GRHSs _ _ds))::GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) = do -- decls <- liftT $ hsDecls ds decls <- liftT $ hsDecls match nm <- getRefactNameMap if not $ emptyList (definingDeclsRdrNames nm [pn] decls False False) then do logm "MoveDef:demoteInMatch" -- ++AZ++ done <- getRefactDone match' <- if (not done) then doDemoting' match pn else return match return match' else return match --3. The demoted definition is a local decl in a pattern binding demoteInPat x@(pat@(GHC.L _ (GHC.ValD (GHC.PatBind _p (GHC.GRHSs _grhs _lb) _ _ _)))::GHC.LHsDecl GHC.RdrName) = do decls <- liftT $ hsDeclsPatBindD x nm <- getRefactNameMap if not $ emptyList (definingDeclsRdrNames nm [pn] decls False False) then do logm "MoveDef:demoteInPat" -- ++AZ++ done <- getRefactDone pat' <- if (not done) then doDemoting' pat pn else return pat return pat' else return x demoteInPat x = return x --4: The demoted definition is a local decl in a Let expression demoteInLet x@(letExp@(GHC.L _ (GHC.HsLet _ds _e))::GHC.LHsExpr GHC.RdrName) = do decls <- liftT $ hsDecls x nm <- getRefactNameMap if not $ emptyList (definingDeclsRdrNames nm [pn] decls False False) then do logm "MoveDef:demoteInLet" -- ++AZ++ done <- getRefactDone letExp' <- if (not done) then doDemoting' letExp pn else return letExp return letExp' else return x demoteInLet x = return x --6.The demoted definition is a local decl in a Let statement. -- demoteInStmt (letStmt@(HsLetStmt ds stmts):: (HsStmt (HsExpP) (HsPatP) [HsDeclP])) demoteInStmt (letStmt@(GHC.L _ (GHC.LetStmt _binds))::GHC.LStmt GHC.RdrName (GHC.LHsExpr GHC.RdrName)) = do decls <- liftT $ hsDecls letStmt nm <- getRefactNameMap if not $ emptyList (definingDeclsRdrNames nm [pn] decls False False) then do logm "MoveDef:demoteInStmt" -- ++AZ++ done <- getRefactDone letStmt' <- if (not done) then doDemoting' letStmt pn else return letStmt return letStmt' else return letStmt demoteInStmt x = return x -- |Demote the declaration of 'pn' in the context of 't'. doDemoting' :: (UsedByRhs t) => t -> GHC.Name -> RefactGhc t doDemoting' t pn = do nm <- getRefactNameMap -- origDecls <- liftT $ hsDecls t origDecls <- liftT $ hsDeclsGeneric t let demotedDecls'= definingDeclsRdrNames nm [pn] origDecls True False declaredPns = nub $ concatMap (definedNamesRdr nm) demotedDecls' pnsUsed = usedByRhsRdr nm t declaredPns logm $ "doDemoting':(pn,declaredPns)=" ++ showGhc (pn,declaredPns) -- logm $ "doDemoting':t=" ++ (SYB.showData SYB.Renamer 0 t) logm $ "doDemoting':(declaredPns,pnsUsed)=" ++ showGhc (declaredPns,pnsUsed) r <- if not pnsUsed -- (usedByRhs t declaredPns) then do logm $ "doDemoting' no pnsUsed" -- dt <- liftT $ hsDecls t let dt = origDecls let demotedDecls = definingDeclsRdrNames nm [pn] dt True True otherBinds = (deleteFirstsBy (sameBindRdr nm) dt demotedDecls) {- From 'hsDecls t' to 'hsDecls t \\ demotedDecls'. Bug fixed 06/09/2004 to handle direct recursive function. -} xx = map (\b -> (b,uses nm declaredPns [b])) otherBinds useCount = sum $ concatMap snd xx logm $ "doDemoting': declaredPns=" ++ (showGhc declaredPns) logm $ "doDemoting': uses xx=" ++ (showGhc xx) logm $ "doDemoting': uses useCount=" ++ (show useCount) case useCount of 0 ->do error "\n Nowhere to demote this function!\n" 1 -> --This function is only used by one friend function do logm "MoveDef.doDemoting':target location found" -- ++AZ++ let (FN f,_d) = hsFreeAndDeclaredRdr nm demotedDecls (ds,removedDecl,_sigRemoved) <- rmDecl pn False t (t',demotedSigs) <- rmTypeSigs declaredPns ds logDataWithAnns "MoveDef.doDemoting':after rmTypeSigs:demotedSigs=" demotedSigs logm $ "MoveDef:declaredPns=" ++ (showGhc declaredPns) -- ++AZ++ dl <- mapM (flip (declaredNamesInTargetPlace nm) ds) declaredPns logm $ "mapM declaredNamesInTargetPlace done" --make sure free variable in 'f' do not clash with variables in 'dl', --otherwise do renaming. let clashedNames=filter (\x-> elem (id x) (map id f)) $ (nub.concat) dl --rename clashed names to new names created automatically,update TOKEN STREAM as well. if clashedNames/=[] then error ("The identifier(s):" ++ showGhc clashedNames ++ ", declared in where the definition will be demoted to, will cause name clash/capture" ++" after demoting, please do renaming first!") else --duplicate demoted declarations to the right place. do duplicateDecls declaredPns removedDecl demotedSigs t' _ ->error "\nThis function/pattern binding is used by more than one friend bindings\n" else error "This function can not be demoted as it is used in current level!\n" return r where ---find how many matches/pattern bindings use 'pn'------- uses :: NameMap -> [GHC.Name] -> [GHC.LHsDecl GHC.RdrName] -> [Int] uses nm pns t2 = concatMap used t2 where used :: GHC.LHsDecl GHC.RdrName -> [Int] #if __GLASGOW_HASKELL__ <= 710 used (GHC.L _ (GHC.ValD (GHC.FunBind _n _ (GHC.MG matches _ _ _) _ _ _))) #else used (GHC.L _ (GHC.ValD (GHC.FunBind _n (GHC.MG (GHC.L _ matches) _ _ _) _ _ _))) #endif = concatMap (usedInMatch pns) matches used (GHC.L _ (GHC.ValD (GHC.PatBind pat rhs _ _ _))) | (not $ findNamesRdr nm pns pat) && findNamesRdr nm pns rhs = [1::Int] used _ = [] usedInMatch pns' (GHC.L _ (GHC.Match _ pats _ rhs)) | (not $ findNamesRdr nm pns' pats) && findNamesRdr nm pns' rhs = [1::Int] usedInMatch _ _ = [] duplicateDecls :: (SYB.Data t,SYB.Typeable t) => [GHC.Name] -- ^ function names to be demoted -> GHC.LHsDecl GHC.RdrName -- ^Bind being demoted -> [GHC.LSig GHC.RdrName] -- ^Signatures being demoted, if any -> t -> RefactGhc t duplicateDecls pns demoted dsig o = do logm $ "duplicateDecls:t=" ++ SYB.showData SYB.Parser 0 o hasDeclsSybTransform workerHsDecls workerBind o where workerHsDecls :: forall t. HasDecls t => t -> RefactGhc t workerHsDecls t' = do dds <- liftT $ hsDecls t' ds'' <- duplicateDecls' pns demoted dsig dds liftT $ replaceDecls t' ds'' workerBind :: (GHC.LHsBind GHC.RdrName -> RefactGhc (GHC.LHsBind GHC.RdrName)) workerBind t'@(GHC.L _ (GHC.PatBind{})) = do dds <- liftT $ hsDeclsPatBind t' ds'' <- duplicateDecls' pns demoted dsig dds liftT $ replaceDeclsPatBind t' ds'' workerBind x = error $ "MoveDef.duplicateDecls.workerBind:unmatched LHsBind:" ++ showGhc x -- duplicate demotedDecls to the right place (the outer most level where it is used). duplicateDecls' :: [GHC.Name] -- ^ function names to be demoted -> GHC.LHsDecl GHC.RdrName -- ^Bind being demoted -> [GHC.LSig GHC.RdrName] -- ^Signatures being demoted, if any -> [GHC.LHsDecl GHC.RdrName] -- ^Binds of original top -- level entiity, -- including src and dst -> RefactGhc [GHC.LHsDecl GHC.RdrName] duplicateDecls' pns demoted dsig decls = do nm <- getRefactNameMap everywhereMStaged' SYB.Parser (SYB.mkM (dupInMatch nm) -- top-down approach `SYB.extM` (dupInPat nm)) decls where dupInMatch nm (match@(GHC.L _ (GHC.Match _ pats _mt rhs)) :: GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) | (not $ findNamesRdr nm pns pats) && findNamesRdr nm pns rhs = do done <- getRefactDone logm $ "duplicateDecls.dupInMatch:value of done=" ++ (show done) -- ++AZ++ if done then return match else do logm "duplicateDecls:setting done" -- ++AZ++ setRefactDone match' <- foldParams pns match decls demoted dsig return match' dupInMatch _ x = return x dupInPat nm ((GHC.PatBind pat rhs@(GHC.GRHSs grhs lb) ty fvs ticks) :: GHC.HsBind GHC.RdrName) | (not $ findNamesRdr nm pns pat) && findNamesRdr nm pns rhs = do logm $ "duplicateDecls.dupInPat" let declsToLift = definingDeclsRdrNames' nm pns t lb' <- moveDecl1 lb Nothing pns declsToLift pns [] return (GHC.PatBind pat (GHC.GRHSs grhs lb') ty fvs ticks) dupInPat _ x = return x -- demotedDecls = definingDecls pns decls True False --------------------------------------------------------------------- declaredNamesInTargetPlace :: (SYB.Data t) => NameMap -> GHC.Name -> t -> RefactGhc [GHC.Name] declaredNamesInTargetPlace nm pn' t' = do logm $ "declaredNamesInTargetPlace:pn=" ++ (showGhc pn') res <- applyTU (stop_tdTU (failTU `adhocTU` inMatch `adhocTU` inPat)) t' logm $ "declaredNamesInTargetPlace:res=" ++ (showGhc res) return res where inMatch ((GHC.Match _ _pats _ rhs) :: GHC.Match GHC.RdrName (GHC.LHsExpr GHC.RdrName)) | findNameInRdr nm pn' rhs = do logm $ "declaredNamesInTargetPlace:inMatch" -- fds <- hsFDsFromInside rhs let (_,DN ds) = hsFDsFromInsideRdr nm rhs return ds inMatch _ = return mzero inPat ((GHC.PatBind pat rhs _ _ _) :: GHC.HsBind GHC.RdrName) |findNameInRdr nm pn' rhs = do logm $ "declaredNamesInTargetPlace:inPat" let (_,DN ds) = hsFDsFromInsideRdr nm pat return ds inPat _= return mzero -- --------------------------------------------------------------------- {- foldParams:remove parameters in the demotedDecls if possible parameters: pn -- the function/pattern name to be demoted in PName format match--where the demotedDecls will be demoted to demotedDecls -- the declarations to be demoted. example: module Test where demote 'sq' module Test where sumSquares x y ===> sumSquares x y =(sq 0) + (sq y) = sq x 0+ sq x y where sq y=x ^ y sq x y=x^y -} --PROBLEM: TYPE SIGNATURE SHOULD BE CHANGED. --- TEST THIS FUNCTION!!! foldParams :: [GHC.Name] -- ^The (list?) function name being demoted -> GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName) -- ^The RHS of the place to receive the demoted decls -> [GHC.LHsDecl GHC.RdrName] -- ^Binds of original top level entiity, including src and dst -> GHC.LHsDecl GHC.RdrName -- ^The decls being demoted -> [GHC.LSig GHC.RdrName] -- ^Signatures being demoted, if any -> RefactGhc (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) foldParams pns match@(GHC.L l (GHC.Match _mfn _pats _mt rhs)) _decls demotedDecls dsig =do logm $ "MoveDef.foldParams entered" nm <- getRefactNameMap let matches = concatMap matchesInDecls [demotedDecls] pn = ghead "foldParams" pns --pns /=[] logm $ "MoveDef.foldParams before allParams" params <- allParams pn rhs [] logm $ "foldParams:params=" ++ showGhc params if (length.nub.map length) params==1 -- have same number of param && ((length matches)==1) -- only one 'match' in the demoted declaration then do let patsInDemotedDecls=(patsInMatch.(ghead "foldParams")) matches subst = mkSubst nm patsInDemotedDecls params fstSubst = map fst subst sndSubst = map snd subst rhs' <- rmParamsInParent pn sndSubst rhs let ls = map (hsFreeAndDeclaredRdr nm) sndSubst let newNames = ((concatMap (fn . fst) ls)) \\ (fstSubst) --There may be name clashing because of introducing new names. clashedNames <- getClashedNames nm fstSubst newNames (ghead "foldParams" matches) logm $ "MoveDef.foldParams about to foldInDemotedDecls" demotedDecls''' <- foldInDemotedDecls pns clashedNames subst [demotedDecls] logm $ "MoveDef.foldParams foldInDemotedDecls done" let match' = GHC.L l ((GHC.unLoc match) {GHC.m_grhss = rhs' }) match'' <- addDecl match' Nothing (demotedDecls''',Nothing) logm $ "MoveDef.foldParams addDecl done 1" return match'' else do logm $ "foldParams:no params" let sigs = map wrapSig dsig match' <- addDecl match Nothing (sigs++[demotedDecls],Nothing) logm "MoveDef.foldParams addDecl done 2" return match' where matchesInDecls :: GHC.LHsDecl GHC.RdrName -> [GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)] #if __GLASGOW_HASKELL__ <= 710 matchesInDecls (GHC.L _ (GHC.ValD (GHC.FunBind _ _ (GHC.MG matches _ _ _) _ _ _))) = matches #else matchesInDecls (GHC.L _ (GHC.ValD (GHC.FunBind _ (GHC.MG (GHC.L _ matches) _ _ _) _ _ _))) = matches #endif matchesInDecls _x = [] patsInMatch (GHC.L _ (GHC.Match _ pats' _ _)) = pats' foldInDemotedDecls :: [GHC.Name] -- ^The (list?) of names to be demoted -> [GHC.Name] -- ^Any names that clash -> [(GHC.Name, GHC.HsExpr GHC.RdrName)] -- ^Parameter substitutions required -> [GHC.LHsDecl GHC.RdrName] -- ^Binds of original top level entity, including src and dst -> RefactGhc [GHC.LHsDecl GHC.RdrName] foldInDemotedDecls pns' clashedNames subst decls = do logm $ "foldInDemotedDecls:(pns',clashedNames,subst)=" ++ showGhc (pns',clashedNames,subst) logm $ "foldInDemotedDecls:decls=" ++ SYB.showData SYB.Parser 0 decls nm <- getRefactNameMap SYB.everywhereMStaged SYB.Parser (SYB.mkM (worker nm) `SYB.extM` (workerBind nm)) decls where #if __GLASGOW_HASKELL__ <= 710 worker nm (match'@(GHC.L _ (GHC.FunBind ln _ (GHC.MG _matches _ _ _) _ _ _)) :: GHC.LHsBind GHC.RdrName) #else worker nm (match'@(GHC.L _ (GHC.FunBind ln (GHC.MG _matches _ _ _) _ _ _)) :: GHC.LHsBind GHC.RdrName) #endif = do logm $ "foldInDemotedDecls:rdrName2NamePure nm ln=" ++ show (rdrName2NamePure nm ln) if isJust (find (== rdrName2NamePure nm ln) pns') then do logm $ "foldInDemotedDecls:found match'" match'' <- foldM (flip autoRenameLocalVar) match' clashedNames match''' <- foldM replaceExpWithUpdToks match'' subst rmParamsInDemotedDecls (map fst subst) match''' else return match' worker _ x = return x workerBind nm ((GHC.L ll (GHC.ValD d)) :: GHC.LHsDecl GHC.RdrName) = do (GHC.L _ d') <- worker nm (GHC.L ll d) return (GHC.L ll (GHC.ValD d')) workerBind _ x = return x ------Get all of the paramaters supplied to pn --------------------------- {- eg. sumSquares x1 y1 x2 y2 = rt x1 y1 + rt x2 y2 rt x y = x+y demote 'rt' to 'sumSquares', 'allParams pn rhs []' returns [[x1,x2],[y1,y2]] where pn is 'rt' and rhs is 'rt x1 y1 + rt x2 y2' -} allParams :: GHC.Name -> GHC.GRHSs GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> [[GHC.HsExpr GHC.RdrName]] -> RefactGhc [[GHC.HsExpr GHC.RdrName]] allParams pn rhs1 initial -- pn: demoted function/pattern name. =do nm <- getRefactNameMap let p = getOneParam nm pn rhs1 -- putStrLn (show p) logm $ "allParams:p=" ++ showGhc p if (nonEmptyList p) then do rhs' <- rmOneParam pn rhs1 logDataWithAnns "allParams:rhs'=" rhs' allParams pn rhs' (initial++[p]) else return initial where getOneParam :: (SYB.Data t) => NameMap -> GHC.Name -> t -> [GHC.HsExpr GHC.RdrName] getOneParam nm pn1 = SYB.everythingStaged SYB.Renamer (++) [] ([] `SYB.mkQ` worker) -- =applyTU (stop_tdTU (failTU `adhocTU` worker)) where worker :: GHC.HsExpr GHC.RdrName -> [GHC.HsExpr GHC.RdrName] worker (GHC.HsApp e1 e2) |(expToNameRdr nm e1 == Just pn1) = [GHC.unLoc e2] worker _ = [] rmOneParam :: (SYB.Data t) => GHC.Name -> t -> RefactGhc t rmOneParam pn1 t -- This genuinely needs to be done once only. Damn. -- =applyTP (stop_tdTP (failTP `adhocTP` worker)) = do -- _ <- clearRefactDone nm <- getRefactNameMap everywhereMStaged' SYB.Parser (SYB.mkM (worker nm)) t where worker nm (GHC.L _ (GHC.HsApp e1 _e2 )) -- The param being removed is e2 |expToNameRdr nm e1 == Just pn1 = return e1 worker _ x = return x {- AST output addthree x y z becomes (HsApp (L {test/testdata/Demote/WhereIn6.hs:10:17-28} (HsApp (L {test/testdata/Demote/WhereIn6.hs:10:17-26} (HsApp (L {test/testdata/Demote/WhereIn6.hs:10:17-24} (HsVar {Name: WhereIn6.addthree})) (L {test/testdata/Demote/WhereIn6.hs:10:26} (HsVar {Name: x})))) (L {test/testdata/Demote/WhereIn6.hs:10:28} (HsVar {Name: y})))) (L {test/testdata/Demote/WhereIn6.hs:10:30} (HsVar {Name: z}))) ----- (HsApp (HsApp (HsApp (HsVar {Name: WhereIn6.addthree})) (HsVar {Name: x})))) (HsVar {Name: y})))) (HsVar {Name: z}))) ----- sq p x becomes (HsApp (HsApp (HsVar {Name: Demote.WhereIn4.sq})) (HsVar {Name: p})))) (HsVar {Name: x}))) ---- sq x becomes (HsApp (HsVar {Name: sq})) (HsVar {Name: x}))) -} -----------remove parameters in demotedDecls------------------------------- rmParamsInDemotedDecls :: [GHC.Name] -> GHC.LHsBind GHC.RdrName -> RefactGhc (GHC.LHsBind GHC.RdrName) rmParamsInDemotedDecls ps bind -- =applyTP (once_tdTP (failTP `adhocTP` worker)) = SYB.everywhereMStaged SYB.Parser (SYB.mkM worker) bind where worker :: GHC.Match GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> RefactGhc (GHC.Match GHC.RdrName (GHC.LHsExpr GHC.RdrName)) worker (GHC.Match mfn' pats2 typ rhs1) = do nm <- getRefactNameMap let pats'=filter (\x->not ((patToNameRdr nm x /= Nothing) && elem (gfromJust "rmParamsInDemotedDecls" $ patToNameRdr nm x) ps)) pats2 return (GHC.Match mfn' pats' typ rhs1) ----------remove parameters in the parent functions' rhs------------------- rmParamsInParent :: GHC.Name -> [GHC.HsExpr GHC.RdrName] -> GHC.GRHSs GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> RefactGhc (GHC.GRHSs GHC.RdrName (GHC.LHsExpr GHC.RdrName)) rmParamsInParent pn es grhss = do nm <- getRefactNameMap -- =applyTP (full_buTP (idTP `adhocTP` worker)) SYB.everywhereMStaged SYB.Renamer (SYB.mkM (worker nm)) grhss where worker nm expr@(GHC.L _ (GHC.HsApp e1 e2)) | findNamesRdr nm [pn] e1 && (elem (showGhc (GHC.unLoc e2)) (map (showGhc) es)) = do liftT $ transferEntryDPT expr e1 return e1 worker nm (expr@(GHC.L _ (GHC.HsPar e1))) |Just pn==expToNameRdr nm e1 = do liftT $ transferEntryDPT expr e1 return e1 worker _ x =return x getClashedNames :: NameMap -> [GHC.Name] -> [GHC.Name] -> GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> RefactGhc [GHC.Name] getClashedNames nm oldNames newNames match' = do let (_f,DN d) = hsFDsFromInsideRdr nm match' ds'' <- mapM (flip (hsVisibleDsRdr nm) match') oldNames let ds' = map (\(DN ds) -> ds) ds'' -- return clashed names return (filter (\x->elem ({- pNtoName -} x) newNames) --Attention: nub ( nub (d `union` (nub.concat) ds'))) ----- make Substitions between formal and actual parameters.----------------- mkSubst :: NameMap -> [GHC.LPat GHC.RdrName] -> [[GHC.HsExpr GHC.RdrName]] -> [(GHC.Name,GHC.HsExpr GHC.RdrName)] mkSubst nm pats1 params = catMaybes (zipWith (\x y -> if (patToNameRdr nm x/=Nothing) && (length (nub $ map showGhc y)==1) then Just (gfromJust "mkSubst" $ patToNameRdr nm x,(ghead "mkSubst") y) else Nothing) pats1 params) -- |substitute an old expression by new expression replaceExpWithUpdToks :: GHC.LHsBind GHC.RdrName -> (GHC.Name, GHC.HsExpr GHC.RdrName) -> RefactGhc (GHC.LHsBind GHC.RdrName) replaceExpWithUpdToks decls subst = do nm <- getRefactNameMap let worker (e@(GHC.L l _)::GHC.LHsExpr GHC.RdrName) |(expToNameRdr nm e) == Just (fst subst) = return (GHC.L l (snd subst)) worker x=return x -- = applyTP (full_buTP (idTP `adhocTP` worker)) decls everywhereMStaged' SYB.Parser (SYB.mkM worker) decls -- | return True if pn is a local function/pattern name isLocalFunOrPatName :: SYB.Data t => NameMap -> GHC.Name -> t -> Bool isLocalFunOrPatName nm pn scope = isLocalPN pn && isFunOrPatName nm pn scope -- EOF
RefactoringTools/HaRe
src/Language/Haskell/Refact/Refactoring/MoveDef.hs
Haskell
bsd-3-clause
76,745
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE TemplateHaskell #-} module Snap.Snaplet.Internal.Tests ( tests, initTest ) where ------------------------------------------------------------------------------ import Control.Lens (makeLenses) import Control.Monad.Trans (MonadIO, liftIO) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B import Data.Text (Text) import Prelude hiding (catch, (.)) import System.Directory (getCurrentDirectory) import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.Framework.Providers.SmallCheck (testProperty) import Test.HUnit hiding (Test, path) import Test.SmallCheck ((==>)) ------------------------------------------------------------------------------ import Snap.Snaplet.Internal.Initializer import Snap.Snaplet.Internal.Types --------------------------------- -- TODO: this module is a mess -- --------------------------------- ------------------------------------------------------------------------------ data Foo = Foo Int data Bar = Bar Int data App = App { _foo :: Snaplet Foo , _bar :: Snaplet Bar } makeLenses ''App --showConfig :: SnapletConfig -> IO () --showConfig c = do -- putStrLn "SnapletConfig:" -- print $ _scAncestry c -- print $ _scFilePath c -- print $ _scId c -- print $ _scDescription c -- print $ _scRouteContext c -- putStrLn "" ------------------------------------------------------------------------------ assertGet :: (MonadIO m, Show a, Eq a) => String -> m a -> a -> m () assertGet name getter val = do v <- getter liftIO $ assertEqual name val v ------------------------------------------------------------------------------ configAssertions :: (MonadSnaplet m, MonadIO (m b v)) => [Char] -> ([Text], FilePath, Maybe Text, Text, ByteString) -> m b v () configAssertions prefix (a,f,n,d,r) = do assertGet (prefix ++ "ancestry" ) getSnapletAncestry a assertGet (prefix ++ "file path" ) getSnapletFilePath f assertGet (prefix ++ "name" ) getSnapletName n assertGet (prefix ++ "description" ) getSnapletDescription d assertGet (prefix ++ "route context" ) getSnapletRootURL r ------------------------------------------------------------------------------ appInit :: SnapletInit App App appInit = makeSnaplet "app" "Test application" Nothing $ do cwd <- liftIO getCurrentDirectory configAssertions "root " ([], cwd, Just "app", "Test application", "") assertGet "environment" getEnvironment "devel" f <- nestSnaplet "foo" foo $ fooInit b <- nestSnaplet "bar" bar $ barInit return $ App f b ------------------------------------------------------------------------------ fooInit :: SnapletInit b Foo fooInit = makeSnaplet "foo" "Foo Snaplet" Nothing $ do cwd <- liftIO getCurrentDirectory let dir = cwd ++ "/snaplets/foo" configAssertions "foo " (["app"], dir, Just "foo", "Foo Snaplet", "foo") return $ Foo 42 ------------------------------------------------------------------------------ barInit :: SnapletInit b Bar barInit = makeSnaplet "bar" "Bar Snaplet" Nothing $ do cwd <- liftIO getCurrentDirectory let dir = cwd ++ "/snaplets/bar" configAssertions "bar " (["app"], dir, Just "bar", "Bar Snaplet", "bar") return $ Bar 2 ------------------------------------------------------------------------------ initTest :: IO () initTest = do (out,_,_) <- runSnaplet Nothing appInit -- note from gdc: wtf? if out == "aoeu" then putStrLn "Something really strange" else return () ------------------------------------------------------------------------------ tests :: Test tests = testGroup "Snap.Snaplet.Internal" [ testCase "initializer tests" initTest , testProperty "buildPath generates no double slashes" doubleSlashes ] --doubleSlashes :: Monad m => [String] -> Property m doubleSlashes arrStr = noSlashes ==> not (B.isInfixOf "//" $ buildPath arr) where arr = map B.pack arrStr noSlashes = not $ or $ map (B.elem '/') arr
sopvop/snap
test/suite/Snap/Snaplet/Internal/Tests.hs
Haskell
bsd-3-clause
4,669
module MapFusion where import Prelude hiding (map) {-# RULES "map-fusion" forall f g. map f . map g = map (f . g) #-} map :: (a -> b) -> [a] -> [b] map f [] = [] map f (a:as) = f a : map f as
conal/hermit
examples/map-fusion/MapFusion.hs
Haskell
bsd-2-clause
201
{-# LANGUAGE DeriveGeneric #-} module GHC.ForeignSrcLang.Type ( ForeignSrcLang(..) ) where import Prelude -- See note [Why do we import Prelude here?] import GHC.Generics (Generic) -- | Foreign formats supported by GHC via TH data ForeignSrcLang = LangC -- ^ C | LangCxx -- ^ C++ | LangObjc -- ^ Objective C | LangObjcxx -- ^ Objective C++ | LangAsm -- ^ Assembly language (.s) | RawObject -- ^ Object (.o) deriving (Eq, Show, Generic)
sdiehl/ghc
libraries/ghc-boot-th/GHC/ForeignSrcLang/Type.hs
Haskell
bsd-3-clause
470
module B1 where import A1 f :: C1 -> [Int] f (C1 x@[]) = x f (C1 x@(b_1 : b_2)) = x f (C1 x) = x
kmate/HaRe
old/testing/subIntroPattern/B1_TokOut.hs
Haskell
bsd-3-clause
98
module ScopeNamesBase where import ScopeNames import ScopeNamesBaseStruct import DefinedNamesBase() import FreeNamesBase() import Syntax instance Eq i => ScopeNames i e (HsExpI i) (HsExpI (i,e)) where scopeNames = scopeNamesRec instance Eq i => ScopeNames i e (HsDeclI i) (HsDeclI (i,e)) where scopeNames = scopeNamesRec instance ScopeNames i e (HsPatI i) (HsPatI (i,e)) where scopeNames = scopeNamesRec instance ScopeNames i e (HsTypeI i) (HsTypeI (i,e)) where scopeNames = scopeNamesRec
forste/haReFork
tools/base/defs/ScopeNamesBase.hs
Haskell
bsd-3-clause
507
module Pfe2Cmds where --import Prelude hiding (putStr,putStrLn) --import WorkModule(analyzeSCM,expRel,inscpRel,mkWM) import Relations(applyRel) import SourceNames(SN(..)) import SrcLoc1(loc0) import Pfe1Cmds(pfe1Cmds) import PfeParse(moduleArg,idArgs,runCmds) import PFE2(runPFE2,getModuleExports,getAllExports) import PFE0(pput,allModules) --import AbstractIO import PrettyPrint import MUtils(done) pfe2 ext = runPFE2Cmds ext pfe2Cmds runPFE2Cmds ext = runCmds (runPFE2 ext) pfe2Cmds = pfe1Cmds ++ [-- Module system queries (import/export, top level environment) -- ("topenv" , (Null topenv, "check all import and export specifications")), -- just update, no output ("exports" , (moduleArg exports,"list entities exported by the modules")), ("find" , (idArgs find,"find exported entities with the given names")) ] --- Module system queries (import/export, top level environment) --------------- exports = showModuleInfo snd showModuleInfo sel m = pput . ppModuleInfo sel m =<< getModuleExports m ppExports = ppModuleInfo snd ppModuleInfo sel m info = sep [m<>":",nest 2 . ppi $ sel info] find ids = do exports <- getAllExports mapM_ (mapM_ pp1 . find1 exports) ids where pp1 (m,ents) = pput (m<>":"<+>vcat ents) find1 mes id = [(m,ents)|(m,(t,es))<-mes, let ents=applyRel es (sn id), not (null ents)] --topenv = analyzeModules >> done sn n = SN n loc0 -- !!
forste/haReFork
tools/pfe/Pfe2Cmds.hs
Haskell
bsd-3-clause
1,444
{-# LANGUAGE Unsafe #-} {-# LANGUAGE ExistentialQuantification, NoImplicitPrelude #-} module GHC.Event.Internal ( -- * Event back end Backend , backend , delete , poll , modifyFd , modifyFdOnce -- * Event type , Event , evtRead , evtWrite , evtClose , eventIs -- * Lifetimes , Lifetime(..) , EventLifetime , eventLifetime , elLifetime , elEvent -- * Timeout type , Timeout(..) -- * Helpers , throwErrnoIfMinus1NoRetry ) where import Data.Bits ((.|.), (.&.)) import Data.OldList (foldl', filter, intercalate, null) import Foreign.C.Error (eINTR, getErrno, throwErrno) import System.Posix.Types (Fd) import GHC.Base import GHC.Num (Num(..)) import GHC.Show (Show(..)) -- | An I\/O event. newtype Event = Event Int deriving (Eq) evtNothing :: Event evtNothing = Event 0 {-# INLINE evtNothing #-} -- | Data is available to be read. evtRead :: Event evtRead = Event 1 {-# INLINE evtRead #-} -- | The file descriptor is ready to accept a write. evtWrite :: Event evtWrite = Event 2 {-# INLINE evtWrite #-} -- | Another thread closed the file descriptor. evtClose :: Event evtClose = Event 4 {-# INLINE evtClose #-} eventIs :: Event -> Event -> Bool eventIs (Event a) (Event b) = a .&. b /= 0 -- | @since 4.3.1.0 instance Show Event where show e = '[' : (intercalate "," . filter (not . null) $ [evtRead `so` "evtRead", evtWrite `so` "evtWrite", evtClose `so` "evtClose"]) ++ "]" where ev `so` disp | e `eventIs` ev = disp | otherwise = "" -- | @since 4.3.1.0 instance Monoid Event where mempty = evtNothing mappend = evtCombine mconcat = evtConcat evtCombine :: Event -> Event -> Event evtCombine (Event a) (Event b) = Event (a .|. b) {-# INLINE evtCombine #-} evtConcat :: [Event] -> Event evtConcat = foldl' evtCombine evtNothing {-# INLINE evtConcat #-} -- | The lifetime of an event registration. -- -- @since 4.8.1.0 data Lifetime = OneShot -- ^ the registration will be active for only one -- event | MultiShot -- ^ the registration will trigger multiple times deriving (Show, Eq) -- | The longer of two lifetimes. elSupremum :: Lifetime -> Lifetime -> Lifetime elSupremum OneShot OneShot = OneShot elSupremum _ _ = MultiShot {-# INLINE elSupremum #-} -- | @mappend@ == @elSupremum@ -- -- @since 4.8.0.0 instance Monoid Lifetime where mempty = OneShot mappend = elSupremum -- | A pair of an event and lifetime -- -- Here we encode the event in the bottom three bits and the lifetime -- in the fourth bit. newtype EventLifetime = EL Int deriving (Show, Eq) -- | @since 4.8.0.0 instance Monoid EventLifetime where mempty = EL 0 EL a `mappend` EL b = EL (a .|. b) eventLifetime :: Event -> Lifetime -> EventLifetime eventLifetime (Event e) l = EL (e .|. lifetimeBit l) where lifetimeBit OneShot = 0 lifetimeBit MultiShot = 8 {-# INLINE eventLifetime #-} elLifetime :: EventLifetime -> Lifetime elLifetime (EL x) = if x .&. 8 == 0 then OneShot else MultiShot {-# INLINE elLifetime #-} elEvent :: EventLifetime -> Event elEvent (EL x) = Event (x .&. 0x7) {-# INLINE elEvent #-} -- | A type alias for timeouts, specified in seconds. data Timeout = Timeout {-# UNPACK #-} !Double | Forever deriving (Show) -- | Event notification backend. data Backend = forall a. Backend { _beState :: !a -- | Poll backend for new events. The provided callback is called -- once per file descriptor with new events. , _bePoll :: a -- backend state -> Maybe Timeout -- timeout in milliseconds ('Nothing' for non-blocking poll) -> (Fd -> Event -> IO ()) -- I/O callback -> IO Int -- | Register, modify, or unregister interest in the given events -- on the given file descriptor. , _beModifyFd :: a -> Fd -- file descriptor -> Event -- old events to watch for ('mempty' for new) -> Event -- new events to watch for ('mempty' to delete) -> IO Bool -- | Register interest in new events on a given file descriptor, set -- to be deactivated after the first event. , _beModifyFdOnce :: a -> Fd -- file descriptor -> Event -- new events to watch -> IO Bool , _beDelete :: a -> IO () } backend :: (a -> Maybe Timeout -> (Fd -> Event -> IO ()) -> IO Int) -> (a -> Fd -> Event -> Event -> IO Bool) -> (a -> Fd -> Event -> IO Bool) -> (a -> IO ()) -> a -> Backend backend bPoll bModifyFd bModifyFdOnce bDelete state = Backend state bPoll bModifyFd bModifyFdOnce bDelete {-# INLINE backend #-} poll :: Backend -> Maybe Timeout -> (Fd -> Event -> IO ()) -> IO Int poll (Backend bState bPoll _ _ _) = bPoll bState {-# INLINE poll #-} -- | Returns 'True' if the modification succeeded. -- Returns 'False' if this backend does not support -- event notifications on this type of file. modifyFd :: Backend -> Fd -> Event -> Event -> IO Bool modifyFd (Backend bState _ bModifyFd _ _) = bModifyFd bState {-# INLINE modifyFd #-} -- | Returns 'True' if the modification succeeded. -- Returns 'False' if this backend does not support -- event notifications on this type of file. modifyFdOnce :: Backend -> Fd -> Event -> IO Bool modifyFdOnce (Backend bState _ _ bModifyFdOnce _) = bModifyFdOnce bState {-# INLINE modifyFdOnce #-} delete :: Backend -> IO () delete (Backend bState _ _ _ bDelete) = bDelete bState {-# INLINE delete #-} -- | Throw an 'IOError' corresponding to the current value of -- 'getErrno' if the result value of the 'IO' action is -1 and -- 'getErrno' is not 'eINTR'. If the result value is -1 and -- 'getErrno' returns 'eINTR' 0 is returned. Otherwise the result -- value is returned. throwErrnoIfMinus1NoRetry :: (Eq a, Num a) => String -> IO a -> IO a throwErrnoIfMinus1NoRetry loc f = do res <- f if res == -1 then do err <- getErrno if err == eINTR then return 0 else throwErrno loc else return res
snoyberg/ghc
libraries/base/GHC/Event/Internal.hs
Haskell
bsd-3-clause
6,369
module Main where import X main :: IO () main = print $ case f x of A -> True; B -> False
ghc-android/ghc
testsuite/tests/driver/recomp010/Main.hs
Haskell
bsd-3-clause
93
module Main where import Game main = putStrLn "This game is not yet implemented, so you win by default!"
PolyglotSymposium/textual-game-hs
Main.hs
Haskell
mit
107
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} import qualified Data.ByteString as BS import Control.Applicative ((<$>)) import Data.Proxy import Manifest.Manifest import Manifest.PureManifest import Manifest.PostgreSQL data User = User BS.ByteString deriving (Show) type Email = BS.ByteString data WithEmail a = WithEmail a Email deriving (Show) email :: WithEmail a -> Email email (WithEmail _ x) = x instance ManifestKey User where manifestibleKeyDump (User b) = b manifestibleKeyPull = Just . User instance Manifestible (WithEmail a) where type ManifestibleKey (WithEmail a) = a type ManifestibleValue (WithEmail a) = Email manifestibleKey (WithEmail x _) = x manifestibleValue (WithEmail _ x) = x manifestibleFactorization = WithEmail ada = User "ada" richard = User "richard" adaEmail = WithEmail ada "ada@clare.com" richardEmail = WithEmail richard "richard@carstone.com" -- If we wish to use a PureManifest, all we have to do is uncomment this, -- and remove the conflicting definitions below! --type MyEmailManifest = PureManifest --myEmailManifest :: MyEmailManifest a --myEmailManifest = emptyPM type MyEmailManifest = PostgreSQL myEmailManifest = postgresql info "emails" where info = ConnectInfo "localhost" (fromIntegral 5432) "" "" "alex" main = do let emailManifest = myEmailManifest let writeem = do { mput adaEmail (Proxy :: Proxy MyEmailManifest); mput richardEmail (Proxy :: Proxy MyEmailManifest); } let readem = do { adasEmail <- mget ada (Proxy :: Proxy (MyEmailManifest (WithEmail User))); richardsEmail <- mget richard (Proxy :: Proxy (MyEmailManifest (WithEmail User))); return (email <$> adasEmail, email <$> richardsEmail) } (writeOutcome, emailManifest) <- manifest emailManifest writeem (readOutcome1, emailManifest) <- manifest emailManifest readem let deleteem = do { richardsEmail <- mdel richard (Proxy :: Proxy (MyEmailManifest (WithEmail User))); return richardsEmail } (deleteOutcome, emailManifest) <- manifest emailManifest deleteem (readOutcome2, emailManifest) <- manifest emailManifest readem printOutcome writeOutcome printOutcome readOutcome1 printOutcome deleteOutcome printOutcome readOutcome2 where printOutcome x = case x of Right y -> putStr "OK! " >> print y Left y -> case y of GeneralFailure f -> putStr "Not OK! " >> print f PeculiarFailure f -> putStr "Not OK! " >> print f
avieth/Manifest-PostgreSQL
examples/User.hs
Haskell
mit
2,579
{-# LANGUAGE ExistentialQuantification, MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings, FlexibleInstances #-} {-# OPTIONS_HADDOCK prune, not-home #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | Provides framework to interact with REST api gateways. Implementations specific to the -- Discord API are provided in Network.Discord.Rest.Channel, Network.Discord.Rest.Guild, -- and Network.Discord.Rest.User. module Network.Discord.Rest ( module Network.Discord.Rest , module Network.Discord.Rest.Prelude , module Network.Discord.Rest.Channel , module Network.Discord.Rest.Guild , module Network.Discord.Rest.User ) where import Control.Monad (void) import Data.Maybe (fromJust) import Control.Exception (throwIO) import qualified Network.HTTP.Req as R import Control.Monad.Morph (lift) import Data.Aeson.Types import Data.Hashable import Network.URL import Pipes.Core import Network.Discord.Types as Dc import Network.Discord.Rest.Channel import Network.Discord.Rest.Guild import Network.Discord.Rest.Prelude import Network.Discord.Rest.User import Network.Discord.Rest.HTTP (baseUrl) -- | Perform an API request. fetch :: (DoFetch a, Hashable a) => a -> Pipes.Core.Proxy X () c' c DiscordM Fetched fetch req = restServer +>> (request $ Fetch req) -- | Perform an API request, ignoring the response fetch' :: (DoFetch a, Hashable a) => a -> Pipes.Core.Proxy X () c' c DiscordM () fetch' = void . fetch -- | Alternative method of interacting with the REST api withApi :: Pipes.Core.Client Fetchable Fetched DiscordM Fetched -> Effect DiscordM () withApi inner = void $ restServer +>> inner -- | Provides a pipe to perform REST actions restServer :: Fetchable -> Server Fetchable Fetched DiscordM Fetched restServer req = lift (doFetch req) >>= respond >>= restServer instance R.MonadHttp IO where handleHttpException = throwIO -- | Obtains a new gateway to connect to. getGateway :: IO URL getGateway = do r <- R.req R.GET (baseUrl R./: "gateway") R.NoReqBody R.jsonResponse mempty return . fromJust $ importURL =<< parseMaybe getURL (R.responseBody r) where getURL :: Value -> Parser String getURL = withObject "url" (.: "url")
jano017/Discord.hs
src/Network/Discord/Rest.hs
Haskell
mit
2,346
{-| Parse a list of flags supported in any of the front ends. Returns the flags in a data structure, along with any invalid flags. Deal with any files/include files in this stage. -} module CmdLine.Flag( CmdFlag(..), flagsHelp, flagsWebArgs, flagsWebQuery, flagsCmdLine ) where import General.Code import General.Glob --------------------------------------------------------------------- -- The flags data CmdFlag = Version -- ^ Version information | Web -- ^ Operate as a CGI process | Help -- ^ Help text | Test -- ^ Run the regression tests | Color Bool -- ^ Colors on the console | Start Int -- ^ First result to show | Count Int -- ^ Number of results to show | Convert FilePath -- ^ Convert a database | Output FilePath -- ^ Output file | Dump String -- ^ Dump a database to a file (optional section) | DataFile FilePath -- ^ Database location | Verbose -- ^ Display verbose information | Info -- ^ Display as much information as you can | Debug -- ^ Do debugging activities | Include FilePath -- ^ Include directory | TestFile FilePath -- ^ Run tests in a file | Rank FilePath -- ^ Generate rankings | Combine FilePath -- ^ Merge a set of databases | Mode String -- ^ Web modes deriving (Show,Eq {-! Enum !-} ) -- | In which circumstances are you allowed to pass this command data Permission = PWebArgs | PWebQuery | PCmdLine | PMultiple deriving (Show,Eq) data Argument = ArgNone CmdFlag | ArgBool (Bool -> CmdFlag) | ArgInt (Int -> CmdFlag) | ArgNat (Int -> CmdFlag) | ArgPos (Int -> CmdFlag) | ArgFileIn (FilePath -> CmdFlag) [String] | ArgFileOut (FilePath -> CmdFlag) | ArgDir (FilePath -> CmdFlag) | ArgStr (String -> CmdFlag) instance Show Argument where show (ArgNone _) = "" show (ArgInt _) = "INT" show (ArgNat _) = "NAT" show (ArgPos _) = "POS" show (ArgBool _) = "BOOL" show (ArgFileIn _ _) = "FILE" show (ArgFileOut _) = "FILE" show (ArgDir _) = "DIR" show (ArgStr _) = "STR" data FlagInfo = FlagInfo { argument :: Argument, names :: [String], permissions :: [Permission], description :: String } flagInfo = [f (ArgNone Version) ["version","ver"] [PCmdLine] "Print out version information" ,f (ArgNone Help) ["?","help","h"] [PCmdLine] "Show help message" ,f (ArgNone Web) ["w","web"] [PCmdLine] "Run as though it was a CGI script" ,f (ArgBool Color) ["c","color","col","colour"] [PCmdLine] "Show color output (default=false)" ,f (ArgPos Start) ["s","start"] [PCmdLine,PWebArgs] "First result to show (default=1)" ,f (ArgPos Count) ["n","count","length","len"] [PCmdLine,PWebArgs] "Number of results to show (default=all)" ,f (ArgNone Test) ["test"] [PCmdLine] "Run the regression tests" ,f (ArgFileIn Convert ["txt"]) ["convert"] [PCmdLine,PMultiple] "Convert a database" ,f (ArgFileOut Output) ["output"] [PCmdLine] "Output file for convert" ,f (ArgStr Dump) ["dump"] [PCmdLine] "Dump a database for debugging" ,f (ArgFileIn DataFile ["hoo"]) ["d","data"] [PCmdLine,PMultiple] "Database file" ,f (ArgNone Verbose) ["v","verbose"] [PCmdLine] "Display verbose information" ,f (ArgNone Info) ["info"] [PCmdLine] "Display full information on an entry" ,f (ArgNone Debug) ["debug"] [PCmdLine] "Debugging only" ,f (ArgDir Include) ["i","include"] [PCmdLine,PMultiple] "Include directories" ,f (ArgFileIn TestFile ["txt"]) ["testfile"] [PCmdLine,PMultiple] "Run tests from a file" ,f (ArgFileIn Rank ["txt"]) ["rank"] [PCmdLine,PMultiple] "Generate ranking scores" ,f (ArgFileIn Combine ["hoo"]) ["combine"] [PCmdLine,PMultiple] "Combine multiple databases" ,f (ArgStr Mode) ["mode"] [PCmdLine,PWebArgs] "Web mode" ] where f = FlagInfo cmdFlagBadArg flag typ "" = "Missing argument to flag " ++ flag ++ ", expected argument of type " ++ typ cmdFlagBadArg flag "" x = "Unexpected argument to flag " ++ flag ++ ", got \"" ++ x ++ "\"" cmdFlagBadArg flag typ x = "Bad argument to flag " ++ flag ++ ", expected argument of type " ++ typ ++ ", got \"" ++ x ++ "\"" cmdFlagPermission flag = "Flag not allowed when running in this mode, flag " ++ flag cmdFlagUnknown flag = "Unknown flag " ++ flag cmdFlagDuplicate flag = "The flag " ++ flag ++ " may only occur once, but occured multiple times" --------------------------------------------------------------------- -- Operations on Flags -- | flags that are passed in through web arguments, -- i.e. ?foo=bar&... flagsWebArgs :: [(String,String)] -> IO ([CmdFlag],[String]) flagsWebArgs = parseFlags PWebArgs -- | flags that are given in the web query string flagsWebQuery :: [(String,String)] -> IO ([CmdFlag],[String]) flagsWebQuery = parseFlags PWebQuery -- | flags that are given in a query on the command line flagsCmdLine :: [(String,String)] -> IO ([CmdFlag],[String]) flagsCmdLine = parseFlags PCmdLine flagsHelp :: String flagsHelp = unlines $ map f res where f (a,b,c) = " " ++ (if null a then " " else "--" ++ a ++ ",") ++ " --" ++ b ++ replicate (maxLong - length b) ' ' ++ " " ++ c maxLong = maximum $ map (length . snd3) res res = [ (shortOpt (names i), longOpt (names i) ++ typ (argument i), description i) | i <- flagInfo, PCmdLine `elem` permissions i] shortOpt ([x]:_) = [x] shortOpt _ = "" longOpt ([_]:x:_) = x longOpt (x:_) = x typ x = ['='|s/=""] ++ s where s = show x --------------------------------------------------------------------- -- Parsing Flags -- TODO: check no flag is specified twice -- TODO: Fix a bug, try /merge=t1;t2 and you get [t1,t1,t2,t2] parseFlags :: Permission -> [(String,String)] -> IO ([CmdFlag],[String]) parseFlags perm xs = do let args = concatMap (parseFlag perm) xs inc = [x | Right (_,_,_,Include x) <- args] incs <- mapM globDir $ ["."|null inc] ++ inc (a,b) <- mapAndUnzipM (f incs) args return ([Include "."|null inc] ++ concat a, concat b) where f inc (Right (_,val,FlagInfo{argument=ArgFileIn gen exts},_)) = do let vals = parseFile val files <- concatMapM (globFile inc exts) vals return (map gen files, []) f inc (Left v) = return ([],[v]) f inc (Right (_,_,_,v)) = return ([v],[]) -- does all validity checks apart from checking for duplicate flags parseFlag :: Permission -> (String, String) -> [Either String (String,String,FlagInfo,CmdFlag)] parseFlag perm (key,val) | isNothing m = [Left $ cmdFlagUnknown key] | perm `notElem` permissions flg = [Left $ cmdFlagPermission key] | null arg = [Left $ cmdFlagBadArg key (show $ argument flg) val] | otherwise = [Right (key,val,flg,a) | a <- arg] where key2 = lower key m@ ~(Just flg) = listToMaybe [i | i <- flagInfo, key2 `elem` names i] arg = parseArg (argument flg) val parseArg :: Argument -> String -> [CmdFlag] parseArg (ArgNone v) xs = [v | null xs] parseArg (ArgStr v) xs = [v xs] parseArg (ArgBool v) xs = map v $ parseBool xs parseArg (ArgNat v) xs = map v $ parseNat xs parseArg (ArgInt v) xs = map v $ parseInt xs parseArg (ArgPos v) xs = map v $ parsePos xs parseArg (ArgFileIn v _) xs = map v $ parseFile xs parseArg (ArgFileOut v) xs = map v $ parseFile xs parseArg (ArgDir v) xs = map v $ parseFile xs parseNat, parsePos, parseInt :: String -> [Int] parseNat = filter (>= 0) . parseInt parsePos = filter (> 0) . parseInt parseInt x = [a | (a,"") <- reads x] parseFile :: String -> [String] parseFile = splitSearchPath parseBool :: String -> [Bool] parseBool v | v2 `elem` ["","on","yes","1","true","meep"] = [True] | v2 `elem` ["off","no","0","false","moop"] = [False] | otherwise = [] where v2 = lower v -------------------------------------------------------- -- DERIVES GENERATED CODE -- DO NOT MODIFY BELOW THIS LINE -- CHECKSUM: 1401092643 instance Enum CmdFlag where toEnum 0 = Version{} toEnum 1 = Web{} toEnum 2 = Help{} toEnum 3 = Test{} toEnum 4 = Color{} toEnum 5 = Start{} toEnum 6 = Count{} toEnum 7 = Convert{} toEnum 8 = Output{} toEnum 9 = Dump{} toEnum 10 = DataFile{} toEnum 11 = Verbose{} toEnum 12 = Info{} toEnum 13 = Debug{} toEnum 14 = Include{} toEnum 15 = TestFile{} toEnum 16 = Rank{} toEnum 17 = Combine{} toEnum n = error ((++) "toEnum " ((++) (show n) ", not defined for CmdFlag")) fromEnum (Version {}) = 0 fromEnum (Web {}) = 1 fromEnum (Help {}) = 2 fromEnum (Test {}) = 3 fromEnum (Color {}) = 4 fromEnum (Start {}) = 5 fromEnum (Count {}) = 6 fromEnum (Convert {}) = 7 fromEnum (Output {}) = 8 fromEnum (Dump {}) = 9 fromEnum (DataFile {}) = 10 fromEnum (Verbose {}) = 11 fromEnum (Info {}) = 12 fromEnum (Debug {}) = 13 fromEnum (Include {}) = 14 fromEnum (TestFile {}) = 15 fromEnum (Rank {}) = 16 fromEnum (Combine {}) = 17
Pnom/haskell-ast-pretty
Test/examples/RealHoogle.hs
Haskell
mit
9,798
import Graphics.UI.SDL import Graphics.Rendering.OpenGL import Data.List import Data.Maybe import Data.Word import Control.Monad import Control.Monad.State import Formulae type ARTFVect = (GLfloat, GLfloat, GLfloat) data Camera = Camera { pos :: ARTFVect } data ARTFFlags = Alive | Dead deriving (Eq) data ARTF = ARTF { flags :: ARTFFlags, cam :: Camera, formula :: Int -> GLfloat -> GLfloat -> Formula, gen :: Int, -- change this to (Data.)Word lineLen :: GLfloat, angle :: GLfloat, userinput :: String } initialARTF :: ARTF initialARTF = ARTF Alive (Camera (0.0, 0.0, 0.0)) plant 6 0.1 6 "" handleUserInput :: ARTF -> ARTF handleUserInput artf = artf incGenerations :: Int -> ARTF -> ARTF incGenerations nN artf@(ARTF flags cam f n l a ui) | newN > 0 = ARTF flags cam f newN l a ui | otherwise = artf where newN = nN + n incAngle :: GLfloat -> ARTF -> ARTF incAngle nA artf@(ARTF flags cam f n l a ui) = ARTF flags cam f n l (a+nA) ui artfAlive :: ARTF -> Bool artfAlive artf = (flags artf) == Alive main :: IO () main = do Graphics.UI.SDL.init [InitVideo] setVideoMode 640 480 32 [OpenGL, HWSurface] viewport $= (Position 0 0, Size 640 480) clearColor $= (Color4 0 1.0 0 0) --initialDisplayMode $= [DoubleBuffered, RGBMode, WithDepthBuffer] lighting $= Enabled depthFunc $= Just Less scr <- getVideoSurface gameLoop initialARTF scr quit gameLoop :: ARTF -> s -> IO () gameLoop artf@(ARTF flags (Camera (cx, cy, cz)) f n l a ui) w = do clear [ColorBuffer, DepthBuffer] loadIdentity translate $ Vector3 cx cy cz --rotate (90 :: GLfloat) $ Vector3 0 0 1 mapM_ (renderPrimitive (vertType vert) . mapM_ vertex) (vertices vert) --mapM_ (renderPrimitive LineStrip . mapM_ vertex) (sierpinski 8 lineLen) translate $ Vector3 (-cx) (-cy) (-cz) glSwapBuffers events <- getEvents let newartf = handleEvents artf events if artfAlive newartf then gameLoop newartf w else return () where vert = f n l a -- Get all Events so they can be worked with in a pure context getEvents :: IO [Event] getEvents = do ev <- pollEvent nextEvents ev where nextEvents :: Event -> IO [Event] nextEvents NoEvent = return [] nextEvents x = do ev <- pollEvent xs <- nextEvents ev return (x:xs) -- a b are ignored handleKeyDown :: ARTF -> SDLKey -> a -> b -> ARTF handleKeyDown artf@(ARTF flags oldcam@(Camera (cx, cy, cz)) f n l a ui) key sym mod | key == SDLK_q = (ARTF Dead oldcam f n l a ui) | key == SDLK_d = (ARTF flags (Camera ((cx-0.1), cy, cz)) f n l a ui) | key == SDLK_a = (ARTF flags (Camera ((cx+0.1), cy, cz)) f n l a ui) | key == SDLK_w = (ARTF flags (Camera (cx, (cy-0.1), cz)) f n l a ui) | key == SDLK_s = (ARTF flags (Camera (cx, (cy+0.1), cz)) f n l a ui) | key == SDLK_v = (ARTF flags oldcam f n (l/2) a ui) | key == SDLK_b = (ARTF flags oldcam f n (l*2) a ui) | key == SDLK_y = (ARTF flags oldcam sierpinski n l a ui) | key == SDLK_t = (ARTF flags oldcam cantor n l a ui) | key == SDLK_f = (ARTF flags oldcam koch n l a ui) | key == SDLK_e = (ARTF flags oldcam dragon n l a ui) | key == SDLK_g = (ARTF flags oldcam plant 6 l 25 ui) | key == SDLK_p = incGenerations 1 artf | key == SDLK_o = incGenerations (-1) artf | key == SDLK_r = initialARTF | key == SDLK_l = incAngle 5.0 artf | key == SDLK_k = incAngle (-5.0) artf | otherwise = (ARTF flags oldcam f n l a ui) handleEvents :: ARTF -> [Event] -> ARTF handleEvents artf [] = artf handleEvents oldartf@(ARTF flags cam f n l a ui) (x:xs) = do case x of (KeyDown (Keysym key a b)) -> handleKeyDown oldartf key a b Quit -> (ARTF Dead cam f n l a ui) _ -> (ARTF flags cam f n l a ui)
esjee/hlsystem-artf
Main.hs
Haskell
mit
3,626
module Core.LambdaLift.DeBruijn ( deBruijn ) where import Common import Core.AST import Core.AnnotAST import Core.FreeVars import Core.Prelude import qualified Data.Map as M import qualified Data.Set as S deBruijn :: Program Name -> AnnotProgram Int (Annot Int Name) deBruijn = ProgramF . map deBruijnSC . getProgramF . freeVars where deBruijnSC (SupercombF name [] body) = SupercombF name [] body' where body' = deBruijnExpr 0 M.empty body deBruijnExpr :: Int -> M.Map Name Int -> AnnotExpr (S.Set Name) Name -> AnnotExpr Int (Annot Int Name) deBruijnExpr k env (Annot (fv, e)) = Annot $ case e of EVarF v -> (M.findWithDefault 0 v env, EVarF v) ENumF n -> (0, ENumF n) EConstrF tag arity -> (0, EConstrF tag arity) EApF e1 e2 -> (,) k' $ if isArith (EAp (removeAnnot e1) (removeAnnot e2)) then EApF (Annot (k', unAnnot e1')) e2' else EApF e1' e2' where e1' = deBruijnExpr k env e1 e2' = deBruijnExpr k env e2 k' = max (getAnnot e1') (getAnnot e2') ELetF rec defs body -> (getAnnot body', ELetF rec defs' body') where xs' = map (Annot . (,) k') xs exps' = map (deBruijnExpr k (if rec then env' else env)) exps defs' = zip xs' exps' body' = deBruijnExpr k env' body env' = extend env (zip xs (repeat k')) env'' = if rec then extend env (zip xs (repeat 0)) else env k' = deBruijnFreeVars env'' (S.unions (map getAnnot exps)) (xs, exps) = unzip defs ECaseF e alts -> (k'', ECaseF e' alts') where e' = deBruijnExpr k env e alts' = map (deBruijnAlter k k' env) alts k' = getAnnot e' k'' = foldr max k' [getAnnot body | AlterF _ _ body <- alts'] EAbsF args body -> (deBruijnFreeVars env fv, EAbsF args' body') where args' = map (Annot . (,) k') args body' = deBruijnExpr k' env' body env' = extend env (zip args (repeat k')) k' = k + 1 deBruijnAlter :: Int -> Int -> M.Map Name Int -> AnnotAlter (S.Set Name) Name -> AnnotAlter Int (Annot Int Name) deBruijnAlter k k' env (AlterF tag xs body) = AlterF tag xs' body' where xs' = map (Annot . (,) k') xs body' = deBruijnExpr k env' body env' = extend env (zip xs (repeat k')) deBruijnFreeVars :: M.Map Name Int -> S.Set Name -> Int deBruijnFreeVars env fv = foldr max 0 xs where xs = [M.findWithDefault 0 v env | v <- S.toList fv]
meimisaki/Rin
src/Core/LambdaLift/DeBruijn.hs
Haskell
mit
2,400