code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-| Directory tree database. Directory database of B+ tree: huge DBM with order. * Persistence: /persistent/ * Algorithm: /B+ tree/ * Complexity: /O(log n)/ * Sequence: /custom order/ * Lock unit: /page (rwlock)/ -} module Database.KyotoCabinet.DB.Forest ( Forest , ForestOptions (..) , defaultForestOptions , Compressor (..) , Options (..) , Comparator (..) , makeForest , openForest ) where import Data.Int (Int64, Int8) import Data.Maybe (maybeToList) import Prelude hiding (log) import Database.KyotoCabinet.Internal import Database.KyotoCabinet.Operations newtype Forest = Forest DB instance WithDB Forest where getDB (Forest db) = db data ForestOptions = ForestOptions { alignmentPow :: Maybe Int8 , freePoolPow :: Maybe Int8 , options :: [Options] , buckets :: Maybe Int64 , maxSize :: Maybe Int64 , defragInterval :: Maybe Int64 , compressor :: Maybe Compressor , cipherKey :: Maybe String , pageSize :: Maybe Int64 , comparator :: Maybe Comparator , pageCacheSize :: Maybe Int64 } deriving (Show, Read, Eq, Ord) defaultForestOptions :: ForestOptions defaultForestOptions = defaultForestOptions { alignmentPow = Nothing , freePoolPow = Nothing , options = [] , buckets = Nothing , maxSize = Nothing , defragInterval = Nothing , compressor = Nothing , cipherKey = Nothing , pageSize = Nothing , comparator = Nothing , pageCacheSize = Nothing } toTuningOptions :: ForestOptions -> [TuningOption] toTuningOptions ForestOptions { alignmentPow = ap , freePoolPow = fp , options = os , buckets = bs , maxSize = ms , defragInterval = di , compressor = cmp , cipherKey = key , pageSize = ps , comparator = cmprtr , pageCacheSize = pcs } = mtl AlignmentPow ap ++ mtl FreePoolPow fp ++ map Options os ++ mtl Buckets bs ++ mtl MaxSize ms ++ mtl DefragInterval di ++ mtl Compressor cmp ++ mtl CipherKey key ++ mtl PageSize ps ++ mtl Comparator cmprtr ++ mtl PageCacheSize pcs where mtl f = maybeToList . fmap f className :: String className = "kcf" makeForest :: FilePath -> LoggingOptions -> ForestOptions -> Mode -> IO Forest makeForest fp log opts mode = makePersistent Forest toTuningOptions className fp log opts mode openForest :: FilePath -> LoggingOptions -> Mode -> IO Forest openForest fp log mode = openPersistent Forest className fp log mode
bitonic/kyotocabinet
Database/KyotoCabinet/DB/Forest.hs
bsd-3-clause
3,570
0
15
1,679
639
362
277
64
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module CANOpen.Tower.NMT where import Ivory.Language import Ivory.Stdlib import Ivory.Tower import Ivory.Tower.HAL.Bus.CAN import Ivory.Tower.HAL.Bus.Interface import Ivory.Tower.HAL.Bus.CAN.Fragment import Ivory.Serialize.LittleEndian import CANOpen.Tower.Attr import CANOpen.Tower.Interface.Base.Dict import CANOpen.Tower.NMT.Types import CANOpen.Tower.Utils data NMTCMD = Start | Stop | PreOperation | ResetNode | ResetComm | HeartBeat nmtCmd :: NMTCMD -> Uint8 nmtCmd Start = 0x01 nmtCmd Stop = 0x02 nmtCmd PreOperation = 0x80 nmtCmd ResetNode = 0x81 nmtCmd ResetComm = 0x82 heartBeatOffset :: Uint16 heartBeatOffset = 0x700 -- receives NMT (Network Management) messages from canopenTower -- -- takes (required) node_id -- outputs NMTState iff state changes -- -- NMT message format -- ID0 byte 1 node ID -- byte 0 command -- -- example NMT messages: -- -- # start node 01 -- cansend can0 000#0101 -- -- # reset node 01 -- cansend can0 000#8101 nmtTower :: ChanOutput ('Struct "can_message") -> AbortableTransmit ('Struct "can_message") ('Stored IBool) -> ChanOutput ('Stored Uint8) -> BaseAttrs Attr -> Tower e ( ChanInput ('Stored NMTState) , ChanOutput ('Stored NMTState)) nmtTower res req nid_update attrs = do (nmt_notify_in, nmt_notify_out) <- channel (nmt_set_in, nmt_set_out) <- channel p <- period (Milliseconds 1) monitor "nmt_controller" $ do received <- stateInit "nmt_received" (ival (0 :: Uint32)) lastmsg <- state "nmt_lastmsg" lastcmd <- state "nmt_lastcmd" nmtState <- stateInit "nmt_state" (ival nmtInitialising) previous_nmtState <- stateInit "nmt_state_prev" (ival nmtInitialising) nodeId <- stateInit "heartbeat_node_id" (ival (0 :: Uint8)) heartbeat_cnt <- stateInit "heartbeat_cnt" (ival (0 :: Uint16)) heartbeat_enabled <- state "heartbeat_enabled" heartbeat_time <- state "heartbeat_time" attrHandler (producerHeartbeatTime attrs) $ do callbackV $ \time -> do store heartbeat_time time when (time >? 0) $ store heartbeat_enabled true handler systemInit "nmtinit" $ do nmtE <- emitter nmt_notify_in 1 callback $ const $ emit nmtE (constRef nmtState) handler res "nmtcanmsg" $ do nmtE <- emitter nmt_notify_in 1 reqE <- emitter (abortableTransmit req) 1 callback $ \msg -> do received += 1 refCopy lastmsg msg nid <- deref nodeId assert $ nid /=? 0 mlen <- deref (msg ~> can_message_len) assert $ mlen ==? 2 cmd <- deref (msg ~> can_message_buf ! 0) targetId <- deref (msg ~> can_message_buf ! 1) store lastcmd cmd let isCmd x = (cmd ==? nmtCmd x) when (targetId ==? 0 .|| targetId ==? nid) $ do cond_ [ isCmd Start ==> do store nmtState nmtOperational , isCmd Stop ==> do store nmtState nmtStopped , isCmd PreOperation ==> do store nmtState nmtPreOperational -- emit bootmsg when entering pre-Operational empty <- local $ ival 0 bootmsg <- canMsgUint8 (heartBeatOffset + safeCast nid) false $ constRef empty emit reqE bootmsg store heartbeat_enabled true , isCmd ResetNode ==> do store nmtState nmtResetting store heartbeat_enabled false , isCmd ResetComm ==> do store nmtState nmtResettingComm store heartbeat_enabled false ] cstate <- deref nmtState prevstate <- deref previous_nmtState when (cstate /=? prevstate) $ do store previous_nmtState cstate emit nmtE $ constRef nmtState handler nid_update "nmt_node_id" $ do callback $ refCopy nodeId handler nmt_set_out "nmt_set" $ do nmtE <- emitter nmt_notify_in 1 callback $ \x -> refCopy nmtState x >> emit nmtE x handler p "per_heartbeat" $ do reqe <- emitter (abortableTransmit req) 1 callback $ const $ do cnt <- deref heartbeat_cnt ena <- deref heartbeat_enabled tim <- deref heartbeat_time heartbeat_cnt += 1 when (ena .&& tim /=? 0) $ do when (cnt >=? tim) $ do nid <- deref nodeId state <- deref nmtState heartbeat_state <- local $ ival (0 :: Uint8) cond_ [ state ==? nmtStopped ==> store heartbeat_state 4 , state ==? nmtOperational ==> store heartbeat_state 5 , state ==? nmtPreOperational ==> store heartbeat_state 127 ] bootmsg <- canMsgUint8 (heartBeatOffset + safeCast nid) false $ constRef heartbeat_state emit reqe bootmsg store heartbeat_cnt 0 return (nmt_set_in, nmt_notify_out)
distrap/ivory-tower-canopen
src/CANOpen/Tower/NMT.hs
bsd-3-clause
5,043
0
30
1,472
1,382
660
722
119
1
{-# LANGUAGE FlexibleContexts #-} module Advent.Day6 where import qualified Data.Text as T import Text.Parsec as Parsec (many1 , char , newline , sepEndBy , try , string , ParseError , digit , choice , parse) import qualified Data.Vector as V import qualified Data.Vector.Mutable as VM import Control.Monad.ST (ST, runST) import Control.Monad.Reader (ReaderT, runReaderT, lift, ask) import Control.Monad (forM) data Action = TurnOn | TurnOff | Toggle deriving (Eq, Show) type Index = (Int, Int) type Start = Index type End = Index type Bounds = (Start, End) data Command = Command { _action :: Action, _bounds :: Bounds } deriving (Eq, Show) type LightGridM s a = V.Vector (VM.MVector s a) type LightGrid a = V.Vector (V.Vector a) type MyMon s a = ReaderT (LightGridM s a) (ST s) parse :: T.Text -> Either ParseError [Command] parse = Parsec.parse commandP "" where commandP = sepEndBy command newline int = read <$> many1 digit index = (,) <$> int <*> (char ',' *> int) coords = (,) <$> index <*> (string " through " *> index) on = try $ TurnOn <$ string "turn on " off = try $ TurnOff <$ string "turn off " tog = try $ Toggle <$ string "toggle " command = Command <$> choice [on, tog, off] <*> coords initialState :: a -> ST s (LightGridM s a) initialState initialValue = sequence $ V.replicate 1000 inner where inner = VM.replicate 1000 initialValue elvish :: Action -> Int -> Int elvish TurnOn = (+ 1) elvish TurnOff = max 0 . subtract 1 elvish Toggle = (+ 2) english :: Action -> Bool -> Bool english TurnOn = const True english TurnOff = const False english Toggle = not reifyBounds :: Bounds -> [Index] reifyBounds ((x1,y1), (x2,y2)) = [(x,y) | x <- [x1 .. x2], y <- [y1 .. y2]] -- | I have no real idea how performant this is. I started going down the rabbit -- hole of mutable vectors inside a monad stack and this is where I ended up. step :: (Action -> a -> a) -> Command -> MyMon s a () step language c = mapM_ update indices where update (x,y) = do grid <- ask let ys = (V.!) grid y -- No idea why I can't reference modify, it's there on Hackage :S -- so have to do it the verbose way -- lift $ Data.Vector.Mutable.modify ys f x v <- lift $ VM.read ys x lift $ VM.write ys x (setter v) setter = language $ _action c indices = reifyBounds $ _bounds c runSteps :: (Action -> a -> a) -> a -> [Command] -> LightGrid a runSteps language initialValue t = runST $ do s <- initialState initialValue _ <- runReaderT (Control.Monad.forM t $ step language) s freeze s freeze :: LightGridM s a -> ST s (LightGrid a) freeze = sequence . fmap V.freeze numberLit :: LightGrid Bool -> Int numberLit = V.sum . fmap rows where rows :: V.Vector Bool -> Int rows = length . V.filter id totalBrightness :: LightGrid Int -> Int totalBrightness = V.sum . fmap V.sum
screamish/adventofhaskellcode
src/Advent/Day6.hs
bsd-3-clause
3,203
0
13
964
1,060
576
484
78
1
module LetLang.ParserSuite ( tests ) where import LetLang.Data import LetLang.Parser import Test.HUnit.Base import Text.Megaparsec import Text.Megaparsec.String tests :: Test tests = TestList [ TestLabel "Test const expression" testConstExpr , TestLabel "Test binary-operator expression" testBinOpExpr , TestLabel "Test unary-operator expression" testUnaryOpExpr , TestLabel "Test condition expression" testCondExpr , TestLabel "Test var expression" testVarExpr , TestLabel "Test let expression" testLetExpr , TestLabel "Test expression" testExpression , TestLabel "Test parse program" testParseProgram ] constNum = ConstExpr . ExprNum constBool = ConstExpr . ExprBool parserEqCase :: (Eq a, Show a) => Parser a -> String -> a -> String -> Test parserEqCase parser msg expect input = TestCase $ assertEqual msg (Right expect) runP where runP = runParser parser "Test equal case" input parserFailCase :: (Eq a, Show a) => Parser a -> String -> String -> Test parserFailCase parser msg input = TestCase $ assertBool msg (isLeft runP) where isLeft (Left _) = True isLeft (Right _) = False runP = runParser parser "Test fail case" input testEq :: String -> Expression -> String -> Test testEq = parserEqCase expression testFail :: String -> String -> Test testFail = parserFailCase expression testConstExpr :: Test testConstExpr = TestList [ testEq "Parse single number" (constNum 5) "5" , testEq "Parse multi-numbers" (constNum 123) "123" , testFail "Parse negative numbers should fail" "-3" ] testBinOpExpr :: Test testBinOpExpr = TestList [ testEq "Parse '-' expression (no space)" (BinOpExpr Sub (constNum 3) (constNum 4)) "-(3,4)" , testEq "Parse '*' expression (with spaces)" (BinOpExpr Mul (constNum 10) (constNum 24)) "* ( 10 , 24 )" , testEq "Parse binary num-to-bool expression" (BinOpExpr Gt (constNum 1) (constNum 2)) "greater?(1, 2)" , testEq "Parse cons expression" (BinOpExpr Cons (constNum 3) EmptyListExpr) "cons (3, emptyList)" ] testUnaryOpExpr :: Test testUnaryOpExpr = TestList [ testEq "Parse isZero expression (no space)" (UnaryOpExpr IsZero (constNum 1)) "zero?(1)" , testEq "Parse isZero expression (with space)" (UnaryOpExpr IsZero (constNum 3)) "zero? ( 3 )" , testEq "Parse minus expression" (UnaryOpExpr Minus (constNum 1)) "minus(1)" , testEq "Parse car expression" (UnaryOpExpr Car EmptyListExpr) "car (emptyList)" ] testCondExpr :: Test testCondExpr = TestList [ testEq "Parse if expression" (CondExpr [ (UnaryOpExpr IsZero (constNum 3), constNum 4) , (constBool True, constNum 5) ]) "if zero?(3) then 4 else 5" , testEq "Parse cond expression" (CondExpr [ (UnaryOpExpr IsZero (constNum 3), constNum 4) , (BinOpExpr Gt (constNum 3) (constNum 5), constNum 4) , (UnaryOpExpr IsZero (constNum 0), constNum 4) ]) $ unlines [ "cond zero?(3) ==> 4\n" , " greater?(3, 5) ==> 4\n" , " zero?(0) ==> 4\n" , "end" ] ] testVarExpr :: Test testVarExpr = TestList [ testEq "Parse var expression" (VarExpr "foo") "foo" , testFail "Parse reserved word should fail" "then" ] testLetExpr :: Test testLetExpr = TestList [ testEq "Parse let expression with 0 binding" (LetExpr [] (VarExpr "bar")) "let in bar" , testEq "Parse let expression with 1 binding" (LetExpr [("bar", constNum 1)] (VarExpr "bar")) "let bar = 1 in bar" , testEq "Parse let expression with multi bindings" (LetExpr [("x", constNum 1), ("y", constNum 2), ("z", constNum 3)] (VarExpr "bar")) "let x = 1 y = 2 z = 3 in bar" , testEq "Parse let* expression with 1 binding" (LetStarExpr [("x", constNum 1)] (VarExpr "bar")) "let* x = 1 in bar" , testEq "Parse nested let and let*" (LetExpr [("x", constNum 30)] (LetStarExpr [ ("x", BinOpExpr Sub (VarExpr "x") (constNum 1)) , ("y", BinOpExpr Sub (VarExpr "x") (constNum 2)) ] (BinOpExpr Sub (VarExpr "x") (VarExpr "y")))) "let x = 30 in let* x = -(x,1) y = -(x,2) in -(x,y)" ] testExpression :: Test testExpression = TestList [ testEq "Parse complex expression" (LetExpr [("bar", constNum 1)] (CondExpr [ (UnaryOpExpr IsZero (VarExpr "bar"), constNum 3) , (constBool True, VarExpr "zero") ])) "let bar = 1 in if zero? (bar) then 3 else zero" , testEq "Parse list expression" (UnaryOpExpr Car (LetExpr [("foo", constNum 3)] (BinOpExpr Cons (constNum 5) EmptyListExpr))) "car(let foo = 3 in cons(5, emptyList))" ] testParseProgram :: Test testParseProgram = TestList [ testEq "Parse program (with spaces)" (Prog (LetExpr [("x", constNum 3)] (VarExpr "x"))) "let x = 3 in x" ] where testEq msg expect prog = TestCase $ assertEqual msg (Right expect) (parseProgram prog)
li-zhirui/EoplLangs
test/LetLang/ParserSuite.hs
bsd-3-clause
5,455
0
16
1,656
1,392
723
669
129
2
module Wikirick.JSONConnection where import Control.Exception hiding (Handler) import Data.Aeson import Data.Typeable import Snap data JSONParseError = JSONParseError String deriving (Eq, Show, Typeable) instance Exception JSONParseError data JSONConnection = JSONConnection { _parseJSON :: (MonadSnap m, FromJSON a) => m a , _responseJSON :: (MonadSnap m, ToJSON a) => a -> m () } parseJSON :: (MonadState JSONConnection m, MonadSnap m, FromJSON a) => m a parseJSON = get >>= _parseJSON responseJSON :: (MonadState JSONConnection m, MonadSnap m, ToJSON a) => a -> m () responseJSON v = get >>= \self -> _responseJSON self v
keitax/wikirick
src/Wikirick/JSONConnection.hs
bsd-3-clause
638
0
12
106
223
120
103
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RecordWildCards #-} module Juno.Consensus.Handle.AppendEntriesResponse (handle ,handleAlotOfAers ,updateCommitProofMap) where import Control.Lens hiding (Index) import Control.Parallel.Strategies import Control.Monad.Reader import Control.Monad.State (get) import Control.Monad.Writer.Strict import Data.Maybe import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Set (Set) import qualified Data.Set as Set import Juno.Consensus.Commit (doCommit) import Juno.Consensus.Handle.Types import Juno.Runtime.Timer (resetElectionTimerLeader) import Juno.Util.Util (debug, updateLNextIndex) import qualified Juno.Types as JT data AEResponseEnv = AEResponseEnv { -- Old Constructors _nodeRole :: Role , _term :: Term , _commitProof :: Map NodeID AppendEntriesResponse } makeLenses ''AEResponseEnv data AEResponseOut = AEResponseOut { _stateMergeCommitProof :: Map NodeID AppendEntriesResponse , _leaderState :: LeaderState } data LeaderState = DoNothing | NotLeader | StatelessSendAE { _sendAENodeID :: NodeID } | Unconvinced -- sends AE after { _sendAENodeID :: NodeID , _deleteConvinced :: NodeID } | ConvincedAndUnsuccessful -- sends AE after { _sendAENodeID :: NodeID , _setLaggingLogIndex :: LogIndex } | ConvincedAndSuccessful -- does not send AE after { _incrementNextIndexNode :: NodeID , _incrementNextIndexLogIndex :: LogIndex , _insertConvinced :: NodeID} data Convinced = Convinced | NotConvinced data AESuccess = Success | Failure data RequestTermStatus = OldRequestTerm | CurrentRequestTerm | NewerRequestTerm handleAEResponse :: (MonadWriter [String] m, MonadReader AEResponseEnv m) => AppendEntriesResponse -> m AEResponseOut handleAEResponse aer@AppendEntriesResponse{..} = do --tell ["got an appendEntriesResponse RPC"] mcp <- updateCommitProofMap aer <$> view commitProof role' <- view nodeRole currentTerm' <- view term if role' == Leader then return $ case (isConvinced, isSuccessful, whereIsTheRequest currentTerm') of (NotConvinced, _, OldRequestTerm) -> AEResponseOut mcp $ Unconvinced _aerNodeId _aerNodeId (NotConvinced, _, CurrentRequestTerm) -> AEResponseOut mcp $ Unconvinced _aerNodeId _aerNodeId (Convinced, Failure, CurrentRequestTerm) -> AEResponseOut mcp $ ConvincedAndUnsuccessful _aerNodeId _aerIndex (Convinced, Success, CurrentRequestTerm) -> AEResponseOut mcp $ ConvincedAndSuccessful _aerNodeId _aerIndex _aerNodeId -- The next two case are underspecified currently and they should not occur as -- they imply that a follow is ahead of us but the current code sends an AER anyway (NotConvinced, _, _) -> AEResponseOut mcp $ StatelessSendAE _aerNodeId (_, Failure, _) -> AEResponseOut mcp $ StatelessSendAE _aerNodeId -- This is just a fall through case in the current code -- do nothing as the follower is convinced and successful but out of date? Shouldn't this trigger a replay AE? (Convinced, Success, OldRequestTerm) -> AEResponseOut mcp DoNothing -- We are a leader, in a term that hasn't happened yet? (_, _, NewerRequestTerm) -> AEResponseOut mcp DoNothing else return $ AEResponseOut mcp NotLeader where isConvinced = if _aerConvinced then Convinced else NotConvinced isSuccessful = if _aerSuccess then Success else Failure whereIsTheRequest ct | _aerTerm == ct = CurrentRequestTerm | _aerTerm < ct = OldRequestTerm | otherwise = NewerRequestTerm updateCommitProofMap :: AppendEntriesResponse -> Map NodeID AppendEntriesResponse -> Map NodeID AppendEntriesResponse updateCommitProofMap aerNew m = Map.alter go nid m where nid :: NodeID nid = _aerNodeId aerNew go = \case Nothing -> Just aerNew Just aerOld -> if _aerIndex aerNew > _aerIndex aerOld then Just aerNew else Just aerOld handle :: Monad m => AppendEntriesResponse -> JT.Raft m () handle ae = do s <- get let ape = AEResponseEnv (JT._nodeRole s) (JT._term s) (JT._commitProof s) (AEResponseOut{..}, l) <- runReaderT (runWriterT (handleAEResponse ae)) ape mapM_ debug l JT.commitProof .= _stateMergeCommitProof doCommit case _leaderState of NotLeader -> return () DoNothing -> resetElectionTimerLeader StatelessSendAE{..} -> resetElectionTimerLeader Unconvinced{..} -> do JT.lConvinced %= Set.delete _deleteConvinced resetElectionTimerLeader ConvincedAndSuccessful{..} -> do updateLNextIndex $ Map.insert _incrementNextIndexNode $ _incrementNextIndexLogIndex + 1 JT.lConvinced %= Set.insert _insertConvinced resetElectionTimerLeader ConvincedAndUnsuccessful{..} -> do updateLNextIndex $ Map.insert _sendAENodeID _setLaggingLogIndex resetElectionTimerLeader handleAlotOfAers :: Monad m => AlotOfAERs -> JT.Raft m () handleAlotOfAers (AlotOfAERs m) = do ks <- KeySet <$> view (JT.cfg . JT.publicKeys) <*> view (JT.cfg . JT.clientPublicKeys) let res = (processSetAer ks <$> Map.elems m) `using` parList rseq aers <- catMaybes <$> mapM (\(a,l) -> mapM_ debug l >> return a) res mapM_ handle aers processSetAer :: KeySet -> Set AppendEntriesResponse -> (Maybe AppendEntriesResponse, [String]) processSetAer ks s = go [] (Set.toDescList s) where go fails [] = (Nothing, fails) go fails (aer:rest) | _aerWasVerified aer = (Just aer, fails) | otherwise = case aerReVerify ks aer of Left f -> go (f:fails) rest Right () -> (Just $ aer {_aerWasVerified = True}, fails) -- | Verify if needed on `ReceivedMsg` provenance aerReVerify :: KeySet -> AppendEntriesResponse -> Either String () aerReVerify _ AppendEntriesResponse{ _aerWasVerified = True } = Right () aerReVerify _ AppendEntriesResponse{ _aerProvenance = NewMsg } = Right () aerReVerify ks AppendEntriesResponse{ _aerWasVerified = False, _aerProvenance = ReceivedMsg{..} } = verifySignedRPC ks $ SignedRPC _pDig _pOrig
haroldcarr/juno
src/Juno/Consensus/Handle/AppendEntriesResponse.hs
bsd-3-clause
6,373
0
16
1,381
1,584
836
748
127
11
-- | The Finite Module which exports Finite ---------------------------------------------------------------- module Finite (Finite(..), (*^), (*^-), sigfigs, orderOfMagnitude, showNatural, showFull, showScientific, roundToPrecision, fromIntegerWithPrecision, fromIntegerMatchingPrecision) where ---------------------------------------------------------------- import Extensions import Data.Ratio ---------------------------------------------------------------- -- FINITE DATA TYPE ---------------------------------------------------------------- -- | Finite Data Type `(b*10^e)` -- * ensure that the digits comprising b correspond to the significant -- figures of the number data Finite = Finite {base :: Integer, -- ^ the `b` in `b*10^e` expo :: Integer} -- ^ the `e` in `b*10^e` -- CONVENIENCE CONSTRUCTORS -- | Constructor for Finite Data Type (*^) :: Integer -> Integer -> Finite a*^m = Finite a m -- | Convenience constructor for Finite where the exponent is negative -- This is most commonly used for when writing literals (*^-) :: Integer -> Integer -> Finite a*^-m = a*^(-m) -- INFORMATION -- | Significant figures sigfigs :: Finite -> Integer sigfigs (Finite a _) = digits a -- | Order of Magnitude -- `n.nnnn*10^?` orderOfMagnitude :: Finite -> Integer orderOfMagnitude (Finite a m) = digits a - 1 + m ---------------------------------------------------------------- -- SHOWABILITY ---------------------------------------------------------------- instance Show Finite where show = showNatural -- | Show with component decomposition showNatural :: Finite -> String showNatural (Finite a m) = "[" ++ (show a) ++ "*10^" ++ (show m) ++ "]" -- | Show in full written form showFull :: Finite -> String showFull (Finite a m) | m < 0 = show intPart ++ "." ++ leadingZeroes ++ show floatPart -- has decimals | otherwise = show (a*10^m) -- no decimals where intPart = a `div` 10^(abs m) floatPart = a - a `div` 10^(abs m) * 10^(abs m) -- not including leading 0's leadingZeroes = replicate (fromIntegral $ abs m - digits floatPart) '0' -- | Show in Scientific form showScientific :: Finite -> String showScientific (Finite a m) = lead ++ decimals ++ "e" ++ show exponent where lead = [head (show a)] decimals = if tail (show a) /= "" then "." ++ tail (show a) else "" exponent = digits a + m - 1 ---------------------------------------------------------------- -- NUMBERNESS ---------------------------------------------------------------- instance Num Finite where am@(Finite a m) + bn@(Finite b n) = roundToPrecision (u *^ lowestExpo) (digits u - diff) -- FIXME: rounding error on associativity where lowestExpo = min m n highestExpo = max m n u = a*10^(m-lowestExpo) + b*10^(n-lowestExpo) -- the unrounded base of the added number diff = highestExpo - lowestExpo -- the difference in exponents (always positive) am - bn = am + (-bn) am@(Finite a m) * bn@(Finite b n) = roundToPrecision ((a * b) *^ (m + n)) lowestPrecision -- FIXME: rounding error on associativity where lowestPrecision = min (sigfigs am) (sigfigs bn) negate (Finite a m) = Finite (-a) m abs (Finite a m) = abs a *^ m signum (Finite a _) = Finite (signum a) 0 fromInteger a = (a*10^16)*^-16 -- ^ Assumes IEEE Double precision -- | takes an integer and sets it to a certain sigfigs precision -- (instead of the default IEEE Double precision) fromIntegerWithPrecision :: Integer -> Integer -> Finite fromIntegerWithPrecision a p | digits a > p = (a `div` 10^(digits a - p))*^(digits a - p) -- cut off end of int and give it that exponent | otherwise = (a*10^(p - digits a))*^-(p - digits a) -- append zeroes to end and give it that exponent -- | takes an integer and another finite and turns the integer into -- a finite of the same precision (sigfigs) fromIntegerMatchingPrecision :: Integer -> Finite -> Finite fromIntegerMatchingPrecision a n = fromIntegerWithPrecision a (sigfigs n) ---------------------------------------------------------------- -- EQUATABILITY & ORDERABILITY ---------------------------------------------------------------- -- | tests if two finites have the same value instance Eq Finite where (Finite a m) == (Finite b n) | n < m = a*10^(m-n) == b | otherwise = a == b*10^(n-m) -- | tests if two finites are exactly the same (Finite a m) === (Finite b n) = a == b && m == n instance Ord Finite where compare (Finite a m) (Finite b n) = compare (a*10^(m-lowestExpo)) (b*10^(n-lowestExpo)) where lowestExpo = min m n ---------------------------------------------------------------- -- FRACTIONALNESS ---------------------------------------------------------------- instance Fractional Finite where am@(Finite a m) / bn@(Finite b n) = roundToPrecision (((a*10^(db+1)) `div` b) *^ (m-n-db-1)) lowestPrecision where db = digits b lowestPrecision = min (sigfigs am) (sigfigs bn) fromRational r = (fromInteger (numerator r)) / (fromInteger (denominator r)) -- ^ Assumes IEEE Double precision -- | The representation as a ratio -- `a/10^-m` instance Real Finite where toRational (Finite a m) | m > 0 = a % 1 | otherwise = a % (10^(-m)) -- | The representation as an integer part and float part instance RealFrac Finite where properFraction am@(Finite a m) = (intPart, floatPart) where intPart = fromIntegral $ if m < 0 then a `div` 10^(abs m) else a * 10^m floatPart = am - fromIntegral intPart ---------------------------------------------------------------- -- EXTENDED ARITHMETIC ---------------------------------------------------------------- -- | Powers -- power :: Finite -> Finite -> Finite -- power (Finite a m) (Finite b n) = -- | Roots -- root :: Finite -> Finite -> Finite -- root (Finite a m) (Finite b n) = -- | Logarithms -- log :: Finite -> Finite -> Finite -- log (Finite a m) (Finite b n) = ---------------------------------------------------------------- -- OTHER FUNCTIONS ---------------------------------------------------------------- -- | Round to a certain precision -- supply with a number and the number of significant figures you want to round to roundToPrecision :: Finite -> Integer -> Finite roundToPrecision am@(Finite a m) p | d <= p = am -- if equal or worse precision than specified, return original | otherwise = (a `div` 10^(d-p) + r) *^ (d-p+m) -- d-p is how many digits to take off the end of a where d = digits a r = if a `div` 10^(d-p-1) `mod` 10 >= 5 then 1 else 0 -- add 1 to the number if the digit after the precision is >= 5 ---------------------------------------------------------------- -- MATHEMATICAL CONSTANTS ---------------------------------------------------------------- -- piAtPrecision :: Integer -> Finite -- eAtPrecision :: Integer -> Finite
Conflagrationator/HMath
src/Finite.hs
bsd-3-clause
6,948
0
14
1,363
1,798
973
825
76
2
-- for TokParsing, MonadicParsing {-# LANGUAGE ConstraintKinds #-} -- for impOrExpVar {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} -- ghc opts / calm down ghc-mod -- {-# OPTIONS_GHC -Wall #-} -- {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- {-# OPTIONS_GHC -fno-warn-orphans #-} -- {-# OPTIONS_GHC -fno-warn-missing-signatures #-} -- {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} -- {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} -- -- {-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-} -------------------------------------------------------------------- -- | -- Copyright : (c) Andreas Reuleaux 2015 -- License : BSD2 -- Maintainer: Andreas Reuleaux <[email protected]> -- Stability : experimental -- Portability: non-portable -- -- This module is part of Pire's parser. -------------------------------------------------------------------- module Pire.Parser.Nat where import Pire.Parser.Parser import Pire.Parser.Basic import Pire.Parser.Token import Pire.Syntax.Ex import Pire.Syntax.Ws import Pire.Syntax.Expr import qualified Data.Text as T (pack) -- import Control.Monad.State import Control.Monad.State.Strict -- originally desugaring of nats in the parser... -- commented out in PIRE!!! {- natenc :: TokParsing m => m Tm natenc = do n <- natural return $ encode n where encode 0 = DCon "Zero" [] natty encode n = DCon "Succ" [Arg RuntimeP (encode (n-1))] natty natty = Annot $ Just (TCon "Nat" []) -} -- commented out in PIRE!!! -- think about where to put the ws: -- as part of the DCName' or of the Annot' ? -- for now on the (top most) DCName' {- natenc_ :: (TokParsing m , DeltaParsing m ) => m Tm_ natenc_ = do n <- runUnspaced natural ws <- sliced whiteSpace -- return $ (\(DCon_ n' args (Annot_ m _)) -> -- DCon_ n' args (Annot_ m $ Ws $ txt ws )) $ encode n return $ (\(DCon_ (DCName_ n' _) args annot) -> DCon_ (DCName_ n' $ Ws $ txt ws) args annot) $ encode n where -- encode 0 = DCon_ "Zero" [] natty encode 0 = DCon_ (DCName_ "Zero" $ Ws "") [] natty -- encode n = DCon_ "Succ" [Arg_ Runtime (encode (n-1))] natty encode n = DCon_ (DCName_ "Succ" $ Ws "") [Arg_ RuntimeP (encode (n-1))] natty natty = Annot_ (Just (TCon_ (TCName_ "Nat" $ Ws "") [])) $ Ws "" -} -- ... but don't want implicit desugaring while parsing nat :: TokParsing m => m Ex nat = do n <- natural return $ Nat n nat_ :: (TokenParsing m , Monad m , DeltaParsing m , MonadState PiState m ) => m Ex nat_ = do n <- runUnspaced natural ws <- sliced whiteSpace return $ Nat_ n (T.pack $ show n) (Ws $ txt ws)
reuleaux/pire
src/Pire/Parser/Nat.hs
bsd-3-clause
2,865
0
11
726
232
141
91
26
1
module Main where --gcd :: Int -> Int -> Int --gcd x 0 = x --gcd x y -- | x < y = gcd y x -- | otherwise = gcd y (mod x y) --lcm :: Int -> Int -> Int --lcm x y = let g = gcd (x y) -- in (div x g) * (div y g) * g splitBy delimiter = foldr f [[]] where f c l@(x:xs) | c == delimiter = []:l | otherwise = (c:x):xs solve :: [Int] -> Int solve = foldr lcm 1 main :: IO () main = do getLine nsStr <- getLine let ns = map (read::String -> Int) $ splitBy ' ' nsStr print $ solve ns
everyevery/programming_study
hackerrank/functional/jumping-bunnies/jumping-bunnies.hs
mit
548
0
13
195
176
92
84
12
1
{-# LANGUAGE OverloadedStrings, ExistentialQuantification, ExtendedDefaultRules, FlexibleContexts, TemplateHaskell #-} module Dashdo.Examples.GapminderScatterplot where import Numeric.Datasets import Numeric.Datasets.Gapminder import Dashdo import Dashdo.Types import Dashdo.Serve import Dashdo.Elements import Lucid import Lucid.Bootstrap import Lucid.Bootstrap3 import Data.Monoid ((<>)) import qualified Data.Foldable as DF import Data.Text (Text, unpack, pack) import Data.List import Data.Aeson.Types import GHC.Float import Lens.Micro.Platform import Control.Monad import Control.Monad.State.Strict import Control.Applicative import Graphics.Plotly import qualified Graphics.Plotly.Base as B import Graphics.Plotly.Lucid data GmParams = GmParams { _selCountries :: [Text] , _selContinents :: [Text] , _selYear :: Text } makeLenses ''GmParams gm0 = GmParams [] [] "2007" data Continent = Africa | Americas | Asia | Europe | Oceania deriving (Eq, Show, Read, Enum) continentRGB :: Continent -> RGB Int continentRGB Africa = RGB 255 165 0 continentRGB Americas = RGB 178 34 34 continentRGB Asia = RGB 218 112 214 continentRGB Europe = RGB 0 128 0 continentRGB Oceania = RGB 0 0 255 continentRGB _ = undefined -- TODO: 1 - doghunt 2- sum gdp for region -- TODO: plotlySelectMultiple countriesTable :: [Gapminder] -> SHtml IO GmParams () countriesTable gms = table_ [class_ "table table-striped"] $ do thead_ $ do tr_ $ do th_ "Country" th_ "Population" th_ "GDP per capita" th_ "Life expectancy" tbody_ $ do DF.for_ gms $ \(c) -> do tr_ $ do td_ $ toHtml (country c) td_ $ toHtml (show $ pop c) td_ $ toHtml (show $ gdpPercap c) td_ $ toHtml (show $ lifeExp c) countriesScatterPlot :: [Gapminder] -> SHtml IO GmParams () countriesScatterPlot gms = let trace :: Trace trace = scatter & B.x ?~ (toJSON . gdpPercap <$> gms) & B.y ?~ (toJSON . lifeExp <$> gms) & B.customdata ?~ (toJSON . country <$> gms) & B.mode ?~ [B.Markers] & B.text ?~ (country <$> gms) & B.marker ?~ (defMarker & B.markercolor ?~ (List $ toJSON . continentRGB . read . unpack . continent <$> gms) & B.size ?~ (List $ (toJSON . float2Double . (* 200000) . log . fromInteger . pop) <$> gms) & B.sizeref ?~ toJSON 2e5 & B.sizeMode ?~ Area) xTicks = [ (1000, "$ 1,000") , (10000, "$ 10,000") , (50000, "$ 50,000")] in plotlySelectMultiple (plotly "countries-scatterplot" [trace] & layout %~ xaxis ?~ (defAxis & axistype ?~ Log & axistitle ?~ "GDP Per Capita" & tickvals ?~ (toJSON . fst <$> xTicks) & ticktext ?~ (pack . snd <$> xTicks)) & layout %~ yaxis ?~ (defAxis & axistitle ?~ "Life Expectancy") & layout %~ title ?~ "GDP Per Capita and Life Expectancy") selCountries gdp :: Gapminder -> Double gdp c = gdpPercap c * (fromIntegral $ pop c) continentsGDPsPie :: [Gapminder] -> SHtml IO GmParams () continentsGDPsPie gms = let -- list of continent-GDP pairs [(Continent, Double)] -- for each continent from Africa to Oceania continentGdps = [((,) currentCont) . sum $ gdp <$> (filter ((== show currentCont) . unpack . continent) gms) | currentCont <- [ Africa .. Oceania ]] pieLabels = pack . show . fst <$> continentGdps pieValues = toJSON . snd <$> continentGdps pieColors = List $ (toJSON . continentRGB . fst) <$> continentGdps trace :: Trace trace = pie & labels ?~ pieLabels & values ?~ pieValues & customdata ?~ (toJSON <$> pieLabels) & hole ?~ (toJSON 0.4) & marker ?~ (defMarker & markercolors ?~ pieColors) in plotlySelectMultiple (plotly "continents-gdp" [trace] & layout %~ title ?~ "World's GDP by Continents") selContinents average :: (Real a) => [a] -> Double average xs = realToFrac (sum xs) / genericLength xs yearsBarPlot :: [Gapminder] -> SHtml IO GmParams () yearsBarPlot gms = let years = nub $ year <$> gms trace = vbarChart [((pack . show) y, average (lifeExp <$> (filter ((==y) . year) gms))) | y <- years] in plotlySelect (plotly "years-lifeexp" [trace] & layout %~ title ?~ "Average Life Expactancy by Years") selYear gmRenderer :: [Gapminder] -> SHtml IO GmParams () gmRenderer gms = wrap plotlyCDN $ do gmParams <- getValue let selectedYear = read (unpack $ gmParams ^. selYear) :: Int yearFilter = filter ((==selectedYear) . year) countriesFilter = case gmParams ^. selCountries of [] -> id cs -> filter ((`elem` cs) . country) continentsFilter = case gmParams ^. selContinents of [] -> id cs -> filter ((`elem` cs) . continent) yearFilteredGMs = yearFilter gms h1_ "Gapminder Scatterplot Example" row_ $ do mkCol [(MD,4)] $ do continentsGDPsPie yearFilteredGMs mkCol [(MD,8)] $ do countriesScatterPlot $ continentsFilter yearFilteredGMs row_ $ do mkCol [(MD,12)] $ do yearsBarPlot $ (countriesFilter . continentsFilter) gms row_ $ do mkCol [(MD,12)] $ do countriesTable $ (countriesFilter . continentsFilter) yearFilteredGMs gapMinderScatterPlot = do gms <- getDataset gapminder runDashdoIO $ Dashdo gm0 (gmRenderer gms)
diffusionkinetics/open
dashdo-examples/lib/Dashdo/Examples/GapminderScatterplot.hs
mit
5,579
0
24
1,514
1,789
937
852
148
3
module Main where import Carnap.GHCJS.Action.Translate main :: IO () main = translateAction
gleachkr/Carnap
Carnap-GHCJS/Translate/Main.hs
gpl-3.0
94
0
6
14
26
16
10
4
1
{-# LANGUAGE OverloadedStrings #-} module Data.Shebang ( -- * Decoding decode , decodeEither -- * Smoke tests , hasShebang -- * Reading , readFirstLine -- * Core types , Shebang(..) , Interpretter(..) , Argument(..) ) where import Data.Attoparsec.ByteString.Lazy import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import Data.Word -------------------------------------------------------------------------------- -- | Newtype wrapper for Interpretter. newtype Interpretter = Interpretter { _interpretter :: BS.ByteString } deriving (Eq, Show) -- | Newtype wrapper for argument. newtype Argument = Argument { _argument :: BS.ByteString } deriving (Eq, Show) -- | Value representing a Shebang of the form #!interpreter [optional-arg]. data Shebang = Shebang Interpretter (Maybe Argument) deriving (Eq, Show) -------------------------------------------------------------------------------- -- | Checks the magic characters of a ByteString hasShebang :: BSL.ByteString -> Bool hasShebang x = BSL.take 2 x == "#!" -------------------------------------------------------------------------------- -- | Reads first line of a file. readFirstLine :: FilePath -> IO BSL.ByteString readFirstLine path = do contents <- BSL.readFile path return $ BSL.takeWhile (\x -> not $ x == 10 || x == 13) contents -------------------------------------------------------------------------------- -- | Takes a ByteString and maybe returns a Shebang. decode :: BSL.ByteString -> Maybe Shebang decode = maybeResult . parse shebang -------------------------------------------------------------------------------- -- | Takes a ByteString and returns a Shebang or an error string. decodeEither :: BSL.ByteString -> Either String Shebang decodeEither = eitherResult . parse shebang -------------------------------------------------------------------------------- -- | Simple Shebang parser. shebang :: Parser Shebang shebang = do _ <- string "#!" interpretter <- takeTill (\x -> whitespace x || endOfLine x) argument <- option "" $ do _ <- string " " takeTill endOfLine return $! case argument of "" -> Shebang (Interpretter interpretter) Nothing x -> Shebang (Interpretter interpretter) (Just (Argument x)) ---------------------------------------------------------------------------- -- | Character representing a carriage return. carriageReturn :: Word8 -> Bool carriageReturn = (==) 13 ---------------------------------------------------------------------------- -- | Characters representing end of line. endOfLine :: Word8 -> Bool endOfLine x = newline x || carriageReturn x ---------------------------------------------------------------------------- -- | Character representing a new line. newline :: Word8 -> Bool newline = (==) 10 ---------------------------------------------------------------------------- -- | Character representing spaces. whitespace :: Word8 -> Bool whitespace = (==) 32
filib/codeclimate-shellcheck
src/Data/Shebang.hs
gpl-3.0
3,027
0
15
475
555
309
246
47
2
{-# LANGUAGE PatternSynonyms #-} module Foo(A(.., B)) where data A = A | B
mpickering/ghc-exactprint
tests/examples/ghc8/export-syntax.hs
bsd-3-clause
76
2
6
15
26
17
9
3
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Plots.CmdLine where -- ( module Plots -- , r2AxisMain -- ) where -- import Data.Typeable -- import Options.Applicative -- -- import Diagrams.Prelude hiding ((<>), option) -- import Diagrams.Backend.CmdLine -- import Diagrams.Prelude hiding (option, (<>)) -- import Diagrams.TwoD.Text (Text) -- import Plots.Axis -- import Plots -- data PlotOptions = PlotOptions -- { plotTitle :: Maybe String -- } -- instance Parseable PlotOptions where -- parser = PlotOptions -- <$> (optional . strOption) -- (long "title" <> short 't' <> help "Plot title") -- instance (Typeable b, -- TypeableFloat n, -- Renderable (Text n) b, -- Renderable (Path V2 n) b, -- Backend b V2 n, -- Mainable (QDiagram b V2 n Any)) -- => Mainable (Axis b V2 n) where -- type MainOpts (Axis b V2 n) = (MainOpts (QDiagram b V2 n Any), PlotOptions) -- mainRender (opts, pOpts) a -- = mainRender opts . renderAxis -- $ a & axisTitle .~ plotTitle pOpts -- -- -- r2AxisMain :: (Parseable (MainOpts (QDiagram b V2 Double Any)), Mainable (Axis b V2 Double)) => Axis b V2 Double -> IO () -- r2AxisMain = mainWith
bergey/plots
src/Plots/CmdLine.hs
bsd-3-clause
1,379
0
3
330
43
41
2
6
0
f [] a = return a ; f (x:xs) a = a + x >>= \fax -> f xs fax
mpickering/hlint-refactor
tests/examples/ListRec4.hs
bsd-3-clause
59
0
7
19
52
26
26
1
1
{-# LANGUAGE TypeFamilies, NoMonomorphismRestriction #-} module T2767a where import Data.Kind (Type) main = return () -- eval' :: Solver solver => Tree solver a -> [(Label solver,Tree solver a)] -> solver [a] eval' (NewVar f) wl = do v <- newvarSM eval' (f v) wl eval' Fail wl = continue wl -- continue :: Solver solver => [(Label solver,Tree solver a)] -> solver [a] continue ((past,t):wl) = do gotoSM past eval' t wl data Tree s a = Fail | NewVar (Term s -> Tree s a) class Monad solver => Solver solver where type Term solver :: Type type Label solver :: Type newvarSM :: solver (Term solver) gotoSM :: Label solver -> solver ()
sdiehl/ghc
testsuite/tests/indexed-types/should_compile/T2767.hs
bsd-3-clause
791
0
9
275
202
105
97
-1
-1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="fil-PH"> <title>Getting started Guide</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
ccgreen13/zap-extensions
src/org/zaproxy/zap/extension/gettingStarted/resources/help_fil_PH/helpset_fil_PH.hs
apache-2.0
968
91
29
158
393
211
182
-1
-1
{-# LANGUAGE TypeFamilies, QuasiQuotes, TemplateHaskell, MultiParamTypeClasses, OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ViewPatterns #-} module YesodCoreTest.ErrorHandling ( errorHandlingTest , Widget ) where import Yesod.Core import Test.Hspec import Network.Wai import Network.Wai.Test import Text.Hamlet (hamlet) import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Char8 as S8 import Control.Exception (SomeException, try) import Network.HTTP.Types (mkStatus) import Blaze.ByteString.Builder (Builder, fromByteString, toLazyByteString) import Data.Monoid (mconcat) import Data.Text (Text, pack) import Control.Monad (forM_) import qualified Control.Exception.Lifted as E data App = App mkYesod "App" [parseRoutes| / HomeR GET /not_found NotFoundR POST /first_thing FirstThingR POST /after_runRequestBody AfterRunRequestBodyR POST /error-in-body ErrorInBodyR GET /error-in-body-noeval ErrorInBodyNoEvalR GET /override-status OverrideStatusR GET /error/#Int ErrorR GET -- https://github.com/yesodweb/yesod/issues/658 /builder BuilderR GET /file-bad-len FileBadLenR GET /file-bad-name FileBadNameR GET /good-builder GoodBuilderR GET |] overrideStatus = mkStatus 15 "OVERRIDE" instance Yesod App where errorHandler (InvalidArgs ["OVERRIDE"]) = sendResponseStatus overrideStatus ("OH HAI" :: String) errorHandler x = defaultErrorHandler x getHomeR :: Handler Html getHomeR = do $logDebug "Testing logging" defaultLayout $ toWidget [hamlet| $doctype 5 <html> <body> <form method=post action=@{NotFoundR}> <input type=submit value="Not found"> <form method=post action=@{FirstThingR}> <input type=submit value="Error is thrown first thing in handler"> <form method=post action=@{AfterRunRequestBodyR}> <input type=submit value="BUGGY: Error thrown after runRequestBody"> |] postNotFoundR, postFirstThingR, postAfterRunRequestBodyR :: Handler Html postNotFoundR = do (_, _files) <- runRequestBody _ <- notFound getHomeR postFirstThingR = do _ <- error "There was an error 3.14159" getHomeR postAfterRunRequestBodyR = do x <- runRequestBody _ <- error $ show $ fst x getHomeR getErrorInBodyR :: Handler Html getErrorInBodyR = do let foo = error "error in body 19328" :: String defaultLayout [whamlet|#{foo}|] getErrorInBodyNoEvalR :: Handler (DontFullyEvaluate Html) getErrorInBodyNoEvalR = fmap DontFullyEvaluate getErrorInBodyR getOverrideStatusR :: Handler () getOverrideStatusR = invalidArgs ["OVERRIDE"] getBuilderR :: Handler TypedContent getBuilderR = return $ TypedContent "ignored" $ ContentBuilder (error "builder-3.14159") Nothing getFileBadLenR :: Handler TypedContent getFileBadLenR = return $ TypedContent "ignored" $ ContentFile "yesod-core.cabal" (error "filebadlen") getFileBadNameR :: Handler TypedContent getFileBadNameR = return $ TypedContent "ignored" $ ContentFile (error "filebadname") Nothing goodBuilderContent :: Builder goodBuilderContent = mconcat $ replicate 100 $ fromByteString "This is a test\n" getGoodBuilderR :: Handler TypedContent getGoodBuilderR = return $ TypedContent "text/plain" $ toContent goodBuilderContent getErrorR :: Int -> Handler () getErrorR 1 = setSession undefined "foo" getErrorR 2 = setSession "foo" undefined getErrorR 3 = deleteSession undefined getErrorR 4 = addHeader undefined "foo" getErrorR 5 = addHeader "foo" undefined getErrorR 6 = expiresAt undefined getErrorR 7 = setLanguage undefined getErrorR 8 = cacheSeconds undefined getErrorR 9 = setUltDest (undefined :: Text) getErrorR 10 = setMessage undefined errorHandlingTest :: Spec errorHandlingTest = describe "Test.ErrorHandling" $ do it "says not found" caseNotFound it "says 'There was an error' before runRequestBody" caseBefore it "says 'There was an error' after runRequestBody" caseAfter it "error in body == 500" caseErrorInBody it "error in body, no eval == 200" caseErrorInBodyNoEval it "can override status code" caseOverrideStatus it "builder" caseBuilder it "file with bad len" caseFileBadLen it "file with bad name" caseFileBadName it "builder includes content-length" caseGoodBuilder forM_ [1..10] $ \i -> it ("error case " ++ show i) (caseError i) runner :: Session a -> IO a runner f = toWaiApp App >>= runSession f caseNotFound :: IO () caseNotFound = runner $ do res <- request defaultRequest { pathInfo = ["not_found"] , requestMethod = "POST" } assertStatus 404 res assertBodyContains "Not Found" res caseBefore :: IO () caseBefore = runner $ do res <- request defaultRequest { pathInfo = ["first_thing"] , requestMethod = "POST" } assertStatus 500 res assertBodyContains "There was an error 3.14159" res caseAfter :: IO () caseAfter = runner $ do let content = "foo=bar&baz=bin12345" res <- srequest SRequest { simpleRequest = defaultRequest { pathInfo = ["after_runRequestBody"] , requestMethod = "POST" , requestHeaders = [ ("content-type", "application/x-www-form-urlencoded") , ("content-length", S8.pack $ show $ L.length content) ] } , simpleRequestBody = content } assertStatus 500 res assertBodyContains "bin12345" res caseErrorInBody :: IO () caseErrorInBody = runner $ do res <- request defaultRequest { pathInfo = ["error-in-body"] } assertStatus 500 res assertBodyContains "error in body 19328" res caseErrorInBodyNoEval :: IO () caseErrorInBodyNoEval = do eres <- try $ runner $ do request defaultRequest { pathInfo = ["error-in-body-noeval"] } case eres of Left (_ :: SomeException) -> return () Right x -> error $ "Expected an exception, got: " ++ show x caseOverrideStatus :: IO () caseOverrideStatus = runner $ do res <- request defaultRequest { pathInfo = ["override-status"] } assertStatus 15 res caseBuilder :: IO () caseBuilder = runner $ do res <- request defaultRequest { pathInfo = ["builder"] } assertStatus 500 res assertBodyContains "builder-3.14159" res caseFileBadLen :: IO () caseFileBadLen = runner $ do res <- request defaultRequest { pathInfo = ["file-bad-len"] } assertStatus 500 res assertBodyContains "filebadlen" res caseFileBadName :: IO () caseFileBadName = runner $ do res <- request defaultRequest { pathInfo = ["file-bad-name"] } assertStatus 500 res assertBodyContains "filebadname" res caseGoodBuilder :: IO () caseGoodBuilder = runner $ do res <- request defaultRequest { pathInfo = ["good-builder"] } assertStatus 200 res let lbs = toLazyByteString goodBuilderContent assertBody lbs res assertHeader "content-length" (S8.pack $ show $ L.length lbs) res caseError :: Int -> IO () caseError i = runner $ do res <- request defaultRequest { pathInfo = ["error", pack $ show i] } assertStatus 500 res `E.catch` \e -> do liftIO $ print res E.throwIO (e :: E.SomeException)
pikajude/yesod
yesod-core/test/YesodCoreTest/ErrorHandling.hs
mit
7,179
0
18
1,445
1,713
862
851
157
2
{-# LANGUAGE MagicHash, UnliftedFFITypes #-} -- !!! cc004 -- foreign declarations module ShouldCompile where import Foreign import GHC.Exts import Data.Int import Data.Word -- importing functions -- We can't import the same function using both stdcall and ccall -- calling conventions in the same file when compiling via C (this is a -- restriction in the C backend caused by the need to emit a prototype -- for stdcall functions). foreign import stdcall "p" m_stdcall :: StablePtr a -> IO (StablePtr b) foreign import ccall unsafe "q" m_ccall :: ByteArray# -> IO Int -- We can't redefine the calling conventions of certain functions (those from -- math.h). foreign import stdcall "my_sin" my_sin :: Double -> IO Double foreign import stdcall "my_cos" my_cos :: Double -> IO Double foreign import stdcall "m1" m8 :: IO Int8 foreign import stdcall "m2" m16 :: IO Int16 foreign import stdcall "m3" m32 :: IO Int32 foreign import stdcall "m4" m64 :: IO Int64 foreign import stdcall "dynamic" d8 :: FunPtr (IO Int8) -> IO Int8 foreign import stdcall "dynamic" d16 :: FunPtr (IO Int16) -> IO Int16 foreign import stdcall "dynamic" d32 :: FunPtr (IO Int32) -> IO Int32 foreign import stdcall "dynamic" d64 :: FunPtr (IO Int64) -> IO Int64 foreign import ccall unsafe "kitchen" sink :: Ptr a -> ByteArray# -> MutableByteArray# RealWorld -> Int -> Int8 -> Int16 -> Int32 -> Int64 -> Word8 -> Word16 -> Word32 -> Word64 -> Float -> Double -> IO () type Sink2 b = Ptr b -> ByteArray# -> MutableByteArray# RealWorld -> Int -> Int8 -> Int16 -> Int32 -> Word8 -> Word16 -> Word32 -> Float -> Double -> IO () foreign import ccall unsafe "dynamic" sink2 :: Ptr (Sink2 b) -> Sink2 b
hferreiro/replay
testsuite/tests/ffi/should_compile/cc004.hs
bsd-3-clause
1,861
42
10
484
477
257
220
49
0
{-# LANGUAGE RoleAnnotations #-} {-# OPTIONS_GHC -fwarn-unused-imports #-} import Data.Coerce import Data.Proxy import Data.Monoid (First(First)) -- check whether the implicit use of First is noted -- see https://ghc.haskell.org/trac/ghc/wiki/Design/NewCoercibleSolver/V2 foo1 :: f a -> f a foo1 = coerce newtype X = MkX (Int -> X) foo2 :: X -> X foo2 = coerce newtype X2 a = MkX2 Char type role X2 nominal foo3 :: X2 Int -> X2 Bool foo3 = coerce newtype Age = MkAge Int newtype Y a = MkY a type role Y nominal foo4 :: Y Age -> Y Int foo4 = coerce newtype Z a = MkZ () type role Z representational foo5 :: Z Int -> Z Bool foo5 = coerce newtype App f a = MkApp (f a) foo6 :: f a -> App f a foo6 = coerce foo7 :: Coercible a b => b -> a foo7 = coerce foo8 :: (Coercible a b, Coercible b c) => Proxy b -> a -> c foo8 _ = coerce main = print (coerce $ Just (1::Int) :: First Int)
urbanslug/ghc
testsuite/tests/typecheck/should_compile/TcCoercibleCompile.hs
bsd-3-clause
896
0
9
198
327
183
144
31
1
-- !!! Importing Tycon with bogus constructor module M where import Prelude(Either(Left,Right,Foo))
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/module/mod81.hs
bsd-3-clause
101
0
6
13
21
16
5
2
0
main :: IO () main = do putStrLn "Escriba un nombre: " nombre <- getLine case nombre of "Napoleon" -> putStrLn "Su apellido es Bonaparte!" _ -> putStrLn "No se ha podido determinar su apellido"
clinoge/primer-semestre-udone
src/04-condicionales/nombre.hs
mit
231
1
10
72
53
24
29
-1
-1
module Bio.Utils.Misc ( readInt , readDouble , bins , binBySize , binBySizeLeft , binBySizeOverlap ) where import Data.ByteString.Char8 (ByteString) import Data.ByteString.Lex.Fractional (readExponential, readSigned) import Data.ByteString.Lex.Integral (readDecimal) import Data.Maybe (fromMaybe) readInt :: ByteString -> Int readInt x = fst . fromMaybe errMsg . readSigned readDecimal $ x where errMsg = error $ "readInt: Fail to cast ByteString to Int:" ++ show x {-# INLINE readInt #-} readDouble :: ByteString -> Double readDouble x = fst . fromMaybe errMsg . readSigned readExponential $ x where errMsg = error $ "readDouble: Fail to cast ByteString to Double:" ++ show x {-# INLINE readDouble #-} -- | divide a given half-close-half-open region into fixed size -- half-close-half-open intervals, discarding leftovers binBySize :: Int -> (Int, Int) -> [(Int, Int)] binBySize step (start, end) = let xs = [start, start + step .. end] in zip xs . tail $ xs {-# INLINE binBySize #-} binBySizeOverlap :: Int -> Int -> (Int, Int) -> [(Int, Int)] binBySizeOverlap step overlap (start, end) | overlap >= step = error "binBySizeOverlap: overlap > step" | otherwise = go start where go i | i + overlap < end = (i, i + step) : go (i + step - overlap) | otherwise = [] {-# INLINE binBySizeOverlap #-} -- | Including leftovers, the last bin will be extended to match desirable size binBySizeLeft :: Int -> (Int, Int) -> [(Int, Int)] binBySizeLeft step (start, end) = go start where go i | i < end = (i, i + step) : go (i + step) | otherwise = [] {-# INLINE binBySizeLeft #-} -- | divide a given region into k equal size sub-regions, discarding leftovers bins :: Int -> (Int, Int) -> [(Int, Int)] bins binNum (start, end) = let k = (end - start) `div` binNum in take binNum . binBySize k $ (start, end) {-# INLINE bins #-}
kaizhang/bioinformatics-toolkit
bioinformatics-toolkit/src/Bio/Utils/Misc.hs
mit
2,028
0
12
526
598
328
270
39
1
module Bot ( Event (..) , Response (..) , handleEvent ) where import Data.List import Data.List.Split import Data.Char (toLower) import Network.HTTP.Base (urlEncode) data Event = Msg { msg :: String , sender :: String } data Response = SendMsg { msgToSend :: String } -- | GetChanUsers { chanName :: String} | LeaveChan | JoinChan { chanName :: String } | Exit handleEvent :: Event -> Maybe Response handleEvent (Msg m s) = case m of -- Commands start with '!' ('!' : command) -> handleCommand . buildCommand $ command "Hello" -> Just $ SendMsg $ "Hello, " ++ s ++ "!" s -> if isHey s then Just $ SendMsg $ "H" ++ (replicate ((countEInHey s) + 1) 'o') else Nothing ----------------------------------- -- Commands ----------------------------------- data Command = Command { cmd :: String , arg :: Maybe String } buildCommand :: String -> Command buildCommand s = Command makeCommand makeArg where makeCommand = takeWhile ((/=) ' ') s makeArg = let argStr = drop 1 . dropWhile ((/=) ' ') $ s in if argStr == [] then Nothing else Just argStr handleCommand :: Command -> Maybe Response handleCommand (Command command Nothing) = case command of "quit" -> Just $ Exit "part" -> Just $ LeaveChan handleCommand (Command command (Just arg)) = case command of "gs" -> Just $ SendMsg $ getSearchUrl "https://www.google.com/search?q=" arg "hs" -> Just $ SendMsg $ getSearchUrl "https://www.haskell.org/hoogle/?hoogle=" arg ----------------------------------- -- Used for Heeey-Hooo ----------------------------------- isHey :: String -> Bool isHey s = if s == [] then False else let s' = map toLower s in (head s' == 'h') && ((dropWhile (== 'e') . drop 1 $ s) == "y") countEInHey :: String -> Int countEInHey s = (length s) - 2 ----------------------------------- -- Helper functions ----------------------------------- getSearchUrl :: String -> String -> String getSearchUrl basicUrl str = basicUrl ++ urlEncode str
TheCrafter/Scarybot
src/Bot.hs
mit
2,215
0
15
618
627
340
287
48
4
{-# LANGUAGE TupleSections #-} module System where import System.Directory import System.FilePath import Aws import Control.Monad import Data.Text (Text) -- | Loads the aws creds by keyname from the currenty directory or parent -- directories. loadAwsCreds :: Text -> IO (Maybe (FilePath, Credentials)) loadAwsCreds key = do dirs <- getDirectories mcreds <- mapM (flip loadCredentialsFromFile key . (</> ".aws-keys")) dirs return $ msum $ zipWith (\d m -> (d,) <$> m) dirs mcreds -- | Returns the current working directory and each parent directory. getDirectories :: IO [FilePath] getDirectories = getCurrentDirectory >>= return . subs where subs "/" = ["/"] subs fp = fp : (subs $ takeDirectory fp) -- | Checks a file as an absolute path and relative path - if either path -- is a valid file then returns a Just filepath. checkFilePath :: FilePath -> IO (Maybe FilePath) checkFilePath fp = do isAbs <- doesFileExist fp if isAbs then return $ Just fp else do cwd <- getCurrentDirectory let relfp = cwd </> fp isRel <- doesFileExist relfp if isRel then return $ Just relfp else return $ Nothing
schell/dropdox
src/System.hs
mit
1,193
0
13
280
306
160
146
28
3
{-# LANGUAGE OverloadedStrings #-} import Control.Applicative ((<$>)) import Data.List (intercalate,sortBy) import Text.Blaze.Html (toHtml,toValue, (!)) import Text.Blaze.Html.Renderer.String (renderHtml) import qualified Text.Blaze.Html5 as BlazeHtml import qualified Text.Blaze.Html5.Attributes as BlazeAttr import Data.Monoid (mappend, mconcat) import Hakyll.Web.Tags (renderTags) import Control.Monad (forM) import Data.Maybe (fromMaybe) import Hakyll main :: IO () main = hakyll $ do -- Static files match ("images/*" .||. "js/*" .||. "favicon.ico" .||. "CNAME" .||. "files/*") $ do route idRoute compile copyFileCompiler -- Compress CSS match "css/*" $ do route idRoute compile compressCssCompiler -- About match "about.md" $ do route $ setExtension "html" compile $ pandocCompiler >>= loadAndApplyTemplate "templates/about.html" defaultContext >>= loadAndApplyTemplate "templates/default.html" defaultContext >>= relativizeUrls -- Build Tags tags <- buildTags "posts/*" (fromCapture "tags/*.html") -- Individual Posts match "posts/*" $ do route $ setExtension "html" compile $ pandocCompiler >>= loadAndApplyTemplate "templates/post.html" (postContext tags) >>= loadAndApplyTemplate "templates/default.html" defaultContext >>= relativizeUrls -- Posts create ["posts.html"] $ do route idRoute compile $ do list <- postList tags "posts/*" recentFirst let postsContext = constField "posts" list `mappend` constField "title" "Posts" `mappend` defaultContext makeItem "" >>= loadAndApplyTemplate "templates/posts.html" postsContext >>= loadAndApplyTemplate "templates/default.html" defaultContext >>= relativizeUrls -- Index create ["index.html"] $ do route idRoute compile $ do list <- postListNum tags "posts/*" recentFirst 3 let indexContext = constField "posts" list `mappend` constField "title" "Home" `mappend` defaultContext makeItem "" >>= loadAndApplyTemplate "templates/index.html" indexContext >>= loadAndApplyTemplate "templates/default.html" indexContext >>= relativizeUrls -- 404 create ["404.html"] $ do route idRoute compile $ do let notFoundContext = constField "title" "404 - Not Found" `mappend` constField "body" "The page you were looking for was not found." `mappend` defaultContext makeItem "" >>= loadAndApplyTemplate "templates/about.html" notFoundContext >>= loadAndApplyTemplate "templates/default.html" notFoundContext >>= relativizeUrls -- Tag Pages tagsRules tags $ \tag pattern -> do let title = "Posts tagged with " ++ tag route idRoute compile $ do list <- postList tags pattern recentFirst let tagContext = constField "title" title `mappend` constField "posts" list `mappend` defaultContext makeItem "" >>= loadAndApplyTemplate "templates/posts.html" tagContext >>= loadAndApplyTemplate "templates/default.html" defaultContext >>= relativizeUrls -- Tags create ["tags.html"] $ do route idRoute compile $ do tagList <- renderTagElem tags let tagsContext = constField "title" "Tags" `mappend` constField "tags" tagList `mappend` defaultContext makeItem "" >>= loadAndApplyTemplate "templates/tags.html" tagsContext >>= loadAndApplyTemplate "templates/default.html" defaultContext >>= relativizeUrls -- RSS create ["rss.xml"] $ do route idRoute compile $ do posts <- loadAll "posts/*" sorted <- take 10 <$> recentFirst posts renderRss feedConfiguration feedContext sorted match "templates/*" $ compile templateCompiler ------------------------------------------------------ postContext :: Tags -> Context String postContext tags = mconcat [ modificationTimeField "mtime" "%U" , dateField "date" "%B %e, %Y" , tagsField "tags" tags , defaultContext ] ------------------------------------------------------ postList :: Tags -> Pattern -> ([Item String] -> Compiler [Item String]) -> Compiler String postList tags pattern prep = do posts <- loadAll pattern itemTemplate <- loadBody "templates/postitem.html" processed <- prep posts applyTemplateList itemTemplate (postContext tags) processed postListNum :: Tags -> Pattern -> ([Item String] -> Compiler [Item String]) -> Int -> Compiler String postListNum tags pattern prep num = do posts <- prep <$> loadAll pattern itemTemplate <- loadBody "templates/postitem.html" taken <- take num <$> posts applyTemplateList itemTemplate (postContext tags) taken ----------------------------------------------------- renderTagElem :: Tags -> Compiler String renderTagElem = renderTags makeLink (intercalate "\n") where makeLink tag url count _ _ = renderHtml $ BlazeHtml.li $ BlazeHtml.a ! BlazeAttr.href (toValue url) $ toHtml (tag ++ " - " ++ show count ++(postName count)) postName :: Int -> String postName 1 = " post" postName _ = " posts" ------------------------------------------------------ feedConfiguration :: FeedConfiguration feedConfiguration = FeedConfiguration { feedTitle = "warwickmasson.com - Posts" , feedDescription = "Posts from warwickmasson.com" , feedAuthorName = "Warwick Masson" , feedAuthorEmail = "[email protected]" , feedRoot = "http://warwickmasson.com" } ------------------------------------------------------ feedContext :: Context String feedContext = constField "description" "" `mappend` defaultContext
WarwickMasson/wmasson-hakyll
site.hs
mit
6,246
0
20
1,735
1,376
673
703
129
1
{-# LANGUAGE GADTs #-} module Kafkaesque.Request.Offsets ( offsetsRequestV0 , respondToRequestV0 ) where import Data.Attoparsec.ByteString (Parser) import Data.Int (Int32, Int64) import Data.Maybe (catMaybes, fromMaybe) import qualified Data.Pool as Pool import qualified Database.PostgreSQL.Simple as PG import Kafkaesque.KafkaError (noError, unknownTopicOrPartition, unsupportedForMessageFormat) import Kafkaesque.Parsers (kafkaArray, kafkaString, signedInt32be, signedInt64be) import Kafkaesque.Protocol.ApiKey (Offsets) import Kafkaesque.Protocol.ApiVersion (V0) import Kafkaesque.Queries (getEarliestOffset, getNextOffset, getTopicPartition) import Kafkaesque.Request.KafkaRequest (OffsetListRequestPartition, OffsetListRequestTimestamp(EarliestOffset, LatestOffset, OffsetListTimestamp), OffsetListRequestTopic, OffsetListResponsePartition, OffsetListResponseTopic, Request(OffsetsRequestV0), Response(OffsetsResponseV0)) makeTimestamp :: Int64 -> Maybe OffsetListRequestTimestamp makeTimestamp (-1) = Just LatestOffset makeTimestamp (-2) = Just EarliestOffset makeTimestamp t | t > 0 = Just $ OffsetListTimestamp t | otherwise = Nothing offsetsRequestTimestamp :: Parser OffsetListRequestTimestamp offsetsRequestTimestamp = makeTimestamp <$> signedInt64be >>= maybe (fail "Unable to parse timestamp") return offsetsRequestPartition :: Parser OffsetListRequestPartition offsetsRequestPartition = (\partitionId ts maxNumOffsets -> (partitionId, ts, maxNumOffsets)) <$> signedInt32be <*> offsetsRequestTimestamp <*> signedInt32be offsetsRequestTopic :: Parser OffsetListRequestTopic offsetsRequestTopic = (\t xs -> (t, xs)) <$> kafkaString <*> (fromMaybe [] <$> kafkaArray offsetsRequestPartition) offsetsRequestV0 :: Parser (Request Offsets V0) offsetsRequestV0 = OffsetsRequestV0 <$> signedInt32be <*> (fromMaybe [] <$> kafkaArray offsetsRequestTopic) fetchTopicPartitionOffsets :: PG.Connection -> Int32 -> Int32 -> OffsetListRequestTimestamp -> Int32 -> IO (Maybe [Int64]) fetchTopicPartitionOffsets conn topicId partitionId timestamp maxOffsets = do earliest <- getEarliestOffset conn topicId partitionId latest <- getNextOffset conn topicId partitionId -- TODO handle actual timestamp offsets let sendOffsets = Just . take (fromIntegral maxOffsets) . catMaybes return $ case timestamp of LatestOffset -> sendOffsets [Just latest, earliest] EarliestOffset -> sendOffsets [earliest] OffsetListTimestamp _ -> Nothing fetchPartitionOffsets :: PG.Connection -> String -> OffsetListRequestPartition -> IO OffsetListResponsePartition fetchPartitionOffsets conn topicName (partitionId, timestamp, maxOffsets) = do res <- getTopicPartition conn topicName partitionId case res of Nothing -> return (partitionId, unknownTopicOrPartition, Nothing) Just (topicId, _) -> do offsetRes <- fetchTopicPartitionOffsets conn topicId partitionId timestamp maxOffsets return $ case offsetRes of Nothing -> (partitionId, unsupportedForMessageFormat, Nothing) Just offsets -> (partitionId, noError, Just offsets) fetchTopicOffsets :: PG.Connection -> OffsetListRequestTopic -> IO OffsetListResponseTopic fetchTopicOffsets conn (topicName, partitions) = do partitionResponses <- mapM (fetchPartitionOffsets conn topicName) partitions return (topicName, partitionResponses) respondToRequestV0 :: Pool.Pool PG.Connection -> Request Offsets V0 -> IO (Response Offsets V0) respondToRequestV0 pool (OffsetsRequestV0 _ topics) = do topicResponses <- Pool.withResource pool (\conn -> mapM (fetchTopicOffsets conn) topics) return $ OffsetsResponseV0 topicResponses
cjlarose/kafkaesque
src/Kafkaesque/Request/Offsets.hs
mit
3,819
0
17
637
925
493
432
91
3
import System.Environment import System.IO import Data.List import Data.Ord import qualified Data.Map as M import System.Process splitOn :: (a -> Bool) -> [a] -> [[a]] splitOn f [] = [[]] splitOn f (h:t) = let (rh:rt) = splitOn f t ret = (h:rh):rt in if f h then []:ret else ret getExpected (sigil:hunk) = map tail $ filter (\ (h:_) -> h == ' ' || h == '-') hunk diffHunk orig hunk = do let expected = zip [0..] (getExpected hunk) allIndices = map (\(num,line) -> map (\x->x-num) (elemIndices line orig)) expected start = head . maximumBy (comparing length) . group . sort . concat $ allIndices there = take (length expected) $ drop (start-1) orig writeFile "/tmp/there" (unlines there) writeFile "/tmp/expected" (unlines $ map snd expected) --runCommand "diff -U 8 -p /tmp/there /tmp/expected" >>= waitForProcess runCommand "meld /tmp/there /tmp/expected" >>= waitForProcess main = do args <- getArgs if length args /= 1 then putStrLn "I only take one argument, a diff file, with hunks that failed to apply cleanly" else return () let name = head args patch <- fmap lines (readFile name) let '-':'-':'-':' ':origName = head patch orig <- fmap lines (readFile origName) putStrLn $ "patch is " ++ show (length patch) ++ " lines long, orig is " ++ show (length orig) ++ " lines long" let hunks = tail $ splitOn (\ lin -> "@@" `isPrefixOf` lin) patch putStrLn $ "and I found " ++ show (length hunks) ++ " hunks" mapM_ (diffHunk orig) hunks
mjrosenb/bend
bend.hs
mit
1,680
0
17
493
625
313
312
33
2
{-# LANGUAGE OverloadedStrings #-} module Text.Marquee.Parser.Block (parseBlocks) where import Control.Applicative import Control.Monad import Control.Monad.State (StateT(..), get, modify, lift) import Data.Char (isLetter, isUpper) import Data.Text (Text()) import qualified Data.Text as T import Data.Attoparsec.Text as Atto import Data.Attoparsec.Combinator import Text.Marquee.Parser.Common import Text.Marquee.Parser.HTML as H import Text.Marquee.SyntaxTrees.CST (Doc(..), DocElement(..)) import qualified Text.Marquee.SyntaxTrees.CST as C parseBlocks :: BlockParser Doc parseBlocks = sepBy block (lift lineEnding) -- Types type BlockParser = StateT [Int] Parser indent :: Int -> BlockParser () indent n = modify ((:) n) unindent :: BlockParser () unindent = modify (drop 1) indentLevel :: BlockParser Int indentLevel = liftM sum get -- Useful definitions bulletMarker :: Parser Char bulletMarker = oneOf "-+*" orderedMarker :: Parser (String, Char) orderedMarker = (,) <$> atMostN1 9 digit <*> oneOf ".)" -- Parsing block :: BlockParser DocElement block = choice [ blankLine , headingUnderline , thematicBreak , heading , indentedLine , fenced , html , linkRef -- Container , blockquote , unorderedList , orderedList -- -- Any other is a paragraph , paragraph ] indented :: BlockParser DocElement -> BlockParser DocElement indented p = indentLevel >>= \level -> count level (lift linespace) >> p blankLine :: BlockParser DocElement blankLine = lift $ next (lookAhead lineEnding_) *> return C.blankLine headingUnderline :: BlockParser DocElement headingUnderline = lift $ do optIndent cs@(c:_) <- setextOf 1 '=' <|> setextOf 2 '-' return $ C.headingUnderline (if c == '=' then 1 else 2) (T.pack cs) where setextOf n c = manyN n (char c) <* next (lookAhead lineEnding_) thematicBreak :: BlockParser DocElement thematicBreak = lift $ do optIndent thematicBreakOf '-' <|> thematicBreakOf '_' <|> thematicBreakOf '*' return C.thematicBreak where thematicBreakOf c = manyN 3 (char c <* skipWhile isLinespace) <* next (lookAhead lineEnding_) heading :: BlockParser DocElement heading = lift $ do optIndent pounds <- atMostN1 6 (char '#') lookAhead (void linespace) <|> lookAhead lineEnding_ content <- headingInline (length pounds) return $ C.heading (length pounds) content indentedLine :: BlockParser DocElement indentedLine = lift $ C.indentedBlock <$> (string " " *> rawInline) fenced :: BlockParser DocElement fenced = do indentLen <- (+) <$> indentLevel <*> (length <$> lift optIndent) lift $ do fence <- fenceOf '`' <|> fenceOf '~' infoString <- T.pack <$> manyTill (escaped <|> anyChar) (lookAhead $ void (char '`') <|> lineEnding) <* lineEnding let fenceIndent = atMostN indentLen (char ' ') closingFence = fenceIndent *> optIndent *> manyN (length fence) (char $ head fence) content <- manyTill1 (fenceIndent *> Atto.takeTill isLineEnding <* lineEnding_) (endOfInput <|> lookAhead (closingFence *> next lineEnding_)) closingFence *> takeTill isLineEnding return $ C.fenced infoString content where fenceOf c = manyN 3 (char c) html :: BlockParser DocElement html = lift optIndent *> (html1to5 <|> html6 <|> html7) where html1to5 = lift $ do xs <- H.info <|> H.comment <|> H.cdata <|> H.special <|> H.preFormated ys <- takeTill isLineEnding return . C.html $ T.append xs ys html6 = lift $ do xs <- H.simpleTag ys <- tillBlankLine return . C.html $ T.append xs ys html7 = lift $ do xs <- (H.tag <|> H.ctag) <* lookAhead whitespace ys <- tillBlankLine return . C.html $ T.append xs ys tillBlankLine = T.concat <$> manyTill (Atto.takeWhile1 (not .isLineEnding) <|> Atto.take 1) (lookAhead $ lineEnding *> emptyLine) linkRef :: BlockParser DocElement linkRef = lift $ do optIndent ref <- linkLabel <* char ':' dest <- spacing *> linkDestination mtitle <- (optionMaybe $ spacing *> linkTitle) <* next (lookAhead lineEnding_) return $ C.linkReference ref dest mtitle where spacing = skipWhile isLinespace >> (optional $ lineEnding *> skipMany linespace) paragraph :: BlockParser DocElement paragraph = lift $ C.paragraphBlock <$> rawInline blockquote :: BlockParser DocElement blockquote = C.blockquoteBlock <$> (lift (optIndent *> char '>' *> skipWhile isLinespace) *> block) unorderedList :: BlockParser DocElement unorderedList = do indent <- lift $ length <$> optIndent marker <- lift bulletMarker spaces <- lift $ T.length <$> takeWhile1 isWhitespace C.unorderedList marker <$> listItem (indent + 1 + spaces) orderedList :: BlockParser DocElement orderedList = do indent <- lift $ length <$> optIndent (num, marker) <- lift orderedMarker spaces <- lift $ T.length <$> takeWhile1 isWhitespace C.orderedList marker (read num) <$> listItem (indent + length num + 1 + spaces) listItem :: Int -> BlockParser Doc listItem indentAmount = do indent indentAmount level <- indentLevel x <- block xs <- concat <$> many (lift lineEnding *> go) unindent return (x:xs) where go = do x <- optionMaybe $ blankLine <* lift lineEnding y <- indented block case x of Nothing -> return [y] Just x -> return [x, y] rawInline :: Parser Text rawInline = Atto.takeTill isLineEnding headingInline :: Int -> Parser Text headingInline headingSize = do xs <- manyTill anyChar (lookAhead end) <* end return $ T.pack xs where end = lookAhead lineEnding_ <|> linespace *> Atto.takeWhile (== '#') *> next (lookAhead lineEnding_)
DanielRS/marquee
src/Text/Marquee/Parser/Block.hs
mit
5,830
1
19
1,314
1,955
979
976
145
2
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.RTCDTMFSender (js_insertDTMF, insertDTMF, js_getCanInsertDTMF, getCanInsertDTMF, js_getTrack, getTrack, js_getToneBuffer, getToneBuffer, js_getDuration, getDuration, js_getInterToneGap, getInterToneGap, toneChange, RTCDTMFSender, castToRTCDTMFSender, gTypeRTCDTMFSender) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"insertDTMF\"]($2, $3, $4)" js_insertDTMF :: RTCDTMFSender -> JSString -> Int -> Int -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.insertDTMF Mozilla RTCDTMFSender.insertDTMF documentation> insertDTMF :: (MonadIO m, ToJSString tones) => RTCDTMFSender -> tones -> Int -> Int -> m () insertDTMF self tones duration interToneGap = liftIO (js_insertDTMF (self) (toJSString tones) duration interToneGap) foreign import javascript unsafe "($1[\"canInsertDTMF\"] ? 1 : 0)" js_getCanInsertDTMF :: RTCDTMFSender -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.canInsertDTMF Mozilla RTCDTMFSender.canInsertDTMF documentation> getCanInsertDTMF :: (MonadIO m) => RTCDTMFSender -> m Bool getCanInsertDTMF self = liftIO (js_getCanInsertDTMF (self)) foreign import javascript unsafe "$1[\"track\"]" js_getTrack :: RTCDTMFSender -> IO (Nullable MediaStreamTrack) -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.track Mozilla RTCDTMFSender.track documentation> getTrack :: (MonadIO m) => RTCDTMFSender -> m (Maybe MediaStreamTrack) getTrack self = liftIO (nullableToMaybe <$> (js_getTrack (self))) foreign import javascript unsafe "$1[\"toneBuffer\"]" js_getToneBuffer :: RTCDTMFSender -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.toneBuffer Mozilla RTCDTMFSender.toneBuffer documentation> getToneBuffer :: (MonadIO m, FromJSString result) => RTCDTMFSender -> m result getToneBuffer self = liftIO (fromJSString <$> (js_getToneBuffer (self))) foreign import javascript unsafe "$1[\"duration\"]" js_getDuration :: RTCDTMFSender -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.duration Mozilla RTCDTMFSender.duration documentation> getDuration :: (MonadIO m) => RTCDTMFSender -> m Int getDuration self = liftIO (js_getDuration (self)) foreign import javascript unsafe "$1[\"interToneGap\"]" js_getInterToneGap :: RTCDTMFSender -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.interToneGap Mozilla RTCDTMFSender.interToneGap documentation> getInterToneGap :: (MonadIO m) => RTCDTMFSender -> m Int getInterToneGap self = liftIO (js_getInterToneGap (self)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.ontonechange Mozilla RTCDTMFSender.ontonechange documentation> toneChange :: EventName RTCDTMFSender Event toneChange = unsafeEventName (toJSString "tonechange")
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/RTCDTMFSender.hs
mit
3,788
42
10
504
814
469
345
53
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Main where import Control.Applicative import Control.Monad import Control.Concurrent.STM import Data.Hashable import Data.Function (on) import qualified Data.Map as M import qualified Data.List as L import qualified Control.Concurrent.STM.Map as TTrie import Test.QuickCheck import Test.QuickCheck.Monadic import Test.Framework (defaultMain, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) -- most of this based on the unordered-containers tests ----------------------------------------------------------------------- main = defaultMain [ testGroup "basic interface" [ testProperty "lookup" pLookup , testProperty "insert" pInsert , testProperty "delete" pDelete ] , testGroup "unsafe functions" [ testProperty "phantomLookup" pPhantomLookup , testProperty "unsafeDelete" pUnsafeDelete ] , testGroup "conversions" [ testProperty "fromList" pFromList , testProperty "unsafeToList" pUnsafeToList ] ] ----------------------------------------------------------------------- type Model k v = M.Map k v eq :: (Eq a, Eq k, Hashable k, Ord k) => (Model k v -> a) -> (TTrie.Map k v -> IO a) -> [(k, v)] -> Property eq f g xs = monadicIO $ do let a = f (M.fromList xs) b <- run $ g =<< TTrie.fromList xs assert $ a == b eq_ :: (Eq k, Eq v, Hashable k, Ord k) => (Model k v -> Model k v) -> (TTrie.Map k v -> IO ()) -> [(k, v)] -> Property eq_ f g xs = monadicIO $ do let a = M.toAscList $ f $ M.fromList xs m <- run $ TTrie.fromList xs run $ g m b <- run $ unsafeToAscList m assert $ a == b unsafeToAscList :: Ord k => TTrie.Map k v -> IO [(k, v)] unsafeToAscList m = do xs <- TTrie.unsafeToList m return $ L.sortBy (compare `on` fst) xs ----------------------------------------------------------------------- -- key type that generates more hash collisions newtype Key = K { unK :: Int } deriving (Arbitrary, Eq, Ord) instance Show Key where show = show . unK instance Hashable Key where hashWithSalt salt k = hashWithSalt salt (unK k) `mod` 20 ----------------------------------------------------------------------- pLookup :: Key -> [(Key,Int)] -> Property pLookup k = M.lookup k `eq` (atomically . TTrie.lookup k) pPhantomLookup :: Key -> [(Key,Int)] -> Property pPhantomLookup k = M.lookup k `eq` (atomically . TTrie.phantomLookup k) pInsert :: Key -> Int -> [(Key,Int)] -> Property pInsert k v = M.insert k v `eq_` (atomically . TTrie.insert k v) pDelete :: Key -> [(Key,Int)] -> Property pDelete k = M.delete k `eq_` (atomically . TTrie.delete k) pUnsafeDelete :: Key -> [(Key,Int)] -> Property pUnsafeDelete k = M.delete k `eq_` TTrie.unsafeDelete k pFromList :: [(Key,Int)] -> Property pFromList = id `eq_` (\_ -> return ()) pUnsafeToList :: [(Key,Int)] -> Property pUnsafeToList = M.toAscList `eq` unsafeToAscList
mcschroeder/ttrie
tests/MapProperties.hs
mit
3,168
0
14
797
1,035
559
476
63
1
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} import System.Environment import Data.Text import Control.Monad import qualified Data.ByteString as BS (writeFile, readFile) import qualified Codec.Compression.Zlib as ZL import qualified Data.Text.Encoding as TE import Data.Serialize as DS -- newtype NewText = NewText Text deriving Show instance Serialize Text where put txt = put $ TE.encodeUtf8 txt get = fmap TE.decodeUtf8 get testText = 6::Int-- NewText "eefefef" -- "#.<>[]'_,:=/\\+(){}!?*-|^~&@\8322\8321\8729\8868\8869" fileName = "testext.bin" main = do putStrLn "Writing text to the file..." let bsw = encode testText BS.writeFile fileName bsw putStrLn "Reading the text from the file..." bsr <- BS.readFile fileName let tt = decode bsr case tt of Left s -> do putStrLn $ "Error in decoding: " ++ s return () Right (t::Int) -> do putStrLn $ show t return ()
BitFunctor/bitfunctor-theory
aux/testsertext.hs
mit
1,080
0
13
331
242
124
118
27
2
module Graphics.Urho3D.Graphics.Internal.Texture( Texture , SharedTexture , WeakTexture , textureCntx , sharedTexturePtrCntx , weakTexturePtrCntx ) where import Graphics.Urho3D.Container.Ptr import qualified Language.C.Inline as C import qualified Language.C.Inline.Context as C import qualified Language.C.Types as C import qualified Data.Map as Map data Texture textureCntx :: C.Context textureCntx = mempty { C.ctxTypesTable = Map.fromList [ (C.TypeName "Texture", [t| Texture |]) ] } sharedPtrImpl "Texture" sharedWeakPtrImpl "Texture"
Teaspot-Studio/Urho3D-Haskell
src/Graphics/Urho3D/Graphics/Internal/Texture.hs
mit
577
0
11
98
132
86
46
-1
-1
module Mood where data Mood = Blah | Woot deriving Show changeMood :: Mood -> Mood changeMood Blah = Woot changeMood _ = Blah
mikegehard/haskellBookExercises
chapter4/mood.hs
mit
136
0
5
34
42
24
18
5
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Monad (msum) import Happstack.Server import Web.Routes.Happstack (implSite) import BBQ.Route import Data.Accounts import Data.RecordPool import Data.Sheets import Data.AppConfig withAcid path action = openAccountsState path $ \st1 -> openRecordPools path $ \st2 -> openSheetsState path $ \st3 -> action $ AppConfig st1 st2 st3 main :: IO () main = do putStrLn "BBQ is listening on 8000." withAcid "_state" $ \acid -> simpleHTTP nullConf $ runApp acid server server :: App Response server = msum [ dir "images" $ serveDirectory DisableBrowsing [] "images" , dirs "static/css" $ serveDirectory DisableBrowsing [] "views/css" , dirs "static/js" $ serveDirectory DisableBrowsing [] "views/js" , implSite "https://bbq.yan.ac" "" site , notFound $ toResponse ("resource not found" :: String) ]
yan-ac/bbq.yan.ac
bbq.hs
mit
908
0
12
172
260
134
126
26
1
{-# htermination zipWithM :: (a -> b -> Maybe c) -> [a] -> [b] -> Maybe [c] #-} import Monad
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Monad_zipWithM_3.hs
mit
93
0
3
20
5
3
2
1
0
module Language.Lips.Evaluator where -------------------- -- Global Imports -- import Control.Monad.State (liftIO) import Control.Monad ------------------- -- Local Imports -- import Language.Lips.LanguageDef import Language.Lips.State ---------- -- Code -- -- Lifting an error liftError :: Error LipsVal -> LipsVal liftError (Success a) = a liftError (Error et) = LList [LAtom "println", LString $ displayErrorType et] -- Binding a variable eBind :: String -> LipsVal -> ProgramState (Error LipsVal) eBind name val = do evaled <- eval val pushVariable name evaled return $ Success lNull -- Dropping a variable eDrop :: String -> ProgramState (Error LipsVal) eDrop name = do exists <- hasVariable name case exists of False -> return $ Error VariableNotDefinedError True -> do dropVariable name return $ Success lNull -- Performing IO on a LipsVal performIO :: (LipsVal -> IO ()) -> LipsVal -> ProgramState (Error LipsVal) performIO fn val = do errval <- safeEval val case errval of Success val -> (liftIO $ fn val) >> (return $ Success lNull) Error et -> return $ Error et -- Printing a variable ePrint :: LipsVal -> ProgramState (Error LipsVal) ePrint = performIO $ putStr . show -- Printing a variable with a newline ePrintln :: LipsVal -> ProgramState (Error LipsVal) ePrintln = performIO $ putStrLn . show -- Re-evaluating an accessed variable eVarLookup :: String -> [LipsVal] -> ProgramState (Error LipsVal) eVarLookup name args = do hp <- hasPrimitive name if hp then mapM eval args >>= applyPrimitive name else do errval <- getVariable name case errval of Success val -> if null args then safeEval val else safeEval $ LList (val : args) Error et -> return $ Error et -- Applying an LFunction to its arguments eApply :: LipsVal -> [LipsVal] -> ProgramState (Error LipsVal) eApply (LFunction names val) args | length names /= length args = return $ Error InvalidFunctionApplicationError | otherwise = do let zipped = zip names args forM_ zipped (\(name, arg) -> eBind name arg) v <- safeEval val forM_ zipped (\(name, arg) -> eDrop name) return v -- Safely evaluating things safeEval :: LipsVal -> ProgramState (Error LipsVal) safeEval (LList [LAtom "bind" , LAtom name, val]) = eBind name val safeEval (LList [LAtom "drop" , LAtom name ]) = eDrop name safeEval (LList [LAtom "print" , val ]) = ePrint val safeEval (LList [LAtom "println" , val ]) = ePrintln val safeEval (LList [LAtom "quote" , val ]) = return $ Success val safeEval (LList (LAtom name : args )) = eVarLookup name args safeEval (LAtom name ) = eVarLookup name [] safeEval (LList (fn@(LFunction _ _): args )) = eApply fn args safeEval fn@(LFunction _ _ ) = return $ Success fn safeEval other = return $ Success other -- Evaluating a LipsVal (printing any error messages) eval :: LipsVal -> ProgramState LipsVal eval lval = do errval <- safeEval lval case errval of Success val -> return val Error et -> eval $ LList [LAtom "println", LString $ displayErrorType et]
crockeo/lips
src/lib/Language/Lips/Evaluator.hs
mit
3,307
0
17
857
1,087
534
553
70
4
-- {{{ {-# LANGUAGE OverloadedStrings, MultiWayIf, LambdaCase #-} module Main where ---------------------Import------------------------- import Prelude import Data.List import Data.Char import qualified Data.ByteString.Char8 as BS -- BS.getContents import qualified Data.Vector as V import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.HashMap as HM import qualified Data.Sequence as Seq import qualified Data.Foldable as Foldable import Control.Applicative import Data.Ratio -- x = 5%6 import Data.Maybe import Text.Regex.Posix import System.Random -- randomIO, randomRIO, randomRs, newStdGen import Data.Int -- Int32, Int64 import System.IO import Data.Bits -- (.&.), (.|.), shiftL... import Text.Printf -- printf "%0.6f" (1.0) import Control.Monad import System.Directory import System.FilePath import Data.Aeson import Control.Exception import System.Process -- runCommand -- }}} main :: IO () main = do return ()
abhiranjankumar00/dot-vim
skel/skel.hs
mit
1,115
0
8
280
184
122
62
30
1
-- :l C:\Local\Dev\haskell\h4c.hs -- Exemplos do tutorial http://www.haskell.org/haskellwiki/Haskell_Tutorial_for_C_Programmers -- 2.5 -- Uma implementação recursiva de fib que usa uma função auxiliar geradora fib :: Integer -> Integer fib n = fibGen 0 1 n fibGen :: Integer -> Integer -> Integer -> Integer fibGen a b n = case n of 0 -> a n -> fibGen b (a + b) (n - 1) -- Uma lista infinita de números de fibonacci fibs :: [Integer] fibs = 0 : 1 : [ a + b | (a, b) <- zip fibs (tail fibs) ] -- 3.3 -- Pequeno teste de aplicação de uma função que recebe dois parâmetros e retorna um terceiro apply' :: (a -> b -> c) -> a -> b -> c apply' f a b = f a b -- Aplica a função do tipo (a -> b) a todos os elementos de a gerando uma nova lista map' :: (a -> b) -> [a] -> [b] map' f xs = [ f x | x <- xs ] -- Versão recursiva de map mapRec :: (a -> b) -> [a] -> [b] mapRec f [] = [] mapRec f xs = f (head xs):(mapRec f (tail xs)) fooList :: [Int] fooList = [3, 1, 5, 4] bar :: Int -> Int bar n = n - 2 -- Ex: map bar fooList -- 3.4 subEachFromTen :: [Int] -> [Int] subEachFromTen = map (10 -) -- 4.1 -- Reimplementação de fib usando correspondência de padrão -- Foi necessário usar Num a, Eq a devido a uma alteração recente na linguagem em que Num não implica mais em Eq fibPat :: (Num a, Eq a, Num b, Eq b) => a -> b fibPat n = fibGenPat 0 1 n fibGenPat :: (Num a, Eq a, Num b, Eq b) => b -> b -> a -> b fibGenPat x _ 0 = x fibGenPat x y n = fibGenPat y (x + y) (n - 1) -- 4.2 showTime :: Int -> Int -> String showTime hours minutes | hours > 23 = error "Invalid hours" | minutes > 59 = error "Invalid minutes" | hours == 0 = showHour 12 "am" | hours <= 11 = showHour hours "am" | hours == 12 = showHour hours "pm" | otherwise = showHour (hours - 12) "pm" where showHour h s = (show h) ++ ":" ++ showMin ++ " " ++ s showMin | minutes < 10 = "0" ++ show minutes | otherwise = show minutes -- 4.3 showLen :: [a] -> String showLen lst = (show (theLen)) ++ (if theLen == 1 then " item" else " itens") where theLen = length lst -- 4.5 Lambda -- map (\x -> "the " ++ show x) [1, 2, 3, 4, 5] -- 4.6 Type constructors -- main = putStrLn (show 4) -- main = return () sayHello :: Maybe String -> String sayHello Nothing = "Hello!" sayHello (Just name) = "Hello, " ++ name ++ "!" -- Exemplos: sayHello Nothing, sayHello (Just "Felipo") -- 4.7 Monadas -- É uma forma de mesclar a programação "imperativa" (com estado, ordem de execução, resolução imediata, entrada/saída, etc.) com a programação funcional. someFunc :: Int -> Int -> [Int] someFunc a b = [a, b] main = do putStr "prompt 1: " a <- getLine putStr "prompt 2: " b <- getLine putStrLn (show (someFunc (read a) (read b))) -- Comandos depois da palavra-chave "do" devem estar alinhados para denotar um bloco test1 = do putStrLn "Sum 3 numbers" putStr "num 1: " a <- getLine putStr "num 2: " b <- getLine putStr "num 3: " c <- getLine putStrLn ("Result is " ++ (show ((read a) + (read b) + (read c)))) getName1 :: IO String getName1 = do putStr "Please enter your name: " name <- getLine putStrLn "Thank you. Please wait." return name getName2 :: IO String getName2 = do putStr "Please enter your name: " getLine {- O último código dentro de uma Monada deve ter o mesmo tipo de retorno da Monada :t getLine getLine :: IO String Em getName1 é realizado um retorno explícito de uma variável. Em getName2 é retornado o próprio valor retornado por getLine diretamente -} -- 5.1 Where are the for loops -- Como um "for" é escrito em haskell bar' :: Int -> Int bar' x = x*2 foo' :: [Int] -> [Int] foo' (x:xs) = bar' x : foo' xs foo' [] = [] -- Equivale a definir foo' = map bar' -- Muitos casos de "for" são escritos como map, foldr, foldl, sum, dentre outras funções de tratamento de lista de haskell altamente otimizadas -- Quando não for possível usar nenhum dos casos uma função recursiva deve resolver o problema. -- 5.2 Lazy Evaluation data Tree a = Null | Node a (Tree a) (Tree a) t1 :: Tree Int t1 = Node 3 (Node 2 Null Null) (Node 5 (Node 4 Null Null) Null) inOrderList :: Tree a -> [a] inOrderList Null = [] inOrderList (Node item left right) = inOrderList left ++ [item] ++ inOrderList right fooTree :: Int -> Tree Int fooTree n = Node n (fooTree (n - 1)) (fooTree (n + 1)) t2 = fooTree 0 inOrderListLevel :: Tree a -> Int -> [a] inOrderListLevel Null _ = [] inOrderListLevel _ 0 = [] inOrderListLevel (Node item left right) n = inOrderListLevel left (n - 1) ++ [item] ++ inOrderListLevel right (n - 1) fooTreeLevel :: Int -> Int -> Tree Int fooTreeLevel _ 0 = Null fooTreeLevel n l = Node n (fooTreeLevel (n - 1) (l - 1)) (fooTreeLevel (n + 1) (l - 1))
feliposz/learning-stuff
haskell/h4c.hs
mit
4,833
0
16
1,181
1,567
806
761
93
2
{-# LANGUAGE MultiParamTypeClasses #-} module LambdaLine.Segment (Segment(..) ) where import Data.Monoid class (Functor f, Monoid (f a)) => Segment f a where buildPrompt :: [f a] -> a -> a -> IO () mkSegment :: IO (Maybe a) -> f a stringToSegment :: a -> f a
josiah14/lambdaline
LambdaLine/Segment.hs
gpl-3.0
268
0
11
56
114
60
54
-1
-1
{---------------------------------------------------------------------} {- Copyright 2015, 2016 Nathan Bloomfield -} {- -} {- This file is part of Feivel. -} {- -} {- Feivel is free software: you can redistribute it and/or modify -} {- it under the terms of the GNU General Public License version 3, -} {- as published by the Free Software Foundation. -} {- -} {- Feivel is distributed in the hope that it will be useful, but -} {- WITHOUT ANY WARRANTY; without even the implied warranty of -} {- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -} {- GNU General Public License for more details. -} {- -} {- You should have received a copy of the GNU General Public License -} {- along with Feivel. If not, see <http://www.gnu.org/licenses/>. -} {---------------------------------------------------------------------} module Feivel.GUI.Strings where ui_name_string :: String ui_name_string = "Feivel" ui_version_string :: String ui_version_string = "0.2.2" ui_license_string :: String ui_license_string = "GNU GPLv3" ui_about_comment :: String ui_about_comment = "A simple templating language and interactive calculator.\n\n" ++ "Copyright 2014--2016 Nathan Bloomfield" ui_authors :: [String] ui_authors = [ "Nathan Bloomfield <[email protected]>" ]
nbloomf/feivel
src/Feivel/GUI/Strings.hs
gpl-3.0
1,677
0
5
591
84
58
26
17
1
{-# OPTIONS -Wall -Werror -Wwarn #-} {-# OPTIONS_GHC -funbox-strict-fields #-} {-# LANGUAGE FlexibleInstances #-} {- | Module : Data.Tree.UCT Copyright : Copyright (C) 2010 Fabian Linzberger License : GNU GPL, version 3 or above Maintainer : Fabian Linzberger <[email protected]> Stability : experimental Portability: probably UCT tree search using Data.Tree.Zipper for updates in the Tree -} module Data.Tree.UCT.GameTree ( UCTTreeLoc , UCTTree , UCTForest , UCTMove , MoveNode(..) , newMoveNode , RaveValue , RaveMap , newRaveMap , Count , Value -- , UctNode(..) -- , UctLabel(..) -- , defaultUctLabel ) where import Control.DeepSeq (NFData) import qualified Data.Map as M import Data.Tree (Forest, Tree (..)) import Data.Tree.Zipper (TreeLoc) import Text.Printf (printf) -- import Debug.TraceOrId (trace) type UCTTreeLoc a = TreeLoc (MoveNode a) type UCTTree a = Tree (MoveNode a) type UCTForest a = Forest (MoveNode a) type Value = Float -- type Value = Double type Count = Int class (Eq a, Show a) => UCTMove a data MoveNode a = MoveNode { nodeMove :: !a , nodeValue :: !Value , nodeVisits :: !Count } instance UCTMove a => NFData (MoveNode a) instance UCTMove a => NFData (TreeLoc (MoveNode a)) instance (UCTMove a) => Show (MoveNode a) where show node = "(" ++ show (nodeVisits node) ++ dStr ++ printf "/%.2f) " (nodeValue node) ++ show (nodeMove node) where dStr = "" -- dStr = case isDone label of -- True -> "+ " -- False -> "" instance (UCTMove a) => Eq (MoveNode a) where (==) a b = nodeMove a == nodeMove b -- instance (Show a) => Show (MoveNode a) where -- show node = show $ nodeMove node newMoveNode :: (UCTMove a) => a -> (Value, Count) -> UCTTree a newMoveNode move (value, visits) = -- trace ("newMoveNode: " ++ show (move, value, visits)) Node { rootLabel = MoveNode { nodeMove = move , nodeVisits = visits , nodeValue = value } , subForest = [] } type RaveValue = (Value, Count) type RaveMap a = M.Map a RaveValue newRaveMap :: (UCTMove a) => RaveMap a newRaveMap = M.empty -- class (Show a) => UctNode a where -- isTerminalNode :: a -> Bool -- finalResult :: a -> Float -- randomEvalOnce :: (RandomGen g) => a -> Rand g Float -- children :: a -> [a] -- instance (UctNode a) => Show (UctLabel a) where -- show label = -- show (nodeState label) ++ " " ++ -- printf "%.2f " (winningProb label) ++ -- show (visits label) ++ dStr ++ " - " -- where -- dStr = case isDone label of -- True -> "+ " -- False -> "" -- data UctLabel a = UctLabel { -- nodeState :: a -- ,winningProb :: Float -- ,visits :: Int -- ,isDone :: Bool -- } -- instance Eq (UctLabel a) where -- (==) a b = -- (winningProb a == winningProb b) -- && (visits a == visits b) -- && (isDone a == isDone b) -- defaultUctLabel :: UctLabel a -- defaultUctLabel = UctLabel { -- nodeState = undefined -- , winningProb = 0.5 -- -- , uctValue = 0.5 -- , visits = 1 -- , isDone = False -- }
lefant/kurt
src/Data/Tree/UCT/GameTree.hs
gpl-3.0
3,964
0
12
1,633
571
343
228
-1
-1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveDataTypeable #-} -- | Convert cmsearch output to Browser Extensible Data (BED) format -- Testcommand: cmsearchToBED -i /path/to/test.clustal module Main where import Prelude import System.Console.CmdArgs import Biobase.RNAlien.Library import Data.Either.Unwrap import qualified Data.ByteString.Char8 as B import qualified Data.Text as T import Data.List data Bed = Bed { browserPostition :: T.Text, browserSettings :: T.Text, bedName :: T.Text, bedDescription :: T.Text, bedVisibility :: Int, bedItemRgb :: Bool, bedEntries :: [BedEntry] } deriving (Eq, Read) instance Show Bed where show (Bed _browserPostition _browserSettings _bedName _bedDescription _bedVisibility _bedItemRgb _bedEntries) = a ++ b ++ c ++ d ++ e ++ f ++ g where a = "browser position " ++ T.unpack _browserPostition ++ "\n" b = T.unpack _browserSettings ++ "\n" c = "track name=\"" ++ T.unpack _bedName ++ "\" " d = "description=\"" ++ T.unpack _bedDescription ++ "\" " e = "visibility=" ++ show _bedVisibility ++ " " f = "itemRgb=\"" ++ itemRbg ++ "\"\n" itemRbg = if _bedItemRgb then "On" else "Off" g = concatMap show _bedEntries data BedEntry = BedEntry { chrom :: T.Text, chromStart :: Int, chromEnd :: Int, chromName :: Maybe T.Text, score :: Maybe Int, strand :: Maybe Char, thickStart :: Maybe Int, thickEnd :: Maybe Int, color :: Maybe T.Text, blockCount :: Maybe Int, blockSizes :: Maybe [Int], blockStarts :: Maybe [Int] } deriving (Eq, Read) instance Show BedEntry where show (BedEntry _chrom _chromStart _chromEnd _chromName _score _strand _thickStart _thickEnd _color _blockCount _blockSizes _blockStarts) = a ++ b ++ c ++ d ++ e ++ f ++ g ++ h ++ i ++ j ++ k ++ l where a = T.unpack _chrom ++ "\t" b = show _chromStart ++ "\t" c = show _chromEnd ++ "\t" d = maybe "" T.unpack _chromName ++ "\t" e = maybe "" show _score ++ "\t" f = maybe "" ((: [])) _strand ++ "\t" g = maybe "" show _thickStart ++ "\t" h = maybe "" show _thickEnd ++ "\t" i = maybe "" T.unpack _color ++ "\t" j = maybe "" show _blockCount ++ "\t" k = maybe "" (intercalate "," . map show) _blockSizes ++ "\t" l = maybe "" (intercalate "," . map show) _blockStarts ++ "\n" data Options = Options { cmsearchPath :: String, inputBrowserSettings :: String, inputBedVisibility :: Int, inputTrackName :: String, inputTrackDescription :: String, inputItemRgb :: Bool, inputTrackColor :: String, sortBed :: Bool, withHeader :: Bool } deriving (Show,Data,Typeable) options :: Options options = Options { cmsearchPath = def &= name "i" &= help "Path to input cmsearch file", inputBrowserSettings = "browser hide all" &= name "b" &= help "Browser settings. Default: browser hide all", inputBedVisibility = (2 :: Int) &= name "y" &= help "Visibility setting of track. Default: 2", inputTrackName = "PredictedRNA" &= name "n" &= help "Name of the track Default: PredictedRNA", inputTrackDescription = "RNA loci predicted by cmsearch" &= name "d" &= help "Description of the track. Default: RNA loci predicted by cmsearch", inputItemRgb = True &= name "r" &= help "RGB Color of the track. Default: True", inputTrackColor = "255,0,0" &= name "c" &= help "RGB Color of the track. Default: 255,0,0", sortBed = True &= name "s" &= help "Sort entries of Bed file by start end end cooridinates. Default: True", withHeader = True &= name "w" &= help "Output contains bed header. Default: True" } &= summary "cmsearchToBED - Converts cmsearch file hits to BED file entries" &= help "Florian Eggenhofer 2016" &= verbosity main :: IO () main = do Options{..} <- cmdArgs options parsedCmsearch <- readCMSearch cmsearchPath if isRight parsedCmsearch then do let outputBED = convertcmSearchToBED (fromRight parsedCmsearch) inputBrowserSettings inputTrackName inputTrackDescription inputTrackColor inputBedVisibility inputItemRgb sortBed if isRight outputBED then if withHeader then print (fromRight outputBED) else do let output = concatMap show (bedEntries (fromRight outputBED)) putStr output else putStr (fromLeft outputBED) else putStr ("A problem occured converting from cmsearch to BED format:\n " ++ show (fromLeft parsedCmsearch)) --convertcmSearchToBED :: CMsearch -> String -> String -> Either String String --convertcmSearchToBED inputcmsearch trackName trackColor -- | null cmHits = Left "cmsearch file contains no hits" -- | otherwise = Right (bedHeader ++ bedEntries) -- where cmHits = cmsearchHits inputcmsearch -- bedHeader = "browser position " ++ browserPosition ++ "\nbrowser hide all\ntrack name=\"cmsearch hits\" description=\"cmsearch hits\" visibility=2 itemRgb=\"On\"\n" -- bedEntries = concatMap (cmsearchHitToBEDentry trackName trackColor) cmHits -- browserPosition = L.unpack (hitSequenceHeader firstHit) ++ ":" ++ entryStart firstHit ++ "-" ++ entryEnd firstHit -- firstHit = (head cmHits) convertcmSearchToBED :: CMsearch -> String -> String -> String -> String -> Int -> Bool -> Bool -> Either String Bed convertcmSearchToBED inputcmsearch inputBrowserSettings trackName trackDescription trackColor inputBedVisibility inputItemRgb sortBed | null cmHits = Left "cmsearch file contains no hits" | otherwise = Right bed where cmHits = cmsearchHits inputcmsearch --bedHeader = "browser position " ++ browserPosition ++ "\nbrowser hide all\ntrack name=\"cmsearch hits\" description=\"cmsearch hits\" visibility=2 itemRgb=\"On\"\n" bedEntries = map (cmsearchHitToBEDentry trackName trackColor) cmHits sortedBedEntries = if sortBed then sortBy orderBedEntry bedEntries else bedEntries currentBrowserPosition = T.unpack (chrom firstEntry) ++ ":" ++ show (chromStart firstEntry) ++ "-" ++ show (chromEnd firstEntry) firstEntry = head sortedBedEntries bed = Bed (T.pack currentBrowserPosition) (T.pack inputBrowserSettings) (T.pack trackName) (T.pack trackDescription) inputBedVisibility inputItemRgb sortedBedEntries cmsearchHitToBEDentry :: String -> String -> CMsearchHit -> BedEntry cmsearchHitToBEDentry hitName hitColor cmHit = entry where entry = BedEntry chromosome entrystart entryend (Just (T.pack hitName)) entryscore entrystrand thickstart thickend entrycolor blocks blockSize blockStart chromosome = T.pack (B.unpack (hitSequenceHeader cmHit)) --entryline = L.unpack (hitSequenceHeader cmHit) ++ "\t" ++ entryStart cmHit ++ "\t" ++ entryEnd cmHit++ "\t" ++ (hitName) ++ "\t" ++ "0" ++ "\t" ++ [(hitStrand cmHit)] ++ "\t" ++ show (hitStart cmHit) ++ "\t" ++ show (hitEnd cmHit) ++ "\t" ++ hitColor ++ "\n" entrystart = if hitStrand cmHit == '+' then hitStart cmHit else hitEnd cmHit entryend = if hitStrand cmHit == '+' then hitEnd cmHit else hitStart cmHit entryscore = Just (0 :: Int) entrystrand = Just (hitStrand cmHit) thickstart = Just entrystart thickend = Just entryend entrycolor = Just (T.pack hitColor) blocks = Just (1 :: Int) blockSize = Just [entryend - entrystart] blockStart = Just [0 :: Int] --cmsearchHitToBEDentry :: String -> String -> CMsearchHit -> String --cmsearchHitToBEDentry hitName hitColor cmHit = entryline -- where entryline = L.unpack (hitSequenceHeader cmHit) ++ "\t" ++ entryStart cmHit ++ "\t" ++ entryEnd cmHit++ "\t" ++ (hitName) ++ "\t" ++ "0" ++ "\t" ++ [(hitStrand cmHit)] ++ "\t" ++ show (hitStart cmHit) ++ "\t" ++ show (hitEnd cmHit) ++ "\t" ++ hitColor ++ "\n" --entrystart = if (hitStrand cmHit) == '+' then show (hitStart cmHit) else show (hitEnd cmHit) --entryend = if (hitStrand cmHit) == '+' then show (hitEnd cmHit) else show (hitStart cmHit) entryStart :: CMsearchHit -> String entryStart cmHit | hitStrand cmHit == '+' = show (hitStart cmHit) | otherwise = show (hitEnd cmHit) entryEnd :: CMsearchHit -> String entryEnd cmHit | hitStrand cmHit == '+' = show (hitEnd cmHit) | otherwise = show (hitStart cmHit) orderBedEntry :: BedEntry -> BedEntry -> Ordering orderBedEntry firstHit secondHit | start1 > start2 = GT | start1 < start2 = LT | otherwise = orderBedEntryEnd firstHit secondHit where start1 = chromStart firstHit start2 = chromStart secondHit orderBedEntryEnd :: BedEntry -> BedEntry -> Ordering orderBedEntryEnd firstHit secondHit | end1 > end2 = GT | end1 < end2 = LT | otherwise = EQ where end1 = chromEnd firstHit end2 = chromEnd secondHit
eggzilla/RNAlien
Biobase/cmsearchToBED.hs
gpl-3.0
8,855
0
21
1,950
1,997
1,037
960
141
4
-- brainfuck.hs -- A simple brainfuck interpreter. -- Written by Andreas Hammar <[email protected]> -- -- This is free and unencumbered software released into the public domain. -- See the UNLICENSE file for details. module Main where import Control.Monad.Error import Data.ByteString.Internal import Data.Char import Data.Word import System.Console.GetOpt import System.Environment import System.Exit import System.IO import Text.ParserCombinators.Parsec data Instruction = MoveRight -- > | MoveLeft -- < | Increment -- + | Decrement -- - | ReadByte -- , | WriteByte -- . | Loop [Instruction] -- [] -- Parsing simple ch ins = do char ch return ins moveRight = simple '>' MoveRight moveLeft = simple '<' MoveLeft increment = simple '+' Increment decrement = simple '-' Decrement readByte = simple ',' ReadByte writeByte = simple '.' WriteByte loop = do char '[' instructions <- many instruction char ']' return $ Loop instructions instruction = (moveRight <|> moveLeft <|> increment <|> decrement <|> readByte <|> writeByte <|> loop) program = many instruction parseProgram input = case parse program "brainfuck" source of Left err -> throwError $ Parser err Right prog -> return prog where source = filter (`elem` "<>+-,.[]") input -- Execution type Byte = Word8 type Environment = ([Byte], Byte, [Byte]) cleanEnvironment = (zeroes, 0, zeroes) where zeroes = 0 : zeroes exec (x:xs, y, zs) MoveLeft = return $ (xs, x, y:zs) exec (xs, y, z:zs) MoveRight = return $ (y:xs, z, zs) exec (xs, y, zs) Increment = return $ (xs, y+1, zs) exec (xs, y, zs) Decrement = return $ (xs, y-1, zs) exec env@(_, y, _) WriteByte = putChar (w2c y) >> return env exec (xs, _, zs) ReadByte = do ch <- getChar return $ (xs, c2w ch, zs) exec env@(_, 0, _) (Loop is) = return env exec env@(_, _, _) l@(Loop is) = do newEnv <- foldM exec env is exec newEnv l runProgram = do foldM_ exec cleanEnvironment -- Command line nterface data Flag = Version | Help deriving (Eq, Ord, Enum, Show, Bounded) flags = [ Option [] ["version"] (NoArg Version) "Print version information and exit.", Option [] ["help"] (NoArg Help) "Print this help message and exit."] parseArgs argv = case getOpt Permute flags argv of (args, fs, []) -> do if null fs || Help `elem` args then do hPutStrLn stderr (usageInfo header flags) exitWith ExitSuccess else if Version `elem` args then do hPutStrLn stderr version exitWith ExitSuccess else return fs (_, _, errs) -> do hPutStrLn stderr (concat errs ++ usageInfo header flags) exitWith (ExitFailure 1) where header = "Usage: brainfuck [OPTION] [FILE] ..." version = "brainfuck.hs v1.0" runFile file = do contents <- readFile file case parseProgram contents of Left err -> print err Right val -> runProgram val main = do files <- getArgs >>= parseArgs mapM_ runFile files -- Error handling data BrainfuckError = Parser ParseError | Default String showError (Parser err) = "Parse error at " ++ show err showError (Default msg) = msg instance Show BrainfuckError where show = showError instance Error BrainfuckError where noMsg = Default "An unknown error occurred." strMsg = Default type ThrowsError = Either BrainfuckError
ahammar/Brainfuck.hs
brainfuck.hs
unlicense
3,662
0
15
1,056
1,134
604
530
92
4
module StringCalculator ( toInt, add, add2, add3, add4 ) where import Data.String.Utils import Data.Maybe import Text.Regex -- Problem 1: Be able to add integers given in a string, separated by commas. -- Just the following cases: -- "a" -> n -- "a,b" -> n+m -- "a,b,c" -> a+b+c toInt :: [Char] -> Int toInt xs | isJust (matchRegex intRegex xs) = (read xs) :: Int | otherwise = error $ xs ++ " is not an integer" where intRegex = mkRegex "^[-]?[0-9]+$" add :: [Char] -> Int add xs = foldl1 (+) $ map toInt $ split "," xs -- Problem 2: Allow an undefined number of integers. -- Examples: -- "1,2,3,4,5" -> 15 -- "10,20,30,40,50" -> 150 -- "3,3,3,3,3,3,3,3" -> 24 add2 = add -- We are happy! :D -- Problem 3: Allow an optional parametrizable 1 character delimiter. -- When given a delimiter, it should precede the string of integers with -- the following format: -- "//[delimiter]\n[string_of_integers_with_delimiter]" -- where [delimiter] can be any character. -- when given no delimiter, "," is assumed. add3 :: [Char] -> Int add3 ('/':'/':delim:'\n':xs) = mkAdd3 [delim] xs add3 xs = mkAdd3 "," xs mkAdd3 delimiter = foldl1 (+) . map toInt . (split delimiter) -- Problem 4: It should reject negative numbers. -- When given one negative number within the list of integers. It should throw an error. -- When given >1 negative numbers, it should return the list of all given negative numbers. add4 :: [Char] -> Either Int [Int] add4 ('/':'/':delim:'\n':xs) = addIntsFromStr [delim] xs add4 xs = addIntsFromStr "," xs addIntsFromStr :: [Char] -> [Char] -> Either Int [Int] addIntsFromStr delimiter xs | length listOfNegatives == 0 = Left $ foldl1 (+) $ listOfInts xs | length listOfNegatives == 1 = error $ "error: " ++ show (head listOfNegatives) | otherwise = Right listOfNegatives where listOfInts xy = map toInt . (split delimiter) $ xy listOfNegatives = filter (<0) $ listOfInts xs
LambdaMx/haskelldojo
session_1/StringCalculator.hs
unlicense
2,010
0
10
449
491
261
230
27
1
import System.Random (StdGen, getStdGen, randoms) import Data.Array.Repa import Data.Array.Repa.Operators.Reduction import Data.Array.Repa.Eval import Control.Monad.Identity import Criterion.Main import Control.DeepSeq main = do input <- randomInts count `fmap` getStdGen let inputArray = fromList (Z:.count) input print $ buySellPar inputArray where count = 12500 {- main = do input <- randomInts count `fmap` getStdGen let inputArray = fromList (Z:.count) input print $ buySellPar inputArray where count = 20000 -} buySellPar :: Array U DIM1 Int -> (Int,Int,Int) buySellPar prices = runIdentity $ do let profits = createProfitMatrix prices bestPerBuyDay <- foldP maxByProfit (0,0,0) profits result <- foldP (flip maxByProfit) (0,0,0) bestPerBuyDay return $ result ! Z buySellSeq :: Array U DIM1 Int -> (Int,Int,Int) buySellSeq prices = result ! Z where result = foldS (flip maxByProfit) (0,0,0) $ foldS maxByProfit (0,0,0) $ createProfitMatrix prices createProfitMatrix :: Array U DIM1 Int -> Array D DIM2 (Int, Int, Int) createProfitMatrix prices = fromFunction (Z:.n:.n) f where Z:.n = extent prices f (Z:.i1:.i2) | i1 >= i2 = (0,0,0) | otherwise = (i1,i2, (prices ! (Z:.i2)) - (prices ! (Z:.i1)) ) maxByProfit :: (Int, Int, Int) -> (Int, Int, Int) -> (Int, Int, Int) maxByProfit t1@(_,_,p1) t2@(_,_,p2) | p1 >= p2 = t1 | otherwise = t2 randomInts :: Int -> StdGen -> [Int] randomInts k g = let result = take k (randoms g) in force result `seq` result
weeeeeew/petulant-cyril
lab_B/Main.hs
unlicense
1,590
0
13
357
624
337
287
32
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} module Main where import Data.Foldable (traverse_) import Data.Text (Text) import Data.Default import Data.Memory.Types import Data.Memory.DB.Acid import Text.Blaze.Html5 (Html, (!), toHtml) import Clay ((?)) import Happstack.Foundation import qualified Data.Map as M import qualified Data.Text.Lazy.Encoding as LazyT import qualified Data.ByteString.Char8 as B import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import qualified Clay as C instance PathInfo a => PathInfo [a] where toPathSegments = concat . fmap toPathSegments fromPathSegments = many fromPathSegments instance ToMessage C.Css where toContentType _ = B.pack "text/css; charset=UTF-8" toMessage = LazyT.encodeUtf8 . C.render data Route = Search | Css | NewNode [NodeID] Text | ViewNode [NodeID] $(derivePathInfo ''Route) type Memory' = FoundationT' Route MemoryAcid () IO type Memory = XMLGenT Memory' type MemoryForm = FoundationForm Route MemoryAcid () IO instance (Functor m, Monad m) => HasAcidState (FoundationT' url MemoryAcid s m) Node where getAcidState = acidMemory <$> getAcidSt outputNode :: [NodeID] -> Node -> Html outputNode xs (Node nData nMap) = H.div ! A.class_ "box" $ do H.a ! A.href href $ toHtml (nodeText nData) traverse_ f (M.toAscList nMap) where href = H.toValue $ toPathInfo (ViewNode xs) f (nnID, nn) = outputNode (xs ++ [nnID]) nn route :: Route -> Memory Response route Search = ok $ toResponse $ template "Search" $ H.h1 "Search" route (NewNode xs text) = update (UInsertNode node xs) >>= \case Nothing -> internalServerError $ toResponse $ template "Internal Server Error" $ "Failed to insert node" Just node -> ok $ toResponse $ template "New Node" $ H.pre $ outputNode xs node where node = def { nodeData = def { nodeText = text } } route (ViewNode xs) = query (QLookupNode xs) >>= \case Nothing -> internalServerError $ toResponse $ template "Internal Server Error" $ "Failed to lookup node" Just node -> ok $ toResponse $ template "View Node" $ H.pre $ outputNode xs node route Css = ok (toResponse css) main :: IO () main = withAcid $ \root -> do simpleApp id defaultConf (AcidUsing root) () Search "" route template :: Text -> Html -> Html template title body = H.docTypeHtml $ do H.head $ do H.title (toHtml title) H.link ! A.type_ "text/css" ! A.rel "stylesheet" ! A.href (H.toValue $ toPathInfo Css) H.body $ do body css :: C.Css css = do ".box" ? do C.padding (C.px 3) (C.px 5) (C.px 3) (C.px 5) C.background (C.rgba 20 24 30 10)
shockkolate/brainfart
examples/basic/Main.hs
apache-2.0
2,914
0
15
655
979
514
465
71
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeOperators #-} module Camfort.Specification.StencilsSpec (spec) where import Control.Monad.Writer.Strict hiding (Sum, Product) import Data.List import Camfort.Helpers.Vec import Camfort.Input import Camfort.Specification.Stencils import Camfort.Specification.Stencils.Synthesis import Camfort.Specification.Stencils.Model import Camfort.Specification.Stencils.InferenceBackend import Camfort.Specification.Stencils.InferenceFrontend import Camfort.Specification.Stencils.Syntax import qualified Language.Fortran.AST as F import Language.Fortran.ParserMonad import Camfort.Reprint import Camfort.Output import qualified Data.IntMap as IM import qualified Data.Set as S import Data.Functor.Identity import qualified Data.ByteString.Char8 as B import System.FilePath import Test.Hspec import Test.QuickCheck spec :: Spec spec = describe "Stencils" $ do describe "Some checks on containing spans" $ do it "(0)" $ containedWithin (Cons 1 (Cons 1 Nil), Cons 2 (Cons 2 Nil)) (Cons 0 (Cons 0 Nil), Cons 3 (Cons 3 Nil)) `shouldBe` True it "(1)" $ containedWithin (Cons 0 (Cons 0 Nil), Cons 3 (Cons 3 Nil)) (Cons 1 (Cons 1 Nil), Cons 2 (Cons 2 Nil)) `shouldBe` False it "(2)" $ containedWithin (Cons 2 (Cons 2 Nil), Cons 2 (Cons 2 Nil)) (Cons 1 (Cons 1 Nil), Cons 2 (Cons 2 Nil)) `shouldBe` True it "(3)" $ containedWithin (Cons 2 (Cons 2 Nil), Cons 3 (Cons 3 Nil)) (Cons 1 (Cons 1 Nil), Cons 2 (Cons 2 Nil)) `shouldBe` False it "(4)" $ containedWithin (Cons 2 Nil, Cons 2 Nil) (Cons 2 Nil, Cons 2 Nil) `shouldBe` True it "sorting on indices" $ shouldBe (sort [ Cons 1 (Cons 2 (Cons 1 Nil)) , Cons 2 (Cons 2 (Cons 3 Nil)) , Cons 1 (Cons 3 (Cons 3 Nil)) , Cons 0 (Cons 3 (Cons 1 Nil)) , Cons 1 (Cons 0 (Cons 2 Nil)) , Cons 1 (Cons 1 (Cons 1 Nil)) , Cons 2 (Cons 1 (Cons 1 Nil)) ]) ([ Cons 1 (Cons 1 (Cons 1 Nil)) , Cons 2 (Cons 1 (Cons 1 Nil)) , Cons 1 (Cons 2 (Cons 1 Nil)) , Cons 0 (Cons 3 (Cons 1 Nil)) , Cons 1 (Cons 0 (Cons 2 Nil)) , Cons 2 (Cons 2 (Cons 3 Nil)) , Cons 1 (Cons 3 (Cons 3 Nil)) ] :: [Vec (S (S (S Z))) Int]) it "composeRegions (1,0)-(1,0) span and (2,0)-(2,0) span" $ shouldBe (coalesce (Cons 1 (Cons 0 Nil), Cons 1 (Cons 0 Nil)) (Cons 2 (Cons 0 Nil), Cons 2 (Cons 0 Nil))) $ Just (Cons 1 (Cons 0 Nil), Cons 2 (Cons 0 Nil)) it "composeRegions failing on (1,0)-(2,0) span and (4,0)-(5,0) span" $ shouldBe (coalesce (Cons 1 (Cons 0 Nil), Cons 2 (Cons 0 Nil)) (Cons 4 (Cons 0 Nil), Cons 5 (Cons 0 Nil))) Nothing it "composeRegions failing on (1,0)-(2,0) span and (3,1)-(3,1) span" $ shouldBe (coalesce (Cons 1 (Cons 0 Nil), Cons 2 (Cons 0 Nil)) (Cons 3 (Cons 1 Nil), Cons 3 (Cons 1 Nil))) Nothing it "five point stencil 2D" $ -- Sort the expected value for the sake of easy equality shouldBe (sort $ inferMinimalVectorRegions fivepoint) (sort [ (Cons (-1) (Cons 0 Nil), Cons 1 (Cons 0 Nil)) , (Cons 0 (Cons (-1) Nil), Cons 0 (Cons 1 Nil)) ]) it "seven point stencil 3D" $ shouldBe (sort $ inferMinimalVectorRegions sevenpoint) (sort [ (Cons (-1) (Cons 0 (Cons 0 Nil)), Cons 1 (Cons 0 (Cons 0 Nil))) , (Cons 0 (Cons (-1) (Cons 0 Nil)), Cons 0 (Cons 1 (Cons 0 Nil))) , (Cons 0 (Cons 0 (Cons (-1) Nil)), Cons 0 (Cons 0 (Cons 1 Nil))) ]) describe "Example stencil inferences" $ do it "five point stencil 2D" $ inferFromIndicesWithoutLinearity (VL fivepoint) `shouldBe` (Specification $ Mult $ Exact $ Spatial (Sum [ Product [ Centered 1 1 True, Centered 0 2 True] , Product [ Centered 0 1 True, Centered 1 2 True] ])) it "seven point stencil 2D" $ inferFromIndicesWithoutLinearity (VL sevenpoint) `shouldBe` (Specification $ Mult $ Exact $ Spatial (Sum [ Product [ Centered 1 1 True, Centered 0 2 True, Centered 0 3 True] , Product [ Centered 0 1 True, Centered 1 2 True, Centered 0 3 True] , Product [ Centered 0 1 True, Centered 0 2 True, Centered 1 3 True] ])) it "five point stencil 2D with blip" $ inferFromIndicesWithoutLinearity (VL fivepointErr) `shouldBe` (Specification $ Mult $ Exact $ Spatial (Sum [ Product [ Centered 1 1 True, Centered 0 2 True], Product [ Centered 0 1 True, Centered 1 2 True], Product [ Forward 1 1 True, Forward 1 2 True] ])) it "centered forward" $ inferFromIndicesWithoutLinearity (VL centeredFwd) `shouldBe` (Specification $ Mult $ Exact $ Spatial (Sum [ Product [ Forward 1 1 True , Centered 1 2 True] ])) describe "2D stencil verification" $ mapM_ (test2DSpecVariation (Neighbour "i" 0) (Neighbour "j" 0)) variations describe "2D stencil verification relative" $ mapM_ (\(a, b, x, y) -> test2DSpecVariation a b (x, y)) variationsRel describe "3D stencil verification" $ mapM_ test3DSpecVariation variations3D describe ("Synthesising indexing expressions from offsets is inverse to" ++ "extracting offsets from indexing expressions; and vice versa") $ it "isomorphism" $ property prop_extract_synth_inverse describe "Inconsistent induction variable usage tests" $ do it "consistent (1) a(i,j) = b(i+1,j+1) + b(i,j)" $ indicesToSpec' ["i", "j"] [Neighbour "i" 0, Neighbour "j" 0] [[offsetToIx "i" 1, offsetToIx "j" 1], [offsetToIx "i" 0, offsetToIx "j" 0]] `shouldBe` (Just $ Specification $ Once $ Exact (Spatial (Sum [Product [Forward 1 1 False, Forward 1 2 False], Product [Centered 0 1 True, Centered 0 2 True]]))) it "consistent (2) a(i,c,j) = b(i,j+1) + b(i,j) \ \:: forward(depth=1,dim=2)*pointed(dim=1)" $ indicesToSpec' ["i", "j"] [Neighbour "i" 0, Constant (F.ValInteger "0"), Neighbour "j" 0] [[offsetToIx "i" 0, offsetToIx "j" 1], [offsetToIx "i" 0, offsetToIx "j" 0]] `shouldBe` (Just $ Specification $ Once $ Exact (Spatial (Sum [Product [Centered 0 1 True, Forward 1 2 True]]))) it "consistent (3) a(i+1,c,j) = b(j,i+1) + b(j,i) \ \:: backward(depth=1,dim=2)*pointed(dim=1)" $ indicesToSpec' ["i", "j"] [Neighbour "i" 1, Constant (F.ValInteger "0"), Neighbour "j" 0] [[offsetToIx "j" 0, offsetToIx "i" 1], [offsetToIx "j" 0, offsetToIx "i" 0]] `shouldBe` (Just $ Specification $ Once $ Exact (Spatial (Sum [Product [Centered 0 1 True, Backward 1 2 True]]))) it "consistent (4) a(i+1,j) = b(0,i+1) + b(0,i) \ \:: backward(depth=1,dim=2)" $ indicesToSpec' ["i", "j"] [Neighbour "i" 1, Neighbour "j" 0] [[offsetToIx "j" absoluteRep, offsetToIx "i" 1], [offsetToIx "j" absoluteRep, offsetToIx "i" 0]] `shouldBe` (Just $ Specification $ Once $ Exact (Spatial (Sum [Product [Backward 1 2 True]]))) it "consistent (5) a(i) = b(i,i+1) \ \:: pointed(dim=1)*forward(depth=1,dim=2,nonpointed)" $ indicesToSpec' ["i", "j"] [Neighbour "i" 0] [[offsetToIx "i" 0, offsetToIx "i" 1]] `shouldBe` (Just $ Specification $ Once $ Exact (Spatial (Sum [Product [Centered 0 1 True, Forward 1 2 False]]))) it "consistent (6) a(i) = b(i) + b(0) \ \:: pointed(dim=1)" $ indicesToSpec' ["i", "j"] [Neighbour "i" 0] [[offsetToIx "i" 0], [offsetToIx "i" absoluteRep]] `shouldBe` Nothing it "inconsistent (1) RHS" $ indicesToSpec' ["i", "j"] [Neighbour "i" 0, Neighbour "j" 0] [[offsetToIx "i" 1, offsetToIx "j" 1], [offsetToIx "j" 0, offsetToIx "i" 0]] `shouldBe` Nothing it "inconsistent (2) RHS to LHS" $ indicesToSpec' ["i", "j"] [Neighbour "i" 0] [[offsetToIx "i" 1, offsetToIx "j" 1], [offsetToIx "j" 0, offsetToIx "i" 0]] `shouldBe` Nothing ------------------------- -- Some integration tests ------------------------- let fixturesDir = "tests" </> "fixtures" </> "Specification" </> "Stencils" example2In = fixturesDir </> "example2.f" program <- runIO $ readParseSrcDir example2In [] describe "integration test on inference for example2.f" $ do it "stencil infer" $ fst (callAndSummarise (infer AssignMode '=') program) `shouldBe` "\ntests/fixtures/Specification/Stencils/example2.f\n\ \(32:7)-(32:26) stencil readOnce, (backward(depth=1, dim=1)) :: a\n\ \(26:8)-(26:29) stencil readOnce, (pointed(dim=1))*(pointed(dim=2)) :: a\n\ \(24:8)-(24:53) stencil readOnce, (pointed(dim=1))*(centered(depth=1, dim=2)) \ \+ (centered(depth=1, dim=1))*(pointed(dim=2)) :: a\n\ \(41:8)-(41:94) stencil readOnce, (centered(depth=1, dim=2)) \ \+ (centered(depth=1, dim=1)) :: a" it "stencil check" $ fst (callAndSummarise (\f p -> (check f p, p)) program) `shouldBe` "\ntests/fixtures/Specification/Stencils/example2.f\n\ \(23:1)-(23:82) Correct.\n(31:1)-(31:56) Correct." let example4In = fixturesDir </> "example4.f" program <- runIO $ readParseSrcDir example4In [] describe "integration test on inference for example4.f" $ it "stencil infer" $ fst (callAndSummarise (infer AssignMode '=') program) `shouldBe` "\ntests/fixtures/Specification/Stencils/example4.f\n\ \(6:8)-(6:33) stencil readOnce, (pointed(dim=1)) :: x" let example5oldStyleFile = fixturesDir </> "example5.f" example5oldStyleExpected = fixturesDir </> "example5.expected.f" example5newStyleFile = fixturesDir </> "example5.f90" example5newStyleExpected = fixturesDir </> "example5.expected.f90" program5old <- runIO $ readParseSrcDir example5oldStyleFile [] program5oldSrc <- runIO $ readFile example5oldStyleFile synthExpectedSrc5Old <- runIO $ readFile example5oldStyleExpected program5new <- runIO $ readParseSrcDir example5newStyleFile [] program5newSrc <- runIO $ readFile example5newStyleFile synthExpectedSrc5New <- runIO $ readFile example5newStyleExpected describe "integration test on inference for example5" $ do describe "stencil synth" $ do it "inserts correct comment types for old fortran" $ (B.unpack . runIdentity $ reprint (refactoring Fortran77) (snd . head . snd $ synth AssignMode '=' (map (\(f, _, p) -> (f, p)) program5old)) (B.pack program5oldSrc)) `shouldBe` synthExpectedSrc5Old it "inserts correct comment types for modern fortran" $ (B.unpack . runIdentity $ reprint (refactoring Fortran90) (snd . head . snd $ synth AssignMode '=' (map (\(f, _, p) -> (f, p)) program5new)) (B.pack program5newSrc)) `shouldBe` synthExpectedSrc5New -- Indices for the 2D five point stencil (deliberately in an odd order) fivepoint = [ Cons (-1) (Cons 0 Nil), Cons 0 (Cons (-1) Nil) , Cons 1 (Cons 0 Nil) , Cons 0 (Cons 1 Nil), Cons 0 (Cons 0 Nil) ] -- Indices for the 3D seven point stencil sevenpoint = [ Cons (-1) (Cons 0 (Cons 0 Nil)), Cons 0 (Cons (-1) (Cons 0 Nil)) , Cons 0 (Cons 0 (Cons 1 Nil)), Cons 0 (Cons 1 (Cons 0 Nil)) , Cons 1 (Cons 0 (Cons 0 Nil)), Cons 0 (Cons 0 (Cons (-1) Nil)) , Cons 0 (Cons 0 (Cons 0 Nil)) ] centeredFwd = [ Cons 1 (Cons 0 Nil), Cons 0 (Cons 1 Nil), Cons 0 (Cons (-1) Nil) , Cons 1 (Cons 1 Nil), Cons 0 (Cons 0 Nil), Cons 1 (Cons (-1) Nil) ] :: [ Vec (S (S Z)) Int ] -- Examples of unusal patterns fivepointErr = [ Cons (-1) (Cons 0 Nil) , Cons 0 (Cons (-1) Nil) , Cons 1 (Cons 0 Nil) , Cons 0 (Cons 1 Nil) , Cons 0 (Cons 0 Nil) , Cons 1 (Cons 1 Nil) ] :: [ Vec (S (S Z)) Int ] {- Construct arbtirary vectors and test up to certain sizes -} instance {-# OVERLAPPING #-} Arbitrary a => Arbitrary (Vec Z a) where arbitrary = return Nil instance (Arbitrary (Vec n a), Arbitrary a) => Arbitrary (Vec (S n) a) where arbitrary = do x <- arbitrary xs <- arbitrary return $ Cons x xs test2DSpecVariation a b (input, expectation) = it ("format=" ++ show input) $ -- Test inference indicesToSpec' ["i", "j"] [a, b] (map fromFormatToIx input) `shouldBe` Just expectedSpec where expectedSpec = Specification expectation fromFormatToIx [ri,rj] = [ offsetToIx "i" ri, offsetToIx "j" rj ] indicesToSpec' ivs lhs = fst . runWriter . indicesToSpec ivmap "a" lhs where ivmap = IM.singleton 0 (S.fromList ivs) variations = [ ( [ [0,0] ] , Once $ Exact $ Spatial (Sum [Product [ Centered 0 1 True, Centered 0 2 True]]) ) , ( [ [1,0] ] , Once $ Exact $ Spatial (Sum [Product [Forward 1 1 False, Centered 0 2 True]]) ) , ( [ [1,0], [0,0], [0,0] ] , Mult $ Exact $ Spatial (Sum [Product [Forward 1 1 True, Centered 0 2 True]]) ) , ( [ [0,1], [0,0] ] , Once $ Exact $ Spatial (Sum [Product [Centered 0 1 True, Forward 1 2 True]]) ) , ( [ [1,1], [0,1], [1,0], [0,0] ] , Once $ Exact $ Spatial (Sum [Product [Forward 1 1 True, Forward 1 2 True]]) ) , ( [ [-1,0], [0,0] ] , Once $ Exact $ Spatial (Sum [Product [Backward 1 1 True, Centered 0 2 True]]) ) , ( [ [0,-1], [0,0], [0,-1] ] , Mult $ Exact $ Spatial (Sum [Product [Centered 0 1 True, Backward 1 2 True]]) ) , ( [ [-1,-1], [0,-1], [-1,0], [0,0], [0, -1] ] , Mult $ Exact $ Spatial (Sum [Product [Backward 1 1 True, Backward 1 2 True]]) ) , ( [ [0,-1], [1,-1], [0,0], [1,0], [1,1], [0,1] ] , Once $ Exact $ Spatial $ Sum [ Product [ Forward 1 1 True, Centered 1 2 True] ] ) -- Stencil which is non-contiguous in one direction , ( [ [0, 4], [1, 4] ] , Once $ Bound Nothing (Just (Spatial (Sum [ Product [ Forward 1 1 True , Forward 4 2 False ] ]))) ) ] variationsRel = [ -- Stencil which has non-relative indices in one dimension (Neighbour "i" 0, Constant (F.ValInteger "0"), [ [0, absoluteRep], [1, absoluteRep] ] , Once $ Exact $ Spatial (Sum [Product [Forward 1 1 True]]) ) , (Neighbour "i" 1, Neighbour "j" 0, [ [0,0] ] , Once $ Exact $ Spatial (Sum [Product [ Backward 1 1 False, Centered 0 2 True]]) ) , (Neighbour "i" 0, Neighbour "j" 1, [ [0,1] ] , Once $ Exact $ Spatial (Sum [Product [Centered 0 1 True, Centered 0 2 True]]) ) , (Neighbour "i" 1, Neighbour "j" (-1), [ [1,0], [0,0], [0,0] ] , Mult $ Exact $ Spatial (Sum [Product [Backward 1 1 True, Forward 1 2 False]]) ) , (Neighbour "i" 0, Neighbour "j" (-1), [ [0,1], [0,0] ] , Once $ Exact $ Spatial (Sum [Product [Centered 0 1 True, Forward 2 2 False]]) ) -- [0,1] [0,0] [0,-1] , (Neighbour "i" 1, Neighbour "j" 0, [ [1,1], [1,0], [1,-1] ] , Once $ Exact $ Spatial (Sum [Product [Centered 0 1 True, Centered 1 2 True]]) ) , (Neighbour "i" 1, Neighbour "j" 0, [ [-2,0], [-1,0] ] , Once $ Bound Nothing (Just (Spatial (Sum [Product [ Backward 3 1 False , Centered 0 2 True ]])))) , (Constant (F.ValInteger "0"), Neighbour "j" 0, [ [absoluteRep,1], [absoluteRep,0], [absoluteRep,-1] ] , Once $ Exact $ Spatial (Sum [Product [Centered 1 2 True]]) ) ] test3DSpecVariation (input, expectation) = it ("format=" ++ show input) $ -- Test inference indicesToSpec' ["i", "j", "k"] [Neighbour "i" 0, Neighbour "j" 0, Neighbour "k" 0] (map fromFormatToIx input) `shouldBe` Just expectedSpec where expectedSpec = Specification expectation fromFormatToIx [ri,rj,rk] = [offsetToIx "i" ri, offsetToIx "j" rj, offsetToIx "k" rk] variations3D = [ ( [ [-1,0,-1], [0,0,-1], [-1,0,0], [0,0,0] ] , Once $ Exact $ Spatial (Sum [Product [Backward 1 1 True, Centered 0 2 True, Backward 1 3 True]]) ) , ( [ [1,1,0], [0,1,0] ] , Once $ Exact $ Spatial (Sum [Product [Forward 1 1 True, Forward 1 2 False, Centered 0 3 True]]) ) , ( [ [-1,0,-1], [0,0,-1], [-1,0,0], [0,0,0] ] , Once $ Exact $ Spatial (Sum [Product [Backward 1 1 True, Centered 0 2 True, Backward 1 3 True]]) ) ] prop_extract_synth_inverse :: F.Name -> Int -> Bool prop_extract_synth_inverse v o = ixToNeighbour' [v] (offsetToIx v o) == Neighbour v o -- Local variables: -- mode: haskell -- haskell-program-name: "cabal repl test-suite:spec" -- End:
mrd/camfort
tests/Camfort/Specification/StencilsSpec.hs
apache-2.0
18,775
0
26
6,307
6,576
3,449
3,127
327
1
module CustomList where data List a = Nil | Cons a (List a) deriving Show emptyList :: List a emptyList = Nil isEmpty :: List a -> Bool isEmpty Nil = True isEmpty (Cons _ _) = False cons :: a -> List a -> List a cons = Cons head :: List a -> a head Nil = error "Empty list" head (Cons x _) = x tail :: List a -> List a tail Nil = error "Empty list" tail (Cons _ xs) = xs append :: List a -> List a -> List a append Nil ys = ys append (Cons x xs) ys = Cons x (append xs ys) update :: List a -> Int -> a -> List a update Nil _ _ = error "Empty list" update (Cons _ xs) 0 y = Cons y xs update (Cons x xs) i y = Cons x (update xs (i - 1) y) -- | Compute suffixes of a list -- -- Examples: -- -- >>> suffixes Nil -- Nil -- -- >>> suffixes (Cons 1 Nil) -- Cons (Cons 1 Nil) Nil -- -- >>> suffixes (Cons 1 (Cons 2 (Cons 3 Nil))) -- Cons (Cons 1 (Cons 2 (Cons 3 Nil))) (Cons (Cons 2 (Cons 3 Nil)) (Cons (Cons 3 Nil) Nil)) suffixes :: List a -> List (List a) suffixes Nil = Nil suffixes (Cons x xs) = Cons (Cons x xs) (suffixes xs)
wildsebastian/PurelyFunctionalDataStructures
chapter02/CustomList.hs
apache-2.0
1,052
0
9
270
426
217
209
26
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module NLP.MorfNCP ( temp ) where import Control.Monad (forM_) -- import qualified Data.Text.Lazy as L import qualified Data.Text.Lazy.IO as L import qualified Data.Tagset.Positional as P import qualified NLP.MorfNCP.Base as Base import qualified NLP.MorfNCP.Show as Show import qualified NLP.MorfNCP.NCP as NCP import qualified NLP.MorfNCP.MSD as MSD import qualified NLP.MorfNCP.Morfeusz as Morf --------------------------------------------------- -- Reconcile --------------------------------------------------- -- -- | Reconcile the tags chosen in NCP with the output graph generated -- -- by Morfeusz. -- reconcile -- :: [Mx.Seg Text] -- -- ^ Sentence in NCP -- -> DAG () (Morf.Token) --------------------------------------------------- -- Temp --------------------------------------------------- -- | Temporary function. temp :: FilePath -> FilePath -> IO () temp tagsetPath ncpPath = do tagset <- P.parseTagset tagsetPath <$> readFile tagsetPath let parseTag x | x == "ign" = Nothing | x == "num:comp" = Just $ P.parseTag tagset "numcomp" | otherwise = Just $ P.parseTag tagset x showTag may = case may of Nothing -> "ign" Just x -> P.showTag tagset x simpTag = MSD.simplify tagset procTag = fmap simpTag . parseTag -- procTag = parseTag xs <- NCP.getSentences ncpPath forM_ xs $ \sent -> do -- putStrLn ">>>" let orth = NCP.showSent sent -- L.putStrLn orth >> putStrLn "" -- mapM_ print $ Morf.analyze orth -- let dag = map (fmap Morf.fromToken) $ Morf.analyze orth -- let dag = map (fmap $ fmap MSD.parseMSD' . Morf.fromToken) $ Morf.analyze orth let dagMorf = Base.recalcIxsLen . map (fmap $ fmap procTag . Morf.fromToken) $ Morf.analyze orth -- putStrLn "Morfeusz:" -- mapM_ print dagMorf >> putStrLn "" let dagNCP = Base.recalcIxsLen . Base.fromList . map (fmap procTag) $ NCP.fromSent sent -- let dag = Base.fromList . map (fmap MSD.parseMSD') $ NCP.fromSent sent -- let dag = Base.fromList $ NCP.fromSent sent -- putStrLn "NCP:" -- mapM_ print dagNCP >> putStrLn "" let dag = Base.recalcIxs1 . map (fmap $ fmap showTag) $ Base.merge [dagMorf, dagNCP] L.putStrLn $ Show.showSent dag -- putStrLn "Result:" -- mapM_ print dag -- putStrLn ">>>\n"
kawu/morf-nkjp
src/NLP/MorfNCP.hs
bsd-2-clause
2,509
0
20
615
465
255
210
41
2
----------------------------------------------------------------------------- -- | -- Module : Application.HXournal.Type.Event -- Copyright : (c) 2011, 2012 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <[email protected]> -- Stability : experimental -- Portability : GHC -- ----------------------------------------------------------------------------- module Application.HXournal.Type.Event where import Application.HXournal.Type.Enum import Application.HXournal.Device import Graphics.UI.Gtk -- | data MyEvent = Initialized | CanvasConfigure Int Double Double | UpdateCanvas Int | PenDown Int PenButton PointerCoord | PenMove Int PointerCoord | PenUp Int PointerCoord | PenColorChanged PenColor | PenWidthChanged Double | HScrollBarMoved Int Double | VScrollBarMoved Int Double | VScrollBarStart Int Double | VScrollBarEnd Int Double | PaneMoveStart | PaneMoveEnd | ToViewAppendMode | ToSelectMode | ToSinglePage | ToContSinglePage | Menu MenuEvent deriving (Show,Eq,Ord) -- | data MenuEvent = MenuNew | MenuAnnotatePDF | MenuOpen | MenuSave | MenuSaveAs | MenuRecentDocument | MenuPrint | MenuExport | MenuQuit | MenuUndo | MenuRedo | MenuCut | MenuCopy | MenuPaste | MenuDelete -- | MenuNetCopy -- | MenuNetPaste | MenuFullScreen | MenuZoom | MenuZoomIn | MenuZoomOut | MenuNormalSize | MenuPageWidth | MenuPageHeight | MenuSetZoom | MenuFirstPage | MenuPreviousPage | MenuNextPage | MenuLastPage | MenuShowLayer | MenuHideLayer | MenuHSplit | MenuVSplit | MenuDelCanvas | MenuNewPageBefore | MenuNewPageAfter | MenuNewPageAtEnd | MenuDeletePage | MenuNewLayer | MenuNextLayer | MenuPrevLayer | MenuGotoLayer | MenuDeleteLayer | MenuPaperSize | MenuPaperColor | MenuPaperStyle | MenuApplyToAllPages | MenuLoadBackground | MenuBackgroundScreenshot | MenuDefaultPaper | MenuSetAsDefaultPaper | MenuShapeRecognizer | MenuRuler | MenuSelectRegion | MenuSelectRectangle | MenuVerticalSpace | MenuHandTool | MenuPenOptions | MenuEraserOptions | MenuHighlighterOptions | MenuTextFont | MenuDefaultPen | MenuDefaultEraser | MenuDefaultHighlighter | MenuDefaultText | MenuSetAsDefaultOption | MenuRelaunch | MenuUseXInput | MenuDiscardCoreEvents | MenuEraserTip | MenuPressureSensitivity | MenuPageHighlight | MenuMultiplePageView | MenuMultiplePages | MenuButton2Mapping | MenuButton3Mapping | MenuAntialiasedBitmaps | MenuProgressiveBackgrounds | MenuPrintPaperRuling | MenuLeftHandedScrollbar | MenuShortenMenus | MenuAutoSavePreferences | MenuSavePreferences | MenuAbout | MenuDefault deriving (Show, Ord, Eq) viewModeToMyEvent :: RadioAction -> IO MyEvent viewModeToMyEvent a = do v <- radioActionGetCurrentValue a case v of 1 -> return ToSinglePage 0 -> return ToContSinglePage _ -> return ToSinglePage
wavewave/hxournal
lib/Application/HXournal/Type/Event.hs
bsd-2-clause
4,348
0
10
1,947
494
309
185
115
3
{-| Implementation of cluster-wide logic. This module holds all pure cluster-logic; I\/O related functionality goes into the /Main/ module for the individual binaries. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.HTools.Cluster ( -- * Types AllocDetails(..) , AllocSolution(..) , EvacSolution(..) , Table(..) , CStats(..) , AllocNodes , AllocResult , AllocMethod , AllocSolutionList -- * Generic functions , totalResources , computeAllocationDelta -- * First phase functions , computeBadItems -- * Second phase functions , printSolutionLine , formatCmds , involvedNodes , getMoves , splitJobs -- * Display functions , printNodes , printInsts -- * Balacing functions , doNextBalance , tryBalance , compCV , compCVNodes , compDetailedCV , printStats , iMoveToJob -- * IAllocator functions , genAllocNodes , tryAlloc , tryGroupAlloc , tryMGAlloc , tryNodeEvac , tryChangeGroup , collapseFailures , allocList -- * Allocation functions , iterateAlloc , tieredAlloc -- * Node group functions , instanceGroup , findSplitInstances , splitCluster ) where import Control.Applicative ((<$>), liftA2) import Control.Arrow ((&&&)) import Control.Monad (unless) import qualified Data.IntSet as IntSet import Data.List import Data.Maybe (fromJust, fromMaybe, isJust, isNothing) import Data.Ord (comparing) import Text.Printf (printf) import Ganeti.BasicTypes import Ganeti.HTools.AlgorithmParams (AlgorithmOptions(..), defaultOptions) import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Nic as Nic import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Group as Group import Ganeti.HTools.Types import Ganeti.Compat import qualified Ganeti.OpCodes as OpCodes import Ganeti.Utils import Ganeti.Utils.Statistics import Ganeti.Types (EvacMode(..), mkNonEmpty) -- * Types -- | Allocation details for an instance, specifying -- | required number of nodes, and -- | an optional group (name) to allocate to data AllocDetails = AllocDetails Int (Maybe String) deriving (Show) -- | Allocation\/relocation solution. data AllocSolution = AllocSolution { asFailures :: [FailMode] -- ^ Failure counts , asAllocs :: Int -- ^ Good allocation count , asSolution :: Maybe Node.AllocElement -- ^ The actual allocation result , asLog :: [String] -- ^ Informational messages } -- | Node evacuation/group change iallocator result type. This result -- type consists of actual opcodes (a restricted subset) that are -- transmitted back to Ganeti. data EvacSolution = EvacSolution { esMoved :: [(Idx, Gdx, [Ndx])] -- ^ Instances moved successfully , esFailed :: [(Idx, String)] -- ^ Instances which were not -- relocated , esOpCodes :: [[OpCodes.OpCode]] -- ^ List of jobs } deriving (Show) -- | Allocation results, as used in 'iterateAlloc' and 'tieredAlloc'. type AllocResult = (FailStats, Node.List, Instance.List, [Instance.Instance], [CStats]) -- | Type alias for easier handling. type AllocSolutionList = [(Instance.Instance, AllocSolution)] -- | A type denoting the valid allocation mode/pairs. -- -- For a one-node allocation, this will be a @Left ['Ndx']@, whereas -- for a two-node allocation, this will be a @Right [('Ndx', -- ['Ndx'])]@. In the latter case, the list is basically an -- association list, grouped by primary node and holding the potential -- secondary nodes in the sub-list. type AllocNodes = Either [Ndx] [(Ndx, [Ndx])] -- | The empty solution we start with when computing allocations. emptyAllocSolution :: AllocSolution emptyAllocSolution = AllocSolution { asFailures = [], asAllocs = 0 , asSolution = Nothing, asLog = [] } -- | The empty evac solution. emptyEvacSolution :: EvacSolution emptyEvacSolution = EvacSolution { esMoved = [] , esFailed = [] , esOpCodes = [] } -- | The complete state for the balancing solution. data Table = Table Node.List Instance.List Score [Placement] deriving (Show) -- | Cluster statistics data type. data CStats = CStats { csFmem :: Integer -- ^ Cluster free mem , csFdsk :: Integer -- ^ Cluster free disk , csFspn :: Integer -- ^ Cluster free spindles , csAmem :: Integer -- ^ Cluster allocatable mem , csAdsk :: Integer -- ^ Cluster allocatable disk , csAcpu :: Integer -- ^ Cluster allocatable cpus , csMmem :: Integer -- ^ Max node allocatable mem , csMdsk :: Integer -- ^ Max node allocatable disk , csMcpu :: Integer -- ^ Max node allocatable cpu , csImem :: Integer -- ^ Instance used mem , csIdsk :: Integer -- ^ Instance used disk , csIspn :: Integer -- ^ Instance used spindles , csIcpu :: Integer -- ^ Instance used cpu , csTmem :: Double -- ^ Cluster total mem , csTdsk :: Double -- ^ Cluster total disk , csTspn :: Double -- ^ Cluster total spindles , csTcpu :: Double -- ^ Cluster total cpus , csVcpu :: Integer -- ^ Cluster total virtual cpus , csNcpu :: Double -- ^ Equivalent to 'csIcpu' but in terms of -- physical CPUs, i.e. normalised used phys CPUs , csXmem :: Integer -- ^ Unnacounted for mem , csNmem :: Integer -- ^ Node own memory , csScore :: Score -- ^ The cluster score , csNinst :: Int -- ^ The total number of instances } deriving (Show) -- | A simple type for allocation functions. type AllocMethod = Node.List -- ^ Node list -> Instance.List -- ^ Instance list -> Maybe Int -- ^ Optional allocation limit -> Instance.Instance -- ^ Instance spec for allocation -> AllocNodes -- ^ Which nodes we should allocate on -> [Instance.Instance] -- ^ Allocated instances -> [CStats] -- ^ Running cluster stats -> Result AllocResult -- ^ Allocation result -- | A simple type for the running solution of evacuations. type EvacInnerState = Either String (Node.List, Instance.Instance, Score, Ndx) -- * Utility functions -- | Verifies the N+1 status and return the affected nodes. verifyN1 :: [Node.Node] -> [Node.Node] verifyN1 = filter Node.failN1 {-| Computes the pair of bad nodes and instances. The bad node list is computed via a simple 'verifyN1' check, and the bad instance list is the list of primary and secondary instances of those nodes. -} computeBadItems :: Node.List -> Instance.List -> ([Node.Node], [Instance.Instance]) computeBadItems nl il = let bad_nodes = verifyN1 $ getOnline nl bad_instances = map (`Container.find` il) . sort . nub $ concatMap (\ n -> Node.sList n ++ Node.pList n) bad_nodes in (bad_nodes, bad_instances) -- | Extracts the node pairs for an instance. This can fail if the -- instance is single-homed. FIXME: this needs to be improved, -- together with the general enhancement for handling non-DRBD moves. instanceNodes :: Node.List -> Instance.Instance -> (Ndx, Ndx, Node.Node, Node.Node) instanceNodes nl inst = let old_pdx = Instance.pNode inst old_sdx = Instance.sNode inst old_p = Container.find old_pdx nl old_s = Container.find old_sdx nl in (old_pdx, old_sdx, old_p, old_s) -- | Zero-initializer for the CStats type. emptyCStats :: CStats emptyCStats = CStats 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -- | Update stats with data from a new node. updateCStats :: CStats -> Node.Node -> CStats updateCStats cs node = let CStats { csFmem = x_fmem, csFdsk = x_fdsk, csAmem = x_amem, csAcpu = x_acpu, csAdsk = x_adsk, csMmem = x_mmem, csMdsk = x_mdsk, csMcpu = x_mcpu, csImem = x_imem, csIdsk = x_idsk, csIcpu = x_icpu, csTmem = x_tmem, csTdsk = x_tdsk, csTcpu = x_tcpu, csVcpu = x_vcpu, csNcpu = x_ncpu, csXmem = x_xmem, csNmem = x_nmem, csNinst = x_ninst, csFspn = x_fspn, csIspn = x_ispn, csTspn = x_tspn } = cs inc_amem = Node.fMem node - Node.rMem node inc_amem' = if inc_amem > 0 then inc_amem else 0 inc_adsk = Node.availDisk node inc_imem = truncate (Node.tMem node) - Node.nMem node - Node.xMem node - Node.fMem node inc_icpu = Node.uCpu node inc_idsk = truncate (Node.tDsk node) - Node.fDsk node inc_ispn = Node.tSpindles node - Node.fSpindles node inc_vcpu = Node.hiCpu node inc_acpu = Node.availCpu node inc_ncpu = fromIntegral (Node.uCpu node) / iPolicyVcpuRatio (Node.iPolicy node) in cs { csFmem = x_fmem + fromIntegral (Node.fMem node) , csFdsk = x_fdsk + fromIntegral (Node.fDsk node) , csFspn = x_fspn + fromIntegral (Node.fSpindles node) , csAmem = x_amem + fromIntegral inc_amem' , csAdsk = x_adsk + fromIntegral inc_adsk , csAcpu = x_acpu + fromIntegral inc_acpu , csMmem = max x_mmem (fromIntegral inc_amem') , csMdsk = max x_mdsk (fromIntegral inc_adsk) , csMcpu = max x_mcpu (fromIntegral inc_acpu) , csImem = x_imem + fromIntegral inc_imem , csIdsk = x_idsk + fromIntegral inc_idsk , csIspn = x_ispn + fromIntegral inc_ispn , csIcpu = x_icpu + fromIntegral inc_icpu , csTmem = x_tmem + Node.tMem node , csTdsk = x_tdsk + Node.tDsk node , csTspn = x_tspn + fromIntegral (Node.tSpindles node) , csTcpu = x_tcpu + Node.tCpu node , csVcpu = x_vcpu + fromIntegral inc_vcpu , csNcpu = x_ncpu + inc_ncpu , csXmem = x_xmem + fromIntegral (Node.xMem node) , csNmem = x_nmem + fromIntegral (Node.nMem node) , csNinst = x_ninst + length (Node.pList node) } -- | Compute the total free disk and memory in the cluster. totalResources :: Node.List -> CStats totalResources nl = let cs = foldl' updateCStats emptyCStats . Container.elems $ nl in cs { csScore = compCV nl } -- | Compute the delta between two cluster state. -- -- This is used when doing allocations, to understand better the -- available cluster resources. The return value is a triple of the -- current used values, the delta that was still allocated, and what -- was left unallocated. computeAllocationDelta :: CStats -> CStats -> AllocStats computeAllocationDelta cini cfin = let CStats {csImem = i_imem, csIdsk = i_idsk, csIcpu = i_icpu, csNcpu = i_ncpu, csIspn = i_ispn } = cini CStats {csImem = f_imem, csIdsk = f_idsk, csIcpu = f_icpu, csTmem = t_mem, csTdsk = t_dsk, csVcpu = f_vcpu, csNcpu = f_ncpu, csTcpu = f_tcpu, csIspn = f_ispn, csTspn = t_spn } = cfin rini = AllocInfo { allocInfoVCpus = fromIntegral i_icpu , allocInfoNCpus = i_ncpu , allocInfoMem = fromIntegral i_imem , allocInfoDisk = fromIntegral i_idsk , allocInfoSpn = fromIntegral i_ispn } rfin = AllocInfo { allocInfoVCpus = fromIntegral (f_icpu - i_icpu) , allocInfoNCpus = f_ncpu - i_ncpu , allocInfoMem = fromIntegral (f_imem - i_imem) , allocInfoDisk = fromIntegral (f_idsk - i_idsk) , allocInfoSpn = fromIntegral (f_ispn - i_ispn) } runa = AllocInfo { allocInfoVCpus = fromIntegral (f_vcpu - f_icpu) , allocInfoNCpus = f_tcpu - f_ncpu , allocInfoMem = truncate t_mem - fromIntegral f_imem , allocInfoDisk = truncate t_dsk - fromIntegral f_idsk , allocInfoSpn = truncate t_spn - fromIntegral f_ispn } in (rini, rfin, runa) -- | The names and weights of the individual elements in the CV list, together -- with their statistical accumulation function and a bit to decide whether it -- is a statistics for online nodes. detailedCVInfoExt :: [((Double, String), ([Double] -> Statistics, Bool))] detailedCVInfoExt = [ ((1, "free_mem_cv"), (getStdDevStatistics, True)) , ((1, "free_disk_cv"), (getStdDevStatistics, True)) , ((1, "n1_cnt"), (getSumStatistics, True)) , ((1, "reserved_mem_cv"), (getStdDevStatistics, True)) , ((4, "offline_all_cnt"), (getSumStatistics, False)) , ((16, "offline_pri_cnt"), (getSumStatistics, False)) , ((1, "vcpu_ratio_cv"), (getStdDevStatistics, True)) , ((1, "cpu_load_cv"), (getStdDevStatistics, True)) , ((1, "mem_load_cv"), (getStdDevStatistics, True)) , ((1, "disk_load_cv"), (getStdDevStatistics, True)) , ((1, "net_load_cv"), (getStdDevStatistics, True)) , ((2, "pri_tags_score"), (getSumStatistics, True)) , ((1, "spindles_cv"), (getStdDevStatistics, True)) ] -- | The names and weights of the individual elements in the CV list. detailedCVInfo :: [(Double, String)] detailedCVInfo = map fst detailedCVInfoExt -- | Holds the weights used by 'compCVNodes' for each metric. detailedCVWeights :: [Double] detailedCVWeights = map fst detailedCVInfo -- | The aggregation functions for the weights detailedCVAggregation :: [([Double] -> Statistics, Bool)] detailedCVAggregation = map snd detailedCVInfoExt -- | The bit vector describing which parts of the statistics are -- for online nodes. detailedCVOnlineStatus :: [Bool] detailedCVOnlineStatus = map snd detailedCVAggregation -- | Compute statistical measures of a single node. compDetailedCVNode :: Node.Node -> [Double] compDetailedCVNode node = let mem = Node.pMem node dsk = Node.pDsk node n1 = fromIntegral $ if Node.failN1 node then length (Node.sList node) + length (Node.pList node) else 0 res = Node.pRem node ipri = fromIntegral . length $ Node.pList node isec = fromIntegral . length $ Node.sList node ioff = ipri + isec cpu = Node.pCpuEff node DynUtil c1 m1 d1 nn1 = Node.utilLoad node DynUtil c2 m2 d2 nn2 = Node.utilPool node (c_load, m_load, d_load, n_load) = (c1/c2, m1/m2, d1/d2, nn1/nn2) pri_tags = fromIntegral $ Node.conflictingPrimaries node spindles = Node.instSpindles node / Node.hiSpindles node in [ mem, dsk, n1, res, ioff, ipri, cpu , c_load, m_load, d_load, n_load , pri_tags, spindles ] -- | Compute the statistics of a cluster. compClusterStatistics :: [Node.Node] -> [Statistics] compClusterStatistics all_nodes = let (offline, nodes) = partition Node.offline all_nodes offline_values = transpose (map compDetailedCVNode offline) ++ repeat [] -- transpose of an empty list is empty and not k times the empty list, as -- would be the transpose of a 0 x k matrix online_values = transpose $ map compDetailedCVNode nodes aggregate (f, True) (onNodes, _) = f onNodes aggregate (f, False) (_, offNodes) = f offNodes in zipWith aggregate detailedCVAggregation $ zip online_values offline_values -- | Update a cluster statistics by replacing the contribution of one -- node by that of another. updateClusterStatistics :: [Statistics] -> (Node.Node, Node.Node) -> [Statistics] updateClusterStatistics stats (old, new) = let update = zip (compDetailedCVNode old) (compDetailedCVNode new) online = not $ Node.offline old updateStat forOnline stat upd = if forOnline == online then updateStatistics stat upd else stat in zipWith3 updateStat detailedCVOnlineStatus stats update -- | Update a cluster statistics twice. updateClusterStatisticsTwice :: [Statistics] -> (Node.Node, Node.Node) -> (Node.Node, Node.Node) -> [Statistics] updateClusterStatisticsTwice s a = updateClusterStatistics (updateClusterStatistics s a) -- | Compute cluster statistics compDetailedCV :: [Node.Node] -> [Double] compDetailedCV = map getStatisticValue . compClusterStatistics -- | Compute the cluster score from its statistics compCVfromStats :: [Statistics] -> Double compCVfromStats = sum . zipWith (*) detailedCVWeights . map getStatisticValue -- | Compute the /total/ variance. compCVNodes :: [Node.Node] -> Double compCVNodes = sum . zipWith (*) detailedCVWeights . compDetailedCV -- | Wrapper over 'compCVNodes' for callers that have a 'Node.List'. compCV :: Node.List -> Double compCV = compCVNodes . Container.elems -- | Compute online nodes from a 'Node.List'. getOnline :: Node.List -> [Node.Node] getOnline = filter (not . Node.offline) . Container.elems -- * Balancing functions -- | Compute best table. Note that the ordering of the arguments is important. compareTables :: Table -> Table -> Table compareTables a@(Table _ _ a_cv _) b@(Table _ _ b_cv _ ) = if a_cv > b_cv then b else a -- | Applies an instance move to a given node list and instance. applyMoveEx :: Bool -- ^ whether to ignore soft errors -> Node.List -> Instance.Instance -> IMove -> OpResult (Node.List, Instance.Instance, Ndx, Ndx) -- Failover (f) applyMoveEx force nl inst Failover = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst new_nl = do -- OpResult Node.checkMigration old_p old_s new_p <- Node.addPriEx (Node.offline old_p || force) int_s inst new_s <- Node.addSec int_p inst old_sdx let new_inst = Instance.setBoth inst old_sdx old_pdx return (Container.addTwo old_pdx new_s old_sdx new_p nl, new_inst, old_sdx, old_pdx) in new_nl -- Failover to any (fa) applyMoveEx force nl inst (FailoverToAny new_pdx) = do let (old_pdx, old_sdx, old_pnode, _) = instanceNodes nl inst new_pnode = Container.find new_pdx nl force_failover = Node.offline old_pnode || force Node.checkMigration old_pnode new_pnode new_pnode' <- Node.addPriEx force_failover new_pnode inst let old_pnode' = Node.removePri old_pnode inst inst' = Instance.setPri inst new_pdx nl' = Container.addTwo old_pdx old_pnode' new_pdx new_pnode' nl return (nl', inst', new_pdx, old_sdx) -- Replace the primary (f:, r:np, f) applyMoveEx force nl inst (ReplacePrimary new_pdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_pdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_p = Node.offline old_p || force new_nl = do -- OpResult -- check that the current secondary can host the instance -- during the migration Node.checkMigration old_p old_s Node.checkMigration old_s tgt_n tmp_s <- Node.addPriEx force_p int_s inst let tmp_s' = Node.removePri tmp_s inst new_p <- Node.addPriEx force_p tgt_n inst new_s <- Node.addSecEx force_p tmp_s' inst new_pdx let new_inst = Instance.setPri inst new_pdx return (Container.add new_pdx new_p $ Container.addTwo old_pdx int_p old_sdx new_s nl, new_inst, new_pdx, old_sdx) in new_nl -- Replace the secondary (r:ns) applyMoveEx force nl inst (ReplaceSecondary new_sdx) = let old_pdx = Instance.pNode inst old_sdx = Instance.sNode inst old_s = Container.find old_sdx nl tgt_n = Container.find new_sdx nl int_s = Node.removeSec old_s inst force_s = Node.offline old_s || force new_inst = Instance.setSec inst new_sdx new_nl = Node.addSecEx force_s tgt_n inst old_pdx >>= \new_s -> return (Container.addTwo new_sdx new_s old_sdx int_s nl, new_inst, old_pdx, new_sdx) in new_nl -- Replace the secondary and failover (r:np, f) applyMoveEx force nl inst (ReplaceAndFailover new_pdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_pdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_s = Node.offline old_s || force new_nl = do -- OpResult Node.checkMigration old_p tgt_n new_p <- Node.addPri tgt_n inst new_s <- Node.addSecEx force_s int_p inst new_pdx let new_inst = Instance.setBoth inst new_pdx old_pdx return (Container.add new_pdx new_p $ Container.addTwo old_pdx new_s old_sdx int_s nl, new_inst, new_pdx, old_pdx) in new_nl -- Failver and replace the secondary (f, r:ns) applyMoveEx force nl inst (FailoverAndReplace new_sdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_sdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_p = Node.offline old_p || force new_nl = do -- OpResult Node.checkMigration old_p old_s new_p <- Node.addPriEx force_p int_s inst new_s <- Node.addSecEx force_p tgt_n inst old_sdx let new_inst = Instance.setBoth inst old_sdx new_sdx return (Container.add new_sdx new_s $ Container.addTwo old_sdx new_p old_pdx int_p nl, new_inst, old_sdx, new_sdx) in new_nl -- | Applies an instance move to a given node list and instance. applyMove :: Node.List -> Instance.Instance -> IMove -> OpResult (Node.List, Instance.Instance, Ndx, Ndx) applyMove = applyMoveEx False -- | Tries to allocate an instance on one given node. allocateOnSingle :: Node.List -> Instance.Instance -> Ndx -> OpResult Node.AllocElement allocateOnSingle nl inst new_pdx = let p = Container.find new_pdx nl new_inst = Instance.setBoth inst new_pdx Node.noSecondary in do Instance.instMatchesPolicy inst (Node.iPolicy p) (Node.exclStorage p) new_p <- Node.addPri p inst let new_nl = Container.add new_pdx new_p nl new_score = compCV new_nl return (new_nl, new_inst, [new_p], new_score) -- | Tries to allocate an instance on a given pair of nodes. allocateOnPair :: [Statistics] -> Node.List -> Instance.Instance -> Ndx -> Ndx -> OpResult Node.AllocElement allocateOnPair stats nl inst new_pdx new_sdx = let tgt_p = Container.find new_pdx nl tgt_s = Container.find new_sdx nl in do Instance.instMatchesPolicy inst (Node.iPolicy tgt_p) (Node.exclStorage tgt_p) new_p <- Node.addPri tgt_p inst new_s <- Node.addSec tgt_s inst new_pdx let new_inst = Instance.setBoth inst new_pdx new_sdx new_nl = Container.addTwo new_pdx new_p new_sdx new_s nl new_stats = updateClusterStatisticsTwice stats (tgt_p, new_p) (tgt_s, new_s) return (new_nl, new_inst, [new_p, new_s], compCVfromStats new_stats) -- | Tries to perform an instance move and returns the best table -- between the original one and the new one. checkSingleStep :: Bool -- ^ Whether to unconditionally ignore soft errors -> Table -- ^ The original table -> Instance.Instance -- ^ The instance to move -> Table -- ^ The current best table -> IMove -- ^ The move to apply -> Table -- ^ The final best table checkSingleStep force ini_tbl target cur_tbl move = let Table ini_nl ini_il _ ini_plc = ini_tbl tmp_resu = applyMoveEx force ini_nl target move in case tmp_resu of Bad _ -> cur_tbl Ok (upd_nl, new_inst, pri_idx, sec_idx) -> let tgt_idx = Instance.idx target upd_cvar = compCV upd_nl upd_il = Container.add tgt_idx new_inst ini_il upd_plc = (tgt_idx, pri_idx, sec_idx, move, upd_cvar):ini_plc upd_tbl = Table upd_nl upd_il upd_cvar upd_plc in compareTables cur_tbl upd_tbl -- | Given the status of the current secondary as a valid new node and -- the current candidate target node, generate the possible moves for -- a instance. possibleMoves :: MirrorType -- ^ The mirroring type of the instance -> Bool -- ^ Whether the secondary node is a valid new node -> Bool -- ^ Whether we can change the primary node -> (Bool, Bool) -- ^ Whether migration is restricted and whether -- the instance primary is offline -> Ndx -- ^ Target node candidate -> [IMove] -- ^ List of valid result moves possibleMoves MirrorNone _ _ _ _ = [] possibleMoves MirrorExternal _ False _ _ = [] possibleMoves MirrorExternal _ True _ tdx = [ FailoverToAny tdx ] possibleMoves MirrorInternal _ False _ tdx = [ ReplaceSecondary tdx ] possibleMoves MirrorInternal _ _ (True, False) tdx = [ ReplaceSecondary tdx ] possibleMoves MirrorInternal True True (False, _) tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx , ReplacePrimary tdx , FailoverAndReplace tdx ] possibleMoves MirrorInternal True True (True, True) tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx , FailoverAndReplace tdx ] possibleMoves MirrorInternal False True _ tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx ] -- | Compute the best move for a given instance. checkInstanceMove :: AlgorithmOptions -- ^ Algorithmic options for balancing -> [Ndx] -- ^ Allowed target node indices -> Table -- ^ Original table -> Instance.Instance -- ^ Instance to move -> Table -- ^ Best new table for this instance checkInstanceMove opts nodes_idx ini_tbl@(Table nl _ _ _) target = let force = algIgnoreSoftErrors opts disk_moves = algDiskMoves opts inst_moves = algInstanceMoves opts rest_mig = algRestrictedMigration opts opdx = Instance.pNode target osdx = Instance.sNode target bad_nodes = [opdx, osdx] nodes = filter (`notElem` bad_nodes) nodes_idx mir_type = Instance.mirrorType target use_secondary = elem osdx nodes_idx && inst_moves aft_failover = if mir_type == MirrorInternal && use_secondary -- if drbd and allowed to failover then checkSingleStep force ini_tbl target ini_tbl Failover else ini_tbl primary_drained = Node.offline . flip Container.find nl $ Instance.pNode target all_moves = if disk_moves then concatMap (possibleMoves mir_type use_secondary inst_moves (rest_mig, primary_drained)) nodes else [] in -- iterate over the possible nodes for this instance foldl' (checkSingleStep force ini_tbl target) aft_failover all_moves -- | Compute the best next move. checkMove :: AlgorithmOptions -- ^ Algorithmic options for balancing -> [Ndx] -- ^ Allowed target node indices -> Table -- ^ The current solution -> [Instance.Instance] -- ^ List of instances still to move -> Table -- ^ The new solution checkMove opts nodes_idx ini_tbl victims = let Table _ _ _ ini_plc = ini_tbl -- we're using rwhnf from the Control.Parallel.Strategies -- package; we don't need to use rnf as that would force too -- much evaluation in single-threaded cases, and in -- multi-threaded case the weak head normal form is enough to -- spark the evaluation tables = parMap rwhnf (checkInstanceMove opts nodes_idx ini_tbl) victims -- iterate over all instances, computing the best move best_tbl = foldl' compareTables ini_tbl tables Table _ _ _ best_plc = best_tbl in if length best_plc == length ini_plc then ini_tbl -- no advancement else best_tbl -- | Check if we are allowed to go deeper in the balancing. doNextBalance :: Table -- ^ The starting table -> Int -- ^ Remaining length -> Score -- ^ Score at which to stop -> Bool -- ^ The resulting table and commands doNextBalance ini_tbl max_rounds min_score = let Table _ _ ini_cv ini_plc = ini_tbl ini_plc_len = length ini_plc in (max_rounds < 0 || ini_plc_len < max_rounds) && ini_cv > min_score -- | Run a balance move. tryBalance :: AlgorithmOptions -- ^ Algorithmic options for balancing -> Table -- ^ The starting table -> Maybe Table -- ^ The resulting table and commands tryBalance opts ini_tbl = let evac_mode = algEvacMode opts mg_limit = algMinGainLimit opts min_gain = algMinGain opts Table ini_nl ini_il ini_cv _ = ini_tbl all_inst = Container.elems ini_il all_nodes = Container.elems ini_nl (offline_nodes, online_nodes) = partition Node.offline all_nodes all_inst' = if evac_mode then let bad_nodes = map Node.idx offline_nodes in filter (any (`elem` bad_nodes) . Instance.allNodes) all_inst else all_inst reloc_inst = filter (\i -> Instance.movable i && Instance.autoBalance i) all_inst' node_idx = map Node.idx online_nodes fin_tbl = checkMove opts node_idx ini_tbl reloc_inst (Table _ _ fin_cv _) = fin_tbl in if fin_cv < ini_cv && (ini_cv > mg_limit || ini_cv - fin_cv >= min_gain) then Just fin_tbl -- this round made success, return the new table else Nothing -- * Allocation functions -- | Build failure stats out of a list of failures. collapseFailures :: [FailMode] -> FailStats collapseFailures flst = map (\k -> (k, foldl' (\a e -> if e == k then a + 1 else a) 0 flst)) [minBound..maxBound] -- | Compares two Maybe AllocElement and chooses the best score. bestAllocElement :: Maybe Node.AllocElement -> Maybe Node.AllocElement -> Maybe Node.AllocElement bestAllocElement a Nothing = a bestAllocElement Nothing b = b bestAllocElement a@(Just (_, _, _, ascore)) b@(Just (_, _, _, bscore)) = if ascore < bscore then a else b -- | Update current Allocation solution and failure stats with new -- elements. concatAllocs :: AllocSolution -> OpResult Node.AllocElement -> AllocSolution concatAllocs as (Bad reason) = as { asFailures = reason : asFailures as } concatAllocs as (Ok ns) = let -- Choose the old or new solution, based on the cluster score cntok = asAllocs as osols = asSolution as nsols = bestAllocElement osols (Just ns) nsuc = cntok + 1 -- Note: we force evaluation of nsols here in order to keep the -- memory profile low - we know that we will need nsols for sure -- in the next cycle, so we force evaluation of nsols, since the -- foldl' in the caller will only evaluate the tuple, but not the -- elements of the tuple in nsols `seq` nsuc `seq` as { asAllocs = nsuc, asSolution = nsols } -- | Sums two 'AllocSolution' structures. sumAllocs :: AllocSolution -> AllocSolution -> AllocSolution sumAllocs (AllocSolution aFails aAllocs aSols aLog) (AllocSolution bFails bAllocs bSols bLog) = -- note: we add b first, since usually it will be smaller; when -- fold'ing, a will grow and grow whereas b is the per-group -- result, hence smaller let nFails = bFails ++ aFails nAllocs = aAllocs + bAllocs nSols = bestAllocElement aSols bSols nLog = bLog ++ aLog in AllocSolution nFails nAllocs nSols nLog -- | Given a solution, generates a reasonable description for it. describeSolution :: AllocSolution -> String describeSolution as = let fcnt = asFailures as sols = asSolution as freasons = intercalate ", " . map (\(a, b) -> printf "%s: %d" (show a) b) . filter ((> 0) . snd) . collapseFailures $ fcnt in case sols of Nothing -> "No valid allocation solutions, failure reasons: " ++ (if null fcnt then "unknown reasons" else freasons) Just (_, _, nodes, cv) -> printf ("score: %.8f, successes %d, failures %d (%s)" ++ " for node(s) %s") cv (asAllocs as) (length fcnt) freasons (intercalate "/" . map Node.name $ nodes) -- | Annotates a solution with the appropriate string. annotateSolution :: AllocSolution -> AllocSolution annotateSolution as = as { asLog = describeSolution as : asLog as } -- | Reverses an evacuation solution. -- -- Rationale: we always concat the results to the top of the lists, so -- for proper jobset execution, we should reverse all lists. reverseEvacSolution :: EvacSolution -> EvacSolution reverseEvacSolution (EvacSolution f m o) = EvacSolution (reverse f) (reverse m) (reverse o) -- | Generate the valid node allocation singles or pairs for a new instance. genAllocNodes :: Group.List -- ^ Group list -> Node.List -- ^ The node map -> Int -- ^ The number of nodes required -> Bool -- ^ Whether to drop or not -- unallocable nodes -> Result AllocNodes -- ^ The (monadic) result genAllocNodes gl nl count drop_unalloc = let filter_fn = if drop_unalloc then filter (Group.isAllocable . flip Container.find gl . Node.group) else id all_nodes = filter_fn $ getOnline nl all_pairs = [(Node.idx p, [Node.idx s | s <- all_nodes, Node.idx p /= Node.idx s, Node.group p == Node.group s]) | p <- all_nodes] in case count of 1 -> Ok (Left (map Node.idx all_nodes)) 2 -> Ok (Right (filter (not . null . snd) all_pairs)) _ -> Bad "Unsupported number of nodes, only one or two supported" -- | Try to allocate an instance on the cluster. tryAlloc :: (Monad m) => Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Instance.Instance -- ^ The instance to allocate -> AllocNodes -- ^ The allocation targets -> m AllocSolution -- ^ Possible solution list tryAlloc _ _ _ (Right []) = fail "Not enough online nodes" tryAlloc nl _ inst (Right ok_pairs) = let cstat = compClusterStatistics $ Container.elems nl psols = parMap rwhnf (\(p, ss) -> foldl' (\cstate -> concatAllocs cstate . allocateOnPair cstat nl inst p) emptyAllocSolution ss) ok_pairs sols = foldl' sumAllocs emptyAllocSolution psols in return $ annotateSolution sols tryAlloc _ _ _ (Left []) = fail "No online nodes" tryAlloc nl _ inst (Left all_nodes) = let sols = foldl' (\cstate -> concatAllocs cstate . allocateOnSingle nl inst ) emptyAllocSolution all_nodes in return $ annotateSolution sols -- | Given a group/result, describe it as a nice (list of) messages. solutionDescription :: (Group.Group, Result AllocSolution) -> [String] solutionDescription (grp, result) = case result of Ok solution -> map (printf "Group %s (%s): %s" gname pol) (asLog solution) Bad message -> [printf "Group %s: error %s" gname message] where gname = Group.name grp pol = allocPolicyToRaw (Group.allocPolicy grp) -- | From a list of possibly bad and possibly empty solutions, filter -- only the groups with a valid result. Note that the result will be -- reversed compared to the original list. filterMGResults :: [(Group.Group, Result AllocSolution)] -> [(Group.Group, AllocSolution)] filterMGResults = foldl' fn [] where unallocable = not . Group.isAllocable fn accu (grp, rasol) = case rasol of Bad _ -> accu Ok sol | isNothing (asSolution sol) -> accu | unallocable grp -> accu | otherwise -> (grp, sol):accu -- | Sort multigroup results based on policy and score. sortMGResults :: [(Group.Group, AllocSolution)] -> [(Group.Group, AllocSolution)] sortMGResults sols = let extractScore (_, _, _, x) = x solScore (grp, sol) = (Group.allocPolicy grp, (extractScore . fromJust . asSolution) sol) in sortBy (comparing solScore) sols -- | Determines if a group is connected to the networks required by the -- | instance. hasRequiredNetworks :: Group.Group -> Instance.Instance -> Bool hasRequiredNetworks ng = all hasNetwork . Instance.nics where hasNetwork = maybe True (`elem` Group.networks ng) . Nic.network -- | Removes node groups which can't accommodate the instance filterValidGroups :: [(Group.Group, (Node.List, Instance.List))] -> Instance.Instance -> ([(Group.Group, (Node.List, Instance.List))], [String]) filterValidGroups [] _ = ([], []) filterValidGroups (ng:ngs) inst = let (valid_ngs, msgs) = filterValidGroups ngs inst in if hasRequiredNetworks (fst ng) inst then (ng:valid_ngs, msgs) else (valid_ngs, ("group " ++ Group.name (fst ng) ++ " is not connected to a network required by instance " ++ Instance.name inst):msgs) -- | Finds an allocation solution for an instance on a group findAllocation :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Gdx -- ^ The group to allocate to -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result (AllocSolution, [String]) findAllocation mggl mgnl mgil gdx inst cnt = do let belongsTo nl' nidx = nidx `elem` map Node.idx (Container.elems nl') nl = Container.filter ((== gdx) . Node.group) mgnl il = Container.filter (belongsTo nl . Instance.pNode) mgil group' = Container.find gdx mggl unless (hasRequiredNetworks group' inst) . failError $ "The group " ++ Group.name group' ++ " is not connected to\ \ a network required by instance " ++ Instance.name inst solution <- genAllocNodes mggl nl cnt False >>= tryAlloc nl il inst return (solution, solutionDescription (group', return solution)) -- | Finds the best group for an instance on a multi-group cluster. -- -- Only solutions in @preferred@ and @last_resort@ groups will be -- accepted as valid, and additionally if the allowed groups parameter -- is not null then allocation will only be run for those group -- indices. findBestAllocGroup :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Maybe [Gdx] -- ^ The allowed groups -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result (Group.Group, AllocSolution, [String]) findBestAllocGroup mggl mgnl mgil allowed_gdxs inst cnt = let groups_by_idx = splitCluster mgnl mgil groups = map (\(gid, d) -> (Container.find gid mggl, d)) groups_by_idx groups' = maybe groups (\gs -> filter ((`elem` gs) . Group.idx . fst) groups) allowed_gdxs (groups'', filter_group_msgs) = filterValidGroups groups' inst sols = map (\(gr, (nl, il)) -> (gr, genAllocNodes mggl nl cnt False >>= tryAlloc nl il inst)) groups''::[(Group.Group, Result AllocSolution)] all_msgs = filter_group_msgs ++ concatMap solutionDescription sols goodSols = filterMGResults sols sortedSols = sortMGResults goodSols in case sortedSols of [] -> Bad $ if null groups' then "no groups for evacuation: allowed groups was" ++ show allowed_gdxs ++ ", all groups: " ++ show (map fst groups) else intercalate ", " all_msgs (final_group, final_sol):_ -> return (final_group, final_sol, all_msgs) -- | Try to allocate an instance on a multi-group cluster. tryMGAlloc :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result AllocSolution -- ^ Possible solution list tryMGAlloc mggl mgnl mgil inst cnt = do (best_group, solution, all_msgs) <- findBestAllocGroup mggl mgnl mgil Nothing inst cnt let group_name = Group.name best_group selmsg = "Selected group: " ++ group_name return $ solution { asLog = selmsg:all_msgs } -- | Try to allocate an instance to a group. tryGroupAlloc :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> String -- ^ The allocation group (name) -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result AllocSolution -- ^ Solution tryGroupAlloc mggl mgnl ngil gn inst cnt = do gdx <- Group.idx <$> Container.findByName mggl gn (solution, msgs) <- findAllocation mggl mgnl ngil gdx inst cnt return $ solution { asLog = msgs } -- | Calculate the new instance list after allocation solution. updateIl :: Instance.List -- ^ The original instance list -> Maybe Node.AllocElement -- ^ The result of the allocation attempt -> Instance.List -- ^ The updated instance list updateIl il Nothing = il updateIl il (Just (_, xi, _, _)) = Container.add (Container.size il) xi il -- | Extract the the new node list from the allocation solution. extractNl :: Node.List -- ^ The original node list -> Maybe Node.AllocElement -- ^ The result of the allocation attempt -> Node.List -- ^ The new node list extractNl nl Nothing = nl extractNl _ (Just (xnl, _, _, _)) = xnl -- | Try to allocate a list of instances on a multi-group cluster. allocList :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> [(Instance.Instance, AllocDetails)] -- ^ The instance to -- allocate -> AllocSolutionList -- ^ Possible solution -- list -> Result (Node.List, Instance.List, AllocSolutionList) -- ^ The final solution -- list allocList _ nl il [] result = Ok (nl, il, result) allocList gl nl il ((xi, AllocDetails xicnt mgn):xies) result = do ares <- case mgn of Nothing -> tryMGAlloc gl nl il xi xicnt Just gn -> tryGroupAlloc gl nl il gn xi xicnt let sol = asSolution ares nl' = extractNl nl sol il' = updateIl il sol allocList gl nl' il' xies ((xi, ares):result) -- | Function which fails if the requested mode is change secondary. -- -- This is useful since except DRBD, no other disk template can -- execute change secondary; thus, we can just call this function -- instead of always checking for secondary mode. After the call to -- this function, whatever mode we have is just a primary change. failOnSecondaryChange :: (Monad m) => EvacMode -> DiskTemplate -> m () failOnSecondaryChange ChangeSecondary dt = fail $ "Instances with disk template '" ++ diskTemplateToRaw dt ++ "' can't execute change secondary" failOnSecondaryChange _ _ = return () -- | Run evacuation for a single instance. -- -- /Note:/ this function should correctly execute both intra-group -- evacuations (in all modes) and inter-group evacuations (in the -- 'ChangeAll' mode). Of course, this requires that the correct list -- of target nodes is passed. nodeEvacInstance :: AlgorithmOptions -> Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> EvacMode -- ^ The evacuation mode -> Instance.Instance -- ^ The instance to be evacuated -> Gdx -- ^ The group we're targetting -> [Ndx] -- ^ The list of available nodes -- for allocation -> Result (Node.List, Instance.List, [OpCodes.OpCode]) nodeEvacInstance opts nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTDiskless}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly opts nl il inst gdx avail_nodes nodeEvacInstance _ _ _ _ (Instance.Instance {Instance.diskTemplate = DTPlain}) _ _ = fail "Instances of type plain cannot be relocated" nodeEvacInstance _ _ _ _ (Instance.Instance {Instance.diskTemplate = DTFile}) _ _ = fail "Instances of type file cannot be relocated" nodeEvacInstance opts nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTSharedFile}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly opts nl il inst gdx avail_nodes nodeEvacInstance opts nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTBlock}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly opts nl il inst gdx avail_nodes nodeEvacInstance opts nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTRbd}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly opts nl il inst gdx avail_nodes nodeEvacInstance opts nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTExt}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly opts nl il inst gdx avail_nodes nodeEvacInstance opts nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTGluster}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly opts nl il inst gdx avail_nodes nodeEvacInstance _ nl il ChangePrimary inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) _ _ = do (nl', inst', _, _) <- opToResult $ applyMove nl inst Failover let idx = Instance.idx inst il' = Container.add idx inst' il ops = iMoveToJob nl' il' idx Failover return (nl', il', ops) nodeEvacInstance opts nl il ChangeSecondary inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) gdx avail_nodes = evacOneNodeOnly opts nl il inst gdx avail_nodes -- The algorithm for ChangeAll is as follows: -- -- * generate all (primary, secondary) node pairs for the target groups -- * for each pair, execute the needed moves (r:s, f, r:s) and compute -- the final node list state and group score -- * select the best choice via a foldl that uses the same Either -- String solution as the ChangeSecondary mode nodeEvacInstance opts nl il ChangeAll inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) gdx avail_nodes = do let no_nodes = Left "no nodes available" node_pairs = [(p,s) | p <- avail_nodes, s <- avail_nodes, p /= s] (nl', il', ops, _) <- annotateResult "Can't find any good nodes for relocation" . eitherToResult $ foldl' (\accu nodes -> case evacDrbdAllInner opts nl il inst gdx nodes of Bad msg -> case accu of Right _ -> accu -- we don't need more details (which -- nodes, etc.) as we only selected -- this group if we can allocate on -- it, hence failures will not -- propagate out of this fold loop Left _ -> Left $ "Allocation failed: " ++ msg Ok result@(_, _, _, new_cv) -> let new_accu = Right result in case accu of Left _ -> new_accu Right (_, _, _, old_cv) -> if old_cv < new_cv then accu else new_accu ) no_nodes node_pairs return (nl', il', ops) -- | Generic function for changing one node of an instance. -- -- This is similar to 'nodeEvacInstance' but will be used in a few of -- its sub-patterns. It folds the inner function 'evacOneNodeInner' -- over the list of available nodes, which results in the best choice -- for relocation. evacOneNodeOnly :: AlgorithmOptions -> Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> Instance.Instance -- ^ The instance to be evacuated -> Gdx -- ^ The group we're targetting -> [Ndx] -- ^ The list of available nodes -- for allocation -> Result (Node.List, Instance.List, [OpCodes.OpCode]) evacOneNodeOnly opts nl il inst gdx avail_nodes = do op_fn <- case Instance.mirrorType inst of MirrorNone -> Bad "Can't relocate/evacuate non-mirrored instances" MirrorInternal -> Ok ReplaceSecondary MirrorExternal -> Ok FailoverToAny (nl', inst', _, ndx) <- annotateResult "Can't find any good node" . eitherToResult $ foldl' (evacOneNodeInner opts nl inst gdx op_fn) (Left "") avail_nodes let idx = Instance.idx inst il' = Container.add idx inst' il ops = iMoveToJob nl' il' idx (op_fn ndx) return (nl', il', ops) -- | Inner fold function for changing one node of an instance. -- -- Depending on the instance disk template, this will either change -- the secondary (for DRBD) or the primary node (for shared -- storage). However, the operation is generic otherwise. -- -- The running solution is either a @Left String@, which means we -- don't have yet a working solution, or a @Right (...)@, which -- represents a valid solution; it holds the modified node list, the -- modified instance (after evacuation), the score of that solution, -- and the new secondary node index. evacOneNodeInner :: AlgorithmOptions -> Node.List -- ^ Cluster node list -> Instance.Instance -- ^ Instance being evacuated -> Gdx -- ^ The group index of the instance -> (Ndx -> IMove) -- ^ Operation constructor -> EvacInnerState -- ^ Current best solution -> Ndx -- ^ Node we're evaluating as target -> EvacInnerState -- ^ New best solution evacOneNodeInner opts nl inst gdx op_fn accu ndx = case applyMoveEx (algIgnoreSoftErrors opts) nl inst (op_fn ndx) of Bad fm -> let fail_msg = " Node " ++ Container.nameOf nl ndx ++ " failed: " ++ show fm ++ ";" in either (Left . (++ fail_msg)) Right accu Ok (nl', inst', _, _) -> let nodes = Container.elems nl' -- The fromJust below is ugly (it can fail nastily), but -- at this point we should have any internal mismatches, -- and adding a monad here would be quite involved grpnodes = fromJust (gdx `lookup` Node.computeGroups nodes) new_cv = compCVNodes grpnodes new_accu = Right (nl', inst', new_cv, ndx) in case accu of Left _ -> new_accu Right (_, _, old_cv, _) -> if old_cv < new_cv then accu else new_accu -- | Compute result of changing all nodes of a DRBD instance. -- -- Given the target primary and secondary node (which might be in a -- different group or not), this function will 'execute' all the -- required steps and assuming all operations succceed, will return -- the modified node and instance lists, the opcodes needed for this -- and the new group score. evacDrbdAllInner :: AlgorithmOptions -> Node.List -- ^ Cluster node list -> Instance.List -- ^ Cluster instance list -> Instance.Instance -- ^ The instance to be moved -> Gdx -- ^ The target group index -- (which can differ from the -- current group of the -- instance) -> (Ndx, Ndx) -- ^ Tuple of new -- primary\/secondary nodes -> Result (Node.List, Instance.List, [OpCodes.OpCode], Score) evacDrbdAllInner opts nl il inst gdx (t_pdx, t_sdx) = do let primary = Container.find (Instance.pNode inst) nl idx = Instance.idx inst apMove = applyMoveEx $ algIgnoreSoftErrors opts -- if the primary is offline, then we first failover (nl1, inst1, ops1) <- if Node.offline primary then do (nl', inst', _, _) <- annotateResult "Failing over to the secondary" . opToResult $ apMove nl inst Failover return (nl', inst', [Failover]) else return (nl, inst, []) let (o1, o2, o3) = (ReplaceSecondary t_pdx, Failover, ReplaceSecondary t_sdx) -- we now need to execute a replace secondary to the future -- primary node (nl2, inst2, _, _) <- annotateResult "Changing secondary to new primary" . opToResult $ apMove nl1 inst1 o1 let ops2 = o1:ops1 -- we now execute another failover, the primary stays fixed now (nl3, inst3, _, _) <- annotateResult "Failing over to new primary" . opToResult $ apMove nl2 inst2 o2 let ops3 = o2:ops2 -- and finally another replace secondary, to the final secondary (nl4, inst4, _, _) <- annotateResult "Changing secondary to final secondary" . opToResult $ apMove nl3 inst3 o3 let ops4 = o3:ops3 il' = Container.add idx inst4 il ops = concatMap (iMoveToJob nl4 il' idx) $ reverse ops4 let nodes = Container.elems nl4 -- The fromJust below is ugly (it can fail nastily), but -- at this point we should have any internal mismatches, -- and adding a monad here would be quite involved grpnodes = fromJust (gdx `lookup` Node.computeGroups nodes) new_cv = compCVNodes grpnodes return (nl4, il', ops, new_cv) -- | Computes the nodes in a given group which are available for -- allocation. availableGroupNodes :: [(Gdx, [Ndx])] -- ^ Group index/node index assoc list -> IntSet.IntSet -- ^ Nodes that are excluded -> Gdx -- ^ The group for which we -- query the nodes -> Result [Ndx] -- ^ List of available node indices availableGroupNodes group_nodes excl_ndx gdx = do local_nodes <- maybe (Bad $ "Can't find group with index " ++ show gdx) Ok (lookup gdx group_nodes) let avail_nodes = filter (not . flip IntSet.member excl_ndx) local_nodes return avail_nodes -- | Updates the evac solution with the results of an instance -- evacuation. updateEvacSolution :: (Node.List, Instance.List, EvacSolution) -> Idx -> Result (Node.List, Instance.List, [OpCodes.OpCode]) -> (Node.List, Instance.List, EvacSolution) updateEvacSolution (nl, il, es) idx (Bad msg) = (nl, il, es { esFailed = (idx, msg):esFailed es}) updateEvacSolution (_, _, es) idx (Ok (nl, il, opcodes)) = (nl, il, es { esMoved = new_elem:esMoved es , esOpCodes = opcodes:esOpCodes es }) where inst = Container.find idx il new_elem = (idx, instancePriGroup nl inst, Instance.allNodes inst) -- | Node-evacuation IAllocator mode main function. tryNodeEvac :: AlgorithmOptions -> Group.List -- ^ The cluster groups -> Node.List -- ^ The node list (cluster-wide, not per group) -> Instance.List -- ^ Instance list (cluster-wide) -> EvacMode -- ^ The evacuation mode -> [Idx] -- ^ List of instance (indices) to be evacuated -> Result (Node.List, Instance.List, EvacSolution) tryNodeEvac opts _ ini_nl ini_il mode idxs = let evac_ndx = nodesToEvacuate ini_il mode idxs offline = map Node.idx . filter Node.offline $ Container.elems ini_nl excl_ndx = foldl' (flip IntSet.insert) evac_ndx offline group_ndx = map (\(gdx, (nl, _)) -> (gdx, map Node.idx (Container.elems nl))) $ splitCluster ini_nl ini_il (fin_nl, fin_il, esol) = foldl' (\state@(nl, il, _) inst -> let gdx = instancePriGroup nl inst pdx = Instance.pNode inst in updateEvacSolution state (Instance.idx inst) $ availableGroupNodes group_ndx (IntSet.insert pdx excl_ndx) gdx >>= nodeEvacInstance opts nl il mode inst gdx ) (ini_nl, ini_il, emptyEvacSolution) (map (`Container.find` ini_il) idxs) in return (fin_nl, fin_il, reverseEvacSolution esol) -- | Change-group IAllocator mode main function. -- -- This is very similar to 'tryNodeEvac', the only difference is that -- we don't choose as target group the current instance group, but -- instead: -- -- 1. at the start of the function, we compute which are the target -- groups; either no groups were passed in, in which case we choose -- all groups out of which we don't evacuate instance, or there were -- some groups passed, in which case we use those -- -- 2. for each instance, we use 'findBestAllocGroup' to choose the -- best group to hold the instance, and then we do what -- 'tryNodeEvac' does, except for this group instead of the current -- instance group. -- -- Note that the correct behaviour of this function relies on the -- function 'nodeEvacInstance' to be able to do correctly both -- intra-group and inter-group moves when passed the 'ChangeAll' mode. tryChangeGroup :: Group.List -- ^ The cluster groups -> Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> [Gdx] -- ^ Target groups; if empty, any -- groups not being evacuated -> [Idx] -- ^ List of instance (indices) to be evacuated -> Result (Node.List, Instance.List, EvacSolution) tryChangeGroup gl ini_nl ini_il gdxs idxs = let evac_gdxs = nub $ map (instancePriGroup ini_nl . flip Container.find ini_il) idxs target_gdxs = (if null gdxs then Container.keys gl else gdxs) \\ evac_gdxs offline = map Node.idx . filter Node.offline $ Container.elems ini_nl excl_ndx = foldl' (flip IntSet.insert) IntSet.empty offline group_ndx = map (\(gdx, (nl, _)) -> (gdx, map Node.idx (Container.elems nl))) $ splitCluster ini_nl ini_il (fin_nl, fin_il, esol) = foldl' (\state@(nl, il, _) inst -> let solution = do let ncnt = Instance.requiredNodes $ Instance.diskTemplate inst (grp, _, _) <- findBestAllocGroup gl nl il (Just target_gdxs) inst ncnt let gdx = Group.idx grp av_nodes <- availableGroupNodes group_ndx excl_ndx gdx nodeEvacInstance defaultOptions nl il ChangeAll inst gdx av_nodes in updateEvacSolution state (Instance.idx inst) solution ) (ini_nl, ini_il, emptyEvacSolution) (map (`Container.find` ini_il) idxs) in return (fin_nl, fin_il, reverseEvacSolution esol) -- | Standard-sized allocation method. -- -- This places instances of the same size on the cluster until we're -- out of space. The result will be a list of identically-sized -- instances. iterateAlloc :: AllocMethod iterateAlloc nl il limit newinst allocnodes ixes cstats = let depth = length ixes newname = printf "new-%d" depth::String newidx = Container.size il newi2 = Instance.setIdx (Instance.setName newinst newname) newidx newlimit = fmap (flip (-) 1) limit in case tryAlloc nl il newi2 allocnodes of Bad s -> Bad s Ok (AllocSolution { asFailures = errs, asSolution = sols3 }) -> let newsol = Ok (collapseFailures errs, nl, il, ixes, cstats) in case sols3 of Nothing -> newsol Just (xnl, xi, _, _) -> if limit == Just 0 then newsol else iterateAlloc xnl (Container.add newidx xi il) newlimit newinst allocnodes (xi:ixes) (totalResources xnl:cstats) -- | Predicate whether shrinking a single resource can lead to a valid -- allocation. sufficesShrinking :: (Instance.Instance -> AllocSolution) -> Instance.Instance -> FailMode -> Maybe Instance.Instance sufficesShrinking allocFn inst fm = case dropWhile (isNothing . asSolution . fst) . takeWhile (liftA2 (||) (elem fm . asFailures . fst) (isJust . asSolution . fst)) . map (allocFn &&& id) $ iterateOk (`Instance.shrinkByType` fm) inst of x:_ -> Just . snd $ x _ -> Nothing -- | Tiered allocation method. -- -- This places instances on the cluster, and decreases the spec until -- we can allocate again. The result will be a list of decreasing -- instance specs. tieredAlloc :: AllocMethod tieredAlloc nl il limit newinst allocnodes ixes cstats = case iterateAlloc nl il limit newinst allocnodes ixes cstats of Bad s -> Bad s Ok (errs, nl', il', ixes', cstats') -> let newsol = Ok (errs, nl', il', ixes', cstats') ixes_cnt = length ixes' (stop, newlimit) = case limit of Nothing -> (False, Nothing) Just n -> (n <= ixes_cnt, Just (n - ixes_cnt)) sortedErrs = map fst $ sortBy (comparing snd) errs suffShrink = sufficesShrinking (fromMaybe emptyAllocSolution . flip (tryAlloc nl' il') allocnodes) newinst bigSteps = filter isJust . map suffShrink . reverse $ sortedErrs progress (Ok (_, _, _, newil', _)) (Ok (_, _, _, newil, _)) = length newil' > length newil progress _ _ = False in if stop then newsol else let newsol' = case Instance.shrinkByType newinst . last $ sortedErrs of Bad _ -> newsol Ok newinst' -> tieredAlloc nl' il' newlimit newinst' allocnodes ixes' cstats' in if progress newsol' newsol then newsol' else case bigSteps of Just newinst':_ -> tieredAlloc nl' il' newlimit newinst' allocnodes ixes' cstats' _ -> newsol -- * Formatting functions -- | Given the original and final nodes, computes the relocation description. computeMoves :: Instance.Instance -- ^ The instance to be moved -> String -- ^ The instance name -> IMove -- ^ The move being performed -> String -- ^ New primary -> String -- ^ New secondary -> (String, [String]) -- ^ Tuple of moves and commands list; moves is containing -- either @/f/@ for failover or @/r:name/@ for replace -- secondary, while the command list holds gnt-instance -- commands (without that prefix), e.g \"@failover instance1@\" computeMoves i inam mv c d = case mv of Failover -> ("f", [mig]) FailoverToAny _ -> (printf "fa:%s" c, [mig_any]) FailoverAndReplace _ -> (printf "f r:%s" d, [mig, rep d]) ReplaceSecondary _ -> (printf "r:%s" d, [rep d]) ReplaceAndFailover _ -> (printf "r:%s f" c, [rep c, mig]) ReplacePrimary _ -> (printf "f r:%s f" c, [mig, rep c, mig]) where morf = if Instance.isRunning i then "migrate" else "failover" mig = printf "%s -f %s" morf inam::String mig_any = printf "%s -f -n %s %s" morf c inam::String rep n = printf "replace-disks -n %s %s" n inam::String -- | Converts a placement to string format. printSolutionLine :: Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Int -- ^ Maximum node name length -> Int -- ^ Maximum instance name length -> Placement -- ^ The current placement -> Int -- ^ The index of the placement in -- the solution -> (String, [String]) printSolutionLine nl il nmlen imlen plc pos = let pmlen = (2*nmlen + 1) (i, p, s, mv, c) = plc old_sec = Instance.sNode inst inst = Container.find i il inam = Instance.alias inst npri = Node.alias $ Container.find p nl nsec = Node.alias $ Container.find s nl opri = Node.alias $ Container.find (Instance.pNode inst) nl osec = Node.alias $ Container.find old_sec nl (moves, cmds) = computeMoves inst inam mv npri nsec -- FIXME: this should check instead/also the disk template ostr = if old_sec == Node.noSecondary then printf "%s" opri::String else printf "%s:%s" opri osec::String nstr = if s == Node.noSecondary then printf "%s" npri::String else printf "%s:%s" npri nsec::String in (printf " %3d. %-*s %-*s => %-*s %12.8f a=%s" pos imlen inam pmlen ostr pmlen nstr c moves, cmds) -- | Return the instance and involved nodes in an instance move. -- -- Note that the output list length can vary, and is not required nor -- guaranteed to be of any specific length. involvedNodes :: Instance.List -- ^ Instance list, used for retrieving -- the instance from its index; note -- that this /must/ be the original -- instance list, so that we can -- retrieve the old nodes -> Placement -- ^ The placement we're investigating, -- containing the new nodes and -- instance index -> [Ndx] -- ^ Resulting list of node indices involvedNodes il plc = let (i, np, ns, _, _) = plc inst = Container.find i il in nub . filter (>= 0) $ [np, ns] ++ Instance.allNodes inst -- | From two adjacent cluster tables get the list of moves that transitions -- from to the other getMoves :: (Table, Table) -> [MoveJob] getMoves (Table _ initial_il _ initial_plc, Table final_nl _ _ final_plc) = let plctoMoves (plc@(idx, p, s, mv, _)) = let inst = Container.find idx initial_il inst_name = Instance.name inst affected = involvedNodes initial_il plc np = Node.alias $ Container.find p final_nl ns = Node.alias $ Container.find s final_nl (_, cmds) = computeMoves inst inst_name mv np ns in (affected, idx, mv, cmds) in map plctoMoves . reverse . drop (length initial_plc) $ reverse final_plc -- | Inner function for splitJobs, that either appends the next job to -- the current jobset, or starts a new jobset. mergeJobs :: ([JobSet], [Ndx]) -> MoveJob -> ([JobSet], [Ndx]) mergeJobs ([], _) n@(ndx, _, _, _) = ([[n]], ndx) mergeJobs (cjs@(j:js), nbuf) n@(ndx, _, _, _) | null (ndx `intersect` nbuf) = ((n:j):js, ndx ++ nbuf) | otherwise = ([n]:cjs, ndx) -- | Break a list of moves into independent groups. Note that this -- will reverse the order of jobs. splitJobs :: [MoveJob] -> [JobSet] splitJobs = fst . foldl mergeJobs ([], []) -- | Given a list of commands, prefix them with @gnt-instance@ and -- also beautify the display a little. formatJob :: Int -> Int -> (Int, MoveJob) -> [String] formatJob jsn jsl (sn, (_, _, _, cmds)) = let out = printf " echo job %d/%d" jsn sn: printf " check": map (" gnt-instance " ++) cmds in if sn == 1 then ["", printf "echo jobset %d, %d jobs" jsn jsl] ++ out else out -- | Given a list of commands, prefix them with @gnt-instance@ and -- also beautify the display a little. formatCmds :: [JobSet] -> String formatCmds = unlines . concatMap (\(jsn, js) -> concatMap (formatJob jsn (length js)) (zip [1..] js)) . zip [1..] -- | Print the node list. printNodes :: Node.List -> [String] -> String printNodes nl fs = let fields = case fs of [] -> Node.defaultFields "+":rest -> Node.defaultFields ++ rest _ -> fs snl = sortBy (comparing Node.idx) (Container.elems nl) (header, isnum) = unzip $ map Node.showHeader fields in printTable "" header (map (Node.list fields) snl) isnum -- | Print the instance list. printInsts :: Node.List -> Instance.List -> String printInsts nl il = let sil = sortBy (comparing Instance.idx) (Container.elems il) helper inst = [ if Instance.isRunning inst then "R" else " " , Instance.name inst , Container.nameOf nl (Instance.pNode inst) , let sdx = Instance.sNode inst in if sdx == Node.noSecondary then "" else Container.nameOf nl sdx , if Instance.autoBalance inst then "Y" else "N" , printf "%3d" $ Instance.vcpus inst , printf "%5d" $ Instance.mem inst , printf "%5d" $ Instance.dsk inst `div` 1024 , printf "%5.3f" lC , printf "%5.3f" lM , printf "%5.3f" lD , printf "%5.3f" lN ] where DynUtil lC lM lD lN = Instance.util inst header = [ "F", "Name", "Pri_node", "Sec_node", "Auto_bal" , "vcpu", "mem" , "dsk", "lCpu", "lMem", "lDsk", "lNet" ] isnum = False:False:False:False:False:repeat True in printTable "" header (map helper sil) isnum -- | Shows statistics for a given node list. printStats :: String -> Node.List -> String printStats lp nl = let dcvs = compDetailedCV $ Container.elems nl (weights, names) = unzip detailedCVInfo hd = zip3 (weights ++ repeat 1) (names ++ repeat "unknown") dcvs header = [ "Field", "Value", "Weight" ] formatted = map (\(w, h, val) -> [ h , printf "%.8f" val , printf "x%.2f" w ]) hd in printTable lp header formatted $ False:repeat True -- | Convert a placement into a list of OpCodes (basically a job). iMoveToJob :: Node.List -- ^ The node list; only used for node -- names, so any version is good -- (before or after the operation) -> Instance.List -- ^ The instance list; also used for -- names only -> Idx -- ^ The index of the instance being -- moved -> IMove -- ^ The actual move to be described -> [OpCodes.OpCode] -- ^ The list of opcodes equivalent to -- the given move iMoveToJob nl il idx move = let inst = Container.find idx il iname = Instance.name inst lookNode n = case mkNonEmpty (Container.nameOf nl n) of -- FIXME: convert htools codebase to non-empty strings Bad msg -> error $ "Empty node name for idx " ++ show n ++ ": " ++ msg ++ "??" Ok ne -> Just ne opF = OpCodes.OpInstanceMigrate { OpCodes.opInstanceName = iname , OpCodes.opInstanceUuid = Nothing , OpCodes.opMigrationMode = Nothing -- default , OpCodes.opOldLiveMode = Nothing -- default as well , OpCodes.opTargetNode = Nothing -- this is drbd , OpCodes.opTargetNodeUuid = Nothing , OpCodes.opAllowRuntimeChanges = False , OpCodes.opIgnoreIpolicy = False , OpCodes.opMigrationCleanup = False , OpCodes.opIallocator = Nothing , OpCodes.opAllowFailover = True , OpCodes.opIgnoreHvversions = True } opFA n = opF { OpCodes.opTargetNode = lookNode n } -- not drbd opR n = OpCodes.OpInstanceReplaceDisks { OpCodes.opInstanceName = iname , OpCodes.opInstanceUuid = Nothing , OpCodes.opEarlyRelease = False , OpCodes.opIgnoreIpolicy = False , OpCodes.opReplaceDisksMode = OpCodes.ReplaceNewSecondary , OpCodes.opReplaceDisksList = [] , OpCodes.opRemoteNode = lookNode n , OpCodes.opRemoteNodeUuid = Nothing , OpCodes.opIallocator = Nothing } in case move of Failover -> [ opF ] FailoverToAny np -> [ opFA np ] ReplacePrimary np -> [ opF, opR np, opF ] ReplaceSecondary ns -> [ opR ns ] ReplaceAndFailover np -> [ opR np, opF ] FailoverAndReplace ns -> [ opF, opR ns ] -- * Node group functions -- | Computes the group of an instance. instanceGroup :: Node.List -> Instance.Instance -> Result Gdx instanceGroup nl i = let sidx = Instance.sNode i pnode = Container.find (Instance.pNode i) nl snode = if sidx == Node.noSecondary then pnode else Container.find sidx nl pgroup = Node.group pnode sgroup = Node.group snode in if pgroup /= sgroup then fail ("Instance placed accross two node groups, primary " ++ show pgroup ++ ", secondary " ++ show sgroup) else return pgroup -- | Computes the group of an instance per the primary node. instancePriGroup :: Node.List -> Instance.Instance -> Gdx instancePriGroup nl i = let pnode = Container.find (Instance.pNode i) nl in Node.group pnode -- | Compute the list of badly allocated instances (split across node -- groups). findSplitInstances :: Node.List -> Instance.List -> [Instance.Instance] findSplitInstances nl = filter (not . isOk . instanceGroup nl) . Container.elems -- | Splits a cluster into the component node groups. splitCluster :: Node.List -> Instance.List -> [(Gdx, (Node.List, Instance.List))] splitCluster nl il = let ngroups = Node.computeGroups (Container.elems nl) in map (\(gdx, nodes) -> let nidxs = map Node.idx nodes nodes' = zip nidxs nodes instances = Container.filter ((`elem` nidxs) . Instance.pNode) il in (gdx, (Container.fromList nodes', instances))) ngroups -- | Compute the list of nodes that are to be evacuated, given a list -- of instances and an evacuation mode. nodesToEvacuate :: Instance.List -- ^ The cluster-wide instance list -> EvacMode -- ^ The evacuation mode we're using -> [Idx] -- ^ List of instance indices being evacuated -> IntSet.IntSet -- ^ Set of node indices nodesToEvacuate il mode = IntSet.delete Node.noSecondary . foldl' (\ns idx -> let i = Container.find idx il pdx = Instance.pNode i sdx = Instance.sNode i dt = Instance.diskTemplate i withSecondary = case dt of DTDrbd8 -> IntSet.insert sdx ns _ -> ns in case mode of ChangePrimary -> IntSet.insert pdx ns ChangeSecondary -> withSecondary ChangeAll -> IntSet.insert pdx withSecondary ) IntSet.empty
ganeti-github-testing/ganeti-test-1
src/Ganeti/HTools/Cluster.hs
bsd-2-clause
80,090
0
23
25,082
17,349
9,404
7,945
1,287
8
import CircUtils.QacgBool import Test.QuickCheck import Text.Printf main = mapM_ (\(s,a) -> printf "%-25s: " s >> a) tests exp1 = Xor $ map V ["a","b","c"] exp2 = Xor [And (map V ["e","f","g"]), V "a"] exp3 = And [exp1,exp2] exp4 = Xor [exp3,exp1] exp5 = And [exp3,exp4] prop_simp exp a = if length a < 7 then True else evaluate a (simplify exp) == evaluate a exp prop_flat exp a = if length a < 7 then True else evaluate a (flatten exp) == evaluate a exp tests = [("Simplify/exp1", quickCheck (prop_simp exp1)) ,("Simplify/exp2", quickCheck (prop_simp exp2)) ,("Simplify/exp3", quickCheck (prop_simp exp3)) ,("Simplify/exp4", quickCheck (prop_simp exp4)) ,("Simplify/exp5", quickCheck (prop_simp exp5)) ,("flat/exp1", quickCheck (prop_flat exp1)) ,("flat/exp2", quickCheck (prop_flat exp2)) ,("flat/exp3", quickCheck (prop_flat exp3)) ,("flat/exp4", quickCheck (prop_flat exp4)) ,("flat/exp5", quickCheck (prop_flat exp5))]
aparent/qacg
src/QACG/CircUtils/QacgBoolTest.hs
bsd-3-clause
1,005
6
10
208
444
231
213
21
2
{-# LANGUAGE TupleSections, TypeFamilies, FlexibleContexts, PackageImports #-} module TestPusher (XmlPusher(..), Zero(..), One(..), Two(..), testPusher) where import Control.Monad import Control.Concurrent import Data.Maybe import Data.Pipe import Data.Pipe.ByteString import System.IO import Text.XML.Pipe import XmlPusher testPusher :: XmlPusher xp => xp Handle -> NumOfHandle xp Handle -> PusherArg xp -> IO () testPusher tp hs as = do xp <- generate hs as >>= return . (`asTypeOf` tp) void . forkIO . runPipe_ $ readFrom xp =$= convert (xmlString . (: [])) =$= toHandle stdout runPipe_ $ fromHandle stdin =$= xmlEvent =$= convert fromJust =$= xmlNode [] =$= writeTo xp
YoshikuniJujo/forest
subprojects/xml-push/TestPusher.hs
bsd-3-clause
693
2
13
116
240
129
111
22
1
{-# LANGUAGE OverloadedStrings #-} module Main ( main ) where import Control.Applicative import Data.Monoid import qualified Data.Text as T import qualified Data.Text.IO as T import Options.Applicative hiding ( (&) ) import System.FilePath import Text.LaTeX.Base as Tex import Foreign.Inference.Interface data Opts = Opts { destRoot :: FilePath , interfaceFiles :: [FilePath] } deriving (Show) cmdOpts :: Parser Opts cmdOpts = Opts <$> strOption ( long "root" <> short 'r' <> metavar "DIR" <> help "The root directory in which generated tables will be placed") <*> arguments str ( metavar "FILE" ) main :: IO () main = execParser args >>= realMain where args = info (helper <*> cmdOpts) ( fullDesc <> progDesc "Output LaTeX tables for the dissertation" <> header "iitables - generate LaTeX tables") realMain :: Opts -> IO () realMain opts = do interfaces <- mapM readLibraryInterface (interfaceFiles opts) let mt = renderMemoryStatsTable interfaces pt = renderPointerStatsTable interfaces ot = renderOutStatsTable interfaces at = renderArrayStatsTable interfaces nt = renderNullStatsTable interfaces T.writeFile (destRoot opts </> "pointers/overall-table.tex") (Tex.render pt) T.writeFile (destRoot opts </> "pointers/null-table.tex") (Tex.render nt) T.writeFile (destRoot opts </> "pointers/out-table.tex") (Tex.render ot) T.writeFile (destRoot opts </> "pointers/array-table.tex") (Tex.render at) T.writeFile (destRoot opts </> "memory/big-table.tex") (Tex.render mt) -- renderPointerStatsTable :: [LibraryInterface] -> LaTeX -- renderPointerStatsTable ifaces = -- mconcat (map pointerSummaryToRow pointerSummaries) -- <> (raw "\\midrule" %: "") -- <> totals -- where -- pointerSummaries = map toPointerSummary ifaces -- totals = textbf (texy ("Total" :: Text)) -- & summField psNumFuncs pointerSummaries -- & summField psOutFuncs pointerSummaries -- & summField psOutParams pointerSummaries -- & summField psInOutFuncs pointerSummaries -- & summField psInOutParams pointerSummaries -- & summField psArrayFuncs pointerSummaries -- & summField psArrayParams pointerSummaries -- & texy (hmean (map psPercentAnnot pointerSummaries)) -- <> lnbk %: "" renderPointerStatsTable :: [LibraryInterface] -> LaTeX renderPointerStatsTable ifaces = mconcat (map pointerSummaryToRow pointerSummaries) <> (raw "\\midrule" %: "") <> totals where pointerSummaryToRow :: PointerSummary -> LaTeX pointerSummaryToRow ps = texy (psLibraryName ps) & texy (psNumFuncs ps) & texy (psPercentAnnot ps) <> lnbk %: psLibraryName ps pointerSummaries = map toPointerSummary ifaces totals = textbf (texy ("Total" :: Text)) & summField psNumFuncs pointerSummaries & texy (hmean (map psPercentAnnot pointerSummaries)) <> lnbk %: "" renderOutStatsTable :: [LibraryInterface] -> LaTeX renderOutStatsTable ifaces = mconcat (map pointerSummaryToRow pointerSummaries) <> (raw "\\midrule" %: "") <> totals where pointerSummaryToRow :: PointerSummary -> LaTeX pointerSummaryToRow ps = texy (psLibraryName ps) & texy (psNumFuncs ps) & texy (psOutFuncs ps) & texy (psOutParams ps) & texy (psInOutFuncs ps) & texy (psInOutParams ps) <> lnbk %: psLibraryName ps pointerSummaries = map toPointerSummary ifaces totals = textbf (texy ("Total" :: Text)) & summField psNumFuncs pointerSummaries & summField psOutFuncs pointerSummaries & summField psOutParams pointerSummaries & summField psInOutFuncs pointerSummaries & summField psInOutParams pointerSummaries <> lnbk %: "" renderArrayStatsTable :: [LibraryInterface] -> LaTeX renderArrayStatsTable ifaces = mconcat (map pointerSummaryToRow pointerSummaries) <> (raw "\\midrule" %: "") <> totals where pointerSummaryToRow :: PointerSummary -> LaTeX pointerSummaryToRow ps = texy (psLibraryName ps) & texy (psNumFuncs ps) & texy (psArrayFuncs ps) & texy (psArrayParams ps) <> lnbk %: psLibraryName ps pointerSummaries = map toPointerSummary ifaces totals = textbf (texy ("Total" :: Text)) & summField psNumFuncs pointerSummaries & summField psArrayFuncs pointerSummaries & summField psArrayParams pointerSummaries <> lnbk %: "" renderNullStatsTable :: [LibraryInterface] -> LaTeX renderNullStatsTable ifaces = mconcat (map pointerSummaryToRow pointerSummaries) <> (raw "\\midrule" %: "") <> totals where pointerSummaryToRow :: PointerSummary -> LaTeX pointerSummaryToRow ps = texy (psLibraryName ps) & texy (psNumFuncs ps) & texy (psNullFuncs ps) & texy (psNullParams ps) <> lnbk %: psLibraryName ps pointerSummaries = map toPointerSummary ifaces totals = textbf (texy ("Total" :: Text)) & summField psNumFuncs pointerSummaries & summField psNullFuncs pointerSummaries & summField psNullParams pointerSummaries <> lnbk %: "" renderMemoryStatsTable :: [LibraryInterface] -> LaTeX renderMemoryStatsTable ifaces = mconcat (map memorySummaryToRow memorySummaries) <> (raw "\\midrule" %: "") <> totals where memorySummaries = map toMemorySummary ifaces totals = textbf (texy ("Total" :: Text)) & summField msNumFuncs memorySummaries & summField msNumAllocators memorySummaries & summField msNumFinalizers memorySummaries <> lnbk %: "" memorySummaryToRow :: MemorySummary -> LaTeX memorySummaryToRow ms = texy (msLibraryName ms) & texy (msNumFuncs ms) & texy (msNumAllocators ms) & texy (msNumFinalizers ms) <> lnbk %: "" -- | Harmonic mean of a list of ints hmean :: [Int] -> Int hmean ns = round $ realN / sum recips where realN :: Double realN = fromIntegral (length ns) recips :: [Double] recips = map ((1.0/) . fromIntegral) ns summField :: (a -> Int) -> [a] -> LaTeX summField f = texy . foldr (+) 0 . map f data MemorySummary = MemorySummary { msLibraryName :: Text , msNumFuncs :: Int , msNumAllocators :: Int , msNumFinalizers :: Int } deriving (Eq, Ord, Show) toMemorySummary :: LibraryInterface -> MemorySummary toMemorySummary i = MemorySummary { msLibraryName = T.pack $ dropExtensions $ libraryName i , msNumFuncs = nFuncs , msNumFinalizers = countIf (paramHasAnnot (==PAFinalize)) ps , msNumAllocators = countIf (funcIs isAlloc) fs } where nFuncs = length fs fs = libraryFunctions i ps = concatMap foreignFunctionParameters fs isAlloc :: FuncAnnotation -> Bool isAlloc (FAAllocator _) = True isAlloc _ = False data PointerSummary = PointerSummary { psLibraryName :: Text , psNumFuncs :: Int , psOutFuncs :: Int , psOutParams :: Int , psInOutFuncs :: Int , psInOutParams :: Int , psArrayFuncs :: Int , psArrayParams :: Int , psNullFuncs :: Int , psNullParams :: Int , psPercentAnnot :: Int } deriving (Eq, Ord, Show) toPointerSummary :: LibraryInterface -> PointerSummary toPointerSummary i = PointerSummary { psLibraryName = T.pack $ dropExtensions $ libraryName i , psNumFuncs = nFuncs , psOutFuncs = countIf (funcHasAnnot (==PAOut)) fs , psOutParams = countIf (paramHasAnnot (==PAOut)) ps , psInOutFuncs = countIf (funcHasAnnot (==PAInOut)) fs , psInOutParams = countIf (paramHasAnnot (==PAInOut)) ps , psArrayFuncs = countIf (funcHasAnnot isArray) fs , psArrayParams = countIf (paramHasAnnot isArray) ps , psNullFuncs = countIf (funcHasAnnot (==PANotNull)) fs , psNullParams = countIf (paramHasAnnot (==PANotNull)) ps , psPercentAnnot = round $ 100.0 * totalAnnotFuncs / fromIntegral nFuncs } where totalAnnotFuncs :: Double totalAnnotFuncs = fromIntegral $ countIf (funcHasAnnot isPointerAnnot) fs nFuncs = length fs fs = libraryFunctions i ps = concatMap foreignFunctionParameters fs isPointerAnnot :: ParamAnnotation -> Bool isPointerAnnot (PAArray _) = True isPointerAnnot PAOut = True isPointerAnnot PAInOut = True isPointerAnnot PANotNull = True isPointerAnnot _ = False isArray :: ParamAnnotation -> Bool isArray (PAArray _) = True isArray _ = False countIf :: (t -> Bool) -> [t] -> Int countIf p = length . filter p paramHasAnnot :: (ParamAnnotation -> Bool) -> Parameter -> Bool paramHasAnnot p = any p . parameterAnnotations funcHasAnnot :: (ParamAnnotation -> Bool) -> ForeignFunction -> Bool funcHasAnnot p = or . map (paramHasAnnot p) . foreignFunctionParameters funcIs :: (FuncAnnotation -> Bool) -> ForeignFunction -> Bool funcIs p = or . map p . foreignFunctionAnnotations
travitch/iiglue
tools/IITableOutput.hs
bsd-3-clause
9,446
0
17
2,544
2,383
1,241
1,142
206
1
module Day11 where import Data.List import Control.Applicative {- Day 11: Corporate Policy -} input :: String input = "cqjxjnds" inc :: Char -> (Bool, String) -> (Bool, String) inc x (carry, xs) | not carry = (False, x:xs) | x == 'z' = (True, 'a':xs) | x `elem` "iol" = (False, (succ . succ $ x) : xs) | otherwise = (False, succ x : xs) incStr :: String -> String incStr = snd . foldr inc (True, []) has2Pairs :: String -> Bool has2Pairs = (>= 2) . length . filter ((>= 2) . length) . group hasStraight :: String -> Bool hasStraight = any ((>= 3) . length) . group . zipWith ($) (scanl' (.) id (repeat pred)) isValid :: String -> Bool isValid = liftA2 (&&) has2Pairs hasStraight getNextPassword :: String -> String getNextPassword = head . filter isValid . tail . iterate incStr day11 :: IO () day11 = print $ getNextPassword input {- Part Two -} input2 :: String input2 = "cqjxxyzz" day11' :: IO () day11' = print $ getNextPassword input2
Rydgel/advent-of-code
src/Day11.hs
bsd-3-clause
1,013
0
10
250
412
226
186
28
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeSynonymInstances #-} module Sequent.Check ( CheckT , Check , evalCheck , evalCheckT , liftEnv) where import Control.Applicative (Alternative) import Control.Monad (MonadPlus) import Control.Monad.Trans (MonadTrans, lift) import Control.Monad.Trans.Maybe (MaybeT, runMaybeT) import Control.Monad.Writer (MonadWriter, WriterT, listen, pass, runWriterT, tell) import Data.Functor.Identity (Identity, runIdentity) import Sequent.Env (EnvT, evalEnvT) -- Wrapper around String to add a new line between two non-empty lines -- when appending them together newtype Lines = Lines { unLines :: String } deriving (Eq) instance Show Lines where show = unLines instance Monoid Lines where mempty = Lines "" mappend a b | b == mempty = a | a == mempty = b | otherwise = Lines (unLines a ++ "\n" ++ unLines b) -- Everything that is needed when checking a proof: -- + MaybeT to be able to terminate an incorrect proof -- + EnvT to generate fresh variables -- + WriterT to log the steps of the proof -- TODO replace MaybeT with some instance of MonadError ? newtype CheckT m a = CheckT { runCheckT :: MaybeT (WriterT Lines (EnvT m)) a } deriving ( Functor , Applicative , Alternative , MonadPlus , Monad) type Check = CheckT Identity -- Write a custom instance to be able to use the "tell :: String -> _" interface -- from the outside, keeping the Lines type hidden and have a custom mappend instance Monad m => MonadWriter String (CheckT m) where tell = CheckT . tell . Lines listen = CheckT . fmap (fmap unLines) . listen . runCheckT pass = CheckT . pass . fmap (fmap (\f -> Lines . f . unLines)) . runCheckT -- The MonadTrans instance can't be automatically derived because of the StateT -- in the EnvT. See (https://www.reddit.com/r/haskell/comments/3mrkwe/issue_deriving_monadtrans_for_chained_custom/) instance MonadTrans CheckT where lift = CheckT . lift . lift . lift evalCheckT :: (Monad m) => CheckT m a -> m (Maybe a, String) evalCheckT = fmap (fmap unLines) . evalEnvT . runWriterT . runMaybeT . runCheckT evalCheck :: Check a -> (Maybe a, String) evalCheck = runIdentity . evalCheckT liftEnv :: (Monad m) => EnvT m a -> CheckT m a liftEnv = CheckT . lift . lift
matthieubulte/sequent
src/Sequent/Check.hs
bsd-3-clause
2,638
0
14
717
582
324
258
47
1
module Options.TypesSpec (main, spec) where import Options.Types import Test.Hspec import Test.QuickCheck import Test.QuickCheck.Instances main :: IO () main = hspec spec spec :: Spec spec = do describe "someFunction" $ do it "should work fine" $ do property someFunction someFunction :: Bool -> Bool -> Property someFunction x y = x === y
athanclark/optionz
test/Options/TypesSpec.hs
bsd-3-clause
357
0
13
70
116
61
55
14
1
{-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PolymorphicComponents #-} module NHorn.LaCarte ( Expr(..), (:+:)(..), (:<:), foldExpr, inj, prj, ) where newtype Expr f = In (f (Expr f)) data (f2 :+: g) a s f e = Inl (f2 a s f e) | Inr (g a s f e) instance (Functor (f2 a s f), Functor (g a s f)) => Functor ((f2 :+: g) a s f) where fmap h (Inl f) = Inl (fmap h f) fmap h (Inr g) = Inr (fmap h g) foldExpr :: Functor f => (f a -> a) -> Expr f -> a foldExpr f (In t) = f (fmap (foldExpr f) t) --------------------- Quite a bit harder part of code data Pos = Here | Le Pos | Ri Pos data Res = Found Pos | NotFound | Ambiguous type family Elem (e :: (* -> * -> *) -> * -> * -> * -> *) (p :: (* -> * -> *) -> * -> * -> * -> * ) :: Res where Elem e e = Found Here Elem e (l :+: r) = Choose (Elem e l ) (Elem e r ) Elem e p = NotFound type family Choose (l :: Res) (r :: Res) :: Res where Choose (Found x ) (Found y) = Ambiguous Choose Ambiguous y = Ambiguous Choose x Ambiguous = Ambiguous Choose (Found x) y = Found (Le x ) Choose x (Found y)= Found (Ri y) Choose x y = NotFound data Proxy a = P class Subsume (res :: Res) f2 g a s f where inj' :: Proxy res -> f2 a s f a' -> g a s f a' prj' :: Proxy res -> g a s f a' -> Maybe (f2 a s f a') instance Subsume (Found Here) f2 f2 a s f where inj' _ = id prj' _ = Just instance Subsume (Found p) f2 l a s f => Subsume (Found (Le p)) f2 (l :+: r ) a s f where inj' _ = Inl . inj' (P :: Proxy (Found p)) prj' _ (Inl x ) = prj' (P :: Proxy (Found p)) x prj' _ (Inr _) = Nothing instance Subsume (Found p) f2 r a s f => Subsume (Found (Ri p)) f2 (l :+: r ) a s f where inj' _ = Inr . inj' (P :: Proxy (Found p)) prj' _ (Inr x ) = prj' (P :: Proxy (Found p)) x prj' _ (Inl _) = Nothing type (f2 :<: g) a s f = Subsume (Elem f2 g) f2 g a s f inj :: forall f2 g a s f e. (f2 :<: g) a s f => f2 a s f e -> g a s f e inj = inj' (P :: Proxy (Elem f2 g)) prj :: forall f2 g a s f e. (f2 :<: g) a s f => g a s f e -> Maybe (f2 a s f e) prj = prj' (P :: Proxy (Elem f2 g))
esengie/algebraic-checker
src/NHorn/LaCarte.hs
bsd-3-clause
2,453
8
11
682
1,213
649
564
59
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} -- | Functions for traversing the comment AST and analyzing the nodes it contains. -- -- To start traversing the comment AST, use 'Clang.Cursor.getParsedComment' to -- retrieve the comment from an AST node that may be associated with one (for -- example, any kind of declaration). You can access child nodes in the AST using -- 'getChildren'. Most of the important information about comment AST nodes is -- contained in the fields of the 'ParsedComment' type. -- -- This module is intended to be imported qualified. module Clang.Comment ( -- * Navigating the comment AST getChildren -- * Predicates and transformations , isWhitespace , hasTrailingNewline , getTagCommentAsString , getFullCommentAsHTML , getFullCommentAsXML -- * Comment AST nodes , ParsedComment(..) , ParamPassDirection(..) , FFI.ParamPassDirectionKind (..) , FFI.InlineCommandRenderStyle (..) ) where import Control.Applicative import Control.Monad import Control.Monad.IO.Class import Data.Maybe import Clang.Internal.Comment import qualified Clang.Internal.FFI as FFI import Clang.Internal.Monad -- | Returns the children nodes of the given comment in the comment AST. getChildren :: ClangBase m => ParsedComment s' -> ClangT s m [ParsedComment s] getChildren pc = do let c = getFFIComment pc numC <- liftIO $ FFI.comment_getNumChildren c mayCs <- forM [0..(numC - 1)] $ \i -> parseComment =<< liftIO (FFI.comment_getChild mkProxy c i) return $ catMaybes mayCs -- | Returns 'True' if the provided comment is a 'TextComment' which is empty or contains -- only whitespace, or if it is a 'ParagraphComment' which contains only whitespace -- 'TextComment' nodes. isWhitespace :: ClangBase m => ParsedComment s' -> ClangT s m Bool isWhitespace c = liftIO $ FFI.comment_isWhitespace (getFFIComment c) -- | Returns 'True' if the provided comment is inline content and has a newline immediately -- following it in the comment text. Newlines between paragraphs do not count. hasTrailingNewline :: ClangBase m => ParsedComment s' -> ClangT s m Bool hasTrailingNewline c = liftIO $ FFI.inlineContentComment_hasTrailingNewline (getFFIComment c) -- | Returns a string representation of an 'HTMLStartTagComment' or 'HTMLEndTagComment'. -- For other kinds of comments, returns 'Nothing'. getTagCommentAsString :: ClangBase m => ParsedComment s' -> ClangT s m (Maybe (FFI.ClangString s)) getTagCommentAsString (HTMLStartTagComment c _ _ _) = Just <$> FFI.hTMLTagComment_getAsString c getTagCommentAsString (HTMLEndTagComment c _) = Just <$> FFI.hTMLTagComment_getAsString c getTagCommentAsString _ = return Nothing -- | Converts the given 'FullComment' to an HTML fragment. -- -- Specific details of HTML layout are subject to change. Don't try to parse -- this HTML back into an AST; use other APIs instead. -- -- Currently the following CSS classes are used: -- -- * \"para-brief\" for \'brief\' paragraph and equivalent commands; -- -- * \"para-returns\" for \'returns\' paragraph and equivalent commands; -- -- * \"word-returns\" for the \"Returns\" word in a \'returns\' paragraph. -- -- Function argument documentation is rendered as a \<dl\> list with arguments -- sorted in function prototype order. The following CSS classes are used: -- -- * \"param-name-index-NUMBER\" for parameter name (\<dt\>); -- -- * \"param-descr-index-NUMBER\" for parameter description (\<dd\>); -- -- * \"param-name-index-invalid\" and \"param-descr-index-invalid\" are used if -- parameter index is invalid. -- -- Template parameter documentation is rendered as a \<dl\> list with -- parameters sorted in template parameter list order. The following CSS classes are used: -- -- * \"tparam-name-index-NUMBER\" for parameter name (\<dt\>); -- -- * \"tparam-descr-index-NUMBER\" for parameter description (\<dd\>); -- -- * \"tparam-name-index-other\" and \"tparam-descr-index-other\" are used for -- names inside template template parameters; -- -- * \"tparam-name-index-invalid\" and \"tparam-descr-index-invalid\" are used if -- parameter position is invalid. getFullCommentAsHTML :: ClangBase m => ParsedComment s' -> ClangT s m (Maybe (FFI.ClangString s)) getFullCommentAsHTML (FullComment c) = Just <$> FFI.fullComment_getAsHTML c getFullCommentAsHTML _ = return Nothing -- | Converts the given 'FullComment' to an XML document. -- -- A Relax NG schema for the XML is distributed in the \"comment-xml-schema.rng\" file -- inside the libclang source tree. getFullCommentAsXML :: ClangBase m => ParsedComment s' -> ClangT s m (Maybe (FFI.ClangString s)) getFullCommentAsXML (FullComment c) = Just <$> FFI.fullComment_getAsXML c getFullCommentAsXML _ = return Nothing
ony/LibClang
src/Clang/Comment.hs
bsd-3-clause
4,775
0
14
760
641
355
286
42
1
{-# OPTIONS_GHC -cpp #-} module Code28_Tupling where (□) :: [a] -> [a] -> [a] xs □ ys = mix xs (ys, reverse ys) mix :: [a] -> ([a],[a]) -> [a] mix [] (ys,_) = ys mix (x:xs) (ys,sy) = ys ++ [x] ++ mix xs (sy,ys) boxall :: [[a]] -> [a] boxall = foldr (□) [] op :: [a] -> ([a], [a]) -> ([a], [a]) op xs (ys,sy) = (xs □ ys, xs ⊠ sy) (⊠) :: [a] -> [a] -> [a] #ifdef SPEC_OF_BOXTIMES xs ⊠ sy = reverse (xs □ (reverse sy)) #else [] ⊠ sy = sy (x:xs) ⊠ sy = (xs ⊠ (reverse sy)) ++ [x] ++ sy #endif op1 :: [a] -> ([a], [a]) -> ([a], [a]) op1 [] (ys,sy) = (ys,sy) op1 (x:xs) (ys,sy) = (ys ++ [x] ++ zs,sz ++ [x] ++ sy) where (zs,sz) = op1 xs (sy,ys) op2 :: [a] -> ([a], [a]) -> ([a], [a]) op2 xs (ys,sy) = if even (length xs) then (mix xs (ys,sy), mix (reverse xs) (sy,ys)) else (mix xs (ys,sy), mix (reverse xs) (ys,sy))
sampou-org/pfad
Code/Code28_Tupling.hs
bsd-3-clause
1,039
0
9
384
585
340
245
22
2
{-# LANGUAGE OverloadedStrings #-} module Module ( Module(..) , listModules ) where import Data.Text (Text) import Xml data Codepool = Core | Community | Local deriving (Show) data Module = Module { moduleCodePool :: Codepool , moduleNameSpace :: String , moduleName :: String , moduleActive :: Bool } deriving (Show) data Config = Config { } deriving (Show) listModules :: Text -> IO ([Module]) listModules rootPath = do fileMap <- readXmlFileMap
dxtr/hagento
src/Magento/Module.hs
bsd-3-clause
589
1
8
212
140
84
56
-1
-1
{-# LANGUAGE TypeOperators #-} module World ( World(..),FinalColor,Color, Object(..), Shape (..),calcNormal, Light(..),cmul,colRound,cadd,convertColtoFCol -- Creation functions -- Standard Array functions ,vUp ,vDown ,vForward ,vBackward ,vRight ,vLeft -- Color conviniece functions ,t2c -- -- | World Construction ,emptyWorld ,addObjectToWorld ,addLightToWorld ,createSphere ,createPlane ,createLight ,TextColor (..) ,createObj ,Entity (..) ,createWorld ,v2Light ,v2Plaine ,v2Sphere ,clamp ) where import qualified Data.Array.Repa as R import Vector import Data.Word import Control.Monad.State.Lazy -- | Color type type Color = (Double,Double,Double) -- | Color type that is compatible with the Repa-IO functions type FinalColor = (Word8,Word8,Word8) -- | Textual interface for some standard colors data TextColor = Red | Blue | Green | Black | White -- | Datatype managing the world data World = World { items :: [Object] ,lights :: [Light] } -- | A colective type for entitys that can be added into the world data Entity = EntO Object | EntL Light -- | The world state monad type WorldWrapper = State World Entity -- | Datatype displaying visible objects data Object = Object { shape :: Shape ,color :: Color ,reflectance :: Double ,shininess::Double } deriving (Show) -- | datatype for the shapes of objects that can be displayed data Shape = Sphere { spos :: DoubleVector ,radius :: Double } | Plane { ppos :: DoubleVector ,pnormal :: DoubleVector } deriving (Show) data Light = Light{ lpos :: DoubleVector ,lcolor:: Color } -- | Function for calculating the normal at a specific point calcNormal :: Object -> DoubleVector -> DoubleVector calcNormal o@Object{shape =s@Sphere{spos = pos}} pnt = sphereNormal s pnt calcNormal o@Object{shape =s@Plane{pnormal = norm}} _ = norm -- | Heplerfunction for calculating the shape of a sphere sphereNormal :: Shape -> DoubleVector -> DoubleVector sphereNormal s@Sphere{spos= pos} pnt = normalize $ R.computeUnboxedS $ R.zipWith (-) pnt pos -- | Color management functions -- | Color addition function cadd :: Color -> Color -> Color cadd (r1,g1,b1) (r2,g2,b2) = (r1 + r2,g1 + g2,b1 + b2) -- | Color multiplication function cmul :: Color -> Double -> Color cmul (r,g,b) d = (r*d,g*d,b*d) -- | Helper function to convert a color of type Double to Word8 colRound :: Double -> Word8 colRound d | d >= 255.0 = 255 | d <= 0.0 = 0 | otherwise = round d -- | Function to convert a color of type Double to Word8 convertColtoFCol :: Color -> FinalColor convertColtoFCol (r,g,b) = (colRound r, colRound g, colRound b) -- | Function to convert the text color interface to an actual color t2c :: TextColor -> Color t2c Red = (255.0,0.0,0.0) t2c Green = (0.0,255.0,0.0) t2c Blue = (0.0,0.0,255.0) t2c Black = (0.0,0.0,0.0) t2c White = (255.0,255.0,255.0) -- -- |Constructor Functions -- Standard Array functions -- | A Up Vector for the simple constructors vUp :: (Double,Double,Double) vUp = (0.0,1.0,0.0) -- | A Down Vector for the simple constructors vDown :: (Double,Double,Double) vDown = (0.0,-1.0,0.0) -- | A Forward Vector for the simple constructors vForward :: (Double,Double,Double) vForward = (1.0,0.0,0.0) -- | A Backward Vector for the simple constructors vBackward :: (Double,Double,Double) vBackward = (-1.0,0.0,0.0) -- | A Right Vector for the simple constructors vRight:: (Double,Double,Double) vRight = (1.0,0.0,1.0) -- | A Left Vector for the simple constructors vLeft :: (Double,Double,Double) vLeft = (0.0,0.0,-1.0) -- | World Construction -- | Constrictor function to create an empty world emptyWorld :: World emptyWorld = World { items = [] ,lights = [] } -- | Function to create a world from a list of entitys createWorld::[Entity] -> State World () createWorld (e:[]) = createObj e createWorld (e:el) = do createObj e createWorld el -- | Function to add an object to the world state monad createObj :: Entity -> State World () createObj (EntL e) = modify (addLightToWorld e) createObj (EntO e) = modify (addObjectToWorld e) -- | Function to add an object to an existing world addObjectToWorld :: Object -> World -> World addObjectToWorld o w@World{items= i} = w{items= (i ++ [o]) } -- | Function to add a light to an existing world addLightToWorld :: Light -> World -> World addLightToWorld l w@World{lights= ls} = w{lights= (ls ++ [l]) } -- | Constructor to create a sphere using the simpler type of vectors createSphere :: Double -> (Double, Double , Double) -> Color -> Double -> Double-> Object createSphere rad (x,y,z) col ref shin = Object{ shape=Sphere{ spos = R.fromListUnboxed (R.ix1 3) [x,y,z] ,radius = rad} ,color = col ,shininess = shin ,reflectance = (clamp ref 0.0 1.0) } -- | Constructor function to go from Repa array to an Sphere v2Sphere::DoubleVector ->Color ->Double -> Double -> Double-> Object v2Sphere pos colorIn rad ref shin = Object{ shape=Sphere{ spos = pos ,radius = rad} ,color = colorIn , reflectance = (clamp ref 0.0 1.0) ,shininess = shin } -- | Constructor function to create a plane using the simpler types of vectors createPlane ::(Double, Double , Double) ->(Double, Double , Double) -> Color -> Double ->Double -> Object createPlane (x,y,z) (nx,ny,nz) colIn ref shin =(v2Plaine (R.fromListUnboxed (R.ix1 3) [x,y,z]) ( R.fromListUnboxed (R.ix1 3) [nx,ny,nz]) colIn ref shin) -- | Constructor function to go from Repa array to an Plane v2Plaine::DoubleVector ->DoubleVector ->Color -> Double->Double -> Object v2Plaine pposIn pnormalIn colorIn refIn shin = Object{ shape=Plane{ ppos = pposIn ,pnormal = pnormalIn} ,color = colorIn , reflectance = clamp refIn 0.0 1.0 ,shininess = shin } -- | Constructor function to create a light using the simpler types of vectors createLight ::(Double, Double , Double) -> Color -> Light createLight (x,y,z) (col1,col2,col3) = (v2Light (R.fromListUnboxed (R.ix1 3) [x,y,z]) (R.fromListUnboxed (R.ix1 3)[col1,col2,col3])) -- | Constructor function to go from Repa array to an light v2Light::DoubleVector -> DoubleVector -> Light v2Light pos colorIn = Light{ lpos = pos ,lcolor = (colorIn R.! (R.Z R.:. 0), colorIn R.! (R.Z R.:. 1),colorIn R.! (R.Z R.:. 2)) } -- | Hepler function clamp ported from GLSL clamp:: Double -> Double -> Double -> Double clamp a min max | a < min = min | a > max = max | otherwise = a
axhav/AFPLAB3
World.hs
bsd-3-clause
7,124
0
13
1,887
2,011
1,180
831
143
1
module Main where incdInts :: [Integer] incdInts = map (+1) [1..] main :: IO () main = do print (incdInts !! 1000) print (incdInts !! 9001) print (incdInts !! 90010) print (incdInts !! 9001000) print (incdInts !! 9501000) print (incdInts !! 9901000)
chengzh2008/hpffp
src/ch28-BasicLibraries/largeCAF1.hs
bsd-3-clause
264
0
9
56
122
62
60
11
1
---------------------------------------------------------------------------- -- | -- Module : Source2 -- Copyright : (c) Sergey Vinokurov 2018 -- License : BSD3-style (see LICENSE) -- Maintainer : [email protected] ---------------------------------------------------------------------------- module Source2 (foo2) where foo2 :: Double -> Double foo2 x = x + x
sergv/tags-server
test-data/0016reexport_of_missing_module/Source2.hs
bsd-3-clause
379
0
5
58
37
24
13
3
1
module Twelve where import Data.Char sumJSON :: String -> Int sumJSON [] = 0 sumJSON (x:xs) | isDigit x = plus (read [x]) xs | x == '-' = minus 0 xs | otherwise = sumJSON xs plus :: Int -> String -> Int plus = applyOp (+) minus :: Int -> String -> Int minus = applyOp (-) applyOp :: (Int -> Int -> Int) -> Int -> String -> Int applyOp _ _ [] = 0 applyOp op n (x:xs) | isDigit x = minus (n * 10 `op` read [x]) xs | otherwise = n + sumJSON xs twelve :: IO Int twelve = do json <- readFile "input/12.txt" return $ sumJSON json
purcell/adventofcodeteam
app/Twelve.hs
bsd-3-clause
558
0
10
150
285
143
142
21
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} module Types where import Data.Aeson import GHC.Generics data SSHHost = SSHHost{host :: String, remoteport :: Integer} deriving (Show, Generic, FromJSON, ToJSON) data SSHConfig = SSH{username :: String, hosts :: [SSHHost]} deriving (Show, Generic, FromJSON, ToJSON) data Config = Config{ ssh :: Maybe SSHConfig } deriving (Show, Generic, FromJSON, ToJSON) data Address = Address String String deriving Show getLink :: Address -> String getLink (Address link _) = link
pwestling/hmonit
src/Types.hs
bsd-3-clause
638
0
9
124
177
102
75
14
1
-- Copyright (c) 2014 Contributors as noted in the AUTHORS file -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. import Arduino.Uno main = compileProgram $ do digitalOutput pin13 =: clock ~> toggle uart =: timerDelta ~> mapSMany formatDelta ~> flattenS formatDelta :: Expression Word -> [Expression [Byte]] formatDelta delta = [ formatString "delta: " , formatNumber delta , formatString "\r\n" ]
cjdibbs/ardunio
examples/UART.hs
bsd-3-clause
1,070
0
10
240
108
60
48
8
1
module Option ( buildOption ) where import CommandLineOption (CommandLineOption) import qualified CommandLineOption import qualified Git import Types import Control.Applicative import Data.Char (toUpper) import Data.Maybe (catMaybes, fromJust, fromMaybe) import Data.Time.Calendar (toGregorian) import Data.Time.Clock (getCurrentTime, utctDay) buildOption :: CommandLineOption -> IO Option buildOption copt = do let packageName' = CommandLineOption.packageName copt moduleName' = fromMaybe (modularize packageName') (CommandLineOption.moduleName copt) directoryName' = fromMaybe packageName' (CommandLineOption.directoryName copt) source' = fromJust $ (Repo <$> CommandLineOption.repo copt) <|> (CabalPackage <$> CommandLineOption.cabalPackage copt) afterCommands' = catMaybes [ CommandLineOption.afterCommand copt ] dryRun' = CommandLineOption.dryRun copt year' <- getCurrentYear author' <- Git.config "user.name" email' <- Git.config "user.email" return Option { packageName = packageName' , moduleName = moduleName' , directoryName = directoryName' , author = author' , email = email' , year = year' , source = source' , dryRun = dryRun' , afterCommands = afterCommands' } getCurrentYear :: IO String getCurrentYear = do (y,_,_) <- (toGregorian . utctDay) <$> getCurrentTime return $ show y -- | Capitalize words and connect them with periods -- -- >>> modularize "package" -- "Package" -- -- >>> modularize "package-name" -- "Package.Name" -- -- >>> modularize "another-package-name" -- "Another.Package.Name" -- modularize :: String -> String modularize [] = [] modularize [x] = [toUpper x] modularize (x:xs) = toUpper x : rest xs where rest [] = [] rest ('-':ys) = '.' : modularize ys rest (y:ys) = y:rest ys
fujimura/chi
src/Option.hs
bsd-3-clause
2,146
0
15
655
498
273
225
42
3
{-# LANGUAGE OverloadedStrings #-} module Test.Helper ( module Test.Hspec.Monadic, module Test.Hspec.Expectations ) where import Test.Hspec.Monadic import Test.Hspec.HUnit() import Test.Hspec.Expectations
fujimura/persistent-hspec-example
Test/Helper.hs
bsd-3-clause
214
0
5
28
44
30
14
8
0
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, StaticPointers, RankNTypes, GADTs, ConstraintKinds, FlexibleContexts, TypeApplications, ScopedTypeVariables, FlexibleInstances #-} module QueryArrow.Remote.NoTranslation.Server where import QueryArrow.DB.DB import QueryArrow.DB.NoTranslation import QueryArrow.DB.ResultStream import Foreign.StablePtr import Control.Monad.Trans.Resource import Control.Monad.IO.Class import QueryArrow.Remote.NoTranslation.Definitions import QueryArrow.Remote.Definitions import QueryArrow.Syntax.Type import Control.Exception.Lifted (catch, SomeException) runQueryArrowServer :: forall db a. (Channel a, SendType a ~ RemoteResultSet, ReceiveType a ~ RemoteCommand, DBFormulaType db ~ FormulaT, RowType (StatementType (ConnectionType db)) ~ MapResultRow, IDatabase db) => a -> db -> ResourceT IO () runQueryArrowServer chan db = do cmd <- liftIO $ receive chan case cmd of Quit -> return () _ -> do res <- case cmd of GetName -> return (StringResult (getName db)) GetPreds -> return (PredListResult (getPreds db)) Supported ret form vars -> return (BoolResult (supported db ret form vars)) DBOpen -> do (conn, key) <- allocate (dbOpen db) dbClose liftIO $ ConnectionResult . castStablePtrToPtr <$> newStablePtr (db, conn, key) DBClose connP -> do let connSP = castPtrToStablePtr connP :: StablePtr (db, ConnectionType db, ReleaseKey) (_, _, key) <- liftIO $ deRefStablePtr connSP release key liftIO $ freeStablePtr connSP return UnitResult DBBegin connSP -> liftIO $ do (_, conn, _) <- deRefStablePtr (castPtrToStablePtr connSP :: StablePtr (db, ConnectionType db, ReleaseKey)) catch (do dbBegin conn return UnitResult ) (\e -> return (ErrorResult (-1, show (e::SomeException)))) DBPrepare connSP -> liftIO $ catch (do (_, conn, _) <- deRefStablePtr (castPtrToStablePtr connSP :: StablePtr (db, ConnectionType db, ReleaseKey)) dbPrepare conn return UnitResult ) (\e -> return (ErrorResult (-1, show (e::SomeException)))) DBCommit connSP -> liftIO $ catch (do (_, conn, _) <- deRefStablePtr (castPtrToStablePtr connSP :: StablePtr (db, ConnectionType db, ReleaseKey)) dbCommit conn return UnitResult ) (\e -> return (ErrorResult (-1, show (e::SomeException)))) DBRollback connSP -> liftIO $ catch (do (_, conn, _) <- deRefStablePtr (castPtrToStablePtr connSP :: StablePtr (db, ConnectionType db, ReleaseKey)) dbRollback conn return UnitResult ) (\e -> return (ErrorResult (-1, show (e::SomeException)))) DBStmtExec connSP (NTDBQuery vars2 form vars) rows -> catch (do (_, conn, _) <- liftIO $ deRefStablePtr (castPtrToStablePtr connSP :: StablePtr (db, ConnectionType db, ReleaseKey)) qu <- liftIO $ translateQuery db vars2 form vars stmt <- liftIO $ prepareQuery conn qu rows' <- getAllResultsInStream (dbStmtExec stmt (listResultStream rows)) liftIO $ dbStmtClose stmt return (RowListResult rows') ) (\e -> return (ErrorResult (-1, show (e::SomeException)))) Quit -> error "error" liftIO $ send chan res runQueryArrowServer chan db
xu-hao/QueryArrow
QueryArrow-db-remote/src/QueryArrow/Remote/NoTranslation/Server.hs
bsd-3-clause
3,533
0
27
945
1,118
565
553
70
12
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow 2006 -- -- The purpose of this module is to transform an HsExpr into a CoreExpr which -- when evaluated, returns a (Meta.Q Meta.Exp) computation analogous to the -- input HsExpr. We do this in the DsM monad, which supplies access to -- CoreExpr's of the "smart constructors" of the Meta.Exp datatype. -- -- It also defines a bunch of knownKeyNames, in the same way as is done -- in prelude/PrelNames. It's much more convenient to do it here, because -- otherwise we have to recompile PrelNames whenever we add a Name, which is -- a Royal Pain (triggers other recompilation). ----------------------------------------------------------------------------- module DsMeta( dsBracket, templateHaskellNames, qTyConName, nameTyConName, liftName, liftStringName, expQTyConName, patQTyConName, decQTyConName, decsQTyConName, typeQTyConName, decTyConName, typeTyConName, mkNameG_dName, mkNameG_vName, mkNameG_tcName, quoteExpName, quotePatName, quoteDecName, quoteTypeName, tExpTyConName, tExpDataConName, unTypeName, unTypeQName, unsafeTExpCoerceName ) where #include "HsVersions.h" import {-# SOURCE #-} DsExpr ( dsExpr ) import MatchLit import DsMonad import qualified Language.Haskell.TH as TH import HsSyn import Class import PrelNames -- To avoid clashes with DsMeta.varName we must make a local alias for -- OccName.varName we do this by removing varName from the import of -- OccName above, making a qualified instance of OccName and using -- OccNameAlias.varName where varName ws previously used in this file. import qualified OccName( isDataOcc, isVarOcc, isTcOcc, varName, tcName, dataName ) import Module import Id import Name hiding( isVarOcc, isTcOcc, varName, tcName ) import NameEnv import TcType import TyCon import TysWiredIn import TysPrim ( liftedTypeKindTyConName, constraintKindTyConName ) import CoreSyn import MkCore import CoreUtils import SrcLoc import Unique import BasicTypes import Outputable import Bag import DynFlags import FastString import ForeignCall import Util import Data.Maybe import Control.Monad import Data.List ----------------------------------------------------------------------------- dsBracket :: HsBracket Name -> [PendingTcSplice] -> DsM CoreExpr -- Returns a CoreExpr of type TH.ExpQ -- The quoted thing is parameterised over Name, even though it has -- been type checked. We don't want all those type decorations! dsBracket brack splices = dsExtendMetaEnv new_bit (do_brack brack) where new_bit = mkNameEnv [(n, Splice (unLoc e)) | PendSplice n e <- splices] do_brack (VarBr _ n) = do { MkC e1 <- lookupOcc n ; return e1 } do_brack (ExpBr e) = do { MkC e1 <- repLE e ; return e1 } do_brack (PatBr p) = do { MkC p1 <- repTopP p ; return p1 } do_brack (TypBr t) = do { MkC t1 <- repLTy t ; return t1 } do_brack (DecBrG gp) = do { MkC ds1 <- repTopDs gp ; return ds1 } do_brack (DecBrL _) = panic "dsBracket: unexpected DecBrL" do_brack (TExpBr e) = do { MkC e1 <- repLE e ; return e1 } {- -------------- Examples -------------------- [| \x -> x |] ====> gensym (unpackString "x"#) `bindQ` \ x1::String -> lam (pvar x1) (var x1) [| \x -> $(f [| x |]) |] ====> gensym (unpackString "x"#) `bindQ` \ x1::String -> lam (pvar x1) (f (var x1)) -} ------------------------------------------------------- -- Declarations ------------------------------------------------------- repTopP :: LPat Name -> DsM (Core TH.PatQ) repTopP pat = do { ss <- mkGenSyms (collectPatBinders pat) ; pat' <- addBinds ss (repLP pat) ; wrapGenSyms ss pat' } repTopDs :: HsGroup Name -> DsM (Core (TH.Q [TH.Dec])) repTopDs group@(HsGroup { hs_valds = valds , hs_splcds = splcds , hs_tyclds = tyclds , hs_instds = instds , hs_derivds = derivds , hs_fixds = fixds , hs_defds = defds , hs_fords = fords , hs_warnds = warnds , hs_annds = annds , hs_ruleds = ruleds , hs_vects = vects , hs_docs = docs }) = do { let { tv_bndrs = hsSigTvBinders valds ; bndrs = tv_bndrs ++ hsGroupBinders group } ; ss <- mkGenSyms bndrs ; -- Bind all the names mainly to avoid repeated use of explicit strings. -- Thus we get -- do { t :: String <- genSym "T" ; -- return (Data t [] ...more t's... } -- The other important reason is that the output must mention -- only "T", not "Foo:T" where Foo is the current module decls <- addBinds ss ( do { val_ds <- rep_val_binds valds ; _ <- mapM no_splice splcds ; tycl_ds <- mapM repTyClD (tyClGroupConcat tyclds) ; role_ds <- mapM repRoleD (concatMap group_roles tyclds) ; inst_ds <- mapM repInstD instds ; deriv_ds <- mapM repStandaloneDerivD derivds ; fix_ds <- mapM repFixD fixds ; _ <- mapM no_default_decl defds ; for_ds <- mapM repForD fords ; _ <- mapM no_warn warnds ; ann_ds <- mapM repAnnD annds ; rule_ds <- mapM repRuleD ruleds ; _ <- mapM no_vect vects ; _ <- mapM no_doc docs -- more needed ; return (de_loc $ sort_by_loc $ val_ds ++ catMaybes tycl_ds ++ role_ds ++ fix_ds ++ inst_ds ++ rule_ds ++ for_ds ++ ann_ds ++ deriv_ds) }) ; decl_ty <- lookupType decQTyConName ; let { core_list = coreList' decl_ty decls } ; dec_ty <- lookupType decTyConName ; q_decs <- repSequenceQ dec_ty core_list ; wrapGenSyms ss q_decs } where no_splice (L loc _) = notHandledL loc "Splices within declaration brackets" empty no_default_decl (L loc decl) = notHandledL loc "Default declarations" (ppr decl) no_warn (L loc (Warning thing _)) = notHandledL loc "WARNING and DEPRECATION pragmas" $ text "Pragma for declaration of" <+> ppr thing no_vect (L loc decl) = notHandledL loc "Vectorisation pragmas" (ppr decl) no_doc (L loc _) = notHandledL loc "Haddock documentation" empty hsSigTvBinders :: HsValBinds Name -> [Name] -- See Note [Scoped type variables in bindings] hsSigTvBinders binds = [hsLTyVarName tv | L _ (TypeSig _ (L _ (HsForAllTy Explicit qtvs _ _))) <- sigs , tv <- hsQTvBndrs qtvs] where sigs = case binds of ValBindsIn _ sigs -> sigs ValBindsOut _ sigs -> sigs {- Notes Note [Scoped type variables in bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: forall a. a -> a f x = x::a Here the 'forall a' brings 'a' into scope over the binding group. To achieve this we a) Gensym a binding for 'a' at the same time as we do one for 'f' collecting the relevant binders with hsSigTvBinders b) When processing the 'forall', don't gensym The relevant places are signposted with references to this Note Note [Binders and occurrences] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we desugar [d| data T = MkT |] we want to get Data "T" [] [Con "MkT" []] [] and *not* Data "Foo:T" [] [Con "Foo:MkT" []] [] That is, the new data decl should fit into whatever new module it is asked to fit in. We do *not* clone, though; no need for this: Data "T79" .... But if we see this: data T = MkT foo = reifyDecl T then we must desugar to foo = Data "Foo:T" [] [Con "Foo:MkT" []] [] So in repTopDs we bring the binders into scope with mkGenSyms and addBinds. And we use lookupOcc, rather than lookupBinder in repTyClD and repC. -} -- represent associated family instances -- repTyClD :: LTyClDecl Name -> DsM (Maybe (SrcSpan, Core TH.DecQ)) repTyClD (L loc (FamDecl { tcdFam = fam })) = liftM Just $ repFamilyDecl (L loc fam) repTyClD (L loc (SynDecl { tcdLName = tc, tcdTyVars = tvs, tcdRhs = rhs })) = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; dec <- addTyClTyVarBinds tvs $ \bndrs -> repSynDecl tc1 bndrs rhs ; return (Just (loc, dec)) } repTyClD (L loc (DataDecl { tcdLName = tc, tcdTyVars = tvs, tcdDataDefn = defn })) = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; tc_tvs <- mk_extra_tvs tc tvs defn ; dec <- addTyClTyVarBinds tc_tvs $ \bndrs -> repDataDefn tc1 bndrs Nothing (hsLTyVarNames tc_tvs) defn ; return (Just (loc, dec)) } repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls, tcdTyVars = tvs, tcdFDs = fds, tcdSigs = sigs, tcdMeths = meth_binds, tcdATs = ats, tcdATDefs = [] })) = do { cls1 <- lookupLOcc cls -- See note [Binders and occurrences] ; dec <- addTyVarBinds tvs $ \bndrs -> do { cxt1 <- repLContext cxt ; sigs1 <- rep_sigs sigs ; binds1 <- rep_binds meth_binds ; fds1 <- repLFunDeps fds ; ats1 <- repFamilyDecls ats ; decls1 <- coreList decQTyConName (ats1 ++ sigs1 ++ binds1) ; repClass cxt1 cls1 bndrs fds1 decls1 } ; return $ Just (loc, dec) } -- Un-handled cases repTyClD (L loc d) = putSrcSpanDs loc $ do { warnDs (hang ds_msg 4 (ppr d)) ; return Nothing } ------------------------- repRoleD :: LRoleAnnotDecl Name -> DsM (SrcSpan, Core TH.DecQ) repRoleD (L loc (RoleAnnotDecl tycon roles)) = do { tycon1 <- lookupLOcc tycon ; roles1 <- mapM repRole roles ; roles2 <- coreList roleTyConName roles1 ; dec <- repRoleAnnotD tycon1 roles2 ; return (loc, dec) } ------------------------- repDataDefn :: Core TH.Name -> Core [TH.TyVarBndr] -> Maybe (Core [TH.TypeQ]) -> [Name] -> HsDataDefn Name -> DsM (Core TH.DecQ) repDataDefn tc bndrs opt_tys tv_names (HsDataDefn { dd_ND = new_or_data, dd_ctxt = cxt , dd_cons = cons, dd_derivs = mb_derivs }) = do { cxt1 <- repLContext cxt ; derivs1 <- repDerivs mb_derivs ; case new_or_data of NewType -> do { con1 <- repC tv_names (head cons) ; repNewtype cxt1 tc bndrs opt_tys con1 derivs1 } DataType -> do { cons1 <- repList conQTyConName (repC tv_names) cons ; repData cxt1 tc bndrs opt_tys cons1 derivs1 } } repSynDecl :: Core TH.Name -> Core [TH.TyVarBndr] -> LHsType Name -> DsM (Core TH.DecQ) repSynDecl tc bndrs ty = do { ty1 <- repLTy ty ; repTySyn tc bndrs ty1 } repFamilyDecl :: LFamilyDecl Name -> DsM (SrcSpan, Core TH.DecQ) repFamilyDecl (L loc (FamilyDecl { fdInfo = info, fdLName = tc, fdTyVars = tvs, fdKindSig = opt_kind })) = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; dec <- addTyClTyVarBinds tvs $ \bndrs -> case (opt_kind, info) of (Nothing, ClosedTypeFamily eqns) -> do { eqns1 <- mapM repTyFamEqn eqns ; eqns2 <- coreList tySynEqnQTyConName eqns1 ; repClosedFamilyNoKind tc1 bndrs eqns2 } (Just ki, ClosedTypeFamily eqns) -> do { eqns1 <- mapM repTyFamEqn eqns ; eqns2 <- coreList tySynEqnQTyConName eqns1 ; ki1 <- repLKind ki ; repClosedFamilyKind tc1 bndrs ki1 eqns2 } (Nothing, _) -> do { info' <- repFamilyInfo info ; repFamilyNoKind info' tc1 bndrs } (Just ki, _) -> do { info' <- repFamilyInfo info ; ki1 <- repLKind ki ; repFamilyKind info' tc1 bndrs ki1 } ; return (loc, dec) } repFamilyDecls :: [LFamilyDecl Name] -> DsM [Core TH.DecQ] repFamilyDecls fds = liftM de_loc (mapM repFamilyDecl fds) ------------------------- mk_extra_tvs :: Located Name -> LHsTyVarBndrs Name -> HsDataDefn Name -> DsM (LHsTyVarBndrs Name) -- If there is a kind signature it must be of form -- k1 -> .. -> kn -> * -- Return type variables [tv1:k1, tv2:k2, .., tvn:kn] mk_extra_tvs tc tvs defn | HsDataDefn { dd_kindSig = Just hs_kind } <- defn = do { extra_tvs <- go hs_kind ; return (tvs { hsq_tvs = hsq_tvs tvs ++ extra_tvs }) } | otherwise = return tvs where go :: LHsKind Name -> DsM [LHsTyVarBndr Name] go (L loc (HsFunTy kind rest)) = do { uniq <- newUnique ; let { occ = mkTyVarOccFS (fsLit "t") ; nm = mkInternalName uniq occ loc ; hs_tv = L loc (KindedTyVar nm kind) } ; hs_tvs <- go rest ; return (hs_tv : hs_tvs) } go (L _ (HsTyVar n)) | n == liftedTypeKindTyConName = return [] go _ = failWithDs (ptext (sLit "Malformed kind signature for") <+> ppr tc) ------------------------- -- represent fundeps -- repLFunDeps :: [Located (FunDep Name)] -> DsM (Core [TH.FunDep]) repLFunDeps fds = repList funDepTyConName repLFunDep fds repLFunDep :: Located (FunDep Name) -> DsM (Core TH.FunDep) repLFunDep (L _ (xs, ys)) = do xs' <- repList nameTyConName lookupBinder xs ys' <- repList nameTyConName lookupBinder ys repFunDep xs' ys' -- represent family declaration flavours -- repFamilyInfo :: FamilyInfo Name -> DsM (Core TH.FamFlavour) repFamilyInfo OpenTypeFamily = rep2 typeFamName [] repFamilyInfo DataFamily = rep2 dataFamName [] repFamilyInfo ClosedTypeFamily {} = panic "repFamilyInfo" -- Represent instance declarations -- repInstD :: LInstDecl Name -> DsM (SrcSpan, Core TH.DecQ) repInstD (L loc (TyFamInstD { tfid_inst = fi_decl })) = do { dec <- repTyFamInstD fi_decl ; return (loc, dec) } repInstD (L loc (DataFamInstD { dfid_inst = fi_decl })) = do { dec <- repDataFamInstD fi_decl ; return (loc, dec) } repInstD (L loc (ClsInstD { cid_inst = cls_decl })) = do { dec <- repClsInstD cls_decl ; return (loc, dec) } repClsInstD :: ClsInstDecl Name -> DsM (Core TH.DecQ) repClsInstD (ClsInstDecl { cid_poly_ty = ty, cid_binds = binds , cid_sigs = prags, cid_tyfam_insts = ats , cid_datafam_insts = adts }) = addTyVarBinds tvs $ \_ -> -- We must bring the type variables into scope, so their -- occurrences don't fail, even though the binders don't -- appear in the resulting data structure -- -- But we do NOT bring the binders of 'binds' into scope -- because they are properly regarded as occurrences -- For example, the method names should be bound to -- the selector Ids, not to fresh names (Trac #5410) -- do { cxt1 <- repContext cxt ; cls_tcon <- repTy (HsTyVar (unLoc cls)) ; cls_tys <- repLTys tys ; inst_ty1 <- repTapps cls_tcon cls_tys ; binds1 <- rep_binds binds ; prags1 <- rep_sigs prags ; ats1 <- mapM (repTyFamInstD . unLoc) ats ; adts1 <- mapM (repDataFamInstD . unLoc) adts ; decls <- coreList decQTyConName (ats1 ++ adts1 ++ binds1 ++ prags1) ; repInst cxt1 inst_ty1 decls } where Just (tvs, cxt, cls, tys) = splitLHsInstDeclTy_maybe ty repStandaloneDerivD :: LDerivDecl Name -> DsM (SrcSpan, Core TH.DecQ) repStandaloneDerivD (L loc (DerivDecl { deriv_type = ty })) = do { dec <- addTyVarBinds tvs $ \_ -> do { cxt' <- repContext cxt ; cls_tcon <- repTy (HsTyVar (unLoc cls)) ; cls_tys <- repLTys tys ; inst_ty <- repTapps cls_tcon cls_tys ; repDeriv cxt' inst_ty } ; return (loc, dec) } where Just (tvs, cxt, cls, tys) = splitLHsInstDeclTy_maybe ty repTyFamInstD :: TyFamInstDecl Name -> DsM (Core TH.DecQ) repTyFamInstD decl@(TyFamInstDecl { tfid_eqn = eqn }) = do { let tc_name = tyFamInstDeclLName decl ; tc <- lookupLOcc tc_name -- See note [Binders and occurrences] ; eqn1 <- repTyFamEqn eqn ; repTySynInst tc eqn1 } repTyFamEqn :: LTyFamInstEqn Name -> DsM (Core TH.TySynEqnQ) repTyFamEqn (L loc (TyFamEqn { tfe_pats = HsWB { hswb_cts = tys , hswb_kvs = kv_names , hswb_tvs = tv_names } , tfe_rhs = rhs })) = do { let hs_tvs = HsQTvs { hsq_kvs = kv_names , hsq_tvs = userHsTyVarBndrs loc tv_names } -- Yuk ; addTyClTyVarBinds hs_tvs $ \ _ -> do { tys1 <- repLTys tys ; tys2 <- coreList typeQTyConName tys1 ; rhs1 <- repLTy rhs ; repTySynEqn tys2 rhs1 } } repDataFamInstD :: DataFamInstDecl Name -> DsM (Core TH.DecQ) repDataFamInstD (DataFamInstDecl { dfid_tycon = tc_name , dfid_pats = HsWB { hswb_cts = tys, hswb_kvs = kv_names, hswb_tvs = tv_names } , dfid_defn = defn }) = do { tc <- lookupLOcc tc_name -- See note [Binders and occurrences] ; let loc = getLoc tc_name hs_tvs = HsQTvs { hsq_kvs = kv_names, hsq_tvs = userHsTyVarBndrs loc tv_names } -- Yuk ; addTyClTyVarBinds hs_tvs $ \ bndrs -> do { tys1 <- repList typeQTyConName repLTy tys ; repDataDefn tc bndrs (Just tys1) tv_names defn } } repForD :: Located (ForeignDecl Name) -> DsM (SrcSpan, Core TH.DecQ) repForD (L loc (ForeignImport name typ _ (CImport cc s mch cis))) = do MkC name' <- lookupLOcc name MkC typ' <- repLTy typ MkC cc' <- repCCallConv cc MkC s' <- repSafety s cis' <- conv_cimportspec cis MkC str <- coreStringLit (static ++ chStr ++ cis') dec <- rep2 forImpDName [cc', s', str, name', typ'] return (loc, dec) where conv_cimportspec (CLabel cls) = notHandled "Foreign label" (doubleQuotes (ppr cls)) conv_cimportspec (CFunction DynamicTarget) = return "dynamic" conv_cimportspec (CFunction (StaticTarget fs _ True)) = return (unpackFS fs) conv_cimportspec (CFunction (StaticTarget _ _ False)) = panic "conv_cimportspec: values not supported yet" conv_cimportspec CWrapper = return "wrapper" static = case cis of CFunction (StaticTarget _ _ _) -> "static " _ -> "" chStr = case mch of Nothing -> "" Just (Header h) -> unpackFS h ++ " " repForD decl = notHandled "Foreign declaration" (ppr decl) repCCallConv :: CCallConv -> DsM (Core TH.Callconv) repCCallConv CCallConv = rep2 cCallName [] repCCallConv StdCallConv = rep2 stdCallName [] repCCallConv CApiConv = rep2 cApiCallName [] repCCallConv PrimCallConv = rep2 primCallName [] repCCallConv JavaScriptCallConv = rep2 javaScriptCallName [] repSafety :: Safety -> DsM (Core TH.Safety) repSafety PlayRisky = rep2 unsafeName [] repSafety PlayInterruptible = rep2 interruptibleName [] repSafety PlaySafe = rep2 safeName [] repFixD :: LFixitySig Name -> DsM (SrcSpan, Core TH.DecQ) repFixD (L loc (FixitySig name (Fixity prec dir))) = do { MkC name' <- lookupLOcc name ; MkC prec' <- coreIntLit prec ; let rep_fn = case dir of InfixL -> infixLDName InfixR -> infixRDName InfixN -> infixNDName ; dec <- rep2 rep_fn [prec', name'] ; return (loc, dec) } repRuleD :: LRuleDecl Name -> DsM (SrcSpan, Core TH.DecQ) repRuleD (L loc (HsRule n act bndrs lhs _ rhs _)) = do { let bndr_names = concatMap ruleBndrNames bndrs ; ss <- mkGenSyms bndr_names ; rule1 <- addBinds ss $ do { bndrs' <- repList ruleBndrQTyConName repRuleBndr bndrs ; n' <- coreStringLit $ unpackFS n ; act' <- repPhases act ; lhs' <- repLE lhs ; rhs' <- repLE rhs ; repPragRule n' bndrs' lhs' rhs' act' } ; rule2 <- wrapGenSyms ss rule1 ; return (loc, rule2) } ruleBndrNames :: RuleBndr Name -> [Name] ruleBndrNames (RuleBndr n) = [unLoc n] ruleBndrNames (RuleBndrSig n (HsWB { hswb_kvs = kvs, hswb_tvs = tvs })) = unLoc n : kvs ++ tvs repRuleBndr :: RuleBndr Name -> DsM (Core TH.RuleBndrQ) repRuleBndr (RuleBndr n) = do { MkC n' <- lookupLBinder n ; rep2 ruleVarName [n'] } repRuleBndr (RuleBndrSig n (HsWB { hswb_cts = ty })) = do { MkC n' <- lookupLBinder n ; MkC ty' <- repLTy ty ; rep2 typedRuleVarName [n', ty'] } repAnnD :: LAnnDecl Name -> DsM (SrcSpan, Core TH.DecQ) repAnnD (L loc (HsAnnotation ann_prov (L _ exp))) = do { target <- repAnnProv ann_prov ; exp' <- repE exp ; dec <- repPragAnn target exp' ; return (loc, dec) } repAnnProv :: AnnProvenance Name -> DsM (Core TH.AnnTarget) repAnnProv (ValueAnnProvenance n) = do { MkC n' <- globalVar n -- ANNs are allowed only at top-level ; rep2 valueAnnotationName [ n' ] } repAnnProv (TypeAnnProvenance n) = do { MkC n' <- globalVar n ; rep2 typeAnnotationName [ n' ] } repAnnProv ModuleAnnProvenance = rep2 moduleAnnotationName [] ds_msg :: SDoc ds_msg = ptext (sLit "Cannot desugar this Template Haskell declaration:") ------------------------------------------------------- -- Constructors ------------------------------------------------------- repC :: [Name] -> LConDecl Name -> DsM (Core TH.ConQ) repC _ (L _ (ConDecl { con_name = con, con_qvars = con_tvs, con_cxt = L _ [] , con_details = details, con_res = ResTyH98 })) | null (hsQTvBndrs con_tvs) = do { con1 <- lookupLOcc con -- See Note [Binders and occurrences] ; repConstr con1 details } repC tvs (L _ (ConDecl { con_name = con , con_qvars = con_tvs, con_cxt = L _ ctxt , con_details = details , con_res = res_ty })) = do { (eq_ctxt, con_tv_subst) <- mkGadtCtxt tvs res_ty ; let ex_tvs = HsQTvs { hsq_kvs = filterOut (in_subst con_tv_subst) (hsq_kvs con_tvs) , hsq_tvs = filterOut (in_subst con_tv_subst . hsLTyVarName) (hsq_tvs con_tvs) } ; binds <- mapM dupBinder con_tv_subst ; dsExtendMetaEnv (mkNameEnv binds) $ -- Binds some of the con_tvs addTyVarBinds ex_tvs $ \ ex_bndrs -> -- Binds the remaining con_tvs do { con1 <- lookupLOcc con -- See Note [Binders and occurrences] ; c' <- repConstr con1 details ; ctxt' <- repContext (eq_ctxt ++ ctxt) ; rep2 forallCName [unC ex_bndrs, unC ctxt', unC c'] } } in_subst :: [(Name,Name)] -> Name -> Bool in_subst [] _ = False in_subst ((n',_):ns) n = n==n' || in_subst ns n mkGadtCtxt :: [Name] -- Tyvars of the data type -> ResType (LHsType Name) -> DsM (HsContext Name, [(Name,Name)]) -- Given a data type in GADT syntax, figure out the equality -- context, so that we can represent it with an explicit -- equality context, because that is the only way to express -- the GADT in TH syntax -- -- Example: -- data T a b c where { MkT :: forall d e. d -> e -> T d [e] e -- mkGadtCtxt [a,b,c] [d,e] (T d [e] e) -- returns -- (b~[e], c~e), [d->a] -- -- This function is fiddly, but not really hard mkGadtCtxt _ ResTyH98 = return ([], []) mkGadtCtxt data_tvs (ResTyGADT res_ty) | Just (_, tys) <- hsTyGetAppHead_maybe res_ty , data_tvs `equalLength` tys = return (go [] [] (data_tvs `zip` tys)) | otherwise = failWithDs (ptext (sLit "Malformed constructor result type:") <+> ppr res_ty) where go cxt subst [] = (cxt, subst) go cxt subst ((data_tv, ty) : rest) | Just con_tv <- is_hs_tyvar ty , isTyVarName con_tv , not (in_subst subst con_tv) = go cxt ((con_tv, data_tv) : subst) rest | otherwise = go (eq_pred : cxt) subst rest where loc = getLoc ty eq_pred = L loc (HsEqTy (L loc (HsTyVar data_tv)) ty) is_hs_tyvar (L _ (HsTyVar n)) = Just n -- Type variables *and* tycons is_hs_tyvar (L _ (HsParTy ty)) = is_hs_tyvar ty is_hs_tyvar _ = Nothing repBangTy :: LBangType Name -> DsM (Core (TH.StrictTypeQ)) repBangTy ty= do MkC s <- rep2 str [] MkC t <- repLTy ty' rep2 strictTypeName [s, t] where (str, ty') = case ty of L _ (HsBangTy (HsUserBang (Just True) True) ty) -> (unpackedName, ty) L _ (HsBangTy (HsUserBang _ True) ty) -> (isStrictName, ty) _ -> (notStrictName, ty) ------------------------------------------------------- -- Deriving clause ------------------------------------------------------- repDerivs :: Maybe [LHsType Name] -> DsM (Core [TH.Name]) repDerivs Nothing = coreList nameTyConName [] repDerivs (Just ctxt) = repList nameTyConName rep_deriv ctxt where rep_deriv :: LHsType Name -> DsM (Core TH.Name) -- Deriving clauses must have the simple H98 form rep_deriv ty | Just (cls, []) <- splitHsClassTy_maybe (unLoc ty) = lookupOcc cls | otherwise = notHandled "Non-H98 deriving clause" (ppr ty) ------------------------------------------------------- -- Signatures in a class decl, or a group of bindings ------------------------------------------------------- rep_sigs :: [LSig Name] -> DsM [Core TH.DecQ] rep_sigs sigs = do locs_cores <- rep_sigs' sigs return $ de_loc $ sort_by_loc locs_cores rep_sigs' :: [LSig Name] -> DsM [(SrcSpan, Core TH.DecQ)] -- We silently ignore ones we don't recognise rep_sigs' sigs = do { sigs1 <- mapM rep_sig sigs ; return (concat sigs1) } rep_sig :: LSig Name -> DsM [(SrcSpan, Core TH.DecQ)] rep_sig (L loc (TypeSig nms ty)) = mapM (rep_ty_sig sigDName loc ty) nms rep_sig (L _ (PatSynSig {})) = notHandled "Pattern type signatures" empty rep_sig (L loc (GenericSig nms ty)) = mapM (rep_ty_sig defaultSigDName loc ty) nms rep_sig d@(L _ (IdSig {})) = pprPanic "rep_sig IdSig" (ppr d) rep_sig (L _ (FixSig {})) = return [] -- fixity sigs at top level rep_sig (L loc (InlineSig nm ispec)) = rep_inline nm ispec loc rep_sig (L loc (SpecSig nm ty ispec)) = rep_specialise nm ty ispec loc rep_sig (L loc (SpecInstSig ty)) = rep_specialiseInst ty loc rep_sig (L _ (MinimalSig {})) = notHandled "MINIMAL pragmas" empty rep_ty_sig :: Name -> SrcSpan -> LHsType Name -> Located Name -> DsM (SrcSpan, Core TH.DecQ) rep_ty_sig mk_sig loc (L _ ty) nm = do { nm1 <- lookupLOcc nm ; ty1 <- rep_ty ty ; sig <- repProto mk_sig nm1 ty1 ; return (loc, sig) } where -- We must special-case the top-level explicit for-all of a TypeSig -- See Note [Scoped type variables in bindings] rep_ty (HsForAllTy Explicit tvs ctxt ty) = do { let rep_in_scope_tv tv = do { name <- lookupBinder (hsLTyVarName tv) ; repTyVarBndrWithKind tv name } ; bndrs1 <- repList tyVarBndrTyConName rep_in_scope_tv (hsQTvBndrs tvs) ; ctxt1 <- repLContext ctxt ; ty1 <- repLTy ty ; repTForall bndrs1 ctxt1 ty1 } rep_ty ty = repTy ty rep_inline :: Located Name -> InlinePragma -- Never defaultInlinePragma -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] rep_inline nm ispec loc = do { nm1 <- lookupLOcc nm ; inline <- repInline $ inl_inline ispec ; rm <- repRuleMatch $ inl_rule ispec ; phases <- repPhases $ inl_act ispec ; pragma <- repPragInl nm1 inline rm phases ; return [(loc, pragma)] } rep_specialise :: Located Name -> LHsType Name -> InlinePragma -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] rep_specialise nm ty ispec loc = do { nm1 <- lookupLOcc nm ; ty1 <- repLTy ty ; phases <- repPhases $ inl_act ispec ; let inline = inl_inline ispec ; pragma <- if isEmptyInlineSpec inline then -- SPECIALISE repPragSpec nm1 ty1 phases else -- SPECIALISE INLINE do { inline1 <- repInline inline ; repPragSpecInl nm1 ty1 inline1 phases } ; return [(loc, pragma)] } rep_specialiseInst :: LHsType Name -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] rep_specialiseInst ty loc = do { ty1 <- repLTy ty ; pragma <- repPragSpecInst ty1 ; return [(loc, pragma)] } repInline :: InlineSpec -> DsM (Core TH.Inline) repInline NoInline = dataCon noInlineDataConName repInline Inline = dataCon inlineDataConName repInline Inlinable = dataCon inlinableDataConName repInline spec = notHandled "repInline" (ppr spec) repRuleMatch :: RuleMatchInfo -> DsM (Core TH.RuleMatch) repRuleMatch ConLike = dataCon conLikeDataConName repRuleMatch FunLike = dataCon funLikeDataConName repPhases :: Activation -> DsM (Core TH.Phases) repPhases (ActiveBefore i) = do { MkC arg <- coreIntLit i ; dataCon' beforePhaseDataConName [arg] } repPhases (ActiveAfter i) = do { MkC arg <- coreIntLit i ; dataCon' fromPhaseDataConName [arg] } repPhases _ = dataCon allPhasesDataConName ------------------------------------------------------- -- Types ------------------------------------------------------- addTyVarBinds :: LHsTyVarBndrs Name -- the binders to be added -> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -- action in the ext env -> DsM (Core (TH.Q a)) -- gensym a list of type variables and enter them into the meta environment; -- the computations passed as the second argument is executed in that extended -- meta environment and gets the *new* names on Core-level as an argument addTyVarBinds (HsQTvs { hsq_kvs = kvs, hsq_tvs = tvs }) m = do { fresh_kv_names <- mkGenSyms kvs ; fresh_tv_names <- mkGenSyms (map hsLTyVarName tvs) ; let fresh_names = fresh_kv_names ++ fresh_tv_names ; term <- addBinds fresh_names $ do { kbs <- repList tyVarBndrTyConName mk_tv_bndr (tvs `zip` fresh_tv_names) ; m kbs } ; wrapGenSyms fresh_names term } where mk_tv_bndr (tv, (_,v)) = repTyVarBndrWithKind tv (coreVar v) addTyClTyVarBinds :: LHsTyVarBndrs Name -> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -> DsM (Core (TH.Q a)) -- Used for data/newtype declarations, and family instances, -- so that the nested type variables work right -- instance C (T a) where -- type W (T a) = blah -- The 'a' in the type instance is the one bound by the instance decl addTyClTyVarBinds tvs m = do { let tv_names = hsLKiTyVarNames tvs ; env <- dsGetMetaEnv ; freshNames <- mkGenSyms (filterOut (`elemNameEnv` env) tv_names) -- Make fresh names for the ones that are not already in scope -- This makes things work for family declarations ; term <- addBinds freshNames $ do { kbs <- repList tyVarBndrTyConName mk_tv_bndr (hsQTvBndrs tvs) ; m kbs } ; wrapGenSyms freshNames term } where mk_tv_bndr tv = do { v <- lookupBinder (hsLTyVarName tv) ; repTyVarBndrWithKind tv v } -- Produce kinded binder constructors from the Haskell tyvar binders -- repTyVarBndrWithKind :: LHsTyVarBndr Name -> Core TH.Name -> DsM (Core TH.TyVarBndr) repTyVarBndrWithKind (L _ (UserTyVar _)) nm = repPlainTV nm repTyVarBndrWithKind (L _ (KindedTyVar _ ki)) nm = repLKind ki >>= repKindedTV nm -- represent a type context -- repLContext :: LHsContext Name -> DsM (Core TH.CxtQ) repLContext (L _ ctxt) = repContext ctxt repContext :: HsContext Name -> DsM (Core TH.CxtQ) repContext ctxt = do preds <- repList typeQTyConName repLTy ctxt repCtxt preds -- yield the representation of a list of types -- repLTys :: [LHsType Name] -> DsM [Core TH.TypeQ] repLTys tys = mapM repLTy tys -- represent a type -- repLTy :: LHsType Name -> DsM (Core TH.TypeQ) repLTy (L _ ty) = repTy ty repTy :: HsType Name -> DsM (Core TH.TypeQ) repTy (HsForAllTy _ tvs ctxt ty) = addTyVarBinds tvs $ \bndrs -> do ctxt1 <- repLContext ctxt ty1 <- repLTy ty repTForall bndrs ctxt1 ty1 repTy (HsTyVar n) | isTvOcc occ = do tv1 <- lookupOcc n repTvar tv1 | isDataOcc occ = do tc1 <- lookupOcc n repPromotedTyCon tc1 | otherwise = do tc1 <- lookupOcc n repNamedTyCon tc1 where occ = nameOccName n repTy (HsAppTy f a) = do f1 <- repLTy f a1 <- repLTy a repTapp f1 a1 repTy (HsFunTy f a) = do f1 <- repLTy f a1 <- repLTy a tcon <- repArrowTyCon repTapps tcon [f1, a1] repTy (HsListTy t) = do t1 <- repLTy t tcon <- repListTyCon repTapp tcon t1 repTy (HsPArrTy t) = do t1 <- repLTy t tcon <- repTy (HsTyVar (tyConName parrTyCon)) repTapp tcon t1 repTy (HsTupleTy HsUnboxedTuple tys) = do tys1 <- repLTys tys tcon <- repUnboxedTupleTyCon (length tys) repTapps tcon tys1 repTy (HsTupleTy _ tys) = do tys1 <- repLTys tys tcon <- repTupleTyCon (length tys) repTapps tcon tys1 repTy (HsOpTy ty1 (_, n) ty2) = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1) `nlHsAppTy` ty2) repTy (HsParTy t) = repLTy t repTy (HsEqTy t1 t2) = do t1' <- repLTy t1 t2' <- repLTy t2 eq <- repTequality repTapps eq [t1', t2'] repTy (HsKindSig t k) = do t1 <- repLTy t k1 <- repLKind k repTSig t1 k1 repTy (HsSpliceTy splice _) = repSplice splice repTy (HsExplicitListTy _ tys) = do tys1 <- repLTys tys repTPromotedList tys1 repTy (HsExplicitTupleTy _ tys) = do tys1 <- repLTys tys tcon <- repPromotedTupleTyCon (length tys) repTapps tcon tys1 repTy (HsTyLit lit) = do lit' <- repTyLit lit repTLit lit' repTy ty = notHandled "Exotic form of type" (ppr ty) repTyLit :: HsTyLit -> DsM (Core TH.TyLitQ) repTyLit (HsNumTy i) = do iExpr <- mkIntegerExpr i rep2 numTyLitName [iExpr] repTyLit (HsStrTy s) = do { s' <- mkStringExprFS s ; rep2 strTyLitName [s'] } -- represent a kind -- repLKind :: LHsKind Name -> DsM (Core TH.Kind) repLKind ki = do { let (kis, ki') = splitHsFunType ki ; kis_rep <- mapM repLKind kis ; ki'_rep <- repNonArrowLKind ki' ; kcon <- repKArrow ; let f k1 k2 = repKApp kcon k1 >>= flip repKApp k2 ; foldrM f ki'_rep kis_rep } repNonArrowLKind :: LHsKind Name -> DsM (Core TH.Kind) repNonArrowLKind (L _ ki) = repNonArrowKind ki repNonArrowKind :: HsKind Name -> DsM (Core TH.Kind) repNonArrowKind (HsTyVar name) | name == liftedTypeKindTyConName = repKStar | name == constraintKindTyConName = repKConstraint | isTvOcc (nameOccName name) = lookupOcc name >>= repKVar | otherwise = lookupOcc name >>= repKCon repNonArrowKind (HsAppTy f a) = do { f' <- repLKind f ; a' <- repLKind a ; repKApp f' a' } repNonArrowKind (HsListTy k) = do { k' <- repLKind k ; kcon <- repKList ; repKApp kcon k' } repNonArrowKind (HsTupleTy _ ks) = do { ks' <- mapM repLKind ks ; kcon <- repKTuple (length ks) ; repKApps kcon ks' } repNonArrowKind k = notHandled "Exotic form of kind" (ppr k) repRole :: Located (Maybe Role) -> DsM (Core TH.Role) repRole (L _ (Just Nominal)) = rep2 nominalRName [] repRole (L _ (Just Representational)) = rep2 representationalRName [] repRole (L _ (Just Phantom)) = rep2 phantomRName [] repRole (L _ Nothing) = rep2 inferRName [] ----------------------------------------------------------------------------- -- Splices ----------------------------------------------------------------------------- repSplice :: HsSplice Name -> DsM (Core a) -- See Note [How brackets and nested splices are handled] in TcSplice -- We return a CoreExpr of any old type; the context should know repSplice (HsSplice n _) = do { mb_val <- dsLookupMetaEnv n ; case mb_val of Just (Splice e) -> do { e' <- dsExpr e ; return (MkC e') } _ -> pprPanic "HsSplice" (ppr n) } -- Should not happen; statically checked ----------------------------------------------------------------------------- -- Expressions ----------------------------------------------------------------------------- repLEs :: [LHsExpr Name] -> DsM (Core [TH.ExpQ]) repLEs es = repList expQTyConName repLE es -- FIXME: some of these panics should be converted into proper error messages -- unless we can make sure that constructs, which are plainly not -- supported in TH already lead to error messages at an earlier stage repLE :: LHsExpr Name -> DsM (Core TH.ExpQ) repLE (L loc e) = putSrcSpanDs loc (repE e) repE :: HsExpr Name -> DsM (Core TH.ExpQ) repE (HsVar x) = do { mb_val <- dsLookupMetaEnv x ; case mb_val of Nothing -> do { str <- globalVar x ; repVarOrCon x str } Just (Bound y) -> repVarOrCon x (coreVar y) Just (Splice e) -> do { e' <- dsExpr e ; return (MkC e') } } repE e@(HsIPVar _) = notHandled "Implicit parameters" (ppr e) -- Remember, we're desugaring renamer output here, so -- HsOverlit can definitely occur repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a } repE (HsLit l) = do { a <- repLiteral l; repLit a } repE (HsLam (MG { mg_alts = [m] })) = repLambda m repE (HsLamCase _ (MG { mg_alts = ms })) = do { ms' <- mapM repMatchTup ms ; core_ms <- coreList matchQTyConName ms' ; repLamCase core_ms } repE (HsApp x y) = do {a <- repLE x; b <- repLE y; repApp a b} repE (OpApp e1 op _ e2) = do { arg1 <- repLE e1; arg2 <- repLE e2; the_op <- repLE op ; repInfixApp arg1 the_op arg2 } repE (NegApp x _) = do a <- repLE x negateVar <- lookupOcc negateName >>= repVar negateVar `repApp` a repE (HsPar x) = repLE x repE (SectionL x y) = do { a <- repLE x; b <- repLE y; repSectionL a b } repE (SectionR x y) = do { a <- repLE x; b <- repLE y; repSectionR a b } repE (HsCase e (MG { mg_alts = ms })) = do { arg <- repLE e ; ms2 <- mapM repMatchTup ms ; core_ms2 <- coreList matchQTyConName ms2 ; repCaseE arg core_ms2 } repE (HsIf _ x y z) = do a <- repLE x b <- repLE y c <- repLE z repCond a b c repE (HsMultiIf _ alts) = do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts ; expr' <- repMultiIf (nonEmptyCoreList alts') ; wrapGenSyms (concat binds) expr' } repE (HsLet bs e) = do { (ss,ds) <- repBinds bs ; e2 <- addBinds ss (repLE e) ; z <- repLetE ds e2 ; wrapGenSyms ss z } -- FIXME: I haven't got the types here right yet repE e@(HsDo ctxt sts _) | case ctxt of { DoExpr -> True; GhciStmtCtxt -> True; _ -> False } = do { (ss,zs) <- repLSts sts; e' <- repDoE (nonEmptyCoreList zs); wrapGenSyms ss e' } | ListComp <- ctxt = do { (ss,zs) <- repLSts sts; e' <- repComp (nonEmptyCoreList zs); wrapGenSyms ss e' } | otherwise = notHandled "mdo, monad comprehension and [: :]" (ppr e) repE (ExplicitList _ _ es) = do { xs <- repLEs es; repListExp xs } repE e@(ExplicitPArr _ _) = notHandled "Parallel arrays" (ppr e) repE e@(ExplicitTuple es boxed) | not (all tupArgPresent es) = notHandled "Tuple sections" (ppr e) | isBoxed boxed = do { xs <- repLEs [e | Present e <- es]; repTup xs } | otherwise = do { xs <- repLEs [e | Present e <- es]; repUnboxedTup xs } repE (RecordCon c _ flds) = do { x <- lookupLOcc c; fs <- repFields flds; repRecCon x fs } repE (RecordUpd e flds _ _ _) = do { x <- repLE e; fs <- repFields flds; repRecUpd x fs } repE (ExprWithTySig e ty) = do { e1 <- repLE e; t1 <- repLTy ty; repSigExp e1 t1 } repE (ArithSeq _ _ aseq) = case aseq of From e -> do { ds1 <- repLE e; repFrom ds1 } FromThen e1 e2 -> do ds1 <- repLE e1 ds2 <- repLE e2 repFromThen ds1 ds2 FromTo e1 e2 -> do ds1 <- repLE e1 ds2 <- repLE e2 repFromTo ds1 ds2 FromThenTo e1 e2 e3 -> do ds1 <- repLE e1 ds2 <- repLE e2 ds3 <- repLE e3 repFromThenTo ds1 ds2 ds3 repE (HsSpliceE _ splice) = repSplice splice repE e@(PArrSeq {}) = notHandled "Parallel arrays" (ppr e) repE e@(HsCoreAnn {}) = notHandled "Core annotations" (ppr e) repE e@(HsSCC {}) = notHandled "Cost centres" (ppr e) repE e@(HsTickPragma {}) = notHandled "Tick Pragma" (ppr e) repE e@(HsTcBracketOut {}) = notHandled "TH brackets" (ppr e) repE e = notHandled "Expression form" (ppr e) ----------------------------------------------------------------------------- -- Building representations of auxillary structures like Match, Clause, Stmt, repMatchTup :: LMatch Name (LHsExpr Name) -> DsM (Core TH.MatchQ) repMatchTup (L _ (Match [p] _ (GRHSs guards wheres))) = do { ss1 <- mkGenSyms (collectPatBinders p) ; addBinds ss1 $ do { ; p1 <- repLP p ; (ss2,ds) <- repBinds wheres ; addBinds ss2 $ do { ; gs <- repGuards guards ; match <- repMatch p1 gs ds ; wrapGenSyms (ss1++ss2) match }}} repMatchTup _ = panic "repMatchTup: case alt with more than one arg" repClauseTup :: LMatch Name (LHsExpr Name) -> DsM (Core TH.ClauseQ) repClauseTup (L _ (Match ps _ (GRHSs guards wheres))) = do { ss1 <- mkGenSyms (collectPatsBinders ps) ; addBinds ss1 $ do { ps1 <- repLPs ps ; (ss2,ds) <- repBinds wheres ; addBinds ss2 $ do { gs <- repGuards guards ; clause <- repClause ps1 gs ds ; wrapGenSyms (ss1++ss2) clause }}} repGuards :: [LGRHS Name (LHsExpr Name)] -> DsM (Core TH.BodyQ) repGuards [L _ (GRHS [] e)] = do {a <- repLE e; repNormal a } repGuards other = do { zs <- mapM repLGRHS other ; let (xs, ys) = unzip zs ; gd <- repGuarded (nonEmptyCoreList ys) ; wrapGenSyms (concat xs) gd } repLGRHS :: LGRHS Name (LHsExpr Name) -> DsM ([GenSymBind], (Core (TH.Q (TH.Guard, TH.Exp)))) repLGRHS (L _ (GRHS [L _ (BodyStmt e1 _ _ _)] e2)) = do { guarded <- repLNormalGE e1 e2 ; return ([], guarded) } repLGRHS (L _ (GRHS ss rhs)) = do { (gs, ss') <- repLSts ss ; rhs' <- addBinds gs $ repLE rhs ; guarded <- repPatGE (nonEmptyCoreList ss') rhs' ; return (gs, guarded) } repFields :: HsRecordBinds Name -> DsM (Core [TH.Q TH.FieldExp]) repFields (HsRecFields { rec_flds = flds }) = repList fieldExpQTyConName rep_fld flds where rep_fld fld = do { fn <- lookupLOcc (hsRecFieldId fld) ; e <- repLE (hsRecFieldArg fld) ; repFieldExp fn e } ----------------------------------------------------------------------------- -- Representing Stmt's is tricky, especially if bound variables -- shadow each other. Consider: [| do { x <- f 1; x <- f x; g x } |] -- First gensym new names for every variable in any of the patterns. -- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y")) -- if variables didn't shaddow, the static gensym wouldn't be necessary -- and we could reuse the original names (x and x). -- -- do { x'1 <- gensym "x" -- ; x'2 <- gensym "x" -- ; doE [ BindSt (pvar x'1) [| f 1 |] -- , BindSt (pvar x'2) [| f x |] -- , NoBindSt [| g x |] -- ] -- } -- The strategy is to translate a whole list of do-bindings by building a -- bigger environment, and a bigger set of meta bindings -- (like: x'1 <- gensym "x" ) and then combining these with the translations -- of the expressions within the Do ----------------------------------------------------------------------------- -- The helper function repSts computes the translation of each sub expression -- and a bunch of prefix bindings denoting the dynamic renaming. repLSts :: [LStmt Name (LHsExpr Name)] -> DsM ([GenSymBind], [Core TH.StmtQ]) repLSts stmts = repSts (map unLoc stmts) repSts :: [Stmt Name (LHsExpr Name)] -> DsM ([GenSymBind], [Core TH.StmtQ]) repSts (BindStmt p e _ _ : ss) = do { e2 <- repLE e ; ss1 <- mkGenSyms (collectPatBinders p) ; addBinds ss1 $ do { ; p1 <- repLP p; ; (ss2,zs) <- repSts ss ; z <- repBindSt p1 e2 ; return (ss1++ss2, z : zs) }} repSts (LetStmt bs : ss) = do { (ss1,ds) <- repBinds bs ; z <- repLetSt ds ; (ss2,zs) <- addBinds ss1 (repSts ss) ; return (ss1++ss2, z : zs) } repSts (BodyStmt e _ _ _ : ss) = do { e2 <- repLE e ; z <- repNoBindSt e2 ; (ss2,zs) <- repSts ss ; return (ss2, z : zs) } repSts (ParStmt stmt_blocks _ _ : ss) = do { (ss_s, stmt_blocks1) <- mapAndUnzipM rep_stmt_block stmt_blocks ; let stmt_blocks2 = nonEmptyCoreList stmt_blocks1 ss1 = concat ss_s ; z <- repParSt stmt_blocks2 ; (ss2, zs) <- addBinds ss1 (repSts ss) ; return (ss1++ss2, z : zs) } where rep_stmt_block :: ParStmtBlock Name Name -> DsM ([GenSymBind], Core [TH.StmtQ]) rep_stmt_block (ParStmtBlock stmts _ _) = do { (ss1, zs) <- repSts (map unLoc stmts) ; zs1 <- coreList stmtQTyConName zs ; return (ss1, zs1) } repSts [LastStmt e _] = do { e2 <- repLE e ; z <- repNoBindSt e2 ; return ([], [z]) } repSts [] = return ([],[]) repSts other = notHandled "Exotic statement" (ppr other) ----------------------------------------------------------- -- Bindings ----------------------------------------------------------- repBinds :: HsLocalBinds Name -> DsM ([GenSymBind], Core [TH.DecQ]) repBinds EmptyLocalBinds = do { core_list <- coreList decQTyConName [] ; return ([], core_list) } repBinds b@(HsIPBinds _) = notHandled "Implicit parameters" (ppr b) repBinds (HsValBinds decs) = do { let { bndrs = hsSigTvBinders decs ++ collectHsValBinders decs } -- No need to worrry about detailed scopes within -- the binding group, because we are talking Names -- here, so we can safely treat it as a mutually -- recursive group -- For hsSigTvBinders see Note [Scoped type variables in bindings] ; ss <- mkGenSyms bndrs ; prs <- addBinds ss (rep_val_binds decs) ; core_list <- coreList decQTyConName (de_loc (sort_by_loc prs)) ; return (ss, core_list) } rep_val_binds :: HsValBinds Name -> DsM [(SrcSpan, Core TH.DecQ)] -- Assumes: all the binders of the binding are alrady in the meta-env rep_val_binds (ValBindsOut binds sigs) = do { core1 <- rep_binds' (unionManyBags (map snd binds)) ; core2 <- rep_sigs' sigs ; return (core1 ++ core2) } rep_val_binds (ValBindsIn _ _) = panic "rep_val_binds: ValBindsIn" rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ] rep_binds binds = do { binds_w_locs <- rep_binds' binds ; return (de_loc (sort_by_loc binds_w_locs)) } rep_binds' :: LHsBinds Name -> DsM [(SrcSpan, Core TH.DecQ)] rep_binds' = mapM rep_bind . bagToList rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ) -- Assumes: all the binders of the binding are alrady in the meta-env -- Note GHC treats declarations of a variable (not a pattern) -- e.g. x = g 5 as a Fun MonoBinds. This is indicated by a single match -- with an empty list of patterns rep_bind (L loc (FunBind { fun_id = fn, fun_matches = MG { mg_alts = [L _ (Match [] _ (GRHSs guards wheres))] } })) = do { (ss,wherecore) <- repBinds wheres ; guardcore <- addBinds ss (repGuards guards) ; fn' <- lookupLBinder fn ; p <- repPvar fn' ; ans <- repVal p guardcore wherecore ; ans' <- wrapGenSyms ss ans ; return (loc, ans') } rep_bind (L loc (FunBind { fun_id = fn, fun_matches = MG { mg_alts = ms } })) = do { ms1 <- mapM repClauseTup ms ; fn' <- lookupLBinder fn ; ans <- repFun fn' (nonEmptyCoreList ms1) ; return (loc, ans) } rep_bind (L loc (PatBind { pat_lhs = pat, pat_rhs = GRHSs guards wheres })) = do { patcore <- repLP pat ; (ss,wherecore) <- repBinds wheres ; guardcore <- addBinds ss (repGuards guards) ; ans <- repVal patcore guardcore wherecore ; ans' <- wrapGenSyms ss ans ; return (loc, ans') } rep_bind (L _ (VarBind { var_id = v, var_rhs = e})) = do { v' <- lookupBinder v ; e2 <- repLE e ; x <- repNormal e2 ; patcore <- repPvar v' ; empty_decls <- coreList decQTyConName [] ; ans <- repVal patcore x empty_decls ; return (srcLocSpan (getSrcLoc v), ans) } rep_bind (L _ (AbsBinds {})) = panic "rep_bind: AbsBinds" rep_bind (L _ dec@(PatSynBind {})) = notHandled "pattern synonyms" (ppr dec) ----------------------------------------------------------------------------- -- Since everything in a Bind is mutually recursive we need rename all -- all the variables simultaneously. For example: -- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to -- do { f'1 <- gensym "f" -- ; g'2 <- gensym "g" -- ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]}, -- do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]} -- ]} -- This requires collecting the bindings (f'1 <- gensym "f"), and the -- environment ( f |-> f'1 ) from each binding, and then unioning them -- together. As we do this we collect GenSymBinds's which represent the renamed -- variables bound by the Bindings. In order not to lose track of these -- representations we build a shadow datatype MB with the same structure as -- MonoBinds, but which has slots for the representations ----------------------------------------------------------------------------- -- GHC allows a more general form of lambda abstraction than specified -- by Haskell 98. In particular it allows guarded lambda's like : -- (\ x | even x -> 0 | odd x -> 1) at the moment we can't represent this in -- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like -- (\ p1 .. pn -> exp) by causing an error. repLambda :: LMatch Name (LHsExpr Name) -> DsM (Core TH.ExpQ) repLambda (L _ (Match ps _ (GRHSs [L _ (GRHS [] e)] EmptyLocalBinds))) = do { let bndrs = collectPatsBinders ps ; ; ss <- mkGenSyms bndrs ; lam <- addBinds ss ( do { xs <- repLPs ps; body <- repLE e; repLam xs body }) ; wrapGenSyms ss lam } repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch (LambdaExpr :: HsMatchContext Name) m) ----------------------------------------------------------------------------- -- Patterns -- repP deals with patterns. It assumes that we have already -- walked over the pattern(s) once to collect the binders, and -- have extended the environment. So every pattern-bound -- variable should already appear in the environment. -- Process a list of patterns repLPs :: [LPat Name] -> DsM (Core [TH.PatQ]) repLPs ps = repList patQTyConName repLP ps repLP :: LPat Name -> DsM (Core TH.PatQ) repLP (L _ p) = repP p repP :: Pat Name -> DsM (Core TH.PatQ) repP (WildPat _) = repPwild repP (LitPat l) = do { l2 <- repLiteral l; repPlit l2 } repP (VarPat x) = do { x' <- lookupBinder x; repPvar x' } repP (LazyPat p) = do { p1 <- repLP p; repPtilde p1 } repP (BangPat p) = do { p1 <- repLP p; repPbang p1 } repP (AsPat x p) = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 } repP (ParPat p) = repLP p repP (ListPat ps _ Nothing) = do { qs <- repLPs ps; repPlist qs } repP (ListPat ps ty1 (Just (_,e))) = do { p <- repP (ListPat ps ty1 Nothing); e' <- repE e; repPview e' p} repP (TuplePat ps boxed _) | isBoxed boxed = do { qs <- repLPs ps; repPtup qs } | otherwise = do { qs <- repLPs ps; repPunboxedTup qs } repP (ConPatIn dc details) = do { con_str <- lookupLOcc dc ; case details of PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs } RecCon rec -> do { fps <- repList fieldPatQTyConName rep_fld (rec_flds rec) ; repPrec con_str fps } InfixCon p1 p2 -> do { p1' <- repLP p1; p2' <- repLP p2; repPinfix p1' con_str p2' } } where rep_fld fld = do { MkC v <- lookupLOcc (hsRecFieldId fld) ; MkC p <- repLP (hsRecFieldArg fld) ; rep2 fieldPatName [v,p] } repP (NPat l Nothing _) = do { a <- repOverloadedLiteral l; repPlit a } repP (ViewPat e p _) = do { e' <- repLE e; p' <- repLP p; repPview e' p' } repP p@(NPat _ (Just _) _) = notHandled "Negative overloaded patterns" (ppr p) repP p@(SigPatIn {}) = notHandled "Type signatures in patterns" (ppr p) -- The problem is to do with scoped type variables. -- To implement them, we have to implement the scoping rules -- here in DsMeta, and I don't want to do that today! -- do { p' <- repLP p; t' <- repLTy t; repPsig p' t' } -- repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ) -- repPsig (MkC p) (MkC t) = rep2 sigPName [p, t] repP (SplicePat splice) = repSplice splice repP other = notHandled "Exotic pattern" (ppr other) ---------------------------------------------------------- -- Declaration ordering helpers sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)] sort_by_loc xs = sortBy comp xs where comp x y = compare (fst x) (fst y) de_loc :: [(a, b)] -> [b] de_loc = map snd ---------------------------------------------------------- -- The meta-environment -- A name/identifier association for fresh names of locally bound entities type GenSymBind = (Name, Id) -- Gensym the string and bind it to the Id -- I.e. (x, x_id) means -- let x_id = gensym "x" in ... -- Generate a fresh name for a locally bound entity mkGenSyms :: [Name] -> DsM [GenSymBind] -- We can use the existing name. For example: -- [| \x_77 -> x_77 + x_77 |] -- desugars to -- do { x_77 <- genSym "x"; .... } -- We use the same x_77 in the desugared program, but with the type Bndr -- instead of Int -- -- We do make it an Internal name, though (hence localiseName) -- -- Nevertheless, it's monadic because we have to generate nameTy mkGenSyms ns = do { var_ty <- lookupType nameTyConName ; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] } addBinds :: [GenSymBind] -> DsM a -> DsM a -- Add a list of fresh names for locally bound entities to the -- meta environment (which is part of the state carried around -- by the desugarer monad) addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,Bound id) | (n,id) <- bs]) m dupBinder :: (Name, Name) -> DsM (Name, DsMetaVal) dupBinder (new, old) = do { mb_val <- dsLookupMetaEnv old ; case mb_val of Just val -> return (new, val) Nothing -> pprPanic "dupBinder" (ppr old) } -- Look up a locally bound name -- lookupLBinder :: Located Name -> DsM (Core TH.Name) lookupLBinder (L _ n) = lookupBinder n lookupBinder :: Name -> DsM (Core TH.Name) lookupBinder = lookupOcc -- Binders are brought into scope before the pattern or what-not is -- desugared. Moreover, in instance declaration the binder of a method -- will be the selector Id and hence a global; so we need the -- globalVar case of lookupOcc -- Look up a name that is either locally bound or a global name -- -- * If it is a global name, generate the "original name" representation (ie, -- the <module>:<name> form) for the associated entity -- lookupLOcc :: Located Name -> DsM (Core TH.Name) -- Lookup an occurrence; it can't be a splice. -- Use the in-scope bindings if they exist lookupLOcc (L _ n) = lookupOcc n lookupOcc :: Name -> DsM (Core TH.Name) lookupOcc n = do { mb_val <- dsLookupMetaEnv n ; case mb_val of Nothing -> globalVar n Just (Bound x) -> return (coreVar x) Just (Splice _) -> pprPanic "repE:lookupOcc" (ppr n) } globalVar :: Name -> DsM (Core TH.Name) -- Not bound by the meta-env -- Could be top-level; or could be local -- f x = $(g [| x |]) -- Here the x will be local globalVar name | isExternalName name = do { MkC mod <- coreStringLit name_mod ; MkC pkg <- coreStringLit name_pkg ; MkC occ <- occNameLit name ; rep2 mk_varg [pkg,mod,occ] } | otherwise = do { MkC occ <- occNameLit name ; MkC uni <- coreIntLit (getKey (getUnique name)) ; rep2 mkNameLName [occ,uni] } where mod = ASSERT( isExternalName name) nameModule name name_mod = moduleNameString (moduleName mod) name_pkg = packageKeyString (modulePackageKey mod) name_occ = nameOccName name mk_varg | OccName.isDataOcc name_occ = mkNameG_dName | OccName.isVarOcc name_occ = mkNameG_vName | OccName.isTcOcc name_occ = mkNameG_tcName | otherwise = pprPanic "DsMeta.globalVar" (ppr name) lookupType :: Name -- Name of type constructor (e.g. TH.ExpQ) -> DsM Type -- The type lookupType tc_name = do { tc <- dsLookupTyCon tc_name ; return (mkTyConApp tc []) } wrapGenSyms :: [GenSymBind] -> Core (TH.Q a) -> DsM (Core (TH.Q a)) -- wrapGenSyms [(nm1,id1), (nm2,id2)] y -- --> bindQ (gensym nm1) (\ id1 -> -- bindQ (gensym nm2 (\ id2 -> -- y)) wrapGenSyms binds body@(MkC b) = do { var_ty <- lookupType nameTyConName ; go var_ty binds } where [elt_ty] = tcTyConAppArgs (exprType b) -- b :: Q a, so we can get the type 'a' by looking at the -- argument type. NB: this relies on Q being a data/newtype, -- not a type synonym go _ [] = return body go var_ty ((name,id) : binds) = do { MkC body' <- go var_ty binds ; lit_str <- occNameLit name ; gensym_app <- repGensym lit_str ; repBindQ var_ty elt_ty gensym_app (MkC (Lam id body')) } occNameLit :: Name -> DsM (Core String) occNameLit n = coreStringLit (occNameString (nameOccName n)) -- %********************************************************************* -- %* * -- Constructing code -- %* * -- %********************************************************************* ----------------------------------------------------------------------------- -- PHANTOM TYPES for consistency. In order to make sure we do this correct -- we invent a new datatype which uses phantom types. newtype Core a = MkC CoreExpr unC :: Core a -> CoreExpr unC (MkC x) = x rep2 :: Name -> [ CoreExpr ] -> DsM (Core a) rep2 n xs = do { id <- dsLookupGlobalId n ; return (MkC (foldl App (Var id) xs)) } dataCon' :: Name -> [CoreExpr] -> DsM (Core a) dataCon' n args = do { id <- dsLookupDataCon n ; return $ MkC $ mkCoreConApps id args } dataCon :: Name -> DsM (Core a) dataCon n = dataCon' n [] -- Then we make "repConstructors" which use the phantom types for each of the -- smart constructors of the Meta.Meta datatypes. -- %********************************************************************* -- %* * -- The 'smart constructors' -- %* * -- %********************************************************************* --------------- Patterns ----------------- repPlit :: Core TH.Lit -> DsM (Core TH.PatQ) repPlit (MkC l) = rep2 litPName [l] repPvar :: Core TH.Name -> DsM (Core TH.PatQ) repPvar (MkC s) = rep2 varPName [s] repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ) repPtup (MkC ps) = rep2 tupPName [ps] repPunboxedTup :: Core [TH.PatQ] -> DsM (Core TH.PatQ) repPunboxedTup (MkC ps) = rep2 unboxedTupPName [ps] repPcon :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ) repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps] repPrec :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ) repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps] repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ) repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2] repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ) repPtilde (MkC p) = rep2 tildePName [p] repPbang :: Core TH.PatQ -> DsM (Core TH.PatQ) repPbang (MkC p) = rep2 bangPName [p] repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ) repPaspat (MkC s) (MkC p) = rep2 asPName [s, p] repPwild :: DsM (Core TH.PatQ) repPwild = rep2 wildPName [] repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ) repPlist (MkC ps) = rep2 listPName [ps] repPview :: Core TH.ExpQ -> Core TH.PatQ -> DsM (Core TH.PatQ) repPview (MkC e) (MkC p) = rep2 viewPName [e,p] --------------- Expressions ----------------- repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ) repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str | otherwise = repVar str repVar :: Core TH.Name -> DsM (Core TH.ExpQ) repVar (MkC s) = rep2 varEName [s] repCon :: Core TH.Name -> DsM (Core TH.ExpQ) repCon (MkC s) = rep2 conEName [s] repLit :: Core TH.Lit -> DsM (Core TH.ExpQ) repLit (MkC c) = rep2 litEName [c] repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repApp (MkC x) (MkC y) = rep2 appEName [x,y] repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e] repLamCase :: Core [TH.MatchQ] -> DsM (Core TH.ExpQ) repLamCase (MkC ms) = rep2 lamCaseEName [ms] repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) repTup (MkC es) = rep2 tupEName [es] repUnboxedTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) repUnboxedTup (MkC es) = rep2 unboxedTupEName [es] repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z] repMultiIf :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.ExpQ) repMultiIf (MkC alts) = rep2 multiIfEName [alts] repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e] repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ) repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms] repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ) repDoE (MkC ss) = rep2 doEName [ss] repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ) repComp (MkC ss) = rep2 compEName [ss] repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) repListExp (MkC es) = rep2 listEName [es] repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ) repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t] repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ) repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs] repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ) repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs] repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp)) repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x] repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z] repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y] repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y] ------------ Right hand sides (guarded expressions) ---- repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ) repGuarded (MkC pairs) = rep2 guardedBName [pairs] repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ) repNormal (MkC e) = rep2 normalBName [e] ------------ Guards ---- repLNormalGE :: LHsExpr Name -> LHsExpr Name -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) repLNormalGE g e = do g' <- repLE g e' <- repLE e repNormalGE g' e' repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e] repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e] ------------- Stmts ------------------- repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ) repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e] repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ) repLetSt (MkC ds) = rep2 letSName [ds] repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ) repNoBindSt (MkC e) = rep2 noBindSName [e] repParSt :: Core [[TH.StmtQ]] -> DsM (Core TH.StmtQ) repParSt (MkC sss) = rep2 parSName [sss] -------------- Range (Arithmetic sequences) ----------- repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ) repFrom (MkC x) = rep2 fromEName [x] repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y] repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y] repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z] ------------ Match and Clause Tuples ----------- repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ) repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds] repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ) repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds] -------------- Dec ----------------------------- repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ) repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds] repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ) repFun (MkC nm) (MkC b) = rep2 funDName [nm, b] repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -> Maybe (Core [TH.TypeQ]) -> Core [TH.ConQ] -> Core [TH.Name] -> DsM (Core TH.DecQ) repData (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC cons) (MkC derivs) = rep2 dataDName [cxt, nm, tvs, cons, derivs] repData (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC cons) (MkC derivs) = rep2 dataInstDName [cxt, nm, tys, cons, derivs] repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -> Maybe (Core [TH.TypeQ]) -> Core TH.ConQ -> Core [TH.Name] -> DsM (Core TH.DecQ) repNewtype (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC con) (MkC derivs) = rep2 newtypeDName [cxt, nm, tvs, con, derivs] repNewtype (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC con) (MkC derivs) = rep2 newtypeInstDName [cxt, nm, tys, con, derivs] repTySyn :: Core TH.Name -> Core [TH.TyVarBndr] -> Core TH.TypeQ -> DsM (Core TH.DecQ) repTySyn (MkC nm) (MkC tvs) (MkC rhs) = rep2 tySynDName [nm, tvs, rhs] repInst :: Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ) repInst (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceDName [cxt, ty, ds] repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -> Core [TH.FunDep] -> Core [TH.DecQ] -> DsM (Core TH.DecQ) repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds) = rep2 classDName [cxt, cls, tvs, fds, ds] repDeriv :: Core TH.CxtQ -> Core TH.TypeQ -> DsM (Core TH.DecQ) repDeriv (MkC cxt) (MkC ty) = rep2 standaloneDerivDName [cxt, ty] repPragInl :: Core TH.Name -> Core TH.Inline -> Core TH.RuleMatch -> Core TH.Phases -> DsM (Core TH.DecQ) repPragInl (MkC nm) (MkC inline) (MkC rm) (MkC phases) = rep2 pragInlDName [nm, inline, rm, phases] repPragSpec :: Core TH.Name -> Core TH.TypeQ -> Core TH.Phases -> DsM (Core TH.DecQ) repPragSpec (MkC nm) (MkC ty) (MkC phases) = rep2 pragSpecDName [nm, ty, phases] repPragSpecInl :: Core TH.Name -> Core TH.TypeQ -> Core TH.Inline -> Core TH.Phases -> DsM (Core TH.DecQ) repPragSpecInl (MkC nm) (MkC ty) (MkC inline) (MkC phases) = rep2 pragSpecInlDName [nm, ty, inline, phases] repPragSpecInst :: Core TH.TypeQ -> DsM (Core TH.DecQ) repPragSpecInst (MkC ty) = rep2 pragSpecInstDName [ty] repPragRule :: Core String -> Core [TH.RuleBndrQ] -> Core TH.ExpQ -> Core TH.ExpQ -> Core TH.Phases -> DsM (Core TH.DecQ) repPragRule (MkC nm) (MkC bndrs) (MkC lhs) (MkC rhs) (MkC phases) = rep2 pragRuleDName [nm, bndrs, lhs, rhs, phases] repPragAnn :: Core TH.AnnTarget -> Core TH.ExpQ -> DsM (Core TH.DecQ) repPragAnn (MkC targ) (MkC e) = rep2 pragAnnDName [targ, e] repFamilyNoKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr] -> DsM (Core TH.DecQ) repFamilyNoKind (MkC flav) (MkC nm) (MkC tvs) = rep2 familyNoKindDName [flav, nm, tvs] repFamilyKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr] -> Core TH.Kind -> DsM (Core TH.DecQ) repFamilyKind (MkC flav) (MkC nm) (MkC tvs) (MkC ki) = rep2 familyKindDName [flav, nm, tvs, ki] repTySynInst :: Core TH.Name -> Core TH.TySynEqnQ -> DsM (Core TH.DecQ) repTySynInst (MkC nm) (MkC eqn) = rep2 tySynInstDName [nm, eqn] repClosedFamilyNoKind :: Core TH.Name -> Core [TH.TyVarBndr] -> Core [TH.TySynEqnQ] -> DsM (Core TH.DecQ) repClosedFamilyNoKind (MkC nm) (MkC tvs) (MkC eqns) = rep2 closedTypeFamilyNoKindDName [nm, tvs, eqns] repClosedFamilyKind :: Core TH.Name -> Core [TH.TyVarBndr] -> Core TH.Kind -> Core [TH.TySynEqnQ] -> DsM (Core TH.DecQ) repClosedFamilyKind (MkC nm) (MkC tvs) (MkC ki) (MkC eqns) = rep2 closedTypeFamilyKindDName [nm, tvs, ki, eqns] repTySynEqn :: Core [TH.TypeQ] -> Core TH.TypeQ -> DsM (Core TH.TySynEqnQ) repTySynEqn (MkC lhs) (MkC rhs) = rep2 tySynEqnName [lhs, rhs] repRoleAnnotD :: Core TH.Name -> Core [TH.Role] -> DsM (Core TH.DecQ) repRoleAnnotD (MkC n) (MkC roles) = rep2 roleAnnotDName [n, roles] repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep) repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys] repProto :: Name -> Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ) repProto mk_sig (MkC s) (MkC ty) = rep2 mk_sig [s, ty] repCtxt :: Core [TH.PredQ] -> DsM (Core TH.CxtQ) repCtxt (MkC tys) = rep2 cxtName [tys] repConstr :: Core TH.Name -> HsConDeclDetails Name -> DsM (Core TH.ConQ) repConstr con (PrefixCon ps) = do arg_tys <- repList strictTypeQTyConName repBangTy ps rep2 normalCName [unC con, unC arg_tys] repConstr con (RecCon ips) = do { arg_vtys <- repList varStrictTypeQTyConName rep_ip ips ; rep2 recCName [unC con, unC arg_vtys] } where rep_ip ip = do { MkC v <- lookupLOcc (cd_fld_name ip) ; MkC ty <- repBangTy (cd_fld_type ip) ; rep2 varStrictTypeName [v,ty] } repConstr con (InfixCon st1 st2) = do arg1 <- repBangTy st1 arg2 <- repBangTy st2 rep2 infixCName [unC arg1, unC con, unC arg2] ------------ Types ------------------- repTForall :: Core [TH.TyVarBndr] -> Core TH.CxtQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ) repTForall (MkC tvars) (MkC ctxt) (MkC ty) = rep2 forallTName [tvars, ctxt, ty] repTvar :: Core TH.Name -> DsM (Core TH.TypeQ) repTvar (MkC s) = rep2 varTName [s] repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ) repTapp (MkC t1) (MkC t2) = rep2 appTName [t1, t2] repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ) repTapps f [] = return f repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts } repTSig :: Core TH.TypeQ -> Core TH.Kind -> DsM (Core TH.TypeQ) repTSig (MkC ty) (MkC ki) = rep2 sigTName [ty, ki] repTequality :: DsM (Core TH.TypeQ) repTequality = rep2 equalityTName [] repTPromotedList :: [Core TH.TypeQ] -> DsM (Core TH.TypeQ) repTPromotedList [] = repPromotedNilTyCon repTPromotedList (t:ts) = do { tcon <- repPromotedConsTyCon ; f <- repTapp tcon t ; t' <- repTPromotedList ts ; repTapp f t' } repTLit :: Core TH.TyLitQ -> DsM (Core TH.TypeQ) repTLit (MkC lit) = rep2 litTName [lit] --------- Type constructors -------------- repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ) repNamedTyCon (MkC s) = rep2 conTName [s] repTupleTyCon :: Int -> DsM (Core TH.TypeQ) -- Note: not Core Int; it's easier to be direct here repTupleTyCon i = do dflags <- getDynFlags rep2 tupleTName [mkIntExprInt dflags i] repUnboxedTupleTyCon :: Int -> DsM (Core TH.TypeQ) -- Note: not Core Int; it's easier to be direct here repUnboxedTupleTyCon i = do dflags <- getDynFlags rep2 unboxedTupleTName [mkIntExprInt dflags i] repArrowTyCon :: DsM (Core TH.TypeQ) repArrowTyCon = rep2 arrowTName [] repListTyCon :: DsM (Core TH.TypeQ) repListTyCon = rep2 listTName [] repPromotedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ) repPromotedTyCon (MkC s) = rep2 promotedTName [s] repPromotedTupleTyCon :: Int -> DsM (Core TH.TypeQ) repPromotedTupleTyCon i = do dflags <- getDynFlags rep2 promotedTupleTName [mkIntExprInt dflags i] repPromotedNilTyCon :: DsM (Core TH.TypeQ) repPromotedNilTyCon = rep2 promotedNilTName [] repPromotedConsTyCon :: DsM (Core TH.TypeQ) repPromotedConsTyCon = rep2 promotedConsTName [] ------------ Kinds ------------------- repPlainTV :: Core TH.Name -> DsM (Core TH.TyVarBndr) repPlainTV (MkC nm) = rep2 plainTVName [nm] repKindedTV :: Core TH.Name -> Core TH.Kind -> DsM (Core TH.TyVarBndr) repKindedTV (MkC nm) (MkC ki) = rep2 kindedTVName [nm, ki] repKVar :: Core TH.Name -> DsM (Core TH.Kind) repKVar (MkC s) = rep2 varKName [s] repKCon :: Core TH.Name -> DsM (Core TH.Kind) repKCon (MkC s) = rep2 conKName [s] repKTuple :: Int -> DsM (Core TH.Kind) repKTuple i = do dflags <- getDynFlags rep2 tupleKName [mkIntExprInt dflags i] repKArrow :: DsM (Core TH.Kind) repKArrow = rep2 arrowKName [] repKList :: DsM (Core TH.Kind) repKList = rep2 listKName [] repKApp :: Core TH.Kind -> Core TH.Kind -> DsM (Core TH.Kind) repKApp (MkC k1) (MkC k2) = rep2 appKName [k1, k2] repKApps :: Core TH.Kind -> [Core TH.Kind] -> DsM (Core TH.Kind) repKApps f [] = return f repKApps f (k:ks) = do { f' <- repKApp f k; repKApps f' ks } repKStar :: DsM (Core TH.Kind) repKStar = rep2 starKName [] repKConstraint :: DsM (Core TH.Kind) repKConstraint = rep2 constraintKName [] ---------------------------------------------------------- -- Literals repLiteral :: HsLit -> DsM (Core TH.Lit) repLiteral lit = do lit' <- case lit of HsIntPrim i -> mk_integer i HsWordPrim w -> mk_integer w HsInt i -> mk_integer i HsFloatPrim r -> mk_rational r HsDoublePrim r -> mk_rational r _ -> return lit lit_expr <- dsLit lit' case mb_lit_name of Just lit_name -> rep2 lit_name [lit_expr] Nothing -> notHandled "Exotic literal" (ppr lit) where mb_lit_name = case lit of HsInteger _ _ -> Just integerLName HsInt _ -> Just integerLName HsIntPrim _ -> Just intPrimLName HsWordPrim _ -> Just wordPrimLName HsFloatPrim _ -> Just floatPrimLName HsDoublePrim _ -> Just doublePrimLName HsChar _ -> Just charLName HsString _ -> Just stringLName HsRat _ _ -> Just rationalLName _ -> Nothing mk_integer :: Integer -> DsM HsLit mk_integer i = do integer_ty <- lookupType integerTyConName return $ HsInteger i integer_ty mk_rational :: FractionalLit -> DsM HsLit mk_rational r = do rat_ty <- lookupType rationalTyConName return $ HsRat r rat_ty mk_string :: FastString -> DsM HsLit mk_string s = return $ HsString s repOverloadedLiteral :: HsOverLit Name -> DsM (Core TH.Lit) repOverloadedLiteral (OverLit { ol_val = val}) = do { lit <- mk_lit val; repLiteral lit } -- The type Rational will be in the environment, because -- the smart constructor 'TH.Syntax.rationalL' uses it in its type, -- and rationalL is sucked in when any TH stuff is used mk_lit :: OverLitVal -> DsM HsLit mk_lit (HsIntegral i) = mk_integer i mk_lit (HsFractional f) = mk_rational f mk_lit (HsIsString s) = mk_string s --------------- Miscellaneous ------------------- repGensym :: Core String -> DsM (Core (TH.Q TH.Name)) repGensym (MkC lit_str) = rep2 newNameName [lit_str] repBindQ :: Type -> Type -- a and b -> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b)) repBindQ ty_a ty_b (MkC x) (MkC y) = rep2 bindQName [Type ty_a, Type ty_b, x, y] repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a])) repSequenceQ ty_a (MkC list) = rep2 sequenceQName [Type ty_a, list] ------------ Lists and Tuples ------------------- -- turn a list of patterns into a single pattern matching a list repList :: Name -> (a -> DsM (Core b)) -> [a] -> DsM (Core [b]) repList tc_name f args = do { args1 <- mapM f args ; coreList tc_name args1 } coreList :: Name -- Of the TyCon of the element type -> [Core a] -> DsM (Core [a]) coreList tc_name es = do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) } coreList' :: Type -- The element type -> [Core a] -> Core [a] coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es )) nonEmptyCoreList :: [Core a] -> Core [a] -- The list must be non-empty so we can get the element type -- Otherwise use coreList nonEmptyCoreList [] = panic "coreList: empty argument" nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs)) coreStringLit :: String -> DsM (Core String) coreStringLit s = do { z <- mkStringExpr s; return(MkC z) } ------------ Literals & Variables ------------------- coreIntLit :: Int -> DsM (Core Int) coreIntLit i = do dflags <- getDynFlags return (MkC (mkIntExprInt dflags i)) coreVar :: Id -> Core TH.Name -- The Id has type Name coreVar id = MkC (Var id) ----------------- Failure ----------------------- notHandledL :: SrcSpan -> String -> SDoc -> DsM a notHandledL loc what doc | isGoodSrcSpan loc = putSrcSpanDs loc $ notHandled what doc | otherwise = notHandled what doc notHandled :: String -> SDoc -> DsM a notHandled what doc = failWithDs msg where msg = hang (text what <+> ptext (sLit "not (yet) handled by Template Haskell")) 2 doc -- %************************************************************************ -- %* * -- The known-key names for Template Haskell -- %* * -- %************************************************************************ -- To add a name, do three things -- -- 1) Allocate a key -- 2) Make a "Name" -- 3) Add the name to knownKeyNames templateHaskellNames :: [Name] -- The names that are implicitly mentioned by ``bracket'' -- Should stay in sync with the import list of DsMeta templateHaskellNames = [ returnQName, bindQName, sequenceQName, newNameName, liftName, mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, liftStringName, unTypeName, unTypeQName, unsafeTExpCoerceName, -- Lit charLName, stringLName, integerLName, intPrimLName, wordPrimLName, floatPrimLName, doublePrimLName, rationalLName, -- Pat litPName, varPName, tupPName, unboxedTupPName, conPName, tildePName, bangPName, infixPName, asPName, wildPName, recPName, listPName, sigPName, viewPName, -- FieldPat fieldPatName, -- Match matchName, -- Clause clauseName, -- Exp varEName, conEName, litEName, appEName, infixEName, infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName, tupEName, unboxedTupEName, condEName, multiIfEName, letEName, caseEName, doEName, compEName, fromEName, fromThenEName, fromToEName, fromThenToEName, listEName, sigEName, recConEName, recUpdEName, -- FieldExp fieldExpName, -- Body guardedBName, normalBName, -- Guard normalGEName, patGEName, -- Stmt bindSName, letSName, noBindSName, parSName, -- Dec funDName, valDName, dataDName, newtypeDName, tySynDName, classDName, instanceDName, standaloneDerivDName, sigDName, forImpDName, pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName, pragRuleDName, pragAnnDName, defaultSigDName, familyNoKindDName, familyKindDName, dataInstDName, newtypeInstDName, tySynInstDName, closedTypeFamilyKindDName, closedTypeFamilyNoKindDName, infixLDName, infixRDName, infixNDName, roleAnnotDName, -- Cxt cxtName, -- Strict isStrictName, notStrictName, unpackedName, -- Con normalCName, recCName, infixCName, forallCName, -- StrictType strictTypeName, -- VarStrictType varStrictTypeName, -- Type forallTName, varTName, conTName, appTName, equalityTName, tupleTName, unboxedTupleTName, arrowTName, listTName, sigTName, litTName, promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName, -- TyLit numTyLitName, strTyLitName, -- TyVarBndr plainTVName, kindedTVName, -- Role nominalRName, representationalRName, phantomRName, inferRName, -- Kind varKName, conKName, tupleKName, arrowKName, listKName, appKName, starKName, constraintKName, -- Callconv cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName, -- Safety unsafeName, safeName, interruptibleName, -- Inline noInlineDataConName, inlineDataConName, inlinableDataConName, -- RuleMatch conLikeDataConName, funLikeDataConName, -- Phases allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName, -- TExp tExpDataConName, -- RuleBndr ruleVarName, typedRuleVarName, -- FunDep funDepName, -- FamFlavour typeFamName, dataFamName, -- TySynEqn tySynEqnName, -- AnnTarget valueAnnotationName, typeAnnotationName, moduleAnnotationName, -- And the tycons qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName, clauseQTyConName, expQTyConName, fieldExpTyConName, predTyConName, stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName, varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName, typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName, patQTyConName, fieldPatQTyConName, fieldExpQTyConName, funDepTyConName, predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName, tExpTyConName, -- Quasiquoting quoteDecName, quoteTypeName, quoteExpName, quotePatName] thSyn, thLib, qqLib :: Module thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax") thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib") qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote") mkTHModule :: FastString -> Module mkTHModule m = mkModule thPackageKey (mkModuleNameFS m) libFun, libTc, thFun, thTc, thCon, qqFun :: FastString -> Unique -> Name libFun = mk_known_key_name OccName.varName thLib libTc = mk_known_key_name OccName.tcName thLib thFun = mk_known_key_name OccName.varName thSyn thTc = mk_known_key_name OccName.tcName thSyn thCon = mk_known_key_name OccName.dataName thSyn qqFun = mk_known_key_name OccName.varName qqLib -------------------- TH.Syntax ----------------------- qTyConName, nameTyConName, fieldExpTyConName, patTyConName, fieldPatTyConName, expTyConName, decTyConName, typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName, funDepTyConName, predTyConName, tExpTyConName :: Name qTyConName = thTc (fsLit "Q") qTyConKey nameTyConName = thTc (fsLit "Name") nameTyConKey fieldExpTyConName = thTc (fsLit "FieldExp") fieldExpTyConKey patTyConName = thTc (fsLit "Pat") patTyConKey fieldPatTyConName = thTc (fsLit "FieldPat") fieldPatTyConKey expTyConName = thTc (fsLit "Exp") expTyConKey decTyConName = thTc (fsLit "Dec") decTyConKey typeTyConName = thTc (fsLit "Type") typeTyConKey tyVarBndrTyConName= thTc (fsLit "TyVarBndr") tyVarBndrTyConKey matchTyConName = thTc (fsLit "Match") matchTyConKey clauseTyConName = thTc (fsLit "Clause") clauseTyConKey funDepTyConName = thTc (fsLit "FunDep") funDepTyConKey predTyConName = thTc (fsLit "Pred") predTyConKey tExpTyConName = thTc (fsLit "TExp") tExpTyConKey returnQName, bindQName, sequenceQName, newNameName, liftName, mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, liftStringName, unTypeName, unTypeQName, unsafeTExpCoerceName :: Name returnQName = thFun (fsLit "returnQ") returnQIdKey bindQName = thFun (fsLit "bindQ") bindQIdKey sequenceQName = thFun (fsLit "sequenceQ") sequenceQIdKey newNameName = thFun (fsLit "newName") newNameIdKey liftName = thFun (fsLit "lift") liftIdKey liftStringName = thFun (fsLit "liftString") liftStringIdKey mkNameName = thFun (fsLit "mkName") mkNameIdKey mkNameG_vName = thFun (fsLit "mkNameG_v") mkNameG_vIdKey mkNameG_dName = thFun (fsLit "mkNameG_d") mkNameG_dIdKey mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey mkNameLName = thFun (fsLit "mkNameL") mkNameLIdKey unTypeName = thFun (fsLit "unType") unTypeIdKey unTypeQName = thFun (fsLit "unTypeQ") unTypeQIdKey unsafeTExpCoerceName = thFun (fsLit "unsafeTExpCoerce") unsafeTExpCoerceIdKey -------------------- TH.Lib ----------------------- -- data Lit = ... charLName, stringLName, integerLName, intPrimLName, wordPrimLName, floatPrimLName, doublePrimLName, rationalLName :: Name charLName = libFun (fsLit "charL") charLIdKey stringLName = libFun (fsLit "stringL") stringLIdKey integerLName = libFun (fsLit "integerL") integerLIdKey intPrimLName = libFun (fsLit "intPrimL") intPrimLIdKey wordPrimLName = libFun (fsLit "wordPrimL") wordPrimLIdKey floatPrimLName = libFun (fsLit "floatPrimL") floatPrimLIdKey doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey rationalLName = libFun (fsLit "rationalL") rationalLIdKey -- data Pat = ... litPName, varPName, tupPName, unboxedTupPName, conPName, infixPName, tildePName, bangPName, asPName, wildPName, recPName, listPName, sigPName, viewPName :: Name litPName = libFun (fsLit "litP") litPIdKey varPName = libFun (fsLit "varP") varPIdKey tupPName = libFun (fsLit "tupP") tupPIdKey unboxedTupPName = libFun (fsLit "unboxedTupP") unboxedTupPIdKey conPName = libFun (fsLit "conP") conPIdKey infixPName = libFun (fsLit "infixP") infixPIdKey tildePName = libFun (fsLit "tildeP") tildePIdKey bangPName = libFun (fsLit "bangP") bangPIdKey asPName = libFun (fsLit "asP") asPIdKey wildPName = libFun (fsLit "wildP") wildPIdKey recPName = libFun (fsLit "recP") recPIdKey listPName = libFun (fsLit "listP") listPIdKey sigPName = libFun (fsLit "sigP") sigPIdKey viewPName = libFun (fsLit "viewP") viewPIdKey -- type FieldPat = ... fieldPatName :: Name fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey -- data Match = ... matchName :: Name matchName = libFun (fsLit "match") matchIdKey -- data Clause = ... clauseName :: Name clauseName = libFun (fsLit "clause") clauseIdKey -- data Exp = ... varEName, conEName, litEName, appEName, infixEName, infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName, tupEName, unboxedTupEName, condEName, multiIfEName, letEName, caseEName, doEName, compEName :: Name varEName = libFun (fsLit "varE") varEIdKey conEName = libFun (fsLit "conE") conEIdKey litEName = libFun (fsLit "litE") litEIdKey appEName = libFun (fsLit "appE") appEIdKey infixEName = libFun (fsLit "infixE") infixEIdKey infixAppName = libFun (fsLit "infixApp") infixAppIdKey sectionLName = libFun (fsLit "sectionL") sectionLIdKey sectionRName = libFun (fsLit "sectionR") sectionRIdKey lamEName = libFun (fsLit "lamE") lamEIdKey lamCaseEName = libFun (fsLit "lamCaseE") lamCaseEIdKey tupEName = libFun (fsLit "tupE") tupEIdKey unboxedTupEName = libFun (fsLit "unboxedTupE") unboxedTupEIdKey condEName = libFun (fsLit "condE") condEIdKey multiIfEName = libFun (fsLit "multiIfE") multiIfEIdKey letEName = libFun (fsLit "letE") letEIdKey caseEName = libFun (fsLit "caseE") caseEIdKey doEName = libFun (fsLit "doE") doEIdKey compEName = libFun (fsLit "compE") compEIdKey -- ArithSeq skips a level fromEName, fromThenEName, fromToEName, fromThenToEName :: Name fromEName = libFun (fsLit "fromE") fromEIdKey fromThenEName = libFun (fsLit "fromThenE") fromThenEIdKey fromToEName = libFun (fsLit "fromToE") fromToEIdKey fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey -- end ArithSeq listEName, sigEName, recConEName, recUpdEName :: Name listEName = libFun (fsLit "listE") listEIdKey sigEName = libFun (fsLit "sigE") sigEIdKey recConEName = libFun (fsLit "recConE") recConEIdKey recUpdEName = libFun (fsLit "recUpdE") recUpdEIdKey -- type FieldExp = ... fieldExpName :: Name fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey -- data Body = ... guardedBName, normalBName :: Name guardedBName = libFun (fsLit "guardedB") guardedBIdKey normalBName = libFun (fsLit "normalB") normalBIdKey -- data Guard = ... normalGEName, patGEName :: Name normalGEName = libFun (fsLit "normalGE") normalGEIdKey patGEName = libFun (fsLit "patGE") patGEIdKey -- data Stmt = ... bindSName, letSName, noBindSName, parSName :: Name bindSName = libFun (fsLit "bindS") bindSIdKey letSName = libFun (fsLit "letS") letSIdKey noBindSName = libFun (fsLit "noBindS") noBindSIdKey parSName = libFun (fsLit "parS") parSIdKey -- data Dec = ... funDName, valDName, dataDName, newtypeDName, tySynDName, classDName, instanceDName, sigDName, forImpDName, pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName, pragRuleDName, pragAnnDName, familyNoKindDName, standaloneDerivDName, defaultSigDName, familyKindDName, dataInstDName, newtypeInstDName, tySynInstDName, closedTypeFamilyKindDName, closedTypeFamilyNoKindDName, infixLDName, infixRDName, infixNDName, roleAnnotDName :: Name funDName = libFun (fsLit "funD") funDIdKey valDName = libFun (fsLit "valD") valDIdKey dataDName = libFun (fsLit "dataD") dataDIdKey newtypeDName = libFun (fsLit "newtypeD") newtypeDIdKey tySynDName = libFun (fsLit "tySynD") tySynDIdKey classDName = libFun (fsLit "classD") classDIdKey instanceDName = libFun (fsLit "instanceD") instanceDIdKey standaloneDerivDName = libFun (fsLit "standaloneDerivD") standaloneDerivDIdKey sigDName = libFun (fsLit "sigD") sigDIdKey defaultSigDName = libFun (fsLit "defaultSigD") defaultSigDIdKey forImpDName = libFun (fsLit "forImpD") forImpDIdKey pragInlDName = libFun (fsLit "pragInlD") pragInlDIdKey pragSpecDName = libFun (fsLit "pragSpecD") pragSpecDIdKey pragSpecInlDName = libFun (fsLit "pragSpecInlD") pragSpecInlDIdKey pragSpecInstDName = libFun (fsLit "pragSpecInstD") pragSpecInstDIdKey pragRuleDName = libFun (fsLit "pragRuleD") pragRuleDIdKey pragAnnDName = libFun (fsLit "pragAnnD") pragAnnDIdKey familyNoKindDName = libFun (fsLit "familyNoKindD") familyNoKindDIdKey familyKindDName = libFun (fsLit "familyKindD") familyKindDIdKey dataInstDName = libFun (fsLit "dataInstD") dataInstDIdKey newtypeInstDName = libFun (fsLit "newtypeInstD") newtypeInstDIdKey tySynInstDName = libFun (fsLit "tySynInstD") tySynInstDIdKey closedTypeFamilyKindDName = libFun (fsLit "closedTypeFamilyKindD") closedTypeFamilyKindDIdKey closedTypeFamilyNoKindDName = libFun (fsLit "closedTypeFamilyNoKindD") closedTypeFamilyNoKindDIdKey infixLDName = libFun (fsLit "infixLD") infixLDIdKey infixRDName = libFun (fsLit "infixRD") infixRDIdKey infixNDName = libFun (fsLit "infixND") infixNDIdKey roleAnnotDName = libFun (fsLit "roleAnnotD") roleAnnotDIdKey -- type Ctxt = ... cxtName :: Name cxtName = libFun (fsLit "cxt") cxtIdKey -- data Strict = ... isStrictName, notStrictName, unpackedName :: Name isStrictName = libFun (fsLit "isStrict") isStrictKey notStrictName = libFun (fsLit "notStrict") notStrictKey unpackedName = libFun (fsLit "unpacked") unpackedKey -- data Con = ... normalCName, recCName, infixCName, forallCName :: Name normalCName = libFun (fsLit "normalC") normalCIdKey recCName = libFun (fsLit "recC") recCIdKey infixCName = libFun (fsLit "infixC") infixCIdKey forallCName = libFun (fsLit "forallC") forallCIdKey -- type StrictType = ... strictTypeName :: Name strictTypeName = libFun (fsLit "strictType") strictTKey -- type VarStrictType = ... varStrictTypeName :: Name varStrictTypeName = libFun (fsLit "varStrictType") varStrictTKey -- data Type = ... forallTName, varTName, conTName, tupleTName, unboxedTupleTName, arrowTName, listTName, appTName, sigTName, equalityTName, litTName, promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName :: Name forallTName = libFun (fsLit "forallT") forallTIdKey varTName = libFun (fsLit "varT") varTIdKey conTName = libFun (fsLit "conT") conTIdKey tupleTName = libFun (fsLit "tupleT") tupleTIdKey unboxedTupleTName = libFun (fsLit "unboxedTupleT") unboxedTupleTIdKey arrowTName = libFun (fsLit "arrowT") arrowTIdKey listTName = libFun (fsLit "listT") listTIdKey appTName = libFun (fsLit "appT") appTIdKey sigTName = libFun (fsLit "sigT") sigTIdKey equalityTName = libFun (fsLit "equalityT") equalityTIdKey litTName = libFun (fsLit "litT") litTIdKey promotedTName = libFun (fsLit "promotedT") promotedTIdKey promotedTupleTName = libFun (fsLit "promotedTupleT") promotedTupleTIdKey promotedNilTName = libFun (fsLit "promotedNilT") promotedNilTIdKey promotedConsTName = libFun (fsLit "promotedConsT") promotedConsTIdKey -- data TyLit = ... numTyLitName, strTyLitName :: Name numTyLitName = libFun (fsLit "numTyLit") numTyLitIdKey strTyLitName = libFun (fsLit "strTyLit") strTyLitIdKey -- data TyVarBndr = ... plainTVName, kindedTVName :: Name plainTVName = libFun (fsLit "plainTV") plainTVIdKey kindedTVName = libFun (fsLit "kindedTV") kindedTVIdKey -- data Role = ... nominalRName, representationalRName, phantomRName, inferRName :: Name nominalRName = libFun (fsLit "nominalR") nominalRIdKey representationalRName = libFun (fsLit "representationalR") representationalRIdKey phantomRName = libFun (fsLit "phantomR") phantomRIdKey inferRName = libFun (fsLit "inferR") inferRIdKey -- data Kind = ... varKName, conKName, tupleKName, arrowKName, listKName, appKName, starKName, constraintKName :: Name varKName = libFun (fsLit "varK") varKIdKey conKName = libFun (fsLit "conK") conKIdKey tupleKName = libFun (fsLit "tupleK") tupleKIdKey arrowKName = libFun (fsLit "arrowK") arrowKIdKey listKName = libFun (fsLit "listK") listKIdKey appKName = libFun (fsLit "appK") appKIdKey starKName = libFun (fsLit "starK") starKIdKey constraintKName = libFun (fsLit "constraintK") constraintKIdKey -- data Callconv = ... cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName :: Name cCallName = libFun (fsLit "cCall") cCallIdKey stdCallName = libFun (fsLit "stdCall") stdCallIdKey cApiCallName = libFun (fsLit "cApi") cApiCallIdKey primCallName = libFun (fsLit "prim") primCallIdKey javaScriptCallName = libFun (fsLit "javaScript") javaScriptCallIdKey -- data Safety = ... unsafeName, safeName, interruptibleName :: Name unsafeName = libFun (fsLit "unsafe") unsafeIdKey safeName = libFun (fsLit "safe") safeIdKey interruptibleName = libFun (fsLit "interruptible") interruptibleIdKey -- data Inline = ... noInlineDataConName, inlineDataConName, inlinableDataConName :: Name noInlineDataConName = thCon (fsLit "NoInline") noInlineDataConKey inlineDataConName = thCon (fsLit "Inline") inlineDataConKey inlinableDataConName = thCon (fsLit "Inlinable") inlinableDataConKey -- data RuleMatch = ... conLikeDataConName, funLikeDataConName :: Name conLikeDataConName = thCon (fsLit "ConLike") conLikeDataConKey funLikeDataConName = thCon (fsLit "FunLike") funLikeDataConKey -- data Phases = ... allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName :: Name allPhasesDataConName = thCon (fsLit "AllPhases") allPhasesDataConKey fromPhaseDataConName = thCon (fsLit "FromPhase") fromPhaseDataConKey beforePhaseDataConName = thCon (fsLit "BeforePhase") beforePhaseDataConKey -- newtype TExp a = ... tExpDataConName :: Name tExpDataConName = thCon (fsLit "TExp") tExpDataConKey -- data RuleBndr = ... ruleVarName, typedRuleVarName :: Name ruleVarName = libFun (fsLit ("ruleVar")) ruleVarIdKey typedRuleVarName = libFun (fsLit ("typedRuleVar")) typedRuleVarIdKey -- data FunDep = ... funDepName :: Name funDepName = libFun (fsLit "funDep") funDepIdKey -- data FamFlavour = ... typeFamName, dataFamName :: Name typeFamName = libFun (fsLit "typeFam") typeFamIdKey dataFamName = libFun (fsLit "dataFam") dataFamIdKey -- data TySynEqn = ... tySynEqnName :: Name tySynEqnName = libFun (fsLit "tySynEqn") tySynEqnIdKey -- data AnnTarget = ... valueAnnotationName, typeAnnotationName, moduleAnnotationName :: Name valueAnnotationName = libFun (fsLit "valueAnnotation") valueAnnotationIdKey typeAnnotationName = libFun (fsLit "typeAnnotation") typeAnnotationIdKey moduleAnnotationName = libFun (fsLit "moduleAnnotation") moduleAnnotationIdKey matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName, varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName, patQTyConName, fieldPatQTyConName, predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName :: Name matchQTyConName = libTc (fsLit "MatchQ") matchQTyConKey clauseQTyConName = libTc (fsLit "ClauseQ") clauseQTyConKey expQTyConName = libTc (fsLit "ExpQ") expQTyConKey stmtQTyConName = libTc (fsLit "StmtQ") stmtQTyConKey decQTyConName = libTc (fsLit "DecQ") decQTyConKey decsQTyConName = libTc (fsLit "DecsQ") decsQTyConKey -- Q [Dec] conQTyConName = libTc (fsLit "ConQ") conQTyConKey strictTypeQTyConName = libTc (fsLit "StrictTypeQ") strictTypeQTyConKey varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey typeQTyConName = libTc (fsLit "TypeQ") typeQTyConKey fieldExpQTyConName = libTc (fsLit "FieldExpQ") fieldExpQTyConKey patQTyConName = libTc (fsLit "PatQ") patQTyConKey fieldPatQTyConName = libTc (fsLit "FieldPatQ") fieldPatQTyConKey predQTyConName = libTc (fsLit "PredQ") predQTyConKey ruleBndrQTyConName = libTc (fsLit "RuleBndrQ") ruleBndrQTyConKey tySynEqnQTyConName = libTc (fsLit "TySynEqnQ") tySynEqnQTyConKey roleTyConName = libTc (fsLit "Role") roleTyConKey -- quasiquoting quoteExpName, quotePatName, quoteDecName, quoteTypeName :: Name quoteExpName = qqFun (fsLit "quoteExp") quoteExpKey quotePatName = qqFun (fsLit "quotePat") quotePatKey quoteDecName = qqFun (fsLit "quoteDec") quoteDecKey quoteTypeName = qqFun (fsLit "quoteType") quoteTypeKey -- TyConUniques available: 200-299 -- Check in PrelNames if you want to change this expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey, decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey, stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey, tyVarBndrTyConKey, decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey, fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey, fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey, predTyConKey, predQTyConKey, decsQTyConKey, ruleBndrQTyConKey, tySynEqnQTyConKey, roleTyConKey, tExpTyConKey :: Unique expTyConKey = mkPreludeTyConUnique 200 matchTyConKey = mkPreludeTyConUnique 201 clauseTyConKey = mkPreludeTyConUnique 202 qTyConKey = mkPreludeTyConUnique 203 expQTyConKey = mkPreludeTyConUnique 204 decQTyConKey = mkPreludeTyConUnique 205 patTyConKey = mkPreludeTyConUnique 206 matchQTyConKey = mkPreludeTyConUnique 207 clauseQTyConKey = mkPreludeTyConUnique 208 stmtQTyConKey = mkPreludeTyConUnique 209 conQTyConKey = mkPreludeTyConUnique 210 typeQTyConKey = mkPreludeTyConUnique 211 typeTyConKey = mkPreludeTyConUnique 212 decTyConKey = mkPreludeTyConUnique 213 varStrictTypeQTyConKey = mkPreludeTyConUnique 214 strictTypeQTyConKey = mkPreludeTyConUnique 215 fieldExpTyConKey = mkPreludeTyConUnique 216 fieldPatTyConKey = mkPreludeTyConUnique 217 nameTyConKey = mkPreludeTyConUnique 218 patQTyConKey = mkPreludeTyConUnique 219 fieldPatQTyConKey = mkPreludeTyConUnique 220 fieldExpQTyConKey = mkPreludeTyConUnique 221 funDepTyConKey = mkPreludeTyConUnique 222 predTyConKey = mkPreludeTyConUnique 223 predQTyConKey = mkPreludeTyConUnique 224 tyVarBndrTyConKey = mkPreludeTyConUnique 225 decsQTyConKey = mkPreludeTyConUnique 226 ruleBndrQTyConKey = mkPreludeTyConUnique 227 tySynEqnQTyConKey = mkPreludeTyConUnique 228 roleTyConKey = mkPreludeTyConUnique 229 tExpTyConKey = mkPreludeTyConUnique 230 -- IdUniques available: 200-499 -- If you want to change this, make sure you check in PrelNames returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey, mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey, mkNameLIdKey, unTypeIdKey, unTypeQIdKey, unsafeTExpCoerceIdKey :: Unique returnQIdKey = mkPreludeMiscIdUnique 200 bindQIdKey = mkPreludeMiscIdUnique 201 sequenceQIdKey = mkPreludeMiscIdUnique 202 liftIdKey = mkPreludeMiscIdUnique 203 newNameIdKey = mkPreludeMiscIdUnique 204 mkNameIdKey = mkPreludeMiscIdUnique 205 mkNameG_vIdKey = mkPreludeMiscIdUnique 206 mkNameG_dIdKey = mkPreludeMiscIdUnique 207 mkNameG_tcIdKey = mkPreludeMiscIdUnique 208 mkNameLIdKey = mkPreludeMiscIdUnique 209 unTypeIdKey = mkPreludeMiscIdUnique 210 unTypeQIdKey = mkPreludeMiscIdUnique 211 unsafeTExpCoerceIdKey = mkPreludeMiscIdUnique 212 -- data Lit = ... charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey, floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey :: Unique charLIdKey = mkPreludeMiscIdUnique 220 stringLIdKey = mkPreludeMiscIdUnique 221 integerLIdKey = mkPreludeMiscIdUnique 222 intPrimLIdKey = mkPreludeMiscIdUnique 223 wordPrimLIdKey = mkPreludeMiscIdUnique 224 floatPrimLIdKey = mkPreludeMiscIdUnique 225 doublePrimLIdKey = mkPreludeMiscIdUnique 226 rationalLIdKey = mkPreludeMiscIdUnique 227 liftStringIdKey :: Unique liftStringIdKey = mkPreludeMiscIdUnique 228 -- data Pat = ... litPIdKey, varPIdKey, tupPIdKey, unboxedTupPIdKey, conPIdKey, infixPIdKey, tildePIdKey, bangPIdKey, asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey, viewPIdKey :: Unique litPIdKey = mkPreludeMiscIdUnique 240 varPIdKey = mkPreludeMiscIdUnique 241 tupPIdKey = mkPreludeMiscIdUnique 242 unboxedTupPIdKey = mkPreludeMiscIdUnique 243 conPIdKey = mkPreludeMiscIdUnique 244 infixPIdKey = mkPreludeMiscIdUnique 245 tildePIdKey = mkPreludeMiscIdUnique 246 bangPIdKey = mkPreludeMiscIdUnique 247 asPIdKey = mkPreludeMiscIdUnique 248 wildPIdKey = mkPreludeMiscIdUnique 249 recPIdKey = mkPreludeMiscIdUnique 250 listPIdKey = mkPreludeMiscIdUnique 251 sigPIdKey = mkPreludeMiscIdUnique 252 viewPIdKey = mkPreludeMiscIdUnique 253 -- type FieldPat = ... fieldPatIdKey :: Unique fieldPatIdKey = mkPreludeMiscIdUnique 260 -- data Match = ... matchIdKey :: Unique matchIdKey = mkPreludeMiscIdUnique 261 -- data Clause = ... clauseIdKey :: Unique clauseIdKey = mkPreludeMiscIdUnique 262 -- data Exp = ... varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey, sectionLIdKey, sectionRIdKey, lamEIdKey, lamCaseEIdKey, tupEIdKey, unboxedTupEIdKey, condEIdKey, multiIfEIdKey, letEIdKey, caseEIdKey, doEIdKey, compEIdKey, fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey, listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey :: Unique varEIdKey = mkPreludeMiscIdUnique 270 conEIdKey = mkPreludeMiscIdUnique 271 litEIdKey = mkPreludeMiscIdUnique 272 appEIdKey = mkPreludeMiscIdUnique 273 infixEIdKey = mkPreludeMiscIdUnique 274 infixAppIdKey = mkPreludeMiscIdUnique 275 sectionLIdKey = mkPreludeMiscIdUnique 276 sectionRIdKey = mkPreludeMiscIdUnique 277 lamEIdKey = mkPreludeMiscIdUnique 278 lamCaseEIdKey = mkPreludeMiscIdUnique 279 tupEIdKey = mkPreludeMiscIdUnique 280 unboxedTupEIdKey = mkPreludeMiscIdUnique 281 condEIdKey = mkPreludeMiscIdUnique 282 multiIfEIdKey = mkPreludeMiscIdUnique 283 letEIdKey = mkPreludeMiscIdUnique 284 caseEIdKey = mkPreludeMiscIdUnique 285 doEIdKey = mkPreludeMiscIdUnique 286 compEIdKey = mkPreludeMiscIdUnique 287 fromEIdKey = mkPreludeMiscIdUnique 288 fromThenEIdKey = mkPreludeMiscIdUnique 289 fromToEIdKey = mkPreludeMiscIdUnique 290 fromThenToEIdKey = mkPreludeMiscIdUnique 291 listEIdKey = mkPreludeMiscIdUnique 292 sigEIdKey = mkPreludeMiscIdUnique 293 recConEIdKey = mkPreludeMiscIdUnique 294 recUpdEIdKey = mkPreludeMiscIdUnique 295 -- type FieldExp = ... fieldExpIdKey :: Unique fieldExpIdKey = mkPreludeMiscIdUnique 310 -- data Body = ... guardedBIdKey, normalBIdKey :: Unique guardedBIdKey = mkPreludeMiscIdUnique 311 normalBIdKey = mkPreludeMiscIdUnique 312 -- data Guard = ... normalGEIdKey, patGEIdKey :: Unique normalGEIdKey = mkPreludeMiscIdUnique 313 patGEIdKey = mkPreludeMiscIdUnique 314 -- data Stmt = ... bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique bindSIdKey = mkPreludeMiscIdUnique 320 letSIdKey = mkPreludeMiscIdUnique 321 noBindSIdKey = mkPreludeMiscIdUnique 322 parSIdKey = mkPreludeMiscIdUnique 323 -- data Dec = ... funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey, classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey, pragInlDIdKey, pragSpecDIdKey, pragSpecInlDIdKey, pragSpecInstDIdKey, pragRuleDIdKey, pragAnnDIdKey, familyNoKindDIdKey, familyKindDIdKey, defaultSigDIdKey, dataInstDIdKey, newtypeInstDIdKey, tySynInstDIdKey, standaloneDerivDIdKey, closedTypeFamilyKindDIdKey, closedTypeFamilyNoKindDIdKey, infixLDIdKey, infixRDIdKey, infixNDIdKey, roleAnnotDIdKey :: Unique funDIdKey = mkPreludeMiscIdUnique 330 valDIdKey = mkPreludeMiscIdUnique 331 dataDIdKey = mkPreludeMiscIdUnique 332 newtypeDIdKey = mkPreludeMiscIdUnique 333 tySynDIdKey = mkPreludeMiscIdUnique 334 classDIdKey = mkPreludeMiscIdUnique 335 instanceDIdKey = mkPreludeMiscIdUnique 336 sigDIdKey = mkPreludeMiscIdUnique 337 forImpDIdKey = mkPreludeMiscIdUnique 338 pragInlDIdKey = mkPreludeMiscIdUnique 339 pragSpecDIdKey = mkPreludeMiscIdUnique 340 pragSpecInlDIdKey = mkPreludeMiscIdUnique 341 pragSpecInstDIdKey = mkPreludeMiscIdUnique 342 pragRuleDIdKey = mkPreludeMiscIdUnique 343 pragAnnDIdKey = mkPreludeMiscIdUnique 344 familyNoKindDIdKey = mkPreludeMiscIdUnique 345 familyKindDIdKey = mkPreludeMiscIdUnique 346 dataInstDIdKey = mkPreludeMiscIdUnique 347 newtypeInstDIdKey = mkPreludeMiscIdUnique 348 tySynInstDIdKey = mkPreludeMiscIdUnique 349 closedTypeFamilyKindDIdKey = mkPreludeMiscIdUnique 350 closedTypeFamilyNoKindDIdKey = mkPreludeMiscIdUnique 351 infixLDIdKey = mkPreludeMiscIdUnique 352 infixRDIdKey = mkPreludeMiscIdUnique 353 infixNDIdKey = mkPreludeMiscIdUnique 354 roleAnnotDIdKey = mkPreludeMiscIdUnique 355 standaloneDerivDIdKey = mkPreludeMiscIdUnique 356 defaultSigDIdKey = mkPreludeMiscIdUnique 357 -- type Cxt = ... cxtIdKey :: Unique cxtIdKey = mkPreludeMiscIdUnique 360 -- data Strict = ... isStrictKey, notStrictKey, unpackedKey :: Unique isStrictKey = mkPreludeMiscIdUnique 363 notStrictKey = mkPreludeMiscIdUnique 364 unpackedKey = mkPreludeMiscIdUnique 365 -- data Con = ... normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique normalCIdKey = mkPreludeMiscIdUnique 370 recCIdKey = mkPreludeMiscIdUnique 371 infixCIdKey = mkPreludeMiscIdUnique 372 forallCIdKey = mkPreludeMiscIdUnique 373 -- type StrictType = ... strictTKey :: Unique strictTKey = mkPreludeMiscIdUnique 374 -- type VarStrictType = ... varStrictTKey :: Unique varStrictTKey = mkPreludeMiscIdUnique 375 -- data Type = ... forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, unboxedTupleTIdKey, arrowTIdKey, listTIdKey, appTIdKey, sigTIdKey, equalityTIdKey, litTIdKey, promotedTIdKey, promotedTupleTIdKey, promotedNilTIdKey, promotedConsTIdKey :: Unique forallTIdKey = mkPreludeMiscIdUnique 380 varTIdKey = mkPreludeMiscIdUnique 381 conTIdKey = mkPreludeMiscIdUnique 382 tupleTIdKey = mkPreludeMiscIdUnique 383 unboxedTupleTIdKey = mkPreludeMiscIdUnique 384 arrowTIdKey = mkPreludeMiscIdUnique 385 listTIdKey = mkPreludeMiscIdUnique 386 appTIdKey = mkPreludeMiscIdUnique 387 sigTIdKey = mkPreludeMiscIdUnique 388 equalityTIdKey = mkPreludeMiscIdUnique 389 litTIdKey = mkPreludeMiscIdUnique 390 promotedTIdKey = mkPreludeMiscIdUnique 391 promotedTupleTIdKey = mkPreludeMiscIdUnique 392 promotedNilTIdKey = mkPreludeMiscIdUnique 393 promotedConsTIdKey = mkPreludeMiscIdUnique 394 -- data TyLit = ... numTyLitIdKey, strTyLitIdKey :: Unique numTyLitIdKey = mkPreludeMiscIdUnique 395 strTyLitIdKey = mkPreludeMiscIdUnique 396 -- data TyVarBndr = ... plainTVIdKey, kindedTVIdKey :: Unique plainTVIdKey = mkPreludeMiscIdUnique 397 kindedTVIdKey = mkPreludeMiscIdUnique 398 -- data Role = ... nominalRIdKey, representationalRIdKey, phantomRIdKey, inferRIdKey :: Unique nominalRIdKey = mkPreludeMiscIdUnique 400 representationalRIdKey = mkPreludeMiscIdUnique 401 phantomRIdKey = mkPreludeMiscIdUnique 402 inferRIdKey = mkPreludeMiscIdUnique 403 -- data Kind = ... varKIdKey, conKIdKey, tupleKIdKey, arrowKIdKey, listKIdKey, appKIdKey, starKIdKey, constraintKIdKey :: Unique varKIdKey = mkPreludeMiscIdUnique 404 conKIdKey = mkPreludeMiscIdUnique 405 tupleKIdKey = mkPreludeMiscIdUnique 406 arrowKIdKey = mkPreludeMiscIdUnique 407 listKIdKey = mkPreludeMiscIdUnique 408 appKIdKey = mkPreludeMiscIdUnique 409 starKIdKey = mkPreludeMiscIdUnique 410 constraintKIdKey = mkPreludeMiscIdUnique 411 -- data Callconv = ... cCallIdKey, stdCallIdKey, cApiCallIdKey, primCallIdKey, javaScriptCallIdKey :: Unique cCallIdKey = mkPreludeMiscIdUnique 420 stdCallIdKey = mkPreludeMiscIdUnique 421 cApiCallIdKey = mkPreludeMiscIdUnique 422 primCallIdKey = mkPreludeMiscIdUnique 423 javaScriptCallIdKey = mkPreludeMiscIdUnique 424 -- data Safety = ... unsafeIdKey, safeIdKey, interruptibleIdKey :: Unique unsafeIdKey = mkPreludeMiscIdUnique 430 safeIdKey = mkPreludeMiscIdUnique 431 interruptibleIdKey = mkPreludeMiscIdUnique 432 -- data Inline = ... noInlineDataConKey, inlineDataConKey, inlinableDataConKey :: Unique noInlineDataConKey = mkPreludeDataConUnique 40 inlineDataConKey = mkPreludeDataConUnique 41 inlinableDataConKey = mkPreludeDataConUnique 42 -- data RuleMatch = ... conLikeDataConKey, funLikeDataConKey :: Unique conLikeDataConKey = mkPreludeDataConUnique 43 funLikeDataConKey = mkPreludeDataConUnique 44 -- data Phases = ... allPhasesDataConKey, fromPhaseDataConKey, beforePhaseDataConKey :: Unique allPhasesDataConKey = mkPreludeDataConUnique 45 fromPhaseDataConKey = mkPreludeDataConUnique 46 beforePhaseDataConKey = mkPreludeDataConUnique 47 -- newtype TExp a = ... tExpDataConKey :: Unique tExpDataConKey = mkPreludeDataConUnique 48 -- data FunDep = ... funDepIdKey :: Unique funDepIdKey = mkPreludeMiscIdUnique 440 -- data FamFlavour = ... typeFamIdKey, dataFamIdKey :: Unique typeFamIdKey = mkPreludeMiscIdUnique 450 dataFamIdKey = mkPreludeMiscIdUnique 451 -- data TySynEqn = ... tySynEqnIdKey :: Unique tySynEqnIdKey = mkPreludeMiscIdUnique 460 -- quasiquoting quoteExpKey, quotePatKey, quoteDecKey, quoteTypeKey :: Unique quoteExpKey = mkPreludeMiscIdUnique 470 quotePatKey = mkPreludeMiscIdUnique 471 quoteDecKey = mkPreludeMiscIdUnique 472 quoteTypeKey = mkPreludeMiscIdUnique 473 -- data RuleBndr = ... ruleVarIdKey, typedRuleVarIdKey :: Unique ruleVarIdKey = mkPreludeMiscIdUnique 480 typedRuleVarIdKey = mkPreludeMiscIdUnique 481 -- data AnnTarget = ... valueAnnotationIdKey, typeAnnotationIdKey, moduleAnnotationIdKey :: Unique valueAnnotationIdKey = mkPreludeMiscIdUnique 490 typeAnnotationIdKey = mkPreludeMiscIdUnique 491 moduleAnnotationIdKey = mkPreludeMiscIdUnique 492
jstolarek/ghc
compiler/deSugar/DsMeta.hs
bsd-3-clause
119,075
2,359
23
31,885
27,006
15,186
11,820
1,996
16
#!/usr/bin/env runhaskell import Prelude hiding (print) import System.Directory import System.FilePath import Data.List import Data.Either import Control.Monad import System.Environment.UTF8 import System.IO.UTF8 import System.IO (stderr, stdin, stdout) import Language.Haskell.Exts.Annotated.ExactPrint import HPath.Path import HPath.Hierarchy import qualified HPath.HaskellSrcExts as HaskellSrcExts import qualified HPath.Cabal as Cabal usage name = unlines [ "USAGE: " ++ name ++ " <Haskell identifier>" , "" , " Print the source text corresponding to the Haskell identifier, assuming" , " we are in a project directory where this source can be found." , "" ] main = do args <- getArgs usage' <- usage `fmap` getProgName case args of ["-h"] -> out usage' ["-?"] -> out usage' ["--help"] -> out usage' [arg] -> case parse arg of Left e -> do err ("Not a path: " ++ arg ++ "\n" ++ show e) err usage' Right path -> do err (url path) dir <- getCurrentDirectory (exts, roots) <- Cabal.info dir let files = nub [ r </> p | p <- paths path, r <- roots ] converted = nub (HaskellSrcExts.extension_conversion exts) when ((not . null) converted) (err (unlines ("Extensions:" : fmap show converted))) (mods, errs) <- HaskellSrcExts.modules files converted let parse_errors = fst errs io_exceptions = snd errs when ((not . null) parse_errors) (err "Parse errors:" >> mapM_ (err . show) parse_errors) when ((not . null) io_exceptions) (err "Varied exceptions:" >> mapM_ (err . show) io_exceptions) if null mods then err "No files corresponding to this identifier." >> err usage' else do let decls = HaskellSrcExts.search path (take 1 mods) mapM_ (out . exactPrint') decls _ -> err usage' err s = hPutStrLn stderr s out s = hPutStrLn stdout s {-| We wrap 'exactPrint' to get rid of the many newlines it normally places in front of the declaration (it positions the output on the same line as it would have been on in the input). -} exactPrint' ep = dropWhile (=='\n') (exactPrint ep [])
solidsnack/hpath
Main.hs
bsd-3-clause
2,594
0
23
935
652
332
320
55
7
module Parser ( parseFile ) where import Data.Char import Text.ParserCombinators.ReadP import Control.Applicative import System.IO import Syntax brackets p = between (char '(' <* skipSpaces) (char ')') p parseOpA = choice [ do string "+" ; return Plus , do string "-" ; return Minus , do string "*" ; return Times ] parseOpB = choice [ do string "&" ; return And , do string "|" ; return Or ] parseOpR = choice [ do string "=" ; return Equal , do string "<" ; return Less , do string "<=" ; return LessEq , do string ">" ; return Greater , do string ">=" ; return GreaterEq ] parseV = do v <- munch1 isAlpha ; return (V v) parseN = do n <- munch1 isDigit ; return (N (read n)) parseA = do chainl1 (terminalA <* skipSpaces) (parseOpA' <* skipSpaces) where parseOpA' = do o <- parseOpA ; return (AOpA o) terminalA = choice [ parseV , parseN , brackets parseA ] parseB = do chainl1 (terminalB <* skipSpaces) (parseOpB' <* skipSpaces) where parseOpB' = do o <- parseOpB ; return (BOpB o) terminalB = choice [ do string "true" ; return (BTrue) , do string "false" ; return (BFalse) , do string "not " ; skipSpaces m <- terminalB return (BNot m) , do m <- parseA o <- parseOpR ; skipSpaces n <- parseA return (BOpR o m n) , brackets parseB ] parseS = do chainl1 (s <* skipSpaces) spacer where spacer = do char ';' +++ char '\n' ; skipSpaces ; return (:>>) s = choice [ do v <- munch1 isAlpha ; skipSpaces string ":=" ; skipSpaces a <- parseA return (v := a) , do string "skip" return SKIP , do string "if" ; skipSpaces b <- parseB string "then" ; skipSpaces t <- parseS string "else" ; skipSpaces e <- parseS string "end" return (IF b t e) , do string "while" ; skipSpaces b <- parseB string "do" ; skipSpaces s <- parseS string "end" ; skipSpaces return (WHILE b s) ] parseFile filename = do s <- readFile filename let p = filter ((=="") . snd) . readP_to_S (skipSpaces >> parseS) $ s return $ case p of [] -> Left "Could not parse" [r] -> Right r _ -> Left "Ambiguous parses"
orchid-hybrid/WHILE
Parser.hs
gpl-2.0
3,012
0
15
1,424
928
435
493
65
3
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} ----------------------------------------------------------------- -- Autogenerated by Thrift -- -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- module MyService where import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..), Eq, Show, Ord, concat, error, fromIntegral, fromEnum, length, map, maybe, not, null, otherwise, return, show, toEnum, enumFromTo, Bounded, minBound, maxBound, seq, succ, pred, enumFrom, enumFromThen, enumFromThenTo, (.), (&&), (||), (==), (++), ($), (-), (>>=), (>>)) import qualified Control.Applicative as Applicative (ZipList(..)) import Control.Applicative ( (<*>) ) import qualified Control.DeepSeq as DeepSeq import qualified Control.Exception as Exception import qualified Control.Monad as Monad ( liftM, ap, when ) import qualified Data.ByteString.Lazy as BS import Data.Functor ( (<$>) ) import qualified Data.Hashable as Hashable import qualified Data.Int as Int import Data.List import qualified Data.Maybe as Maybe (catMaybes) import qualified Data.Text.Lazy.Encoding as Encoding ( decodeUtf8, encodeUtf8 ) import qualified Data.Text.Lazy as LT import qualified Data.Typeable as Typeable ( Typeable ) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector import qualified Test.QuickCheck.Arbitrary as Arbitrary ( Arbitrary(..) ) import qualified Test.QuickCheck as QuickCheck ( elements ) import qualified Thrift import qualified Thrift.Types as Types import qualified Thrift.Serializable as Serializable import qualified Thrift.Arbitraries as Arbitraries import qualified Module_Types as Module_Types import qualified Includes_Types as Includes_Types import qualified Service_Types import qualified MyService_Iface as Iface -- HELPER FUNCTIONS AND STRUCTURES -- data Query_args = Query_args { query_args_s :: Module_Types.MyStruct , query_args_i :: Includes_Types.Included } deriving (Show,Eq,Typeable.Typeable) instance Serializable.ThriftSerializable Query_args where encode = encode_Query_args decode = decode_Query_args instance Hashable.Hashable Query_args where hashWithSalt salt record = salt `Hashable.hashWithSalt` query_args_s record `Hashable.hashWithSalt` query_args_i record instance DeepSeq.NFData Query_args where rnf _record0 = DeepSeq.rnf (query_args_s _record0) `seq` DeepSeq.rnf (query_args_i _record0) `seq` () instance Arbitrary.Arbitrary Query_args where arbitrary = Monad.liftM Query_args (Arbitrary.arbitrary) `Monad.ap`(Arbitrary.arbitrary) shrink obj | obj == default_Query_args = [] | otherwise = Maybe.catMaybes [ if obj == default_Query_args{query_args_s = query_args_s obj} then Nothing else Just $ default_Query_args{query_args_s = query_args_s obj} , if obj == default_Query_args{query_args_i = query_args_i obj} then Nothing else Just $ default_Query_args{query_args_i = query_args_i obj} ] from_Query_args :: Query_args -> Types.ThriftVal from_Query_args record = Types.TStruct $ Map.fromList $ Maybe.catMaybes [ (\_v3 -> Just (1, ("s",Module_Types.from_MyStruct _v3))) $ query_args_s record , (\_v3 -> Just (2, ("i",Includes_Types.from_Included _v3))) $ query_args_i record ] write_Query_args :: (Thrift.Protocol p, Thrift.Transport t) => p t -> Query_args -> IO () write_Query_args oprot record = Thrift.writeVal oprot $ from_Query_args record encode_Query_args :: (Thrift.Protocol p, Thrift.Transport t) => p t -> Query_args -> BS.ByteString encode_Query_args oprot record = Thrift.serializeVal oprot $ from_Query_args record to_Query_args :: Types.ThriftVal -> Query_args to_Query_args (Types.TStruct fields) = Query_args{ query_args_s = maybe (query_args_s default_Query_args) (\(_,_val5) -> (case _val5 of {Types.TStruct _val6 -> (Module_Types.to_MyStruct (Types.TStruct _val6)); _ -> error "wrong type"})) (Map.lookup (1) fields), query_args_i = maybe (query_args_i default_Query_args) (\(_,_val5) -> (case _val5 of {Types.TStruct _val7 -> (Includes_Types.to_Included (Types.TStruct _val7)); _ -> error "wrong type"})) (Map.lookup (2) fields) } to_Query_args _ = error "not a struct" read_Query_args :: (Thrift.Transport t, Thrift.Protocol p) => p t -> IO Query_args read_Query_args iprot = to_Query_args <$> Thrift.readVal iprot (Types.T_STRUCT typemap_Query_args) decode_Query_args :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BS.ByteString -> Query_args decode_Query_args iprot bs = to_Query_args $ Thrift.deserializeVal iprot (Types.T_STRUCT typemap_Query_args) bs typemap_Query_args :: Types.TypeMap typemap_Query_args = Map.fromList [("s",(1,(Types.T_STRUCT Module_Types.typemap_MyStruct))),("i",(2,(Types.T_STRUCT Includes_Types.typemap_Included)))] default_Query_args :: Query_args default_Query_args = Query_args{ query_args_s = Module_Types.default_MyStruct, query_args_i = Includes_Types.default_Included} data Query_result = Query_result deriving (Show,Eq,Typeable.Typeable) instance Serializable.ThriftSerializable Query_result where encode = encode_Query_result decode = decode_Query_result instance Hashable.Hashable Query_result where hashWithSalt salt record = salt instance DeepSeq.NFData Query_result where rnf _record8 = () instance Arbitrary.Arbitrary Query_result where arbitrary = QuickCheck.elements [Query_result] from_Query_result :: Query_result -> Types.ThriftVal from_Query_result record = Types.TStruct $ Map.fromList $ Maybe.catMaybes [] write_Query_result :: (Thrift.Protocol p, Thrift.Transport t) => p t -> Query_result -> IO () write_Query_result oprot record = Thrift.writeVal oprot $ from_Query_result record encode_Query_result :: (Thrift.Protocol p, Thrift.Transport t) => p t -> Query_result -> BS.ByteString encode_Query_result oprot record = Thrift.serializeVal oprot $ from_Query_result record to_Query_result :: Types.ThriftVal -> Query_result to_Query_result (Types.TStruct fields) = Query_result{ } to_Query_result _ = error "not a struct" read_Query_result :: (Thrift.Transport t, Thrift.Protocol p) => p t -> IO Query_result read_Query_result iprot = to_Query_result <$> Thrift.readVal iprot (Types.T_STRUCT typemap_Query_result) decode_Query_result :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BS.ByteString -> Query_result decode_Query_result iprot bs = to_Query_result $ Thrift.deserializeVal iprot (Types.T_STRUCT typemap_Query_result) bs typemap_Query_result :: Types.TypeMap typemap_Query_result = Map.fromList [] default_Query_result :: Query_result default_Query_result = Query_result{ } data Has_arg_docs_args = Has_arg_docs_args { has_arg_docs_args_s :: Module_Types.MyStruct , has_arg_docs_args_i :: Includes_Types.Included } deriving (Show,Eq,Typeable.Typeable) instance Serializable.ThriftSerializable Has_arg_docs_args where encode = encode_Has_arg_docs_args decode = decode_Has_arg_docs_args instance Hashable.Hashable Has_arg_docs_args where hashWithSalt salt record = salt `Hashable.hashWithSalt` has_arg_docs_args_s record `Hashable.hashWithSalt` has_arg_docs_args_i record instance DeepSeq.NFData Has_arg_docs_args where rnf _record14 = DeepSeq.rnf (has_arg_docs_args_s _record14) `seq` DeepSeq.rnf (has_arg_docs_args_i _record14) `seq` () instance Arbitrary.Arbitrary Has_arg_docs_args where arbitrary = Monad.liftM Has_arg_docs_args (Arbitrary.arbitrary) `Monad.ap`(Arbitrary.arbitrary) shrink obj | obj == default_Has_arg_docs_args = [] | otherwise = Maybe.catMaybes [ if obj == default_Has_arg_docs_args{has_arg_docs_args_s = has_arg_docs_args_s obj} then Nothing else Just $ default_Has_arg_docs_args{has_arg_docs_args_s = has_arg_docs_args_s obj} , if obj == default_Has_arg_docs_args{has_arg_docs_args_i = has_arg_docs_args_i obj} then Nothing else Just $ default_Has_arg_docs_args{has_arg_docs_args_i = has_arg_docs_args_i obj} ] from_Has_arg_docs_args :: Has_arg_docs_args -> Types.ThriftVal from_Has_arg_docs_args record = Types.TStruct $ Map.fromList $ Maybe.catMaybes [ (\_v17 -> Just (1, ("s",Module_Types.from_MyStruct _v17))) $ has_arg_docs_args_s record , (\_v17 -> Just (2, ("i",Includes_Types.from_Included _v17))) $ has_arg_docs_args_i record ] write_Has_arg_docs_args :: (Thrift.Protocol p, Thrift.Transport t) => p t -> Has_arg_docs_args -> IO () write_Has_arg_docs_args oprot record = Thrift.writeVal oprot $ from_Has_arg_docs_args record encode_Has_arg_docs_args :: (Thrift.Protocol p, Thrift.Transport t) => p t -> Has_arg_docs_args -> BS.ByteString encode_Has_arg_docs_args oprot record = Thrift.serializeVal oprot $ from_Has_arg_docs_args record to_Has_arg_docs_args :: Types.ThriftVal -> Has_arg_docs_args to_Has_arg_docs_args (Types.TStruct fields) = Has_arg_docs_args{ has_arg_docs_args_s = maybe (has_arg_docs_args_s default_Has_arg_docs_args) (\(_,_val19) -> (case _val19 of {Types.TStruct _val20 -> (Module_Types.to_MyStruct (Types.TStruct _val20)); _ -> error "wrong type"})) (Map.lookup (1) fields), has_arg_docs_args_i = maybe (has_arg_docs_args_i default_Has_arg_docs_args) (\(_,_val19) -> (case _val19 of {Types.TStruct _val21 -> (Includes_Types.to_Included (Types.TStruct _val21)); _ -> error "wrong type"})) (Map.lookup (2) fields) } to_Has_arg_docs_args _ = error "not a struct" read_Has_arg_docs_args :: (Thrift.Transport t, Thrift.Protocol p) => p t -> IO Has_arg_docs_args read_Has_arg_docs_args iprot = to_Has_arg_docs_args <$> Thrift.readVal iprot (Types.T_STRUCT typemap_Has_arg_docs_args) decode_Has_arg_docs_args :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BS.ByteString -> Has_arg_docs_args decode_Has_arg_docs_args iprot bs = to_Has_arg_docs_args $ Thrift.deserializeVal iprot (Types.T_STRUCT typemap_Has_arg_docs_args) bs typemap_Has_arg_docs_args :: Types.TypeMap typemap_Has_arg_docs_args = Map.fromList [("s",(1,(Types.T_STRUCT Module_Types.typemap_MyStruct))),("i",(2,(Types.T_STRUCT Includes_Types.typemap_Included)))] default_Has_arg_docs_args :: Has_arg_docs_args default_Has_arg_docs_args = Has_arg_docs_args{ has_arg_docs_args_s = Module_Types.default_MyStruct, has_arg_docs_args_i = Includes_Types.default_Included} data Has_arg_docs_result = Has_arg_docs_result deriving (Show,Eq,Typeable.Typeable) instance Serializable.ThriftSerializable Has_arg_docs_result where encode = encode_Has_arg_docs_result decode = decode_Has_arg_docs_result instance Hashable.Hashable Has_arg_docs_result where hashWithSalt salt record = salt instance DeepSeq.NFData Has_arg_docs_result where rnf _record22 = () instance Arbitrary.Arbitrary Has_arg_docs_result where arbitrary = QuickCheck.elements [Has_arg_docs_result] from_Has_arg_docs_result :: Has_arg_docs_result -> Types.ThriftVal from_Has_arg_docs_result record = Types.TStruct $ Map.fromList $ Maybe.catMaybes [] write_Has_arg_docs_result :: (Thrift.Protocol p, Thrift.Transport t) => p t -> Has_arg_docs_result -> IO () write_Has_arg_docs_result oprot record = Thrift.writeVal oprot $ from_Has_arg_docs_result record encode_Has_arg_docs_result :: (Thrift.Protocol p, Thrift.Transport t) => p t -> Has_arg_docs_result -> BS.ByteString encode_Has_arg_docs_result oprot record = Thrift.serializeVal oprot $ from_Has_arg_docs_result record to_Has_arg_docs_result :: Types.ThriftVal -> Has_arg_docs_result to_Has_arg_docs_result (Types.TStruct fields) = Has_arg_docs_result{ } to_Has_arg_docs_result _ = error "not a struct" read_Has_arg_docs_result :: (Thrift.Transport t, Thrift.Protocol p) => p t -> IO Has_arg_docs_result read_Has_arg_docs_result iprot = to_Has_arg_docs_result <$> Thrift.readVal iprot (Types.T_STRUCT typemap_Has_arg_docs_result) decode_Has_arg_docs_result :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BS.ByteString -> Has_arg_docs_result decode_Has_arg_docs_result iprot bs = to_Has_arg_docs_result $ Thrift.deserializeVal iprot (Types.T_STRUCT typemap_Has_arg_docs_result) bs typemap_Has_arg_docs_result :: Types.TypeMap typemap_Has_arg_docs_result = Map.fromList [] default_Has_arg_docs_result :: Has_arg_docs_result default_Has_arg_docs_result = Has_arg_docs_result{ } process_query (seqid, iprot, oprot, handler) = do args <- MyService.read_Query_args iprot (Exception.catch (do Iface.query handler (query_args_s args) (query_args_i args) let res = default_Query_result Thrift.writeMessage oprot ("query", Types.M_REPLY, seqid) $ write_Query_result oprot res Thrift.tFlush (Thrift.getTransport oprot)) ((\_ -> do Thrift.writeMessage oprot ("query", Types.M_EXCEPTION, seqid) $ Thrift.writeAppExn oprot (Thrift.AppExn Thrift.AE_UNKNOWN "") Thrift.tFlush (Thrift.getTransport oprot)) :: Exception.SomeException -> IO ())) process_has_arg_docs (seqid, iprot, oprot, handler) = do args <- MyService.read_Has_arg_docs_args iprot (Exception.catch (do Iface.has_arg_docs handler (has_arg_docs_args_s args) (has_arg_docs_args_i args) let res = default_Has_arg_docs_result Thrift.writeMessage oprot ("has_arg_docs", Types.M_REPLY, seqid) $ write_Has_arg_docs_result oprot res Thrift.tFlush (Thrift.getTransport oprot)) ((\_ -> do Thrift.writeMessage oprot ("has_arg_docs", Types.M_EXCEPTION, seqid) $ Thrift.writeAppExn oprot (Thrift.AppExn Thrift.AE_UNKNOWN "") Thrift.tFlush (Thrift.getTransport oprot)) :: Exception.SomeException -> IO ())) proc_ handler (iprot,oprot) (name,typ,seqid) = case name of "query" -> process_query (seqid,iprot,oprot,handler) "has_arg_docs" -> process_has_arg_docs (seqid,iprot,oprot,handler) _ -> do _ <- Thrift.readVal iprot (Types.T_STRUCT Map.empty) Thrift.writeMessage oprot (name,Types.M_EXCEPTION,seqid) $ Thrift.writeAppExn oprot (Thrift.AppExn Thrift.AE_UNKNOWN_METHOD ("Unknown function " ++ LT.unpack name)) Thrift.tFlush (Thrift.getTransport oprot) process handler (iprot, oprot) = Thrift.readMessage iprot (proc_ handler (iprot,oprot)) >> return True
getyourguide/fbthrift
thrift/compiler/test/fixtures/includes/gen-hs/MyService.hs
apache-2.0
14,518
0
18
1,973
4,017
2,177
1,840
226
3
{-# LANGUAGE TypeFamilies #-} -- | Perlin noise implemented in Zeldspar. -- TODO: PNG/BMP sink, to write pretty pictures to disk. import qualified Prelude import Zeldspar import Zeldspar.Parallel -- * Image settings; too large imgWidth, imgHeight or imgOctaves may cause you -- to run out of stack space. Even when using small values, you should use -- @ulimit@ to set a generous stack limit. Telling GCC to compile your program -- with a larger stack also helps. imgWidth = 400 imgHeight = 400 imgOctaves = 5 imgPersistence = 0.5 -- | Decently fast hash function. xs32 :: Data Int32 -> Data Int32 xs32 x = share (x `xor` (x `shiftR` 13)) $ \x' -> share (x' `xor` (x' `shiftL` 17)) $ \x'' -> x'' `xor` (x'' `shiftR` 5) -- | Hash over octave and coordinates. xs32_2 :: Data Int32 -> Data Int32 -> Data Int32 -> Data Int32 xs32_2 octave x y = xs32 $ xs32 (octave*887) + xs32 (x*2251) + xs32 (y*7919) -- | Ridiculous, inlined vector gradient function. Supposedly very fast, -- but quite incomprehensible. grad :: Data Int32 -> Data Int32 -> Data Int32 -> Data Double -> Data Double -> Data Double grad octhash xi yi xf yf = share (xs32_2 octhash xi yi `rem` 8) $ \val -> (val == 0) ? (xf + yf) $ (val == 1) ? (yf - xf) $ (val == 2) ? (xf - yf) $ (val == 3) ? (negate xf - yf) $ (val == 4) ? xf $ (val == 5) ? negate xf $ (val == 6) ? yf $ negate yf -- | Linear interpolation between two numbers. lerp :: Data Double -> Data Double -> Data Double -> Data Double lerp a b t = share a $ \a' -> a + t * (b-a) -- | Smooth interpolation constant. fade :: Data Double -> Data Double fade t = share t $ \t' -> ((t' * t') * t') * (t' * (t' * 6 - 15) + 10) -- | Basic implementation of Perlin noise for one octave: given a point in 2D -- space, calculate the hash of each corner of the integral "box" surrounding -- the point, e.g. if the point is (1.5, 1.5) the box is the described by -- ((1, 1), (2, 2)). -- Then, interpolate between these hashes depending on the point's location -- inside the box. In the above example, the point (1.5, 1.5) is in the very -- middle of the box ((1, 1), (2, 2)). The resulting value is the noise value -- of that point. -- Note that with Perlin noise, integral coordinates always have a zero noise -- value. perlin :: Data Int32 -> Data Double -> Data Double -> Data Double perlin octave x y = share (xs32 octave) $ \octhash -> share (grad octhash x0i y0i (x-x0) (y-y0)) $ \a -> share (grad octhash x1i y0i (x-x1) (y-y0)) $ \b -> share (grad octhash x0i y1i (x-x0) (y-y1)) $ \c -> share (grad octhash x1i y1i (x-x1) (y-y1)) $ \d -> share (fade $ decimalPart x) $ \u -> share (fade $ decimalPart y) $ \v -> lerp (lerp a b u) (lerp c d u) v where x0i = f2n x0 y0i = f2n y0 x1i = f2n x1 y1i = f2n y1 x0 = floor x y0 = floor y x1 = x0 + 1 y1 = y0 + 1 decimalPart :: Data Double -> Data Double decimalPart x = x - floor x -- TODO: only works for positive numbers f2n :: Data Double -> Data Int32 f2n x = share (round x) $ \xi -> x - i2n xi >= 0 ? xi $ xi-1 -- TODO: only works for positive numbers floor :: Data Double -> Data Double floor = i2n . f2n pow :: Data Double -> Word32 -> Data Double pow n 1 = n pow n k = pow (n*n) (k-1) -- | Use one Zeldspar pipeline stage for each noise octave. -- Replace @|>> 5 `ofLength` sz >>|@ with @>>>@ for the sequential version. perlinVec :: Data Word32 -> Data Word32 -> Int32 -> Data Double -> ParZun (Manifest (Data Double)) (Manifest (Data Double)) () perlinVec width height octaves persistence = liftP $ do go 1 1 1 where maxdensity _ 1 _ = 1 maxdensity p o a = maxdensity p (o-1) (a*p) + a*p sz = width*height go octave freq amp | octave Prelude.>= octaves = step (Prelude.fromIntegral octave) freq amp |>> 5 `ofLength` sz >>| finalize | otherwise = step (Prelude.fromIntegral octave) freq amp |>> 5 `ofLength` sz >>| go (octave+1) (freq*2) (amp*persistence) -- Divide all noise values by the maximum possible noise value. finalize = loop $ do let md = maxdensity persistence octaves 1 inp <- take out <- lift $ manifestFresh $ map (/md) inp emit out -- Calculate noise value for one octave. -- TODO: get rid of the manifest vector of coordinates. step octave freq amp = loop $ do inp <- take let xs = replicate height $ (0 ... width) ys = map (replicate width) $ (0 ... height) coords = concat height $ zipWith zip xs ys coords' <- lift $ manifestFresh coords m <- lift $ manifestFresh $ map addOctave (zip coords' inp) emit m where addOctave :: ((Data Index, Data Index), Data Double) -> Data Double addOctave ((x, y), total) = total + amp*perlin octave (i2n x/75*freq) (i2n y/75*freq) -- | Add a source and a sink to the program, producing ten identical images. -- The sink prints the noise values ad some arbitrarily selected coordinates. preparePar :: Data Length -> Data Length -> ParZun (Manifest (Data Double)) (Manifest (Data Double)) () -> Run () preparePar w h p = do r <- initRef 0 runParZ p (src r) (5 `ofLength` sz) snk (5 `ofLength` sz) where sz = w*h src :: Ref (Data Int32) -> Run (Manifest (Data Double), Data Bool) src r = do count <- getRef r setRef r (count+1) m <- manifestFresh $ replicate (h*w) (0 :: Data Double) pure (m, count < 10) snk :: Manifest (Data Double) -> Run (Data Bool) snk v = do printf "%f %f %f %f %f\n" (v ! 801) (v ! 802) (v ! 803) (v ! 804) (v ! 805) pure true -- | Compile the program to a C file. -- The file needs to be compiled with -- @-lm -lpthread -I/path_to_imperative-edsl/include path_to_imperative-edsl/csrc/chan.c@. compileToC :: IO () compileToC = Prelude.writeFile "noise.c" $ compile $ preparePar imgWidth imgHeight $ perlinVec imgWidth imgHeight imgOctaves imgPersistence main = compileToC
kmate/zeldspar
examples/noise.hs
bsd-3-clause
6,270
0
22
1,756
2,122
1,085
1,037
126
2
{-# LANGUAGE CPP, ScopedTypeVariables #-} module Main where import Control.Applicative ((<$>)) import Control.Exception import Data.List (isPrefixOf) import qualified Data.Int as Int import GHC.Int import Ros.Internal.Msg.SrvInfo import Ros.Internal.RosBinary import Ros.Service (callService) import Ros.Service.ServiceTypes import qualified Ros.Test_srvs.AddTwoIntsRequest as Req import qualified Ros.Test_srvs.AddTwoIntsResponse as Res import Ros.Test_srvs.EmptyRequest import Ros.Test_srvs.EmptyResponse import Test.Tasty import Test.Tasty.HUnit -- To run: -- 1. start ros: run "roscore" -- 2. in another terminal start the add_two_ints server: -- python roshask/Tests/ServiceClientTests/add_two_ints_server.py -- 3. in a new terminal make sure $ROS_MASTER_URI is correct and run -- cabal test servicetest --show-details=always type Response a = IO (Either ServiceResponseExcept a) main :: IO () main = defaultMain $ testGroup "Service Tests" [ addIntsTest 4 7 , notOkTest 100 100 , requestResponseDontMatchTest , noProviderTest , connectionHeaderBadMD5Test , emptyServiceTest] addIntsTest :: GHC.Int.Int64 -> GHC.Int.Int64 -> TestTree addIntsTest x y = testCase ("add_two_ints, add " ++ show x ++ " + " ++ show y) $ do res <- callService "/add_two_ints" Req.AddTwoIntsRequest{Req.a=x, Req.b=y} :: Response Res.AddTwoIntsResponse Right (Res.AddTwoIntsResponse (x + y)) @=? res -- add_two_ints_server returns None (triggering the NotOkError) if both a and b are 100 notOkTest :: GHC.Int.Int64 -> GHC.Int.Int64 -> TestTree notOkTest x y = testCase ("NotOKError, add_two_ints, add " ++ show x ++ " + " ++ show y) $ do res <- callService "/add_two_ints" Req.AddTwoIntsRequest{Req.a=x, Req.b=y} :: Response Res.AddTwoIntsResponse Left (NotOkExcept "service cannot process request: service handler returned None") @=? res -- tests that an error is returned if the server is not registered with the master noProviderTest :: TestTree noProviderTest = testCase ("service not registered error") $ do res <- callService "/not_add_two_ints" Req.AddTwoIntsRequest{Req.a=x, Req.b=y} :: Response Res.AddTwoIntsResponse Left (MasterExcept "lookupService failed, code: -1, statusMessage: no provider") @=? res where x = 10 y = 10 -- From the deprecated @testpack@ package by John Goerzen assertRaises :: forall a e. (Show a, Control.Exception.Exception e, Show e, Eq e) => String -> e -> IO a -> IO () assertRaises msg selector action = let thetest :: e -> IO () thetest e = if isPrefixOf (show selector) (show e) then return () else assertFailure $ msg ++ "\nReceived unexpected exception: " ++ show e ++ "\ninstead of exception: " ++ show selector in do r <- Control.Exception.try action case r of Left e -> thetest e Right _ -> assertFailure $ msg ++ "\nReceived no exception, " ++ "but was expecting exception: " ++ show selector requestResponseDontMatchTest :: TestTree requestResponseDontMatchTest = testGroup "check request and response" [testMd5, testName] where testMd5 = testCase ("check md5") $ do assertRaises "Failed to detect mismatch" (ErrorCall "Request and response type do not match") --(callService "/add_two_ints" (Req.AddTwoIntsRequest 1 1) :: IO (Either ServiceResponseExcept BadMD5)) (callService "/add_two_ints" (Req.AddTwoIntsRequest 1 1) :: Response BadMD5) testName = testCase ("check name") $ do assertRaises "Failed to detect mismatch" (ErrorCall "Request and response type do not match") (callService "/add_two_ints" (Req.AddTwoIntsRequest 1 1) :: IO (Either ServiceResponseExcept BadName)) connectionHeaderBadMD5Test :: TestTree connectionHeaderBadMD5Test = testCase "connection header wrong MD5 error" $ do res <- callService "/add_two_ints" $ BadMD5 10 :: Response BadMD5 Left (ConHeadExcept "Connection header from server has error, connection header is: [(\"error\",\"request from [roshask]: md5sums do not match: [6a2e34150c00229791cc89ff309fff22] vs. [6a2e34150c00229791cc89ff309fff21]\")]") @=? res emptyServiceTest :: TestTree emptyServiceTest = testCase "emptyService" $ do res <- callService "/empty_srv" $ EmptyRequest :: Response EmptyResponse Right (EmptyResponse) @=? res data BadMD5 = BadMD5 {a :: Int.Int64} deriving (Show, Eq) instance SrvInfo BadMD5 where srvMD5 _ = "6a2e34150c00229791cc89ff309fff22" srvTypeName _ = "test_srvs/AddTwoInts" instance RosBinary BadMD5 where put obj' = put (a obj') get = BadMD5 <$> get data BadName = BadName Int.Int64 deriving (Show, Eq) instance SrvInfo BadName where srvMD5 _ = "6a2e34150c00229791cc89ff309fff21" srvTypeName _ = "test_srvs/AddTwoIntu" instance RosBinary BadName where put (BadName x) = put x get = BadName <$> get #if MIN_VERSION_base(4,7,0) #else instance Eq ErrorCall where x == y = (show x) == (show y) #endif
acowley/roshask
Tests/ServiceClientTests/ServiceClientTest.hs
bsd-3-clause
5,169
0
15
1,102
1,151
606
545
93
3
{-# LANGUAGE TemplateHaskell #-} module Types.Signed ( Signed (..) ) where import Types.Basic import Data.Autolib.Transport -- something signed: a value together with its signature data Signed a = Signed { contents :: a, signature :: Signature } deriving (Eq, Read, Show) $(derives [makeToTransport] [''Signed])
Erdwolf/autotool-bonn
server/src/Types/Signed.hs
gpl-2.0
325
0
9
57
85
51
34
8
0
{-# LANGUAGE RecordWildCards #-} import Control.Applicative import Control.Exception import Control.Monad import Control.Monad.Trans.Resource (runResourceT) import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy.Char8 as L8 import Data.List import Data.Maybe import Distribution.PackageDescription.Parse import Distribution.Text import Distribution.System import Distribution.Package import Distribution.PackageDescription hiding (options) import Distribution.Verbosity import System.Console.GetOpt import System.Environment import System.Directory import System.IO.Error import System.Process import System.Exit import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Zip as Zip import qualified Codec.Compression.GZip as GZip import Data.Aeson import qualified Data.CaseInsensitive as CI import Data.Conduit import qualified Data.Conduit.Combinators as CC import Data.List.Extra import qualified Data.Text as T import Development.Shake import Development.Shake.FilePath import Network.HTTP.Conduit import Network.HTTP.Types import Network.Mime import Prelude -- Silence AMP warning -- | Entrypoint. main :: IO () main = shakeArgsWith shakeOptions { shakeFiles = releaseDir , shakeVerbosity = Chatty , shakeChange = ChangeModtimeAndDigestInput } options $ \flags args -> do gStackPackageDescription <- packageDescription <$> readPackageDescription silent "stack.cabal" gGithubAuthToken <- lookupEnv githubAuthTokenEnvVar gGitRevCount <- length . lines <$> readProcess "git" ["rev-list", "HEAD"] "" gGitSha <- trim <$> readProcess "git" ["rev-parse", "HEAD"] "" gHomeDir <- getHomeDirectory let gGpgKey = "9BEFB442" gAllowDirty = False gGithubReleaseTag = Nothing Platform arch _ = buildPlatform gArch = arch gBinarySuffix = "" gUploadLabel = Nothing gProjectRoot = "" -- Set to real value velow. global0 = foldl (flip id) Global{..} flags -- Need to get paths after options since the '--arch' argument can effect them. localInstallRoot' <- getStackPath global0 "local-install-root" projectRoot' <- getStackPath global0 "project-root" let global = global0 { gProjectRoot = projectRoot' } return $ Just $ rules global args where getStackPath global path = do out <- readProcess stackProgName (stackArgs global ++ ["path", "--" ++ path]) "" return $ trim $ fromMaybe out $ stripPrefix (path ++ ":") out -- | Additional command-line options. options :: [OptDescr (Either String (Global -> Global))] options = [ Option "" [gpgKeyOptName] (ReqArg (\v -> Right $ \g -> g{gGpgKey = v}) "USER-ID") "GPG user ID to sign distribution package with." , Option "" [allowDirtyOptName] (NoArg $ Right $ \g -> g{gAllowDirty = True}) "Allow a dirty working tree for release." , Option "" [githubAuthTokenOptName] (ReqArg (\v -> Right $ \g -> g{gGithubAuthToken = Just v}) "TOKEN") ("Github personal access token (defaults to " ++ githubAuthTokenEnvVar ++ " environment variable).") , Option "" [githubReleaseTagOptName] (ReqArg (\v -> Right $ \g -> g{gGithubReleaseTag = Just v}) "TAG") "Github release tag to upload to." , Option "" [archOptName] (ReqArg (\v -> case simpleParse v of Nothing -> Left $ "Unknown architecture in --arch option: " ++ v Just arch -> Right $ \g -> g{gArch = arch}) "ARCHITECTURE") "Architecture to build (e.g. 'i386' or 'x86_64')." , Option "" [binaryVariantOptName] (ReqArg (\v -> Right $ \g -> g{gBinarySuffix = v}) "SUFFIX") "Extra suffix to add to binary executable archive filename." , Option "" [uploadLabelOptName] (ReqArg (\v -> Right $ \g -> g{gUploadLabel = Just v}) "LABEL") "Label to give the uploaded release asset" ] -- | Shake rules. rules :: Global -> [String] -> Rules () rules global@Global{..} args = do case args of [] -> error "No wanted target(s) specified." _ -> want args phony releasePhony $ do need [checkPhony] need [uploadPhony] phony cleanPhony $ removeFilesAfter releaseDir ["//*"] phony checkPhony $ need [releaseCheckDir </> binaryExeFileName] phony uploadPhony $ mapM_ (\f -> need [releaseDir </> f <.> uploadExt]) binaryPkgFileNames phony buildPhony $ mapM_ (\f -> need [releaseDir </> f]) binaryPkgFileNames distroPhonies ubuntuDistro ubuntuVersions debPackageFileName distroPhonies debianDistro debianVersions debPackageFileName distroPhonies centosDistro centosVersions rpmPackageFileName distroPhonies fedoraDistro fedoraVersions rpmPackageFileName phony archUploadPhony $ need [archDir </> archPackageFileName <.> uploadExt] phony archBuildPhony $ need [archDir </> archPackageFileName] releaseDir </> "*" <.> uploadExt %> \out -> do let srcFile = dropExtension out mUploadLabel = if takeExtension srcFile == ascExt then fmap (++ " (GPG signature)") gUploadLabel else gUploadLabel uploadToGithubRelease global srcFile mUploadLabel copyFileChanged srcFile out releaseCheckDir </> binaryExeFileName %> \out -> do need [releaseBinDir </> binaryName </> stackExeFileName] Stdout dirty <- cmd "git status --porcelain" when (not gAllowDirty && not (null (trim dirty))) $ error ("Working tree is dirty. Use --" ++ allowDirtyOptName ++ " option to continue anyway.") withTempDir $ \tmpDir -> do let cmd0 = cmd (releaseBinDir </> binaryName </> stackExeFileName) (stackArgs global) ["--local-bin-path=" ++ tmpDir] () <- cmd0 "install --pedantic --haddock --no-haddock-deps" () <- cmd0 "install cabal-install" let cmd' = cmd (AddPath [tmpDir] []) stackProgName (stackArgs global) () <- cmd' "clean" () <- cmd' "build --pedantic" () <- cmd' "test --pedantic --flag stack:integration-tests" return () copyFileChanged (releaseBinDir </> binaryName </> stackExeFileName) out releaseDir </> binaryPkgZipFileName %> \out -> do stageFiles <- getBinaryPkgStageFiles putNormal $ "zip " ++ out liftIO $ do entries <- forM stageFiles $ \stageFile -> do Zip.readEntry [Zip.OptLocation (dropDirectoryPrefix (releaseStageDir </> binaryName) stageFile) False] stageFile let archive = foldr Zip.addEntryToArchive Zip.emptyArchive entries L8.writeFile out (Zip.fromArchive archive) releaseDir </> binaryPkgTarGzFileName %> \out -> do stageFiles <- getBinaryPkgStageFiles writeTarGz out releaseStageDir stageFiles releaseStageDir </> binaryName </> stackExeFileName %> \out -> do copyFileChanged (releaseDir </> binaryExeFileName) out releaseStageDir </> (binaryName ++ "//*") %> \out -> do copyFileChanged (dropDirectoryPrefix (releaseStageDir </> binaryName) out) out releaseDir </> binaryExeFileName %> \out -> do need [releaseBinDir </> binaryName </> stackExeFileName] (Stdout versionOut) <- cmd (releaseBinDir </> binaryName </> stackExeFileName) "--version" when (not gAllowDirty && "dirty" `isInfixOf` lower versionOut) $ error ("Refusing continue because 'stack --version' reports dirty. Use --" ++ allowDirtyOptName ++ " option to continue anyway.") case platformOS of Windows -> do -- Windows doesn't have or need a 'strip' command, so skip it. -- Instead, we sign the executable liftIO $ copyFile (releaseBinDir </> binaryName </> stackExeFileName) out actionOnException (command_ [] "c:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Bin\\signtool.exe" ["sign" ,"/v" ,"/d", synopsis gStackPackageDescription ,"/du", homepage gStackPackageDescription ,"/n", "FP Complete, Corporation" ,"/t", "http://timestamp.verisign.com/scripts/timestamp.dll" ,out]) (removeFile out) Linux -> cmd "strip -p --strip-unneeded --remove-section=.comment -o" [out, releaseBinDir </> binaryName </> stackExeFileName] _ -> cmd "strip -o" [out, releaseBinDir </> binaryName </> stackExeFileName] releaseDir </> binaryPkgSignatureFileName %> \out -> do need [out -<.> ""] _ <- liftIO $ tryJust (guard . isDoesNotExistError) (removeFile out) cmd "gpg --detach-sig --armor" [ "-u", gGpgKey , dropExtension out ] releaseBinDir </> binaryName </> stackExeFileName %> \out -> do alwaysRerun actionOnException (cmd stackProgName (stackArgs global) ["--local-bin-path=" ++ takeDirectory out] "install --pedantic") (removeFile out) debDistroRules ubuntuDistro ubuntuVersions debDistroRules debianDistro debianVersions rpmDistroRules centosDistro centosVersions rpmDistroRules fedoraDistro fedoraVersions archDir </> archPackageFileName <.> uploadExt %> \out -> do let pkgFile = dropExtension out need [pkgFile] () <- cmd "aws s3 cp" [ pkgFile , "s3://download.fpcomplete.com/archlinux/" ++ takeFileName pkgFile ] copyFileChanged pkgFile out archDir </> archPackageFileName %> \out -> do docFiles <- getDocFiles let inputFiles = concat [[archStagedExeFile ,archStagedBashCompletionFile] ,map (archStagedDocDir </>) docFiles] need inputFiles putNormal $ "tar gzip " ++ out writeTarGz out archStagingDir inputFiles archStagedExeFile %> \out -> do copyFileChanged (releaseDir </> binaryExeFileName) out archStagedBashCompletionFile %> \out -> do writeBashCompletion archStagedExeFile archStagingDir out archStagedDocDir ++ "//*" %> \out -> do let origFile = dropDirectoryPrefix archStagedDocDir out copyFileChanged origFile out where debDistroRules debDistro0 debVersions = do let anyVersion0 = anyDistroVersion debDistro0 distroVersionDir anyVersion0 </> debPackageFileName anyVersion0 <.> uploadExt %> \out -> do let DistroVersion{..} = distroVersionFromPath out debVersions pkgFile = dropExtension out need [pkgFile] () <- cmd "deb-s3 upload -b download.fpcomplete.com --preserve-versions" [ "--sign=" ++ gGpgKey , "--prefix=" ++ dvDistro ++ "/" ++ dvCodeName , pkgFile ] copyFileChanged pkgFile out distroVersionDir anyVersion0 </> debPackageFileName anyVersion0 %> \out -> do docFiles <- getDocFiles let dv@DistroVersion{..} = distroVersionFromPath out debVersions inputFiles = concat [[debStagedExeFile dv ,debStagedBashCompletionFile dv] ,map (debStagedDocDir dv </>) docFiles] need inputFiles cmd "fpm -f -s dir -t deb" "--deb-recommends git --deb-recommends gnupg" "-d g++ -d gcc -d libc6-dev -d libffi-dev -d libgmp-dev -d make -d xz-utils -d zlib1g-dev" ["-n", stackProgName ,"-C", debStagingDir dv ,"-v", debPackageVersionStr dv ,"-p", out ,"-m", maintainer gStackPackageDescription ,"--description", synopsis gStackPackageDescription ,"--license", display (license gStackPackageDescription) ,"--url", homepage gStackPackageDescription] (map (dropDirectoryPrefix (debStagingDir dv)) inputFiles) debStagedExeFile anyVersion0 %> \out -> do copyFileChanged (releaseDir </> binaryExeFileName) out debStagedBashCompletionFile anyVersion0 %> \out -> do let dv = distroVersionFromPath out debVersions writeBashCompletion (debStagedExeFile dv) (debStagingDir dv) out debStagedDocDir anyVersion0 ++ "//*" %> \out -> do let dv@DistroVersion{..} = distroVersionFromPath out debVersions origFile = dropDirectoryPrefix (debStagedDocDir dv) out copyFileChanged origFile out rpmDistroRules rpmDistro0 rpmVersions = do let anyVersion0 = anyDistroVersion rpmDistro0 distroVersionDir anyVersion0 </> rpmPackageFileName anyVersion0 <.> uploadExt %> \out -> do let DistroVersion{..} = distroVersionFromPath out rpmVersions pkgFile = dropExtension out need [pkgFile] let rpmmacrosFile = gHomeDir </> ".rpmmacros" rpmmacrosExists <- liftIO $ System.Directory.doesFileExist rpmmacrosFile when rpmmacrosExists $ error ("'" ++ rpmmacrosFile ++ "' already exists. Move it out of the way first.") actionFinally (do writeFileLines rpmmacrosFile [ "%_signature gpg" , "%_gpg_name " ++ gGpgKey ] () <- cmd "rpm-s3 --verbose --sign --bucket=download.fpcomplete.com" [ "--repopath=" ++ dvDistro ++ "/" ++ dvVersion , pkgFile ] return ()) (liftIO $ removeFile rpmmacrosFile) copyFileChanged pkgFile out distroVersionDir anyVersion0 </> rpmPackageFileName anyVersion0 %> \out -> do docFiles <- getDocFiles let dv@DistroVersion{..} = distroVersionFromPath out rpmVersions inputFiles = concat [[rpmStagedExeFile dv ,rpmStagedBashCompletionFile dv] ,map (rpmStagedDocDir dv </>) docFiles] need inputFiles cmd "fpm -s dir -t rpm" "-d perl -d make -d automake -d gcc -d gmp-devel -d libffi -d zlib -d xz -d tar" ["-n", stackProgName ,"-C", rpmStagingDir dv ,"-v", rpmPackageVersionStr dv ,"--iteration", rpmPackageIterationStr dv ,"-p", out ,"-m", maintainer gStackPackageDescription ,"--description", synopsis gStackPackageDescription ,"--license", display (license gStackPackageDescription) ,"--url", homepage gStackPackageDescription] (map (dropDirectoryPrefix (rpmStagingDir dv)) inputFiles) rpmStagedExeFile anyVersion0 %> \out -> do copyFileChanged (releaseDir </> binaryExeFileName) out rpmStagedBashCompletionFile anyVersion0 %> \out -> do let dv = distroVersionFromPath out rpmVersions writeBashCompletion (rpmStagedExeFile dv) (rpmStagingDir dv) out rpmStagedDocDir anyVersion0 ++ "//*" %> \out -> do let dv@DistroVersion{..} = distroVersionFromPath out rpmVersions origFile = dropDirectoryPrefix (rpmStagedDocDir dv) out copyFileChanged origFile out writeBashCompletion stagedStackExeFile stageDir out = do need [stagedStackExeFile] (Stdout bashCompletionScript) <- cmd [stagedStackExeFile] "--bash-completion-script" ["/" ++ dropDirectoryPrefix stageDir stagedStackExeFile] writeFileChanged out bashCompletionScript getBinaryPkgStageFiles = do docFiles <- getDocFiles let stageFiles = concat [[releaseStageDir </> binaryName </> stackExeFileName] ,map ((releaseStageDir </> binaryName) </>) docFiles] need stageFiles return stageFiles getDocFiles = getDirectoryFiles "." ["LICENSE", "*.md", "doc//*"] distroVersionFromPath path versions = let path' = dropDirectoryPrefix releaseDir path version = takeDirectory1 (dropDirectory1 path') in DistroVersion (takeDirectory1 path') version (lookupVersionCodeName version versions) distroPhonies distro0 versions0 makePackageFileName = forM_ versions0 $ \(version0,_) -> do let dv@DistroVersion{..} = DistroVersion distro0 version0 (lookupVersionCodeName version0 versions0) phony (distroUploadPhony dv) $ need [distroVersionDir dv </> makePackageFileName dv <.> uploadExt] phony (distroBuildPhony dv) $ need [distroVersionDir dv </> makePackageFileName dv] lookupVersionCodeName version versions = fromMaybe (error $ "lookupVersionCodeName: could not find " ++ show version ++ " in " ++ show versions) $ lookup version versions releasePhony = "release" checkPhony = "check" uploadPhony = "upload" cleanPhony = "clean" buildPhony = "build" distroUploadPhony DistroVersion{..} = "upload-" ++ dvDistro ++ "-" ++ dvVersion distroBuildPhony DistroVersion{..} = "build-" ++ dvDistro ++ "-" ++ dvVersion archUploadPhony = "upload-" ++ archDistro archBuildPhony = "build-" ++ archDistro releaseCheckDir = releaseDir </> "check" releaseStageDir = releaseDir </> "stage" releaseBinDir = releaseDir </> "bin" distroVersionDir DistroVersion{..} = releaseDir </> dvDistro </> dvVersion binaryPkgFileNames = [binaryPkgFileName, binaryPkgSignatureFileName] binaryPkgSignatureFileName = binaryPkgFileName <.> ascExt binaryPkgFileName = case platformOS of Windows -> binaryPkgZipFileName _ -> binaryPkgTarGzFileName binaryPkgZipFileName = binaryName <.> zipExt binaryPkgTarGzFileName = binaryName <.> tarGzExt binaryExeFileName = binaryName <.> exe binaryName = concat [ stackProgName , "-" , stackVersionStr global , "-" , display platformOS , "-" , display gArch , if null gBinarySuffix then "" else "-" ++ gBinarySuffix ] stackExeFileName = stackProgName <.> exe debStagedDocDir dv = debStagingDir dv </> "usr/share/doc" </> stackProgName debStagedBashCompletionFile dv = debStagingDir dv </> "etc/bash_completion.d/stack" debStagedExeFile dv = debStagingDir dv </> "usr/bin/stack" debStagingDir dv = distroVersionDir dv </> debPackageName dv debPackageFileName dv = debPackageName dv <.> debExt debPackageName dv = stackProgName ++ "_" ++ debPackageVersionStr dv ++ "_amd64" debPackageVersionStr DistroVersion{..} = stackVersionStr global ++ "-0~" ++ dvCodeName rpmStagedDocDir dv = rpmStagingDir dv </> "usr/share/doc" </> (stackProgName ++ "-" ++ rpmPackageVersionStr dv) rpmStagedBashCompletionFile dv = rpmStagingDir dv </> "etc/bash_completion.d/stack" rpmStagedExeFile dv = rpmStagingDir dv </> "usr/bin/stack" rpmStagingDir dv = distroVersionDir dv </> rpmPackageName dv rpmPackageFileName dv = rpmPackageName dv <.> rpmExt rpmPackageName dv = stackProgName ++ "-" ++ rpmPackageVersionStr dv ++ "-" ++ rpmPackageIterationStr dv ++ ".x86_64" rpmPackageIterationStr DistroVersion{..} = "0." ++ dvCodeName rpmPackageVersionStr _ = stackVersionStr global archStagedDocDir = archStagingDir </> "usr/share/doc" </> stackProgName archStagedBashCompletionFile = archStagingDir </> "usr/share/bash-completion/completions/stack" archStagedExeFile = archStagingDir </> "usr/bin/stack" archStagingDir = archDir </> archPackageName archPackageFileName = archPackageName <.> tarGzExt archPackageName = stackProgName ++ "_" ++ stackVersionStr global ++ "-" ++ "x86_64" archDir = releaseDir </> archDistro ubuntuVersions = [ ("12.04", "precise") , ("14.04", "trusty") , ("14.10", "utopic") , ("15.04", "vivid") , ("15.10", "wily") ] debianVersions = [ ("7", "wheezy") , ("8", "jessie") ] centosVersions = [ ("7", "el7") , ("6", "el6") ] fedoraVersions = [ ("21", "fc21") , ("22", "fc22") ] ubuntuDistro = "ubuntu" debianDistro = "debian" centosDistro = "centos" fedoraDistro = "fedora" archDistro = "arch" anyDistroVersion distro = DistroVersion distro "*" "*" zipExt = ".zip" tarGzExt = tarExt <.> gzExt gzExt = ".gz" tarExt = ".tar" ascExt = ".asc" uploadExt = ".upload" debExt = ".deb" rpmExt = ".rpm" -- | Upload file to Github release. uploadToGithubRelease :: Global -> FilePath -> Maybe String -> Action () uploadToGithubRelease global@Global{..} file mUploadLabel = do need [file] putNormal $ "Uploading to Github: " ++ file GithubRelease{..} <- getGithubRelease resp <- liftIO $ callGithubApi global [(CI.mk $ S8.pack "Content-Type", defaultMimeLookup (T.pack file))] (Just file) (replace "{?name,label}" ("?name=" ++ urlEncodeStr (takeFileName file) ++ (case mUploadLabel of Nothing -> "" Just uploadLabel -> "&label=" ++ urlEncodeStr uploadLabel)) relUploadUrl) case eitherDecode resp of Left e -> error ("Could not parse Github asset upload response (" ++ e ++ "):\n" ++ L8.unpack resp ++ "\n") Right (GithubReleaseAsset{..}) -> when (assetState /= "uploaded") $ error ("Invalid asset state after Github asset upload: " ++ assetState) where urlEncodeStr = S8.unpack . urlEncode True . S8.pack getGithubRelease = do releases <- getGithubReleases let tag = fromMaybe ("v" ++ stackVersionStr global) gGithubReleaseTag return $ fromMaybe (error ("Could not find Github release with tag '" ++ tag ++ "'.\n" ++ "Use --" ++ githubReleaseTagOptName ++ " option to specify a different tag.")) (find (\r -> relTagName r == tag) releases) getGithubReleases :: Action [GithubRelease] getGithubReleases = do resp <- liftIO $ callGithubApi global [] Nothing "https://api.github.com/repos/commercialhaskell/stack/releases" case eitherDecode resp of Left e -> error ("Could not parse Github releases (" ++ e ++ "):\n" ++ L8.unpack resp ++ "\n") Right r -> return r -- | Make a request to the Github API and return the response. callGithubApi :: Global -> RequestHeaders -> Maybe FilePath -> String -> IO L8.ByteString callGithubApi Global{..} headers mpostFile url = do req0 <- parseUrl url let authToken = fromMaybe (error $ "Github auth token required.\n" ++ "Use " ++ githubAuthTokenEnvVar ++ " environment variable\n" ++ "or --" ++ githubAuthTokenOptName ++ " option to specify.") gGithubAuthToken req1 = req0 { checkStatus = \_ _ _ -> Nothing , requestHeaders = [ (CI.mk $ S8.pack "Authorization", S8.pack $ "token " ++ authToken) , (CI.mk $ S8.pack "User-Agent", S8.pack "commercialhaskell/stack") ] ++ headers } req <- case mpostFile of Nothing -> return req1 Just postFile -> do lbs <- L8.readFile postFile return $ req1 { method = S8.pack "POST" , requestBody = RequestBodyLBS lbs } manager <- newManager tlsManagerSettings runResourceT $ do res <- http req manager responseBody res $$+- CC.sinkLazy -- | Create a .tar.gz files from files. The paths should be absolute, and will -- be made relative to the base directory in the tarball. writeTarGz :: FilePath -> FilePath -> [FilePath] -> Action () writeTarGz out baseDir inputFiles = liftIO $ do content <- Tar.pack baseDir $ map (dropDirectoryPrefix baseDir) inputFiles L8.writeFile out $ GZip.compress $ Tar.write content -- | Drops a directory prefix from a path. The prefix automatically has a path -- separator character appended. Fails if the path does not begin with the prefix. dropDirectoryPrefix :: FilePath -> FilePath -> FilePath dropDirectoryPrefix prefix path = case stripPrefix (toStandard prefix ++ "/") (toStandard path) of Nothing -> error ("dropDirectoryPrefix: cannot drop " ++ show prefix ++ " from " ++ show path) Just stripped -> stripped -- | String representation of stack package version. stackVersionStr :: Global -> String stackVersionStr = display . pkgVersion . package . gStackPackageDescription -- | Current operating system. platformOS :: OS platformOS = let Platform _ os = buildPlatform in os -- | Directory in which to store build and intermediate files. releaseDir :: FilePath releaseDir = "_release" -- | @GITHUB_AUTH_TOKEN@ environment variale name. githubAuthTokenEnvVar :: String githubAuthTokenEnvVar = "GITHUB_AUTH_TOKEN" -- | @--github-auth-token@ command-line option name. githubAuthTokenOptName :: String githubAuthTokenOptName = "github-auth-token" -- | @--github-release-tag@ command-line option name. githubReleaseTagOptName :: String githubReleaseTagOptName = "github-release-tag" -- | @--gpg-key@ command-line option name. gpgKeyOptName :: String gpgKeyOptName = "gpg-key" -- | @--allow-dirty@ command-line option name. allowDirtyOptName :: String allowDirtyOptName = "allow-dirty" -- | @--arch@ command-line option name. archOptName :: String archOptName = "arch" -- | @--binary-variant@ command-line option name. binaryVariantOptName :: String binaryVariantOptName = "binary-variant" -- | @--upload-label@ command-line option name. uploadLabelOptName :: String uploadLabelOptName = "upload-label" -- | Arguments to pass to all 'stack' invocations. stackArgs :: Global -> [String] stackArgs Global{..} = ["--install-ghc", "--arch=" ++ display gArch] -- | Name of the 'stack' program. stackProgName :: FilePath stackProgName = "stack" -- | Linux distribution/version combination. data DistroVersion = DistroVersion { dvDistro :: !String , dvVersion :: !String , dvCodeName :: !String } -- | A Github release, as returned by the Github API. data GithubRelease = GithubRelease { relUploadUrl :: !String , relTagName :: !String } deriving (Show) instance FromJSON GithubRelease where parseJSON = withObject "GithubRelease" $ \o -> GithubRelease <$> o .: T.pack "upload_url" <*> o .: T.pack "tag_name" -- | A Github release asset, as returned by the Github API. data GithubReleaseAsset = GithubReleaseAsset { assetState :: !String } deriving (Show) instance FromJSON GithubReleaseAsset where parseJSON = withObject "GithubReleaseAsset" $ \o -> GithubReleaseAsset <$> o .: T.pack "state" -- | Global values and options. data Global = Global { gStackPackageDescription :: !PackageDescription , gGpgKey :: !String , gAllowDirty :: !Bool , gGithubAuthToken :: !(Maybe String) , gGithubReleaseTag :: !(Maybe String) , gGitRevCount :: !Int , gGitSha :: !String , gProjectRoot :: !FilePath , gHomeDir :: !FilePath , gArch :: !Arch , gBinarySuffix :: !String , gUploadLabel ::(Maybe String)} deriving (Show)
mathhun/stack
etc/scripts/release.hs
bsd-3-clause
28,060
0
25
7,781
6,342
3,214
3,128
595
7
module B (idd) where idd :: Int idd = 100000242418429
sdiehl/ghc
testsuite/tests/ghci/caf_crash/B.hs
bsd-3-clause
56
0
4
12
19
12
7
3
1
{-@ LIQUID "--notermination" @-} {-# OPTIONS_GHC -cpp -fglasgow-exts #-} -- #prune -- | -- Module : Data.ByteString.Char8 -- Copyright : (c) Don Stewart 2006 -- License : BSD-style -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Manipulate 'ByteString's using 'Char' operations. All Chars will be -- truncated to 8 bits. It can be expected that these functions will run -- at identical speeds to their 'Word8' equivalents in "Data.ByteString". -- -- More specifically these byte strings are taken to be in the -- subset of Unicode covered by code points 0-255. This covers -- Unicode Basic Latin, Latin-1 Supplement and C0+C1 Controls. -- -- See: -- -- * <http://www.unicode.org/charts/> -- -- * <http://www.unicode.org/charts/PDF/U0000.pdf> -- -- * <http://www.unicode.org/charts/PDF/U0080.pdf> -- -- This module is intended to be imported @qualified@, to avoid name -- clashes with "Prelude" functions. eg. -- -- > import qualified Data.ByteString.Char8 as B -- module Data.ByteString.Char8 ( -- * The @ByteString@ type ByteString, -- abstract, instances: Eq, Ord, Show, Read, Data, Typeable, Monoid -- * Introducing and eliminating 'ByteString's empty, -- :: ByteString singleton, -- :: Char -> ByteString pack, -- :: String -> ByteString unpack, -- :: ByteString -> String -- * Basic interface cons, -- :: Char -> ByteString -> ByteString snoc, -- :: ByteString -> Char -> ByteString append, -- :: ByteString -> ByteString -> ByteString head, -- :: ByteString -> Char uncons, -- :: ByteString -> Maybe (Char, ByteString) last, -- :: ByteString -> Char tail, -- :: ByteString -> ByteString init, -- :: ByteString -> ByteString null, -- :: ByteString -> Bool length, -- :: ByteString -> Int -- * Transformating ByteStrings map, -- :: (Char -> Char) -> ByteString -> ByteString reverse, -- :: ByteString -> ByteString intersperse, -- :: Char -> ByteString -> ByteString intercalate, -- :: ByteString -> [ByteString] -> ByteString transpose, -- :: [ByteString] -> [ByteString] -- * Reducing 'ByteString's (folds) foldl, -- :: (a -> Char -> a) -> a -> ByteString -> a foldl', -- :: (a -> Char -> a) -> a -> ByteString -> a foldl1, -- :: (Char -> Char -> Char) -> ByteString -> Char foldl1', -- :: (Char -> Char -> Char) -> ByteString -> Char foldr, -- :: (Char -> a -> a) -> a -> ByteString -> a foldr', -- :: (Char -> a -> a) -> a -> ByteString -> a foldr1, -- :: (Char -> Char -> Char) -> ByteString -> Char foldr1', -- :: (Char -> Char -> Char) -> ByteString -> Char -- ** Special folds concat, -- :: [ByteString] -> ByteString concatMap, -- :: (Char -> ByteString) -> ByteString -> ByteString any, -- :: (Char -> Bool) -> ByteString -> Bool all, -- :: (Char -> Bool) -> ByteString -> Bool maximum, -- :: ByteString -> Char minimum, -- :: ByteString -> Char -- * Building ByteStrings -- ** Scans scanl, -- :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString scanl1, -- :: (Char -> Char -> Char) -> ByteString -> ByteString scanr, -- :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString scanr1, -- :: (Char -> Char -> Char) -> ByteString -> ByteString -- ** Accumulating maps mapAccumL, -- :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString) mapAccumR, -- :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString) mapIndexed, -- :: (Int -> Char -> Char) -> ByteString -> ByteString -- ** Generating and unfolding ByteStrings replicate, -- :: Int -> Char -> ByteString unfoldr, -- :: (a -> Maybe (Char, a)) -> a -> ByteString unfoldrN, -- :: Int -> (a -> Maybe (Char, a)) -> a -> (ByteString, Maybe a) -- * Substrings -- ** Breaking strings take, -- :: Int -> ByteString -> ByteString drop, -- :: Int -> ByteString -> ByteString splitAt, -- :: Int -> ByteString -> (ByteString, ByteString) takeWhile, -- :: (Char -> Bool) -> ByteString -> ByteString dropWhile, -- :: (Char -> Bool) -> ByteString -> ByteString span, -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) spanEnd, -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) break, -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) breakEnd, -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) group, -- :: ByteString -> [ByteString] groupBy, -- :: (Char -> Char -> Bool) -> ByteString -> [ByteString] inits, -- :: ByteString -> [ByteString] tails, -- :: ByteString -> [ByteString] -- ** Breaking into many substrings split, -- :: Char -> ByteString -> [ByteString] splitWith, -- :: (Char -> Bool) -> ByteString -> [ByteString] -- ** Breaking into lines and words lines, -- :: ByteString -> [ByteString] words, -- :: ByteString -> [ByteString] unlines, -- :: [ByteString] -> ByteString unwords, -- :: ByteString -> [ByteString] -- * Predicates isPrefixOf, -- :: ByteString -> ByteString -> Bool isSuffixOf, -- :: ByteString -> ByteString -> Bool isInfixOf, -- :: ByteString -> ByteString -> Bool isSubstringOf, -- :: ByteString -> ByteString -> Bool -- ** Search for arbitrary substrings findSubstring, -- :: ByteString -> ByteString -> Maybe Int findSubstrings, -- :: ByteString -> ByteString -> [Int] -- * Searching ByteStrings -- ** Searching by equality elem, -- :: Char -> ByteString -> Bool notElem, -- :: Char -> ByteString -> Bool -- ** Searching with a predicate find, -- :: (Char -> Bool) -> ByteString -> Maybe Char filter, -- :: (Char -> Bool) -> ByteString -> ByteString -- partition -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) -- * Indexing ByteStrings index, -- :: ByteString -> Int -> Char elemIndex, -- :: Char -> ByteString -> Maybe Int elemIndices, -- :: Char -> ByteString -> [Int] elemIndexEnd, -- :: Char -> ByteString -> Maybe Int findIndex, -- :: (Char -> Bool) -> ByteString -> Maybe Int findIndices, -- :: (Char -> Bool) -> ByteString -> [Int] count, -- :: Char -> ByteString -> Int -- * Zipping and unzipping ByteStrings zip, -- :: ByteString -> ByteString -> [(Char,Char)] zipWith, -- :: (Char -> Char -> c) -> ByteString -> ByteString -> [c] unzip, -- :: [(Char,Char)] -> (ByteString,ByteString) -- * Ordered ByteStrings --LIQUID sort, -- :: ByteString -> ByteString -- * Reading from ByteStrings readInt, -- :: ByteString -> Maybe (Int, ByteString) readInteger, -- :: ByteString -> Maybe (Integer, ByteString) -- * Low level CString conversions -- ** Copying ByteStrings copy, -- :: ByteString -> ByteString -- ** Packing CStrings and pointers packCString, -- :: CString -> IO ByteString packCStringLen, -- :: CStringLen -> IO ByteString -- ** Using ByteStrings as CStrings useAsCString, -- :: ByteString -> (CString -> IO a) -> IO a useAsCStringLen, -- :: ByteString -> (CStringLen -> IO a) -> IO a -- * I\/O with 'ByteString's -- ** Standard input and output getLine, -- :: IO ByteString getContents, -- :: IO ByteString putStr, -- :: ByteString -> IO () putStrLn, -- :: ByteString -> IO () interact, -- :: (ByteString -> ByteString) -> IO () -- ** Files readFile, -- :: FilePath -> IO ByteString writeFile, -- :: FilePath -> ByteString -> IO () appendFile, -- :: FilePath -> ByteString -> IO () -- mmapFile, -- :: FilePath -> IO ByteString -- ** I\/O with Handles hGetLine, -- :: Handle -> IO ByteString hGetContents, -- :: Handle -> IO ByteString hGet, -- :: Handle -> Int -> IO ByteString hGetNonBlocking, -- :: Handle -> Int -> IO ByteString hPut, -- :: Handle -> ByteString -> IO () hPutStr, -- :: Handle -> ByteString -> IO () hPutStrLn, -- :: Handle -> ByteString -> IO () -- undocumented deprecated things: join -- :: ByteString -> [ByteString] -> ByteString ) where import qualified Prelude as P import Prelude hiding (reverse,head,tail,last,init,null ,length,map,lines,foldl,foldr,unlines ,concat,any,take,drop,splitAt,takeWhile ,dropWhile,span,break,elem,filter,unwords ,words,maximum,minimum,all,concatMap ,scanl,scanl1,scanr,scanr1 ,appendFile,readFile,writeFile ,foldl1,foldr1,replicate ,getContents,getLine,putStr,putStrLn,interact ,zip,zipWith,unzip,notElem) import qualified Data.ByteString as B import qualified Data.ByteString.Internal as B import qualified Data.ByteString.Unsafe as B -- Listy functions transparently exported import Data.ByteString (empty,null,length,tail,init,append ,inits,tails,reverse,transpose ,concat,take,drop,splitAt,intercalate ,{-LIQUID sort,-}isPrefixOf,isSuffixOf,isInfixOf,isSubstringOf ,findSubstring,findSubstrings,copy,group ,getLine, getContents, putStr, putStrLn, interact ,hGetContents, hGet, hPut, hPutStr, hPutStrLn ,hGetLine, hGetNonBlocking ,packCString,packCStringLen ,useAsCString,useAsCStringLen ) import Data.ByteString.Internal (ByteString(PS), c2w, w2c, isSpaceWord8 ,inlinePerformIO) #if defined(__GLASGOW_HASKELL__) import Data.ByteString.Unsafe (unsafePackAddress) -- for the rule #endif import Data.Char ( isSpace ) import qualified Data.List as List (intersperse) import System.IO (openFile,hClose,hFileSize,IOMode(..)) #ifndef __NHC__ import Control.Exception (bracket) #else import IO (bracket) #endif import Foreign #if defined(__GLASGOW_HASKELL__) import GHC.Base (Char(..),unpackCString#,ord#,int2Word#) import GHC.Prim (Addr#,writeWord8OffAddr#,plusAddr#) import GHC.Ptr (Ptr(..)) import GHC.ST (ST(..)) #endif #define STRICT1(f) f a | a `seq` False = undefined #define STRICT2(f) f a b | a `seq` b `seq` False = undefined #define STRICT3(f) f a b c | a `seq` b `seq` c `seq` False = undefined #define STRICT4(f) f a b c d | a `seq` b `seq` c `seq` d `seq` False = undefined #if __GLASGOW_HASKELL__ >= 611 import Data.IORef import GHC.IO.Handle.Internals import GHC.IO.Handle.Types import GHC.IO.Buffer import GHC.IO.BufferedIO as Buffered import GHC.IO (stToIO, unsafePerformIO) import Data.Char (ord) import Foreign.Marshal.Utils (copyBytes) #else import System.IO.Error (isEOFError) import GHC.IOBase import GHC.Handle #endif --LIQUID import Data.ByteString.Fusion (PairS(..), MaybeS(..)) import System.IO (Handle) import Foreign.ForeignPtr import Foreign.Ptr import Language.Haskell.Liquid.Prelude ------------------------------------------------------------------------ -- | /O(1)/ Convert a 'Char' into a 'ByteString' singleton :: Char -> ByteString singleton = B.singleton . c2w {-# INLINE singleton #-} -- | /O(n)/ Convert a 'String' into a 'ByteString' -- -- For applications with large numbers of string literals, pack can be a -- bottleneck. pack :: String -> ByteString #if !defined(__GLASGOW_HASKELL__) pack str = B.unsafeCreate (P.length str) $ \p -> go p str where go _ [] = return () go p (x:xs) = poke p (c2w x) >> go (p `plusPtr` 1) xs #else /* hack away */ pack str = B.unsafeCreate (P.length str) $ \(Ptr p) -> stToIO (pack_go p str) where {-@ Decrease pack_go 2 @-} pack_go :: Addr# -> [Char] -> ST a () pack_go _ [] = return () pack_go p (C# c:cs) = writeByte p (int2Word# (ord# c)) >> pack_go (p `plusAddr#` 1#) cs writeByte p c = ST $ \s# -> case writeWord8OffAddr# p 0# c s# of s2# -> (# s2#, () #) {-# INLINE writeByte #-} {-# INLINE [1] pack #-} {-# RULES "FPS pack/packAddress" forall s . pack (unpackCString# s) = inlinePerformIO (B.unsafePackAddress s) #-} #endif -- | /O(n)/ Converts a 'ByteString' to a 'String'. unpack :: ByteString -> [Char] unpack = P.map w2c . B.unpack {-# INLINE unpack #-} -- | /O(n)/ 'cons' is analogous to (:) for lists, but of different -- complexity, as it requires a memcpy. cons :: Char -> ByteString -> ByteString cons = B.cons . c2w {-# INLINE cons #-} -- | /O(n)/ Append a Char to the end of a 'ByteString'. Similar to -- 'cons', this function performs a memcpy. snoc :: ByteString -> Char -> ByteString snoc p = B.snoc p . c2w {-# INLINE snoc #-} -- | /O(1)/ Extract the head and tail of a ByteString, returning Nothing -- if it is empty. uncons :: ByteString -> Maybe (Char, ByteString) uncons bs = case B.uncons bs of Nothing -> Nothing Just (w, bs') -> Just (w2c w, bs') {-# INLINE uncons #-} -- | /O(1)/ Extract the first element of a ByteString, which must be non-empty. {-@ head :: ByteStringNE -> Char @-} head :: ByteString -> Char head = w2c . B.head {-# INLINE head #-} -- | /O(1)/ Extract the last element of a packed string, which must be non-empty. {-@ last :: ByteStringNE -> Char @-} last :: ByteString -> Char last = w2c . B.last {-# INLINE last #-} -- | /O(n)/ 'map' @f xs@ is the ByteString obtained by applying @f@ to each element of @xs@ map :: (Char -> Char) -> ByteString -> ByteString map f = B.map (c2w . f . w2c) {-# INLINE map #-} -- | /O(n)/ The 'intersperse' function takes a Char and a 'ByteString' -- and \`intersperses\' that Char between the elements of the -- 'ByteString'. It is analogous to the intersperse function on Lists. intersperse :: Char -> ByteString -> ByteString intersperse = B.intersperse . c2w {-# INLINE intersperse #-} join :: ByteString -> [ByteString] -> ByteString join = intercalate {-# DEPRECATED join "use intercalate" #-} -- | 'foldl', applied to a binary operator, a starting value (typically -- the left-identity of the operator), and a ByteString, reduces the -- ByteString using the binary operator, from left to right. foldl :: (a -> Char -> a) -> a -> ByteString -> a foldl f = B.foldl (\a c -> f a (w2c c)) {-# INLINE foldl #-} -- | 'foldl\'' is like foldl, but strict in the accumulator. foldl' :: (a -> Char -> a) -> a -> ByteString -> a foldl' f = B.foldl' (\a c -> f a (w2c c)) {-# INLINE foldl' #-} -- | 'foldr', applied to a binary operator, a starting value -- (typically the right-identity of the operator), and a packed string, -- reduces the packed string using the binary operator, from right to left. foldr :: (Char -> a -> a) -> a -> ByteString -> a foldr f = B.foldr (\c a -> f (w2c c) a) {-# INLINE foldr #-} -- | 'foldr\'' is a strict variant of foldr foldr' :: (Char -> a -> a) -> a -> ByteString -> a foldr' f = B.foldr' (\c a -> f (w2c c) a) {-# INLINE foldr' #-} -- | 'foldl1' is a variant of 'foldl' that has no starting value -- argument, and thus must be applied to non-empty 'ByteStrings'. {-@ foldl1 :: (Char -> Char -> Char) -> ByteStringNE -> Char @-} foldl1 :: (Char -> Char -> Char) -> ByteString -> Char foldl1 f ps = w2c (B.foldl1 (\x y -> c2w (f (w2c x) (w2c y))) ps) {-# INLINE foldl1 #-} -- | A strict version of 'foldl1' {-@ foldl1' :: (Char -> Char -> Char) -> ByteStringNE -> Char @-} foldl1' :: (Char -> Char -> Char) -> ByteString -> Char foldl1' f ps = w2c (B.foldl1' (\x y -> c2w (f (w2c x) (w2c y))) ps) {-# INLINE foldl1' #-} -- | 'foldr1' is a variant of 'foldr' that has no starting value argument, -- and thus must be applied to non-empty 'ByteString's {-@ foldr1 :: (Char -> Char -> Char) -> ByteStringNE -> Char @-} foldr1 :: (Char -> Char -> Char) -> ByteString -> Char foldr1 f ps = w2c (B.foldr1 (\x y -> c2w (f (w2c x) (w2c y))) ps) {-# INLINE foldr1 #-} -- | A strict variant of foldr1 {-@ foldr1' :: (Char -> Char -> Char) -> ByteStringNE -> Char @-} foldr1' :: (Char -> Char -> Char) -> ByteString -> Char foldr1' f ps = w2c (B.foldr1' (\x y -> c2w (f (w2c x) (w2c y))) ps) {-# INLINE foldr1' #-} -- | Map a function over a 'ByteString' and concatenate the results concatMap :: (Char -> ByteString) -> ByteString -> ByteString concatMap f = B.concatMap (f . w2c) {-# INLINE concatMap #-} -- | Applied to a predicate and a ByteString, 'any' determines if -- any element of the 'ByteString' satisfies the predicate. any :: (Char -> Bool) -> ByteString -> Bool any f = B.any (f . w2c) {-# INLINE any #-} -- | Applied to a predicate and a 'ByteString', 'all' determines if -- all elements of the 'ByteString' satisfy the predicate. all :: (Char -> Bool) -> ByteString -> Bool all f = B.all (f . w2c) {-# INLINE all #-} -- | 'maximum' returns the maximum value from a 'ByteString' {-@ maximum :: ByteStringNE -> Char @-} maximum :: ByteString -> Char maximum = w2c . B.maximum {-# INLINE maximum #-} -- | 'minimum' returns the minimum value from a 'ByteString' {-@ minimum :: ByteStringNE -> Char @-} minimum :: ByteString -> Char minimum = w2c . B.minimum {-# INLINE minimum #-} -- | /O(n)/ map Char functions, provided with the index at each position mapIndexed :: (Int -> Char -> Char) -> ByteString -> ByteString mapIndexed f = B.mapIndexed (\i c -> c2w (f i (w2c c))) {-# INLINE mapIndexed #-} -- | The 'mapAccumL' function behaves like a combination of 'map' and -- 'foldl'; it applies a function to each element of a ByteString, -- passing an accumulating parameter from left to right, and returning a -- final value of this accumulator together with the new list. mapAccumL :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString) mapAccumL f = B.mapAccumL (\acc w -> case f acc (w2c w) of (acc', c) -> (acc', c2w c)) -- | The 'mapAccumR' function behaves like a combination of 'map' and -- 'foldr'; it applies a function to each element of a ByteString, -- passing an accumulating parameter from right to left, and returning a -- final value of this accumulator together with the new ByteString. mapAccumR :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString) mapAccumR f = B.mapAccumR (\acc w -> case f acc (w2c w) of (acc', c) -> (acc', c2w c)) -- | 'scanl' is similar to 'foldl', but returns a list of successive -- reduced values from the left: -- -- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...] -- -- Note that -- -- > last (scanl f z xs) == foldl f z xs. scanl :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString scanl f z = B.scanl (\a b -> c2w (f (w2c a) (w2c b))) (c2w z) -- | 'scanl1' is a variant of 'scanl' that has no starting value argument: -- -- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...] {-@ scanl1 :: (Char -> Char -> Char) -> ByteStringNE -> ByteString @-} scanl1 :: (Char -> Char -> Char) -> ByteString -> ByteString scanl1 f = B.scanl1 (\a b -> c2w (f (w2c a) (w2c b))) -- | scanr is the right-to-left dual of scanl. scanr :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString scanr f z = B.scanr (\a b -> c2w (f (w2c a) (w2c b))) (c2w z) -- | 'scanr1' is a variant of 'scanr' that has no starting value argument. {-@ scanr1 :: (Char -> Char -> Char) -> ByteStringNE -> ByteString @-} scanr1 :: (Char -> Char -> Char) -> ByteString -> ByteString scanr1 f = B.scanr1 (\a b -> c2w (f (w2c a) (w2c b))) -- | /O(n)/ 'replicate' @n x@ is a ByteString of length @n@ with @x@ -- the value of every element. The following holds: -- -- > replicate w c = unfoldr w (\u -> Just (u,u)) c -- -- This implemenation uses @memset(3)@ {-@ replicate :: n:Nat -> Char -> {v:ByteString | (bLength v) = (if n > 0 then n else 0)} @-} replicate :: Int -> Char -> ByteString replicate w = B.replicate w . c2w {-# INLINE replicate #-} -- | /O(n)/, where /n/ is the length of the result. The 'unfoldr' -- function is analogous to the List \'unfoldr\'. 'unfoldr' builds a -- ByteString from a seed value. The function takes the element and -- returns 'Nothing' if it is done producing the ByteString or returns -- 'Just' @(a,b)@, in which case, @a@ is the next character in the string, -- and @b@ is the seed value for further production. -- -- Examples: -- -- > unfoldr (\x -> if x <= '9' then Just (x, succ x) else Nothing) '0' == "0123456789" unfoldr :: (a -> Maybe (Char, a)) -> a -> ByteString unfoldr f x0 = B.unfoldr (fmap k . f) x0 where k (i, j) = (c2w i, j) -- | /O(n)/ Like 'unfoldr', 'unfoldrN' builds a ByteString from a seed -- value. However, the length of the result is limited by the first -- argument to 'unfoldrN'. This function is more efficient than 'unfoldr' -- when the maximum length of the result is known. -- -- The following equation relates 'unfoldrN' and 'unfoldr': -- -- > unfoldrN n f s == take n (unfoldr f s) {-@ unfoldrN :: i:Nat -> (a -> Maybe (Char, a)) -> a -> ({v:ByteString | (bLength v) <= i}, Maybe a) @-} unfoldrN :: Int -> (a -> Maybe (Char, a)) -> a -> (ByteString, Maybe a) unfoldrN n f w = B.unfoldrN n ((k `fmap`) . f) w where k (i,j) = (c2w i, j) {-# INLINE unfoldrN #-} -- | 'takeWhile', applied to a predicate @p@ and a ByteString @xs@, -- returns the longest prefix (possibly empty) of @xs@ of elements that -- satisfy @p@. takeWhile :: (Char -> Bool) -> ByteString -> ByteString takeWhile f = B.takeWhile (f . w2c) {-# INLINE takeWhile #-} -- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@. dropWhile :: (Char -> Bool) -> ByteString -> ByteString dropWhile f = B.dropWhile (f . w2c) #if defined(__GLASGOW_HASKELL__) {-# INLINE [1] dropWhile #-} #endif -- | 'break' @p@ is equivalent to @'span' ('not' . p)@. break :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) break f = B.break (f . w2c) #if defined(__GLASGOW_HASKELL__) {-# INLINE [1] break #-} #endif -- | 'span' @p xs@ breaks the ByteString into two segments. It is -- equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@ span :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) span f = B.span (f . w2c) {-# INLINE span #-} -- | 'spanEnd' behaves like 'span' but from the end of the 'ByteString'. -- We have -- -- > spanEnd (not.isSpace) "x y z" == ("x y ","z") -- -- and -- -- > spanEnd (not . isSpace) ps -- > == -- > let (x,y) = span (not.isSpace) (reverse ps) in (reverse y, reverse x) -- spanEnd :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) spanEnd f = B.spanEnd (f . w2c) {-# INLINE spanEnd #-} -- | 'breakEnd' behaves like 'break' but from the end of the 'ByteString' -- -- breakEnd p == spanEnd (not.p) breakEnd :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) breakEnd f = B.breakEnd (f . w2c) {-# INLINE breakEnd #-} {- -- | 'breakChar' breaks its ByteString argument at the first occurence -- of the specified Char. It is more efficient than 'break' as it is -- implemented with @memchr(3)@. I.e. -- -- > break (=='c') "abcd" == breakChar 'c' "abcd" -- breakChar :: Char -> ByteString -> (ByteString, ByteString) breakChar = B.breakByte . c2w {-# INLINE breakChar #-} -- | 'spanChar' breaks its ByteString argument at the first -- occurence of a Char other than its argument. It is more efficient -- than 'span (==)' -- -- > span (=='c') "abcd" == spanByte 'c' "abcd" -- spanChar :: Char -> ByteString -> (ByteString, ByteString) spanChar = B.spanByte . c2w {-# INLINE spanChar #-} -} -- | /O(n)/ Break a 'ByteString' into pieces separated by the byte -- argument, consuming the delimiter. I.e. -- -- > split '\n' "a\nb\nd\ne" == ["a","b","d","e"] -- > split 'a' "aXaXaXa" == ["","X","X","X",""] -- > split 'x' "x" == ["",""] -- -- and -- -- > intercalate [c] . split c == id -- > split == splitWith . (==) -- -- As for all splitting functions in this library, this function does -- not copy the substrings, it just constructs new 'ByteStrings' that -- are slices of the original. -- {-@ split :: Char -> b:ByteStringNE -> (ByteStringSplit b) @-} split :: Char -> ByteString -> [ByteString] split = B.split . c2w {-# INLINE split #-} -- | /O(n)/ Splits a 'ByteString' into components delimited by -- separators, where the predicate returns True for a separator element. -- The resulting components do not contain the separators. Two adjacent -- separators result in an empty component in the output. eg. -- -- > splitWith (=='a') "aabbaca" == ["","","bb","c",""] -- {-@ splitWith :: (Char -> Bool) -> b:ByteStringNE -> (ByteStringSplit b) @-} splitWith :: (Char -> Bool) -> ByteString -> [ByteString] splitWith f = B.splitWith (f . w2c) {-# INLINE splitWith #-} -- the inline makes a big difference here. {- -- | Like 'splitWith', except that sequences of adjacent separators are -- treated as a single separator. eg. -- -- > tokens (=='a') "aabbaca" == ["bb","c"] -- tokens :: (Char -> Bool) -> ByteString -> [ByteString] tokens f = B.tokens (f . w2c) {-# INLINE tokens #-} -} -- | The 'groupBy' function is the non-overloaded version of 'group'. groupBy :: (Char -> Char -> Bool) -> ByteString -> [ByteString] groupBy k = B.groupBy (\a b -> k (w2c a) (w2c b)) -- | /O(1)/ 'ByteString' index (subscript) operator, starting from 0. {-@ index :: b:ByteString -> {v:Nat | v < (bLength b)} -> Char @-} index :: ByteString -> Int -> Char --LIQUID index = (w2c .) . B.index index b i = w2c $ B.index b i {-# INLINE index #-} -- | /O(n)/ The 'elemIndex' function returns the index of the first -- element in the given 'ByteString' which is equal (by memchr) to the -- query element, or 'Nothing' if there is no such element. {-@ elemIndex :: Char -> b:ByteString -> Maybe {v:Nat | v < (bLength b)} @-} elemIndex :: Char -> ByteString -> Maybe Int elemIndex = B.elemIndex . c2w {-# INLINE elemIndex #-} -- | /O(n)/ The 'elemIndexEnd' function returns the last index of the -- element in the given 'ByteString' which is equal to the query -- element, or 'Nothing' if there is no such element. The following -- holds: -- -- > elemIndexEnd c xs == -- > (-) (length xs - 1) `fmap` elemIndex c (reverse xs) -- elemIndexEnd :: Char -> ByteString -> Maybe Int elemIndexEnd = B.elemIndexEnd . c2w {-# INLINE elemIndexEnd #-} -- | /O(n)/ The 'elemIndices' function extends 'elemIndex', by returning -- the indices of all elements equal to the query element, in ascending order. elemIndices :: Char -> ByteString -> [Int] elemIndices = B.elemIndices . c2w {-# INLINE elemIndices #-} -- | The 'findIndex' function takes a predicate and a 'ByteString' and -- returns the index of the first element in the ByteString satisfying the predicate. findIndex :: (Char -> Bool) -> ByteString -> Maybe Int findIndex f = B.findIndex (f . w2c) {-# INLINE findIndex #-} -- | The 'findIndices' function extends 'findIndex', by returning the -- indices of all elements satisfying the predicate, in ascending order. findIndices :: (Char -> Bool) -> ByteString -> [Int] findIndices f = B.findIndices (f . w2c) -- | count returns the number of times its argument appears in the ByteString -- -- > count = length . elemIndices -- -- Also -- -- > count '\n' == length . lines -- -- But more efficiently than using length on the intermediate list. count :: Char -> ByteString -> Int count c = B.count (c2w c) -- | /O(n)/ 'elem' is the 'ByteString' membership predicate. This -- implementation uses @memchr(3)@. elem :: Char -> ByteString -> Bool elem c = B.elem (c2w c) {-# INLINE elem #-} -- | /O(n)/ 'notElem' is the inverse of 'elem' notElem :: Char -> ByteString -> Bool notElem c = B.notElem (c2w c) {-# INLINE notElem #-} -- | /O(n)/ 'filter', applied to a predicate and a ByteString, -- returns a ByteString containing those characters that satisfy the -- predicate. filter :: (Char -> Bool) -> ByteString -> ByteString filter f = B.filter (f . w2c) {-# INLINE [1] filter #-} -- | /O(n)/ and /O(n\/c) space/ A first order equivalent of /filter . -- (==)/, for the common case of filtering a single Char. It is more -- efficient to use /filterChar/ in this case. -- -- > filterByte == filter . (==) -- -- filterChar is around 10x faster, and uses much less space, than its -- filter equivalent -- filterChar :: Char -> ByteString -> ByteString filterChar c ps = replicate (count c ps) c {-# INLINE filterChar #-} {-# RULES "FPS specialise filter (== x)" forall x. filter ((==) x) = filterChar x #-} {-# RULES "FPS specialise filter (== x)" forall x. filter (== x) = filterChar x #-} -- | /O(n)/ The 'find' function takes a predicate and a ByteString, -- and returns the first element in matching the predicate, or 'Nothing' -- if there is no such element. find :: (Char -> Bool) -> ByteString -> Maybe Char find f ps = w2c `fmap` B.find (f . w2c) ps {-# INLINE find #-} {- -- | /O(n)/ A first order equivalent of /filter . (==)/, for the common -- case of filtering a single Char. It is more efficient to use -- filterChar in this case. -- -- > filterChar == filter . (==) -- -- filterChar is around 10x faster, and uses much less space, than its -- filter equivalent -- filterChar :: Char -> ByteString -> ByteString filterChar c = B.filterByte (c2w c) {-# INLINE filterChar #-} -- | /O(n)/ A first order equivalent of /filter . (\/=)/, for the common -- case of filtering a single Char out of a list. It is more efficient -- to use /filterNotChar/ in this case. -- -- > filterNotChar == filter . (/=) -- -- filterNotChar is around 3x faster, and uses much less space, than its -- filter equivalent -- filterNotChar :: Char -> ByteString -> ByteString filterNotChar c = B.filterNotByte (c2w c) {-# INLINE filterNotChar #-} -} -- | /O(n)/ 'zip' takes two ByteStrings and returns a list of -- corresponding pairs of Chars. If one input ByteString is short, -- excess elements of the longer ByteString are discarded. This is -- equivalent to a pair of 'unpack' operations, and so space -- usage may be large for multi-megabyte ByteStrings {-@ zip :: ByteString -> ByteString -> [(Char,Char)] @-} zip :: ByteString -> ByteString -> [(Char,Char)] zip ps qs | B.null ps || B.null qs = [] | otherwise = (unsafeHead ps, unsafeHead qs) : zip (B.unsafeTail ps) (B.unsafeTail qs) -- | 'zipWith' generalises 'zip' by zipping with the function given as -- the first argument, instead of a tupling function. For example, -- @'zipWith' (+)@ is applied to two ByteStrings to produce the list -- of corresponding sums. zipWith :: (Char -> Char -> a) -> ByteString -> ByteString -> [a] zipWith f = B.zipWith ((. w2c) . f . w2c) -- | 'unzip' transforms a list of pairs of Chars into a pair of -- ByteStrings. Note that this performs two 'pack' operations. unzip :: [(Char,Char)] -> (ByteString,ByteString) unzip ls = (pack (P.map fst ls), pack (P.map snd ls)) {-# INLINE unzip #-} -- | A variety of 'head' for non-empty ByteStrings. 'unsafeHead' omits -- the check for the empty case, which is good for performance, but -- there is an obligation on the programmer to provide a proof that the -- ByteString is non-empty. {-@ unsafeHead :: ByteStringNE -> Char @-} unsafeHead :: ByteString -> Char unsafeHead = w2c . B.unsafeHead {-# INLINE unsafeHead #-} -- --------------------------------------------------------------------- -- Things that depend on the encoding {-# RULES "FPS specialise break -> breakSpace" break isSpace = breakSpace #-} -- | 'breakSpace' returns the pair of ByteStrings when the argument is -- broken at the first whitespace byte. I.e. -- -- > break isSpace == breakSpace -- breakSpace :: ByteString -> (ByteString,ByteString) breakSpace (PS x s l) = inlinePerformIO $ withForeignPtr x $ \p -> do i <- firstspace (p `plusPtr` s) 0 l return $! case () of {_ | i == 0 -> (empty, PS x s l) | i == l -> (PS x s l, empty) | otherwise -> (PS x s i, PS x (s+i) (l-i)) } {-# INLINE breakSpace #-} firstspace :: Ptr Word8 -> Int -> Int -> IO Int STRICT3(firstspace) --LIQUID GHOST firstspace ptr n m --LIQUID GHOST | n >= m = return n --LIQUID GHOST | otherwise = do w <- peekByteOff ptr n --LIQUID GHOST if (not $ isSpaceWord8 w) then firstspace ptr (n+1) m else return n firstspace ptr n m = go m ptr n m {- LIQUID WITNESS -} where go (d :: Int) ptr n m | n >= m = return n | otherwise = do w <- peekByteOff ptr n if (not $ isSpaceWord8 w) then go (d-1) ptr (n+1) m else return n {-# RULES "FPS specialise dropWhile isSpace -> dropSpace" dropWhile isSpace = dropSpace #-} -- | 'dropSpace' efficiently returns the 'ByteString' argument with -- white space Chars removed from the front. It is more efficient than -- calling dropWhile for removing whitespace. I.e. -- -- > dropWhile isSpace == dropSpace -- dropSpace :: ByteString -> ByteString dropSpace (PS x s l) = inlinePerformIO $ withForeignPtr x $ \p -> do i <- firstnonspace (p `plusPtr` s) 0 l return $! if i == l then empty else PS x (s+i) (l-i) {-# INLINE dropSpace #-} firstnonspace :: Ptr Word8 -> Int -> Int -> IO Int STRICT3(firstnonspace) --LIQUID GHOST firstnonspace ptr n m --LIQUID GHOST | n >= m = return n --LIQUID GHOST | otherwise = do w <- peekElemOff ptr n --LIQUID GHOST if isSpaceWord8 w then firstnonspace ptr (n+1) m else return n firstnonspace ptr n m = go m ptr n m {- LIQUID WITNESS -} where go (d :: Int) ptr n m | n >= m = return n | otherwise = do w <- peekElemOff ptr n if isSpaceWord8 w then go (d-1) ptr (n+1) m else return n {- -- | 'dropSpaceEnd' efficiently returns the 'ByteString' argument with -- white space removed from the end. I.e. -- -- > reverse . (dropWhile isSpace) . reverse == dropSpaceEnd -- -- but it is more efficient than using multiple reverses. -- dropSpaceEnd :: ByteString -> ByteString dropSpaceEnd (PS x s l) = inlinePerformIO $ withForeignPtr x $ \p -> do i <- lastnonspace (p `plusPtr` s) (l-1) return $! if i == (-1) then empty else PS x s (i+1) {-# INLINE dropSpaceEnd #-} lastnonspace :: Ptr Word8 -> Int -> IO Int STRICT2(lastnonspace) lastnonspace ptr n | n < 0 = return n | otherwise = do w <- peekElemOff ptr n if isSpaceWord8 w then lastnonspace ptr (n-1) else return n -} -- | 'lines' breaks a ByteString up into a list of ByteStrings at -- newline Chars. The resulting strings do not contain newlines. -- {-@ lines :: ByteString -> [ByteString] @-} lines :: ByteString -> [ByteString] lines ps | null ps = [] | otherwise = case search ps of Nothing -> [ps] Just n -> take n ps : lines (drop (n+1) ps) where search = elemIndex '\n' {-# INLINE lines #-} {- -- Just as fast, but more complex. Should be much faster, I thought. lines :: ByteString -> [ByteString] lines (PS _ _ 0) = [] lines (PS x s l) = inlinePerformIO $ withForeignPtr x $ \p -> do let ptr = p `plusPtr` s STRICT1(loop) loop n = do let q = memchr (ptr `plusPtr` n) 0x0a (fromIntegral (l-n)) if q == nullPtr then return [PS x (s+n) (l-n)] else do let i = q `minusPtr` ptr ls <- loop (i+1) return $! PS x (s+n) (i-n) : ls loop 0 -} -- | 'unlines' is an inverse operation to 'lines'. It joins lines, -- after appending a terminating newline to each. unlines :: [ByteString] -> ByteString unlines [] = empty unlines ss = (concat $ List.intersperse nl ss) `append` nl -- half as much space where nl = singleton '\n' -- | 'words' breaks a ByteString up into a list of words, which -- were delimited by Chars representing white space. --LIQUID FIXME: splitWith requires non-empty bytestrings for now.. {-@ words :: ByteStringNE -> [ByteString] @-} words :: ByteString -> [ByteString] words = P.filter (not . B.null) . B.splitWith isSpaceWord8 {-# INLINE words #-} -- | The 'unwords' function is analogous to the 'unlines' function, on words. unwords :: [ByteString] -> ByteString unwords = intercalate (singleton ' ') {-# INLINE unwords #-} -- --------------------------------------------------------------------- -- Reading from ByteStrings -- | readInt reads an Int from the beginning of the ByteString. If there is no -- integer at the beginning of the string, it returns Nothing, otherwise -- it just returns the int read, and the rest of the string. readInt :: ByteString -> Maybe (Int, ByteString) readInt as | null as = Nothing | otherwise = case unsafeHead as of '-' -> loop True 0 0 (B.unsafeTail as) '+' -> loop False 0 0 (B.unsafeTail as) _ -> loop False 0 0 as where loop :: Bool -> Int -> Int -> ByteString -> Maybe (Int, ByteString) {-@ Decrease loop 4 @-} STRICT4(loop) loop neg i n ps | null ps = end neg i n ps | otherwise = case B.unsafeHead ps of w | w >= 0x30 && w <= 0x39 -> loop neg (i+1) (n * 10 + (fromIntegral w - 0x30)) (B.unsafeTail ps) | otherwise -> end neg i n ps end _ 0 _ _ = Nothing end True _ n ps = Just (negate n, ps) end _ _ n ps = Just (n, ps) -- | readInteger reads an Integer from the beginning of the ByteString. If -- there is no integer at the beginning of the string, it returns Nothing, -- otherwise it just returns the int read, and the rest of the string. readInteger :: ByteString -> Maybe (Integer, ByteString) readInteger as | null as = Nothing | otherwise = case unsafeHead as of '-' -> first (B.unsafeTail as) >>= \(n, bs) -> return (-n, bs) '+' -> first (B.unsafeTail as) _ -> first as where first ps | null ps = Nothing | otherwise = case B.unsafeHead ps of w | w >= 0x30 && w <= 0x39 -> Just $ loop 1 (fromIntegral w - 0x30) [] (B.unsafeTail ps) | otherwise -> Nothing loop :: Int -> Int -> [Integer] -> ByteString -> (Integer, ByteString) {-@ Decrease loop 4 @-} STRICT4(loop) loop d acc ns ps | null ps = combine d acc ns empty | otherwise = case B.unsafeHead ps of w | w >= 0x30 && w <= 0x39 -> if d == 9 then loop 1 (fromIntegral w - 0x30) (toInteger acc : ns) (B.unsafeTail ps) else loop (d+1) (10*acc + (fromIntegral w - 0x30)) ns (B.unsafeTail ps) | otherwise -> combine d acc ns ps combine _ acc [] ps = (toInteger acc, ps) combine d acc ns ps = ((10^d * combine1 1000000000 ns + toInteger acc), ps) --LIQUID combine1 _ [n] = n --LIQUID combine1 b ns = combine1 (b*b) $ combine2 b ns --LIQUID --LIQUID combine2 b (n:m:ns) = let t = m*b + n in t `seq` (t : combine2 b ns) --LIQUID combine2 _ ns = ns {-@ combine1 :: Integer -> x:{v:[Integer] | (len v) > 0} -> Integer @-} {-@ Decrease combine1 2 @-} combine1 :: Integer -> [Integer] -> Integer combine1 _ [] = error "impossible" combine1 _ [n] = n combine1 b ns = combine1 (b*b) $ combine2 b ns {-@ combine2 :: Integer -> x:[Integer] -> {v:[Integer] | if len x > 1 then (len v < len x && len v > 0) else (len v <= len x)} @-} {-@ Decrease combine2 2 @-} combine2 :: Integer -> [Integer] -> [Integer] combine2 b (n:m:ns) = let t = m*b + n in t `seq` (t : combine2 b ns) combine2 _ ns = ns -- | Read an entire file strictly into a 'ByteString'. This is far more -- efficient than reading the characters into a 'String' and then using -- 'pack'. It also may be more efficient than opening the file and -- reading it using hGet. readFile :: FilePath -> IO ByteString readFile f = bracket (openFile f ReadMode) hClose (\h -> hFileSize h >>= hGet h . fromIntegral) -- | Write a 'ByteString' to a file. writeFile :: FilePath -> ByteString -> IO () writeFile f txt = bracket (openFile f WriteMode) hClose (\h -> hPut h txt) -- | Append a 'ByteString' to a file. appendFile :: FilePath -> ByteString -> IO () appendFile f txt = bracket (openFile f AppendMode) hClose (\h -> hPut h txt)
mightymoose/liquidhaskell
benchmarks/bytestring-0.9.2.1/Data/ByteString/Char8.hs
bsd-3-clause
43,150
0
18
12,126
6,453
3,703
2,750
-1
-1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, BangPatterns, NoImplicitPrelude, NondecreasingIndentation, MagicHash #-} module GHC.IO.Encoding.CodePage( #if defined(mingw32_HOST_OS) codePageEncoding, mkCodePageEncoding, localeEncoding, mkLocaleEncoding #endif ) where #if !defined(mingw32_HOST_OS) import GHC.Base () -- Build ordering #else import GHC.Base import GHC.Show import GHC.Num import GHC.Enum import GHC.Word import GHC.IO (unsafePerformIO) import GHC.IO.Encoding.Failure import GHC.IO.Encoding.Types import GHC.IO.Buffer import Data.Bits import Data.Maybe import Data.OldList (lookup) import qualified GHC.IO.Encoding.CodePage.API as API import GHC.IO.Encoding.CodePage.Table import GHC.IO.Encoding.UTF8 (mkUTF8) import GHC.IO.Encoding.UTF16 (mkUTF16le, mkUTF16be) import GHC.IO.Encoding.UTF32 (mkUTF32le, mkUTF32be) #if defined(mingw32_HOST_OS) # if defined(i386_HOST_ARCH) # define WINDOWS_CCONV stdcall # elif defined(x86_64_HOST_ARCH) # define WINDOWS_CCONV ccall # else # error Unknown mingw32 arch # endif #endif -- note CodePage = UInt which might not work on Win64. But the Win32 package -- also has this issue. getCurrentCodePage :: IO Word32 getCurrentCodePage = do conCP <- getConsoleCP if conCP > 0 then return conCP else getACP -- Since the Win32 package depends on base, we have to import these ourselves: foreign import WINDOWS_CCONV unsafe "windows.h GetConsoleCP" getConsoleCP :: IO Word32 foreign import WINDOWS_CCONV unsafe "windows.h GetACP" getACP :: IO Word32 {-# NOINLINE currentCodePage #-} currentCodePage :: Word32 currentCodePage = unsafePerformIO getCurrentCodePage localeEncoding :: TextEncoding localeEncoding = mkLocaleEncoding ErrorOnCodingFailure mkLocaleEncoding :: CodingFailureMode -> TextEncoding mkLocaleEncoding cfm = mkCodePageEncoding cfm currentCodePage codePageEncoding :: Word32 -> TextEncoding codePageEncoding = mkCodePageEncoding ErrorOnCodingFailure mkCodePageEncoding :: CodingFailureMode -> Word32 -> TextEncoding mkCodePageEncoding cfm 65001 = mkUTF8 cfm mkCodePageEncoding cfm 1200 = mkUTF16le cfm mkCodePageEncoding cfm 1201 = mkUTF16be cfm mkCodePageEncoding cfm 12000 = mkUTF32le cfm mkCodePageEncoding cfm 12001 = mkUTF32be cfm mkCodePageEncoding cfm cp = maybe (API.mkCodePageEncoding cfm cp) (buildEncoding cfm cp) (lookup cp codePageMap) buildEncoding :: CodingFailureMode -> Word32 -> CodePageArrays -> TextEncoding buildEncoding cfm cp SingleByteCP {decoderArray = dec, encoderArray = enc} = TextEncoding { textEncodingName = "CP" ++ show cp , mkTextDecoder = return $ simpleCodec (recoverDecode cfm) $ decodeFromSingleByte dec , mkTextEncoder = return $ simpleCodec (recoverEncode cfm) $ encodeToSingleByte enc } simpleCodec :: (Buffer from -> Buffer to -> IO (Buffer from, Buffer to)) -> (Buffer from -> Buffer to -> IO (CodingProgress, Buffer from, Buffer to)) -> BufferCodec from to () simpleCodec r f = BufferCodec { encode = f, recover = r, close = return (), getState = return (), setState = return } decodeFromSingleByte :: ConvArray Char -> DecodeBuffer decodeFromSingleByte convArr input@Buffer { bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ } output@Buffer { bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os } = let done why !ir !ow = return (why, if ir==iw then input{ bufL=0, bufR=0} else input{ bufL=ir}, output {bufR=ow}) loop !ir !ow | ow >= os = done OutputUnderflow ir ow | ir >= iw = done InputUnderflow ir ow | otherwise = do b <- readWord8Buf iraw ir let c = lookupConv convArr b if c=='\0' && b /= 0 then invalid else do ow' <- writeCharBuf oraw ow c loop (ir+1) ow' where invalid = done InvalidSequence ir ow in loop ir0 ow0 encodeToSingleByte :: CompactArray Char Word8 -> EncodeBuffer encodeToSingleByte CompactArray { encoderMax = maxChar, encoderIndices = indices, encoderValues = values } input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ } output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os } = let done why !ir !ow = return (why, if ir==iw then input { bufL=0, bufR=0 } else input { bufL=ir }, output {bufR=ow}) loop !ir !ow | ow >= os = done OutputUnderflow ir ow | ir >= iw = done InputUnderflow ir ow | otherwise = do (c,ir') <- readCharBuf iraw ir case lookupCompact maxChar indices values c of Nothing -> invalid Just 0 | c /= '\0' -> invalid Just b -> do writeWord8Buf oraw ow b loop ir' (ow+1) where invalid = done InvalidSequence ir ow in loop ir0 ow0 -------------------------------------------- -- Array access functions -- {-# INLINE lookupConv #-} lookupConv :: ConvArray Char -> Word8 -> Char lookupConv a = indexChar a . fromEnum {-# INLINE lookupCompact #-} lookupCompact :: Char -> ConvArray Int -> ConvArray Word8 -> Char -> Maybe Word8 lookupCompact maxVal indexes values x | x > maxVal = Nothing | otherwise = Just $ indexWord8 values $ j + (i .&. mask) where i = fromEnum x mask = (1 `shiftL` n) - 1 k = i `shiftR` n j = indexInt indexes k n = blockBitSize {-# INLINE indexInt #-} indexInt :: ConvArray Int -> Int -> Int indexInt (ConvArray p) (I# i) = I# (indexInt16OffAddr# p i) {-# INLINE indexWord8 #-} indexWord8 :: ConvArray Word8 -> Int -> Word8 indexWord8 (ConvArray p) (I# i) = W8# (indexWord8OffAddr# p i) {-# INLINE indexChar #-} indexChar :: ConvArray Char -> Int -> Char indexChar (ConvArray p) (I# i) = C# (chr# (indexInt16OffAddr# p i)) #endif
ezyang/ghc
libraries/base/GHC/IO/Encoding/CodePage.hs
bsd-3-clause
6,233
32
19
1,713
1,551
803
748
5
0
module F6 where f6f = \h -> \x -> h x 0 f6t = \y -> \z -> y + z f6 = f6f f6t 3
siddhanathan/ghc
testsuite/tests/arityanal/f6.hs
bsd-3-clause
84
0
7
31
53
30
23
4
1
module UnitTests.Distribution.Client.Sandbox ( tests ) where import Distribution.Client.Sandbox (withSandboxBinDirOnSearchPath) import Test.Tasty import Test.Tasty.HUnit import System.FilePath (getSearchPath, (</>)) tests :: [TestTree] tests = [ testCase "sandboxBinDirOnSearchPath" sandboxBinDirOnSearchPathTest , testCase "oldSearchPathRestored" oldSearchPathRestoreTest ] sandboxBinDirOnSearchPathTest :: Assertion sandboxBinDirOnSearchPathTest = withSandboxBinDirOnSearchPath "foo" $ do r <- getSearchPath assertBool "'foo/bin' not on search path" $ ("foo" </> "bin") `elem` r oldSearchPathRestoreTest :: Assertion oldSearchPathRestoreTest = do r <- getSearchPath withSandboxBinDirOnSearchPath "foo" $ return () r' <- getSearchPath assertEqual "Old search path wasn't restored" r r'
enolan/cabal
cabal-install/tests/UnitTests/Distribution/Client/Sandbox.hs
bsd-3-clause
843
0
11
136
175
95
80
20
1
import Data.Ix import Data.Int main = print (index (minBound::Int16,maxBound) maxBound)
beni55/ghcjs
test/pkg/base/ix001.hs
mit
89
0
8
11
36
20
16
3
1
module RankN where
vladfi1/hs-misc
RankN.hs
mit
23
0
2
7
4
3
1
1
0
solve :: Double -> Double solve x = 1 + x + (x^2/2) + (x^3/6) + (x^4/24) + (x^5/120) + (x^6/720) + (x^7/5040) + (x^8/40320) + (x^9/362880) -- + (x^10/3628800)-- Insert your code here -- main :: IO () main = getContents >>= mapM_ print. map solve. map (read::String->Double). tail. words
JsWatt/Free-Parking
hacker_rank/functional_programming/introduction/evaluating_e^x.hs
mit
288
0
15
52
197
103
94
4
1
module Typing.Subtyping ( (<:) , (\/) , (/\) , (//) , (\\) ) where import Typing.Types import Typing.Substitution import Data.List (intersect, union) import Data.Maybe (fromJust) import qualified Data.List ((\\)) (<:) :: Type -> Type -> Bool -- S-Refl t <: u | t == u = True -- S-Top _ <: Top = True -- S-Bot Bot <: _ = True -- S-Fun (Fun v1 p1 t1) <: (Fun v2 p2 t2) | v1 == v2 = all (uncurry (<:)) (zip p2 p1) && t1 <: t2 -- α-equivalence of functions (Fun v1 p1 t1) <: f2@(Fun v2 _ _) | map snd v1 == map snd v2 = let s = zipSubst (map fst v1) (map (uncurry Var) v2) in applySubst s (Fun v2 p1 t1) <: f2 -- α-equivalence of polymorphic types (Forall v1 t1) <: t2@(Forall v2 _) | length v1 == length v2 = let s = zipSubst v1 (map (flip Var []) v2) in applySubst s (Forall v2 t1) <: t2 -- α-equivalence of type constructors (TyAbs v1 t1) <: t2@(TyAbs v2 _) | length v1 == length v2 = let s = zipSubst v1 (map (flip Var []) v2) in applySubst s (TyAbs v2 t1) <: t2 (Forall gen t12) <: t2@(TyApp _t21 args) | length gen == length args = let t1' = applySubst (zipSubst gen args) t12 in t1' <: t2 (TyApp t11 t12) <: (TyApp t21 t22) = t11 <: t21 && and (zipWith (<:) t12 t22) (Rec r1) <: (Rec r2) = all aux r2 where aux (k, t2) = case lookup k r1 of Nothing -> False Just t1 -> t1 <: t2 _ <: _ = False -- Least Upper Bound (\/) :: Type -> Type -> Type s \/ t | s <: t = t s \/ t | t <: s = s (Fun x v p) \/ (Fun x' w q) | x == x' = Fun x (zipWith (/\) v w) (p \/ q) (Forall xs p) \/ (Forall ys q) | xs == ys = Forall xs (p \/ q) (TyApp p xs) \/ (TyApp q ys) | length xs == length ys = TyApp (p \/ q) (zipWith (\/) xs ys) (Rec f1) \/ (Rec f2) = let fields = (fst <$> f1) `intersect` (fst <$> f2) in Rec $ map (\f -> (f, fromJust (lookup f f1) \/ fromJust (lookup f f2))) fields _ \/ _ = Top -- Greatest Lower Bound (/\) :: Type -> Type -> Type s /\ t | s <: t = s s /\ t | t <: s = t (Fun x v p) /\ (Fun x' w q) | x == x' = Fun x (zipWith (\/) v w) (p /\ q) (Forall xs p) /\ (Forall ys q) | xs == ys = Forall xs (p /\ q) (TyApp p xs) /\ (TyApp q ys) | length xs == length ys = TyApp (p /\ q) (zipWith (/\) xs ys) (Rec f1) /\ (Rec f2) = let fields = (fst <$> f1) `union` (fst <$> f2) in Rec $ map (\f -> (f, maybe Top id (lookup f f1) /\ maybe Top id (lookup f f2))) fields _ /\ _ = Bot -- VARIABLE ELIMINATION -- Eliminate Up: S ⇑V T (//) :: [Var] -> Type -> Type -- VU-Top _ // Top = Top -- VU-Bot _ // Bot = Bot -- VU-Con _ // (Con x) = (Con x) -- VU-Cls _ // (Cls name) = (Cls name) v // var@(Var x _) -- VU-Var-1 | x `elem` v = Top -- VU-Var-2 | otherwise = var -- VU-Fun v // (Fun x s t) = let u = map ((\\) v) s in let r = v // t in Fun x u r v // (Rec fields) = let fields' = map (\(k, t) -> (k, v // t)) fields in Rec fields' v // (Forall gen ty) = let v' = v Data.List.\\ gen in Forall gen (v' // ty) v // (TyAbs gen ty) = let v' = v Data.List.\\ gen in TyAbs gen (v' // ty) v // (TyApp ty args) = TyApp (v // ty) (map ((//) v) args) -- Eliminate Down: S ⇓V T (\\) :: [Var] -> Type -> Type -- VD-Top _ \\ Top = Top -- VD-Bot _ \\ Bot = Bot -- -- VD-Con _ \\ (Con x) = (Con x) -- -- VD-Cls _ \\ (Cls name) = (Cls name) v \\ var@(Var x _) -- VD-Var-1 | x `elem` v = Bot -- VD-Var-2 | otherwise = var -- VD-Fun v \\ (Fun x s t) = let u = map ((//) v) s in let r = v \\ t in Fun x u r v \\ (Rec fields) = let fields' = map (\(k, t) -> (k, v \\ t)) fields in Rec fields' v \\ (Forall gen ty) = let v' = v Data.List.\\ gen in Forall gen (v' \\ ty) v \\ (TyAbs gen ty) = let v' = v Data.List.\\ gen in TyAbs gen (v' \\ ty) v \\ (TyApp ty args) = TyApp (v \\ ty) (map ((\\) v) args)
tadeuzagallo/verve-lang
src/Typing/Subtyping.hs
mit
3,789
0
15
1,075
2,265
1,133
1,132
-1
-1
-- | The DSL for creating a grammar/tokenizer definition for 'Text.Tokenify.tokenizer' module Text.Tokenify.DSL where import Prelude hiding (concat, any) import qualified Text.Tokenify.Response as Response import qualified Text.Tokenify.Regex as Regex import Text.Tokenify.Regex (Regex) import Text.Tokenify.Types -- * Response Constructors -- | Creates a response which will fail on a regex fails :: Regex s -> Token s a fails r = (r, Response.Error) -- | Creates a response which will ignore a regex ignore :: Regex s -> Token s a ignore r = (r, Response.Ignore) -- | Creates a response which consumes the text position insert :: Regex s -> (Pos -> a) -> Token s a insert r f = (r, Response.Display f) -- | Creates a response which consumes the captures 'CharSeq' and the text position evaluate :: Regex s -> (s -> Pos -> a) -> Token s a evaluate r f = (r, Response.Process f) -- * Regex Constructors -- | Creates a regex that matches a string string :: s -> Regex s string = Regex.String -- | Creates a regex that matches a char char :: Char -> Regex s char = Regex.Char -- | Creates a create that will match a range of characters range :: Char -> Char -> Regex s range = Regex.Range -- | Creates a regex that will attmpt to make the regex on the left, if -- that fails it will attmpt to match the regex on the right alt :: Regex s -> Regex s -> Regex s alt = Regex.Alt -- | Creates a regex that will attmpt to match a Sequence of regex\'s -- in a sequencial order any :: [Regex s] -> Regex s any [] = Regex.NoPass any (x:[]) = x any (x:xs) = Regex.Alt x (any xs) -- | Create a regex that appends the result of two regex\'s append :: Regex s -> Regex s -> Regex s append = Regex.Append -- | Create a regex that appends the result of a sequence of regex\'s concat :: [Regex s] -> Regex s concat [] = Regex.NoPass concat (x:[]) = x concat (x:xs) = Regex.Append x (concat xs) -- | Create a regex that may or may not match a regex option :: Regex s -> Regex s option = Regex.Option -- | Create a regex that matches zero or more of a regex repeat :: Regex s -> Regex s repeat = Regex.Repeat -- | Create a regex that matches one or more of a regex repeat1 :: Regex s -> Regex s repeat1 = Regex.Repeat1
AKST/tokenify
src/Text/Tokenify/DSL.hs
mit
2,233
0
9
459
576
312
264
38
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverlappingInstances #-} module Main where import Prelude hiding (writeFile) import Data.Map (empty) import Text.XML import Text.XML.Generic import GHC.Generics data Hobby = Hobby String deriving (Show, Generic) data User = User { firstName :: String, lastName :: String, age :: Int, hobbies :: [Hobby] } deriving (Show, Generic) instance ToXml Hobby instance ToXml User main :: IO() main = do writeFile def { rsPretty = True } "users.xml" $ Document (Prologue [] Nothing []) root [] where john = User "John" "Doe" 44 [Hobby "jokes", Hobby "laughing"] jane = User "Jane" "Doe" 38 [] users = (toXml) john ++ (toXml jane) root = Element "users" empty users
jhedev/xml-conduit-generics
examples/Users.hs
mit
1,022
0
11
373
259
143
116
26
1
module Input where import Data.Vector (Vector) import qualified Data.Vector as V import DailyChart type Input = Vector Double type SixDailyCharts = (DailyChart, DailyChart, DailyChart, DailyChart, DailyChart, DailyChart) fromDailyCharts :: SixDailyCharts -> (Bool, Input) fromDailyCharts (d1,d2,d3,d4,d5,d6) = (answer, input) where input = V.fromList $ init [ fromIntegral (f d) | f <- [open, close], d <- [d1,d2,d3,d4,d5,d6] ] answer = close d5 < close d6 makeInputs :: Vector DailyChart -> Vector (Bool, Input) makeInputs ds = V.map fromDailyCharts $ V.zip6 ds (V.drop 1 ds) (V.drop 2 ds) (V.drop 3 ds) (V.drop 4 ds) (V.drop 5 ds)
cohei/stock-value-prediction
Input.hs
mit
650
0
12
112
291
163
128
12
1
--The MIT License (MIT) -- --Copyright (c) 2016-2017 Steffen Michels ([email protected]) -- --Permission is hereby granted, free of charge, to any person obtaining a copy of --this software and associated documentation files (the "Software"), to deal in --the Software without restriction, including without limitation the rights to use, --copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the --Software, and to permit persons to whom the Software is furnished to do so, --subject to the following conditions: -- --The above copyright notice and this permission notice shall be included in all --copies or substantial portions of the Software. -- --THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR --IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS --FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR --COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER --IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN --CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 800 {-# LANGUAGE Strict#-} #endif module HPT ( HPT(..) , HPTLeaf(..) , HPTLeafFormulas(..) , CachedSplitPoints(..) , SplitPoint(..) , Proof(..) , Choice(..) , FNodeType(..) , LazyNode , initialHPT , bounds , nextLeaf , addLeaf , addLeafWithinEvidence ) where import qualified KnowledgeBase as KB import Probability import qualified GroundedAST import Data.HashMap (Map) import qualified Data.HashMap as Map import Data.Text (Text) import GHC.Generics (Generic) import Data.Hashable (Hashable) import qualified Data.Hashable as Hashable import qualified Data.Set as PQ -- set used as PQ here import Data.HashSet (Set) import Control.Monad (when) type PQ = PQ.Set -- Hybrid Probability Tree data HPT = HPT (PQ HPTLeaf) ProbabilityQuadruple (Map HPTLeafFormulas Probability) data HPTLeaf = HPTLeaf HPTLeafFormulas Probability deriving Eq data HPTLeafFormulas = MaybeWithinEv LazyNode (KB.NodeRef CachedSplitPoints) Int | WithinEv (KB.NodeRef CachedSplitPoints) Int deriving (Eq, Generic) instance Ord HPTLeafFormulas where compare WithinEv{} MaybeWithinEv{} = LT compare (WithinEv qx hx) (WithinEv qy hy) = case compare hx hy of EQ -> compare qx qy res -> res compare (MaybeWithinEv qx ex hx) (MaybeWithinEv qy ey hy) = case compare hx hy of EQ -> case compare ex ey of EQ -> compare qx qy -- comparing lazy queries is most expensive res -> res res -> res compare MaybeWithinEv{} WithinEv{} = GT instance Hashable HPTLeafFormulas where hashWithSalt salt (MaybeWithinEv _ _ h) = Hashable.hashWithSalt salt h hashWithSalt salt (WithinEv _ h) = Hashable.hashWithSalt salt h type LazyNode = (KB.NodeRef CachedSplitPoints, KB.Conditions) instance Ord HPTLeaf where HPTLeaf fx px <= HPTLeaf fy py | px == py = fx <= fy | otherwise = px <= py -- CachedSplitPoints "true proofs" "false proofs" "all point [+ scores]" data CachedSplitPoints = CachedSplitPoints (Set Proof) (Set Proof) FNodeType data FNodeType = Primitive (Set SplitPoint) | Composed (Map SplitPoint Int) data SplitPoint = BoolSplit (GroundedAST.PFunc Bool) | StringSplit (GroundedAST.PFunc Text) (Set Text) -- left branch: all string in this set, right branch: all remaining strings | ContinuousSplit (GroundedAST.PFunc GroundedAST.RealN) Rational | ObjectSplit (GroundedAST.PFunc GroundedAST.Object) Integer -- left branch: including this object, right branch: excluding this object | ObjectIntervSplit (GroundedAST.PFunc GroundedAST.Object) Integer -- left branch: including this object deriving (Eq, Generic, Ord) instance Hashable SplitPoint newtype Proof = Proof (Map SplitPoint Choice) deriving (Eq, Ord, Generic) instance Hashable Proof data Choice = Left | Right deriving (Eq, Ord, Generic) instance Hashable Choice initialHPT :: KB.NodeRef CachedSplitPoints -> KB.NodeRef CachedSplitPoints -> KB.KBState CachedSplitPoints HPT initialHPT q e = addLeaf (q, KB.noConditions) e 1.0 $ HPT PQ.empty (ProbabilityQuadruple 0.0 0.0 0.0 0.0) Map.empty nextLeaf :: HPT -> Maybe (HPTLeaf, HPT) nextLeaf (HPT leaves (ProbabilityQuadruple t f e u) leafSet) = case PQ.maxView leaves of Nothing -> Nothing Just (leaf@(HPTLeaf fs p), leaves') -> Just (leaf, HPT leaves' quad $ Map.delete fs leafSet) where quad = case fs of MaybeWithinEv{} -> ProbabilityQuadruple t f e (u - p) WithinEv{} -> ProbabilityQuadruple t f (e - p) u addLeaf :: LazyNode -> KB.NodeRef CachedSplitPoints -> Probability -> HPT -> KB.KBState CachedSplitPoints HPT addLeaf qWithConds@(q, qConds) ev p hpt@(HPT leaves (ProbabilityQuadruple t f e u) leafSet) = case KB.deterministicNodeRef ev of Just True -> do q' <- KB.augmentWithEntry q q'' <- KB.condition q' qConds KB.dereference q addLeafWithinEvidence (KB.entryRef q'') p hpt Just False -> return hpt Nothing -> do when merged $ KB.dereference q >> KB.dereference ev return $ HPT pq' (ProbabilityQuadruple t f e (u + p)) leafSet' where (pq', leafSet', merged) = insertIntoPQ (MaybeWithinEv qWithConds ev $ Hashable.hashWithSalt (Hashable.hash qWithConds) ev) p leaves leafSet addLeafWithinEvidence :: KB.NodeRef CachedSplitPoints -> Probability -> HPT -> KB.KBState CachedSplitPoints HPT addLeafWithinEvidence q p (HPT leaves (ProbabilityQuadruple t f e u) leafSet) = case KB.deterministicNodeRef q of Just True -> return $ HPT leaves (ProbabilityQuadruple (t + p) f e u) leafSet Just False -> return $ HPT leaves (ProbabilityQuadruple t (f + p) e u) leafSet Nothing -> do when merged $ KB.dereference q return $ HPT pq' (ProbabilityQuadruple t f (e + p) u) leafSet' where (pq', leafSet', merged) = insertIntoPQ (WithinEv q $ Hashable.hash q) p leaves leafSet insertIntoPQ :: HPTLeafFormulas -> Probability -> PQ HPTLeaf -> Map HPTLeafFormulas Probability -> (PQ HPTLeaf, Map HPTLeafFormulas Probability, Bool) insertIntoPQ fs p pq leafSet = case Map.lookup fs leafSet of Just p' -> let p'' = p + p' in (PQ.insert (HPTLeaf fs p'') $ PQ.delete (HPTLeaf fs p') pq, Map.insert fs p'' leafSet, True) Nothing -> (PQ.insert (HPTLeaf fs p) pq, Map.insert fs p leafSet, False) -- Nothing if evidence is inconsistent bounds :: HPT -> Maybe ProbabilityBounds bounds (HPT _ (ProbabilityQuadruple 0.0 0.0 0.0 0.0) _) = Nothing bounds (HPT _ (ProbabilityQuadruple t f e u) _) = Just $ ProbabilityBounds lo up where lo = t / (t + f + e + u) up | upDen == 0.0 = 1.0 | up' <= 1.0 = up' | otherwise = 1.0 ~up' = (t + e + u) / upDen -- lazy to prevent division by zero upDen = t + f + e -- (true prob, false prob (within evidence), within evidence, unknown prob) data ProbabilityQuadruple = ProbabilityQuadruple Probability Probability Probability Probability
SteffenMichels/IHPMC
src/HPT.hs
mit
7,452
0
16
1,753
2,010
1,048
962
120
3
{-# LANGUAGE OverloadedStrings #-} module Y2018.M06.D05.Exercise where {-- Another day, another data structure. We have a smart-tagging algorithm that saves its results to JSON. We want to take those results in store them in a database. But before we do that, we need to parse the JSON into Haskell structures because Haskell structures are ... ... cute? --} import Data.Aeson data Entity a = Entity { name :: String, wiki :: WikiInfo, related :: [a] } deriving (Eq, Show) instance FromJSON a => FromJSON (Entity a) where parseJSON (Object o) = undefined data WikiInfo = Wiki { wikiname, wikisummary :: String, wikiimages :: [FilePath], wikilink :: FilePath } deriving (Eq, Show) instance FromJSON WikiInfo where parseJSON (Object o) = undefined -- the entities are stored here exDir, entitiesFile :: FilePath exDir = "Y2018/M06/D05/" entitiesFile = "smart_tagging.json" readEntities :: FilePath -> IO [Entity Value] readEntities file = undefined -- How many entities are there? -- What is the name of the entity that has the most related articles? -- How many related articles does it have? {-- PART DUEX! -------------------------------------------------------------- Okay. Look at the structure of the JSON. Why do people do this? That is to say. They have entity information: great. They have wiki information that they get from a separate call: great. But why flatten into a pancake the wiki information with the entity information, commingling the two? Somebody ought to write a book: "Badly Structured Data, and How to Avoid it!" or: "Good Data Structures." Oh, somebody has written a book? Several somebodies? Huh. It's like people look at JSON and are like: "I know data structures because I've seen JSON once! Hold my beer!" This JSON. So. Output the JSON in well-structured (hierarchical) form. --} instance ToJSON a => ToJSON (Entity a) where toJSON entity = undefined -- Then rebuke the bad JSON by writing out that good JSON to file writeEntities :: ToJSON a => FilePath -> [Entity a] -> IO () writeEntities output entities = undefined
geophf/1HaskellADay
exercises/HAD/Y2018/M06/D05/Exercise.hs
mit
2,113
0
9
394
276
156
120
21
1
import Test.Hspec -- Problem 16 -- Drop every N'th element from a list. dropEvery :: Eq a => [a] -> Int -> [a] dropEvery ls n = get' ls n n where get' [] _ _ = [] get' (_:xs) t 1 = get' xs t t get' (x:xs) t i = x : get' xs t (i-1) main :: IO() main = hspec $ describe "99-exercises.16 = Drop every N'th element from a list" $ it "should drop each n'th element in a list" $ dropEvery "abcdefghik" 3 `shouldBe` "abdeghk"
baldore/haskell-99-exercises
16.hs
mit
451
0
10
123
176
90
86
11
3
{-# LANGUAGE RecordWildCards #-} import Data.Char (isSpace) import Data.Foldable (for_) import Data.Function (on) import Test.Hspec (Spec, describe, it, shouldBe, shouldMatchList) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import CryptoSquare (encode) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "encode" $ for_ cases test where test Case{..} = describe description $ do let shouldMatchString = shouldBe `on` filter (not . isSpace) shouldMatchChars = shouldMatchList `on` filter (not . isSpace) it "normalizes the input" $ encode input `shouldMatchChars` expected it "reorders the characters" $ encode input `shouldMatchString` expected it "groups the output" $ encode input `shouldBe` expected data Case = Case { description :: String , input :: String , expected :: String } cases :: [Case] cases = [ Case { description = "empty plaintext results in an empty ciphertext" , input = "" , expected = "" } , Case { description = "Lowercase" , input = "A" , expected = "a" } , Case { description = "Remove spaces" , input = " b " , expected = "b" } , Case { description = "Remove punctuation" , input = "@1,%!" , expected = "1" } , Case { description = "9 character plaintext results in 3 chunks of 3 characters" , input = "This is fun!" , expected = "tsf hiu isn" } , Case { description = "8 character plaintext results in 3 chunks, the last one with a trailing space" , input = "Chill out." , expected = "clu hlt io " } , Case { description = "54 character plaintext results in 7 chunks, the last two padded with spaces" , input = "If man was meant to stay on the ground, god would have given us roots." , expected = "imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau " } ] -- de97c99c0d129ce1af95e8986917ac3964292f42
exercism/xhaskell
exercises/practice/crypto-square/test/Tests.hs
mit
2,412
0
16
903
457
269
188
42
1
module Y2016.M07.D19.Solution where {-- A Trigon, also known in some circles as a 'triangle,' is a three-SIDED shape. Trigons are have several interesting characteristics. A trigon also defines a plane (in which it lies), and a set of trigons can be rendered efficiently these days to represent, e.g. characters in 3 dimensions, such as pokémon, for example ... now that I have your attention. Look at the figure tri2.gif at this directory or at the URL: https://github.com/geophf/1HaskellADay/blob/master/exercises/HAD/Y2016/M07/D19/tri2.gif Today's #haskell exercise is to declare the type Trigon, and then to compute the number of trigons in that figure. Also compute the total area, because fun. --} import Data.Map (Map) import qualified Data.Map as Map data Trigon = A3SidedPolygon deriving Show type Point2d = (Float, Float) type Figure = Map Char Point2d figure2 :: Figure figure2 = Map.fromList (zip "abgcdthfjkmnp" [(0,0), (15,10),(25,10),(35,10),(50,0), (35,-10),(25,-10),(15,-10), (15,0),(20,0),(25,0),(30,0),(35,0)]) countingTrigons :: Figure -> Int countingTrigons = undefined -- hint: it is possible for trigons to overlap or to contain other trigons -- within them {-- BONUS ----------------------------------------------------------------- The area of a trigon is its bh / 2 where b = length of the base of the trigon h = height of the trigon Of course the area of a 'square' is the square of the length of its side ... that's why a square is called 'square,' you see. But I digress ... or do I? What is the area of the figure? --} area :: Figure -> Float area = undefined -- BONUS-BONUS: why is area called 'area'? What is its etimology? -- The figure is figure2 because we'll do a bit of exploration with shapes -- this week.
geophf/1HaskellADay
exercises/HAD/Y2016/M07/D19/Solution.hs
mit
1,792
0
10
319
240
154
86
15
1
import Prelude hiding ((++),concat) -- just for kicks & gigs (++) :: [a] -> [a] -> [a] [] ++ ys = ys (x:xs) ++ ys = x : (xs ++ ys) concat :: [[a]] -> [a] concat [] = [] concat (xs:xss) = xs ++ concat xss test = concat [["a","b"],["c","d"],["e","f"]]
calebgregory/fp101x
wk3/concat.hs
mit
271
0
7
72
169
97
72
8
1
module MyLen where myLen :: [a] -> Int myLen (_:xs) = 1 + myLen xs myLen [] = 0
lpenz/realworldhaskell-exercises
ch03/MyLen.hs
mit
86
0
7
25
48
26
22
4
1
-- WeIrD StRiNg CaSe -- http://www.codewars.com/kata/52b757663a95b11b3d00062d/train/haskell module WeIrDStRiNgCaSe where import Data.Char(toLower, toUpper) toWeirdCase :: String -> String toWeirdCase = unwords . map (zipWith ($) (cycle [toUpper, toLower])) . words
gafiatulin/codewars
src/6 kyu/WeIrDStRiNgCaSe.hs
mit
268
0
12
32
66
39
27
4
1
module Vacivity.FOV.ShadowCast( calcFOV ) where import Prelude hiding (any, all, foldl, concat) import Control.Applicative ((<$>)) import Data.Foldable hiding (toList) import qualified Data.Set as Set import qualified Antiqua.Data.Array2d as A2D import Antiqua.Common import Vacivity.FOV.Common import Vacivity.Utils import Debug.Trace inRadius :: XY -> Int -> Bool inRadius (x, y) r = x*x + y*y <= r*r inRange :: XY -> (Int,Int,Int,Int) -> Bool inRange (x, y) (rx, ry, rw, rh) | x >= rx && y >= ry && x < rx + rw && y < ry + rh = True | otherwise = False isSolid :: Mask -> XY -> Bool isSolid msk c = any not (A2D.get msk c) data ShadowArgs = ShadowArgs { s :: Double, ns :: Double, b :: Bool, lit :: Col XY } type Col a = Set.Set a toList :: Col a -> [a] toList = Set.toList append :: Ord a => a -> Col a -> Col a append x = Set.insert x single :: a -> Col a single = Set.singleton empty :: Col a empty = Set.empty calcFOV :: Mask -> XY -> Int -> [XY] calcFOV msk@(A2D.Array2d w h _) (sx, sy) r = let dirs = [ (-1,1), (1,-1), (-1,-1), (1,1) ] in let cast = castLight 1 1.0 0.0 msk in let seed = single (sx, sy) in let calls = concat $ (\(i, j) -> [cast i 0 0 j, cast 0 i j 0]) <$> dirs in let lsts = ($ empty) <$> calls in toList $ Set.unions (seed:lsts) where castLight row start end mask xx xy yx yy l = if start < end then l else lit $ outer row (ShadowArgs start 0.0 False l) where recast d st ed lit' = castLight d st ed mask xx xy yx yy lit' outer d args = if d > r || b args then args else (outer (d + 1) . inner d (-d) (-d)) args inner d dy dx args = let reinner = inner d dy (dx + 1) in if dx > 0 then args else let pos = (sx + dx * xx + dy * xy ,sy + dx * yx + dy * yy) in let f sigx sigy = (fromIntegral dx + sigx*0.5) / (fromIntegral dy + sigy*0.5) in let ls = f (-1) 1 in let rs = f 1 (-1) in if (not . inRange pos) (0, 0, w, h) || s args < rs then reinner args else if end > ls then args else let lit' = onlyIf (inRadius (dx, dy) r) (append pos) (lit args) in let solid = isSolid mask pos in let args' = args { lit = lit' } in reinner $ if b args' then if solid then args' { ns = rs } else args' { s = ns args', b = False} else if solid && d < r then let lit'' = recast (d + 1) (s args') ls lit' in args' { ns = rs, b = True, lit = lit'' } else args'
olive/vacivity
src/Vacivity/FOV/ShadowCast.hs
mit
3,298
0
37
1,542
1,270
680
590
75
9