code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Network.Gitit.Plugins.Ditaa (plugin) where {- This plugin allows you to include a ditaa diagram in a page like this: ~~~ {.ditaa name="ditaa_diagram1"} +--------+ +-------+ +-------+ | | --+ ditaa +--> | | | Text | +-------+ |diagram| |Document| |!magic!| | | | {d}| | | | | +---+----+ +-------+ +-------+ : ^ | Lots of work | +-------------------------+ ~~~ Must be installed and in the path: - Java virtual machine (java) - Copy "ditaa.jar" at a known location. See: http://ditaa.sourceforge.net/#download - add ditaa.jar to the CLASSPATH environment variable. - e.g. (Windows): set CLASSPATH=C:\My\AbsPath\To\Jar\Files\ditaa.jar;%CLASSPATH% - e.g. (Unix): export CLASSPATH=/My/AbsPath/To/Jar/Files/ditaa.jar:%CLASSPATH% - We also assume an executable wrapper that will properly handle calls in the form `ditaa myArguments`. The generated png file will be saved in the static img directory. If no name is specified, a unique name will be generated from a hash of the file contents. -} import Network.Gitit.Interface import System.Exit (ExitCode(ExitSuccess)) -- from the utf8-string package on HackageDB: import Data.ByteString.Lazy.UTF8 (fromString) -- from the SHA package on HackageDB: import Data.Digest.Pure.SHA (sha1, showDigest) import System.FilePath ((</>)) import System.IO (openTempFile, hClose, hPutStr, Handle) import System.IO.Error(catchIOError, ioError, isDoesNotExistError) import System.Process (readProcessWithExitCode) import System.Directory(getTemporaryDirectory, removeFile) import Control.Exception (bracket) import Control.Monad.Trans (liftIO) import Control.Concurrent plugin :: Plugin plugin = mkPageTransformM transformBlock transformBlock :: Block -> PluginM Block transformBlock (CodeBlock (_, classes, namevals) contents) | "ditaa" `elem` classes = do cfg <- askConfig let (name, outfile) = case lookup "name" namevals of Just fn -> ([Str fn], fn ++ ".png") Nothing -> ([], uniqueName contents ++ ".png") liftIO $ do (ec, pngData, err) <- withSystemTempFile "ditaa.txt" $ \contentFilePath hf -> do hPutStr hf contents hClose hf readProcessWithExitCode "ditaa" ["-o", contentFilePath, staticDir cfg </> "img" </> outfile] "" if ec == ExitSuccess then return $ Para [Image nullAttr name ("/img/" ++ outfile, "")] else error $ "ditaa returned an error status: " ++ err transformBlock x = return x withSystemTempFile :: String -> (FilePath -> Handle -> IO a) -> IO a withSystemTempFile nameTpl callBack = bracket (getTemporaryDirectory >>= \tmpDir -> openTempFile tmpDir nameTpl) (\(fp, hf) -> hClose hf >> rmFile fp) (uncurry callBack) where rmFile fp = removeFile fp `catchIOError ` recoverHandler recoverHandler e = if isDoesNotExistError e then return () else ioError e -- | Generate a unique filename given the file's contents. uniqueName :: String -> String uniqueName = showDigest . sha1 . fromString
jraygauthier/jrg-gitit-plugins
src/Network/Gitit/Plugins/Ditaa.hs
gpl-2.0
3,409
0
20
955
605
330
275
43
3
module Moves where import Debug.Trace (traceShow) import Data.List (intersect) import Data.Maybe import Control.Applicative import qualified Data.Array as A import Data.Sequence as S import ChessData import Board import Vectors import Eval import Query -- Generate all pseudo-legal moves from a given board position and SideToMove genMoves :: GameState -> Seq GameState genMoves g@(GameState b' stm c ep clk s _) = S.filter (not.isInCheck) pslegal where pieces = fromList $ piecesByColour b' stm enPassents = genEnPassentMoves g pslegal = concatSeq (stdMoves g) pieces >< enPassents -- Get all standard moves, that is moves which aren't enpassent, castling, or pawn -- moves stdMoves :: GameState -> (Square, Piece) -> Seq GameState stdMoves g@(GameState b' stm c ep clk s _) fromPiece@(_, Piece ptype _)= if sliderPiece ptype then genSliderMoves g fromPiece else genNonSliderMoves g fromPiece -- Generate the slider moves for pieces genSliderMoves :: GameState -> (Square, Piece) -> Seq GameState genSliderMoves g@(GameState b' stm c ep clk s _) fromPiece@(sq, p@(Piece ptype _)) = fmap (makeMove g) moves where vects = fromList $ concatMap (sliderPiecePos b' sq stm) $ moveVectors p moves = fmap (\x -> Move sq x p Nothing) vects genNonSliderMoves :: GameState -> (Square, Piece) -> Seq GameState genNonSliderMoves g@(GameState b' stm c ep clk s _) fromPiece@(sq, p@(Piece ptype _)) | ptype == Pawn = genPawnMoves g sq | otherwise = fmap (makeMove g) moves where moves = fmap (\x -> Move sq x p Nothing) legalMoves legalMoves = S.filter (checkSq b' stm) possibleMoves possibleMoves = fmap (addPos sq) $ fromList $ moveVectors p -- Helper function for sequence concatSeq :: (a -> Seq b) -> Seq a -> Seq b concatSeq = foldMap genPawnMoves :: GameState -> Square -> Seq GameState genPawnMoves g@(GameState b' stm c ep clk s _) sq@(a,b) = fmap (makeMove g) moves where -- TODO: Handle promotion moves = fmap (\x -> Move sq x (Piece Pawn stm) Nothing) allMoves allMoves = (stdPawnMoves >< pawnCaptures) stdPawnMoves = S.filter legalDoubleMove stdCandidates stdCandidates = S.filter checkSqPawn (addPos sq <$> pawnVectors sq stm) pawnCaptures = genPawnCaptures g sq checkSqPawn psq = legalPos psq && isEmpty b' psq legalDoubleMove sq'@(c,d) = if abs (b-d) == 2 then checkSqPawn (c, d + colToDir stm) else True colToDir White = 1 colToDir Black = -1 genPawnCaptures :: GameState -> Square -> Seq Square genPawnCaptures g@(GameState b' stm c ep clk s _) sq = avail (S.filter legalPos $ pawnAttackVectors stm sq) where -- keep the available potential squares avail :: Seq Square -> Seq Square avail = S.filter (isOppositeColour b' stm) genEnPassentMoves :: GameState -> Seq GameState genEnPassentMoves g@(GameState b' stm c ep clk s _) | isNothing ep = S.empty | otherwise = fromList $ fmap (\x -> makeMove g (Move (fst x) epSq (snd x) Nothing)) candidates where epSq = fromJust ep attackSqs = Prelude.filter legalPos $ map (addPos epSq) $ if stm == White then [(1, 1), (-1, 1)] else [(1, -1), (-1, -1)] candidates = Prelude.filter (\x -> snd x /= Empty && ptype (snd x) == Pawn) $ map (\x -> (x, pieceAt b' x)) attackSqs -- A helper function which will generate a new state, from move information. -- It will also reverse the side to move, and setup castling and enpassent rights, -- and also increment the half-move clock makeMove :: GameState -> Move -> GameState makeMove g move | isJust $ enPassentSq move = makeEnPassentMove g move | otherwise = makeGeneralMove g move -- When making an en passent move, the pawn moves normally, but an extra piece -- must be removed makeEnPassentMove :: GameState -> Move -> GameState makeEnPassentMove g@(GameState b' stm c ep clk s _) m@(Move fromSq toSq@(x,y) (Piece ptype _) _) = do -- Move the attacking piece let b1 = movePiece b' fromSq toSq -- Take the enPassent victim let b2 = setBoardCell b1 pos Empty -- Return a new state GameState b2 (opposite stm) c Nothing (clk+1) (evalState stm b2) (Just m) where pos | stm == White = (x, y+1) | otherwise = (x, y-1) makeGeneralMove :: GameState -> Move -> GameState makeGeneralMove g@(GameState b' stm c ep clk s _) move@(Move fromSq toSq@(x,y) (Piece ptype _) _) = GameState board next castling ep nclk s m where board = movePiece b' fromSq toSq next = opposite stm castling = [] -- This is not a castling move (handled elsewhere) ep = enPassentSq move nclk = clk + 1 s = evalState next board m = Just move enPassentSq :: Move -> Maybe Square enPassentSq (Move (x,y) (_,y') (Piece ptype _) _) | ptype == Pawn = if abs (y - y') == 2 then Just (x, (y+y') `quot` 2 ) else Nothing | otherwise = Nothing -- Helper function for when testing in ghci stMakeMove :: GameState -> String -> GameState stMakeMove st mvString = makeMove st (Move fromSq toSq p promo) where (fromSq', toSq') = Prelude.splitAt 2 mvString fromSq = positionToSquare fromSq' toSq = positionToSquare toSq' p = pieceAt (board st) fromSq promo = Nothing
CameronDiver/hschess
src/moves.hs
gpl-3.0
5,642
0
15
1,572
1,876
979
897
99
3
module TaskTree.Lib.Edit () where import TaskTree.Lib.Tree (Tree) -- TODO do you need the first Tree? data Edit = Error String | Up | Down Tree | Insert Tree Int Tree -- old, index/pos, new | Delete Tree Int -- old, index/pos | Move -- TODO deriving Show
jefdaj/todotree
old/TaskTree/Lib/Edit.hs
gpl-3.0
277
0
6
69
64
41
23
11
0
(Writer (a, w)) >>= f = let Writer (b, w') = f a in Writer (b, w `mappend` w')
hmemcpy/milewski-ctfp-pdf
src/content/3.4/code/haskell/snippet11.hs
gpl-3.0
103
0
10
43
63
32
31
2
1
module Sound ( play , playBackground , pauseBackgroundMusic , resumeBackgroundMusic , endBackgroundMusic ) where {- Requires (Haskell) sdl, sdl-mixer, (non-Haskell) sdl_mixer -} import Control.Monad import Control.Monad.Fix import Control.Concurrent.Async import Graphics.UI.SDL as SDL import Graphics.UI.SDL.Mixer as Mix audioConsts :: IO () audioConsts = openAudio audioRate audioFormat audioChannels audioBuffers where audioRate = 22050 audioFormat = Mix.AudioS16LSB audioChannels = 2 audioBuffers = 4096 anyChannel = -1 -- | single sound effect play :: String -> IO (Async ()) play s = async $ do SDL.init [SDL.InitAudio] result <- audioConsts sound <- Mix.loadWAV s ch1 <- Mix.playChannel (-1) sound 0 fix $ \loop -> do SDL.delay 50 stillPlaying <- numChannelsPlaying when (stillPlaying /= 0) loop Mix.closeAudio SDL.quit -- | looping background music playBackground :: String -> IO (Async ()) playBackground s = async $ do SDL.init [SDL.InitAudio] result <- audioConsts sound <- Mix.loadWAV s ch1 <- Mix.playChannel 2 sound (-1) resume 2 fix $ \loop -> do SDL.delay 50 stillPlaying <- numChannelsPlaying when (stillPlaying /= 0) loop Mix.closeAudio SDL.quit pauseBackgroundMusic :: IO () pauseBackgroundMusic = pause 2 resumeBackgroundMusic :: IO () resumeBackgroundMusic = resume 2 endBackgroundMusic :: IO () endBackgroundMusic = haltChannel 2 example :: IO () example = do playBackground "../sounds/click.wav" SDL.delay 1000 play "../sounds/song.wav" SDL.delay 1000 pauseBackgroundMusic putStrLn "Hi!"
exitmouse/proper
src/Sound.hs
gpl-3.0
1,695
0
14
391
499
247
252
56
1
module Suggestions where import Data.Char (toLower) import Data.List (intercalate, sortBy, minimumBy) import qualified Data.Map as M import Data.Maybe (isJust, fromJust) import DataTypes import ShrdliteGrammar import Plan import Interpreter suggest :: WorldState -> [String] suggest worldState = map (intercalate " " . goalToUtterance worldState . snd) $ take 10 $ sortBy (\(h1,_) (h2,_) -> compare h2 h1) [(heuristicAStar worldState goal,goal) | goal <- generateAllSugestions worldState] generateAllSugestions :: WorldState -> [Goal] generateAllSugestions worldState = case _holding worldState of Just id -> [ MoveObj id rel id2 | rel <- relations , id2 <- "Floor" : (map fst $ M.toList (_objectsInfo worldState)) , relationValid (_objectsInfo worldState) id id2 rel , id /= id2] Nothing -> [ MoveObj id1 rel id2 | rel <- relations , id1 <- map fst $ M.toList (_objectsInfo worldState) , id2 <- "Floor" : (map fst $ M.toList (_objectsInfo worldState)) , relationValid (_objectsInfo worldState) id1 id2 rel , id1 /= id2] ++ [ TakeObj id1 | id1 <- map fst $ M.toList (_objectsInfo worldState)] relations :: [Relation] relations = [Beside , Leftof , Rightof , Above , Ontop , Under , Inside] -- | Translate a goal to an utterance for displaying in the suggestions list goalToUtterance :: WorldState -> Goal -> Utterance goalToUtterance worldState goal = case goal of TakeObj id1 -> let objDesc = getObjectDescription worldState id1 in if objDesc == [] then [] else ["take", "the"] ++ objDesc MoveObj id1 rel id2 -> let objDesc1 = getObjectDescription worldState id1 objDesc2 = getObjectDescription worldState id2 in if objDesc1 == [] || objDesc2 == [] then [] else (if isJust $ _holding worldState then ["put", "it"] else ["put", "the"] ++ objDesc1) ++ getRelationDescription rel ++ objDesc2 getObjectDescription :: WorldState -> Id -> [String] getObjectDescription worldState id | id == "Floor" = ["the", "floor"] | otherwise = let Just obj = M.lookup id (_objectsInfo worldState) ent = fewestAttributesToIdentifyObject worldState obj id in case ent of BasicEntity Any (Object AnySize AnyColor AnyForm) -> [] BasicEntity _ obj -> objAttrsToString obj RelativeEntity q1 thisObj (Relative rel (BasicEntity q2 obj2)) -> objAttrsToString thisObj ++ ((unwords $ getRelationDescription rel) : "the" : objAttrsToString obj2) -- | Returns a list of strings of the attributes of an object objAttrsToString :: Object -> [String] objAttrsToString (Object size color form) = let sizeList = if size == AnySize then [] else [show size] colorList = if color == AnyColor then [] else [show color] in map (map toLower) $ concat [sizeList, colorList, [show form]] -- | For a given object returns an object with the fewest number of attributes -- for identifying it uniquely in the world -- The entities are created with the "The" quantifier, to make sure only unique -- matches are returned through the "Left" constructor. This criterion is used -- to filter the list. fewestAttributesToIdentifyObject :: WorldState -> Object -> Id -> Entity fewestAttributesToIdentifyObject worldState obj@(Object size color form) id = let allCombEnts = [BasicEntity The (Object s c form) | s <- [AnySize, size] , c <- [AnyColor, color]] uniqueEntities = filter (isLeft . (\ent -> findEntities ent worldState)) allCombEnts in if null uniqueEntities then let allIds = concat $ _world worldState allRels = [Beside, Leftof, Rightof, Above, Ontop, Under, Inside] validRelPairs = [(localId, rel) | localId <- allIds, rel <- allRels , relationHolds worldState id rel localId] allRelEnts = [(RelativeEntity Any (Object s1 c1 form) (Relative rel (BasicEntity The (Object s c frm)))) | (lokId, rel) <- validRelPairs , (Object sz clr frm) <- [fromJust $ M.lookup lokId (_objectsInfo worldState)] , s <- [AnySize, sz] , c <- [AnyColor, clr] , s1 <- [AnySize, size] , c1 <- [AnyColor, color] ] validRels = filter (isLeft . \ent -> findEntities ent worldState) allRelEnts in if null validRels then BasicEntity Any (Object AnySize AnyColor AnyForm) else minimumBy orderRelEntByBothObjects validRels else minimumBy orderEntsByDescrLength uniqueEntities orderRelEntByBothObjects :: Entity -> Entity -> Ordering orderRelEntByBothObjects (RelativeEntity _ obj11 (Relative _ (BasicEntity _ obj12))) (RelativeEntity _ obj21 (Relative _ (BasicEntity _ obj22))) | descriptionLength obj11 + descriptionLength obj12 < descriptionLength obj21 + descriptionLength obj22 = LT | descriptionLength obj11 + descriptionLength obj12 > descriptionLength obj21 + descriptionLength obj22 = GT | otherwise = EQ -- | Order of Entities with respect to their description length orderEntsByDescrLength :: Entity -> Entity -> Ordering orderEntsByDescrLength (BasicEntity _ obj1) (BasicEntity _ obj2) = orderObjByDescr obj1 obj2 orderEntsByDescrLength (RelativeEntity _ _ (Relative _ bEnt1)) (RelativeEntity _ _ (Relative _ bEnt2)) = orderEntsByDescrLength bEnt1 bEnt2 -- | Order of Objects with respect to their description length orderObjByDescr :: Object -> Object -> Ordering orderObjByDescr obj1 obj2 | descriptionLength obj1 < descriptionLength obj2 = LT | descriptionLength obj1 > descriptionLength obj2 = GT | otherwise = EQ -- | Counts how many attributes of the object are actually set, -- i.e. are not Any* descriptionLength :: Object -> Int descriptionLength (Object size color form) = sc + cc + fc where sc = case size of AnySize -> 0 _ -> 1 cc = case color of AnyColor -> 0 _ -> 1 fc = case form of AnyForm -> 0 _ -> 1 -- | Checks if an Either object was constructed with Left isLeft :: Either a b -> Bool isLeft (Left _) = True isLeft x = False getRelationDescription :: Relation -> [String] getRelationDescription relation = return $ case relation of Ontop -> "on the" Inside -> "in the" Above -> "above the" Under -> "under the" Rightof -> "right of the" Leftof -> "left of the" Beside -> "beside the"
carlostome/shrdlite
haskell/Suggestions.hs
gpl-3.0
7,085
0
20
2,154
1,941
999
942
132
7
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AdExchangeBuyer2.Bidders.FilterSets.FilteredBids.Creatives.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- List all creatives associated with a specific reason for which bids were -- filtered, with the number of bids filtered for each creative. -- -- /See:/ <https://developers.google.com/authorized-buyers/apis/reference/rest/ Ad Exchange Buyer API II Reference> for @adexchangebuyer2.bidders.filterSets.filteredBids.creatives.list@. module Network.Google.Resource.AdExchangeBuyer2.Bidders.FilterSets.FilteredBids.Creatives.List ( -- * REST Resource BiddersFilterSetsFilteredBidsCreativesListResource -- * Creating a Request , biddersFilterSetsFilteredBidsCreativesList , BiddersFilterSetsFilteredBidsCreativesList -- * Request Lenses , bfsfbclXgafv , bfsfbclUploadProtocol , bfsfbclFilterSetName , bfsfbclAccessToken , bfsfbclUploadType , bfsfbclCreativeStatusId , bfsfbclPageToken , bfsfbclPageSize , bfsfbclCallback ) where import Network.Google.AdExchangeBuyer2.Types import Network.Google.Prelude -- | A resource alias for @adexchangebuyer2.bidders.filterSets.filteredBids.creatives.list@ method which the -- 'BiddersFilterSetsFilteredBidsCreativesList' request conforms to. type BiddersFilterSetsFilteredBidsCreativesListResource = "v2beta1" :> Capture "filterSetName" Text :> "filteredBids" :> Capture "creativeStatusId" (Textual Int32) :> "creatives" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListCreativeStatusBreakdownByCreativeResponse -- | List all creatives associated with a specific reason for which bids were -- filtered, with the number of bids filtered for each creative. -- -- /See:/ 'biddersFilterSetsFilteredBidsCreativesList' smart constructor. data BiddersFilterSetsFilteredBidsCreativesList = BiddersFilterSetsFilteredBidsCreativesList' { _bfsfbclXgafv :: !(Maybe Xgafv) , _bfsfbclUploadProtocol :: !(Maybe Text) , _bfsfbclFilterSetName :: !Text , _bfsfbclAccessToken :: !(Maybe Text) , _bfsfbclUploadType :: !(Maybe Text) , _bfsfbclCreativeStatusId :: !(Textual Int32) , _bfsfbclPageToken :: !(Maybe Text) , _bfsfbclPageSize :: !(Maybe (Textual Int32)) , _bfsfbclCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BiddersFilterSetsFilteredBidsCreativesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bfsfbclXgafv' -- -- * 'bfsfbclUploadProtocol' -- -- * 'bfsfbclFilterSetName' -- -- * 'bfsfbclAccessToken' -- -- * 'bfsfbclUploadType' -- -- * 'bfsfbclCreativeStatusId' -- -- * 'bfsfbclPageToken' -- -- * 'bfsfbclPageSize' -- -- * 'bfsfbclCallback' biddersFilterSetsFilteredBidsCreativesList :: Text -- ^ 'bfsfbclFilterSetName' -> Int32 -- ^ 'bfsfbclCreativeStatusId' -> BiddersFilterSetsFilteredBidsCreativesList biddersFilterSetsFilteredBidsCreativesList pBfsfbclFilterSetName_ pBfsfbclCreativeStatusId_ = BiddersFilterSetsFilteredBidsCreativesList' { _bfsfbclXgafv = Nothing , _bfsfbclUploadProtocol = Nothing , _bfsfbclFilterSetName = pBfsfbclFilterSetName_ , _bfsfbclAccessToken = Nothing , _bfsfbclUploadType = Nothing , _bfsfbclCreativeStatusId = _Coerce # pBfsfbclCreativeStatusId_ , _bfsfbclPageToken = Nothing , _bfsfbclPageSize = Nothing , _bfsfbclCallback = Nothing } -- | V1 error format. bfsfbclXgafv :: Lens' BiddersFilterSetsFilteredBidsCreativesList (Maybe Xgafv) bfsfbclXgafv = lens _bfsfbclXgafv (\ s a -> s{_bfsfbclXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). bfsfbclUploadProtocol :: Lens' BiddersFilterSetsFilteredBidsCreativesList (Maybe Text) bfsfbclUploadProtocol = lens _bfsfbclUploadProtocol (\ s a -> s{_bfsfbclUploadProtocol = a}) -- | Name of the filter set that should be applied to the requested metrics. -- For example: - For a bidder-level filter set for bidder 123: -- \`bidders\/123\/filterSets\/abc\` - For an account-level filter set for -- the buyer account representing bidder 123: -- \`bidders\/123\/accounts\/123\/filterSets\/abc\` - For an account-level -- filter set for the child seat buyer account 456 whose bidder is 123: -- \`bidders\/123\/accounts\/456\/filterSets\/abc\` bfsfbclFilterSetName :: Lens' BiddersFilterSetsFilteredBidsCreativesList Text bfsfbclFilterSetName = lens _bfsfbclFilterSetName (\ s a -> s{_bfsfbclFilterSetName = a}) -- | OAuth access token. bfsfbclAccessToken :: Lens' BiddersFilterSetsFilteredBidsCreativesList (Maybe Text) bfsfbclAccessToken = lens _bfsfbclAccessToken (\ s a -> s{_bfsfbclAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). bfsfbclUploadType :: Lens' BiddersFilterSetsFilteredBidsCreativesList (Maybe Text) bfsfbclUploadType = lens _bfsfbclUploadType (\ s a -> s{_bfsfbclUploadType = a}) -- | The ID of the creative status for which to retrieve a breakdown by -- creative. See -- [creative-status-codes](https:\/\/developers.google.com\/authorized-buyers\/rtb\/downloads\/creative-status-codes). bfsfbclCreativeStatusId :: Lens' BiddersFilterSetsFilteredBidsCreativesList Int32 bfsfbclCreativeStatusId = lens _bfsfbclCreativeStatusId (\ s a -> s{_bfsfbclCreativeStatusId = a}) . _Coerce -- | A token identifying a page of results the server should return. -- Typically, this is the value of -- ListCreativeStatusBreakdownByCreativeResponse.nextPageToken returned -- from the previous call to the filteredBids.creatives.list method. bfsfbclPageToken :: Lens' BiddersFilterSetsFilteredBidsCreativesList (Maybe Text) bfsfbclPageToken = lens _bfsfbclPageToken (\ s a -> s{_bfsfbclPageToken = a}) -- | Requested page size. The server may return fewer results than requested. -- If unspecified, the server will pick an appropriate default. bfsfbclPageSize :: Lens' BiddersFilterSetsFilteredBidsCreativesList (Maybe Int32) bfsfbclPageSize = lens _bfsfbclPageSize (\ s a -> s{_bfsfbclPageSize = a}) . mapping _Coerce -- | JSONP bfsfbclCallback :: Lens' BiddersFilterSetsFilteredBidsCreativesList (Maybe Text) bfsfbclCallback = lens _bfsfbclCallback (\ s a -> s{_bfsfbclCallback = a}) instance GoogleRequest BiddersFilterSetsFilteredBidsCreativesList where type Rs BiddersFilterSetsFilteredBidsCreativesList = ListCreativeStatusBreakdownByCreativeResponse type Scopes BiddersFilterSetsFilteredBidsCreativesList = '["https://www.googleapis.com/auth/adexchange.buyer"] requestClient BiddersFilterSetsFilteredBidsCreativesList'{..} = go _bfsfbclFilterSetName _bfsfbclCreativeStatusId _bfsfbclXgafv _bfsfbclUploadProtocol _bfsfbclAccessToken _bfsfbclUploadType _bfsfbclPageToken _bfsfbclPageSize _bfsfbclCallback (Just AltJSON) adExchangeBuyer2Service where go = buildClient (Proxy :: Proxy BiddersFilterSetsFilteredBidsCreativesListResource) mempty
brendanhay/gogol
gogol-adexchangebuyer2/gen/Network/Google/Resource/AdExchangeBuyer2/Bidders/FilterSets/FilteredBids/Creatives/List.hs
mpl-2.0
8,521
0
20
1,790
993
578
415
151
1
-- -- Copyright 2017-2018 Azad Bolour -- Licensed under GNU Affero General Public License v3.0 - -- https://github.com/azadbolour/boardgame/blob/master/LICENSE.md -- module Bolour.Util.MiscUtil ( debug , setListElement , isPositive , nonPositive , fromRight , mkUuid , returnR , returnL , isAlphaNumString , contiguous , maybeToEither , mapMaybeToEither , IOEither , IOExceptT , mapFromValueList , zipMaps , inverseMultiValuedMapping ) where import Data.Char (isAlphaNum) import Data.Map (Map) import qualified Data.Map as Map import qualified Data.List as List import qualified Data.Maybe as Maybe import Debug.Trace import Data.UUID import Data.UUID.V4 import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Except (ExceptT) -- | Shorthand for tracing. debug :: String -> a -> a debug message = trace ("TRACE: " ++ message) -- TODO. Is it easier to use lenses here for setting list elements? setListElement :: [element] -> Int -> element -> [element] setListElement [] _ _ = [] -- TODO. Exception?? setListElement list 0 element = element : tail list setListElement list n element = head list : setListElement (tail list) (n - 1) element isPositive :: (Num num, Ord num) => num -> Bool isPositive x = (signum x) > 0 nonPositive :: (Num num, Ord num) => num -> Bool nonPositive = not . isPositive fromRight :: (Show left) => Either left right -> right fromRight = either (error . show) id -- | Get a uuid. mkUuid :: (MonadIO m) => m String mkUuid = do uuid <- liftIO nextRandom return $ toString uuid returnR :: (Monad monad) => a -> monad (Either e a) returnR value = return $ Right value returnL :: (Monad monad) => e -> monad (Either e a) returnL error = return $ Left error -- | Convert a may to an Either supplying an error for Nothing. maybeToEither :: error -> Maybe substrate -> Either error substrate maybeToEither error may = case may of Nothing -> Left error Just substrate -> Right substrate -- | Convert a maybe within a monad to an error within the monad. mapMaybeToEither :: (Monad m) => error -> m (Maybe substrate) -> m (Either error substrate) mapMaybeToEither error monad = maybeToEither error <$> monad isAlphaNumString :: String -> Bool isAlphaNumString s = all isAlphaNum s -- | Does list of integers represent successive values? contiguous :: [Int] -> Bool contiguous [] = True contiguous [x] = True contiguous (x:y:ys) = (y == x + 1) && contiguous (y:ys) type IOEither left right = IO (Either left right) type IOExceptT left right = ExceptT left IO right mapFromValueList :: (Ord key) => (value -> key) -> [value] -> Map key [value] mapFromValueList keyMaker values = let pairMaker value = (keyMaker value, [value]) pairs = pairMaker <$> values in Map.fromListWith (++) pairs lookupJust :: (Ord key) => key -> Map key value -> value lookupJust key map = Maybe.fromJust $ Map.lookup key map zipMaps :: (Ord key) => Map key value1 -> Map key value2 -> Map key (value1, value2) zipMaps map1 map2 = let keys1 = Map.keys map1 keys2 = Map.keys map2 commonKeys = List.intersect keys1 keys2 zipper key = (key, (lookupJust key map1, lookupJust key map2)) in Map.fromList $ zipper <$> commonKeys inverseMultiValuedMapping :: Ord b => (a -> [b]) -> [a] -> Map.Map b [a] inverseMultiValuedMapping mapping as = let inversePairWithMappedValue a = (\b -> (b, [a])) <$> mapping a pairs = as >>= inversePairWithMappedValue in Map.fromListWith (++) pairs
azadbolour/boardgame
haskell-server/src/Bolour/Util/MiscUtil.hs
agpl-3.0
3,519
0
13
702
1,164
626
538
83
2
-- ---------------------------------------------------------------------- -- Copyright 2010-2011 National University of Ireland. -- ---------------------------------------------------------------------- -- This file is part of DysVunctional Language. -- -- DysVunctional Language is free software; you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. -- -- DysVunctional Language 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 Affero General Public License -- along with DysVunctional Language. If not, see <http://www.gnu.org/licenses/>. -- ---------------------------------------------------------------------- {-# LANGUAGE NoImplicitPrelude #-} module FOL.Language.Pretty ( Pretty , pp , real , pprint , sepMap , ppList , symbol , ppForm , module Text.PrettyPrint ) where import FOL.Language.Common import Text.PrettyPrint class Pretty a where pp :: a -> Doc real :: Real -> Doc real = double pprint :: Pretty a => a -> String pprint = render . pp sepMap :: (a -> Doc) -> [a] -> Doc sepMap f = sep . map f ppList :: [Doc] -> Doc ppList = parens . sep symbol :: String -> Doc symbol = text ppForm :: Pretty a => String -> [a] -> Doc ppForm name xs = ppList $ symbol name : map pp xs instance Pretty Name where pp (Name n) = symbol n
axch/dysvunctional-language
haskell-fol/FOL/Language/Pretty.hs
agpl-3.0
1,707
0
8
331
273
158
115
29
1
{- Copyright (C) 2013–2014 Albert Krewinkel <[email protected]> This file is part of ZeitLinse. ZeitLinse is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ZeitLinse is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with ZeitLinse. If not, see <http://www.gnu.org/licenses/>. -} -- | A time-dependent scoring system. module ZeitLinse.Core.ZeitScore ( zeitScore , zeitScore' ) where import ZeitLinse.Core.Types import ZeitLinse.Core.WeightedMerging import Control.Lens.Getter import Data.Time.Clock -- | Calculate the score depending on submission time and reference time. -- Uses simple exponential decay for now, but should be replaced with a -- smarter algorithm. zeitScore :: TimedRating -> UTCTime -> Score zeitScore = zeitScore' $ exp . negate -- | Like zeitScore, but takes an activation function as additional parameter. zeitScore' :: (Double -> Double) -> TimedRating -> UTCTime -> Score zeitScore' fn timedRating referenceTime = applyWeight weightFromTimes $ timedRating^.timedRatingScore where weightFromTimes = Weight . fn . asFloating $ timePassed timePassed = diffUTCTime submissionTime referenceTime submissionTime = timedRating ^. timedRatingTime.fromSubmissionTime asFloating = fromRational . toRational
tarleb/zeitlinse
src/ZeitLinse/Core/ZeitScore.hs
agpl-3.0
1,746
0
9
314
167
96
71
-1
-1
{-# LANGUAGE LambdaCase #-} {-| Module providing Bitcoin script evaluation. See <https://github.com/bitcoin/bitcoin/blob/master/src/script.cpp> EvalScript and <https://en.bitcoin.it/wiki/Script> -} module Network.Haskoin.Script.Evaluator ( -- * Script evaluation verifySpend , evalScript , SigCheck , Flag -- * Evaluation data types , Program , Stack -- * Helper functions , encodeInt , decodeInt , encodeBool , decodeBool , runStack , checkStack , dumpScript , dumpStack , execScript ) where import Control.Monad.State import Control.Monad.Reader import Control.Monad.Except import Control.Monad.Identity import Control.Applicative ((<$>), (<*>)) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import Data.List (intercalate) import Data.Bits (shiftR, shiftL, testBit, setBit, clearBit, (.&.)) import Data.Int (Int64) import Data.Word (Word8, Word64) import Data.Either ( rights ) import Data.Maybe ( mapMaybe, isJust ) import Network.Haskoin.Crypto import Network.Haskoin.Script.Types import Network.Haskoin.Script.SigHash import Network.Haskoin.Util import Network.Haskoin.Transaction.Types import Data.Binary (encode, decodeOrFail) maxScriptSize :: Int maxScriptSize = 10000 maxScriptElementSize :: Int maxScriptElementSize = 520 maxStackSize :: Int maxStackSize = 1000 maxOpcodes :: Int maxOpcodes = 200 maxKeysMultisig :: Int maxKeysMultisig = 20 data Flag = P2SH | STRICTENC | DERSIG | LOW_S | NULLDUMMY | SIGPUSHONLY | MINIMALDATA | DISCOURAGE_UPGRADABLE_NOPS deriving ( Show, Read, Eq ) type FlagSet = [ Flag ] data EvalError = EvalError String | ProgramError String Program | StackError ScriptOp | DisabledOp ScriptOp instance Show EvalError where show (EvalError m) = m show (ProgramError m prog) = m ++ " - program: " ++ show prog show (StackError op) = show op ++ ": Stack Error" show (DisabledOp op) = show op ++ ": disabled" type StackValue = [Word8] type AltStack = [StackValue] type Stack = [StackValue] type HashOps = [ScriptOp] -- the code that is verified by OP_CHECKSIG -- | Defines the type of function required by script evaluating -- functions to check transaction signatures. type SigCheck = [ScriptOp] -> TxSignature -> PubKey -> Bool -- | Data type of the evaluation state. data Program = Program { stack :: Stack, altStack :: AltStack, hashOps :: HashOps, sigCheck :: SigCheck, opCount :: Int } dumpOp :: ScriptOp -> String dumpOp (OP_PUSHDATA payload optype) = "OP_PUSHDATA(" ++ show optype ++ ")" ++ " 0x" ++ bsToHex payload dumpOp op = show op dumpList :: [String] -> String dumpList xs = "[" ++ intercalate "," xs ++ "]" dumpScript :: [ScriptOp] -> String dumpScript script = dumpList $ map dumpOp script dumpStack :: Stack -> String dumpStack s = dumpList $ map (bsToHex . BS.pack) s instance Show Program where show p = " stack: " ++ dumpStack (stack p) type ProgramState = ExceptT EvalError Identity type IfStack = [ Bool ] -- | Monad of actions independent of conditional statements. type ProgramTransition = ReaderT FlagSet ( StateT Program ProgramState ) -- | Monad of actions which taking if statements into account. -- Separate state type from ProgramTransition for type safety type ConditionalProgramTransition a = StateT IfStack ProgramTransition a evalProgramTransition :: ProgramTransition a -> Program -> FlagSet -> Either EvalError a evalProgramTransition m s f = runIdentity . runExceptT $ evalStateT ( runReaderT m f ) s evalConditionalProgram :: ConditionalProgramTransition a -- ^ Program monad -> [ Bool ] -- ^ Initial if state stack -> Program -- ^ Initial computation data -> FlagSet -- ^ Evaluation Flags -> Either EvalError a evalConditionalProgram m s = evalProgramTransition ( evalStateT m s ) -------------------------------------------------------------------------------- -- Error utils programError :: String -> ProgramTransition a programError s = get >>= throwError . ProgramError s disabled :: ScriptOp -> ProgramTransition () disabled op = throwError . DisabledOp $ op -------------------------------------------------------------------------------- -- Type Conversions -- | Encoding function for the stack value format of integers. Most -- significant bit defines sign. encodeInt :: Int64 -> StackValue encodeInt i = prefix $ encode' (fromIntegral $ abs i) [] where encode' :: Word64 -> StackValue -> StackValue encode' 0 bytes = bytes encode' j bytes = fromIntegral j:encode' (j `shiftR` 8) bytes prefix :: StackValue -> StackValue prefix [] = [] prefix xs | testBit (last xs) 7 = prefix $ xs ++ [0] | i < 0 = init xs ++ [setBit (last xs) 7] | otherwise = xs -- | Inverse of `encodeInt`. decodeInt :: StackValue -> Maybe Int64 decodeInt bytes | length bytes > 4 = Nothing | otherwise = Just $ sign' (decodeW bytes) where decodeW [] = 0 decodeW [x] = fromIntegral $ clearBit x 7 decodeW (x:xs) = fromIntegral x + decodeW xs `shiftL` 8 sign' i | null bytes = 0 | testBit (last bytes) 7 = -i | otherwise = i -- | Conversion of StackValue to Bool (true if non-zero). decodeBool :: StackValue -> Bool decodeBool [] = False decodeBool [0x00] = False decodeBool [0x80] = False decodeBool (0x00:vs) = decodeBool vs decodeBool _ = True encodeBool :: Bool -> StackValue encodeBool True = [1] encodeBool False = [] constValue :: ScriptOp -> Maybe StackValue constValue op = case op of OP_0 -> Just $ encodeInt 0 OP_1 -> Just $ encodeInt 1 OP_2 -> Just $ encodeInt 2 OP_3 -> Just $ encodeInt 3 OP_4 -> Just $ encodeInt 4 OP_5 -> Just $ encodeInt 5 OP_6 -> Just $ encodeInt 6 OP_7 -> Just $ encodeInt 7 OP_8 -> Just $ encodeInt 8 OP_9 -> Just $ encodeInt 9 OP_10 -> Just $ encodeInt 10 OP_11 -> Just $ encodeInt 11 OP_12 -> Just $ encodeInt 12 OP_13 -> Just $ encodeInt 13 OP_14 -> Just $ encodeInt 14 OP_15 -> Just $ encodeInt 15 OP_16 -> Just $ encodeInt 16 OP_1NEGATE -> Just $ encodeInt $ -1 (OP_PUSHDATA string _) -> Just $ BS.unpack string _ -> Nothing -- | Check if OpCode is constant isConstant :: ScriptOp -> Bool isConstant = isJust . constValue -- | Check if OpCode is disabled isDisabled :: ScriptOp -> Bool isDisabled op = op `elem` [ OP_CAT , OP_SUBSTR , OP_LEFT , OP_RIGHT , OP_INVERT , OP_AND , OP_OR , OP_XOR , OP_2MUL , OP_2DIV , OP_MUL , OP_DIV , OP_MOD , OP_LSHIFT , OP_RSHIFT , OP_VER , OP_VERIF , OP_VERNOTIF ] -- | Check if OpCode counts towards opcount limit countOp :: ScriptOp -> Bool countOp op | isConstant op = False | op == OP_RESERVED = False | otherwise = True popInt :: ProgramTransition Int64 popInt = minimalStackValEnforcer >> decodeInt <$> popStack >>= \case Nothing -> programError "popInt: data > nMaxNumSize" Just i -> return i pushInt :: Int64 -> ProgramTransition () pushInt = pushStack . encodeInt popBool :: ProgramTransition Bool popBool = decodeBool <$> popStack pushBool :: Bool -> ProgramTransition () pushBool = pushStack . encodeBool opToSv :: StackValue -> BS.ByteString opToSv = BS.pack bsToSv :: BS.ByteString -> StackValue bsToSv = BS.unpack -------------------------------------------------------------------------------- -- Stack Primitives getStack :: ProgramTransition Stack getStack = stack <$> get getCond :: ConditionalProgramTransition [Bool] getCond = get popCond :: ConditionalProgramTransition Bool popCond = get >>= \condStack -> case condStack of [] -> lift $ programError "popCond: empty condStack" (c:cs) -> put cs >> return c pushCond :: Bool -> ConditionalProgramTransition () pushCond c = get >>= \s -> put (c:s) flipCond :: ConditionalProgramTransition () flipCond = popCond >>= pushCond . not withStack :: ProgramTransition Stack withStack = getStack >>= \case [] -> stackError s -> return s putStack :: Stack -> ProgramTransition () putStack st = modify $ \p -> p { stack = st } prependStack :: Stack -> ProgramTransition () prependStack s = getStack >>= \s' -> putStack $ s ++ s' checkPushData :: ScriptOp -> ProgramTransition () checkPushData (OP_PUSHDATA v _) | BS.length v > fromIntegral maxScriptElementSize = programError "OP_PUSHDATA > maxScriptElementSize" | otherwise = return () checkPushData _ = return () checkStackSize :: ProgramTransition () checkStackSize = do n <- length <$> stack <$> get m <- length <$> altStack <$> get when ((n + m) > fromIntegral maxStackSize) $ programError "stack > maxStackSize" pushStack :: StackValue -> ProgramTransition () pushStack v = getStack >>= \s -> putStack (v:s) popStack :: ProgramTransition StackValue popStack = withStack >>= \(s:ss) -> putStack ss >> return s popStackN :: Integer -> ProgramTransition [StackValue] popStackN n | n < 0 = programError "popStackN: negative argument" | n == 0 = return [] | otherwise = (:) <$> popStack <*> popStackN (n - 1) pickStack :: Bool -> Int -> ProgramTransition () pickStack remove n = do st <- getStack when (n < 0) $ programError "pickStack: n < 0" when (n > length st - 1) $ programError "pickStack: n > size" let v = st !! n when remove $ putStack $ take n st ++ drop (n+1) st pushStack v getHashOps :: ProgramTransition HashOps getHashOps = hashOps <$> get -- | Function to track the verified OPs signed by OP_CHECK(MULTI) sig. -- Dependent on the sequence of `OP_CODESEPARATOR` dropHashOpsSeparatedCode :: ProgramTransition () dropHashOpsSeparatedCode = modify $ \p -> let tryDrop = dropWhile ( /= OP_CODESEPARATOR ) $ hashOps p in case tryDrop of -- If no OP_CODESEPARATOR, take the whole script. This case is -- possible when there is no OP_CODESEPARATOR in scriptPubKey but -- one exists in scriptSig [] -> p _ -> p { hashOps = tail tryDrop } -- | Filters out `OP_CODESEPARATOR` from the output script used by -- OP_CHECK(MULTI)SIG preparedHashOps :: ProgramTransition HashOps preparedHashOps = filter ( /= OP_CODESEPARATOR ) <$> getHashOps -- | Removes any PUSHDATA that contains the signatures. Used in -- CHECK(MULTI)SIG so that signatures can be contained in output -- scripts. See FindAndDelete() in Bitcoin Core. findAndDelete :: [ StackValue ] -> [ ScriptOp ] -> [ ScriptOp ] findAndDelete [] ops = ops findAndDelete (s:ss) ops = let pushOp = opPushData . opToSv $ s in findAndDelete ss $ filter ( /= pushOp ) ops checkMultiSig :: SigCheck -- ^ Signature checking function -> [ StackValue ] -- ^ PubKeys -> [ StackValue ] -- ^ Signatures -> [ ScriptOp ] -- ^ CODESEPARATOR'd hashops -> Bool checkMultiSig f encPubKeys encSigs hOps = let pubKeys = mapMaybe ( decodeToMaybe . opToSv ) encPubKeys sigs = rights $ map ( decodeSig . opToSv ) encSigs cleanHashOps = findAndDelete encSigs hOps in (length sigs == length encSigs) && -- check for bad signatures orderedSatisfy (f cleanHashOps) sigs pubKeys -- | Tests whether a function is satisfied for every a with some b "in -- order". By "in order" we mean, if a pair satisfies the function, -- any other satisfying pair must be deeper in each list. Designed to -- return as soon as the result is known to minimize expensive -- function calls. Used in checkMultiSig to verify signature/pubKey -- pairs with a values as signatures and b values as pubkeys orderedSatisfy :: ( a -> b -> Bool ) -> [ a ] -> [ b ] -> Bool orderedSatisfy _ [] _ = True orderedSatisfy _ (_:_) [] = False orderedSatisfy f x@(a:as) y@(b:bs) | length x > length y = False | f a b = orderedSatisfy f as bs | otherwise = orderedSatisfy f x bs tStack1 :: (StackValue -> Stack) -> ProgramTransition () tStack1 f = f <$> popStack >>= prependStack tStack2 :: (StackValue -> StackValue -> Stack) -> ProgramTransition () tStack2 f = f <$> popStack <*> popStack >>= prependStack tStack3 :: (StackValue -> StackValue -> StackValue -> Stack) -> ProgramTransition () tStack3 f = f <$> popStack <*> popStack <*> popStack >>= prependStack tStack4 :: (StackValue -> StackValue -> StackValue -> StackValue -> Stack) -> ProgramTransition () tStack4 f = f <$> popStack <*> popStack <*> popStack <*> popStack >>= prependStack tStack6 :: (StackValue -> StackValue -> StackValue -> StackValue -> StackValue -> StackValue -> Stack) -> ProgramTransition () tStack6 f = f <$> popStack <*> popStack <*> popStack <*> popStack <*> popStack <*> popStack >>= prependStack arith1 :: (Int64 -> Int64) -> ProgramTransition () arith1 f = do i <- popInt pushStack $ encodeInt (f i) arith2 :: (Int64 -> Int64 -> Int64) -> ProgramTransition () arith2 f = do i <- popInt j <- popInt pushStack $ encodeInt (f i j) stackError :: ProgramTransition a stackError = programError "stack error" -- AltStack Primitives pushAltStack :: StackValue -> ProgramTransition () pushAltStack op = modify $ \p -> p { altStack = op:altStack p } popAltStack :: ProgramTransition StackValue popAltStack = get >>= \p -> case altStack p of a:as -> put p { altStack = as } >> return a [] -> programError "popAltStack: empty stack" incrementOpCount :: Int -> ProgramTransition () incrementOpCount i | i > maxOpcodes = programError "reached opcode limit" | otherwise = modify $ \p -> p { opCount = i + 1 } nopDiscourager :: ProgramTransition () nopDiscourager = do flgs <- ask if DISCOURAGE_UPGRADABLE_NOPS `elem` flgs then programError "Discouraged OP used." else return () -- Instruction Evaluation eval :: ScriptOp -> ProgramTransition () eval OP_NOP = return () eval OP_NOP1 = nopDiscourager >> return () eval OP_NOP2 = nopDiscourager >> return () eval OP_NOP3 = nopDiscourager >> return () eval OP_NOP4 = nopDiscourager >> return () eval OP_NOP5 = nopDiscourager >> return () eval OP_NOP6 = nopDiscourager >> return () eval OP_NOP7 = nopDiscourager >> return () eval OP_NOP8 = nopDiscourager >> return () eval OP_NOP9 = nopDiscourager >> return () eval OP_NOP10 = nopDiscourager >> return () eval OP_VERIFY = popBool >>= \case True -> return () False -> programError "OP_VERIFY failed" eval OP_RETURN = programError "explicit OP_RETURN" -- Stack eval OP_TOALTSTACK = popStack >>= pushAltStack eval OP_FROMALTSTACK = popAltStack >>= pushStack eval OP_IFDUP = tStack1 $ \a -> if decodeBool a then [a, a] else [a] eval OP_DEPTH = getStack >>= pushStack . encodeInt . fromIntegral . length eval OP_DROP = void popStack eval OP_DUP = tStack1 $ \a -> [a, a] eval OP_NIP = tStack2 $ \a _ -> [a] eval OP_OVER = tStack2 $ \a b -> [b, a, b] eval OP_PICK = popInt >>= (pickStack False . fromIntegral) eval OP_ROLL = popInt >>= (pickStack True . fromIntegral) eval OP_ROT = tStack3 $ \a b c -> [c, a, b] eval OP_SWAP = tStack2 $ \a b -> [b, a] eval OP_TUCK = tStack2 $ \a b -> [a, b, a] eval OP_2DROP = tStack2 $ \_ _ -> [] eval OP_2DUP = tStack2 $ \a b -> [a, b, a, b] eval OP_3DUP = tStack3 $ \a b c -> [a, b, c, a, b, c] eval OP_2OVER = tStack4 $ \a b c d -> [c, d, a, b, c, d] eval OP_2ROT = tStack6 $ \a b c d e f -> [e, f, a, b, c, d] eval OP_2SWAP = tStack4 $ \a b c d -> [c, d, a, b] -- Splice eval OP_SIZE = (fromIntegral . length <$> head <$> withStack) >>= pushInt -- Bitwise Logic eval OP_EQUAL = tStack2 $ \a b -> [encodeBool (a == b)] eval OP_EQUALVERIFY = eval OP_EQUAL >> eval OP_VERIFY -- Arithmetic eval OP_1ADD = arith1 (+1) eval OP_1SUB = arith1 (subtract 1) eval OP_NEGATE = arith1 negate eval OP_ABS = arith1 abs eval OP_NOT = arith1 $ \case 0 -> 1; _ -> 0 eval OP_0NOTEQUAL = arith1 $ \case 0 -> 0; _ -> 1 eval OP_ADD = arith2 (+) eval OP_SUB = arith2 $ flip (-) eval OP_BOOLAND = (&&) <$> ((0 /=) <$> popInt) <*> ((0 /=) <$> popInt) >>= pushBool eval OP_BOOLOR = (||) <$> ((0 /=) <$> popInt) <*> ((0 /=) <$> popInt) >>= pushBool eval OP_NUMEQUAL = (==) <$> popInt <*> popInt >>= pushBool eval OP_NUMEQUALVERIFY = eval OP_NUMEQUAL >> eval OP_VERIFY eval OP_NUMNOTEQUAL = (/=) <$> popInt <*> popInt >>= pushBool eval OP_LESSTHAN = (>) <$> popInt <*> popInt >>= pushBool eval OP_GREATERTHAN = (<) <$> popInt <*> popInt >>= pushBool eval OP_LESSTHANOREQUAL = (>=) <$> popInt <*> popInt >>= pushBool eval OP_GREATERTHANOREQUAL = (<=) <$> popInt <*> popInt >>= pushBool eval OP_MIN = min <$> popInt <*> popInt >>= pushInt eval OP_MAX = max <$> popInt <*> popInt >>= pushInt eval OP_WITHIN = within <$> popInt <*> popInt <*> popInt >>= pushBool where within y x a = (x <= a) && (a < y) eval OP_RIPEMD160 = tStack1 $ return . bsToSv . hash160BS . opToSv eval OP_SHA1 = tStack1 $ return . bsToSv . hashSha1BS . opToSv eval OP_SHA256 = tStack1 $ return . bsToSv . hash256BS . opToSv eval OP_HASH160 = tStack1 $ return . bsToSv . hash160BS . hash256BS . opToSv eval OP_HASH256 = tStack1 $ return . bsToSv . doubleHash256BS . opToSv eval OP_CODESEPARATOR = dropHashOpsSeparatedCode eval OP_CHECKSIG = do pubKey <- popStack sig <- popStack checker <- sigCheck <$> get hOps <- preparedHashOps pushBool $ checkMultiSig checker [ pubKey ] [ sig ] hOps -- Reuse checkMultiSig code eval OP_CHECKMULTISIG = do nPubKeys <- fromIntegral <$> popInt when (nPubKeys < 0 || nPubKeys > maxKeysMultisig) $ programError $ "nPubKeys outside range: " ++ show nPubKeys pubKeys <- popStackN $ toInteger nPubKeys nSigs <- fromIntegral <$> popInt when (nSigs < 0 || nSigs > nPubKeys) $ programError $ "nSigs outside range: " ++ show nSigs sigs <- popStackN $ toInteger nSigs nullDummyEnforcer void popStack -- spec bug checker <- sigCheck <$> get hOps <- preparedHashOps pushBool $ checkMultiSig checker pubKeys sigs hOps modify $ \p -> p { opCount = opCount p + length pubKeys } eval OP_CHECKSIGVERIFY = eval OP_CHECKSIG >> eval OP_VERIFY eval OP_CHECKMULTISIGVERIFY = eval OP_CHECKMULTISIG >> eval OP_VERIFY eval op = case constValue op of Just sv -> minimalPushEnforcer op >> pushStack sv Nothing -> programError $ "unexpected op " ++ show op minimalPushEnforcer :: ScriptOp -> ProgramTransition () minimalPushEnforcer op = do flgs <- ask if not $ MINIMALDATA `elem` flgs then return () else case checkMinimalPush op of True -> return () False -> programError $ "Non-minimal data: " ++ (show op) checkMinimalPush :: ScriptOp -> Bool -- Putting in a maybe monad to avoid elif chain checkMinimalPush ( OP_PUSHDATA payload optype ) = let l = BS.length payload v = ( BS.unpack payload ) !! 0 in if (BS.null payload) -- Check if could have used OP_0 || (l == 1 && v <= 16 && v >= 1) -- Could have used OP_{1,..,16} || (l == 1 && v == 0x81) -- Could have used OP_1NEGATE || (l <= 75 && optype /= OPCODE) -- Could have used direct push || (l <= 255 && l > 75 && optype /= OPDATA1) || (l > 255 && l <= 65535 && optype /= OPDATA2) then False else True checkMinimalPush _ = True -- | Checks the top of the stack for a minimal numeric representation -- if flagged to do so minimalStackValEnforcer :: ProgramTransition () minimalStackValEnforcer = do flgs <- ask s <- getStack let topStack = if null s then [] else head s if not $ MINIMALDATA `elem` flgs || null topStack then return () else case checkMinimalNumRep topStack of True -> return () False -> programError $ "Non-minimal stack value: " ++ (show topStack) -- | Checks if a stack value is the minimal numeric representation of -- the integer to which it decoes. Based on CScriptNum from Bitcoin -- Core. checkMinimalNumRep :: StackValue -> Bool checkMinimalNumRep [] = True checkMinimalNumRep s = let msb = last s l = length s in if -- If the MSB except sign bit is zero, then nonMinimal ( msb .&. 0x7f == 0 ) -- With the exception of when a new byte is forced by a filled last bit && ( l <= 1 || ( s !! (l-2) ) .&. 0x80 == 0 ) then False else True nullDummyEnforcer :: ProgramTransition () nullDummyEnforcer = do flgs <- ask topStack <- ( getStack >>= headOrError ) if ( NULLDUMMY `elem` flgs ) && ( not . null $ topStack ) then programError $ "Non-null dummy stack in multi-sig" else return () where headOrError s = if null s then programError "Empty stack where dummy op should be." else return ( head s ) -------------------------------------------------------------------------------- -- | Based on the IfStack, returns whether the script is within an -- evaluating if-branch. getExec :: ConditionalProgramTransition Bool getExec = and <$> getCond -- | Converts a `ScriptOp` to a program monad. conditionalEval :: ScriptOp -> ConditionalProgramTransition () conditionalEval scrpOp = do -- lift $ checkOpEnabled scrpOp lift $ checkPushData scrpOp e <- getExec eval' e scrpOp when (countOp scrpOp) $ lift $ join $ incrementOpCount <$> opCount <$> get lift checkStackSize where eval' :: Bool -> ScriptOp -> ConditionalProgramTransition () eval' True OP_IF = lift popStack >>= pushCond . decodeBool eval' True OP_NOTIF = lift popStack >>= pushCond . not . decodeBool eval' True OP_ELSE = flipCond eval' True OP_ENDIF = void popCond eval' True op = lift $ eval op eval' False OP_IF = pushCond False eval' False OP_NOTIF = pushCond False eval' False OP_ELSE = flipCond eval' False OP_ENDIF = void popCond eval' False OP_CODESEPARATOR = lift $ eval OP_CODESEPARATOR eval' False OP_VER = return () eval' False op | isDisabled op = lift $ disabled op | otherwise = return () -- | Builds a Script evaluation monad. evalAll :: [ ScriptOp ] -> ConditionalProgramTransition () evalAll ops = do mapM_ conditionalEval ops cond <- getCond unless (null cond) (lift $ programError "ifStack not empty") checkPushOnly :: [ ScriptOp ] -> ConditionalProgramTransition () checkPushOnly ops | not (all checkPushOp ops) = lift $ programError "only push ops allowed" | otherwise = return () where checkPushOp op = case constValue op of Just _ -> True Nothing -> False checkStack :: Stack -> Bool checkStack (x:_) = decodeBool x checkStack [] = False isPayToScriptHash :: [ ScriptOp ] -> [ Flag ] -> Bool isPayToScriptHash [OP_HASH160, OP_PUSHDATA bytes OPCODE, OP_EQUAL] flgs = ( P2SH `elem` flgs ) && ( BS.length bytes == 20 ) isPayToScriptHash _ _ = False stackToScriptOps :: StackValue -> [ ScriptOp ] stackToScriptOps sv = let script = decodeOrFail $ BSL.pack sv in case script of Left _ -> [] -- Maybe should propogate the error some how Right (_,_,s) -> scriptOps s -- -- exported functions execScript :: Script -- ^ scriptSig ( redeemScript ) -> Script -- ^ scriptPubKey -> SigCheck -- ^ signature verification Function -> [ Flag ] -- ^ Evaluation flags -> Either EvalError Program execScript scriptSig scriptPubKey sigCheckFcn flags = let sigOps = scriptOps scriptSig pubKeyOps = scriptOps scriptPubKey emptyProgram = Program { stack = [], altStack = [], hashOps = pubKeyOps, sigCheck = sigCheckFcn, opCount = 0 } checkSig | isPayToScriptHash pubKeyOps flags = checkPushOnly sigOps | SIGPUSHONLY `elem` flags = checkPushOnly sigOps | otherwise = return () checkKey | BSL.length (encode scriptPubKey) > fromIntegral maxScriptSize = lift $ programError "pubKey > maxScriptSize" | otherwise = return () redeemEval = checkSig >> evalAll sigOps >> lift (stack <$> get) pubKeyEval = checkKey >> evalAll pubKeyOps >> lift get p2shEval [] = lift $ programError "PayToScriptHash: no script on stack" p2shEval (sv:_) = evalAll (stackToScriptOps sv) >> lift get in do s <- evalConditionalProgram redeemEval [] emptyProgram flags p <- evalConditionalProgram pubKeyEval [] emptyProgram { stack = s } flags if ( checkStack . runStack $ p ) && ( isPayToScriptHash pubKeyOps flags ) && ( not . null $ s ) then evalConditionalProgram (p2shEval s) [] emptyProgram { stack = drop 1 s, hashOps = stackToScriptOps $ head s } flags else return p evalScript :: Script -> Script -> SigCheck -> [ Flag ] -> Bool evalScript scriptSig scriptPubKey sigCheckFcn flags = case execScript scriptSig scriptPubKey sigCheckFcn flags of Left _ -> False Right p -> checkStack . runStack $ p runStack :: Program -> Stack runStack = stack -- | A wrapper around 'verifySig' which handles grabbing the hash type verifySigWithType :: Tx -> Int -> [ ScriptOp ] -> TxSignature -> PubKey -> Bool verifySigWithType tx i outOps txSig pubKey = let outScript = Script outOps h = txSigHash tx outScript i ( sigHashType txSig ) in verifySig h ( txSignature txSig ) pubKey -- | Uses `evalScript` to check that the input script of a spending -- transaction satisfies the output script. verifySpend :: Tx -- ^ The spending transaction -> Int -- ^ The input index -> Script -- ^ The output script we are spending -> [ Flag ] -- ^ Evaluation flags -> Bool verifySpend tx i outscript flags = let scriptSig = decode' . scriptInput $ txIn tx !! i verifyFcn = verifySigWithType tx i in evalScript scriptSig outscript verifyFcn flags
nuttycom/haskoin
Network/Haskoin/Script/Evaluator.hs
unlicense
27,294
0
18
7,412
7,742
3,993
3,749
561
20
{-# LANGUAGE BangPatterns, OverloadedStrings #-} -- -- Copyright : (c) T.Mishima 2014 -- License : Apache-2.0 -- module Hinecraft.Rendering.WorldView ( WorldViewVHdl (blockTexture) , initWorldView , drawWorldView , genChunkVAO , WorldVAOList , initWorldVAOList , getBlockVAOList , setBlockVAOList , updateVAOlist -- , appendVAO , deleteVAO ) where --import Data.Tree import Graphics.Rendering.OpenGL as GL import qualified Graphics.GLUtil as GU import qualified Graphics.GLUtil.Camera3D as GU3 --import qualified Graphics.GLUtil.Camera2D as GU2 --import Linear ( M44 ) -- eye4 import Linear.V3 import Linear.V4 import Linear.Matrix import qualified Data.Map as M import Control.Monad ( forM_, forM , foldM {-,when, unless,void-} ) --import Debug.Trace as Dbg import Data.IORef import Control.Applicative import Hinecraft.Types import Hinecraft.Model import Hinecraft.Rendering.Util import Hinecraft.Rendering.Types import Hinecraft.Rendering.WithBasicShader as BSd import Hinecraft.Rendering.WithSimpleShader as SSd data WorldViewVHdl = WorldViewVHdl { basicShader :: BasicShaderProg , simpleShader :: SimpleShaderProg , envCube :: GU.VAO , blockTexture :: TextureObject , skyTexture :: TextureObject , blkVAOList :: IORef WorldVAOList , blkCursol :: GU.VAO , shadowBuf :: (TextureObject,FramebufferObject) --, starTexture :: } type WorldVAOList = M.Map (Int,Int) [Maybe (Int,GU.VAO)] updateVAOlist :: WorldViewVHdl -> [(((Int, Int), Int),SurfacePos)] -> IO () updateVAOlist wvhdl sufList = do !vao <- getBlockVAOList wvhdl !newvao <- foldM fn vao sufList setBlockVAOList wvhdl newvao where fn wvlst ((ij,bNo'),sfs) = case M.lookup ij wvlst of Just d -> do case d !! bNo' of Just (_,v) -> GU.deleteVAO v Nothing -> return () vao <- genChunkVAO wvhdl sfs let newVAO = take bNo' d ++ [vao] ++ drop (bNo' + 1) d return $! M.update (upfn newVAO) ij wvlst Nothing -> return wvlst upfn nv _ = Just nv appendVAO :: WorldViewVHdl -> [(ChunkIdx,[SurfacePos])] -> IO () appendVAO wvhdl sufList = do !vaos <- getBlockVAOList wvhdl !newvaos <- foldM fn vaos sufList setBlockVAOList wvhdl newvaos where fn vaos (ij,sfs) = do vaos' <- mapM (\ s -> do genChunkVAO wvhdl s) sfs return $ M.insert ij vaos' vaos deleteVAO :: WorldViewVHdl -> [ChunkIdx] -> IO () deleteVAO wvhdl cidxs = do !vaos <- getBlockVAOList wvhdl setBlockVAOList wvhdl $ foldl fn vaos cidxs where fn vaos ij = M.delete ij vaos getBlockVAOList :: WorldViewVHdl -> IO WorldVAOList getBlockVAOList vwHdl = readIORef (blkVAOList vwHdl) setBlockVAOList :: WorldViewVHdl -> WorldVAOList -> IO () setBlockVAOList vwHdl = writeIORef (blkVAOList vwHdl) shadowMapSize :: TextureSize2D shadowMapSize = TextureSize2D 512 512 makeShadowBuff :: IO (TextureObject,FramebufferObject) makeShadowBuff = do activeTexture $= TextureUnit 1 b <- genObjectName :: IO TextureObject textureBinding Texture2D $= Just b texImage2D Texture2D NoProxy 0 DepthComponent' shadowMapSize 0 (PixelData DepthComponent UnsignedByte GU.offset0) -- nullPtr) textureFilter Texture2D $= ((Nearest, Nothing), Nearest) textureWrapMode Texture2D S $= (Repeated, ClampToEdge) textureWrapMode Texture2D T $= (Repeated, ClampToEdge) textureBorderColor Texture2D $= Color4 1.0 0.0 0.0 (0.0::GLfloat) textureCompareMode Texture2D $= Just Less f <- genObjectName :: IO FramebufferObject bindFramebuffer Framebuffer $= f framebufferTexture2D Framebuffer DepthAttachment Texture2D b 0 drawBuffer $= NoBuffers readBuffer $= NoBuffers bindFramebuffer Framebuffer $= defaultFramebufferObject activeTexture $= TextureUnit 0 GU.printErrorMsg "GLerror [make FB]" return (b,f) initWorldView :: FilePath -> IO WorldViewVHdl initWorldView home = do !bsh <- initShaderProgram home !ssh <- initShaderProgram home !blks <- loadTexture blkPng !sky <- loadTexture skyPng !cb <- genEnvCubeVAO bsh !vao <- newIORef M.empty !bCur <- genBlockCursol ssh !sbf <- makeShadowBuff return $! WorldViewVHdl { basicShader = bsh , simpleShader = ssh , envCube = cb , blockTexture = blks , skyTexture = sky , blkVAOList = vao , blkCursol = bCur , shadowBuf = sbf } where !blkPng = home ++ "/.Hinecraft/terrain.png" !skyPng = home ++ "/.Hinecraft/mcpatcher/sky/world0/cloud1.png" --starPng = home ++ "/.Hinecraft/mcpatcher/sky/world0/star1.png" initWorldVAOList :: WorldViewVHdl -> [((Int, Int), [SurfacePos])] -> IO () initWorldVAOList wvhdl suflst = do !vao <- M.fromList <$> mapM (\ (ij,slst) -> do ds <- forM slst (genChunkVAO wvhdl) return (ij,ds) ) suflst writeIORef (blkVAOList wvhdl) vao drawShadoWorldView :: BasicShaderProg -> WorldViewVHdl -> WorldVAOList -> M44 GLfloat -> [(TextureObject,GLuint)] -> IO () drawShadoWorldView pg wvhdl vaos mvpMat tex = do alphaFunc $= Nothing bindFramebuffer Framebuffer $= fbo colorMask $= (Color4 Disabled Disabled Disabled Disabled) setShadowSW pg 1 cullFace $= Just Front GL.clear [GL.ColorBuffer, GL.DepthBuffer] setMVPMatrix pg mvpMat setLightMode pg 0 setColorBlendMode pg 0 enableTexture pg False activeTexture $= TextureUnit 0 forM_ vs (\ (_,vas) -> mapM_ (\ v -> renderChunk pg v tex) vas) --mapM_ (\ v -> renderChunkS pg v) vas) setShadowSW pg 0 bindFramebuffer Framebuffer $= defaultFramebufferObject alphaFunc $= Just (Greater, 0.2) where !vs = M.toList vaos !(tbo,fbo) = shadowBuf wvhdl drawWorldView :: WorldViewVHdl -> (Int,Int) -> GuiResource -> WorldVAOList -> UserStatus -> Maybe (WorldIndex,Surface) -> Double -> IO () drawWorldView wvhdl (w,h) res vaos usrStat' pos sunDeg = do useShader pg $ \ shaderPrg -> do GU.withViewport (Position 0 0) (Size (fromIntegral shW) (fromIntegral shH)) $ do drawShadoWorldView pg wvhdl vaos shadowMat tex2 GU.withViewport (Position 0 0) (Size (fromIntegral w) (fromIntegral h)) $ do -- Draw 3D cube colorMask $= (Color4 Enabled Enabled Enabled Enabled) GL.clear [GL.ColorBuffer, GL.DepthBuffer] -- ### draw skybox ### cullFace $= Nothing setMVPMatrix shaderPrg mvpMats renderEnvCube shaderPrg cbVao skyTex -- ### draw grund ### setGlobalLightParam shaderPrg sunDeg' cullFace $= Just Back --Just Front Just FrontAndBack -- setTMatrix shaderPrg tMat setMVPMatrix shaderPrg mvpMatp setLightMode shaderPrg 1 setColorBlendMode shaderPrg 0 enableTexture shaderPrg True forM_ vs (\ (_,vas) -> mapM_ (\ v -> renderChunk shaderPrg v tex) vas) cullFace $= Nothing -- Cursol 選択された面を強調 useShader spg $ \ shaderPrg -> do case pos of Just ((px,py,pz),s) -> do lineWidth $= 0.5 setProjViewMat shaderPrg pMat setCamParam shaderPrg $ GU3.pan ury $ GU3.tilt urx $ GU3.dolly (V3 (ux - fromIntegral px) ((uy + 1.5) - fromIntegral py) (uz - fromIntegral pz)) GU3.fpsCamera renderBlockCursol shaderPrg bCurVAO s Nothing -> return () where TextureSize2D shW shH = shadowMapSize !(tbo,_) = shadowBuf wvhdl !blkTex = blockTexture wvhdl !tex = [(blkTex,0),(tbo,1)] !tex2 = [(blkTex,0)] !pg = basicShader wvhdl !spg = simpleShader wvhdl !bCurVAO = blkCursol wvhdl !vs = M.toList vaos !cbVao = envCube wvhdl !skyTex = skyTexture wvhdl d2f (a,b,c) = (realToFrac a, realToFrac b, realToFrac c) !(ux,uy,uz) = d2f $ userPos usrStat' !(urx,ury,_) = d2f $ userRot usrStat' :: (GLfloat,GLfloat,GLfloat) !dpMat = GU3.projectionMatrix (GU3.deg2rad 15) 1.0 (sunLen - 100) (sunLen + 100) !sunDeg' | sunDeg > 5 && sunDeg < 170 = 180 - (realToFrac sunDeg) | otherwise = 270 ::GLfloat !sunLen = 400 :: GLfloat !sunY = sunLen * (sin $ GU3.deg2rad sunDeg') !sunZ = sunLen * (cos $ GU3.deg2rad sunDeg') !dvMat = GU3.camMatrix $ GU3.tilt (-sunDeg') -- $ GU3.dolly (V3 (0::GLfloat) sunY sunZ) $ GU3.dolly (V3 spx sunY (sunZ + spz)) GU3.fpsCamera !(spx,spz) = ( fromIntegral $ 32 * round (ux / 32) , fromIntegral $ 32 * round (uz / 32)) !mMat = V4 (V4 1.0 0.0 0.0 0.0) (V4 0.0 1.0 0.0 0.0) (V4 0.0 0.0 1.0 0.0) (V4 0.0 0.0 0.0 1.0) !shadowMat = (dpMat !*! dvMat !*! mMat) !pMat = GU3.projectionMatrix (GU3.deg2rad 60) (fromIntegral w/ fromIntegral h) 0.1 (1000::GLfloat) !vMats = GU3.camMatrix $ GU3.pan ury $ GU3.tilt urx GU3.fpsCamera !vMatp = GU3.camMatrix $ GU3.pan ury $ GU3.tilt urx $ GU3.dolly (V3 ux (uy + 1.5) uz) GU3.fpsCamera !mvpMats = pMat !*! vMats !*! mMat !mvpMatp = pMat !*! vMatp !*! mMat !tMat = bMat !*! shadowMat !bMat = V4 (V4 0.5 0.0 0.0 0.5) (V4 0.0 0.5 0.0 0.5) (V4 0.0 0.0 0.5 0.5) (V4 0.0 0.0 0.0 1.0) genBlockCursol :: SimpleShaderProg -> IO GU.VAO genBlockCursol sh = makeSimpShdrVAO sh vertLst vertClrLst texCdLst where !vertLst = concatMap ajust $ concat vlst !vertClrLst = concat $ replicate (4 * 6) [0.1,0.1,0.1,1.0] !texCdLst = concat $ replicate (4 * 6) [0.0,1.0] extnd v = if v > 0 then v + 0.05 else v - 0.05 ajust (a,b,c) = [ extnd a, extnd b, extnd c] !vlst = map (fst . getVertexList Cube ) [STop,SBottom,SFront,SBack ,SRight,SLeft] renderBlockCursol :: SimpleShaderProg -> GU.VAO -> Surface -> IO () renderBlockCursol sh vao s = do currentProgram $= Just (GU.program shprg') --GL.clientState GL.VertexArray $= GL.Enabled enableTexture sh False GU.withVAO vao $ drawArrays LineLoop (calcIdx s) 4 currentProgram $= Nothing where !shprg' = getShaderProgram sh calcIdx f = case f of STop -> 0 SBottom -> 4 SFront -> 8 SBack -> 12 SRight -> 16 SLeft -> 20 renderChunk :: BasicShaderProg -> Maybe (Int,GU.VAO) -> [(TextureObject,GLuint)] -> IO () renderChunk _ Nothing _ = return () renderChunk _ (Just (0,_)) _ = return () renderChunk sh (Just (len,vao)) tex = GU.withVAO vao $ GU.withTexturesAt Texture2D tex $ drawArrays Quads 0 $ fromIntegral len * 4 renderChunkS :: BasicShaderProg -> Maybe (Int,GU.VAO) -> IO () renderChunkS _ Nothing = return () renderChunkS _ (Just (0,_)) = return () renderChunkS sh (Just (len,vao)) = GU.withVAO vao $ drawArrays Quads 0 $ fromIntegral len * 4 genChunkVAO :: WorldViewVHdl -> SurfacePos -> IO (Maybe (Int,GU.VAO)) genChunkVAO wvhdl = genChunkVAO' sh where !sh = basicShader wvhdl genChunkVAO' :: BasicShaderProg -> SurfacePos -> IO (Maybe (Int,GU.VAO)) genChunkVAO' _ [] = return Nothing genChunkVAO' sh bsf = do vao <- makeBasicShdrVAO sh (concat vertlst) (concat clrlst) (concat normlst) (concat coordlst) return $! Just (ndnum, vao) where !(clrlst, normlst, coordlst, vertlst, ndnum) = foldr (\ e (cs,ns,cds,vs,s) -> let (c,n,cd,v,num) = genElem e in (c:cs,n:ns,cd:cds,v:vs,num+s)) ([],[],[],[],0) bsf -- genElem :: (WorldIndex, BlockIDNum, [Surface]) -> ([GLfloat],[GLfloat],[GLfloat],[GLfloat],Int) genElem ((x,y,z),bid,fs) | sp == Cross = ( colorListCross, normListCross, coordListCross , vertexListCross, 4 * 2) | otherwise = ( colorList fs, normList fs, coordList fs , vertexList fs ,4 * length fs) where !sp = shape $ getBlockInfo bid colorList :: [Surface] -> [GLfloat] colorList = concatMap (\ f -> genColorList $ setColor $ case f of STop -> 0 SBottom -> 1 SRight -> 2 SLeft -> 3 SFront -> 4 SBack -> 5) colorListCross :: [GLfloat] colorListCross = concatMap (genColorList . setColor) [0,0] normList :: [Surface] -> [GLfloat] normList = concatMap (\ f -> genNormList $ case f of STop -> (0,1,0) SBottom -> (0,-1,0) SRight -> (1,0,0) SLeft -> (-1,0,0) SFront -> (0,0,-1) SBack -> (0,0,1)) normListCross :: [GLfloat] normListCross = concatMap genNormList [(1,1,1),(-1,1,1)] coordList :: [Surface] -> [GLfloat] coordList = concatMap (\ f -> let (_,uv) = getVertexList sp f in genCoordList (case f of STop -> getTxid 0 SBottom -> getTxid 1 SRight -> getTxid 2 SLeft -> getTxid 3 SFront -> getTxid 4 SBack -> getTxid 5 ) uv ) where texLst = textureIndex $ getBlockInfo bid -- Top | Bottom | Right | Left | Front | Back getTxid i | i < length texLst = texLst !! i | otherwise = (0,0) coordListCross :: [GLfloat] coordListCross = genCoordList texLst $ snd $ getVertexList sp STop where texLst = head $ textureIndex $ getBlockInfo bid vertexList :: [Surface] -> [GLfloat] vertexList = concatMap (\ f -> let (vs,_) = getVertexList sp f in genVertLst vs ) vertexListCross :: [GLfloat] vertexListCross = genVertLst $ fst $ getVertexList sp STop d2fv3 :: (Double,Double,Double) -> VrtxPos3D d2fv3 (a,b,c) = ( realToFrac a, realToFrac b, realToFrac c) setColor i | i < length colorLst = d2fv3 $ colorLst !! i | otherwise = (1.0,1.0,1.0) where colorLst = bcolor (getBlockInfo bid) genColorList :: (GLfloat,GLfloat,GLfloat) -> [GLfloat] genColorList (r,g,b) = (concat . replicate 4) [r,g,b,1.0] genNormList :: (GLfloat,GLfloat,GLfloat) -> [GLfloat] genNormList (nx,ny,nz) = (concat . replicate 4) [nx,ny,nz] genCoordList :: (Int,Int) -> [(GLfloat,GLfloat)] -> [GLfloat] genCoordList (i',j') = concatMap (\ (u,v) -> [i * (1/16) + (1/16) * u , j * (1/16) + (1/16) * v ]) where i = fromIntegral i' ; j = fromIntegral j' genVertLst :: [(GLfloat,GLfloat,GLfloat)] -> [GLfloat] genVertLst = concatMap (\ (x', y', z') -> [ x' + fromIntegral x , y' + fromIntegral y , z' + fromIntegral z ] ) renderEnvCube :: BasicShaderProg -> GU.VAO -> TextureObject -> IO () renderEnvCube sh vao tex = do --currentProgram $= Just (GU.program shprg') --GL.clientState GL.VertexArray $= GL.Enabled setLightMode sh 0 setColorBlendMode sh 1 enableTexture sh True GU.withVAO vao $ GU.withTextures2D [tex] $ drawArrays Quads 0 (4 * 6) --currentProgram $= Nothing where !shprg' = getShaderProgram sh genEnvCubeVAO :: BasicShaderProg -> IO GU.VAO genEnvCubeVAO sh = makeBasicShdrVAO sh cubeVert qColor qnorm qTexCoord where qColor :: [GL.GLfloat] qColor = concat $ replicate 24 [ (180/255),(226/255),(255/255), 1.0 ] p0,p1,p2,p3,p4,p5,p6,p7 :: [GLfloat] {- !p0 = [ -0.5, -0.25, -0.5] !p1 = [ 0.5, -0.25, -0.5] !p2 = [ 0.5, -0.25, 0.5] !p3 = [ -0.5, -0.25, 0.5] -} !p0 = [ -0.5, -0.4, -0.5] !p1 = [ 0.5, -0.4, -0.5] !p2 = [ 0.5, -0.4, 0.5] !p3 = [ -0.5, -0.4, 0.5] !p4 = [ 0.5, 0.5, 0.5] !p5 = [ -0.5, 0.5, 0.5] !p6 = [ -0.5, 0.5, -0.5] !p7 = [ 0.5, 0.5, -0.5] cubeVert :: [GLfloat] !cubeVert = map (* 1000) $ concat [ p6, p7, p1, p0 -- Front , p7, p4, p2, p1 -- Right , p4, p5, p3, p2 -- Back , p5, p6, p0, p3 -- Left , p7, p6, p5, p4 -- Top , p0, p1, p2 ,p3 -- Bottom ] qTexCoord :: [GLfloat] !qTexCoord = [ 1/3, 1/2 , 2/3, 1/2 , 2/3, 1.0 , 1/3, 1.0 , 2/3, 1/2 , 1.0, 1/2 , 1.0, 1.0 , 2/3, 1.0 , 2/3, 0.0 , 1.0, 0.0 , 1.0, 1/2 , 2/3, 1/2 , 0.0, 1/2 , 1/3, 1/2 , 1/3, 1.0 , 0.0, 1.0 , 2/3, 1/2 , 1/3, 1/2 , 1/3, 0.0 , 2/3, 0.0 , 0.0, 0.0 , 1/3, 0.0 , 1/3, 1/2 , 0.0, 1/2 ] qnorm = [ 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 , 0, 0, 0 ]
tmishima/Hinecraft
Hinecraft/Rendering/WorldView.hs
apache-2.0
17,007
0
27
4,980
6,172
3,246
2,926
412
16
import Data.List (delete, genericIndex, genericReplicate, genericTake, nub, permutations, sortOn, tails) import Data.Set (Set) import qualified Data.Set as Set import Helpers.SetHelpers (flatMap) import Helpers.ListHelpers (cartesianProduct) import qualified Data.MemoCombinators as Memo type Base = [Integer] type ConfigurationState = Set Base newtype Strategy = Intermediate (Set (Base, Strategy)) deriving (Show, Eq, Ord) canonical :: Integer -> [Integer] -> [Integer] canonical n l = minimum $ concatMap f $ necklaces l where f necklace = map incrementNecklace [1..n] where incrementNecklace i = map ((`mod` n) . (+i)) necklace necklaces :: [Integer] -> [[Integer]] necklaces l = map (take len) $ take len initialSegments where len = length l initialSegments = tails $ concat $ repeat l -- This is slow and should be memoized. configurationSum :: Integer -> [Integer] -> [Integer] -> Set [Integer] configurationSum = Memo.memo3 Memo.integral (Memo.list Memo.integral) (Memo.list Memo.integral) configurationSum' where configurationSum' n c1 c2 = Set.fromList $ map (canonical n . zipWith (+) c1) $ necklaces c2 zero :: Integer -> [Integer] zero n = genericReplicate n 0 initialStates :: Integer -> Set [Integer] initialStates n = Set.delete (zero n) $ Set.fromList configurations where configurations = map (canonical n) $ cartesianProduct n [1..n] addAll :: Integer -> Integer -> [Integer] -> Set [Integer] -> Set [Integer] addAll n k configuration configurationState = Set.delete (zero (n^k)) $ flatMap (configurationSum n configuration) configurationState -- nextGeneration :: Integer -> ConfigurationState -> [(Base, ConfigurationState)] -- -- map (\move -> (move, addAll move nondeterministicState)) -- nextGeneration n configurationState = map (\move -> (move, addAllN move configurationState)) moveList where -- moveList = essentiallyUniqueStates n -- addAllN = addAll n -- essentiallyUniqueStates :: Integer -> [[Integer]] -- essentiallyUniqueStates n = recurse [] (Set.toList $ initialStates n) where -- f = configurationSum n -- zero' = zero n -- recurse known [] = known -- recurse known (c:cs) = if essentiallyUnique then recurse (c:known) cs else recurse known cs where -- essentiallyUnique = Set.notMember zero' $ flatMap (f c) $ Set.fromList known -- strategy n = recurse (Set.singleton state) state where -- state = initialStates n -- ng = nextGeneration n -- recurse :: Set ConfigurationState -> ConfigurationState -> Strategy -- recurse knownStates currentGeneration -- | Set.null currentGeneration = error "we're done!" -- | otherwise = Intermediate $ Set.fromList iteration where -- iteration = map (\(b, nds) -> (b, recurse newNondeterministicStates nds)) nextGen where -- nextGen :: [(Base, ConfigurationState)] -- nextGen = filter ((`Set.notMember` knownStates) . snd) $ ng currentGeneration -- newNondeterministicStates :: Set ConfigurationState -- newNondeterministicStates = Set.union (Set.map snd $ Set.fromList nextGen) knownStates -- This gives the switching strategy for C_p \wr C_p. switchingStrategy :: Integer -> Integer -> [[Integer]] switchingStrategy n k = recurse [] 1 where recurse strategy c | c == n^k = strategy | otherwise = recurse newStrategy (c + 1) where newStrategy = (strategy ++) . concat . genericReplicate (n-1) $ move:strategy where move = genericTake (n^k) $ map (`mod` n) $ genericIndex pascalsDiagonals c pascalsDiagonals :: [[Integer]] pascalsDiagonals = recurse $ repeat 1 where recurse :: [Integer] -> [[Integer]] recurse l = l : recurse (scanl1 (+) l) -- initialStates' :: Set Int initialStates' n k = Set.delete (replicate n 0) $ Set.fromList configurations where configurations = map (canonical k) $ cartesianProduct n [1..k]
peterokagey/haskellOEIS
src/Sandbox/Sami/SpinningSwitches/CyclicGroup2.hs
apache-2.0
3,839
0
15
682
909
495
414
40
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GADTs #-} module Lycopene.Core.Sprint where import Data.Char (toLower) import qualified Data.Text as T import GHC.Generics import Data.Aeson (ToJSON(..), FromJSON(..)) import Data.Aeson.Types (typeMismatch, Value(..), Parser , genericToEncoding, genericParseJSON, Options(..) , defaultOptions, withText) import Lycopene.Core.Scalar import Lycopene.Freer (Freer, liftR, foldFreer) import Lycopene.Core.Store (Change) import Lycopene.Core.Project (ProjectId) import Lycopene.Core.Identifier (generate, nameIdGen) import Lycopene.Lens (Lens, set, field) type SprintId = Identifier data SprintStatus = SprintFinished | SprintRunning deriving (Show, Eq, Ord) instance ToJSON SprintStatus where toJSON SprintFinished = toJSON "finished" toJSON SprintRunning = toJSON "running" instance FromJSON SprintStatus where parseJSON = withText "running|finished" $ \t -> case T.unpack t of "running" -> return SprintRunning "finished" -> return SprintFinished _ -> fail "running|finished" -- | A time box which includes zero or more issues. data Sprint = Sprint { sprintId :: !SprintId , sprintName :: !Name , sprintDescription :: !Description , sprintStartOn :: !(Maybe Date) , sprintEndOn :: !(Maybe Date) , sprintStatus :: !SprintStatus } deriving (Show, Generic) sprintOptions :: Options sprintOptions = defaultOptions { fieldLabelModifier = map toLower . drop (length "sprint") } instance ToJSON Sprint where toEncoding = genericToEncoding sprintOptions instance FromJSON Sprint where parseJSON = genericParseJSON sprintOptions instance Eq Sprint where x == y = (sprintId x) == (sprintId y) -- Minimal lenses for Sprint -- ================================================================== _sprintStatus :: Lens Sprint SprintStatus _sprintStatus = field sprintStatus (\a s -> s { sprintStatus = a }) _sprintStartOn :: Lens Sprint (Maybe Date) _sprintStartOn = field sprintStartOn (\a s -> s { sprintStartOn = a }) _sprintEndOn :: Lens Sprint (Maybe Date) _sprintEndOn = field sprintEndOn (\a s -> s { sprintEndOn = a }) -- | data SprintF a where -- | AddSprintF :: ProjectId -> Sprint -> SprintF Sprint -- | AddDefaultSprintF :: ProjectId -> Sprint -> SprintF Sprint -- | RemoveSprintF :: Sprint -> SprintF Sprint -- | UpdateSprintF :: Change Sprint -> Sprint -> SprintF Sprint -- | FetchByNameSprintF :: Name -> Name -> SprintF Sprint -- | FetchByStatusSprintF :: Name -> SprintStatus -> SprintF [Sprint] type SprintM = Freer SprintF -- FIXME: IMPLEMENT sprint primitives. newBacklog :: ProjectId -> SprintM Sprint newBacklog p = let new = newSprint "backlog" Nothing Nothing Nothing in liftR $ AddDefaultSprintF p new newSprint :: Name -> Description -> Maybe Date -> Maybe Date -> Sprint newSprint n d s e = let next = generate nameIdGen ("sprint", n) in Sprint next n d s e SprintRunning fetchByNameSprint :: Name -> Name -> SprintM Sprint fetchByNameSprint pj sp = liftR $ FetchByNameSprintF pj sp fetchByStatusSprint :: Name -> SprintStatus -> SprintM [Sprint] fetchByStatusSprint pj st = liftR $ FetchByStatusSprintF pj st addSprint = undefined updateSprint f = undefined removeSprint = undefined fetchByIdSprint = undefined fetchAllSprint = undefined
utky/lycopene
src/Lycopene/Core/Sprint.hs
apache-2.0
3,499
0
11
755
939
513
426
93
1
{- Copyright 2014 David Farrell <[email protected]> - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -} module Core.Nick (plugin) where import Data.Maybe (fromMaybe) import Data.Char (toUpper) import qualified Data.Map as M import Control.Monad.State import IRCD.Types import IRCD.Env import IRCD.Clients import IRCD.Helper import Hoist plugin :: Plugin plugin = defaultPlugin {handlers=[CommandHandler "NICK" nickHandler]} nickHandler :: HandlerSpec nickHandler src@(ClientSrc client) (Message _ _ _ (nick':_)) = do nicks <- gets (byNick . envClients) if upperNick `M.notMember` nicks || (upperNick == map toUpper clientNick && nick' /= clientNick) then return [NickChangeAction src (nick client) nick' ioChange] else return [GenericAction $ reply_ src "Nickname is already in use"] where upperNick = map toUpper nick' clientNick = fromMaybe "" (nick client) ioChange = do hoistState $ modify $ mapEnvClients (replaceClient client client {nick=Just nick'}) when (registered client) $ reply_ src ("NICK " ++ nick') nickHandler src _ = return [GenericAction $ reply_ src "No nickname given"]
shockkolate/lambdircd
plugins/Core/Nick.hs
apache-2.0
1,663
0
15
312
353
188
165
24
2
----------------------------------------------------------------------------- -- | -- Module : XMonad.Prompt.Pass -- Copyright : (c) 2014 Ondřej Súkup -- : (c) 2014 Moritz Ulrich -- License : -- -- -- Maintainer : Ondřej Súkup -- Stability : unstable -- Portability : unportable -- -- Provides promt for Pass - CLI password storage -- ----------------------------------------------------------------------------- module XMonad.Prompt.Pass ( -- * Usage -- $usage passPrompt ) where -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Prompt -- > import XMonad.Prompt.Pass -- -- Then add a keybinding for 'passPrompt': -- -- > , ((modMask x .|. controlMask, xK_h), passPrompt defaultXPconfig) -- -- For detailed instructions on editing your key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings". -- -- import System.Environment import System.FilePath.Find import System.FilePath.Posix import XMonad import XMonad.Prompt data Pass = Pass instance XPrompt Pass where showXPrompt Pass = "Pass: " commandToComplete _ c = c nextCompletion _ = getNextCompletion passPrompt :: XPConfig -> X () passPrompt c = do li <- io getPasswords mkXPrompt Pass c (mkComplFunFromList li) selectPassword selectPassword :: String -> X () selectPassword s = spawn $ "pass -c " ++ s getPasswords :: IO [String] getPasswords = do home <- getEnv "HOME" let passwordStore = home </> ".password-store" entries <- find System.FilePath.Find.always (fileName ~~? "*.gpg") passwordStore return $ map (makeRelative passwordStore . dropExtension) entries
mimi1vx/dotfiles
home/.xmonad/lib/XMonad/Prompt/Pass.hs
bsd-2-clause
1,783
0
11
409
275
156
119
24
1
import System.Environment data PaSym = PaLeft | PaRight | PaText String deriving (Show) -- Lexical analysis lxChar :: Char -> PaSym lxChar '(' = PaLeft lxChar ')' = PaRight lxChar ch = PaText [ch] lxString :: String -> [PaSym] lxString = foldr lxFold [] . map lxChar lx :: String -> [PaSym] lx = concat . map lxString . words lxFold :: PaSym -> [PaSym] -> [PaSym] lxFold PaLeft xs = [PaLeft] ++ xs lxFold PaRight xs = [PaRight] ++ xs lxFold (PaText a) (PaText b:xs) = [PaText (a++b)] ++ xs lxFold (PaText a) xs = [PaText a] ++ xs -- Semantic analysis smCount :: [PaSym] -> Int smCount = foldl (\acc sym -> if acc < 0 then -1 else acc + value sym) 0 where value PaLeft = 1 value PaRight = -1 value _ = 0 sm :: [PaSym] -> Bool sm = (== 0) . smCount -- Entry point main :: IO () main = do params <- getArgs if params == [] then errorUsage else print $ sm (lx (unwords params)) where errorUsage = do putStrLn "Input S-Expression as parameter"
carlmartus/helloworlds
haskell/sexp.hs
bsd-2-clause
1,010
0
13
256
428
227
201
29
4
-- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings where import Prelude import Text.Shakespeare.Text (st) import Language.Haskell.TH.Syntax import Database.Persist.Postgresql (PostgresConf) import Yesod.Default.Config import Yesod.Default.Util import Data.Text (Text) import Settings.Development import Data.Default (def) import Text.Hamlet import Yesod hiding (setTitle) import qualified Data.Text as T -- | Which Persistent backend this site is using. type PersistConf = PostgresConf -- Static setting below. Changing these requires a recompile -- | The location of static files on your system. This is a file system -- path. The default value works properly with your scaffolded site. staticDir :: FilePath staticDir = "static" -- | The base URL for your static files. As you can see by the default -- value, this can simply be "static" appended to your application root. -- A powerful optimization can be serving static files from a separate -- domain name. This allows you to use a web server optimized for static -- files, more easily set expires and cache values, and avoid possibly -- costly transference of cookies on static files. For more information, -- please see: -- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain -- -- If you change the resource pattern for StaticR in Foundation.hs, you will -- have to make a corresponding change here. -- -- To see how this value is used, see urlRenderOverride in Foundation.hs staticRoot :: AppConfig DefaultEnv x -> Text staticRoot conf = [st|#{appRoot conf}/static|] -- | Settings for 'widgetFile', such as which template languages to support and -- default Hamlet settings. -- -- For more information on modifying behavior, see: -- -- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile widgetFileSettings :: WidgetFileSettings widgetFileSettings = def { wfsHamletSettings = hamletSettings } hamletSettings :: HamletSettings hamletSettings = defaultHamletSettings { hamletNewlines = NoNewlines } hamletFile :: FilePath -> Q Exp hamletFile = hamletFileWithSettings hamletRules hamletSettings -- The rest of this file contains settings which rarely need changing by a -- user. widgetFile :: String -> Q Exp widgetFile = (if development then widgetFileReload else widgetFileNoReload) widgetFileSettings addKeywords :: [Text] -> WidgetT m IO () addKeywords ws = toWidgetHead [hamlet|<meta name="keywords" content="#{format ws}">|] where -- add some default keywords, and make the comma separated list format :: [Text] -> Text format = T.append "patrick brisbin, pbrisbin, brisbin, " . T.intercalate ", " pandocFile :: Text -> FilePath pandocFile x = "/home/patrick/Site/pandoc/" ++ T.unpack x ++ ".pdc" parseNothing :: Monad m => a -> b -> m () parseNothing _ _ = return ()
pbrisbin/devsite
Settings.hs
bsd-2-clause
3,154
0
9
537
396
239
157
-1
-1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QPrintDialog_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:16 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QPrintDialog_h where import Foreign.C.Types import Qtc.Enums.Base import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui_h import Qtc.ClassTypes.Gui import Foreign.Marshal.Array instance QunSetUserMethod (QPrintDialog ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QPrintDialog_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QPrintDialog_unSetUserMethod" qtc_QPrintDialog_unSetUserMethod :: Ptr (TQPrintDialog a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QPrintDialogSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QPrintDialog_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QPrintDialog ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QPrintDialog_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QPrintDialogSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QPrintDialog_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QPrintDialog ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QPrintDialog_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QPrintDialogSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QPrintDialog_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QPrintDialog ()) (QPrintDialog x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QPrintDialog setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QPrintDialog_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QPrintDialog_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setUserMethod" qtc_QPrintDialog_setUserMethod :: Ptr (TQPrintDialog a) -> CInt -> Ptr (Ptr (TQPrintDialog x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QPrintDialog :: (Ptr (TQPrintDialog x0) -> IO ()) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QPrintDialog_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QPrintDialogSc a) (QPrintDialog x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QPrintDialog setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QPrintDialog_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QPrintDialog_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QPrintDialog ()) (QPrintDialog x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QPrintDialog setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QPrintDialog_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QPrintDialog_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setUserMethodVariant" qtc_QPrintDialog_setUserMethodVariant :: Ptr (TQPrintDialog a) -> CInt -> Ptr (Ptr (TQPrintDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QPrintDialog :: (Ptr (TQPrintDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QPrintDialog_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QPrintDialogSc a) (QPrintDialog x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QPrintDialog setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QPrintDialog_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QPrintDialog_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QPrintDialog ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QPrintDialog_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QPrintDialog_unSetHandler" qtc_QPrintDialog_unSetHandler :: Ptr (TQPrintDialog a) -> CWString -> IO (CBool) instance QunSetHandler (QPrintDialogSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QPrintDialog_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QPrintDialog ()) (QPrintDialog x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qPrintDialogFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setHandler1" qtc_QPrintDialog_setHandler1 :: Ptr (TQPrintDialog a) -> CWString -> Ptr (Ptr (TQPrintDialog x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QPrintDialog1 :: (Ptr (TQPrintDialog x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QPrintDialog1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QPrintDialogSc a) (QPrintDialog x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qPrintDialogFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QPrintDialog ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QPrintDialog_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QPrintDialog_eventFilter" qtc_QPrintDialog_eventFilter :: Ptr (TQPrintDialog a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QPrintDialogSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QPrintDialog_eventFilter cobj_x0 cobj_x1 cobj_x2 instance QsetHandler (QPrintDialog ()) (QPrintDialog x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qPrintDialogFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setHandler2" qtc_QPrintDialog_setHandler2 :: Ptr (TQPrintDialog a) -> CWString -> Ptr (Ptr (TQPrintDialog x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QPrintDialog2 :: (Ptr (TQPrintDialog x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QPrintDialog2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QPrintDialogSc a) (QPrintDialog x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qPrintDialogFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qexec_h (QPrintDialog ()) (()) where exec_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_exec cobj_x0 foreign import ccall "qtc_QPrintDialog_exec" qtc_QPrintDialog_exec :: Ptr (TQPrintDialog a) -> IO CInt instance Qexec_h (QPrintDialogSc a) (()) where exec_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_exec cobj_x0 instance QsetHandler (QPrintDialog ()) (QPrintDialog x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> IO () setHandlerWrapper x0 = do x0obj <- qPrintDialogFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setHandler3" qtc_QPrintDialog_setHandler3 :: Ptr (TQPrintDialog a) -> CWString -> Ptr (Ptr (TQPrintDialog x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QPrintDialog3 :: (Ptr (TQPrintDialog x0) -> IO ()) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QPrintDialog3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QPrintDialogSc a) (QPrintDialog x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> IO () setHandlerWrapper x0 = do x0obj <- qPrintDialogFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qaccept_h (QPrintDialog ()) (()) where accept_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_accept cobj_x0 foreign import ccall "qtc_QPrintDialog_accept" qtc_QPrintDialog_accept :: Ptr (TQPrintDialog a) -> IO () instance Qaccept_h (QPrintDialogSc a) (()) where accept_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_accept cobj_x0 instance QsetHandler (QPrintDialog ()) (QPrintDialog x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qPrintDialogFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setHandler4" qtc_QPrintDialog_setHandler4 :: Ptr (TQPrintDialog a) -> CWString -> Ptr (Ptr (TQPrintDialog x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QPrintDialog4 :: (Ptr (TQPrintDialog x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> Ptr (TQEvent t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QPrintDialog4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QPrintDialogSc a) (QPrintDialog x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qPrintDialogFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QcloseEvent_h (QPrintDialog ()) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_closeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_closeEvent" qtc_QPrintDialog_closeEvent :: Ptr (TQPrintDialog a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent_h (QPrintDialogSc a) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_closeEvent cobj_x0 cobj_x1 instance QcontextMenuEvent_h (QPrintDialog ()) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_contextMenuEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_contextMenuEvent" qtc_QPrintDialog_contextMenuEvent :: Ptr (TQPrintDialog a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent_h (QPrintDialogSc a) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_contextMenuEvent cobj_x0 cobj_x1 instance QsetHandler (QPrintDialog ()) (QPrintDialog x0 -> Int -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> CInt -> IO () setHandlerWrapper x0 x1 = do x0obj <- qPrintDialogFromPtr x0 let x1int = fromCInt x1 if (objectIsNull x0obj) then return () else _handler x0obj x1int setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setHandler5" qtc_QPrintDialog_setHandler5 :: Ptr (TQPrintDialog a) -> CWString -> Ptr (Ptr (TQPrintDialog x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QPrintDialog5 :: (Ptr (TQPrintDialog x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> CInt -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QPrintDialog5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QPrintDialogSc a) (QPrintDialog x0 -> Int -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> CInt -> IO () setHandlerWrapper x0 x1 = do x0obj <- qPrintDialogFromPtr x0 let x1int = fromCInt x1 if (objectIsNull x0obj) then return () else _handler x0obj x1int setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qdone_h (QPrintDialog ()) ((Int)) where done_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_done cobj_x0 (toCInt x1) foreign import ccall "qtc_QPrintDialog_done" qtc_QPrintDialog_done :: Ptr (TQPrintDialog a) -> CInt -> IO () instance Qdone_h (QPrintDialogSc a) ((Int)) where done_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_done cobj_x0 (toCInt x1) instance QsetHandler (QPrintDialog ()) (QPrintDialog x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qPrintDialogFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setHandler6" qtc_QPrintDialog_setHandler6 :: Ptr (TQPrintDialog a) -> CWString -> Ptr (Ptr (TQPrintDialog x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QPrintDialog6 :: (Ptr (TQPrintDialog x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QPrintDialog6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QPrintDialogSc a) (QPrintDialog x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qPrintDialogFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QPrintDialog ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_event cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_event" qtc_QPrintDialog_event :: Ptr (TQPrintDialog a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QPrintDialogSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_event cobj_x0 cobj_x1 instance QkeyPressEvent_h (QPrintDialog ()) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_keyPressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_keyPressEvent" qtc_QPrintDialog_keyPressEvent :: Ptr (TQPrintDialog a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent_h (QPrintDialogSc a) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_keyPressEvent cobj_x0 cobj_x1 instance QsetHandler (QPrintDialog ()) (QPrintDialog x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qPrintDialogFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setHandler7" qtc_QPrintDialog_setHandler7 :: Ptr (TQPrintDialog a) -> CWString -> Ptr (Ptr (TQPrintDialog x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QPrintDialog7 :: (Ptr (TQPrintDialog x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> IO (Ptr (TQSize t0)))) foreign import ccall "wrapper" wrapSetHandler_QPrintDialog7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QPrintDialogSc a) (QPrintDialog x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qPrintDialogFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqminimumSizeHint_h (QPrintDialog ()) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_minimumSizeHint cobj_x0 foreign import ccall "qtc_QPrintDialog_minimumSizeHint" qtc_QPrintDialog_minimumSizeHint :: Ptr (TQPrintDialog a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint_h (QPrintDialogSc a) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_minimumSizeHint cobj_x0 instance QminimumSizeHint_h (QPrintDialog ()) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QPrintDialog_minimumSizeHint_qth" qtc_QPrintDialog_minimumSizeHint_qth :: Ptr (TQPrintDialog a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint_h (QPrintDialogSc a) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance Qreject_h (QPrintDialog ()) (()) where reject_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_reject cobj_x0 foreign import ccall "qtc_QPrintDialog_reject" qtc_QPrintDialog_reject :: Ptr (TQPrintDialog a) -> IO () instance Qreject_h (QPrintDialogSc a) (()) where reject_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_reject cobj_x0 instance QresizeEvent_h (QPrintDialog ()) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_resizeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_resizeEvent" qtc_QPrintDialog_resizeEvent :: Ptr (TQPrintDialog a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent_h (QPrintDialogSc a) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_resizeEvent cobj_x0 cobj_x1 instance QsetHandler (QPrintDialog ()) (QPrintDialog x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qPrintDialogFromPtr x0 let x1bool = fromCBool x1 if (objectIsNull x0obj) then return () else _handler x0obj x1bool setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setHandler8" qtc_QPrintDialog_setHandler8 :: Ptr (TQPrintDialog a) -> CWString -> Ptr (Ptr (TQPrintDialog x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QPrintDialog8 :: (Ptr (TQPrintDialog x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> CBool -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QPrintDialog8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QPrintDialogSc a) (QPrintDialog x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qPrintDialogFromPtr x0 let x1bool = fromCBool x1 if (objectIsNull x0obj) then return () else _handler x0obj x1bool setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetVisible_h (QPrintDialog ()) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_setVisible cobj_x0 (toCBool x1) foreign import ccall "qtc_QPrintDialog_setVisible" qtc_QPrintDialog_setVisible :: Ptr (TQPrintDialog a) -> CBool -> IO () instance QsetVisible_h (QPrintDialogSc a) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_setVisible cobj_x0 (toCBool x1) instance QshowEvent_h (QPrintDialog ()) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_showEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_showEvent" qtc_QPrintDialog_showEvent :: Ptr (TQPrintDialog a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent_h (QPrintDialogSc a) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_showEvent cobj_x0 cobj_x1 instance QqsizeHint_h (QPrintDialog ()) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_sizeHint cobj_x0 foreign import ccall "qtc_QPrintDialog_sizeHint" qtc_QPrintDialog_sizeHint :: Ptr (TQPrintDialog a) -> IO (Ptr (TQSize ())) instance QqsizeHint_h (QPrintDialogSc a) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_sizeHint cobj_x0 instance QsizeHint_h (QPrintDialog ()) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QPrintDialog_sizeHint_qth" qtc_QPrintDialog_sizeHint_qth :: Ptr (TQPrintDialog a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint_h (QPrintDialogSc a) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QactionEvent_h (QPrintDialog ()) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_actionEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_actionEvent" qtc_QPrintDialog_actionEvent :: Ptr (TQPrintDialog a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent_h (QPrintDialogSc a) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_actionEvent cobj_x0 cobj_x1 instance QchangeEvent_h (QPrintDialog ()) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_changeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_changeEvent" qtc_QPrintDialog_changeEvent :: Ptr (TQPrintDialog a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent_h (QPrintDialogSc a) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_changeEvent cobj_x0 cobj_x1 instance QdevType_h (QPrintDialog ()) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_devType cobj_x0 foreign import ccall "qtc_QPrintDialog_devType" qtc_QPrintDialog_devType :: Ptr (TQPrintDialog a) -> IO CInt instance QdevType_h (QPrintDialogSc a) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_devType cobj_x0 instance QdragEnterEvent_h (QPrintDialog ()) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dragEnterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_dragEnterEvent" qtc_QPrintDialog_dragEnterEvent :: Ptr (TQPrintDialog a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent_h (QPrintDialogSc a) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dragEnterEvent cobj_x0 cobj_x1 instance QdragLeaveEvent_h (QPrintDialog ()) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dragLeaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_dragLeaveEvent" qtc_QPrintDialog_dragLeaveEvent :: Ptr (TQPrintDialog a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent_h (QPrintDialogSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dragLeaveEvent cobj_x0 cobj_x1 instance QdragMoveEvent_h (QPrintDialog ()) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dragMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_dragMoveEvent" qtc_QPrintDialog_dragMoveEvent :: Ptr (TQPrintDialog a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent_h (QPrintDialogSc a) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dragMoveEvent cobj_x0 cobj_x1 instance QdropEvent_h (QPrintDialog ()) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dropEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_dropEvent" qtc_QPrintDialog_dropEvent :: Ptr (TQPrintDialog a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent_h (QPrintDialogSc a) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dropEvent cobj_x0 cobj_x1 instance QenterEvent_h (QPrintDialog ()) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_enterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_enterEvent" qtc_QPrintDialog_enterEvent :: Ptr (TQPrintDialog a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent_h (QPrintDialogSc a) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_enterEvent cobj_x0 cobj_x1 instance QfocusInEvent_h (QPrintDialog ()) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_focusInEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_focusInEvent" qtc_QPrintDialog_focusInEvent :: Ptr (TQPrintDialog a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent_h (QPrintDialogSc a) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_focusInEvent cobj_x0 cobj_x1 instance QfocusOutEvent_h (QPrintDialog ()) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_focusOutEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_focusOutEvent" qtc_QPrintDialog_focusOutEvent :: Ptr (TQPrintDialog a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent_h (QPrintDialogSc a) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_focusOutEvent cobj_x0 cobj_x1 instance QsetHandler (QPrintDialog ()) (QPrintDialog x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qPrintDialogFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setHandler9" qtc_QPrintDialog_setHandler9 :: Ptr (TQPrintDialog a) -> CWString -> Ptr (Ptr (TQPrintDialog x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QPrintDialog9 :: (Ptr (TQPrintDialog x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> CInt -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QPrintDialog9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QPrintDialogSc a) (QPrintDialog x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qPrintDialogFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QheightForWidth_h (QPrintDialog ()) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_heightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QPrintDialog_heightForWidth" qtc_QPrintDialog_heightForWidth :: Ptr (TQPrintDialog a) -> CInt -> IO CInt instance QheightForWidth_h (QPrintDialogSc a) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_heightForWidth cobj_x0 (toCInt x1) instance QhideEvent_h (QPrintDialog ()) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_hideEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_hideEvent" qtc_QPrintDialog_hideEvent :: Ptr (TQPrintDialog a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent_h (QPrintDialogSc a) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_hideEvent cobj_x0 cobj_x1 instance QsetHandler (QPrintDialog ()) (QPrintDialog x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qPrintDialogFromPtr x0 let x1enum = qEnum_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1enum rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setHandler10" qtc_QPrintDialog_setHandler10 :: Ptr (TQPrintDialog a) -> CWString -> Ptr (Ptr (TQPrintDialog x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QPrintDialog10 :: (Ptr (TQPrintDialog x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> CLong -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QPrintDialog10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QPrintDialogSc a) (QPrintDialog x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qPrintDialogFromPtr x0 let x1enum = qEnum_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1enum rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QinputMethodQuery_h (QPrintDialog ()) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QPrintDialog_inputMethodQuery" qtc_QPrintDialog_inputMethodQuery :: Ptr (TQPrintDialog a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery_h (QPrintDialogSc a) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyReleaseEvent_h (QPrintDialog ()) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_keyReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_keyReleaseEvent" qtc_QPrintDialog_keyReleaseEvent :: Ptr (TQPrintDialog a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent_h (QPrintDialogSc a) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_keyReleaseEvent cobj_x0 cobj_x1 instance QleaveEvent_h (QPrintDialog ()) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_leaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_leaveEvent" qtc_QPrintDialog_leaveEvent :: Ptr (TQPrintDialog a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent_h (QPrintDialogSc a) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_leaveEvent cobj_x0 cobj_x1 instance QmouseDoubleClickEvent_h (QPrintDialog ()) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mouseDoubleClickEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_mouseDoubleClickEvent" qtc_QPrintDialog_mouseDoubleClickEvent :: Ptr (TQPrintDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent_h (QPrintDialogSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mouseDoubleClickEvent cobj_x0 cobj_x1 instance QmouseMoveEvent_h (QPrintDialog ()) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mouseMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_mouseMoveEvent" qtc_QPrintDialog_mouseMoveEvent :: Ptr (TQPrintDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent_h (QPrintDialogSc a) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mouseMoveEvent cobj_x0 cobj_x1 instance QmousePressEvent_h (QPrintDialog ()) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mousePressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_mousePressEvent" qtc_QPrintDialog_mousePressEvent :: Ptr (TQPrintDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent_h (QPrintDialogSc a) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mousePressEvent cobj_x0 cobj_x1 instance QmouseReleaseEvent_h (QPrintDialog ()) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mouseReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_mouseReleaseEvent" qtc_QPrintDialog_mouseReleaseEvent :: Ptr (TQPrintDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent_h (QPrintDialogSc a) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mouseReleaseEvent cobj_x0 cobj_x1 instance QmoveEvent_h (QPrintDialog ()) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_moveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_moveEvent" qtc_QPrintDialog_moveEvent :: Ptr (TQPrintDialog a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent_h (QPrintDialogSc a) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_moveEvent cobj_x0 cobj_x1 instance QsetHandler (QPrintDialog ()) (QPrintDialog x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qPrintDialogFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QPrintDialog_setHandler11" qtc_QPrintDialog_setHandler11 :: Ptr (TQPrintDialog a) -> CWString -> Ptr (Ptr (TQPrintDialog x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QPrintDialog11 :: (Ptr (TQPrintDialog x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQPrintDialog x0) -> IO (Ptr (TQPaintEngine t0)))) foreign import ccall "wrapper" wrapSetHandler_QPrintDialog11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QPrintDialogSc a) (QPrintDialog x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QPrintDialog11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QPrintDialog11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QPrintDialog_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQPrintDialog x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qPrintDialogFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QpaintEngine_h (QPrintDialog ()) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_paintEngine cobj_x0 foreign import ccall "qtc_QPrintDialog_paintEngine" qtc_QPrintDialog_paintEngine :: Ptr (TQPrintDialog a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine_h (QPrintDialogSc a) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_paintEngine cobj_x0 instance QpaintEvent_h (QPrintDialog ()) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_paintEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_paintEvent" qtc_QPrintDialog_paintEvent :: Ptr (TQPrintDialog a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent_h (QPrintDialogSc a) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_paintEvent cobj_x0 cobj_x1 instance QtabletEvent_h (QPrintDialog ()) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_tabletEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_tabletEvent" qtc_QPrintDialog_tabletEvent :: Ptr (TQPrintDialog a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent_h (QPrintDialogSc a) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_tabletEvent cobj_x0 cobj_x1 instance QwheelEvent_h (QPrintDialog ()) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_wheelEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_wheelEvent" qtc_QPrintDialog_wheelEvent :: Ptr (TQPrintDialog a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent_h (QPrintDialogSc a) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_wheelEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QPrintDialog_h.hs
bsd-2-clause
65,399
0
18
13,921
21,325
10,273
11,052
-1
-1
{-# LANGUAGE DataKinds #-} {-# OPTIONS_GHC -Wall #-} module Main where import NumHask.Prelude import NumHask.Laws import NumHask.Array import Test.DocTest import Test.Tasty (TestTree, defaultMain, testGroup, localOption) import Test.Tasty.QuickCheck main :: IO () main = do putStrLn ("Array DocTest" :: Text) doctest ["src/NumHask/Array.hs"] putStrLn ("Example DocTest" :: Text) doctest ["src/NumHask/Array/Example.hs"] defaultMain tests tests :: TestTree tests = testGroup "NumHask" [ testsVInt , testsMInt , testsVFloat , testsMFloat ] testsVInt :: TestTree testsVInt = testGroup "Vector [] 6 Int" [ testGroup "Additive" $ testLawOf ([] :: [Vector [] 6 Int]) <$> additiveLaws , testGroup "Additive Group" $ testLawOf ([] :: [Vector [] 6 Int]) <$> additiveGroupLaws , testGroup "Multiplicative" $ testLawOf ([] :: [Vector [] 6 Int]) <$> multiplicativeLaws , testGroup "Distribution" $ testLawOf ([] :: [Vector [] 6 Int]) <$> distributionLaws , testGroup "Additive Module" $ testLawOf2 ([] :: [(Vector [] 6 Int, Int)]) <$> additiveModuleLaws , testGroup "Additive Group Module" $ testLawOf2 ([] :: [(Vector [] 6 Int, Int)]) <$> additiveGroupModuleLaws , testGroup "Multiplicative Module" $ testLawOf2 ([] :: [(Vector [] 6 Int, Int)]) <$> multiplicativeModuleLaws , testGroup "Hilbert" $ testLawOf2 ([] :: [(Vector [] 6 Int, Int)]) <$> hilbertLaws , testGroup "Tensor product" $ testLawOf2 ([] :: [(Vector [] 6 Int, Int)]) <$> tensorProductLaws , testGroup "Additive Basis" $ testLawOf ([] :: [Vector [] 6 Int]) <$> additiveBasisLaws , testGroup "Additive Group Basis" $ testLawOf ([] :: [Vector [] 6 Int]) <$> additiveGroupBasisLaws , testGroup "Multiplicative Basis" $ testLawOf ([] :: [Vector [] 6 Int]) <$> multiplicativeBasisLaws ] testsMInt :: TestTree testsMInt = testGroup "Matrix [] 4 3 Int" [ testGroup "Additive" $ testLawOf ([] :: [Matrix [] 4 3 Int]) <$> additiveLaws , testGroup "Additive Group" $ testLawOf ([] :: [Matrix [] 4 3 Int]) <$> additiveGroupLaws , testGroup "Multiplicative (square only)" $ testLawOf ([] :: [Matrix [] 3 3 Int]) <$> multiplicativeMonoidalLaws , testGroup "Additive Module" $ testLawOf2 ([] :: [(Matrix [] 4 3 Int, Int)]) <$> additiveModuleLaws , testGroup "Additive Group Module" $ testLawOf2 ([] :: [(Matrix [] 4 3 Int, Int)]) <$> additiveGroupModuleLaws , testGroup "Multiplicative Module" $ testLawOf2 ([] :: [(Matrix [] 4 3 Int, Int)]) <$> multiplicativeModuleLaws , testGroup "Hilbert" $ testLawOf2 ([] :: [(Matrix [] 4 3 Int, Int)]) <$> hilbertLaws , testGroup "Tensor product" $ testLawOf2 ([] :: [(Matrix [] 4 3 Int, Int)]) <$> tensorProductLaws , testGroup "Additive Basis" $ testLawOf ([] :: [Matrix [] 4 3 Int]) <$> additiveBasisLaws , testGroup "Additive Group Basis" $ testLawOf ([] :: [Matrix [] 4 3 Int]) <$> additiveGroupBasisLaws , testGroup "Multiplicative Basis" $ testLawOf ([] :: [Matrix [] 4 3 Int]) <$> multiplicativeBasisLaws ] testsVFloat :: TestTree testsVFloat = testGroup "Vector 6 Float" [ testGroup "MultiplicativeGroup" $ testLawOf ([] :: [Vector [] 6 Float]) <$> multiplicativeGroupLaws , testGroup "Signed" $ testLawOf ([] :: [Vector [] 6 Float]) <$> signedLaws , testGroup "Metric" $ testLawOf ([] :: [Vector [] 6 Float]) <$> metricNaperianFloatLaws , testGroup "Exponential Field" $ testLawOf ([] :: [Vector [] 6 Float]) <$> expFieldNaperianLaws , testGroup "Multiplicative Group Module" $ localOption (QuickCheckTests 1000) . testLawOf2 ([] :: [(Vector [] 6 Float, Float)]) <$> multiplicativeGroupModuleLawsFail , testGroup "Multiplicative Group Basis" $ testLawOf ([] :: [Vector [] 6 Float]) <$> multiplicativeGroupBasisLaws ] testsMFloat :: TestTree testsMFloat = testGroup "Matrix [] 4 3 Float" [ testGroup "Multiplicative Group Module" $ localOption (QuickCheckTests 1000) . testLawOf2 ([] :: [(Matrix [] 4 3 Float, Float)]) <$> multiplicativeGroupModuleLawsFail , testGroup "Multiplicative Group Basis" $ testLawOf ([] :: [Matrix [] 4 3 Float]) <$> multiplicativeGroupBasisLaws ]
tonyday567/naperian
test/test.hs
bsd-3-clause
4,371
0
14
986
1,472
773
699
104
1
{-#LANGUAGE Arrows, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, NoMonomorphismRestriction #-} module Web.Horse.Forms.Types where import Control.Arrow.Transformer.Automaton.Monad import Control.Arrow.Transformer.Automaton.Maybe import Control.Arrow.Transformer.LabeledArrow import Debug.Trace import Data.List import Control.Arrow import Control.Arrow.Transformer.All import Control.Arrow.Operations type FormOut = String newtype FormIn = FormIn [(String,String)] deriving (Show) type HoH i o = LabeledArrow (ReaderArrow FormIn (Automaton (Kleisli IO))) i o type HoHMay i o = LabeledArrow (ReaderArrow FormIn (MaybeAutomaton (Kleisli IO))) i o type HoHErr ex i o = LabeledArrow (ErrorArrow ex (ReaderArrow FormIn (Automaton (Kleisli IO)))) i o type HoHErrMay ex i o = LabeledArrow (ErrorArrow ex (ReaderArrow FormIn (MaybeAutomaton (Kleisli IO)))) i o noInput :: FormIn noInput = FormIn [] filterPrefix :: String -> FormIn -> FormIn filterPrefix s (FormIn xss) = FormIn $ filter ((== s) . fst) xss class HasFormOut o where getFormOut :: o -> FormOut setFormOut :: FormOut -> o -> o instance HasFormOut FormOut where getFormOut = id setFormOut = const instance HasFormOut (FormOut, i) where getFormOut (fo,_) = fo setFormOut fo (_,o) = (fo,o) instance HasFormOut (FormOut, o1, o2) where getFormOut (fo,_,_) = fo setFormOut fo (_,o1,o2) = (fo,o1,o2) getSingle :: FormIn -> Maybe String getSingle (FormIn [(_,x)]) = Just x getSingle _ = Nothing withInput :: (ArrowReader FormIn a', ArrowAddLabel a a', ArrowAddAutomaton a1 a' a'1) => a1 (e, String, Maybe String) b -> a e b withInput = withInput0 . restify withInput0 :: (ArrowReader FormIn a', ArrowAddLabel a a') => a' (e,String,Maybe String) b -> a e b withInput0 f = runLabel $ proc (e,lab) -> do fi <- readState -< () f -< (e,show lab,getSingle $ filterPrefix (show lab) fi) restify g = liftMaybeAutomaton $ proc (e,lab,inp) -> do (o,g') <- elimAutomaton g -< (e,lab,inp) case inp of Nothing -> returnA -< (o,Nothing) _ -> returnA -< (o, Just g') catchAuto :: (ArrowAddAutomaton a may a') => (LabeledArrow (ErrorArrow (LabeledArrow a i o) a)) i o -> LabeledArrow a i o catchAuto f = liftAutomaton $ (LabeledArrow $ unLA (elimAutomaton f) >>> second (arr catchAuto)) `elimError` (LabeledArrow $ proc (i,f') -> app -< (unLA (elimAutomaton f'), i)) catchMayAuto :: (ArrowAddAutomaton a may a') => LabeledArrow (ErrorArrow (LabeledArrow a t1 o) may) t1 o -> LabeledArrow may t1 o catchMayAuto f = liftMaybeAutomaton $ (LabeledArrow $ unLA (elimMaybeAutomaton f) >>> second (arr (fmap (fromMaybeAutomaton . catchMayAuto . toMaybeAutomaton) ))) `elimError` (LabeledArrow $ proc (i,f') -> do (o,g) <- app -< (elimAutomaton $ unLA f', i) returnA -< (o, Just $ LabeledArrow g))
jhp/on-a-horse
Web/Horse/Forms/Types.hs
bsd-3-clause
3,149
4
16
816
1,139
618
521
74
2
{-# LANGUAGE DeriveGeneric #-} module Text.OrgMode.Elements.Head where import Control.Applicative hiding ((<|>), many) import Data.Text (Text) import qualified Data.Text as T import Text.Parsec import GHC.Generics import Text.OrgMode.Elements.Keyword import Text.OrgMode.Parsers.Utils data Head = Head { level :: Int , keyword :: Maybe Text , priority :: Maybe Char , title :: Maybe Text , tags :: [Text] } deriving (Show, Generic) sectionHead :: Parsec Text [TodoSeq] Head sectionHead = do stars <- length <$> many1 (char '*') <* blanks todokw <- parseTodoKw <* blanks pri <- parsePri <* blanks title <- parseTitle <* blanks tags <- parseTags <* blanks eoh return $ Head stars todokw pri title tags parsePri :: Parsec Text [TodoSeq] (Maybe Char) parsePri = Just <$> tryAhead (string "[#" *> anyChar <* char ']') <|> return Nothing parseTitle :: Parsec Text [TodoSeq] (Maybe Text) parseTitle = optionMaybe $ T.pack <$> title where title = manyTill anyChar (try $ lookAhead (blanks >> parseTags >> blanks >> eoh)) parseTodoKw :: Parsec Text [TodoSeq] (Maybe Text) parseTodoKw = try parseTodoKw' <|> return Nothing where parseTodoKw' = do tds <- getState todo <- manyTill anyChar blank case haveTodo tds (T.pack todo) of True -> return $ Just $ T.pack todo False -> fail "no such kw in list" haveTodo [] _ = False haveTodo ((TodoSeq ts ds):tds) todo = ts `contains` todo || ds `contains` todo || haveTodo tds todo contains [] _ = False contains ((Todo n _):tds) txt = n == txt || contains tds txt parseTags :: Parsec Text [TodoSeq] [Text] parseTags = char ':' *> sepBy1 parseTag (char ' ') <* (char ':') <|> return [] parseTag :: Parsec Text [TodoSeq] Text parseTag = T.pack <$> many1 (noneOf ": ") eoh :: Parsec Text [TodoSeq] () eoh = eof <|> (newline >> return ())
cvb/hs-orgmode
Text/OrgMode/Elements/Head.hs
bsd-3-clause
2,049
0
14
578
723
377
346
50
4
{-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} module RotateSome where import Utils import Test.QuickCheck (Arbitrary, arbitrary, choose) import XMonad.StackSet (Stack, integrate, up) import XMonad.Actions.RotateSome (rotateSome) newtype Divisor = Divisor Int deriving Show instance Arbitrary Divisor where arbitrary = Divisor <$> choose (1, 5) isMultOf :: Int -> Int -> Bool x `isMultOf` n = (x `rem` n) == 0 -- Total number of elements does not change. prop_rotate_some_length (Divisor d) (stk :: Stack Int) = length (integrate stk) == length (integrate $ rotateSome (`isMultOf` d) stk) -- Applying rotateSome N times completes a cycle, where N is the number of -- elements that satisfy the predicate. prop_rotate_some_cycle (Divisor d) (stk :: Stack Int) = stk == applyN (Just n) (rotateSome (`isMultOf` d)) stk where n = length $ filter (`isMultOf` d) (integrate stk) -- Elements that do not satisfy the predicate remain anchored in place. prop_rotate_some_anchors (Divisor d) (stk :: Stack Int) = all check $ zip (integrate stk) (integrate $ rotateSome (`isMultOf` d) stk) where check (before, after) = (before `isMultOf` d) || before == after -- Elements that satisfy the predicate rotate by one position. prop_rotate_some_rotate (Divisor d) (stk :: Stack Int) = drop 1 before ++ take 1 before == after where before = filter p (integrate stk) after = filter p (integrate $ rotateSome p stk) p = (`isMultOf` d) -- Focus position is preserved. prop_rotate_some_focus (Divisor d) (stk :: Stack Int) = length (up stk) == length (up $ rotateSome (`isMultOf` d) stk)
xmonad/xmonad-contrib
tests/RotateSome.hs
bsd-3-clause
1,669
0
10
312
527
290
237
30
1
{-# LANGUAGE CPP #-} {- | Module : Main Description : License : BSD3 Maintainer : atomb Stability : provisional -} module Main where import Control.Exception import Control.Monad import Data.Maybe import System.IO import System.Console.GetOpt import System.Environment import System.Directory import SAWScript.Options import SAWScript.Utils import SAWScript.Interpreter (processFile) import qualified SAWScript.REPL as REPL import SAWScript.Version (shortVersionText) import SAWScript.Value (AIGProxy(..)) import qualified Data.AIG.CompactGraph as AIG main :: IO () main = do hSetBuffering stdout LineBuffering argv <- getArgs case getOpt Permute options argv of (opts, files, []) -> do opts' <- foldl (>>=) (return defaultOptions) opts opts'' <- processEnv opts' {- We have two modes of operation: batch processing, handled in 'SAWScript.ProcessFile', and a REPL, defined in 'SAWScript.REPL'. -} case files of _ | showVersion opts'' -> hPutStrLn stderr shortVersionText _ | showHelp opts'' -> err opts'' (usageInfo header options) [] -> checkZ3 opts'' *> REPL.run opts'' _ | runInteractively opts'' -> checkZ3 opts'' *> REPL.run opts'' [file] -> checkZ3 opts'' *> processFile (AIGProxy AIG.compactProxy) opts'' file `catch` (\(ErrorCall msg) -> err opts'' msg) (_:_) -> err opts'' "Multiple files not yet supported." (_, _, errs) -> do hPutStrLn stderr (concat errs ++ usageInfo header options) exitProofUnknown where header = "Usage: saw [OPTION...] [-I | file]" checkZ3 opts = do p <- findExecutable "z3" unless (isJust p) $ err opts "Error: z3 is required to run SAW, but it was not found on the system path." err opts msg = do when (verbLevel opts >= Error) (hPutStrLn stderr msg) exitProofUnknown
GaloisInc/saw-script
saw/Main.hs
bsd-3-clause
1,936
0
20
479
499
253
246
44
7
import System.IO import System.Directory import Data.List import Control.Exception main = do contents <- readFile "src/files_for_stream/todo.txt" let todoTasks = lines contents numberedTasks = zipWith (\n line -> show n ++ " - " ++ line) [0..] todoTasks putStrLn "These are your TO-DO items:" mapM_ putStrLn numberedTasks putStrLn "Which one do you want to delete?" numberString <- getLine let number = read numberString newTodoItems = unlines $ delete (todoTasks !! number) todoTasks -- (tempName, tempHandle) <- openTempFile "src/files_for_stream" "temp" -- hPutStr tempHandle newTodoItems -- hClose tempHandle -- removeFile "src/files_for_stream/todo.txt" -- renameFile tempName "src/files_for_stream/todo.txt" bracketOnError (openTempFile "src/files_for_stream" "temp") (\(tempName, tempHandle) -> do hClose tempHandle removeFile tempName) (\(tempName, tempHandle) -> do hPutStr tempHandle newTodoItems hClose tempHandle removeFile "src/files_for_stream/todo.txt" renameFile tempName "src/files_for_stream/todo.txt")
ku00/h-book
src/DeleteToDo.hs
bsd-3-clause
1,179
0
15
275
235
114
121
23
1
{-# LANGUAGE OverloadedStrings #-} module Text.TOML where import qualified Data.Attoparsec.ByteString.Char8 as A import qualified Data.ByteString.Char8 as B import Data.List ( foldl', groupBy ) import Data.Either ( rights ) import Data.Map ( Map ) import qualified Data.Map as M import Text.TOML.Parser import Text.TOML.Value parse :: B.ByteString -> Maybe TOML parse bs = process `fmap` parse' bs parse' bs = (A.maybeResult $ A.feed (A.parse document bs) "") process :: [Token] -> TOML process ts = go (group ts) tempty where go [] m = m go ((ks, kvs):gs) m = go gs (okalter ks kvs m) okalter :: [B.ByteString] -> [(B.ByteString, TOMLV)] -> TOML -> TOML okalter [] kvs t = insertMany kvs t okalter (k:ks) kvs t = liftT (M.alter (Just . f) (B.unpack k)) t where f Nothing = liftTV (okalter ks kvs) (Left tempty) f (Just t') = liftTV (okalter ks kvs) t' insertMany :: [(B.ByteString, TOMLV)] -> TOML -> TOML insertMany kvs m = foldl' (flip $ uncurry tinsert) m kvs' where kvs' = [(B.unpack k, Right v) | (k, v) <- kvs] -- NB: groupBy will never produce an empty group. group ts = alternate $ (map omg) $ (groupBy right ts) where omg ls@((Left l):_) = Left l omg rs@((Right _):_) = Right (rights rs) -- Only key-value pairs are grouped together right (Right _) (Right _) = True right _ _ = False -- If the token list starts with a Right, then there are key-value pairs that -- don't belong to a keygroup. Assign that one the 'empty' keygroup, and match -- pairs. If the token list starts with a right, then there are no "global" -- key-value pairs, and it's ok to straight zip the partition. -- alternate [] = [] alternate ((Left l) : []) = (l , []) : [] alternate ((Right r) : gs) = ([], r ) : (alternate gs) alternate ((Left l ) : (Right r) : gs) = (l , r ) : (alternate gs) alternate ((Left l1) : (Left l2) : gs) = (l1, []) : (alternate $ (Left l2) : gs)
seliopou/toml
src/Text/TOML.hs
bsd-3-clause
2,070
0
12
560
799
432
367
35
7
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Numeral.HR.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Duckling.Dimensions.Types import Duckling.Numeral.HR.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "HR Tests" [ makeCorpusTest [Seal Numeral] corpus ]
facebookincubator/duckling
tests/Duckling/Numeral/HR/Tests.hs
bsd-3-clause
503
0
9
77
79
50
29
11
1
module IRTS.Cil.Builders where import Language.Cil privateSealedClass :: TypeName -> Maybe TypeSpec -> [TypeSpec] -> [FieldDef] -> [MethodDef] -> [TypeDef] -> TypeDef privateSealedClass = classDef [CaPrivate, CaSealed, CaBeforeFieldInit] publicSealedClass :: TypeName -> Maybe TypeSpec -> [TypeSpec] -> [FieldDef] -> [MethodDef] -> [TypeDef] -> TypeDef publicSealedClass = classDef [CaPublic, CaSealed, CaBeforeFieldInit] publicStruct :: TypeName -> [FieldDef] -> [MethodDef] -> [TypeDef] -> TypeDef publicStruct name = classDef [CaPublic] name (extends "[mscorlib]System.ValueType") noImplements defaultCtorDef :: MethodDef defaultCtorDef = Constructor [MaPublic] Void [] [ ldarg 0 , call [CcInstance] Void "" "object" ".ctor" [] , ret ]
bamboo/idris-cil
src/IRTS/Cil/Builders.hs
bsd-3-clause
801
0
11
154
244
135
109
13
1
module Mistral.TypeCheck.Env ( Env(..) , VarType(..), vtSchema, vtExpr , lookupEnv, addSchema, checkingSchema, primitiveSchema , lookupTSyn, addTSyn , depModules , showEnv , getInsts ) where import qualified Mistral.ModuleSystem.Interface as Iface import Mistral.ModuleSystem.Name ( Name ) import Mistral.TypeCheck.AST ( Schema, TySyn(..), Expr(EPrim), Prim, Inst ) import Mistral.TypeCheck.Unify ( Types(..) ) import Mistral.Utils.PP import Control.Applicative ( (<|>) ) import Data.Foldable ( foldMap ) import qualified Data.Map as Map import Data.Monoid ( Monoid(..) ) data VarType = Var Schema | Checking Schema Expr | Primitive Schema Prim deriving (Show) instance Types VarType where typeVars vt = case vt of Var s -> typeVars s -- be careful to never force the expression Checking s _ -> typeVars s Primitive s _ -> typeVars s applyBndrs b u vt = case vt of Var s -> Var (applyBndrs b u s) -- be careful to never force the expression Checking s e -> Checking (applyBndrs b u s) e Primitive s p -> Primitive (applyBndrs b u s) p depModules :: Env -> [Iface.Iface] depModules env = Iface.getIfaces (envIfaces env) vtSchema :: VarType -> Schema vtSchema vt = case vt of Var s -> s Checking s _ -> s Primitive s _ -> s vtExpr :: VarType -> Maybe Expr vtExpr vt = case vt of Var _ -> Nothing Checking _ e -> Just e Primitive _ e -> Just (EPrim e) data Env = Env { envTypes :: Map.Map Name VarType , envTSyns :: Map.Map Name TySyn , envIfaces :: Iface.IfaceTrie } deriving (Show) getInsts :: Env -> [Inst] getInsts env = Iface.getInsts (envIfaces env) -- | A version of show that doesn't touch the recursive parts of the 'VarType'. showEnv :: Env -> String showEnv env = pretty $ vcat [ text "Types" , vcat [ pp n <+> char '=' <+> pp (vtSchema vt) | (n,vt) <- Map.toList (envTypes env) ] , text "Syns" , vcat [ pp syn | syn <- Map.elems (envTSyns env) ] ] instance Monoid Env where mempty = Env { envTypes = Map.empty , envTSyns = Map.empty , envIfaces = mempty } mappend l r = Env { envTypes = merge envTypes , envTSyns = merge envTSyns , envIfaces = mappend (envIfaces l) (envIfaces r) } where merge p = Map.union (p l) (p r) mconcat es = Env { envTypes = merge envTypes , envTSyns = merge envTSyns , envIfaces = foldMap envIfaces es } where merge p = Map.unions (map p es) instance Types Env where typeVars env = typeVars (Map.elems (envTypes env)) applyBndrs i u env = env { envTypes = applyBndrs i u `fmap` envTypes env } -- | Lookup a schema in the environment. First check the local environment, -- then fall back on looking up in the interface environment. lookupEnv :: Name -> Env -> Maybe VarType lookupEnv qn env = Map.lookup qn (envTypes env) <|> fromIface where fromIface = do bind <- Iface.lookupBind qn (envIfaces env) case bind of Iface.IfaceBind ty -> return (Var ty) Iface.IfacePrim ty e -> return (Primitive ty e) -- | Record a name/schema association in the environment. addSchema :: Name -> Schema -> Env -> Env addSchema qn ty env = env { envTypes = Map.insert qn (Var ty) (envTypes env) } -- | A type that's currently being checked. checkingSchema :: Name -> Schema -> Expr -> Env -> Env checkingSchema qn ty ex env = env { envTypes = Map.insert qn (Checking ty ex) (envTypes env) } -- | A primitive, with its expression rewriting. primitiveSchema :: Name -> Schema -> Prim -> Env -> Env primitiveSchema qn ty ex env = env { envTypes = Map.insert qn (Primitive ty ex) (envTypes env) } -- | Record a name/type synonym association in the environment. addTSyn :: TySyn -> Env -> Env addTSyn syn env = env { envTSyns = Map.insert (synName syn) syn (envTSyns env) } -- | Lookup a type synonym in the environment. Check the local environment, -- then fall back on the interface environment. lookupTSyn :: Name -> Env -> Maybe TySyn lookupTSyn n env = Map.lookup n (envTSyns env) <|> Iface.lookupTySyn n (envIfaces env)
GaloisInc/mistral
src/Mistral/TypeCheck/Env.hs
bsd-3-clause
4,424
0
14
1,274
1,387
730
657
92
3
{- Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.0 Kubernetes API version: v1.9.12 Generated by Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) -} {-| Module : Kubernetes.OpenAPI.API.Version -} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MonoLocalBinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-name-shadowing -fno-warn-unused-binds -fno-warn-unused-imports #-} module Kubernetes.OpenAPI.API.Version where import Kubernetes.OpenAPI.Core import Kubernetes.OpenAPI.MimeTypes import Kubernetes.OpenAPI.Model as M import qualified Data.Aeson as A import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.Data as P (Typeable, TypeRep, typeOf, typeRep) import qualified Data.Foldable as P import qualified Data.Map as Map import qualified Data.Maybe as P import qualified Data.Proxy as P (Proxy(..)) import qualified Data.Set as Set import qualified Data.String as P import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import qualified Data.Time as TI import qualified Network.HTTP.Client.MultipartFormData as NH import qualified Network.HTTP.Media as ME import qualified Network.HTTP.Types as NH import qualified Web.FormUrlEncoded as WH import qualified Web.HttpApiData as WH import Data.Text (Text) import GHC.Base ((<|>)) import Prelude ((==),(/=),($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor) import qualified Prelude as P -- * Operations -- ** Version -- *** getCode -- | @GET \/version\/@ -- -- get the code version -- -- AuthMethod: 'AuthApiKeyBearerToken' -- getCode :: KubernetesRequest GetCode MimeNoContent VersionInfo MimeJSON getCode = _mkRequest "GET" ["/version/"] `_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyBearerToken) data GetCode -- | @application/json@ instance Consumes GetCode MimeJSON -- | @application/json@ instance Produces GetCode MimeJSON
denibertovic/haskell
kubernetes/lib/Kubernetes/OpenAPI/API/Version.hs
bsd-3-clause
2,282
0
8
290
433
308
125
-1
-1
{-# LANGUAGE RelaxedPolyRec #-} -- | Duck prefix trie data structure -- -- A prefix trie represents a partial map @[k] -> v@ with the property that no -- key is a proper prefix of any other key. This version additionaly maps -- every prefix @[k] -> a@. -- -- For example, a prefix trie can be used to represent the types of overloaded -- curried functions. module Ptrie ( Ptrie , empty , get , modify , lookup , toList , unionWith , mapInsert ) where import Prelude hiding (lookup) import Data.Map (Map) import qualified Data.Map as Map data Ptrie k a v = Leaf !v | Node a (Map k (Ptrie k a v)) deriving (Eq, Show) empty :: Either a v -> Ptrie k a v empty (Right v) = Leaf v empty (Left a) = Node a Map.empty get :: Ptrie k a v -> Either a v get (Leaf v) = Right v get (Node a _) = Left a set :: Either a v -> Ptrie k a v -> Ptrie k a v set (Left a) (Node _ m) = Node a m set n _ = empty n modify :: (Either a v -> Either a v) -> Ptrie k a v -> Ptrie k a v modify f p = set (f (get p)) p lookup :: Ord k => [k] -> Ptrie k a v -> Maybe (Ptrie k a v) lookup [] t = Just t lookup (x:k) (Node _ m) = lookup k =<< Map.lookup x m lookup _ _ = Nothing singleton :: Ord k => [k] -> Either a v -> Ptrie k a v singleton [] = empty singleton (x:k) = Node (error "Ptrie.singleton") . Map.singleton x . singleton k insert :: Ord k => [k] -> Either a v -> Ptrie k a v -> Ptrie k a v insert [] n p = set n p insert (x:k) n (Node a m) = Node a $ Map.insertWith (const $ insert k n) x (singleton k n) m insert k n _ = singleton k n toList :: Ptrie k a v -> [([k],v)] toList (Leaf v) = [([],v)] toList (Node _ t) = [(x:k,v) | (x,p) <- Map.toList t, (k,v) <- toList p] unionWith :: Ord k => (Either a v -> Either a v -> Either a v) -> Ptrie k a v -> Ptrie k a v -> Ptrie k a v unionWith f p1 p2 = uw (f (get p1) (get p2)) p1 p2 where uw n (Node _ m1) (Node _ m2) = set n $ Node undefined $ Map.unionWith (unionWith f) m1 m2 uw n p@(Node _ _) _ = set n p uw n _ p = set n p mapInsert :: (Ord f, Ord k) => f -> [k] -> Either a v -> Map f (Ptrie k a v) -> Map f (Ptrie k a v) mapInsert f k v = Map.insertWith (const $ insert k v) f (singleton k v)
girving/duck
duck/Ptrie.hs
bsd-3-clause
2,172
0
12
552
1,162
586
576
51
3
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleContexts #-} -- | Example application. module Main where import Data.Maybe import React import React.Ace as Ace import React.Builder import React.Internal import React.Lucid import Control.Lens import Control.Lens.TH import Control.Monad.IO.Class -- | Application state. data State = Start | MainState Main deriving (Show,Eq) data Main = Main {_mainAce :: Ace} deriving (Show,Eq) $(makePrisms ''State) $(makeLenses ''Main) -- | Main entry point. main :: IO () main = do app <- getApp ace <- Ace.new app container <- getElementById "container" (react app (render ace) container) -- | Make the application. getApp :: IO (App State IO) getApp = makeApp Start id -- | Our main view. render :: MonadIO m => Component State Ace m -> State -> ReactT State m () render ace state = do build "div" (text "Hello, world!") buildComponent ace (_MainState . mainAce) (do code_ "main = putStrLn \"Woot\"" Ace.startline_ 0 Ace.startcol_ 0 Ace.endline_ 0 Ace.endcol_ 0)
fpco/ghcjs-react
examples/Main.hs
bsd-3-clause
1,206
0
12
282
342
176
166
44
1
module Config where import Data.Configurator import Data.Configurator.Types as C import Data.Default (def) import Data.Text as T import System.FilePath (joinPath) import Text.Pandoc.Options import Definition -- | The base URL of the website base_url = "http://www.example.com" -- | The directory where the project is located base_directory = "." -- | The number of entries on a page. entries_per_page = 5 -- | The directory where templates are located template_directory = joinPath [base_directory, "templates"] -- | The path to the blog entry template. entry_template = joinPath [template_directory, "entry.html"] -- | The path to the blog index template. index_template = joinPath [template_directory, "index.html"] -- | The path to the tag index page template. tag_template = joinPath [template_directory, "tag.html"] -- | The path to the RSS feed template rss_template = joinPath [template_directory, "rss.xml"] -- | The directory where the static site should be published output_directory = joinPath [base_directory, "output"] -- | The path to the JSON index static_directory = joinPath [base_directory, "static"] -- | How dates shoudl be formatted. date_format = "%B %e, %Y %l:%M %p" -- | Number of recent posts to show in RSS rss_limit = 10 -- | The name of the website site_name = "My WebSite" -- | Site description site_description = "A description of my website" -- | Post-publish hook post_publish_command = "" -- | Get the full path for a blog entry given a page filename. get_page_path:: Blog -> String -> FilePath get_page_path blog filename = joinPath [(outputDirectory blog), filename] -- | Default Pandoc reader options. reader_options = def ReaderOptions -- | Default Pandoc writer options. writer_options = def WriterOptions getBlog :: IO (FilePath, C.Config) -> IO Blog getBlog confGroup = do (_base_directory, _conf) <- confGroup _base_url <- lookupDefault base_url _conf (pack "base_url") _site_name <- lookupDefault site_name _conf (pack "site_name") _site_description <- lookupDefault site_description _conf (pack "site_description") _entries_per_page <- lookupDefault entries_per_page _conf (pack "entries_per_page") _date_format <- lookupDefault date_format _conf (pack "date_format") _rss_limit <- lookupDefault rss_limit _conf (pack "rss_limit") let _template_directory = joinPath [_base_directory, "templates"] let _entry_template = joinPath [_template_directory, "entry.html"] let _index_template = joinPath [_template_directory, "index.html"] let _tag_template = joinPath [_template_directory, "tag.html"] let _error_template = joinPath [_template_directory, "404.html"] let _rss_template = joinPath [_template_directory, "rss.xml"] let _output_directory = joinPath [_base_directory, "output"] let _static_directory = joinPath [_base_directory, "static"] return $ Blog _base_url _site_name _site_description _entries_per_page _base_directory _entry_template _index_template _tag_template _error_template _rss_template _output_directory _static_directory _date_format _rss_limit
mazelife/agilulf
src/Agiluf/Config.hs
bsd-3-clause
3,084
0
11
459
607
327
280
45
1
{- (c) The University of Glasgow, 2000-2006 \section[Finder]{Module Finder} -} {-# LANGUAGE CPP #-} module Finder ( flushFinderCaches, FindResult(..), findImportedModule, findExactModule, findHomeModule, findExposedPackageModule, mkHomeModLocation, mkHomeModLocation2, mkHiOnlyModLocation, addHomeModuleToFinder, uncacheModule, mkStubPaths, findObjectLinkableMaybe, findObjectLinkable, cannotFindModule, cannotFindInterface, ) where #include "HsVersions.h" import Module import HscTypes import Packages import FastString import Util import PrelNames ( gHC_PRIM ) import DynFlags import Outputable import Maybes ( expectJust ) import Data.IORef ( IORef, readIORef, atomicModifyIORef' ) import System.Directory import System.FilePath import Control.Monad import Data.Time import Data.List ( foldl' ) type FileExt = String -- Filename extension type BaseName = String -- Basename of file -- ----------------------------------------------------------------------------- -- The Finder -- The Finder provides a thin filesystem abstraction to the rest of -- the compiler. For a given module, it can tell you where the -- source, interface, and object files for that module live. -- It does *not* know which particular package a module lives in. Use -- Packages.lookupModuleInAllPackages for that. -- ----------------------------------------------------------------------------- -- The finder's cache -- remove all the home modules from the cache; package modules are -- assumed to not move around during a session. flushFinderCaches :: HscEnv -> IO () flushFinderCaches hsc_env = atomicModifyIORef' fc_ref $ \fm -> (filterModuleEnv is_ext fm, ()) where this_pkg = thisPackage (hsc_dflags hsc_env) fc_ref = hsc_FC hsc_env is_ext mod _ | modulePackageKey mod /= this_pkg = True | otherwise = False addToFinderCache :: IORef FinderCache -> Module -> FindResult -> IO () addToFinderCache ref key val = atomicModifyIORef' ref $ \c -> (extendModuleEnv c key val, ()) removeFromFinderCache :: IORef FinderCache -> Module -> IO () removeFromFinderCache ref key = atomicModifyIORef' ref $ \c -> (delModuleEnv c key, ()) lookupFinderCache :: IORef FinderCache -> Module -> IO (Maybe FindResult) lookupFinderCache ref key = do c <- readIORef ref return $! lookupModuleEnv c key -- ----------------------------------------------------------------------------- -- The two external entry points -- | Locate a module that was imported by the user. We have the -- module's name, and possibly a package name. Without a package -- name, this function will use the search path and the known exposed -- packages to find the module, if a package is specified then only -- that package is searched for the module. findImportedModule :: HscEnv -> ModuleName -> Maybe FastString -> IO FindResult findImportedModule hsc_env mod_name mb_pkg = case mb_pkg of Nothing -> unqual_import Just pkg | pkg == fsLit "this" -> home_import -- "this" is special | otherwise -> pkg_import where home_import = findHomeModule hsc_env mod_name pkg_import = findExposedPackageModule hsc_env mod_name mb_pkg unqual_import = home_import `orIfNotFound` findExposedPackageModule hsc_env mod_name Nothing -- | Locate a specific 'Module'. The purpose of this function is to -- create a 'ModLocation' for a given 'Module', that is to find out -- where the files associated with this module live. It is used when -- reading the interface for a module mentioned by another interface, -- for example (a "system import"). findExactModule :: HscEnv -> Module -> IO FindResult findExactModule hsc_env mod = let dflags = hsc_dflags hsc_env in if modulePackageKey mod == thisPackage dflags then findHomeModule hsc_env (moduleName mod) else findPackageModule hsc_env mod -- ----------------------------------------------------------------------------- -- Helpers orIfNotFound :: IO FindResult -> IO FindResult -> IO FindResult orIfNotFound this or_this = do res <- this case res of NotFound { fr_paths = paths1, fr_mods_hidden = mh1 , fr_pkgs_hidden = ph1, fr_suggestions = s1 } -> do res2 <- or_this case res2 of NotFound { fr_paths = paths2, fr_pkg = mb_pkg2, fr_mods_hidden = mh2 , fr_pkgs_hidden = ph2, fr_suggestions = s2 } -> return (NotFound { fr_paths = paths1 ++ paths2 , fr_pkg = mb_pkg2 -- snd arg is the package search , fr_mods_hidden = mh1 ++ mh2 , fr_pkgs_hidden = ph1 ++ ph2 , fr_suggestions = s1 ++ s2 }) _other -> return res2 _other -> return res -- | Helper function for 'findHomeModule': this function wraps an IO action -- which would look up @mod_name@ in the file system (the home package), -- and first consults the 'hsc_FC' cache to see if the lookup has already -- been done. Otherwise, do the lookup (with the IO action) and save -- the result in the finder cache and the module location cache (if it -- was successful.) homeSearchCache :: HscEnv -> ModuleName -> IO FindResult -> IO FindResult homeSearchCache hsc_env mod_name do_this = do let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name modLocationCache hsc_env mod do_this findExposedPackageModule :: HscEnv -> ModuleName -> Maybe FastString -> IO FindResult findExposedPackageModule hsc_env mod_name mb_pkg = case lookupModuleWithSuggestions (hsc_dflags hsc_env) mod_name mb_pkg of LookupFound m pkg_conf -> findPackageModule_ hsc_env m pkg_conf LookupMultiple rs -> return (FoundMultiple rs) LookupHidden pkg_hiddens mod_hiddens -> return (NotFound{ fr_paths = [], fr_pkg = Nothing , fr_pkgs_hidden = map (modulePackageKey.fst) pkg_hiddens , fr_mods_hidden = map (modulePackageKey.fst) mod_hiddens , fr_suggestions = [] }) LookupNotFound suggest -> return (NotFound{ fr_paths = [], fr_pkg = Nothing , fr_pkgs_hidden = [] , fr_mods_hidden = [] , fr_suggestions = suggest }) modLocationCache :: HscEnv -> Module -> IO FindResult -> IO FindResult modLocationCache hsc_env mod do_this = do m <- lookupFinderCache (hsc_FC hsc_env) mod case m of Just result -> return result Nothing -> do result <- do_this addToFinderCache (hsc_FC hsc_env) mod result return result addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module addHomeModuleToFinder hsc_env mod_name loc = do let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name addToFinderCache (hsc_FC hsc_env) mod (Found loc mod) return mod uncacheModule :: HscEnv -> ModuleName -> IO () uncacheModule hsc_env mod = do let this_pkg = thisPackage (hsc_dflags hsc_env) removeFromFinderCache (hsc_FC hsc_env) (mkModule this_pkg mod) -- ----------------------------------------------------------------------------- -- The internal workers -- | Implements the search for a module name in the home package only. Calling -- this function directly is usually *not* what you want; currently, it's used -- as a building block for the following operations: -- -- 1. When you do a normal package lookup, we first check if the module -- is available in the home module, before looking it up in the package -- database. -- -- 2. When you have a package qualified import with package name "this", -- we shortcut to the home module. -- -- 3. When we look up an exact 'Module', if the package key associated with -- the module is the current home module do a look up in the home module. -- -- 4. Some special-case code in GHCi (ToDo: Figure out why that needs to -- call this.) findHomeModule :: HscEnv -> ModuleName -> IO FindResult findHomeModule hsc_env mod_name = homeSearchCache hsc_env mod_name $ let dflags = hsc_dflags hsc_env home_path = importPaths dflags hisuf = hiSuf dflags mod = mkModule (thisPackage dflags) mod_name source_exts = [ ("hs", mkHomeModLocationSearched dflags mod_name "hs") , ("lhs", mkHomeModLocationSearched dflags mod_name "lhs") , ("hsig", mkHomeModLocationSearched dflags mod_name "hsig") , ("lhsig", mkHomeModLocationSearched dflags mod_name "lhsig") ] hi_exts = [ (hisuf, mkHiOnlyModLocation dflags hisuf) , (addBootSuffix hisuf, mkHiOnlyModLocation dflags hisuf) ] -- In compilation manager modes, we look for source files in the home -- package because we can compile these automatically. In one-shot -- compilation mode we look for .hi and .hi-boot files only. exts | isOneShot (ghcMode dflags) = hi_exts | otherwise = source_exts in -- special case for GHC.Prim; we won't find it in the filesystem. -- This is important only when compiling the base package (where GHC.Prim -- is a home module). if mod == gHC_PRIM then return (Found (error "GHC.Prim ModLocation") mod) else searchPathExts home_path mod exts -- | Search for a module in external packages only. findPackageModule :: HscEnv -> Module -> IO FindResult findPackageModule hsc_env mod = do let dflags = hsc_dflags hsc_env pkg_id = modulePackageKey mod -- case lookupPackage dflags pkg_id of Nothing -> return (NoPackage pkg_id) Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf -- | Look up the interface file associated with module @mod@. This function -- requires a few invariants to be upheld: (1) the 'Module' in question must -- be the module identifier of the *original* implementation of a module, -- not a reexport (this invariant is upheld by @Packages.hs@) and (2) -- the 'PackageConfig' must be consistent with the package key in the 'Module'. -- The redundancy is to avoid an extra lookup in the package state -- for the appropriate config. findPackageModule_ :: HscEnv -> Module -> PackageConfig -> IO FindResult findPackageModule_ hsc_env mod pkg_conf = ASSERT( modulePackageKey mod == packageConfigId pkg_conf ) modLocationCache hsc_env mod $ -- special case for GHC.Prim; we won't find it in the filesystem. if mod == gHC_PRIM then return (Found (error "GHC.Prim ModLocation") mod) else let dflags = hsc_dflags hsc_env tag = buildTag dflags -- hi-suffix for packages depends on the build tag. package_hisuf | null tag = "hi" | otherwise = tag ++ "_hi" mk_hi_loc = mkHiOnlyModLocation dflags package_hisuf import_dirs = importDirs pkg_conf -- we never look for a .hi-boot file in an external package; -- .hi-boot files only make sense for the home package. in case import_dirs of [one] | MkDepend <- ghcMode dflags -> do -- there's only one place that this .hi file can be, so -- don't bother looking for it. let basename = moduleNameSlashes (moduleName mod) loc <- mk_hi_loc one basename return (Found loc mod) _otherwise -> searchPathExts import_dirs mod [(package_hisuf, mk_hi_loc)] -- ----------------------------------------------------------------------------- -- General path searching searchPathExts :: [FilePath] -- paths to search -> Module -- module name -> [ ( FileExt, -- suffix FilePath -> BaseName -> IO ModLocation -- action ) ] -> IO FindResult searchPathExts paths mod exts = do result <- search to_search {- hPutStrLn stderr (showSDoc $ vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts) , nest 2 (vcat (map text paths)) , case result of Succeeded (loc, p) -> text "Found" <+> ppr loc Failed fs -> text "not found"]) -} return result where basename = moduleNameSlashes (moduleName mod) to_search :: [(FilePath, IO ModLocation)] to_search = [ (file, fn path basename) | path <- paths, (ext,fn) <- exts, let base | path == "." = basename | otherwise = path </> basename file = base <.> ext ] search [] = return (NotFound { fr_paths = map fst to_search , fr_pkg = Just (modulePackageKey mod) , fr_mods_hidden = [], fr_pkgs_hidden = [] , fr_suggestions = [] }) search ((file, mk_result) : rest) = do b <- doesFileExist file if b then do { loc <- mk_result; return (Found loc mod) } else search rest mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt -> FilePath -> BaseName -> IO ModLocation mkHomeModLocationSearched dflags mod suff path basename = do mkHomeModLocation2 dflags mod (path </> basename) suff -- ----------------------------------------------------------------------------- -- Constructing a home module location -- This is where we construct the ModLocation for a module in the home -- package, for which we have a source file. It is called from three -- places: -- -- (a) Here in the finder, when we are searching for a module to import, -- using the search path (-i option). -- -- (b) The compilation manager, when constructing the ModLocation for -- a "root" module (a source file named explicitly on the command line -- or in a :load command in GHCi). -- -- (c) The driver in one-shot mode, when we need to construct a -- ModLocation for a source file named on the command-line. -- -- Parameters are: -- -- mod -- The name of the module -- -- path -- (a): The search path component where the source file was found. -- (b) and (c): "." -- -- src_basename -- (a): (moduleNameSlashes mod) -- (b) and (c): The filename of the source file, minus its extension -- -- ext -- The filename extension of the source file (usually "hs" or "lhs"). mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation mkHomeModLocation dflags mod src_filename = do let (basename,extension) = splitExtension src_filename mkHomeModLocation2 dflags mod basename extension mkHomeModLocation2 :: DynFlags -> ModuleName -> FilePath -- Of source module, without suffix -> String -- Suffix -> IO ModLocation mkHomeModLocation2 dflags mod src_basename ext = do let mod_basename = moduleNameSlashes mod obj_fn = mkObjPath dflags src_basename mod_basename hi_fn = mkHiPath dflags src_basename mod_basename return (ModLocation{ ml_hs_file = Just (src_basename <.> ext), ml_hi_file = hi_fn, ml_obj_file = obj_fn }) mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String -> IO ModLocation mkHiOnlyModLocation dflags hisuf path basename = do let full_basename = path </> basename obj_fn = mkObjPath dflags full_basename basename return ModLocation{ ml_hs_file = Nothing, ml_hi_file = full_basename <.> hisuf, -- Remove the .hi-boot suffix from -- hi_file, if it had one. We always -- want the name of the real .hi file -- in the ml_hi_file field. ml_obj_file = obj_fn } -- | Constructs the filename of a .o file for a given source file. -- Does /not/ check whether the .o file exists mkObjPath :: DynFlags -> FilePath -- the filename of the source file, minus the extension -> String -- the module name with dots replaced by slashes -> FilePath mkObjPath dflags basename mod_basename = obj_basename <.> osuf where odir = objectDir dflags osuf = objectSuf dflags obj_basename | Just dir <- odir = dir </> mod_basename | otherwise = basename -- | Constructs the filename of a .hi file for a given source file. -- Does /not/ check whether the .hi file exists mkHiPath :: DynFlags -> FilePath -- the filename of the source file, minus the extension -> String -- the module name with dots replaced by slashes -> FilePath mkHiPath dflags basename mod_basename = hi_basename <.> hisuf where hidir = hiDir dflags hisuf = hiSuf dflags hi_basename | Just dir <- hidir = dir </> mod_basename | otherwise = basename -- ----------------------------------------------------------------------------- -- Filenames of the stub files -- We don't have to store these in ModLocations, because they can be derived -- from other available information, and they're only rarely needed. mkStubPaths :: DynFlags -> ModuleName -> ModLocation -> FilePath mkStubPaths dflags mod location = let stubdir = stubDir dflags mod_basename = moduleNameSlashes mod src_basename = dropExtension $ expectJust "mkStubPaths" (ml_hs_file location) stub_basename0 | Just dir <- stubdir = dir </> mod_basename | otherwise = src_basename stub_basename = stub_basename0 ++ "_stub" in stub_basename <.> "h" -- ----------------------------------------------------------------------------- -- findLinkable isn't related to the other stuff in here, -- but there's no other obvious place for it findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable) findObjectLinkableMaybe mod locn = do let obj_fn = ml_obj_file locn maybe_obj_time <- modificationTimeIfExists obj_fn case maybe_obj_time of Nothing -> return Nothing Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time) -- Make an object linkable when we know the object file exists, and we know -- its modification time. findObjectLinkable :: Module -> FilePath -> UTCTime -> IO Linkable findObjectLinkable mod obj_fn obj_time = return (LM obj_time mod [DotO obj_fn]) -- We used to look for _stub.o files here, but that was a bug (#706) -- Now GHC merges the stub.o into the main .o (#3687) -- ----------------------------------------------------------------------------- -- Error messages cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc cannotFindModule = cantFindErr (sLit "Could not find module") (sLit "Ambiguous module name") cannotFindInterface :: DynFlags -> ModuleName -> FindResult -> SDoc cannotFindInterface = cantFindErr (sLit "Failed to load interface for") (sLit "Ambiguous interface for") cantFindErr :: LitString -> LitString -> DynFlags -> ModuleName -> FindResult -> SDoc cantFindErr _ multiple_found _ mod_name (FoundMultiple mods) | Just pkgs <- unambiguousPackages = hang (ptext multiple_found <+> quotes (ppr mod_name) <> colon) 2 ( sep [ptext (sLit "it was found in multiple packages:"), hsep (map ppr pkgs) ] ) | otherwise = hang (ptext multiple_found <+> quotes (ppr mod_name) <> colon) 2 ( vcat (map pprMod mods) ) where unambiguousPackages = foldl' unambiguousPackage (Just []) mods unambiguousPackage (Just xs) (m, ModOrigin (Just _) _ _ _) = Just (modulePackageKey m : xs) unambiguousPackage _ _ = Nothing pprMod (m, o) = ptext (sLit "it is bound as") <+> ppr m <+> ptext (sLit "by") <+> pprOrigin m o pprOrigin _ ModHidden = panic "cantFindErr: bound by mod hidden" pprOrigin m (ModOrigin e res _ f) = sep $ punctuate comma ( if e == Just True then [ptext (sLit "package") <+> ppr (modulePackageKey m)] else [] ++ map ((ptext (sLit "a reexport in package") <+>) .ppr.packageConfigId) res ++ if f then [ptext (sLit "a package flag")] else [] ) cantFindErr cannot_find _ dflags mod_name find_result = ptext cannot_find <+> quotes (ppr mod_name) $$ more_info where more_info = case find_result of NoPackage pkg -> ptext (sLit "no package matching") <+> quotes (ppr pkg) <+> ptext (sLit "was found") NotFound { fr_paths = files, fr_pkg = mb_pkg , fr_mods_hidden = mod_hiddens, fr_pkgs_hidden = pkg_hiddens , fr_suggestions = suggest } | Just pkg <- mb_pkg, pkg /= thisPackage dflags -> not_found_in_package pkg files | not (null suggest) -> pp_suggestions suggest $$ tried_these files | null files && null mod_hiddens && null pkg_hiddens -> ptext (sLit "It is not a module in the current program, or in any known package.") | otherwise -> vcat (map pkg_hidden pkg_hiddens) $$ vcat (map mod_hidden mod_hiddens) $$ tried_these files _ -> panic "cantFindErr" build_tag = buildTag dflags not_found_in_package pkg files | build_tag /= "" = let build = if build_tag == "p" then "profiling" else "\"" ++ build_tag ++ "\"" in ptext (sLit "Perhaps you haven't installed the ") <> text build <> ptext (sLit " libraries for package ") <> quotes (ppr pkg) <> char '?' $$ tried_these files | otherwise = ptext (sLit "There are files missing in the ") <> quotes (ppr pkg) <> ptext (sLit " package,") $$ ptext (sLit "try running 'ghc-pkg check'.") $$ tried_these files tried_these files | null files = Outputable.empty | verbosity dflags < 3 = ptext (sLit "Use -v to see a list of the files searched for.") | otherwise = hang (ptext (sLit "Locations searched:")) 2 $ vcat (map text files) pkg_hidden :: PackageKey -> SDoc pkg_hidden pkgid = ptext (sLit "It is a member of the hidden package") <+> quotes (ppr pkgid) --FIXME: we don't really want to show the package key here we should -- show the source package id or installed package id if it's ambiguous <> dot $$ cabal_pkg_hidden_hint pkgid cabal_pkg_hidden_hint pkgid | gopt Opt_BuildingCabalPackage dflags = let pkg = expectJust "pkg_hidden" (lookupPackage dflags pkgid) in ptext (sLit "Perhaps you need to add") <+> quotes (ppr (packageName pkg)) <+> ptext (sLit "to the build-depends in your .cabal file.") | otherwise = Outputable.empty mod_hidden pkg = ptext (sLit "it is a hidden module in the package") <+> quotes (ppr pkg) pp_suggestions :: [ModuleSuggestion] -> SDoc pp_suggestions sugs | null sugs = Outputable.empty | otherwise = hang (ptext (sLit "Perhaps you meant")) 2 (vcat (map pp_sugg sugs)) -- NB: Prefer the *original* location, and then reexports, and then -- package flags when making suggestions. ToDo: if the original package -- also has a reexport, prefer that one pp_sugg (SuggestVisible m mod o) = ppr m <+> provenance o where provenance ModHidden = Outputable.empty provenance (ModOrigin{ fromOrigPackage = e, fromExposedReexport = res, fromPackageFlag = f }) | Just True <- e = parens (ptext (sLit "from") <+> ppr (modulePackageKey mod)) | f && moduleName mod == m = parens (ptext (sLit "from") <+> ppr (modulePackageKey mod)) | (pkg:_) <- res = parens (ptext (sLit "from") <+> ppr (packageConfigId pkg) <> comma <+> ptext (sLit "reexporting") <+> ppr mod) | f = parens (ptext (sLit "defined via package flags to be") <+> ppr mod) | otherwise = Outputable.empty pp_sugg (SuggestHidden m mod o) = ppr m <+> provenance o where provenance ModHidden = Outputable.empty provenance (ModOrigin{ fromOrigPackage = e, fromHiddenReexport = rhs }) | Just False <- e = parens (ptext (sLit "needs flag -package-key") <+> ppr (modulePackageKey mod)) | (pkg:_) <- rhs = parens (ptext (sLit "needs flag -package-key") <+> ppr (packageConfigId pkg)) | otherwise = Outputable.empty
gcampax/ghc
compiler/main/Finder.hs
bsd-3-clause
25,473
1
20
7,392
4,951
2,521
2,430
392
11
module Problem54 where import Data.Char import Data.List main :: IO () main = do contents <- readFile "txt/54.txt" print . length . filter (== 1) . map (getWinner . splitAt 5 . map toCard . words) . lines $ contents getWinner :: ([Card], [Card]) -> Int getWinner (h1, h2) = if greater val1 val2 then 1 else 2 where val1 = getValue h1 val2 = getValue h2 data Card = Card {value :: Int, suit :: Char} deriving Show toCard :: String -> Card toCard [v, s] = Card v' s where v' = if '2' <= v && v <= '9' then ord v - ord '0' else case v of 'T' -> 10 'J' -> 11 'Q' -> 12 'K' -> 13 'A' -> 14 getValue :: [Card] -> [Int] getValue hand | same sortedValues [10 .. 14] && sameSuit hand = [23] | -- royal flush straight && sameSuit hand = [22, last sortedValues] | -- straight (assuming distinct cards) 4 `elem` valueCounts = [21, findCardWithCount 4, findCardWithCount 1] | -- four of a kind same (sort valueCounts) [2, 3] = [20, findCardWithCount 3, findCardWithCount 2] | -- full house sameSuit hand = 19 : reverseSortedValues | -- flush straight = [18, last sortedValues] | -- straight 3 `elem` valueCounts = [17, findCardWithCount 3] ++ filter (/= findCardWithCount 3) reverseSortedValues | -- three of a kind same (sort valueCounts) [1, 2, 2] = 16 : -- two pairs ( sortBy (flip compare) . map head . filter (\xs -> length xs == 2) . group $ sortedValues ) ++ [findCardWithCount 1] | 2 `elem` valueCounts = [15, findCardWithCount 2] ++ filter (/= findCardWithCount 2) reverseSortedValues | -- one pair otherwise = reverse sortedValues where sortedValues = sort . map value $ hand reverseSortedValues = reverse sortedValues valueCounts = map length . group $ sortedValues findCardWithCount n = head . head . filter (\xs -> length xs == n) . group $ sortedValues straight = same sortedValues [head sortedValues .. last sortedValues] && last sortedValues - head sortedValues == 4 sameSuit :: [Card] -> Bool sameSuit hand = all (\card -> suit card == suit (head hand)) hand same :: [Int] -> [Int] -> Bool same _ [] = True same [] _ = True same (x : xs) (y : ys) = x == y && same xs ys greater :: [Int] -> [Int] -> Bool greater _ [] = True greater [] _ = True greater (x : xs) (y : ys) | x > y = True | x < y = False | otherwise = greater xs ys
adityagupta1089/Project-Euler-Haskell
src/problems/Problem54.hs
bsd-3-clause
2,731
0
16
932
1,012
523
489
87
6
module Main ( main -- :: IO () ) where import Control.Monad (liftM) import Criterion.Main (bgroup, defaultMain) import BLAKE (benchmarks) import BLAKE2 (benchmarks) import Box (benchmarks) import ChaCha20 (benchmarks) import Curve25519 (benchmarks) import Ed25519 (benchmarks) import HMACSHA512 (benchmarks) import Nonce (benchmarks) import Poly1305 (benchmarks) import Random (benchmarks) import SecretBox (benchmarks) import SHA (benchmarks) import Siphash24 (benchmarks) import Siphash48 (benchmarks) import Stream (benchmarks) main :: IO () main = mapM (uncurry bencher) suites >>= defaultMain where bencher name act = bgroup name `liftM` act suites = [ ("BLAKE", BLAKE.benchmarks) , ("BLAKE2", BLAKE2.benchmarks) , ("Box", Box.benchmarks) , ("Curve25519", Curve25519.benchmarks) , ("Ed25519", Ed25519.benchmarks) , ("HMAC-SHA-512-256", HMACSHA512.benchmarks) , ("Nonce", Nonce.benchmarks) , ("Poly1305", Poly1305.benchmarks) , ("Random", Random.benchmarks) , ("SecretBox", SecretBox.benchmarks) , ("SHA", SHA.benchmarks) , ("Siphash24", Siphash24.benchmarks) , ("Siphash48", Siphash48.benchmarks) , ("Stream", Stream.benchmarks) , ("ChaCha20", ChaCha20.benchmarks) ]
thoughtpolice/hs-nacl
benchmarks/bench.hs
bsd-3-clause
1,801
0
9
760
374
230
144
37
1
#define IncludedmapShiftZero mapShiftZero :: RString -> RString -> List Integer -> Proof {-@ mapShiftZero :: target:RString -> i:RString -> is:List (GoodIndex i target) -> {map (shiftStringRight target stringEmp i) is == is } / [llen is] @-} mapShiftZero target i N = map (shiftStringRight target stringEmp i) N ==. N *** QED mapShiftZero target i (C x xs) = map (shiftStringRight target stringEmp i) (C x xs) ==. shiftStringRight target stringEmp i x `C` map (shiftStringRight target stringEmp i) xs ==. shift (stringLen stringEmp) x `C` map (shiftStringRight target stringEmp i) xs ==. shift 0 x `C` map (shiftStringRight target stringEmp i) xs ==. x `C` map (shiftStringRight target stringEmp i) xs ==. x `C` xs ? mapShiftZero target i xs *** QED
nikivazou/verified_string_matching
src/Proofs/mapShiftZero.hs
bsd-3-clause
781
0
19
154
251
126
125
11
1
{-# LANGUAGE CPP, BangPatterns #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} ------------------------------------------------------------------------------ -- | -- Module: Blaze.ByteString.Builder -- Copyright: (c) 2013 Leon P Smith -- License: BSD3 -- Maintainer: Leon P Smith <[email protected]> -- Stability: experimental -- -- An implementation of blaze-builder in terms of bytestring-builder. -- ------------------------------------------------------------------------------ module Blaze.ByteString.Builder ( -- * The 'Builder' type B.Builder -- * Creating builders , module Blaze.ByteString.Builder.Int , module Blaze.ByteString.Builder.Word , module Blaze.ByteString.Builder.ByteString , B.flush -- * Executing builders , B.toLazyByteString , toLazyByteStringWith , toByteString , toByteStringIO , toByteStringIOWith -- * 'Write's , W.Write , W.fromWrite , W.fromWriteSingleton , W.fromWriteList -- ** Writing 'Storable's , W.writeStorable , W.fromStorable , W.fromStorables ) where import Data.Monoid(Monoid(..)) import Control.Monad(when,unless) #if __GLASGOW_HASKELL__ >= 702 import Foreign import qualified Foreign.ForeignPtr.Unsafe as Unsafe #else import Foreign as Unsafe #endif import qualified Blaze.ByteString.Builder.Internal.Write as W import Blaze.ByteString.Builder.ByteString import Blaze.ByteString.Builder.Word import Blaze.ByteString.Builder.Int import Data.ByteString.Builder ( Builder ) import qualified Data.ByteString.Builder as B import qualified Data.ByteString.Builder.Extra as B import qualified Data.ByteString as S import qualified Data.ByteString.Internal as S import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Internal as L -- | Pack the chunks of a lazy bytestring into a single strict bytestring. packChunks :: L.ByteString -> S.ByteString packChunks lbs = do S.unsafeCreate (fromIntegral $ L.length lbs) (copyChunks lbs) where copyChunks !L.Empty !_pf = return () copyChunks !(L.Chunk (S.PS fpbuf o l) lbs') !pf = do withForeignPtr fpbuf $ \pbuf -> copyBytes pf (pbuf `plusPtr` o) l copyChunks lbs' (pf `plusPtr` l) toByteString :: Builder -> S.ByteString toByteString = packChunks . B.toLazyByteString -- | Default size (~32kb) for the buffer that becomes a chunk of the output -- stream once it is filled. -- defaultBufferSize :: Int defaultBufferSize = 32 * 1024 - overhead -- Copied from Data.ByteString.Lazy. where overhead = 2 * sizeOf (undefined :: Int) toByteStringIO :: (S.ByteString -> IO ()) -> Builder -> IO () toByteStringIO = toByteStringIOWith defaultBufferSize liftBufferWriter :: B.BufferWriter -> Int -> IO (S.ByteString, B.Next) liftBufferWriter write !bufSize = do fp <- S.mallocByteString bufSize (len, next) <- withForeignPtr fp $ \p -> write p bufSize -- Should we reallocate the string, at least in some cases? -- And if so, should we try to use realloc? In that case -- we would probably have to avoid allocating a foreign -- pointer, which means we would have to worry about leaking -- memory when exceptions happen... let !bs = S.PS fp 0 len return $! (bs,next) {-# INLINE liftBufferWriter #-} toByteStringIOWith :: Int -- ^ Buffer size (upper bounds -- the number of bytes forced -- per call to the 'IO' action). -> (S.ByteString -> IO ()) -- ^ 'IO' action to execute per -- full buffer, which is -- referenced by a strict -- 'S.ByteString'. -> Builder -- ^ 'Builder' to run. -> IO () -- ^ Resulting 'IO' action. toByteStringIOWith !bufSize io builder = do S.mallocByteString bufSize >>= getBuffer (B.runBuilder builder) bufSize where getBuffer writer !size fp = do let !ptr = Unsafe.unsafeForeignPtrToPtr fp (bytes, next) <- writer ptr size case next of B.Done -> io $! S.PS fp 0 bytes B.More req writer' -> do io $! S.PS fp 0 bytes let !size' = max bufSize req S.mallocByteString size' >>= getBuffer writer' size' B.Chunk bs' writer' -> do if bytes > 0 then do io $! S.PS fp 0 bytes unless (S.null bs') (io bs') S.mallocByteString bufSize >>= getBuffer writer' bufSize else do unless (S.null bs') (io bs') getBuffer writer' size fp {-- S.mallocByteString bufSize >>= getBuffer (B.runBuilder builder) bufSize where getBuffer writer len fp = do (bytes, next) <- withForeignPtr fp $ \p -> writer p len if bytes <= 0 then do case next of B.Done -> return () B.More req writer' -> do if req > bufSize then do fp' <- S.mallocByteString req getBuffer writer' req fp' else do getBuffer writer' len fp B.Chunk bs' writer' -> do unless (S.null bs') (io bs') getBuffer writer' len fp else do io $! S.PS fp 0 bytes case next of B.Done -> return () B.More req writer' -> do let !len' = max req bufSize fp' <- S.mallocByteString len' getBuffer writer' len' fp' B.Chunk bs' writer' -> do unless (S.null bs') (io bs') fp' <- S.mallocByteString bufSize getBuffer writer' bufSize fp' --} toLazyByteStringWith :: Int -> Int -> Int -> Builder -> L.ByteString -> L.ByteString toLazyByteStringWith bufSize _minBufSize firstBufSize builder k = B.toLazyByteStringWith (B.safeStrategy firstBufSize bufSize) k builder
lpsmith/blaze-builder-compat
src/Blaze/ByteString/Builder.hs
bsd-3-clause
6,342
0
20
2,064
1,032
566
466
89
4
module Day3 where import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as C import Data.ByteString (ByteString) import Data.Maybe import Data.Char data Unvalidated data Validated data P3 a = P3 !Int !Int !Int deriving (Show, Eq) validate :: P3 Unvalidated -> Maybe (P3 Validated) validate (P3 x y z) | x + y > z && x + z > y && y + z > x = Just (P3 x y z) | otherwise = Nothing readP3 :: ByteString -> P3 Unvalidated readP3 s = fromJust $ (C.readInt . (C.dropWhile isSpace)) s >>= \(x, s1) -> (C.readInt . (C.dropWhile isSpace)) s1 >>= \(y, s2) -> (C.readInt . (C.dropWhile isSpace)) s2 >>= \(z, _) -> return (P3 x y z) readP3s :: [ByteString] -> [P3 Unvalidated] readP3s bs | null bs = [] | otherwise = P3 x1 y1 z1 : P3 x2 y2 z2 : P3 x3 y3 z3 : readP3s bs' where (l1:l2:l3:_, bs') = splitAt 3 bs P3 x1 x2 x3 = readP3 l1 P3 y1 y2 y3 = readP3 l2 P3 z1 z2 z3 = readP3 l3 validTriangles = length . filter isJust . map (validate . readP3) . C.lines validTriangles2 = length . filter isJust . map validate . readP3s . C.lines
cl04/advent2016
src/Day3.hs
bsd-3-clause
1,134
0
15
295
538
273
265
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} module Data.Lambda.UnTyped where import Data.Data (Data) import Data.Typeable (Typeable) import Test.QuickCheck import Text.Read import Control.Applicative import Data.Name -- $setup -- >>> :set -XOverloadedStrings -- >>> :set -XScopedTypeVariables data Lambda = Variable Name | Lambda Name Lambda | Apply Lambda Lambda deriving (Eq, Ord, Data, Typeable) -- | >>> (Variable "x" `Apply` Variable "y") `Apply` Variable "z" -- x y z -- >>> Lambda "x" (Lambda "y" (Variable "y")) -- \ x y . y -- >>> Lambda "x" (Variable "x" `Apply` (Variable "y" `Apply` Variable "x")) -- \ x . x (y x) -- >>> Apply (Lambda "x" (Variable "x")) (Variable "y") -- (\ x . x) y instance Show Lambda where showsPrec _ (Variable x) = shows x showsPrec d x@Lambda{} = showParen (app_prec < d) (showString "\\ " . f x) where f (Lambda y z) = shows y . showChar ' ' . f z f y = showString ". " . shows y app_prec = 10 showsPrec d x@Apply{} = showParen (app_prec < d) (f x) where f (Apply y z) = f y . showChar ' ' . showsPrec (app_prec+1) z f y = showsPrec (app_prec+1) y app_prec = 10 -- | >>> read "x y z" :: Lambda -- x y z -- >>> read "\\ x y . y" :: Lambda -- \ x y . y -- >>> read "\\ x . \\ y . y" :: Lambda -- \ x y . y -- >>> read "\\ x . x y (y x)" :: Lambda -- \ x . x y (y x) -- >>> read "(\\ x . x) y" :: Lambda -- (\ x . x) y -- -- prop> \ (x :: Lambda) -> (read . show) x == x instance Read Lambda where readPrec = parens (app <++ lam <++ var) where var = Variable <$> readPrec lam = prec app_prec $ lexP >>= isLambda >> f where f = Lambda <$> readPrec <*> ((lexP >>= isDot >> reset readPrec) <++ f) app = prec app_prec $ foldl1 Apply <$> some (step readPrec) isLambda (Punc "\\") = return () isLambda _ = pfail isDot (Symbol ".") = return () isDot _ = pfail app_prec = 10 readsPrec = readPrec_to_S readPrec instance Arbitrary Lambda where arbitrary = frequency [ (,) 3 $ Variable <$> arbitrary , (,) 2 $ Lambda <$> arbitrary <*> arbitrary , (,) 2 $ Apply <$> arbitrary <*> arbitrary ] instance CoArbitrary Lambda where coarbitrary (Variable a) = coarbitrary a coarbitrary (Lambda a b) = coarbitrary a . coarbitrary b coarbitrary (Apply a b) = coarbitrary a . coarbitrary b sCombinator :: Lambda sCombinator = read "\\ f g x . f x (g x)" kCombinator :: Lambda kCombinator = read "\\ x y . x" iCombinator :: Lambda iCombinator = read "\\ x . x" -- | y f -> f (y f) yCombinator :: Lambda yCombinator = read "\\ f . (\\ x . f (x x)) (\\ x . f (x x))" -- | omega omega -> omega omega omegaCombinator :: Lambda omegaCombinator = read "(\\ x . x x) (\\ x . x x)"
kmyk/proof-haskell
Data/Lambda/UnTyped.hs
mit
2,796
0
15
745
752
396
356
54
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE Rank2Types #-} module CO4.THUtil where import Data.Generics (GenericT,everywhere,mkT) import qualified Language.Haskell.TH as TH import qualified Data.Map as M import CO4.Names import CO4.Util (extT') import CO4.Frontend.THPreprocess (noSignatureExpression,noSignaturePattern,noSignatureDeclarations) funD :: Namelike n => n -> [TH.Clause] -> TH.Dec funD n = TH.FunD $ toTHName n funD' :: Namelike n => n -> [TH.Pat] -> TH.Exp -> TH.Dec funD' n pats exp = TH.FunD (toTHName n) [TH.Clause pats (TH.NormalB exp) []] valD' :: Namelike n => n -> TH.Exp -> TH.Dec valD' n exp = TH.ValD (varP n) (TH.NormalB exp) [] sigD' :: Namelike n => n -> TH.Type -> TH.Dec sigD' n = TH.SigD (toTHName n) varE :: Namelike n => n -> TH.Exp varE = TH.VarE . toTHName conE :: Namelike n => n -> TH.Exp conE = TH.ConE . toTHName appsE :: TH.Exp -> [TH.Exp] -> TH.Exp appsE = foldl TH.AppE lamE' :: Namelike n => [n] -> TH.Exp -> TH.Exp lamE' ns = TH.LamE $ map varP ns letE' :: Namelike n => [(n,TH.Exp)] -> TH.Exp -> TH.Exp letE' bindings = TH.LetE $ map (uncurry valD') bindings caseE :: TH.Exp -> [(TH.Pat,TH.Exp)] -> TH.Exp caseE d = TH.CaseE d . map (\(p,m) -> TH.Match p (TH.NormalB m) []) intE :: Integral a => a -> TH.Exp intE = TH.LitE . TH.IntegerL . toInteger nameToIntE :: Namelike n => n -> TH.Exp nameToIntE n = intE i where i = (read $ fromName n) :: Integer stringE :: Namelike n => n -> TH.Exp stringE = TH.LitE . TH.StringL . fromName returnE :: TH.Exp -> TH.Exp returnE = TH.AppE $ TH.VarE 'return bindS' :: Namelike n => n -> TH.Exp -> TH.Stmt bindS' n = TH.BindS $ varP n varT :: Namelike n => n -> TH.Type varT = TH.VarT . toTHName conT :: Namelike n => n -> TH.Type conT name = if fromName name == listName then TH.ListT else TH.ConT $ toTHName name appsT :: TH.Type -> [TH.Type] -> TH.Type appsT = foldl TH.AppT varP :: Namelike n => n -> TH.Pat varP = TH.VarP . toTHName conP :: Namelike n => n -> [TH.Pat] -> TH.Pat conP n = TH.ConP $ toTHName n intP :: Integral a => a -> TH.Pat intP = TH.LitP . TH.IntegerL . toInteger normalC' :: Namelike n => n -> [TH.Type] -> TH.Con normalC' n = TH.NormalC (toTHName n) . map (\t -> ( TH.Bang TH.NoSourceUnpackedness TH.NoSourceStrictness , t )) toTHName :: Namelike n => n -> TH.Name toTHName = TH.mkName . fromName deleteSignatures :: GenericT deleteSignatures = everywhere $ extT' noSignatureDeclarations $ extT' noSignaturePattern $ mkT noSignatureExpression renameTHNames :: [(TH.Name,TH.Name)] -> GenericT renameTHNames renamings = let renamings' = M.fromList renamings rename name = M.findWithDefault name name renamings' in everywhere (mkT rename) typedUndefined :: TH.Type -> TH.Exp typedUndefined = TH.SigE $ TH.VarE 'undefined typedWildcard :: TH.Type -> TH.Pat typedWildcard = TH.SigP TH.WildP unqualifiedNames :: GenericT unqualifiedNames = everywhere $ mkT unqualifiedName where unqualifiedName = TH.mkName . TH.nameBase
apunktbau/co4
src/CO4/THUtil.hs
gpl-3.0
3,224
0
12
791
1,286
668
618
77
2
-- Copyright (C) 2017 Red Hat, Inc. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE TemplateHaskell #-} module BDCS.Label.Types(Label(..), labelDescriptions) where import Data.Aeson((.=), ToJSON, object, toJSON) import qualified Data.Text as T import Database.Persist.TH data Label = DocsLabel | FontsLabel | InfoPageLabel | LibraryLabel | LicenseLabel | ManPageLabel | ServiceLabel | TranslationLabel T.Text deriving(Eq, Read, Show) instance ToJSON Label where toJSON (TranslationLabel lang) = object ["TranslationLabel" .= toJSON lang] toJSON lbl = toJSON $ T.pack $ show lbl derivePersistField "Label" labelDescriptions :: [(String, String)] labelDescriptions = [ ("DocsLabel", "Documentation - mostly things in /usr/share/doc"), ("FontsLabel", "Fonts"), ("InfoPageLabel", "GNU info pages"), ("LibraryLabel", "Static and shared libraries"), ("LicenseLabel", "Files containing a software license"), ("ManPageLabel", "man pages"), ("ServiceLabel", "systemd .service files"), ("TranslationLabel", "Translations - takes a language code as argument") ]
atodorov/bdcs
src/BDCS/Label/Types.hs
lgpl-2.1
1,913
0
9
463
269
169
100
29
1
{-# LANGUAGE NoMonomorphismRestriction #-} module GramLab.Data.Diff.EditTree2Rev ( make , apply , size , check , EditTree(..) ) where import qualified GramLab.Data.Diff.EditTree2 as ET2 newtype EditTree s a = ETR (ET2.EditTree s a) deriving (Show,Eq,Ord) make xs ys = ETR (ET2.make (reverse xs) (reverse ys)) apply (ETR s) xs = reverse $ ET2.apply s (reverse xs) size (ETR s) = ET2.size s check (ETR s) xs = ET2.check s (reverse xs)
bitemyapp/morfette
src/GramLab/Data/Diff/EditTree2Rev.hs
bsd-2-clause
626
0
9
263
191
105
86
12
1
-- | The main loop of the server, processing human and computer player -- moves turn by turn. module Game.LambdaHack.Server.EndServer ( endOrLoop, dieSer ) where import Control.Monad import qualified Data.EnumMap.Strict as EM import Data.Maybe import Game.LambdaHack.Atomic import Game.LambdaHack.Common.Actor import Game.LambdaHack.Common.ActorState import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.Item import Game.LambdaHack.Common.Misc import Game.LambdaHack.Common.MonadStateRead import Game.LambdaHack.Common.State import Game.LambdaHack.Content.ModeKind import Game.LambdaHack.Server.CommonServer import Game.LambdaHack.Server.HandleEffectServer import Game.LambdaHack.Server.ItemServer import Game.LambdaHack.Server.MonadServer import Game.LambdaHack.Server.State -- | Continue or exit or restart the game. endOrLoop :: (MonadAtomic m, MonadServer m) => m () -> (Maybe (GroupName ModeKind) -> m ()) -> m () -> m () -> m () endOrLoop loop restart gameExit gameSave = do factionD <- getsState sfactionD let inGame fact = case gquit fact of Nothing -> True Just Status{stOutcome=Camping} -> True _ -> False gameOver = not $ any inGame $ EM.elems factionD let getQuitter fact = case gquit fact of Just Status{stOutcome=Restart, stNewGame} -> stNewGame _ -> Nothing quitters = mapMaybe getQuitter $ EM.elems factionD let isCamper fact = case gquit fact of Just Status{stOutcome=Camping} -> True _ -> False campers = filter (isCamper . snd) $ EM.assocs factionD -- Wipe out the quit flag for the savegame files. mapM_ (\(fid, fact) -> execUpdAtomic $ UpdQuitFaction fid Nothing (gquit fact) Nothing) campers bkpSave <- getsServer swriteSave when bkpSave $ do modifyServer $ \ser -> ser {swriteSave = False} gameSave case (quitters, campers) of (gameMode : _, _) -> restart $ Just gameMode _ | gameOver -> restart Nothing ([], []) -> loop -- continue current game ([], _ : _) -> gameExit -- don't call @loop@, that is, quit the game loop dieSer :: (MonadAtomic m, MonadServer m) => ActorId -> Actor -> Bool -> m () dieSer aid b hit = -- TODO: clients don't see the death of their last standing actor; -- modify Draw.hs and Client.hs to handle that if bproj b then do dropAllItems aid b hit b2 <- getsState $ getActorBody aid execUpdAtomic $ UpdDestroyActor aid b2 [] else do discoKind <- getsServer sdiscoKind trunk <- getsState $ getItemBody $ btrunk b let ikind = discoKind EM.! jkindIx trunk execUpdAtomic $ UpdRecordKill aid ikind 1 electLeader (bfid b) (blid b) aid tb <- getsState $ getActorBody aid deduceKilled aid tb -- tb has items not dropped, stash in inv fact <- getsState $ (EM.! bfid b) . sfactionD -- Prevent faction's stash from being lost in case they are not spawners. -- Projectiles can't drop stash, because they are blind and so the faction -- would not see the actor that drops the stash, leading to a crash. -- But this is OK; projectiles can't be leaders, so stash dropped earlier. when (isNothing $ gleader fact) $ moveStores aid CSha CInv dropAllItems aid b False b2 <- getsState $ getActorBody aid execUpdAtomic $ UpdDestroyActor aid b2 [] -- | Drop all actor's items. dropAllItems :: (MonadAtomic m, MonadServer m) => ActorId -> Actor -> Bool -> m () dropAllItems aid b hit = do mapActorCStore_ CInv (dropCStoreItem CInv aid b hit) b mapActorCStore_ CEqp (dropCStoreItem CEqp aid b hit) b
Concomitant/LambdaHack
Game/LambdaHack/Server/EndServer.hs
bsd-3-clause
3,617
0
16
786
1,004
514
490
-1
-1
{-# LANGUAGE CPP #-} module Main where import Prelude hiding ((+),map,(!!)) import Nat import Stream fib :: Nat -> Nat fib Zero = Zero fib (Succ Zero) = Succ Zero fib (Succ (Succ n)) = fib (Succ n) + fib n wrap :: Stream a -> (Nat -> a) wrap s n = s !! n unwrap :: (Nat -> a) -> Stream a unwrap f = map f nats main :: IO () main = print (fromNat $ fib $ toNat 30)
conal/hermit
examples/fib-stream/Fib.hs
bsd-2-clause
387
0
9
106
197
105
92
15
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash, UnboxedTuples, StandaloneDeriving, AutoDeriveTypeable, NegativeLiterals #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Int -- Copyright : (c) The University of Glasgow 1997-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- The sized integral datatypes, 'Int8', 'Int16', 'Int32', and 'Int64'. -- ----------------------------------------------------------------------------- module GHC.Int ( Int8(..), Int16(..), Int32(..), Int64(..), uncheckedIShiftL64#, uncheckedIShiftRA64# ) where import Data.Bits import Data.Maybe import GHC.Prim import GHC.Base import GHC.Enum import GHC.Num import GHC.Real import GHC.Read import GHC.Arr import GHC.Word hiding (uncheckedShiftL64#, uncheckedShiftRL64#) import GHC.Show import Data.Typeable ------------------------------------------------------------------------ -- type Int8 ------------------------------------------------------------------------ -- Int8 is represented in the same way as Int. Operations may assume -- and must ensure that it holds only values from its logical range. data {-# CTYPE "HsInt8" #-} Int8 = I8# Int# deriving (Eq, Ord, Typeable) -- ^ 8-bit signed integer type instance Show Int8 where showsPrec p x = showsPrec p (fromIntegral x :: Int) instance Num Int8 where (I8# x#) + (I8# y#) = I8# (narrow8Int# (x# +# y#)) (I8# x#) - (I8# y#) = I8# (narrow8Int# (x# -# y#)) (I8# x#) * (I8# y#) = I8# (narrow8Int# (x# *# y#)) negate (I8# x#) = I8# (narrow8Int# (negateInt# x#)) abs x | x >= 0 = x | otherwise = negate x signum x | x > 0 = 1 signum 0 = 0 signum _ = -1 fromInteger i = I8# (narrow8Int# (integerToInt i)) instance Real Int8 where toRational x = toInteger x % 1 instance Enum Int8 where succ x | x /= maxBound = x + 1 | otherwise = succError "Int8" pred x | x /= minBound = x - 1 | otherwise = predError "Int8" toEnum i@(I# i#) | i >= fromIntegral (minBound::Int8) && i <= fromIntegral (maxBound::Int8) = I8# i# | otherwise = toEnumError "Int8" i (minBound::Int8, maxBound::Int8) fromEnum (I8# x#) = I# x# enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen instance Integral Int8 where quot x@(I8# x#) y@(I8# y#) | y == 0 = divZeroError | y == (-1) && x == minBound = overflowError -- Note [Order of tests] | otherwise = I8# (narrow8Int# (x# `quotInt#` y#)) rem (I8# x#) y@(I8# y#) | y == 0 = divZeroError | otherwise = I8# (narrow8Int# (x# `remInt#` y#)) div x@(I8# x#) y@(I8# y#) | y == 0 = divZeroError | y == (-1) && x == minBound = overflowError -- Note [Order of tests] | otherwise = I8# (narrow8Int# (x# `divInt#` y#)) mod (I8# x#) y@(I8# y#) | y == 0 = divZeroError | otherwise = I8# (narrow8Int# (x# `modInt#` y#)) quotRem x@(I8# x#) y@(I8# y#) | y == 0 = divZeroError -- Note [Order of tests] | y == (-1) && x == minBound = (overflowError, 0) | otherwise = case x# `quotRemInt#` y# of (# q, r #) -> (I8# (narrow8Int# q), I8# (narrow8Int# r)) divMod x@(I8# x#) y@(I8# y#) | y == 0 = divZeroError -- Note [Order of tests] | y == (-1) && x == minBound = (overflowError, 0) | otherwise = case x# `divModInt#` y# of (# d, m #) -> (I8# (narrow8Int# d), I8# (narrow8Int# m)) toInteger (I8# x#) = smallInteger x# instance Bounded Int8 where minBound = -0x80 maxBound = 0x7F instance Ix Int8 where range (m,n) = [m..n] unsafeIndex (m,_) i = fromIntegral i - fromIntegral m inRange (m,n) i = m <= i && i <= n instance Read Int8 where readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s] instance Bits Int8 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (I8# x#) .&. (I8# y#) = I8# (word2Int# (int2Word# x# `and#` int2Word# y#)) (I8# x#) .|. (I8# y#) = I8# (word2Int# (int2Word# x# `or#` int2Word# y#)) (I8# x#) `xor` (I8# y#) = I8# (word2Int# (int2Word# x# `xor#` int2Word# y#)) complement (I8# x#) = I8# (word2Int# (not# (int2Word# x#))) (I8# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = I8# (narrow8Int# (x# `iShiftL#` i#)) | otherwise = I8# (x# `iShiftRA#` negateInt# i#) (I8# x#) `shiftL` (I# i#) = I8# (narrow8Int# (x# `iShiftL#` i#)) (I8# x#) `unsafeShiftL` (I# i#) = I8# (narrow8Int# (x# `uncheckedIShiftL#` i#)) (I8# x#) `shiftR` (I# i#) = I8# (x# `iShiftRA#` i#) (I8# x#) `unsafeShiftR` (I# i#) = I8# (x# `uncheckedIShiftRA#` i#) (I8# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = I8# x# | otherwise = I8# (narrow8Int# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#` (x'# `uncheckedShiftRL#` (8# -# i'#))))) where !x'# = narrow8Word# (int2Word# x#) !i'# = word2Int# (int2Word# i# `and#` 7##) bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i isSigned _ = True popCount (I8# x#) = I# (word2Int# (popCnt8# (int2Word# x#))) bit = bitDefault testBit = testBitDefault instance FiniteBits Int8 where finiteBitSize _ = 8 countLeadingZeros (I8# x#) = I# (word2Int# (clz8# (int2Word# x#))) countTrailingZeros (I8# x#) = I# (word2Int# (ctz8# (int2Word# x#))) {-# RULES "fromIntegral/Int8->Int8" fromIntegral = id :: Int8 -> Int8 "fromIntegral/a->Int8" fromIntegral = \x -> case fromIntegral x of I# x# -> I8# (narrow8Int# x#) "fromIntegral/Int8->a" fromIntegral = \(I8# x#) -> fromIntegral (I# x#) #-} {-# RULES "properFraction/Float->(Int8,Float)" properFraction = \x -> case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Int8) n, y :: Float) } "truncate/Float->Int8" truncate = (fromIntegral :: Int -> Int8) . (truncate :: Float -> Int) "floor/Float->Int8" floor = (fromIntegral :: Int -> Int8) . (floor :: Float -> Int) "ceiling/Float->Int8" ceiling = (fromIntegral :: Int -> Int8) . (ceiling :: Float -> Int) "round/Float->Int8" round = (fromIntegral :: Int -> Int8) . (round :: Float -> Int) #-} {-# RULES "properFraction/Double->(Int8,Double)" properFraction = \x -> case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Int8) n, y :: Double) } "truncate/Double->Int8" truncate = (fromIntegral :: Int -> Int8) . (truncate :: Double -> Int) "floor/Double->Int8" floor = (fromIntegral :: Int -> Int8) . (floor :: Double -> Int) "ceiling/Double->Int8" ceiling = (fromIntegral :: Int -> Int8) . (ceiling :: Double -> Int) "round/Double->Int8" round = (fromIntegral :: Int -> Int8) . (round :: Double -> Int) #-} ------------------------------------------------------------------------ -- type Int16 ------------------------------------------------------------------------ -- Int16 is represented in the same way as Int. Operations may assume -- and must ensure that it holds only values from its logical range. data {-# CTYPE "HsInt16" #-} Int16 = I16# Int# deriving (Eq, Ord, Typeable) -- ^ 16-bit signed integer type instance Show Int16 where showsPrec p x = showsPrec p (fromIntegral x :: Int) instance Num Int16 where (I16# x#) + (I16# y#) = I16# (narrow16Int# (x# +# y#)) (I16# x#) - (I16# y#) = I16# (narrow16Int# (x# -# y#)) (I16# x#) * (I16# y#) = I16# (narrow16Int# (x# *# y#)) negate (I16# x#) = I16# (narrow16Int# (negateInt# x#)) abs x | x >= 0 = x | otherwise = negate x signum x | x > 0 = 1 signum 0 = 0 signum _ = -1 fromInteger i = I16# (narrow16Int# (integerToInt i)) instance Real Int16 where toRational x = toInteger x % 1 instance Enum Int16 where succ x | x /= maxBound = x + 1 | otherwise = succError "Int16" pred x | x /= minBound = x - 1 | otherwise = predError "Int16" toEnum i@(I# i#) | i >= fromIntegral (minBound::Int16) && i <= fromIntegral (maxBound::Int16) = I16# i# | otherwise = toEnumError "Int16" i (minBound::Int16, maxBound::Int16) fromEnum (I16# x#) = I# x# enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen instance Integral Int16 where quot x@(I16# x#) y@(I16# y#) | y == 0 = divZeroError | y == (-1) && x == minBound = overflowError -- Note [Order of tests] | otherwise = I16# (narrow16Int# (x# `quotInt#` y#)) rem (I16# x#) y@(I16# y#) | y == 0 = divZeroError | otherwise = I16# (narrow16Int# (x# `remInt#` y#)) div x@(I16# x#) y@(I16# y#) | y == 0 = divZeroError | y == (-1) && x == minBound = overflowError -- Note [Order of tests] | otherwise = I16# (narrow16Int# (x# `divInt#` y#)) mod (I16# x#) y@(I16# y#) | y == 0 = divZeroError | otherwise = I16# (narrow16Int# (x# `modInt#` y#)) quotRem x@(I16# x#) y@(I16# y#) | y == 0 = divZeroError -- Note [Order of tests] | y == (-1) && x == minBound = (overflowError, 0) | otherwise = case x# `quotRemInt#` y# of (# q, r #) -> (I16# (narrow16Int# q), I16# (narrow16Int# r)) divMod x@(I16# x#) y@(I16# y#) | y == 0 = divZeroError -- Note [Order of tests] | y == (-1) && x == minBound = (overflowError, 0) | otherwise = case x# `divModInt#` y# of (# d, m #) -> (I16# (narrow16Int# d), I16# (narrow16Int# m)) toInteger (I16# x#) = smallInteger x# instance Bounded Int16 where minBound = -0x8000 maxBound = 0x7FFF instance Ix Int16 where range (m,n) = [m..n] unsafeIndex (m,_) i = fromIntegral i - fromIntegral m inRange (m,n) i = m <= i && i <= n instance Read Int16 where readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s] instance Bits Int16 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (I16# x#) .&. (I16# y#) = I16# (word2Int# (int2Word# x# `and#` int2Word# y#)) (I16# x#) .|. (I16# y#) = I16# (word2Int# (int2Word# x# `or#` int2Word# y#)) (I16# x#) `xor` (I16# y#) = I16# (word2Int# (int2Word# x# `xor#` int2Word# y#)) complement (I16# x#) = I16# (word2Int# (not# (int2Word# x#))) (I16# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = I16# (narrow16Int# (x# `iShiftL#` i#)) | otherwise = I16# (x# `iShiftRA#` negateInt# i#) (I16# x#) `shiftL` (I# i#) = I16# (narrow16Int# (x# `iShiftL#` i#)) (I16# x#) `unsafeShiftL` (I# i#) = I16# (narrow16Int# (x# `uncheckedIShiftL#` i#)) (I16# x#) `shiftR` (I# i#) = I16# (x# `iShiftRA#` i#) (I16# x#) `unsafeShiftR` (I# i#) = I16# (x# `uncheckedIShiftRA#` i#) (I16# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = I16# x# | otherwise = I16# (narrow16Int# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#` (x'# `uncheckedShiftRL#` (16# -# i'#))))) where !x'# = narrow16Word# (int2Word# x#) !i'# = word2Int# (int2Word# i# `and#` 15##) bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i isSigned _ = True popCount (I16# x#) = I# (word2Int# (popCnt16# (int2Word# x#))) bit = bitDefault testBit = testBitDefault instance FiniteBits Int16 where finiteBitSize _ = 16 countLeadingZeros (I16# x#) = I# (word2Int# (clz16# (int2Word# x#))) countTrailingZeros (I16# x#) = I# (word2Int# (ctz16# (int2Word# x#))) {-# RULES "fromIntegral/Word8->Int16" fromIntegral = \(W8# x#) -> I16# (word2Int# x#) "fromIntegral/Int8->Int16" fromIntegral = \(I8# x#) -> I16# x# "fromIntegral/Int16->Int16" fromIntegral = id :: Int16 -> Int16 "fromIntegral/a->Int16" fromIntegral = \x -> case fromIntegral x of I# x# -> I16# (narrow16Int# x#) "fromIntegral/Int16->a" fromIntegral = \(I16# x#) -> fromIntegral (I# x#) #-} {-# RULES "properFraction/Float->(Int16,Float)" properFraction = \x -> case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Int16) n, y :: Float) } "truncate/Float->Int16" truncate = (fromIntegral :: Int -> Int16) . (truncate :: Float -> Int) "floor/Float->Int16" floor = (fromIntegral :: Int -> Int16) . (floor :: Float -> Int) "ceiling/Float->Int16" ceiling = (fromIntegral :: Int -> Int16) . (ceiling :: Float -> Int) "round/Float->Int16" round = (fromIntegral :: Int -> Int16) . (round :: Float -> Int) #-} {-# RULES "properFraction/Double->(Int16,Double)" properFraction = \x -> case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Int16) n, y :: Double) } "truncate/Double->Int16" truncate = (fromIntegral :: Int -> Int16) . (truncate :: Double -> Int) "floor/Double->Int16" floor = (fromIntegral :: Int -> Int16) . (floor :: Double -> Int) "ceiling/Double->Int16" ceiling = (fromIntegral :: Int -> Int16) . (ceiling :: Double -> Int) "round/Double->Int16" round = (fromIntegral :: Int -> Int16) . (round :: Double -> Int) #-} ------------------------------------------------------------------------ -- type Int32 ------------------------------------------------------------------------ -- Int32 is represented in the same way as Int. data {-# CTYPE "HsInt32" #-} Int32 = I32# Int# deriving (Eq, Ord, Typeable) -- ^ 32-bit signed integer type instance Show Int32 where showsPrec p x = showsPrec p (fromIntegral x :: Int) instance Num Int32 where (I32# x#) + (I32# y#) = I32# (narrow32Int# (x# +# y#)) (I32# x#) - (I32# y#) = I32# (narrow32Int# (x# -# y#)) (I32# x#) * (I32# y#) = I32# (narrow32Int# (x# *# y#)) negate (I32# x#) = I32# (narrow32Int# (negateInt# x#)) abs x | x >= 0 = x | otherwise = negate x signum x | x > 0 = 1 signum 0 = 0 signum _ = -1 fromInteger i = I32# (narrow32Int# (integerToInt i)) instance Enum Int32 where succ x | x /= maxBound = x + 1 | otherwise = succError "Int32" pred x | x /= minBound = x - 1 | otherwise = predError "Int32" toEnum (I# i#) = I32# i# fromEnum (I32# x#) = I# x# enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen instance Integral Int32 where quot x@(I32# x#) y@(I32# y#) | y == 0 = divZeroError | y == (-1) && x == minBound = overflowError -- Note [Order of tests] | otherwise = I32# (narrow32Int# (x# `quotInt#` y#)) rem (I32# x#) y@(I32# y#) | y == 0 = divZeroError -- The quotRem CPU instruction fails for minBound `quotRem` -1, -- but minBound `rem` -1 is well-defined (0). We therefore -- special-case it. | y == (-1) = 0 | otherwise = I32# (narrow32Int# (x# `remInt#` y#)) div x@(I32# x#) y@(I32# y#) | y == 0 = divZeroError | y == (-1) && x == minBound = overflowError -- Note [Order of tests] | otherwise = I32# (narrow32Int# (x# `divInt#` y#)) mod (I32# x#) y@(I32# y#) | y == 0 = divZeroError -- The divMod CPU instruction fails for minBound `divMod` -1, -- but minBound `mod` -1 is well-defined (0). We therefore -- special-case it. | y == (-1) = 0 | otherwise = I32# (narrow32Int# (x# `modInt#` y#)) quotRem x@(I32# x#) y@(I32# y#) | y == 0 = divZeroError -- Note [Order of tests] | y == (-1) && x == minBound = (overflowError, 0) | otherwise = case x# `quotRemInt#` y# of (# q, r #) -> (I32# (narrow32Int# q), I32# (narrow32Int# r)) divMod x@(I32# x#) y@(I32# y#) | y == 0 = divZeroError -- Note [Order of tests] | y == (-1) && x == minBound = (overflowError, 0) | otherwise = case x# `divModInt#` y# of (# d, m #) -> (I32# (narrow32Int# d), I32# (narrow32Int# m)) toInteger (I32# x#) = smallInteger x# instance Read Int32 where readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s] instance Bits Int32 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (I32# x#) .&. (I32# y#) = I32# (word2Int# (int2Word# x# `and#` int2Word# y#)) (I32# x#) .|. (I32# y#) = I32# (word2Int# (int2Word# x# `or#` int2Word# y#)) (I32# x#) `xor` (I32# y#) = I32# (word2Int# (int2Word# x# `xor#` int2Word# y#)) complement (I32# x#) = I32# (word2Int# (not# (int2Word# x#))) (I32# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = I32# (narrow32Int# (x# `iShiftL#` i#)) | otherwise = I32# (x# `iShiftRA#` negateInt# i#) (I32# x#) `shiftL` (I# i#) = I32# (narrow32Int# (x# `iShiftL#` i#)) (I32# x#) `unsafeShiftL` (I# i#) = I32# (narrow32Int# (x# `uncheckedIShiftL#` i#)) (I32# x#) `shiftR` (I# i#) = I32# (x# `iShiftRA#` i#) (I32# x#) `unsafeShiftR` (I# i#) = I32# (x# `uncheckedIShiftRA#` i#) (I32# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = I32# x# | otherwise = I32# (narrow32Int# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#` (x'# `uncheckedShiftRL#` (32# -# i'#))))) where !x'# = narrow32Word# (int2Word# x#) !i'# = word2Int# (int2Word# i# `and#` 31##) bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i isSigned _ = True popCount (I32# x#) = I# (word2Int# (popCnt32# (int2Word# x#))) bit = bitDefault testBit = testBitDefault instance FiniteBits Int32 where finiteBitSize _ = 32 countLeadingZeros (I32# x#) = I# (word2Int# (clz32# (int2Word# x#))) countTrailingZeros (I32# x#) = I# (word2Int# (ctz32# (int2Word# x#))) {-# RULES "fromIntegral/Word8->Int32" fromIntegral = \(W8# x#) -> I32# (word2Int# x#) "fromIntegral/Word16->Int32" fromIntegral = \(W16# x#) -> I32# (word2Int# x#) "fromIntegral/Int8->Int32" fromIntegral = \(I8# x#) -> I32# x# "fromIntegral/Int16->Int32" fromIntegral = \(I16# x#) -> I32# x# "fromIntegral/Int32->Int32" fromIntegral = id :: Int32 -> Int32 "fromIntegral/a->Int32" fromIntegral = \x -> case fromIntegral x of I# x# -> I32# (narrow32Int# x#) "fromIntegral/Int32->a" fromIntegral = \(I32# x#) -> fromIntegral (I# x#) #-} {-# RULES "properFraction/Float->(Int32,Float)" properFraction = \x -> case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Int32) n, y :: Float) } "truncate/Float->Int32" truncate = (fromIntegral :: Int -> Int32) . (truncate :: Float -> Int) "floor/Float->Int32" floor = (fromIntegral :: Int -> Int32) . (floor :: Float -> Int) "ceiling/Float->Int32" ceiling = (fromIntegral :: Int -> Int32) . (ceiling :: Float -> Int) "round/Float->Int32" round = (fromIntegral :: Int -> Int32) . (round :: Float -> Int) #-} {-# RULES "properFraction/Double->(Int32,Double)" properFraction = \x -> case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Int32) n, y :: Double) } "truncate/Double->Int32" truncate = (fromIntegral :: Int -> Int32) . (truncate :: Double -> Int) "floor/Double->Int32" floor = (fromIntegral :: Int -> Int32) . (floor :: Double -> Int) "ceiling/Double->Int32" ceiling = (fromIntegral :: Int -> Int32) . (ceiling :: Double -> Int) "round/Double->Int32" round = (fromIntegral :: Int -> Int32) . (round :: Double -> Int) #-} instance Real Int32 where toRational x = toInteger x % 1 instance Bounded Int32 where minBound = -0x80000000 maxBound = 0x7FFFFFFF instance Ix Int32 where range (m,n) = [m..n] unsafeIndex (m,_) i = fromIntegral i - fromIntegral m inRange (m,n) i = m <= i && i <= n ------------------------------------------------------------------------ -- type Int64 ------------------------------------------------------------------------ data {-# CTYPE "HsInt64" #-} Int64 = I64# Int64# deriving( Typeable ) -- ^ 64-bit signed integer type instance Eq Int64 where (I64# x#) == (I64# y#) = isTrue# (x# `eqInt64#` y#) (I64# x#) /= (I64# y#) = isTrue# (x# `neInt64#` y#) instance Ord Int64 where (I64# x#) < (I64# y#) = isTrue# (x# `ltInt64#` y#) (I64# x#) <= (I64# y#) = isTrue# (x# `leInt64#` y#) (I64# x#) > (I64# y#) = isTrue# (x# `gtInt64#` y#) (I64# x#) >= (I64# y#) = isTrue# (x# `geInt64#` y#) instance Show Int64 where showsPrec p x = showsPrec p (toInteger x) instance Num Int64 where (I64# x#) + (I64# y#) = I64# (x# `plusInt64#` y#) (I64# x#) - (I64# y#) = I64# (x# `minusInt64#` y#) (I64# x#) * (I64# y#) = I64# (x# `timesInt64#` y#) negate (I64# x#) = I64# (negateInt64# x#) abs x | x >= 0 = x | otherwise = negate x signum x | x > 0 = 1 signum 0 = 0 signum _ = -1 fromInteger i = I64# (integerToInt64 i) instance Enum Int64 where succ x | x /= maxBound = x + 1 | otherwise = succError "Int64" pred x | x /= minBound = x - 1 | otherwise = predError "Int64" toEnum (I# i#) = I64# (intToInt64# i#) fromEnum x@(I64# x#) | x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int) = I# (int64ToInt# x#) | otherwise = fromEnumError "Int64" x enumFrom = integralEnumFrom enumFromThen = integralEnumFromThen enumFromTo = integralEnumFromTo enumFromThenTo = integralEnumFromThenTo instance Integral Int64 where quot x@(I64# x#) y@(I64# y#) | y == 0 = divZeroError | y == (-1) && x == minBound = overflowError -- Note [Order of tests] | otherwise = I64# (x# `quotInt64#` y#) rem (I64# x#) y@(I64# y#) | y == 0 = divZeroError -- The quotRem CPU instruction fails for minBound `quotRem` -1, -- but minBound `rem` -1 is well-defined (0). We therefore -- special-case it. | y == (-1) = 0 | otherwise = I64# (x# `remInt64#` y#) div x@(I64# x#) y@(I64# y#) | y == 0 = divZeroError | y == (-1) && x == minBound = overflowError -- Note [Order of tests] | otherwise = I64# (x# `divInt64#` y#) mod (I64# x#) y@(I64# y#) | y == 0 = divZeroError -- The divMod CPU instruction fails for minBound `divMod` -1, -- but minBound `mod` -1 is well-defined (0). We therefore -- special-case it. | y == (-1) = 0 | otherwise = I64# (x# `modInt64#` y#) quotRem x@(I64# x#) y@(I64# y#) | y == 0 = divZeroError -- Note [Order of tests] | y == (-1) && x == minBound = (overflowError, 0) | otherwise = (I64# (x# `quotInt64#` y#), I64# (x# `remInt64#` y#)) divMod x@(I64# x#) y@(I64# y#) | y == 0 = divZeroError -- Note [Order of tests] | y == (-1) && x == minBound = (overflowError, 0) | otherwise = (I64# (x# `divInt64#` y#), I64# (x# `modInt64#` y#)) toInteger (I64# x) = int64ToInteger x divInt64#, modInt64# :: Int64# -> Int64# -> Int64# -- Define div in terms of quot, being careful to avoid overflow (#7233) x# `divInt64#` y# | isTrue# (x# `gtInt64#` zero) && isTrue# (y# `ltInt64#` zero) = ((x# `minusInt64#` one) `quotInt64#` y#) `minusInt64#` one | isTrue# (x# `ltInt64#` zero) && isTrue# (y# `gtInt64#` zero) = ((x# `plusInt64#` one) `quotInt64#` y#) `minusInt64#` one | otherwise = x# `quotInt64#` y# where !zero = intToInt64# 0# !one = intToInt64# 1# x# `modInt64#` y# | isTrue# (x# `gtInt64#` zero) && isTrue# (y# `ltInt64#` zero) || isTrue# (x# `ltInt64#` zero) && isTrue# (y# `gtInt64#` zero) = if isTrue# (r# `neInt64#` zero) then r# `plusInt64#` y# else zero | otherwise = r# where !zero = intToInt64# 0# !r# = x# `remInt64#` y# instance Read Int64 where readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s] instance Bits Int64 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (I64# x#) .&. (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `and64#` int64ToWord64# y#)) (I64# x#) .|. (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `or64#` int64ToWord64# y#)) (I64# x#) `xor` (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `xor64#` int64ToWord64# y#)) complement (I64# x#) = I64# (word64ToInt64# (not64# (int64ToWord64# x#))) (I64# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = I64# (x# `iShiftL64#` i#) | otherwise = I64# (x# `iShiftRA64#` negateInt# i#) (I64# x#) `shiftL` (I# i#) = I64# (x# `iShiftL64#` i#) (I64# x#) `unsafeShiftL` (I# i#) = I64# (x# `uncheckedIShiftL64#` i#) (I64# x#) `shiftR` (I# i#) = I64# (x# `iShiftRA64#` i#) (I64# x#) `unsafeShiftR` (I# i#) = I64# (x# `uncheckedIShiftRA64#` i#) (I64# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = I64# x# | otherwise = I64# (word64ToInt64# ((x'# `uncheckedShiftL64#` i'#) `or64#` (x'# `uncheckedShiftRL64#` (64# -# i'#)))) where !x'# = int64ToWord64# x# !i'# = word2Int# (int2Word# i# `and#` 63##) bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i isSigned _ = True popCount (I64# x#) = I# (word2Int# (popCnt64# (int64ToWord64# x#))) bit = bitDefault testBit = testBitDefault -- give the 64-bit shift operations the same treatment as the 32-bit -- ones (see GHC.Base), namely we wrap them in tests to catch the -- cases when we're shifting more than 64 bits to avoid unspecified -- behaviour in the C shift operations. iShiftL64#, iShiftRA64# :: Int64# -> Int# -> Int64# a `iShiftL64#` b | isTrue# (b >=# 64#) = intToInt64# 0# | otherwise = a `uncheckedIShiftL64#` b a `iShiftRA64#` b | isTrue# (b >=# 64#) = if isTrue# (a `ltInt64#` (intToInt64# 0#)) then intToInt64# (-1#) else intToInt64# 0# | otherwise = a `uncheckedIShiftRA64#` b {-# RULES "fromIntegral/Int->Int64" fromIntegral = \(I# x#) -> I64# (intToInt64# x#) "fromIntegral/Word->Int64" fromIntegral = \(W# x#) -> I64# (word64ToInt64# (wordToWord64# x#)) "fromIntegral/Word64->Int64" fromIntegral = \(W64# x#) -> I64# (word64ToInt64# x#) "fromIntegral/Int64->Int" fromIntegral = \(I64# x#) -> I# (int64ToInt# x#) "fromIntegral/Int64->Word" fromIntegral = \(I64# x#) -> W# (int2Word# (int64ToInt# x#)) "fromIntegral/Int64->Word64" fromIntegral = \(I64# x#) -> W64# (int64ToWord64# x#) "fromIntegral/Int64->Int64" fromIntegral = id :: Int64 -> Int64 #-} -- No RULES for RealFrac methods if Int is smaller than Int64, we can't -- go through Int and whether going through Integer is faster is uncertain. instance FiniteBits Int64 where finiteBitSize _ = 64 countLeadingZeros (I64# x#) = I# (word2Int# (clz64# (int64ToWord64# x#))) countTrailingZeros (I64# x#) = I# (word2Int# (ctz64# (int64ToWord64# x#))) instance Real Int64 where toRational x = toInteger x % 1 instance Bounded Int64 where minBound = -0x8000000000000000 maxBound = 0x7FFFFFFFFFFFFFFF instance Ix Int64 where range (m,n) = [m..n] unsafeIndex (m,_) i = fromIntegral i - fromIntegral m inRange (m,n) i = m <= i && i <= n {- Note [Order of tests] ~~~~~~~~~~~~~~~~~~~~~~~~~ (See Trac #3065, #5161.) Suppose we had a definition like: quot x y | y == 0 = divZeroError | x == minBound && y == (-1) = overflowError | otherwise = x `primQuot` y Note in particular that the x == minBound test comes before the y == (-1) test. this expands to something like: case y of 0 -> divZeroError _ -> case x of -9223372036854775808 -> case y of -1 -> overflowError _ -> x `primQuot` y _ -> x `primQuot` y Now if we have the call (x `quot` 2), and quot gets inlined, then we get: case 2 of 0 -> divZeroError _ -> case x of -9223372036854775808 -> case 2 of -1 -> overflowError _ -> x `primQuot` 2 _ -> x `primQuot` 2 which simplifies to: case x of -9223372036854775808 -> x `primQuot` 2 _ -> x `primQuot` 2 Now we have a case with two identical branches, which would be eliminated (assuming it doesn't affect strictness, which it doesn't in this case), leaving the desired: x `primQuot` 2 except in the minBound branch we know what x is, and GHC cleverly does the division at compile time, giving: case x of -9223372036854775808 -> -4611686018427387904 _ -> x `primQuot` 2 So instead we use a definition like: quot x y | y == 0 = divZeroError | y == (-1) && x == minBound = overflowError | otherwise = x `primQuot` y which gives us: case y of 0 -> divZeroError -1 -> case x of -9223372036854775808 -> overflowError _ -> x `primQuot` y _ -> x `primQuot` y for which our call (x `quot` 2) expands to: case 2 of 0 -> divZeroError -1 -> case x of -9223372036854775808 -> overflowError _ -> x `primQuot` 2 _ -> x `primQuot` 2 which simplifies to: x `primQuot` 2 as required. But we now have the same problem with a constant numerator: the call (2 `quot` y) expands to case y of 0 -> divZeroError -1 -> case 2 of -9223372036854775808 -> overflowError _ -> 2 `primQuot` y _ -> 2 `primQuot` y which simplifies to: case y of 0 -> divZeroError -1 -> 2 `primQuot` y _ -> 2 `primQuot` y which simplifies to: case y of 0 -> divZeroError -1 -> -2 _ -> 2 `primQuot` y However, constant denominators are more common than constant numerators, so the y == (-1) && x == minBound order gives us better code in the common case. -}
pparkkin/eta
libraries/base/GHC/Int.hs
bsd-3-clause
33,337
0
17
11,098
8,718
4,484
4,234
564
2
{-#LANGUAGE ScopedTypeVariables #-} module Main where import CV.Image import CV.MultiresolutionSpline import CV.ImageOp import CV.Drawing import CV.Filters import CV.ImageMathOp import Control.Applicative import Data.Maybe import qualified CV.ImageMath as IM import CV.Transforms import System.Environment absTresh :: D32 -> Image GrayScale D32 -> Image GrayScale D32 absTresh t a = mask #* a where mask = unsafeImageTo32F $ t |> (IM.abs a::Image GrayScale D32) main = do [fn] <- getArgs Just img <- loadImage fn >>= return.fmap (enlarge 4) let reduce = reconstructFromLaplacian . map (absTresh 0.1) . laplacianPyramid 4 saveImage "denoising_result.png" $ montage (1,2) 2 $ [img,reduce img]
TomMD/CV
examples/PyramidNoise.hs
bsd-3-clause
728
0
14
131
237
124
113
21
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE ExistentialQuantification #-} -- | -- Module : Data.Stream.Monadic -- Copyright : (c) 2014 Kim Altintop -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable -- -- (Mostly mechanical) adaptation of the -- <http://hackage.haskell.org/package/stream-fusion/docs/Data-Stream.html Data.Stream> -- module from the -- <http://hackage.haskell.org/package/stream-fusion stream-fusion> package to a -- monadic 'Stream' datatype similar to the one -- <https://www.fpcomplete.com/blog/2014/08/conduit-stream-fusion proposed> by -- Michael Snoyman for the <http://hackage.haskell.org/package/conduit conduit> -- package. -- -- The intention here is to provide a high-level, "Data.List"-like interface to -- "Database.LevelDB.Iterator"s with predictable space and time complexity (see -- "Database.LevelDB.Streaming"), and without introducing a dependency eg. on -- one of the streaming libraries (all relevant datatypes are fully exported, -- though, so it should be straightforward to write wrappers for your favourite -- streaming library). -- -- Fusion and inlining rules and strictness annotations have been put in place -- faithfully, and may need further profiling. Also, some functions (from -- "Data.List") have been omitted for various reasons. Missing functions may be -- added upon <https://github.com/kim/leveldb-haskell/pulls request>. module Data.Stream.Monadic ( Step (..) , Stream (..) -- * Conversion with lists , toList , fromList -- * Basic functions , append , cons , snoc , head , last , tail , init , null , length -- finitary -- * Transformations , map , mapM , mapM_ , reverse , intersperse , intercalate -- * Folds , foldl , foldl' -- , foldl1 -- , foldl1' , foldr -- , foldr1 , foldMap , foldM , foldM_ -- * Special folds , concat , concatMap , and , or , any , all , sum , product --, maximum -- non-empty --, minimum -- non-empty -- * Building streams -- ** Scans , scanl -- , scanl1 -- , scanr -- , scanr1 -- Accumulating maps -- , mapAccumL -- , mapAccumR -- ** Infinite streams , iterate , repeat , replicate , cycle -- ** Unfolding , unfoldr , unfoldrM -- * Substreams -- ** Extracting substreams , take , drop , splitAt , takeWhile , dropWhile , span , break -- , group -- , inits -- , tails -- ** Predicates , isPrefixOf , isSuffixOf -- , isInfixOf -- would need 'tails' -- * Searching streams -- ** Searching by equality , elem , notElem , lookup -- ** Searching with a predicate , find , filter -- , partition -- Indexing streams -- does not make too much sense -- , index -- , findIndex -- , elemIndex -- , elemIndices -- , findIndices -- * Zipping and unzipping , zip , zip3 , zip4 , zipWith , zipWith3 , zipWith4 , unzip , unzip3 , unzip4 -- * Special streams -- strings - not applicable -- , lines -- , words -- , unlines -- , unwords -- ** \"Set\" operations -- , nub , delete -- , \\ -- , union -- , intersect -- , sort , insert -- * Generalized functions -- User-supplied equality, replacing an Eq context -- , nubBy , deleteBy -- , deleteFirstsBy -- , unionBy -- , intersectBy -- , groupBy -- ** User-supplied comparison, replacing an Ord context -- , sortBy , insertBy -- , maximumBy -- , minimumBy -- * The \"generic\" operations , genericLength , genericTake , genericDrop , genericSplitAt -- , genericIndex , genericReplicate , enumFromToInt , enumFromToChar , enumDeltaInteger ) where import Control.Applicative import Control.Monad (Monad (..), void, (=<<), (>=>)) import Data.Char (Char, chr, ord) import Data.Monoid import Debug.Trace import Prelude (Bool (..), Either (..), Eq (..), Functor (..), Int, Integer, Integral (..), Maybe (..), Num (..), Ord (..), Ordering (..), error, flip, not, otherwise, undefined, ($), (&&), (.), (||)) data Step a s = Yield a !s | Skip !s | Done data Stream m a = forall s. Stream (s -> m (Step a s)) (m s) instance Monad m => Functor (Stream m) where fmap = map toList :: (Functor m, Monad m) => Stream m a -> m [a] toList (Stream next s0) = unfold =<< s0 where unfold !s = do step <- next s case step of Done -> return [] Skip s' -> unfold s' Yield x s' -> (x :) <$> unfold s' {-# INLINE [0] toList #-} fromList :: Monad m => [a] -> Stream m a fromList xs = Stream next (return xs) where {-# INLINE next #-} next [] = return Done next (x:xs') = return $ Yield x xs' {-# INLINE [0] fromList #-} {-# RULES "Stream fromList/toList fusion" forall s. fmap fromList (toList s) = return s #-} append :: (Functor m, Monad m) => Stream m a -> Stream m a -> Stream m a append (Stream next0 s0) (Stream next1 s1) = Stream next (Left <$> s0) where {-# INLINE next #-} next (Left s) = do step <- next0 s case step of Done -> Skip . Right <$> s1 Skip s' -> return $ Skip (Left s') Yield x s' -> return $ Yield x (Left s') next (Right s) = do step <- next1 s return $ case step of Done -> Done Skip s' -> Skip (Right s') Yield x s' -> Yield x (Right s') {-# INLINE [0] append #-} cons :: (Functor m, Monad m) => a -> Stream m a -> Stream m a cons w (Stream next0 s0) = Stream next ((,) S2 <$> s0) where {-# INLINE next #-} next (S2, s) = return $ Yield w (S1, s) next (S1, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (S1, s') Yield x s' -> Yield x (S1, s') {-# INLINE [0] cons #-} snoc :: (Functor m, Monad m) => Stream m a -> a -> Stream m a snoc (Stream next0 s0) y = Stream next (Just <$> s0) where {-# INLINE next #-} next Nothing = return Done next (Just s) = do step <- next0 s return $ case step of Done -> Yield y Nothing Skip s' -> Skip (Just s') Yield x s' -> Yield x (Just s') {-# INLINE [0] snoc #-} -- | Unlike 'Data.List.head', this function does not diverge if the 'Stream' is -- empty. Instead, 'Nothing' is returned. head :: Monad m => Stream m a -> m (Maybe a) head (Stream next s0) = loop =<< s0 where loop !s = do step <- next s case step of Yield x _ -> return $ Just x Skip s' -> loop s' Done -> return Nothing {-# INLINE [0] head #-} -- | Unlike 'Data.List.last', this function does not diverge if the 'Stream' is -- empty. Instead, 'Nothing' is returned. last :: Monad m => Stream m a -> m (Maybe a) last (Stream next s0) = loop =<< s0 where loop !s = do step <- next s case step of Done -> return Nothing Skip s' -> loop s' Yield x s' -> loop' x s' loop' x !s = do step <- next s case step of Done -> return $ Just x Skip s' -> loop' x s' Yield x' s' -> loop' x' s' {-# INLINE [0] last #-} data Switch = S1 | S2 -- | Unlike 'Data.List.tail', this function does not diverge if the 'Stream' is -- empty. Instead, it is the identity in this case. tail :: (Functor m, Monad m) => Stream m a -> Stream m a tail (Stream next0 s0) = Stream next ((,) S1 <$> s0) where {-# INLINE next #-} next (S1, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (S1, s') Yield _ s' -> Skip (S2, s') next (S2, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (S2, s') Yield x s' -> Yield x (S2, s') {-# INLINE [0] tail #-} -- | Unlike 'Data.List.init', this function does not diverge if the 'Stream' is -- empty. Instead, it is the identity in this case. init :: (Functor m, Monad m) => Stream m a -> Stream m a init (Stream next0 s0) = Stream next ((,) Nothing <$> s0) where {-# INLINE next #-} next (Nothing, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (Nothing, s') Yield x s' -> Skip (Just x , s') next (Just x, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (Just x , s') Yield x' s' -> Yield x (Just x', s') {-# INLINE [0] init #-} null :: Monad m => Stream m a -> m Bool null (Stream next s0) = loop =<< s0 where loop !s = do step <- next s case step of Done -> return True Yield _ _ -> return False Skip s' -> loop s' {-# INLINE [0] null #-} length :: Monad m => Stream m a -> m Int length (Stream next s0) = loop 0 =<< s0 where loop !z !s = do step <- next s case step of Done -> return z Skip s' -> loop z s' Yield _ s' -> loop (z+1) s' {-# INLINE [0] length #-} elem :: (Eq a, Monad m) => a -> Stream m a -> m Bool elem x (Stream next s0) = loop =<< s0 where loop !s = do step <- next s case step of Done -> return False Skip s' -> loop s' Yield y s' | y == x -> return True | otherwise -> loop s' {-# INLINE [0] elem #-} notElem :: (Eq a, Monad m) => a -> Stream m a -> m Bool notElem x s = elem x s >>= return . not lookup :: (Eq a, Monad m) => a -> Stream m (a, b) -> m (Maybe b) lookup key (Stream next s0) = loop =<< s0 where loop !s = do step <- next s case step of Done -> return Nothing Skip s' -> loop s' Yield (x, y) s' | key == x -> return $ Just y | otherwise -> loop s' {-# INLINE [0] lookup #-} find :: Monad m => (a -> Bool) -> Stream m a -> m (Maybe a) find p = head . filter p {-# INLINE [0] find #-} filter :: Monad m => (a -> Bool) -> Stream m a -> Stream m a filter p (Stream next0 s0) = Stream next s0 where {-# INLINE next #-} next !s = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip s' Yield x s' | p x -> Yield x s' | otherwise -> Skip s' {-# INLINE [0] filter #-} {-# RULES "Stream filter/filter fusion" forall p q s. filter p (filter q s) = filter (\ x -> q x && p x) s #-} map :: Monad m => (a -> b) -> Stream m a -> Stream m b map f (Stream next0 s0) = Stream next s0 where {-# INLINE next #-} next !s = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip s' Yield x s' -> Yield (f x) s' {-# INLINE [0] map #-} {-# RULES "Stream map/map fusion" forall f g s. map f (map g s) = map (f . g) s #-} mapM :: (Functor m, Monad m) => (a -> m b) -> Stream m a -> Stream m b mapM f (Stream next0 s0) = Stream next s0 where {-# INLINE next #-} next !s = do step <- next0 s case step of Done -> return Done Skip s' -> return $ Skip s' Yield x s' -> (`Yield` s') <$> f x {-# INLINE [0] mapM #-} {-# RULES "Stream mapM/mapM fusion" forall f g s. mapM f (mapM g s) = mapM (g >=> f) s "Stream map/mapM fusion" forall f g s. map f (mapM g s) = mapM (fmap f . g) s "Stream mapM/map fusion" forall f g s. mapM f (map g s) = mapM (f . g) s #-} mapM_ :: (Functor m, Monad m) => (a -> m b) -> Stream m a -> Stream m () mapM_ f s = Stream go (return ()) where {-# INLINE go #-} go _ = foldM_ (\ _ -> void . f) () s >> return Done {-# INLINE [0] mapM_ #-} {-# RULES "Stream mapM_/mapM fusion" forall f g s. mapM_ f (mapM g s) = mapM_ (g >=> f) s "Stream mapM_/map fusion" forall f g s. mapM_ f (map g s) = mapM_ (f . g) s #-} reverse :: (Functor m, Monad m) => Stream m a -> m (Stream m a) reverse = foldl' (flip cons) (fromList []) {-# INLINE reverse #-} intersperse :: (Functor m, Monad m) => a -> Stream m a -> Stream m a intersperse sep (Stream next0 s0) = Stream next ((,,) Nothing S1 <$> s0) where {-# INLINE next #-} next (Nothing, S1, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (Nothing, S1, s') Yield x s' -> Skip (Just x , S1, s') next (Just x, S1, s) = return $ Yield x (Nothing, S2, s) next (Nothing, S2, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (Nothing, S2, s') Yield x s' -> Yield sep (Just x , S1, s') next (Just _, S2, _) = error "Data.Stream.Monadic.intersperse: impossible" {-# INLINE [0] intersperse #-} intercalate :: (Functor m, Monad m) => Stream m a -> Stream m [a] -> Stream m a intercalate sep s = first s `append` rest s where first = concat . take 1 rest = concatMap (append sep . fromList) . drop 1 {-# INLINE intercalate #-} --transpose :: Monad m => Stream m [a] -> Stream m [a] foldMap :: (Monoid m, Functor n, Monad n) => (a -> m) -> Stream n a -> n m foldMap f (Stream next s0) = loop mempty =<< s0 where loop z !s = do step <- next s case step of Done -> return z Skip s' -> loop z s' Yield x s' -> loop (z <> f x) s' {-# INLINE [0] foldMap #-} {-# RULES "Stream foldMap/map fusion" forall f g s. foldMap f (map g s) = foldMap (f . g) s "Stream foldMap/mapM fusion" forall f g s. foldMap f (mapM g s) = foldM (\ z' -> fmap ((z' <>) . f) . g) mempty s #-} foldl :: Monad m => (b -> a -> b) -> b -> Stream m a -> m b foldl f z0 (Stream next s0) = loop z0 =<< s0 where loop z !s = do step <- next s case step of Done -> return z Skip s' -> loop z s' Yield x s' -> loop (f z x) s' {-# INLINE [0] foldl #-} {-# RULES "Stream foldl/map fusion" forall f g z s. foldl f z (map g s) = foldl (\ z' -> f z' . g) z s "Stream foldl/mapM fusion" forall f g z s. foldl f z (mapM g s) = foldM (\ z' -> fmap (f z') . g) z s #-} foldl' :: Monad m => (b -> a -> b) -> b -> Stream m a -> m b foldl' f z0 (Stream next s0) = loop z0 =<< s0 where loop !z !s = do step <- next s case step of Done -> return z Skip s' -> loop z s' Yield x s' -> loop (f z x) s' {-# INLINE [0] foldl' #-} {-# RULES "Stream foldl'/map fusion" forall f g z s. foldl' f z (map g s) = foldl' (\ z' -> f z' . g) z s "Stream foldl'/mapM fusion" forall f g z s. foldl' f z (mapM g s) = foldM (\ z' -> fmap (f z') . g) z s #-} foldr :: (Functor m, Monad m) => (a -> b -> b) -> b -> Stream m a -> m b foldr f z (Stream next s0) = loop =<< s0 where loop !s = do step <- next s case step of Done -> return z Skip s' -> loop s' Yield x s' -> f x <$> loop s' {-# INLINE [0] foldr #-} {-# RULES "Stream foldr/map fusion" forall f g z s. foldr f z (map g s) = foldr (f . g) z s "Stream foldr/mapM fusion" forall f g z s. foldr f z (mapM g s) = foldM (\ z' -> fmap (`f` z') . g) z s #-} foldM :: Monad m => (b -> a -> m b) -> b -> Stream m a -> m b foldM f z0 (Stream next s0) = loop z0 =<< s0 where loop z !s = do step <- next s case step of Done -> return z Skip s' -> loop z s' Yield x s' -> f z x >>= (`loop` s') {-# INLINE [0] foldM #-} {-# RULES "Stream foldM/map fusion" forall f g z s. foldM f z (map g s) = foldM (\ z' -> f z' . g) z s "Stream foldM/mapM fusion" forall f g z s. foldM f z (mapM g s) = foldM (\ z' -> g >=> f z') z s #-} foldM_ :: Monad m => (b -> a -> m b) -> b -> Stream m a -> m () foldM_ f z s = foldM f z s >> return () {-# INLINE foldM_ #-} concat :: (Functor m, Monad m) => Stream m [a] -> Stream m a concat = concatMap fromList {-# INLINE concat #-} concatMap :: (Functor m, Monad m) => (a -> Stream m b) -> Stream m a -> Stream m b concatMap f (Stream next0 s0) = Stream next ((,) Nothing <$> s0) where {-# INLINE next #-} next (Nothing, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (Nothing , s') Yield x s' -> Skip (Just (f x), s') next (Just (Stream g t), s) = do step <- g =<< t return $ case step of Done -> Skip (Nothing , s) Skip t' -> Skip (Just (Stream g (return t')), s) Yield x t' -> Yield x (Just (Stream g (return t')), s) {-# INLINE [0] concatMap #-} {-# RULES "Stream concatMap/map fusion" forall f g s. concatMap f (map g s) = concatMap (f . g) s #-} and :: (Functor m, Monad m) => Stream m Bool -> m Bool and = foldr (&&) True {-# INLINE and #-} or :: (Functor m, Monad m) => Stream m Bool -> m Bool or = foldr (||) False {-# INLINE or #-} any :: Monad m => (a -> Bool) -> Stream m a -> m Bool any p (Stream next s0) = loop =<< s0 where loop !s = do step <- next s case step of Done -> return False Skip s' -> loop s' Yield x s' | p x -> return True | otherwise -> loop s' {-# INLINE [0] any #-} all :: Monad m => (a -> Bool) -> Stream m a -> m Bool all p (Stream next s0) = loop =<< s0 where loop !s = do step <- next s case step of Done -> return True Skip s' -> loop s' Yield x s' | p x -> loop s' | otherwise -> return False {-# INLINE [0] all #-} sum :: (Num a, Monad m) => Stream m a -> m a sum (Stream next s0) = loop 0 =<< s0 where loop !a !s = do step <- next s case step of Done -> return a Skip s' -> loop a s' Yield x s' -> loop (a + x) s' {-# INLINE [0] sum #-} product :: (Num a, Monad m) => Stream m a -> m a product (Stream next s0) = loop 1 =<< s0 where loop !a !s = do step <- next s case step of Done -> return a Skip s' -> loop a s' Yield x s' -> loop (a * x) s' {-# INLINE [0] product #-} scanl :: (Functor m, Monad m) => (b -> a -> b) -> b -> Stream m a -> Stream m b scanl f z0 = go . (`snoc` undefined) where {-# INLINE go #-} go (Stream step s0) = Stream (next step) ((,) z0 <$> s0) {-# INLINE next #-} next step (z, s) = do step' <- step s return $ case step' of Done -> Done Skip s' -> Skip (z , s') Yield x s' -> Yield z (f z x, s') {-# INLINE [0] scanl #-} iterate :: Monad m => (a -> a) -> a -> Stream m a iterate f x0 = Stream next (return x0) where {-# INLINE next #-} next x = return $ Yield x (f x) {-# INLINE [0] iterate #-} repeat :: Monad m => a -> Stream m a repeat x = Stream next (return ()) where {-# INLINE next #-} next _ = return $ Yield x () {-# INLINE [0] repeat #-} {-# RULES "map/repeat" forall f x. map f (repeat x) = repeat (f x) #-} replicate :: Monad m => Int -> a -> Stream m a replicate n x = Stream next (return n) where {-# INLINE next #-} next !i | i <= 0 = return Done | otherwise = return $ Yield x (i-1) {-# INLINE [0] replicate #-} {-# RULES "map/replicate" forall f n x. map f (replicate n x) = replicate n (f x) #-} -- | Unlike 'Data.List.cycle', this function does not diverge if the 'Stream' is -- empty. Instead, it is the identity in this case. cycle :: (Functor m, Monad m) => Stream m a -> Stream m a cycle (Stream next0 s0) = Stream next ((,) S1 <$> s0) where {-# INLINE next #-} next (S1, s) = do step <- next0 s return $ case step of Done -> Done -- error? Skip s' -> Skip (S1, s') Yield x s' -> Yield x (S2, s') next (S2, s) = do step <- next0 s case step of Done -> Skip . (,) S2 <$> s0 Skip s' -> return $ Skip (S2, s') Yield x s' -> return $ Yield x (S2, s') {-# INLINE [0] cycle #-} unfoldr :: Monad m => (b -> Maybe (a, b)) -> b -> Stream m a unfoldr f s0 = Stream next (return s0) where {-# INLINE next #-} next s = return $ case f s of Nothing -> Done Just (w, s') -> Yield w s' {-# INLINE [0] unfoldr #-} -- | Build a stream from a monadic seed (or state function). unfoldrM :: (Functor m, Monad m) => (b -> Maybe (a, m b)) -> m b -> Stream m a unfoldrM f = Stream next where {-# INLINE next #-} next s = case f s of Nothing -> return Done Just (w, s') -> Yield w <$> s' {-# INLINE [0] unfoldrM #-} isPrefixOf :: (Eq a, Monad m) => Stream m a -> Stream m a -> m Bool isPrefixOf (Stream nexta sa0) (Stream nextb sb0) = do sa0' <- sa0 sb0' <- sb0 loop sa0' sb0' Nothing where loop !sa !sb Nothing = do stepa <- nexta sa case stepa of Done -> return True Skip sa' -> loop sa' sb Nothing Yield x sa' -> loop sa' sb (Just x) loop !sa !sb (Just x) = do stepb <- nextb sb case stepb of Done -> return False Skip sb' -> loop sa sb' (Just x) Yield y sb' | x == y -> loop sa sb' Nothing | otherwise -> return False {-# INLINE [0] isPrefixOf #-} -- | Note that this is: -- -- > isSuffixOf a b = reverse a `isPrefixOf` reverse b -- -- It might be more efficient to construct the 'Stream's in reverse order and -- use 'isPrefixOf' directly, as 'reverse' is /O(n)/ and requires a finite -- stream argument. isSuffixOf :: (Eq a, Functor m, Monad m) => Stream m a -> Stream m a -> m Bool isSuffixOf sa sb = do ra <- reverse sa rb <- reverse sb ra `isPrefixOf` rb take :: (Functor m, Monad m) => Int -> Stream m a -> Stream m a take n0 (Stream next0 s0) = Stream next ((,) n0 <$> s0) where {-# INLINE next #-} next (!n, s) | n <= 0 = return Done | otherwise = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (n , s') Yield x s' -> Yield x (n-1, s') {-# INLINE [0] take #-} drop :: (Functor m, Monad m) => Int -> Stream m a -> Stream m a drop n0 (Stream next0 s0) = Stream next ((,) (Just (max 0 n0)) <$> s0) where {-# INLINE next #-} next (Just !n, s) | n == 0 = return $ Skip (Nothing, s) | otherwise = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (Just n , s') Yield _ s' -> Skip (Just (n-1), s') next (Nothing, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (Nothing, s') Yield x s' -> Yield x (Nothing, s') {-# INLINE [0] drop #-} -- | -- -- > splitAt n s = (take n s, drop n s) -- -- Note that the resulting 'Streams' share their state, so do not interleave -- traversals. splitAt :: (Functor m, Monad m) => Int -> Stream m a -> (Stream m a, Stream m a) -- not the most efficient solution, but allows the stream argument to be -- infinite splitAt n s = (take n s, drop n s) {-# INLINE splitAt #-} takeWhile :: Monad m => (a -> Bool) -> Stream m a -> Stream m a takeWhile p (Stream next0 s0) = Stream next s0 where {-# INLINE next #-} next !s = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip s' Yield x s' | p x -> Yield x s' | otherwise -> Done {-# INLINE [0] takeWhile #-} dropWhile :: (Functor m, Monad m) => (a -> Bool) -> Stream m a -> Stream m a dropWhile p (Stream next0 s0) = Stream next ((,) S1 <$> s0) where {-# INLINE next #-} next (S1, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (S1, s') Yield x s' | p x -> Skip (S1, s') | otherwise -> Yield x (S2, s') next (S2, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (S2, s') Yield x s' -> Yield x (S2, s') {-# INLINE [0] dropWhile #-} span :: (Functor m, Monad m) => (a -> Bool) -> Stream m a -> (Stream m a, Stream m a) span p s = (takeWhile p s, dropWhile p s) {-# INLINE span #-} break :: (Functor m, Monad m) => (a -> Bool) -> Stream m a -> (Stream m a, Stream m a) break p = span (not . p) {-# INLINE break #-} zip :: (Functor m, Applicative m, Monad m) => Stream m a -> Stream m b -> Stream m (a, b) zip = zipWith (,) {-# INLINE zip #-} zip3 :: (Functor m, Applicative m, Monad m) => Stream m a -> Stream m b -> Stream m c -> Stream m (a, b, c) zip3 = zipWith3 (,,) {-# INLINE zip3 #-} zip4 :: (Functor m, Applicative m, Monad m) => Stream m a -> Stream m b -> Stream m c -> Stream m d -> Stream m (a, b, c, d) zip4 = zipWith4 (,,,) {-# INLINE zip4 #-} zipWith :: (Functor m, Applicative m, Monad m) => (a -> b -> c) -> Stream m a -> Stream m b -> Stream m c zipWith f (Stream nexta sa0) (Stream nextb sb0) = Stream next ((,,) Nothing <$> sa0 <*> sb0) where {-# INLINE next #-} next (Nothing, sa, sb) = do step <- nexta sa return $ case step of Done -> Done Skip sa' -> Skip (Nothing, sa', sb) Yield a sa' -> Skip (Just a , sa', sb) next (Just a, sa', sb) = do step <- nextb sb return $ case step of Done -> Done Skip sb' -> Skip (Just a, sa', sb') Yield b sb' -> Yield (f a b) (Nothing, sa', sb') {-# INLINE [0] zipWith #-} zipWith3 :: (Functor m, Applicative m , Monad m) => (a -> b -> c -> d) -> Stream m a -> Stream m b -> Stream m c -> Stream m d zipWith3 f (Stream nexta sa0) (Stream nextb sb0) (Stream nextc sc0) = Stream next ((,,,) Nothing <$> sa0 <*> sb0 <*> sc0) where {-# INLINE next #-} next (Nothing, sa, sb, sc) = do step <- nexta sa return $ case step of Done -> Done Skip sa' -> Skip (Nothing , sa', sb, sc) Yield a sa' -> Skip (Just (a, Nothing), sa', sb, sc) next (Just (a, Nothing), sa', sb, sc) = do step <- nextb sb return $ case step of Done -> Done Skip sb' -> Skip (Just (a, Nothing), sa', sb', sc) Yield b sb' -> Skip (Just (a, Just b ), sa', sb', sc) next (Just (a, Just b), sa', sb', sc) = do step <- nextc sc return $ case step of Done -> Done Skip sc' -> Skip (Just (a, Just b), sa', sb', sc') Yield c sc' -> Yield (f a b c) (Nothing , sa', sb', sc') {-# INLINE [0] zipWith3 #-} zipWith4 :: (Functor m, Applicative m , Monad m) => (a -> b -> c -> d -> e) -> Stream m a -> Stream m b -> Stream m c -> Stream m d -> Stream m e zipWith4 f (Stream nexta sa0) (Stream nextb sb0) (Stream nextc sc0) (Stream nextd sd0) = Stream next ((,,,,) Nothing <$> sa0 <*> sb0 <*> sc0 <*> sd0) where {-# INLINE next #-} next (Nothing, sa, sb, sc, sd) = do step <- nexta sa return $ case step of Done -> Done Skip sa' -> Skip (Nothing , sa', sb, sc, sd) Yield a sa' -> Skip (Just (a, Nothing), sa', sb, sc, sd) next (Just (a, Nothing), sa', sb, sc, sd) = do step <- nextb sb return $ case step of Done -> Done Skip sb' -> Skip (Just (a, Nothing) , sa', sb', sc, sd) Yield b sb' -> Skip (Just (a, Just (b, Nothing)), sa', sb', sc, sd) next (Just (a, Just (b, Nothing)), sa', sb', sc, sd) = do step <- nextc sc return $ case step of Done -> Done Skip sc' -> Skip (Just (a, Just (b, Nothing)), sa', sb', sc', sd) Yield c sc' -> Skip (Just (a, Just (b, Just c)) , sa', sb', sc', sd) next (Just (a, Just (b, Just c)), sa', sb', sc', sd) = do step <- nextd sd return $ case step of Done -> Done Skip sd' -> Skip (Just (a, Just (b, Just c)), sa', sb', sc', sd') Yield d sd' -> Yield (f a b c d) (Nothing , sa', sb', sc', sd') {-# INLINE [0] zipWith4 #-} unzip :: (Functor m, Monad m) => Stream m (a, b) -> m ([a], [b]) unzip = foldr (\ (a,b) ~(as,bs) -> (a:as, b:bs)) ([],[]) {-# INLINE unzip #-} unzip3 :: (Functor m, Monad m) => Stream m (a, b, c) -> m ([a], [b], [c]) unzip3 = foldr (\ (a,b,c) ~(as,bs,cs) -> (a:as, b:bs, c:cs)) ([],[],[]) {-# INLINE unzip3 #-} unzip4 :: (Functor m, Monad m) => Stream m (a, b, c, d) -> m ([a], [b], [c], [d]) unzip4 = foldr (\ (a,b,c,d) ~(as,bs,cs,ds) -> (a:as, b:bs, c:cs, d:ds)) ([],[],[],[]) {-# INLINE unzip4 #-} delete :: (Eq a, Functor m, Monad m) => a -> Stream m a -> Stream m a delete = deleteBy (==) {-# INLINE delete #-} insert :: (Ord a, Functor m, Monad m) => a -> Stream m a -> Stream m a insert = insertBy compare {-# INLINE insert #-} deleteBy :: (Functor m, Monad m) => (a -> a -> Bool) -> a -> Stream m a -> Stream m a deleteBy eq a (Stream next0 s0) = Stream next ((,) S1 <$> s0) where {-# INLINE next #-} next (S1, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (S1, s') Yield x s' | a `eq` x -> Skip (S2, s') | otherwise -> Yield x (S1, s') next (S2, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (S2, s') Yield x s' -> Yield x (S2, s') {-# INLINE [0] deleteBy #-} insertBy :: (Functor m, Monad m) => (a -> a -> Ordering) -> a -> Stream m a -> Stream m a insertBy cmp x (Stream next0 s0) = Stream next ((,,) S2 Nothing <$> s0) where {-# INLINE next #-} next (S2, Nothing, s) = do step <- next0 s return $ case step of Done -> Yield x (S1, Nothing, s ) -- a snoc Skip s' -> Skip (S2, Nothing, s') Yield y s' | GT == cmp x y -> Yield y (S2, Nothing, s') | otherwise -> Yield x (S1, Just y , s ) -- insert next (S2, Just _, _) = error "Data.Stream.Monadic.insertBy: impossible" next (S1, Just y, s) = return $ Yield y (S1, Nothing, s) next (S1, Nothing, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (S1, Nothing, s') Yield y s' -> Yield y (S1, Nothing, s') {-# INLINE [0] insertBy #-} -- not sure why this is defined recursively (unlike 'length') genericLength :: (Num i, Functor m, Monad m) => Stream m a -> m i genericLength (Stream next s0) = loop =<< s0 where loop !s = do step <- next s case step of Done -> return 0 Skip s' -> loop s' Yield _ s' -> (1 +) <$> loop s' {-# INLINE [0] genericLength #-} genericTake :: (Integral i, Functor m, Monad m) => i -> Stream m a -> Stream m a genericTake n0 (Stream next0 s0) = Stream next ((,) n0 <$> s0) where {-# INLINE next #-} next (0, _) = return Done next (n, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (n , s') Yield x s' | n > 0 -> Yield x (n-1, s') | otherwise -> error "List.genericTake: negative argument" {-# INLINE [0] genericTake #-} genericDrop :: (Integral i, Functor m, Monad m) => i -> Stream m a -> Stream m a genericDrop n0 (Stream next0 s0) = Stream next ((,) (Just n0) <$> s0) where {-# INLINE next #-} next (Just 0, s) = return $ Skip (Nothing, s) next (Just n, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (Just n , s') Yield _ s' | n > 0 -> Skip (Just (n-1), s') | otherwise -> error "List.genericDrop: negative argument" next (Nothing, s) = do step <- next0 s return $ case step of Done -> Done Skip s' -> Skip (Nothing, s') Yield x s' -> Yield x (Nothing, s') {-# INLINE [0] genericDrop #-} genericSplitAt :: (Integral i, Functor m, Monad m) => i -> Stream m a -> (Stream m a, Stream m a) genericSplitAt i s = (genericTake i s, genericDrop i s) {-# INLINE genericSplitAt #-} genericReplicate :: (Integral i, Functor m, Monad m) => i -> a -> Stream m a genericReplicate n = genericTake n . repeat {-# INLINE [0] genericReplicate #-} {-# RULES "genericReplicate -> replicate/Int" genericReplicate = replicate :: Monad m => Int -> a -> Stream m a #-} -- TODO: is it possible to define rules which would rewrite @fromList [n..m]@ to -- one of the below? -- | Like @fromList ([n..m] :: [Int])@ but avoids allocating a list enumFromToInt :: Monad m => Int -> Int -> Stream m Int enumFromToInt x y = trace "enumFromToInt" $ Stream next (return x) where {-# INLINE next #-} next !n | n > y = return Done | otherwise = return $ Yield n (n+1) {-# INLINE [0] enumFromToInt #-} -- | Like @fromList ([n,n+d..] :: [Integer])@ but avoids allocating a list enumDeltaInteger :: Monad m => Integer -> Integer -> Stream m Integer enumDeltaInteger a d = trace "enumDeltaInteger" $ Stream next (return a) where {-# INLINE next #-} next !x = return $ Yield x (x+d) {-# INLINE [0] enumDeltaInteger #-} -- | Like @fromList ([n..m] :: [Char])@ but avoids allocating a list enumFromToChar :: Monad m => Char -> Char -> Stream m Char enumFromToChar x y = Stream next (return (ord x)) where m = ord y {-# INLINE next #-} next !n | n > m = return Done | otherwise = return $ Yield (chr n) (n+1) {-# INLINE [0] enumFromToChar #-}
kernelim/leveldb-haskell
src/Data/Stream/Monadic.hs
bsd-3-clause
35,760
0
19
12,970
12,346
6,276
6,070
868
12
{-# LANGUAGE GADTs #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeInType #-} module Bug where import Data.Kind data SameKind :: forall k. k -> k -> Type data Foo :: forall a k (b :: k). SameKind a b -> Type where MkFoo :: Foo sameKind
sdiehl/ghc
testsuite/tests/polykinds/T16247.hs
bsd-3-clause
250
0
7
50
68
42
26
-1
-1
{-# LANGUAGE TypeFamilies #-} module Tc251_Help where import Data.Kind (Type) class Cls a where type Fam a :: Type type Fam a = Maybe a
sdiehl/ghc
testsuite/tests/typecheck/should_compile/Tc251_Help.hs
bsd-3-clause
146
0
7
35
43
25
18
-1
-1
module GuardsCase1 where f x = case x of 1 -> let g x = x + 1 in g x _ -> 42
kmate/HaRe
old/testing/whereToLet/GuardsCase1_TokOut.hs
bsd-3-clause
113
0
12
60
49
24
25
4
2
{-# LANGUAGE TypeOperators, TypeFamilies #-} module T2544 where data (:|:) a b = Inl a | Inr b class Ix i where type IxMap i :: * -> * empty :: IxMap i [Int] data BiApp a b c = BiApp (a c) (b c) instance (Ix l, Ix r) => Ix (l :|: r) where type IxMap (l :|: r) = BiApp (IxMap l) (IxMap r) empty = BiApp empty empty -- [W] w1: a c ~ IxMap ii1 [Int] (from first 'empty') -- [W] w2: b c ~ IxMap ii2 [Int] (from second 'empty') -- [W] w3: BiApp a b c ~ IxMap (l :|: r) [Int] (from call of BiApp -- ~ BiApp (IxMap l) (IxMap r) [Int] -- If we process w3 first, we'll rewrite it with w1, w2 -- yielding two constraints (Ix io ~ IxMap l, Ix i1 ~ IxMap r) -- both with location of w3. Then we report just one of them, -- because we suppress multiple errors from the same location -- -- But if we process w1,w2 first, we'll get the same constraints -- but this time with different locations.
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/indexed-types/should_fail/T2544.hs
bsd-3-clause
977
0
8
286
166
98
68
10
0
{-# LANGUAGE RebindableSyntax, NPlusKPatterns #-} {-# OPTIONS -Wno-error=missing-monadfail-instances #-} module Main where { -- import Prelude; import qualified Prelude; import Prelude(String,undefined,Maybe(..),IO,putStrLn, Integer,(++),Rational, (==), (>=) ); debugFunc :: String -> IO a -> IO a; debugFunc s ioa = (putStrLn ("++ " ++ s)) Prelude.>> (ioa Prelude.>>= (\a -> (putStrLn ("-- " ++ s)) Prelude.>> (Prelude.return a) )); return :: a -> IO a; return a = debugFunc "return" (Prelude.return a); infixl 1 >>=; (>>=) :: IO a -> (a -> IO b) -> IO b; (>>=) ma amb = debugFunc ">>=" ((Prelude.>>=) ma amb); infixl 1 >>; (>>) :: IO a -> IO b -> IO b; (>>) ma mb = debugFunc ">>" ((Prelude.>>) ma mb); fail :: String -> IO a; fail s = debugFunc "fail" (Prelude.return undefined); -- fail s = debugFunc "fail" (Prelude.fail s); fromInteger :: Integer -> Integer; fromInteger a = a Prelude.+ a Prelude.+ a Prelude.+ a Prelude.+ a; -- five times fromRational :: Rational -> Rational; fromRational a = a Prelude.+ a Prelude.+ a; -- three times negate :: a -> a; negate a = a; -- don't actually negate (-) :: a -> a -> a; (-) x y = y; -- changed function test_do f g = do { f; -- >> Just a <- g; -- >>= (and fail if g returns Nothing) return a; -- return }; test_fromInteger = 27; test_fromRational = 31.5; test_negate a = - a; test_fromInteger_pattern a@1 = "1=" ++ (Prelude.show a); test_fromInteger_pattern a@(-2) = "(-2)=" ++ (Prelude.show a); test_fromInteger_pattern (a + 7) = "(a + 7)=" ++ Prelude.show a; test_fromRational_pattern [email protected] = "0.5=" ++ (Prelude.show a); test_fromRational_pattern a@(-0.7) = "(-0.7)=" ++ (Prelude.show a); test_fromRational_pattern a = "_=" ++ (Prelude.show a); doTest :: String -> IO a -> IO (); doTest s ioa = (putStrLn ("start test " ++ s)) Prelude.>> ioa Prelude.>> (putStrLn ("end test " ++ s)); main :: IO (); main = (doTest "test_do failure" (test_do (Prelude.return ()) (Prelude.return Nothing)) ) Prelude.>> (doTest "test_do success" (test_do (Prelude.return ()) (Prelude.return (Just ()))) ) Prelude.>> (doTest "test_fromInteger" (putStrLn (Prelude.show test_fromInteger)) ) Prelude.>> (doTest "test_fromRational" (putStrLn (Prelude.show test_fromRational)) ) Prelude.>> (doTest "test_negate" (putStrLn (Prelude.show (test_negate 3))) ) Prelude.>> (doTest "test_fromInteger_pattern 1" (putStrLn (test_fromInteger_pattern 1)) ) Prelude.>> (doTest "test_fromInteger_pattern (-2)" (putStrLn (test_fromInteger_pattern (-2))) ) Prelude.>> (doTest "test_fromInteger_pattern 9" (putStrLn (test_fromInteger_pattern 9)) ) Prelude.>> (doTest "test_fromRational_pattern 0.5" (putStrLn (test_fromRational_pattern 0.5)) ) Prelude.>> (doTest "test_fromRational_pattern (-0.7)" (putStrLn (test_fromRational_pattern (-0.7))) ) Prelude.>> (doTest "test_fromRational_pattern 1.7" (putStrLn (test_fromRational_pattern 1.7)) ); }
sdiehl/ghc
testsuite/tests/rebindable/rebindable3.hs
bsd-3-clause
4,339
1
23
1,893
1,121
611
510
82
1
module StackTest where import Control.Exception import System.Environment import System.FilePath import System.Directory import System.IO import System.Process import System.Exit run' :: FilePath -> [String] -> IO ExitCode run' cmd args = do putStrLn $ "Running " ++ cmd ++ " with args " ++ show args (Nothing, Nothing, Nothing, ph) <- createProcess (proc cmd args) waitForProcess ph run :: FilePath -> [String] -> IO () run cmd args = do ec <- run' cmd args if ec == ExitSuccess then return () else error $ "Exited with exit code: " ++ show ec stack' :: [String] -> IO ExitCode stack' args = do stack <- getEnv "STACK_EXE" run' stack args stack :: [String] -> IO () stack args = do ec <- stack' args if ec == ExitSuccess then return () else error $ "Exited with exit code: " ++ show ec stackErr :: [String] -> IO () stackErr args = do ec <- stack' args if ec == ExitSuccess then error "stack was supposed to fail, but didn't" else return () doesNotExist :: FilePath -> IO () doesNotExist fp = do putStrLn $ "doesNotExist " ++ fp exists <- doesFileOrDirExist fp case exists of (Right msg) -> error msg (Left _) -> return () doesExist :: FilePath -> IO () doesExist fp = do putStrLn $ "doesExist " ++ fp exists <- doesFileOrDirExist fp case exists of (Right msg) -> return () (Left _) -> error "No file or directory exists" doesFileOrDirExist :: FilePath -> IO (Either () String) doesFileOrDirExist fp = do isFile <- doesFileExist fp if isFile then return (Right ("File exists: " ++ fp)) else do isDir <- doesDirectoryExist fp if isDir then return (Right ("Directory exists: " ++ fp)) else return (Left ())
wskplho/stack
test/integration/lib/StackTest.hs
bsd-3-clause
1,836
0
15
516
644
314
330
59
3
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Betfair.StreamingAPI.API.Log ( Log , Direction(..) , toLog , tracePPLog , traceLog , stdOutAndLog ) where import qualified Data.Text as T import GHC.Show import Protolude hiding (empty, show) import qualified Protolude import Text.PrettyPrint.Leijen.Text (empty, space, string) import qualified Text.PrettyPrint.Leijen.Text as PP import Text.PrettyPrint.GenericPretty (Pretty (..), displayPrettyPrefix, pretty) import Betfair.StreamingAPI.API.Context type Log = Text data Direction = From | To | None instance Show Direction where show From = "--->" show To = "<---" show None = "" instance Pretty Direction where pretty From = string "--->" PP.<> space pretty To = string "<---" PP.<> space pretty None = empty toLog :: Context -> Text -> IO () toLog = cLogger toText :: Show a => Direction -> a -> Text toText d t = Protolude.show d <> T.singleton (' ' :: Char) <> Protolude.show t stdOutAndLog :: Context -> Direction -> Text -> IO () stdOutAndLog c d s = let output = displayPrettyPrefix d s in toLog c output >> putText s tracePPLog :: Pretty a => Context -> Direction -> a -> IO a tracePPLog c d s = (toLog c . displayPrettyPrefix d) s >> return s traceLog :: Show a => Context -> Direction -> a -> IO a traceLog c d s = (toLog c . toText d) s >> return s
joe9/streaming-betfair-api
src/Betfair/StreamingAPI/API/Log.hs
mit
1,581
0
9
412
490
265
225
51
1
-- Reverse list -- https://www.codewars.com/kata/57a04da9e298a7ee43000111 module ReverseList where reverseList :: [Int] -> [Int] reverseList = reverse
gafiatulin/codewars
src/7 kyu/ReverseList.hs
mit
153
0
6
18
26
17
9
3
1
-- Lua 5.2 Parser using Parsec -- Matt Donovan module Parser ( parseFile , parseString , Chunk(..) , Stat(..) , RetStat(..) , Var(..) , Exp(..) , TblLookup(..) , FnCall(..) , FnCallArgs(..) , Args(..) , FuncBody(..) , ParList(..) , Field(..) , BinOp(..) , UnOp(..) ) where import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Language import Text.ParserCombinators.Parsec.Expr import qualified Text.ParserCombinators.Parsec.Token as Token import Data.Maybe (isNothing) parseFile :: String -> IO Chunk parseFile file = do program <- readFile file case parse whileParser "" program of Left e -> print e >> fail "parse error" Right r -> return r parseString :: String -> Chunk parseString str = case parse whileParser "" str of Left e -> error $ show e Right r -> r -- Lua AST data types data Chunk = Chunk [Stat] (Maybe RetStat) deriving (Show) data Stat = AssignStat [Var] [Exp] | FnCallStat FnCall | LabelStat String | BreakStat | GotoStat String | DoStat Chunk | WhileStat Exp Chunk | RepeatStat Chunk Exp | IfStat Exp Chunk [(Exp, Chunk)] (Maybe Chunk) | ForStat String Exp Exp (Maybe Exp) Chunk | ForInStat [String] [Exp] Chunk | FnDecStat [String] (Maybe String) FuncBody | LocalFnStat String FuncBody | LocalVarStat [String] [Exp] deriving (Show) data RetStat = RetStat [Exp] deriving (Show) data Var = NameVar String [TblLookup] | FnCallVar FnCall [TblLookup] | ExpVar Exp [TblLookup] deriving (Show) data Exp = NilExp | FalseExp | TrueExp | NumberExp Double | StringExp String | VarArgExp | FuncExp FuncBody | NameExp String [TblLookup] | FnCallExp FnCall [TblLookup] | TblCtorExp [Field] | BinExp BinOp Exp Exp | UnOpExp UnOp Exp deriving (Show) data TblLookup = NameTblLookup String | ExpTblLookup Exp deriving (Show) data FnCall = NameFnCall String [FnCallArgs] | ExpFnCall Exp [FnCallArgs] deriving (Show) data FnCallArgs = FnCallArgs [TblLookup] Args | TblFnCallArgs [TblLookup] String Args deriving (Show) data Args = ExpArgs [Exp] | TblCtorArgs [Field] | StrArgs String deriving (Show) data FuncBody = FuncBody ParList Chunk deriving (Show) -- List of param names and whether there's variable number of args data ParList = ParList [String] Bool deriving (Show) data Field = ExpField Exp | ExpExpField Exp Exp | NameExpField String Exp deriving (Show) data BinOp = AddBinOp | SubBinOp | MultBinOp | DivBinOp | ExpBinOp | ModBinOp | ConcatBinOp | LTBinOp | LTEBinOp | GTBinOp | GTEBinOp | EqBinOp | NEqBinOp | AndBinOp | OrBinOp deriving (Show) data UnOp = NegateUnOp | NotUnOp | HashUnOp deriving (Show) -- Lexical token definitions languageDef = emptyDef { Token.commentStart = "" , Token.commentEnd = "" , Token.commentLine = "--" , Token.identStart = letter , Token.identLetter = alphaNum , Token.opStart = oneOf "+-*/^%.<>=~#:" , Token.opLetter = oneOf "=:." , Token.reservedNames = ["and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while" ] , Token.reservedOpNames = ["+", "-", "*", "/", "^", "%", ".." ,"<", "<=", ">", ">=", "==", "~=" ,"#", "=", "...", ".", ":" ] } lexer = Token.makeTokenParser languageDef identifier = Token.identifier lexer reserved = Token.reserved lexer reservedOp = Token.reservedOp lexer parens = Token.parens lexer brackets = Token.brackets lexer braces = Token.braces lexer integer = Token.integer lexer float = Token.float lexer semi = Token.semi lexer whiteSpace = Token.whiteSpace lexer comma = Token.comma lexer stringLiteral = Token.stringLiteral lexer -- Parser functions whileParser :: Parser Chunk whileParser = whiteSpace >> (do { c <- parseChunk; eof; return c}) parseNumber :: Parser Double parseNumber = try float <|> do { i <- integer; return $ fromIntegral i } parseChunk :: Parser Chunk parseChunk = do stats <- (endBy parseStat (optional semi)) retStat <- optionMaybe parseRetStat return $ Chunk stats retStat parseStat :: Parser Stat parseStat = try assignStat <|> fnCallStat <|> labelStat <|> breakStat <|> gotoStat <|> doStat <|> whileStat <|> repeatStat <|> ifStat <|> (try forStat) <|> forInStat <|> funcDecStat <|> (try localFuncStat) <|> localVarStat where assignStat = do vars <- parseVarList reservedOp "=" exps <- parseExpList return $ AssignStat vars exps fnCallStat = do f <- parseFnCall return $ FnCallStat f labelStat = do reservedOp "::" id <- identifier reservedOp "::" return $ LabelStat id breakStat = do reserved "break" return BreakStat gotoStat = do reserved "goto" id <- identifier return $ GotoStat id doStat = do reserved "do" block <- parseChunk reserved "end" return $ DoStat block whileStat = do reserved "while" exp <- parseExp reserved "do" block <- parseChunk reserved "end" return $ WhileStat exp block repeatStat = do reserved "repeat" block <- parseChunk reserved "until" exp <- parseExp return $ RepeatStat block exp ifStat = do reserved "if" exp <- parseExp reserved "then" block <- parseChunk elifs <- many (do reserved "elseif" e <- parseExp reserved "then" b <- parseChunk return (e,b)) els <- optionMaybe (do {reserved "else"; parseChunk}) reserved "end" return $ IfStat exp block elifs els forStat = do reserved "for" id <- identifier reservedOp "=" exp1 <- parseExp comma exp2 <- parseExp exp3 <- optionMaybe $ do {comma; parseExp} reserved "do" block <- parseChunk reserved "end" return $ ForStat id exp1 exp2 exp3 block forInStat = do reserved "for" ids <- parseNameList reserved "in" exps <- parseExpList reserved "do" block <- parseChunk reserved "end" return $ ForInStat ids exps block funcDecStat = do reserved "function" ids <- sepBy1 identifier (reservedOp ".") id2 <- optionMaybe $ do {reservedOp ":"; identifier} funcBody <- parseFuncBody return $ FnDecStat ids id2 funcBody localFuncStat = do reserved "local" reserved "function" id <- identifier funcBody <- parseFuncBody return $ LocalFnStat id funcBody localVarStat = do reserved "local" ids <- parseNameList exps <- option [] $ do {reservedOp "="; parseExpList} return $ LocalVarStat ids exps parseRetStat = do reserved "return" exps <- option [] parseExpList option "" semi return $ RetStat exps parseVarList :: Parser [Var] parseVarList = sepBy1 parseVar comma parseVar :: Parser Var parseVar = try fnCallVar <|> expVar <|> nameVar where fnCallVar = do fnCall <- parseFnCall tblLookups <- many1 parseTblLookup return $ FnCallVar fnCall tblLookups expVar = do exp <- parens parseExp tblLookups <- many1 parseTblLookup return $ ExpVar exp tblLookups nameVar = do id <- identifier tblLookups <- many parseTblLookup return $ NameVar id tblLookups parseNameList :: Parser [String] parseNameList = sepBy1 identifier comma parseExpList :: Parser [Exp] parseExpList = sepBy1 parseExp comma parseExp = buildExpressionParser opTable parseExpTerm where parseExpTerm = parens parseExp <|> exp opTable = [[Infix (reservedOp "^" >> return (BinExp ExpBinOp)) AssocLeft], [Prefix (reserved "not" >> return (UnOpExp NotUnOp)), Prefix (reservedOp "#" >> return (UnOpExp HashUnOp)), Prefix (reservedOp "-" >> return (UnOpExp NegateUnOp))], [Infix (reservedOp "*" >> return (BinExp MultBinOp)) AssocLeft, Infix (reservedOp "/" >> return (BinExp DivBinOp)) AssocLeft, Infix (reservedOp "%" >> return (BinExp ModBinOp)) AssocLeft], [Infix (reservedOp "+" >> return (BinExp AddBinOp)) AssocLeft, Infix (reservedOp "-" >> return (BinExp SubBinOp)) AssocLeft], [Infix (reservedOp ">" >> return (BinExp GTBinOp)) AssocLeft, Infix (reservedOp ">=" >> return (BinExp GTEBinOp)) AssocLeft, Infix (reservedOp "<" >> return (BinExp LTBinOp)) AssocLeft, Infix (reservedOp "<=" >> return (BinExp LTEBinOp)) AssocLeft, Infix (reservedOp "~=" >> return (BinExp NEqBinOp)) AssocLeft, Infix (reservedOp "==" >> return (BinExp EqBinOp)) AssocLeft], [Infix (reserved "and" >> return (BinExp AndBinOp)) AssocLeft], [Infix (reserved "or" >> return (BinExp OrBinOp)) AssocLeft] ] exp = nilExp <|> falseExp <|> trueExp <|> strExp <|> varArgExp <|> fnDefExp <|> (try fnCallExp) <|> nameExp <|> tblCtorExp <|> numExp nilExp = reserved "nil" >> return NilExp falseExp = reserved "false" >> return FalseExp trueExp = reserved "true" >> return TrueExp varArgExp = reservedOp "..." >> return VarArgExp numExp = do n <- parseNumber return $ NumberExp n strExp = do s <- stringLiteral return $ StringExp s fnDefExp = do reserved "function" funcBody <- parseFuncBody return $ FuncExp funcBody fnCallExp = do f <- parseFnCall tblLookups <- many parseTblLookup return $ FnCallExp f tblLookups nameExp = do id <- identifier tblLookups <- many parseTblLookup return $ NameExp id tblLookups tblCtorExp = do fieldlist <- parseTblCtor return $ TblCtorExp fieldlist parseTblLookup :: Parser TblLookup parseTblLookup = expTblLookup <|> nameTblLookup where expTblLookup = do exp <- brackets parseExp return $ ExpTblLookup exp nameTblLookup = do reservedOp "." id <- identifier return $ NameTblLookup id parseFnCall :: Parser FnCall parseFnCall = nameFnCall <|> expFnCall where nameFnCall = do id <- identifier fnCallArgs <- many1 $ try parseFnCallArgs return $ NameFnCall id fnCallArgs expFnCall = do exp <- parens parseExp fnCallArgs <- many1 $ try parseFnCallArgs return $ ExpFnCall exp fnCallArgs parseFnCallArgs :: Parser FnCallArgs parseFnCallArgs = do ts <- many parseTblLookup args ts <|> tblArgs ts where args ts = do a <- parseArgs return $ FnCallArgs ts a tblArgs ts = do reservedOp ":" id <- identifier a <- parseArgs return $ TblFnCallArgs ts id a parseArgs :: Parser Args parseArgs = expArgs <|> tblCtorArgs <|> strArgs where expArgs = do expList <- parens (option [] parseExpList) return $ ExpArgs expList tblCtorArgs = do fields <- parseTblCtor return $ TblCtorArgs fields strArgs = do str <- stringLiteral return $ StrArgs str parseFuncBody :: Parser FuncBody parseFuncBody = do parlist <- parens (option (ParList [] False) parseParList) block <- parseChunk reserved "end" return $ FuncBody parlist block parseParList :: Parser ParList parseParList = nameParList <|> varArgParList where nameParList = do id <- identifier ids <- many $ try (comma >> identifier) let params = id:ids varArgStr <- optionMaybe (comma >> reservedOp "...") let hasVarArgs = if isNothing varArgStr then False else True return $ ParList params hasVarArgs varArgParList = do reservedOp "..." return $ ParList [] True parseTblCtor :: Parser [Field] parseTblCtor = braces $ sepEndBy parseField (comma <|> semi) parseField :: Parser Field parseField = expExpField <|> (try nameExpField) <|> expField where expExpField = do e1 <- brackets parseExp reservedOp "=" e2 <- parseExp return $ ExpExpField e1 e2 nameExpField = do i <- identifier reservedOp "=" e <- parseExp return $ NameExpField i e expField = do e <- parseExp return $ ExpField e
MattKD/hlua_parser
Parser.hs
mit
12,960
0
18
3,899
3,912
1,958
1,954
358
2
{-# LANGUAGE OverloadedStrings #-} module Hickory.Text.Font where import Data.Attoparsec.Text {-import Data.Attoparsec.Char8-} import Data.Hashable import Control.Applicative import qualified Data.Text as Text data FontInfo a = FontInfo { lineHeight :: a, base :: a, scaleW :: a, scaleH :: a } deriving Show emptyFontInfo :: Integral a => FontInfo a emptyFontInfo = (FontInfo 0 0 0 0) data KerningPair = KerningPair CharIdent CharIdent deriving (Show, Eq) instance Data.Hashable.Hashable KerningPair where hashWithSalt s (KerningPair (CharIdent a) (CharIdent b)) = hashWithSalt s ((a * 1000) + b) newtype CharIdent = CharIdent Int deriving (Eq, Show) instance Data.Hashable.Hashable CharIdent where hashWithSalt s (CharIdent a) = hashWithSalt s a data GlyphSpec a = GlyphSpec { ident :: CharIdent, x :: a, y :: a, width :: a, height :: a, xoffset :: a, yoffset :: a, xadvance :: a } deriving (Show) data KerningSpec a = KerningSpec KerningPair a deriving Show -- common lineHeight=117 base=95 scaleW=512 scaleH=512 pages=1 packed=0 isInlineSpace c = c == ' ' || c == '\t' inlineSpace :: Parser Char inlineSpace = satisfy isInlineSpace <?> "inlineSpace" quotedString :: Parser Text.Text quotedString = do char '"' prop <- takeTill (== '"') char '"' return prop data Value a = StringVal String | CommaSepValue [a] deriving Show stringVal :: Parser (Value a) stringVal = do val <- quotedString return $ StringVal (Text.unpack val) commaSepVal :: Integral a => Parser (Value a) commaSepVal = do lst <- (signed decimal) `sepBy` (char ',') return $ CommaSepValue lst parseProperty :: Integral a => Parser (String, Value a) parseProperty = do key <- many' letter char '=' val <- (stringVal <|> commaSepVal) return (key, val) data CommandResult a = FontInfoResult (FontInfo a) | GlyphResult (GlyphSpec a) | KerningResult (KerningSpec a) | Unused toNum :: Integral a => Value a -> a toNum (CommaSepValue (i:is)) = i toNum _ = 0 pullNumVal :: (Integral a) => String -> [(String, Value a)] -> a pullNumVal key alist = maybe 0 toNum $ lookup key alist interpretCommand :: (Integral a) => (String, [(String, Value a)]) -> CommandResult a interpretCommand ("common", alist) = FontInfoResult $ FontInfo { lineHeight = pullNumVal "lineHeight" alist, base = pullNumVal "base" alist, scaleW = pullNumVal "scaleW" alist, scaleH = pullNumVal "scaleH" alist} interpretCommand ("char", alist) = let pullval = (\k -> pullNumVal k alist) in GlyphResult $ GlyphSpec { ident = (CharIdent $ fromIntegral $ pullval "id"), x = pullval "x", y = pullval "y", width = pullval "width", height = pullval "height", xoffset = pullval "xoffset", yoffset = pullval "yoffset", xadvance = pullval "xadvance" } interpretCommand ("kerning", alist) = let pullval = (\k -> pullNumVal k alist) in KerningResult $ KerningSpec (KerningPair (CharIdent $ fromIntegral $ pullval "first") (CharIdent $ fromIntegral $ pullval "second")) (pullval "amount") interpretCommand _ = Unused parseCommand :: Integral a => Parser (String, [(String, Value a)]) parseCommand = do name <- many' letter inlineSpace alist <- parseProperty `sepBy` inlineSpace return (name, alist) parseFont :: Integral a => Parser ((FontInfo a), [GlyphSpec a], [KerningSpec a]) parseFont = do commands <- parseCommand `sepBy` endOfLine let commands' = map interpretCommand commands return $ foldl (\(fi, chars, kernings) res -> case res of FontInfoResult fi' -> (fi', chars, kernings) GlyphResult g -> (fi, g:chars, kernings) KerningResult k -> (fi, chars, k:kernings) Unused -> (fi, chars, kernings) ) (emptyFontInfo, [], []) commands' runParseFont :: Integral a => Text.Text -> Either String ((FontInfo a), [GlyphSpec a], [KerningSpec a]) runParseFont = Data.Attoparsec.Text.parseOnly parseFont
asivitz/Hickory
Hickory/Text/Font.hs
mit
4,658
0
15
1,508
1,413
757
656
106
4
module Main where import Control.Applicative import Control.Monad (unless, when) import Data.Maybe import qualified Graphics.UI.GLFW as GLFW import System.Environment import System.Exit import System.IO import Draw2 import Control (movement) import Entity import Util (nth) main :: IO () main = do xs <- getArgs let json = fromMaybe cube (nth 1 xs) withWindow width height "bifrost" $ \win -> do GLFW.setErrorCallback $ Just errorCallback GLFW.setKeyCallback win $ Just keyCallback prog <- initResources json mainLoop prog win entity GLFW.destroyWindow win GLFW.terminate exitSuccess where width = 800 height = 600 entity = initEntity cube = "json/cube.json" -- | forever mainLoop :: Resources -> GLFW.Window -> Entity -> IO () mainLoop r w e = do draw r w e GLFW.swapBuffers w GLFW.pollEvents f <- movement w e q <- GLFW.windowShouldClose w unless q $ mainLoop r w f -- | window creation withWindow :: Int -> Int -> String -> (GLFW.Window -> IO ()) -> IO () withWindow width height title f = do GLFW.setErrorCallback $ Just simpleErrorCallback r <- GLFW.init when r $ do m <- GLFW.createWindow width height title Nothing Nothing case m of (Just win) -> do GLFW.makeContextCurrent m f win GLFW.setErrorCallback $ Just simpleErrorCallback GLFW.destroyWindow win Nothing -> return () GLFW.terminate where simpleErrorCallback e s = putStrLn $ unwords [show e, show s] -- | event callBacks errorCallback :: GLFW.ErrorCallback errorCallback err = hPutStrLn stderr keyCallback :: GLFW.KeyCallback keyCallback window key scancode action mods = do when (key == GLFW.Key'Escape && action == GLFW.KeyState'Pressed) $ GLFW.setWindowShouldClose window True when (key == GLFW.Key'Q && action == GLFW.KeyState'Pressed) $ GLFW.setWindowShouldClose window True
joelelmercarlson/bifrost
src/Main.hs
mit
1,955
0
16
470
642
310
332
58
2
{-# LANGUAGE RecordWildCards #-} module LLVM.Typed ( Typed(..), ) where import LLVM.AST import LLVM.AST.Global import LLVM.AST.Type import qualified LLVM.AST.Constant as C import qualified LLVM.AST.Float as F ----- -- Reasoning about types ----- class Typed a where typeOf :: a -> Type instance Typed Operand where typeOf (LocalReference t _) = t typeOf (ConstantOperand c) = typeOf c typeOf _ = MetadataType instance Typed C.Constant where typeOf (C.Int bits _) = IntegerType bits typeOf (C.Float float) = typeOf float typeOf (C.Null t) = t typeOf (C.Struct {..}) = StructureType isPacked (map typeOf memberValues) typeOf (C.Array {..}) = ArrayType (fromIntegral $ length memberValues) memberType typeOf (C.Vector {..}) = VectorType (fromIntegral $ length memberValues) $ case memberValues of [] -> VoidType {- error "Vectors of size zero are not allowed" -} (x:_) -> typeOf x typeOf (C.Undef t) = t typeOf (C.BlockAddress {..}) = ptr i8 typeOf (C.GlobalReference t _) = t typeOf (C.Add {..}) = typeOf operand0 typeOf (C.FAdd {..}) = typeOf operand0 typeOf (C.Sub {..}) = typeOf operand0 typeOf (C.FSub {..}) = typeOf operand0 typeOf (C.Mul {..}) = typeOf operand0 typeOf (C.FMul {..}) = typeOf operand0 typeOf (C.UDiv {..}) = typeOf operand0 typeOf (C.SDiv {..}) = typeOf operand0 typeOf (C.URem {..}) = typeOf operand0 typeOf (C.SRem {..}) = typeOf operand0 typeOf (C.Shl {..}) = typeOf operand0 typeOf (C.LShr {..}) = typeOf operand0 typeOf (C.AShr {..}) = typeOf operand0 typeOf (C.And {..}) = typeOf operand0 typeOf (C.Or {..}) = typeOf operand0 typeOf (C.Xor {..}) = typeOf operand0 typeOf (C.GetElementPtr {..}) = getElementPtrType (typeOf address) indices typeOf (C.Trunc {..}) = type' typeOf (C.ZExt {..}) = type' typeOf (C.SExt {..}) = type' typeOf (C.FPToUI {..}) = type' typeOf (C.FPToSI {..}) = type' typeOf (C.UIToFP {..}) = type' typeOf (C.SIToFP {..}) = type' typeOf (C.FPTrunc {..}) = type' typeOf (C.FPExt {..}) = type' typeOf (C.PtrToInt {..}) = type' typeOf (C.BitCast {..}) = type' typeOf (C.ICmp {..}) = case (typeOf operand0) of (VectorType n _) -> VectorType n i1 _ -> i1 typeOf (C.FCmp {..}) = case (typeOf operand0) of (VectorType n _) -> VectorType n i1 _ -> i1 typeOf (C.Select {..}) = typeOf trueValue typeOf (C.ExtractElement {..}) = case typeOf vector of (VectorType _ t) -> t _ -> VoidType {- error "The first operand of an ‘extractelement‘ instruction is a value of vector type." -} typeOf (C.InsertElement {..}) = typeOf vector typeOf (C.ShuffleVector {..}) = case (typeOf operand0, typeOf mask) of (VectorType _ t, VectorType m _) -> VectorType m t _ -> VoidType {- error -} typeOf (C.ExtractValue {..}) = extractValueType (typeOf aggregate) indices typeOf (C.InsertValue {..}) = typeOf aggregate getElementPtrType :: Type -> [C.Constant] -> Type getElementPtrType ty cons = ptr i8 -- XXX extractValueType = error "extract" instance Typed F.SomeFloat where typeOf (F.Half _) = FloatingPointType 16 IEEE typeOf (F.Single _) = FloatingPointType 32 IEEE typeOf (F.Double _) = FloatingPointType 64 IEEE typeOf (F.Quadruple _ _) = FloatingPointType 128 IEEE typeOf (F.X86_FP80 _ _) = FloatingPointType 80 DoubleExtended typeOf (F.PPC_FP128 _ _) = FloatingPointType 128 PairOfFloats instance Typed Global where typeOf (GlobalVariable {..}) = type' typeOf (GlobalAlias {..}) = type' typeOf (Function {..}) = let (params, isVarArg) = parameters in FunctionType returnType (map typeOf params) isVarArg instance Typed Parameter where typeOf (Parameter t _ _) = t
vjoki/llvm-hs-pretty
src/LLVM/Typed.hs
mit
4,340
0
11
1,388
1,586
810
776
88
1
{- -------------------------------------------------------------------------------------------------------------- Program : stringFunctions.hs Professor : Richard Riehle Programmer : Jigar Gosalia (89753) Description : Learn String Functions in Haskell. References : https://lotz84.github.io/haskellbyexample/ex/string-functions --------------------------------------------------------------------------------------------------------------- -} import Data.List import Data.Char include :: String -> String -> Bool include xs ys = or . map (isPrefixOf ys) . tails $ xs joinWith :: [String] -> String -> String joinWith xs sep = concat . init . concat $ [[x, sep] | x <- xs] split :: String -> Char -> [String] split "" _ = [] split xs c = let (ys, zs) = break (== c) xs in if null zs then [ys] else ys : split (tail zs) c main = do putStrLn "" putStrLn "" putStrLn "Input string is 'hello world' ..... " putStrLn "" putStrLn "" putStrLn $ "String contains 'lo' : " ++ show ("hello world" `include` "lo") putStrLn $ "String count 'l' : " ++ show (length . filter (=='l') $ "hello world") putStrLn $ "String hasPrefix 'wo' : " ++ show (isPrefixOf "wo" "world") putStrLn $ "String hasSuffix 'lo' : " ++ show (isSuffixOf "lo" "hello") putStrLn $ "String index 'o' : " ++ show (elemIndex 'o' "hello world") putStrLn $ "String join strings : " ++ show (["hello", "world"] `joinWith` "-") putStrLn $ "String repeat 'a' 5 times : " ++ show (replicate 5 'a') putStrLn $ "String replace 'o' with '0' : " ++ show (map (\x -> if x == 'o' then '0' else x) "hello world") putStrLn $ "String split by delimiter '-' : " ++ show (split "spilt-hello-world" '-') putStrLn $ "String toLower : " ++ map toLower "hello world" putStrLn $ "String toUpper : " ++ map toUpper "hello world" putStrLn $ "String length : " ++ show (length "hello world!!") putStrLn $ "String character at location 1 : " ++ show ("hello world" !! 1) putStrLn "" putStrLn ""
gosaliajigar/Languages
Haskell/stringFunctions.hs
mit
2,197
0
14
583
561
274
287
31
2
{-# LANGUAGE RecordWildCards #-} module Skybox ( Skybox (..) , initSkybox , skyboxRender ) where import Graphics.Rendering.OpenGL import Hogldev.Pipeline ( Pipeline(..), getTrans, PersProj(..) ) import Hogldev.Camera (Camera(..)) import Hogldev.CubemapTexture import Mesh import SkyboxTechnique data Skybox = Skybox { technique :: !SkyboxTechnique , cubeMapTex :: !CubemapTexture , mesh :: !Mesh , skyPersProj :: !PersProj } deriving (Show) initSkybox :: PersProj -> CubeMapFilenames -> IO Skybox initSkybox perspective cubeMapFiles = do tech <- initSkyboxTechnique enableSkyboxTechnique tech setSkyboxTechniqueUnit tech 0 cubeMapTexture <- loadCubemapTexture cubeMapFiles sphereMesh <- loadMesh "assets/sphere.obj" return Skybox { technique = tech , cubeMapTex = cubeMapTexture , mesh = sphereMesh , skyPersProj = perspective } skyboxRender :: Skybox -> Camera -> IO () skyboxRender Skybox{..} camera = do enableSkyboxTechnique technique -- oldCullFaceMode <- get cullFace -- oldDepthMode <- get depthFunc -- cullFace $= Just Front -- depthFunc $= Just Lequal setSkyboxTechniqueWVP technique $ getTrans WVPPipeline { worldInfo = cameraPos camera, scaleInfo = Vector3 20.0 20.0 20.0, rotateInfo = Vector3 0 0 0, persProj = skyPersProj, pipeCamera = camera } cubeMapTexBind cubeMapTex (TextureUnit 0) renderMesh mesh -- cullFace $= oldCullFaceMode -- depthFunc $= oldDepthMode
triplepointfive/hogldev
tutorial25/Skybox.hs
mit
1,741
0
11
547
346
189
157
52
1
-- Copyright 2013 Thomas Szczarkowski module CTR2 where import Data.Bits import Data.Word import Data.Char import Data.Function import Data.List import Data.Array.IArray import Control.Monad import OpenSSL.Symmetric import OpenSSL.Random import Bytes import Ciphers import CryptoRandom import CTR import LanguageModel guessReusedNonce :: NgramData -> [[Word8]] -> Integer -> IO [[Word8]] guessReusedNonce ngrams ciphertexts timeLimit = let alphabet = ['a'..'z'] ++ " " commonTrigrams = take 200 $ sortBy (compare `on` (scoreTrigram ngrams)) $ [a:b:c:[] | a <- alphabet, b <- alphabet, c <- alphabet] len = maximum $ map length ciphertexts fscore key = sum $ map (score ngrams) $ map (encode . zipWith xor (elems key)) ciphertexts guessLetter key = do str <- cryptoRandomChoice ciphertexts pos <- cryptoRandomInteger (0, length str - 1) letter <- cryptoRandomChoice (decode alphabet) return $ key // [(pos, (str !! pos) `xor` letter)] guessTrigram key = do str <- cryptoRandomChoice ciphertexts pos <- cryptoRandomInteger (0, length str - 3) (a:b:c:_) <- cryptoRandomChoice $ map decode commonTrigrams return $ key // [(pos, (str !! pos) `xor` a), (pos+1, (str !! (pos+1)) `xor` b), (pos+2, (str !! (pos+2)) `xor` c)] loop !(key :: Array Int Word8) !n = if n > timeLimit then return key else do guess <- cryptoRandomChoice [guessTrigram, guessLetter, guessLetter, guessLetter] key' <- guess key loop (if fscore key' > fscore key then key' else key) (n+1) in loop (listArray (0,len-1) (len # 0)) 0 >>= \key -> return $ map (encode . zipWith xor (elems key)) ciphertexts p19 = do putStrLn "\n\n==Problem 19==\n" plaintexts <- liftM (map (decode.Base64).lines) $ readFile "p19" key <- cryptoRandomKey -- encrypt with same CTR stream ciphertexts <- mapM (ctr aes key 0) plaintexts -- n-gram statistics ngrams <- getNgrams putStrLn . intercalate "\n" . map encode =<< guessReusedNonce ngrams ciphertexts 50000
tom-szczarkowski/matasano-crypto-puzzles-solutions
set3/CTR2.hs
mit
2,303
1
18
689
811
420
391
-1
-1
-- No oddities here -- http://www.codewars.com/kata/51fd6bc82bc150b28e0000ce module Codewars.Oddities where noOdds :: Integral n => [n] -> [n] noOdds = filter even
gafiatulin/codewars
src/7 kyu/Oddities.hs
mit
166
0
7
23
38
22
16
3
1
{- Yesod.Auth.Accountの中に、なぜか意図的にCSRFトークンを出力していない フォームがあり、当然ながらCSRFチェックでエラーになってしまうため 使えなかった. これを改善するため、一部ソースを改変したバージョンを作成する. -} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- Only orphan instance is RenderMessage AccountMessage -- | An auth plugin for accounts. Each account consists of a username, email, and password. -- -- This module is designed so that you can use the default pages for login, account -- creation, change password, etc. But the module also exports some forms which you -- can embed into your own pages, customizing the account process. The minimal requirements -- to use this module are: -- -- * If you are not using persistent or just want more control over the user data, you can use -- any datatype for user information and make it an instance of 'UserCredentials'. You must -- also create an instance of 'AccountDB'. -- -- * You may use a user datatype created by persistent, in which case you can make the datatype -- an instance of 'PersistUserCredentials' instead of 'UserCredentials'. In this case, -- 'AccountPersistDB' from this module already implements the 'AccountDB' interface for you. -- -- * Make your master site an instance of 'AccountSendEmail'. By default, this class -- just logs a message so during development this class requires no implementation. -- -- * Make your master site and database an instance of 'YesodAuthFreeAccount'. There is only -- one required function which must be implemented ('runAccountDB') although there -- are several functions you can override in this class to customize the behavior of this -- module. -- -- * Include 'authFreeAccountPlugin' in the list of plugins in your instance of 'YesodAuth'. module Jabara.Yesod.Auth.FreeAccount( -- * Plugin Username , newAccountR , resetPasswordR , authFreeAccountPlugin -- * Login , LoginData(..) , loginForm , loginFormPostTargetR , loginWidget -- * New Account -- $newaccount , verifyR , NewAccountData(..) , newAccountForm , newAccountWidget , createNewAccount , resendVerifyEmailForm , resendVerifyR , resendVerifyEmailWidget -- * Password Reset -- $passwordreset , newPasswordR , resetPasswordForm , resetPasswordWidget , NewPasswordData(..) , newPasswordForm , setPasswordR , newPasswordWidget -- * Database and Email , UserCredentials(..) , PersistUserCredentials(..) , AccountDB(..) , AccountSendEmail(..) -- * Persistent , AccountPersistDB , runAccountPersistDB -- * Customization , YesodAuthFreeAccount(..) -- * Helpers , hashPassword , verifyPassword , newVerifyKey ) where import Control.Applicative import Control.Monad.Reader hiding (lift) import qualified Crypto.PasswordStore as PS import qualified Crypto.Nonce as Nonce import Data.Char (isAlphaNum) import Data.Either (Either(..)) import qualified Data.ByteString as B import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Database.Persist as P import GHC.Base import GHC.Show import System.IO.Unsafe (unsafePerformIO) import Yesod.Core import Yesod.Form import Yesod.Form.Bootstrap3 ( bfs, renderBootstrap3, BootstrapFormLayout(BootstrapBasicForm) ) import Yesod.Auth import Yesod.Persist hiding ( get, replace, insertKey, Entity, entityVal ) import qualified Yesod.Auth.Message as Msg import Jabara.Yesod.Auth.FreeAccount.Message pluginName :: T.Text pluginName = "free-account" -- | Each user is uniquely identified by a username. type Username = T.Text -- | The account authentication plugin. Here is a complete example using persistent 2.1 -- and yesod 1.4. -- -- >{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving #-} -- >{-# LANGUAGE FlexibleContexts, FlexibleInstances, TemplateHaskell, OverloadedStrings #-} -- >{-# LANGUAGE GADTs, MultiParamTypeClasses, TypeSynonymInstances #-} -- > -- >import Data.Text (Text) -- >import Data.ByteString (ByteString) -- >import Database.Persist.Sqlite -- >import Control.Monad.Logger (runStderrLoggingT) -- >import Yesod -- >import Yesod.Auth -- >import Yesod.Auth.Account -- > -- >share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistUpperCase| -- >User -- > username Text -- > UniqueUsername username -- > password ByteString -- > emailAddress Text -- > verified Bool -- > verifyKey Text -- > resetPasswordKey Text -- > deriving Show -- >|] -- > -- >instance PersistUserCredentials User where -- > userUsernameF = UserUsername -- > userPasswordHashF = UserPassword -- > userEmailF = UserEmailAddress -- > userEmailVerifiedF = UserVerified -- > userEmailVerifyKeyF = UserVerifyKey -- > userResetPwdKeyF = UserResetPasswordKey -- > uniqueUsername = UniqueUsername -- > -- > userCreate name email key pwd = User name pwd email False key "" -- > -- >data MyApp = MyApp ConnectionPool -- > -- >mkYesod "MyApp" [parseRoutes| -- >/ HomeR GET -- >/auth AuthR Auth getAuth -- >|] -- > -- >instance Yesod MyApp -- > -- >instance RenderMessage MyApp FormMessage where -- > renderMessage _ _ = defaultFormMessage -- > -- >instance YesodPersist MyApp where -- > type YesodPersistBackend MyApp = SqlBackend -- > runDB action = do -- > MyApp pool <- getYesod -- > runSqlPool action pool -- > -- >instance YesodAuth MyApp where -- > type AuthId MyApp = Username -- > getAuthId = return . Just . credsIdent -- > loginDest _ = HomeR -- > logoutDest _ = HomeR -- > authPlugins _ = [authFreeAccountPlugin] -- > authHttpManager _ = error "No manager needed" -- > onLogin = return () -- > maybeAuthId = lookupSession credsKey -- > -- >instance AccountSendEmail MyApp -- > -- >instance YesodAuthFreeAccount (AccountPersistDB MyApp User) MyApp where -- > runAccountDB = runAccountPersistDB -- > -- >getHomeR :: Handler Html -- >getHomeR = do -- > maid <- maybeAuthId -- > case maid of -- > Nothing -> defaultLayout $ [whamlet| -- ><p>Please visit the <a href="@{AuthR LoginR}">Login page</a> -- >|] -- > Just u -> defaultLayout $ [whamlet| -- ><p>You are logged in as #{u} -- ><p><a href="@{AuthR LogoutR}">Logout</a> -- >|] -- > -- >main :: IO () -- >main = runStderrLoggingT $ withSqlitePool "test.db3" 10 $ \pool -> do -- > runSqlPool (runMigration migrateAll) pool -- > liftIO $ warp 3000 $ MyApp pool -- authFreeAccountPlugin :: YesodAuthFreeAccount db master => AuthPlugin master authFreeAccountPlugin = AuthPlugin pluginName dispatch loginWidget where dispatch "POST" ["login"] = postLoginR >>= sendResponse dispatch "GET" ["newaccount"] = getNewAccountR >>= sendResponse dispatch "POST" ["newaccount"] = postNewAccountR >>= sendResponse dispatch "GET" ["resetpassword"] = getResetPasswordR >>= sendResponse dispatch "POST" ["resetpassword"] = postResetPasswordR >>= sendResponse dispatch "GET" ["verify", u, k] = getVerifyR u k >>= sendResponse dispatch "GET" ["newpassword", u, k] = getNewPasswordR u k >>= sendResponse dispatch "POST" ["setpassword"] = postSetPasswordR >>= sendResponse dispatch "POST" ["resendverifyemail"] = postResendVerifyEmailR >>= sendResponse dispatch _ _ = notFound -- | The POST target for the 'loginForm'. loginFormPostTargetR :: AuthRoute loginFormPostTargetR = PluginR pluginName ["login"] -- | Route for the default new account page. -- -- See the New Account section below for customizing the new account process. newAccountR :: AuthRoute newAccountR = PluginR pluginName ["newaccount"] -- | Route for the reset password page. -- -- This page allows the user to reset their password by requesting an email with a -- reset URL be sent to them. See the Password Reset section below for customization. resetPasswordR :: AuthRoute resetPasswordR = PluginR pluginName ["resetpassword"] -- | The URL sent in an email for email verification verifyR :: Username -> T.Text -- ^ The verification key -> AuthRoute verifyR u k = PluginR pluginName ["verify", u, k] -- | The POST target for resending a verification email resendVerifyR :: AuthRoute resendVerifyR = PluginR pluginName ["resendverifyemail"] -- | The URL sent in an email when the user requests to reset their password newPasswordR :: Username -> T.Text -- ^ The verification key -> AuthRoute newPasswordR u k = PluginR pluginName ["newpassword", u, k] -- | The POST target for reseting the password setPasswordR :: AuthRoute setPasswordR = PluginR pluginName ["setpassword"] --------------------------------------------------------------------------------------------------- -- | The data collected in the login form. data LoginData = LoginData { loginUsername :: T.Text , loginPassword :: T.Text } deriving Show -- | The login form. -- -- You can embed this form into your own pages if you want a custom rendering of this -- form or to include a login form on your own pages. The form submission should be -- posted to 'loginFormPostTargetR'. loginForm :: (MonadHandler m, YesodAuthFreeAccount db master, HandlerSite m ~ master) => AForm m LoginData loginForm = LoginData <$> areq (checkM checkValidUsername textField) userSettings Nothing <*> areq passwordField pwdSettings Nothing where userSettings = (bfs $ SomeMessage MsgUsername) { fsId = Just "username" } pwdSettings = (bfs $ SomeMessage Msg.Password) { fsId = Just "password" } -- | A default rendering of 'loginForm' using renderDivs. -- -- This is the widget used in the default implementation of 'loginHandler'. -- The widget also includes links to the new account and reset password pages. loginWidget :: YesodAuthFreeAccount db master => (Route Auth -> Route master) -> WidgetT master IO () loginWidget tm = do ((_,widget), enctype) <- liftHandlerT $ runFormPost $ render loginForm [whamlet| <div .loginDiv> <form method=post enctype=#{enctype} action=@{tm loginFormPostTargetR}> ^{widget} <button type=submit .btn .btn-success .btn-imp>_{Msg.LoginTitle} <p> <a href="@{tm newAccountR}">_{MsgRegisterLong} <a href="@{tm resetPasswordR}">_{MsgForgotPassword} |] postLoginR :: YesodAuthFreeAccount db master => HandlerT Auth (HandlerT master IO) Html postLoginR = do mr <- lift getMessageRender ((result, _), _) <- lift $ runFormPostNoToken $ renderBootstrap3 BootstrapBasicForm loginForm muser <- case result of FormMissing -> invalidArgs ["Form is missing"] FormFailure msg -> return $ Left msg FormSuccess (LoginData uname pwd) -> do mu <- lift $ runAccountDB $ loadUser uname case mu of Nothing -> return $ Left [mr Msg.InvalidUsernamePass] Just u -> return $ if verifyPassword pwd (userPasswordHash u) then Right u else Left [mr Msg.InvalidUsernamePass] case muser of Left errs -> do setMessage $ toHtml $ T.concat errs redirect LoginR Right u -> if userEmailVerified u then do lift $ setCreds True $ Creds pluginName (username u) [] -- setCreds should redirect so we will never get here badMethod else unregisteredLogin u --------------------------------------------------------------------------------------------------- -- $newaccount -- The new account process works as follows. -- -- * A GET to 'newAccountR' displays a form requesting account information -- from the user. The specific page to display can be customized by implementing -- 'getNewAccountR'. By default, this is the content of 'newAccountForm' which -- consists of an username, email, and a password. The target for the form is a -- POST to 'newAccountR'. -- -- * A POST to 'newAccountR' handles the account creation. By default, 'postNewAccountR' -- processes 'newAccountForm' and then calls 'createNewAccount' to create the account -- in the database, generate a random key, and send an email with the verification key. -- If you have modified 'getNewAccountR' to add additional fields to the new account -- form (for example CAPTCHA or other account info), you can override 'postNewAccountR' -- to handle the form. You should still call 'createNewAccount' from your own processing -- function. -- -- * The verification email includes a URL to 'verifyR'. A GET to 'verifyR' checks -- if the key matches, and if so updates the database and uses 'setCreds' to log the -- user in and redirects to 'loginDest'. If an error occurs, a message is set and the -- user is redirected to 'LoginR'. -- -- * A POST to 'resendVerifyR' of 'resendVerifyEmailForm' will generate a new verification key -- and resend the email. By default, 'unregisteredLogin' displays the form for resending -- the email. -- | The data collected in the new account form. data NewAccountData = NewAccountData { newAccountUsername :: Username , newAccountEmail :: T.Text , newAccountPassword1 :: T.Text , newAccountPassword2 :: T.Text } deriving Show -- | The new account form. -- -- You can embed this form into your own pages or into 'getNewAccountR'. The form -- submission should be posted to 'newAccountR'. Alternatively, you could embed this -- form into a larger form where you prompt for more information during account -- creation. In this case, the NewAccountData should be passed to 'createNewAccount' -- from inside 'postNewAccountR'. newAccountForm :: (YesodAuthFreeAccount db master , MonadHandler m , HandlerSite m ~ master ) => AForm m NewAccountData newAccountForm = NewAccountData <$> areq (checkM checkValidUsername textField) userSettings Nothing <*> areq emailField emailSettings Nothing <*> areq passwordField pwdSettings1 Nothing <*> areq passwordField pwdSettings2 Nothing where userSettings = bfs $ SomeMessage MsgUsername emailSettings = bfs $ SomeMessage Msg.Email pwdSettings1 = bfs $ SomeMessage Msg.Password pwdSettings2 = bfs $ SomeMessage Msg.ConfirmPass -- | A default rendering of the 'newAccountForm' using renderDivs. newAccountWidget :: YesodAuthFreeAccount db master => (Route Auth -> Route master) -> WidgetT master IO () newAccountWidget tm = do ((_,widget), enctype) <- liftHandlerT $ runFormPost $ renderBootstrap3 BootstrapBasicForm newAccountForm [whamlet| <div .newaccountDiv> <form method=post enctype=#{enctype} action=@{tm newAccountR}> ^{widget} <button type=submit .btn .btn-success .btn-imp>_{Msg.Register} |] -- | An action to create a new account. -- -- You can use this action inside your own implementation of 'postNewAccountR' if you -- add additional fields to the new account creation. This action assumes the user has -- not yet been created in the database and will create the user, so this action should -- be run first in your handler. Note that this action does not check if the passwords -- are equal. If an error occurs (username exists, etc.) this will set a message and -- redirect to 'newAccountR'. createNewAccount :: YesodAuthFreeAccount db master => NewAccountData -> (Route Auth -> Route master) -> HandlerT master IO (UserAccount db) createNewAccount (NewAccountData u email pwd _) tm = do muser <- runAccountDB $ loadUser u case muser of Just _ -> do setMessageI $ MsgUsernameExists u redirect $ tm newAccountR Nothing -> return () key <- newVerifyKey hashed <- hashPassword pwd mnew <- runAccountDB $ addNewUser u email key hashed new <- case mnew of Left err -> do setMessage $ toHtml err redirect $ tm newAccountR Right x -> return x render <- getUrlRender sendVerifyEmail u email $ render $ tm $ verifyR u key setMessageI $ Msg.ConfirmationEmailSent email return new getVerifyR :: YesodAuthFreeAccount db master => Username -> T.Text -> HandlerT Auth (HandlerT master IO) () getVerifyR uname k = do muser <- lift $ runAccountDB $ loadUser uname case muser of Nothing -> do lift $ setMessageI Msg.InvalidKey redirect LoginR Just user -> do when ( userEmailVerifyKey user == "" || userEmailVerifyKey user /= k || userEmailVerified user ) $ do lift $ setMessageI Msg.InvalidKey redirect LoginR lift $ runAccountDB $ verifyAccount user lift $ setMessageI MsgEmailVerified lift $ setCreds True $ Creds pluginName uname [] -- | A form to allow the user to request the email validation be resent. -- -- Intended for use in 'unregisteredLogin'. The result should be posted to -- 'resendVerifyR'. resendVerifyEmailForm :: (RenderMessage master FormMessage , MonadHandler m , HandlerSite m ~ master ) => Username -> AForm m Username resendVerifyEmailForm u = areq hiddenField "" $ Just u -- | A default rendering of 'resendVerifyEmailForm' resendVerifyEmailWidget :: YesodAuthFreeAccount db master => Username -> (Route Auth -> Route master) -> WidgetT master IO () resendVerifyEmailWidget u tm = do ((_,widget), enctype) <- liftHandlerT $ runFormPost $ render $ resendVerifyEmailForm u [whamlet| <div .resendVerifyEmailDiv> <form method=post enctype=#{enctype} action=@{tm resendVerifyR}> ^{widget} <button type=submit .btn .btn-success .btn-imp>_{MsgResendVerifyEmail} |] postResendVerifyEmailR :: YesodAuthFreeAccount db master => HandlerT Auth (HandlerT master IO) () postResendVerifyEmailR = do ((result, _), _) <- lift $ runFormPost $ render $ resendVerifyEmailForm "" muser <- case result of FormMissing -> invalidArgs ["Form is missing"] FormFailure msg -> invalidArgs msg FormSuccess uname -> lift $ runAccountDB $ loadUser uname case muser of -- The username is a hidden field so it should be correct. No need to set a message or redirect. Nothing -> invalidArgs ["Invalid username"] Just u -> do key <- newVerifyKey lift $ runAccountDB $ setVerifyKey u key render <- getUrlRender lift $ sendVerifyEmail (username u) (userEmail u) $ render $ verifyR (username u) key lift $ setMessageI $ Msg.ConfirmationEmailSent (userEmail u) redirect LoginR --------------------------------------------------------------------------------------------------- -- $passwordreset -- This plugin implements password reset by sending the user an email containing a URL. When -- the user visits this URL, they are prompted for a new password. This works as follows: -- -- * A GET to 'resetPasswordR' displays a form prompting for username, which when submitted sends -- a post to 'resetPasswordR'. You can customize this page by overriding 'getResetPasswordR' -- or by embedding 'resetPasswordForm' into your own page and not linking your users to this URL. -- -- * A POST to 'resetPasswordR' of 'resetPasswordForm' creates a new key, stores it in the database, -- and sends an email. It then sets a message and redirects to the login page. You can redirect -- somewhere else (or carry out other actions) at the end of 'sendNewPasswordEmail'. The URL sent -- in the email is 'setPasswordR'. -- -- * A GET to 'newPasswordR' checks if the key in the URL is correct and if so displays a form -- where the user can set a new password. The key is set as a hidden field in this form. You -- can customize the look of this page by overriding 'setPasswordHandler'. -- -- * A POST to 'setPasswordR' of 'resetPasswordForm' checks if the key is correct and if so, -- resets the password. It then calls 'setCreds' to successfully log in and so redirects to -- 'loginDest'. -- -- * You can set 'allowPasswordReset' to False, in which case the relevant routes in this -- plugin return 404. You can then implement password reset yourself. -- | A form for the user to request that an email be sent to them to allow them to reset -- their password. This form contains a field for the username (plus the CSRF token). -- The form should be posted to 'resetPasswordR'. resetPasswordForm :: (YesodAuthFreeAccount db master , MonadHandler m , HandlerSite m ~ master ) => AForm m Username resetPasswordForm = areq textField userSettings Nothing where userSettings = (bfs $ SomeMessage MsgUsername) { fsId = Just "username" } -- | A default rendering of 'resetPasswordForm'. resetPasswordWidget :: YesodAuthFreeAccount db master => (Route Auth -> Route master) -> WidgetT master IO () resetPasswordWidget tm = do ((_,widget), enctype) <- liftHandlerT $ runFormPost $ render resetPasswordForm [whamlet| <div .resetPasswordDiv> <form method=post enctype=#{enctype} action=@{tm resetPasswordR}> ^{widget} <button type=submit .btn .btn-success .btn-imp>_{Msg.SendPasswordResetEmail} |] postResetPasswordR :: YesodAuthFreeAccount db master => HandlerT Auth (HandlerT master IO) Html postResetPasswordR = do allow <- allowPasswordReset <$> lift getYesod unless allow notFound ((result, _), _) <- lift $ runFormPost $ render resetPasswordForm mdata <- case result of FormMissing -> invalidArgs ["Form is missing"] FormFailure msg -> return $ Left msg FormSuccess uname -> Right <$> lift (runAccountDB (loadUser uname)) case mdata of Left errs -> do setMessage $ toHtml $ T.concat errs redirect LoginR Right Nothing -> do lift $ setMessageI MsgInvalidUsername redirect resetPasswordR Right (Just u) -> do key <- newVerifyKey lift $ runAccountDB $ setNewPasswordKey u key render <- getUrlRender lift $ sendNewPasswordEmail (username u) (userEmail u) $ render $ newPasswordR (username u) key -- Don't display the email in the message since anybody can request the resend. lift $ setMessageI MsgResetPwdEmailSent redirect LoginR -- | The data for setting a new password. data NewPasswordData = NewPasswordData { newPasswordUser :: Username , newPasswordKey :: T.Text , newPasswordPwd1 :: T.Text , newPasswordPwd2 :: T.Text } deriving Show -- | The form for setting a new password. It contains hidden fields for the username and key and prompts -- for the passwords. This form should be posted to 'setPasswordR'. newPasswordForm :: (YesodAuth master, RenderMessage master FormMessage, MonadHandler m, HandlerSite m ~ master) => Username -> T.Text -- ^ key -> AForm m NewPasswordData newPasswordForm u k = NewPasswordData <$> areq hiddenField "" (Just u) <*> areq hiddenField "" (Just k) <*> areq passwordField pwdSettings1 Nothing <*> areq passwordField pwdSettings2 Nothing where pwdSettings1 = bfs (SomeMessage Msg.NewPass) pwdSettings2 = bfs (SomeMessage Msg.ConfirmPass) -- | A default rendering of 'newPasswordForm'. newPasswordWidget :: YesodAuthFreeAccount db master => UserAccount db -> (Route Auth -> Route master) -> WidgetT master IO () newPasswordWidget user tm = do let key = userResetPwdKey user ((_,widget), enctype) <- liftHandlerT $ runFormPost $ render (newPasswordForm (username user) key) [whamlet| <div .newpassDiv> <p>_{Msg.SetPass} <form method=post enctype=#{enctype} action=@{tm setPasswordR}> ^{widget} <button type=submit .btn .btn-success .btn-imp>_{Msg.SetPassTitle} |] getNewPasswordR :: YesodAuthFreeAccount db master => Username -> T.Text -> HandlerT Auth (HandlerT master IO) Html getNewPasswordR uname k = do allow <- allowPasswordReset <$> lift getYesod unless allow notFound muser <- lift $ runAccountDB $ loadUser uname case muser of Just user | userResetPwdKey user /= "" && userResetPwdKey user == k -> setPasswordHandler user _ -> do lift $ setMessageI Msg.InvalidKey redirect LoginR postSetPasswordR :: YesodAuthFreeAccount db master => HandlerT Auth (HandlerT master IO) () postSetPasswordR = do allow <- allowPasswordReset <$> lift getYesod unless allow notFound ((result,_), _) <- lift $ runFormPost $ render (newPasswordForm "" "") mnew <- case result of FormMissing -> invalidArgs ["Form is missing"] FormFailure msg -> return $ Left msg FormSuccess d | newPasswordPwd1 d == newPasswordPwd2 d -> return $ Right d FormSuccess d -> do lift $ setMessageI Msg.PassMismatch redirect $ newPasswordR (newPasswordUser d) (newPasswordKey d) case mnew of Left errs -> do setMessage $ toHtml $ T.concat errs redirect LoginR Right d -> do muser <- lift $ runAccountDB $ loadUser (newPasswordUser d) case muser of -- username is a hidden field so it should be correct. No need to set a message and redirect. Nothing -> permissionDenied "Invalid username" Just user -> do -- the key is a hidden field, no need to set a message and redirect. when (userResetPwdKey user == "") $ permissionDenied "Invalid key" when (newPasswordKey d /= userResetPwdKey user) $ permissionDenied "Invalid key" hashed <- hashPassword (newPasswordPwd1 d) lift $ runAccountDB $ setNewPassword user hashed lift $ setMessageI Msg.PassUpdated lift $ setCreds True $ Creds pluginName (newPasswordUser d) [] --------------------------------------------------------------------------------------------------- -- | Interface for the data type which stores the user info when not using persistent. -- -- You must make a data type that is either an instance of this class or of -- 'PersistUserCredentials', depending on if you are using persistent or not. -- -- Users are uniquely identified by their username, and for each user we must store the email, -- the verify status, a hashed user password, and a reset password key. The format for the -- hashed password is the format from "Crypto.PasswordStore". If the email has been verified -- and no password reset is in progress, the relevent keys should be the empty string. class UserCredentials u where username :: u -> Username userPasswordHash :: u -> B.ByteString -- ^ see "Crypto.PasswordStore" for the format userEmail :: u -> T.Text userEmailVerified :: u -> Bool -- ^ the status of the user's email verification userEmailVerifyKey :: u -> T.Text -- ^ the verification key which is sent in an email. userResetPwdKey :: u -> T.Text -- ^ the reset password key which is sent in an email. -- | Interface for the data type which stores the user info when using persistent. -- -- You must make a data type that is either an instance of this class or of -- 'UserCredentials', depending on if you are using persistent or not. class PersistUserCredentials u where userUsernameF :: P.EntityField u Username userPasswordHashF :: P.EntityField u B.ByteString userEmailF :: P.EntityField u T.Text userEmailVerifiedF :: P.EntityField u Bool userEmailVerifyKeyF :: P.EntityField u T.Text userResetPwdKeyF :: P.EntityField u T.Text uniqueUsername :: T.Text -> P.Unique u -- | Creates a new user for use during 'addNewUser'. The starting reset password -- key should be the empty string. userCreate :: Username -> T.Text -- ^ unverified email -> T.Text -- ^ email verification key -> B.ByteString -- ^ hashed and salted password -> u -- | These are the database operations to load and update user data. -- -- Persistent users can use 'AccountPersistDB' and don't need to create their own instance. -- If you are not using persistent or are using persistent but want to customize the database -- activity, you must manually make a monad an instance of this class. You can use any monad -- for which you can write 'runAccountDB', but typically the monad will be a newtype of HandlerT. -- For example, -- -- > newtype MyAccountDB a = MyAccountDB {runMyAccountDB :: HandlerT MyApp IO a} -- > deriving (Monad, MonadIO) -- > instance AccountDB MyAccountDB where -- > .... -- class AccountDB m where -- | The data type which stores the user. Must be an instance of 'UserCredentials'. type UserAccount m -- | Load a user by username loadUser :: Username -> m (Maybe (UserAccount m)) -- | Create new account. The password reset key should be added as an empty string. -- The creation can fail with an error message, in which case the error is set in a -- message and the post handler redirects to 'newAccountR'. addNewUser :: Username -- ^ username -> T.Text -- ^ unverified email -> T.Text -- ^ the email verification key -> B.ByteString -- ^ hashed and salted password -> m (Either T.Text (UserAccount m)) -- | Mark the account as successfully verified. This should reset the email validation key -- to the empty string. verifyAccount :: UserAccount m -> m () -- | Change/set the users email verification key. setVerifyKey :: UserAccount m -> T.Text -- ^ the verification key -> m () -- | Change/set the users password reset key. setNewPasswordKey :: UserAccount m -> T.Text -- ^ the key -> m () -- | Set a new hashed password. This should also set the password reset key to the empty -- string. setNewPassword :: UserAccount m -> B.ByteString -- ^ hashed password -> m () -- | A class to send email. -- -- Both of the methods are implemented by default to just log a message, -- so during development there are no required methods. For production, -- I recommend <http://hackage.haskell.org/package/mime-mail>. class AccountSendEmail master where sendVerifyEmail :: Username -> T.Text -- ^ email address -> T.Text -- ^ verification URL -> HandlerT master IO () sendVerifyEmail uname email url = $(logInfo) $ T.concat [ "Verification email for " , uname , " (", email, "): " , url ] sendNewPasswordEmail :: Username -> T.Text -- ^ email address -> T.Text -- ^ new password URL -> HandlerT master IO () sendNewPasswordEmail uname email url = $(logInfo) $ T.concat [ "Reset password email for " , uname , " (", email, "): " , url ] -- | The main class controlling the account plugin. -- -- You must make your database instance of 'AccountDB' and your master site -- an instance of this class. The only required method is 'runAccountDB', although -- this class contains many other methods to customize the behavior of the account plugin. -- -- Continuing the example from the manual creation of 'AccountDB', a minimal instance is -- -- > instance YesodAuthFreeAccount MyAccountDB MyApp where -- > runAccountDB = runMyAccountDB -- -- If instead you are using persistent and have made an instance of 'PersistUserCredentials', -- a minimal instance is -- -- > instance YesodAuthFreeAccount (AccountPersistDB MyApp User) MyApp where -- > runAccountDB = runAccountPersistDB -- class (YesodAuth master , AccountSendEmail master , AccountDB db , UserCredentials (UserAccount db) , RenderMessage master FormMessage ) => YesodAuthFreeAccount db master | master -> db where -- | Run a database action. This is the only required method. runAccountDB :: db a -> HandlerT master IO a -- | A form validator for valid usernames during new account creation. -- -- By default this allows usernames made up of 'isAlphaNum'. You can also ignore -- this validation and instead validate in 'addNewUser', but validating here -- allows the validation to occur before database activity (checking existing -- username) and before random salt creation (requires IO). checkValidUsername :: (MonadHandler m, HandlerSite m ~ master) => Username -> m (Either T.Text Username) checkValidUsername u | T.all isAlphaNum u = return $ Right u checkValidUsername _ = do mr <- getMessageRender return $ Left $ mr MsgInvalidUsername -- | What to do when the user logs in and the email has not yet been verified. -- -- By default, this displays a message and contains 'resendVerifyEmailForm', allowing -- the user to resend the verification email. The handler is run inside the post -- handler for login, so you can call 'setCreds' to preform a successful login. unregisteredLogin :: UserAccount db -> HandlerT Auth (HandlerT master IO) Html unregisteredLogin u = do tm <- getRouteToParent lift $ defaultLayout $ do setTitleI MsgEmailUnverified [whamlet| <p>_{MsgEmailUnverified} ^{resendVerifyEmailWidget (username u) tm} |] -- | The new account page. -- -- This is the page which is displayed on a GET to 'newAccountR', and defaults to -- an embedding of 'newAccountWidget'. getNewAccountR :: HandlerT Auth (HandlerT master IO) Html getNewAccountR = do tm <- getRouteToParent lift $ defaultLayout $ do setTitleI MsgRegisterLong newAccountWidget tm -- | Handles new account creation. -- -- By default, this processes 'newAccountForm', calls 'createNewAccount', sets a message -- and redirects to LoginR. If an error occurs, a message is set and the user is -- redirected to 'newAccountR'. postNewAccountR :: HandlerT Auth (HandlerT master IO) Html postNewAccountR = do tm <- getRouteToParent mr <- lift getMessageRender ((result, _), _) <- lift $ runFormPost $ render newAccountForm mdata <- case result of FormMissing -> invalidArgs ["Form is missing"] FormFailure msg -> return $ Left msg FormSuccess d -> return $ if newAccountPassword1 d == newAccountPassword2 d then Right d else Left [mr Msg.PassMismatch] case mdata of Left errs -> do setMessage $ toHtml $ T.concat errs redirect newAccountR Right d -> do void $ lift $ createNewAccount d tm redirect LoginR -- | Should the password reset inside this plugin be allowed? Defaults to True allowPasswordReset :: master -> Bool allowPasswordReset _ = True -- | The page which prompts for a username and sends an email allowing password reset. -- By default, it embeds 'resetPasswordWidget'. getResetPasswordR :: HandlerT Auth (HandlerT master IO) Html getResetPasswordR = do tm <- getRouteToParent lift $ defaultLayout $ do setTitleI Msg.PasswordResetTitle resetPasswordWidget tm -- | The page which allows the user to set a new password. -- -- This is called only when the email key has been verified as correct. By default, it embeds -- 'newPasswordWidget'. setPasswordHandler :: UserAccount db -> HandlerT Auth (HandlerT master IO) Html setPasswordHandler u = do tm <- getRouteToParent lift $ defaultLayout $ do setTitleI Msg.SetPassTitle newPasswordWidget u tm -- | Used for i18n of 'AccountMsg', defaults to 'defaultAccountMsg'. To support -- multiple languages, you can implement this method using the various translations -- from "Yesod.Auth.Account.Message". renderAccountMessage :: master -> [T.Text] -> AccountMsg -> T.Text renderAccountMessage _ _ = defaultAccountMsg instance YesodAuthFreeAccount db master => RenderMessage master AccountMsg where renderMessage = renderAccountMessage -- | Salt and hash a password. hashPassword :: MonadIO m => T.Text -> m B.ByteString hashPassword pwd = liftIO $ PS.makePassword (TE.encodeUtf8 pwd) 12 -- | Verify a password verifyPassword :: T.Text -- ^ password -> B.ByteString -- ^ hashed password -> Bool verifyPassword pwd = PS.verifyPassword (TE.encodeUtf8 pwd) nonceGen :: Nonce.Generator nonceGen = unsafePerformIO Nonce.new {-# NOINLINE nonceGen #-} -- | Randomly create a new verification key. newVerifyKey :: MonadIO m => m T.Text newVerifyKey = Nonce.nonce128urlT nonceGen --------------------------------------------------------------------------------------------------- -- | Lens getter infixl 8 ^. (^.) :: a -> ((b -> Const b b') -> a -> Const b a') -> b x ^. l = getConst $ l Const x instance (P.PersistEntity u, PersistUserCredentials u) => UserCredentials (P.Entity u) where username u = u ^. fieldLens userUsernameF userPasswordHash u = u ^. fieldLens userPasswordHashF userEmail u = u ^. fieldLens userEmailF userEmailVerified u = u ^. fieldLens userEmailVerifiedF userEmailVerifyKey u = u ^. fieldLens userEmailVerifyKeyF userResetPwdKey u = u ^. fieldLens userResetPwdKeyF -- | Internal state for the AccountPersistDB monad. data PersistFuncs master user = PersistFuncs { pGet :: T.Text -> HandlerT master IO (Maybe (P.Entity user)) , pInsert :: Username -> user -> HandlerT master IO (Either T.Text (P.Entity user)) , pUpdate :: P.Entity user -> [P.Update user] -> HandlerT master IO () } -- | A newtype which when using persistent is an instance of 'AccountDB'. newtype AccountPersistDB master user a = AccountPersistDB (ReaderT (PersistFuncs master user) (HandlerT master IO) a) deriving (Monad, MonadIO, Functor, Applicative) instance (Yesod master, PersistUserCredentials user) => AccountDB (AccountPersistDB master user) where type UserAccount (AccountPersistDB master user) = P.Entity user loadUser name = AccountPersistDB $ do f <- ask lift $ pGet f name addNewUser name email key pwd = AccountPersistDB $ do f <- ask lift $ pInsert f name $ userCreate name email key pwd verifyAccount u = AccountPersistDB $ do f <- ask lift $ pUpdate f u [ userEmailVerifiedF P.=. True , userEmailVerifyKeyF P.=. ""] setVerifyKey u key = AccountPersistDB $ do f <- ask lift $ pUpdate f u [userEmailVerifyKeyF P.=. key] setNewPasswordKey u key = AccountPersistDB $ do f <- ask lift $ pUpdate f u [userResetPwdKeyF P.=. key] setNewPassword u pwd = AccountPersistDB $ do f <- ask lift $ pUpdate f u [ userPasswordHashF P.=. pwd , userResetPwdKeyF P.=. ""] -- | Use this for 'runAccountDB' if you are using 'AccountPersistDB' as your database type. -- runAccountPersistDB :: ( Yesod master -- , YesodPersist master -- , P.PersistEntity user -- , PersistUserCredentials user -- , b ~ YesodPersistBackend master -- , PersistMonadBackend (b (HandlerT master IO)) ~ P.PersistEntityBackend user -- , P.PersistUnique (b (HandlerT master IO)) -- , P.PersistQuery (b (HandlerT master IO)) -- , YesodAuthFreeAccount db master -- , db ~ AccountPersistDB master user -- ) -- => AccountPersistDB master user a -> HandlerT master IO a runAccountPersistDB :: (PersistEntity t1, PersistUnique (YesodPersistBackend t), YesodPersist t, YesodAuthFreeAccount db t, PersistUserCredentials t1, YesodPersistBackend t ~ PersistEntityBackend t1) => AccountPersistDB t t1 a -> HandlerT t IO a runAccountPersistDB (AccountPersistDB m) = runReaderT m funcs where funcs = PersistFuncs { pGet = runDB . P.getBy . uniqueUsername , pInsert = \name u -> do mentity <- runDB $ P.insertBy u mr <- getMessageRender case mentity of Left _ -> return $ Left $ mr $ MsgUsernameExists name Right k -> return $ Right $ P.Entity k u , pUpdate = \(P.Entity key _) u -> runDB $ P.update key u } render :: GHC.Base.Monad m => FormRender m a render = renderBootstrap3 BootstrapBasicForm
jabaraster/jabara-yesod-auth-freeaccount
src/Jabara/Yesod/Auth/FreeAccount.hs
mit
43,058
0
21
11,467
6,581
3,463
3,118
493
10
module Cost where import Libaddutil.Misc (clamp) import Types import Production import Curve type CostFunction = (Price, ProductionFunction) -- Derive CostFunction on quantity - result is MR. -- CostFunction is of type f(q) = fc + vc(q) -- Variable costs must raise for large q. -- Otherwise an unlimited quantity will be produced -- (horizontal supply function). costs :: ProductionFunction -> Rental -> Wage -> Quantity -> Price costs prodfunc r w q = let (k, l) = factors prodfunc r w q in w * l + r * k totalCosts :: CostFunction -> Rental -> Wage -> Quantity -> Price totalCosts (fc, pf) r w q = costs pf r w q + fc marginalCosts :: CostFunction -> Rental -> Wage -> MarginalCostFunction marginalCosts (_, pf) = marginalCosts' pf marginalCosts' :: ProductionFunction -> Rental -> Wage -> MarginalCostFunction marginalCosts' (CobbDouglas prod alpha beta) r w = if alpha + beta == 0.5 then mkCurve $ LinearFunction (epsilon + cobbDouglasCostDerivedConstant prod alpha beta r w) 0 else mkCurve $ ExponentialFunction (cobbDouglasCostDerivedExponent alpha beta) (cobbDouglasCostDerivedConstant prod alpha beta r w) 0 marginalCosts' (Substitute prod alpha) r w = let dp = r / w in if dp < alpha then mkCurve $ LinearFunction (epsilon + (1 / prod) * r) 0 else mkCurve $ LinearFunction (epsilon + (1 / prod) * w) 0 marginalCosts' (Complement prod alpha) r w = mkCurve $ LinearFunction (epsilon + (alpha / prod) * r + (1 / prod) * w) 0 marginalCosts' (Constant prod) _ _ = mkCurve $ LinearFunction (maxCurveValue / prod) (-maxCurveValue) marginalCostsMRTS :: ProductionFunction -> Flt -> MarginalCostFunction marginalCostsMRTS p mrts = marginalCosts' p 1 mrts productionQuantity :: MarginalCostFunction -> Price -> Quantity productionQuantity = (clamp 0 maxCurveValue .) . lookupX productionQuantity' :: ProductionFunction -> Rental -> Wage -> Price -> Quantity productionQuantity' prodfunc r w p = clamp 0 maxCurveValue $ lookupX (marginalCosts' prodfunc r w) p cost :: CostFunction -> Rental -> Wage -> Quantity -> Price cost (fc, CobbDouglas productivity alpha beta) r w q = fc + (cobbDouglasCost productivity alpha beta r w q) cost (fc, Substitute productivity alpha) r w q = fc + (substituteCost productivity alpha r w q) cost (fc, Complement productivity alpha) r w q = fc + (complementCost productivity alpha r w q) cost (fc, Constant productivity) _ _ q = fc + (if q > productivity then maxCurveValue else 0)
anttisalonen/economics
src/Cost.hs
mit
2,489
0
14
474
835
436
399
39
3
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.MediaKeyNeededEvent (js_getInitData, getInitData, MediaKeyNeededEvent, castToMediaKeyNeededEvent, gTypeMediaKeyNeededEvent) 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[\"initData\"]" js_getInitData :: MediaKeyNeededEvent -> IO (Nullable Uint8Array) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaKeyNeededEvent.initData Mozilla MediaKeyNeededEvent.initData documentation> getInitData :: (MonadIO m) => MediaKeyNeededEvent -> m (Maybe Uint8Array) getInitData self = liftIO (nullableToMaybe <$> (js_getInitData (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/MediaKeyNeededEvent.hs
mit
1,432
6
10
165
371
236
135
24
1
{-| Module : PostgREST.Config Description : Manages PostgREST configuration options. This module provides a helper function to read the command line arguments using the optparse-applicative and the AppConfig type to store them. It also can be used to define other middleware configuration that may be delegated to some sort of external configuration. It currently includes a hardcoded CORS policy but this could easly be turned in configurable behaviour if needed. Other hardcoded options such as the minimum version number also belong here. -} module PostgREST.Config ( prettyVersion , readOptions , corsPolicy , minimumPgVersion , AppConfig (..) ) where import Control.Applicative import qualified Data.ByteString.Char8 as BS import qualified Data.CaseInsensitive as CI import Data.List (intercalate) import Data.String.Conversions (cs) import Data.Text (strip) import Data.Version (versionBranch) import Network.Wai import Network.Wai.Middleware.Cors (CorsResourcePolicy (..)) import Options.Applicative import Paths_postgrest (version) import Safe (readMay) import Web.JWT (Secret, secret) import Prelude -- | Data type to store all command line options data AppConfig = AppConfig { configDatabase :: String , configAnonRole :: String , configSchema :: String , configPort :: Int , configJwtSecret :: Secret , configPool :: Int , configMaxRows :: Maybe Integer } argParser :: Parser AppConfig argParser = AppConfig <$> argument str (help "(REQUIRED) database connection string, e.g. postgres://user:pass@host:port/db" <> metavar "DB_URL") <*> strOption (long "anonymous" <> short 'a' <> help "(REQUIRED) postgres role to use for non-authenticated requests" <> metavar "ROLE") <*> strOption (long "schema" <> short 's' <> help "schema to use for API routes" <> metavar "NAME" <> value "public" <> showDefault) <*> option auto (long "port" <> short 'p' <> help "port number on which to run HTTP server" <> metavar "PORT" <> value 3000 <> showDefault) <*> (secret . cs <$> strOption (long "jwt-secret" <> short 'j' <> help "secret used to encrypt and decrypt JWT tokens" <> metavar "SECRET" <> value "secret" <> showDefault)) <*> option auto (long "pool" <> short 'o' <> help "max connections in database pool" <> metavar "COUNT" <> value 10 <> showDefault) <*> (readMay <$> strOption (long "max-rows" <> short 'm' <> help "max rows in response" <> metavar "COUNT" <> value "infinity" <> showDefault)) defaultCorsPolicy :: CorsResourcePolicy defaultCorsPolicy = CorsResourcePolicy Nothing ["GET", "POST", "PATCH", "DELETE", "OPTIONS"] ["Authorization"] Nothing (Just $ 60*60*24) False False True -- | CORS policy to be used in by Wai Cors middleware corsPolicy :: Request -> Maybe CorsResourcePolicy corsPolicy req = case lookup "origin" headers of Just origin -> Just defaultCorsPolicy { corsOrigins = Just ([origin], True) , corsRequestHeaders = "Authentication":accHeaders , corsExposedHeaders = Just [ "Content-Encoding", "Content-Location", "Content-Range", "Content-Type" , "Date", "Location", "Server", "Transfer-Encoding", "Range-Unit" ] } Nothing -> Nothing where headers = requestHeaders req accHeaders = case lookup "access-control-request-headers" headers of Just hdrs -> map (CI.mk . cs . strip . cs) $ BS.split ',' hdrs Nothing -> [] -- | User friendly version number prettyVersion :: String prettyVersion = intercalate "." $ map show $ versionBranch version -- | Function to read and parse options from the command line readOptions :: IO AppConfig readOptions = customExecParser parserPrefs opts where opts = info (helper <*> argParser) $ fullDesc <> progDesc ( "PostgREST " <> prettyVersion <> " / create a REST API to an existing Postgres database" ) parserPrefs = prefs showHelpOnError -- | Tells the minimum PostgreSQL version required by this version of PostgREST minimumPgVersion :: Integer minimumPgVersion = 90300
motiz88/postgrest
src/PostgREST/Config.hs
mit
4,509
0
17
1,224
871
464
407
67
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Main where import qualified Data.ByteString.Lazy as BS import qualified Data.Map as Map import qualified Data.Text as Text import Data.Aeson (encode) import Data.Char (toLower) import Control.Monad (forM_) import System.Directory (createDirectoryIfMissing) import System.FilePath ((</>), (<.>)) import System.Exit (exitFailure, exitSuccess) import Ringo import Ringo.ArgParser import Ringo.InputParser data SQLType = Create | FullRefresh | IncRefresh deriving (Eq, Show) main :: IO () main = do ProgArgs {..} <- parseArgs result <- parseInput progInputFile case result of Left err -> putStrLn err >> exitFailure Right (tables, facts, defaults) -> case makeConfig tables facts progSettings defaults of Left errors -> mapM_ print errors >> exitFailure Right config -> writeFiles progOutputDir config >> exitSuccess writeFiles :: FilePath -> Config -> IO () writeFiles outputDir config = do let Settings{..} = configSettings config forM_ (makeSQLs config dimTables factTables) $ \(sqlType, table, sql) -> do let dirName = outputDir </> map toLower (show sqlType) createDirectoryIfMissing True dirName writeFile (dirName </> Text.unpack table <.> "sql") sql BS.writeFile (outputDir </> Text.unpack settingDependenciesJSONFileName) . encode . foldl (\acc -> Map.union acc . extractDependencies config) Map.empty $ facts BS.writeFile (outputDir </> Text.unpack settingDimensionsJSONFileName) . encode $ [ tableName table | (_, tabs) <- dimTables, table <- tabs , table `notElem` tables ] BS.writeFile (outputDir </> Text.unpack settingFactsJSONFileName) . encode $ [ tableName table | (_, table) <- factTables ] where facts = configFacts config tables = configTables config dimTables = [ (fact, extractDimensionTables config fact) | fact <- facts ] factTables = [ (fact, extractFactTable config fact) | fact <- facts, factTablePersistent fact ] makeSQLs :: Config -> [(Fact, [Table])] -> [(Fact, Table)] -> [(SQLType, TableName, String)] makeSQLs config dimTables factTables = let tables = configTables config dimTableDefinitionSQLs = [ (Create, tableName table, unlines . map Text.unpack $ dimensionTableDefinitionSQL config table) | (_, tabs) <- dimTables , table <- tabs , table `notElem` tables ] factTableDefinitionSQLs = [ (Create , tableName table, unlines . map Text.unpack $ factTableDefinitionSQL config fact table) | (fact, table) <- factTables ] dimTablePopulationSQLs typ gen = [ (typ , tableName table, Text.unpack $ gen config fact (tableName table)) | (fact, tabs) <- dimTables , table <- tabs , table `notElem` tables ] factTablePopulationSQLs typ gen = [ (typ, tableName table, unlines . map Text.unpack $ gen config fact) | (fact, table) <- factTables ] in concat [ dimTableDefinitionSQLs , factTableDefinitionSQLs , dimTablePopulationSQLs FullRefresh $ dimensionTablePopulationSQL FullPopulation , dimTablePopulationSQLs IncRefresh $ dimensionTablePopulationSQL IncrementalPopulation , factTablePopulationSQLs FullRefresh $ factTablePopulationSQL FullPopulation , factTablePopulationSQLs IncRefresh $ factTablePopulationSQL IncrementalPopulation ]
abhin4v/ringo
ringo/src/Main.hs
mit
3,582
0
17
861
1,049
553
496
69
3
module Application.Engine where import Application.Types import qualified Data.Map as M evalEvent :: Event -> AppState -> AppState evalEvent (AddTopic t) as = addTopic t as evalEvent (DeleteTopic t) as = deleteTopic t as evalEvent (AddRoom r) as = addRoom r as evalEvent (DeleteRoom r) as = deleteRoom r as evalEvent (AddBlock b) as = addBlock b as evalEvent (DeleteBlock b) as = deleteBlock b as evalEvent (AssignTopic s t) as = addTimeslot s t as evalEvent (UnassignTopic t) as = as { timeslots = M.filter (/= t) (timeslots as) } evalEvent (ReplayEvents as) _ = foldl (flip evalEvent) emptyState as evalEvent NOP as = as addTimeslot :: Slot -> Topic -> AppState -> AppState addTimeslot s t as = let topicslotFilter = M.filter (/= t) in as { timeslots = M.insert s t $ topicslotFilter (timeslots as) } deleteTimeslot :: Slot -> AppState -> AppState deleteTimeslot s as = as { timeslots = M.delete s (timeslots as) } addTopic :: Topic -> AppState -> AppState addTopic t as = as { topics = t: topics as} deleteTopic :: Topic -> AppState -> AppState deleteTopic t as = let topicslotFilter = M.filter (/= t) in as { topics = filter (/=t) (topics as) , timeslots = topicslotFilter (timeslots as) } addRoom :: Room -> AppState -> AppState addRoom r as = as { rooms = r : rooms as } deleteRoom :: Room -> AppState -> AppState deleteRoom r as = as { rooms = filter (/= r ) (rooms as) , timeslots = M.fromList $ roomFilter $ M.toList (timeslots as)} where roomFilter = filter (\(s, _) -> room s /= r) addBlock :: Block -> AppState -> AppState addBlock b as = as { blocks = b : blocks as } deleteBlock :: Block -> AppState -> AppState deleteBlock b as = as { blocks = filter (/= b ) (blocks as) , timeslots = M.fromList $ blockFilter $ M.toList (timeslots as)} where blockFilter = filter (\(s, _) -> block s /= b) replayEvents :: AppState -> [Event] -> AppState replayEvents = foldl (flip evalEvent) generateEvents :: AppState -> [Event] generateEvents as = concat [t, r, b, ts] where t = reverse $ map AddTopic (topics as) r = reverse $ map AddRoom (rooms as) b = reverse $ map AddBlock (blocks as) ts = map (uncurry AssignTopic) (M.toList (timeslots as))
kRITZCREEK/FROST-Backend
src/Application/Engine.hs
mit
2,426
0
12
669
944
492
452
45
1
split :: [a] -> Int -> ([a], [a]) split (x:xs) n | n > 0 = let (f, l) = split xs (n - 1) in (x : f, l) split xs _ = ([], xs)
curiousily/haskell-99problems
17.hs
mit
125
0
12
36
114
61
53
3
1
{-# LANGUAGE OverloadedStrings #-} module Kashmir.Web where import Data.Aeson import Data.ByteString import Snap mimeTypeJson, mimeTypeCss :: ByteString mimeTypeJson = "application/json" mimeTypeCss = "text/css" ------------------------------------------------------------ jsonResponse :: MonadSnap m => m () jsonResponse = modifyResponse $ setContentType mimeTypeJson writeJSON :: (ToJSON a,MonadSnap m) => a -> m () writeJSON a = do jsonResponse (writeLBS . encode) a writeJSONMaybe :: (MonadSnap m,ToJSON a) => Maybe a -> m () writeJSONMaybe (Just x) = writeJSON x writeJSONMaybe Nothing = notfound writeJSONEither :: (MonadSnap m,ToJSON e,ToJSON a) => Either e a -> m () writeJSONEither (Right x) = writeJSON x writeJSONEither (Left err) = do modifyResponse $ setResponseCode 500 writeJSON err getResponse >>= finishWith ------------------------------------------------------------ handleError :: MonadSnap m => Int -> m b handleError errorCode = do modifyResponse $ setResponseCode errorCode writeBS "" getResponse >>= finishWith handleErrorWithMessage :: (MonadSnap m) => Int -> ByteString -> m b handleErrorWithMessage code errorMessage = do modifyResponse $ setResponseCode code logError errorMessage writeBS errorMessage getResponse >>= finishWith forbidden, unauthorized, notfound :: (MonadSnap m) => m b forbidden = handleError 403 unauthorized = handleError 401 notfound = handleError 404 serverError, malformedRequest :: (MonadSnap m) => ByteString -> m b serverError = handleErrorWithMessage 500 malformedRequest = handleErrorWithMessage 400
krisajenkins/kashmir
src/Kashmir/Web.hs
epl-1.0
1,701
0
9
344
470
235
235
45
1
module HSE.NameMatch( Scope, emptyScope, moduleScope, scopeImports, NameMatch, nameMatch, nameQualify ) where import HSE.Type import HSE.Util import Data.List import Data.Maybe {- the hint file can do: import Prelude (filter) import Data.List (filter) import List (filter) then filter on it's own will get expanded to all of them import Data.List import List as Data.List if Data.List.head x ==> x, then that might match List too -} type NameMatch = QName S -> QName S -> Bool data Scope = Scope [ImportDecl S] deriving Show moduleScope :: Module S -> Scope moduleScope xs = Scope $ [prelude | not $ any isPrelude res] ++ res where res = [x | x <- moduleImports xs, importPkg x /= Just "hint"] prelude = ImportDecl an (ModuleName an "Prelude") False False Nothing Nothing Nothing isPrelude x = fromModuleName (importModule x) == "Prelude" emptyScope :: Scope emptyScope = Scope [] scopeImports :: Scope -> [ImportDecl S] scopeImports (Scope x) = x -- given A B x y, does A{x} possibly refer to the same name as B{y} -- this property is reflexive nameMatch :: Scope -> Scope -> NameMatch nameMatch a b x@Special{} y@Special{} = x =~= y nameMatch a b x y | isSpecial x || isSpecial y = False nameMatch a b x y = unqual x =~= unqual y && not (null $ possModules a x `intersect` possModules b y) -- given A B x, return y such that A{x} == B{y}, if you can nameQualify :: Scope -> Scope -> QName S -> QName S nameQualify a (Scope b) x | isSpecial x = x | null imps = head $ real ++ [x] | any (not . importQualified) imps = unqual x | otherwise = Qual an (head $ mapMaybe importAs imps ++ map importModule imps) $ fromQual x where real = [Qual an (ModuleName an m) $ fromQual x | m <- possModules a x] imps = [i | r <- real, i <- b, possImport i r] -- which modules could a name possibly lie in -- if it's qualified but not matching any import, assume the user -- just lacks an import possModules :: Scope -> QName S -> [String] possModules (Scope is) x = f x where res = [fromModuleName $ importModule i | i <- is, possImport i x] f Special{} = [""] f x@(Qual _ mod _) = [fromModuleName mod | null res] ++ res f _ = res possImport :: ImportDecl S -> QName S -> Bool possImport i Special{} = False possImport i (Qual _ mod x) = fromModuleName mod `elem` map fromModuleName ms && possImport i{importQualified=False} (UnQual an x) where ms = importModule i : maybeToList (importAs i) possImport i (UnQual _ x) = not (importQualified i) && maybe True f (importSpecs i) where f (ImportSpecList _ hide xs) = if hide then Just True `notElem` ms else Nothing `elem` ms || Just True `elem` ms where ms = map g xs g :: ImportSpec S -> Maybe Bool -- does this import cover the name x g (IVar _ y) = Just $ x =~= y g (IAbs _ y) = Just $ x =~= y g (IThingAll _ y) = if x =~= y then Just True else Nothing g (IThingWith _ y ys) = Just $ x `elem_` (y : map fromCName ys) fromCName :: CName S -> Name S fromCName (VarName _ x) = x fromCName (ConName _ x) = x
alphaHeavy/hlint
src/HSE/NameMatch.hs
gpl-2.0
3,199
0
11
833
1,152
583
569
52
7
module HLinear.Hook.ERHook.Algebra where import qualified Prelude as P import HLinear.Utility.Prelude import HLinear.Hook.ERHook.Definition import qualified HLinear.Hook.EchelonForm as EF import qualified HLinear.Matrix.Block as M instance Ring a => MultiplicativeMagma (ERHook a) where {-# INLINABLE (*) #-} (ERHook et m ef) * (ERHook et' m' ef') = ERHook (et'*et) (M.blockSumRows m' mTop) (EF.blockSumHook ef' mBottom ef) where (mTop,mBottom) = M.splitAtCols (nmbRows m') (et'*.m) instance Ring a => MultiplicativeSemigroup (ERHook a)
martinra/hlinear
src/HLinear/Hook/ERHook/Algebra.hs
gpl-3.0
578
0
10
108
188
105
83
14
0
module Declare.Attract where import Types data Attract = Attract { xName :: Maybe String , xClass :: Maybe String , xRole :: Maybe String , xTrans :: Maybe Bool , xFocus :: Maybe (Either SpaceRef TileRef) } deriving (Eq, Ord, Show)
ktvoelker/argon
src/Declare/Attract.hs
gpl-3.0
250
0
11
59
86
48
38
9
0
{-# LANGUAGE ScopedTypeVariables, TemplateHaskell #-} module Test.Scrooge where import Data.Time as Time import Data.Time.Calendar as Time import Data.Time.Calendar.MonthDay as Time import Control.Applicative import Test.QuickCheck import Test.QuickCheck.Text import Test.QuickCheck.All import Scrooge instance Arbitrary Day where arbitrary = do y <- oneof [pure 1984, pure 1983, pure 1, pure 0] m <- choose (1,12) d <- choose (1, monthLength (isLeapYear y) m) return $ fromGregorian y m d prop_Period (sta :: Day) = numOfPeriods sta (addDays 32 sta) == 1 dv = depositValue (Deposit (date "31.12.2014") 365 (Percent 18) (rub 50000)) (date "31.12.2015") return [] main = $quickCheckAll
grwlf/scrooge
Test/Scrooge.hs
gpl-3.0
713
0
13
124
252
134
118
20
1
import Instructions import qualified Data.ByteString.Lazy as B tab = compileTables [ Table "cmap" (cmapTable (cmapFormat0 0 (take 262 $ repeat 0))), Table "glyf" (glyph 0 0 10 10 [0,1,2] (return ()) [3,3,3] [3,4,5] [6,7,8]), Table "hhea" (hhea 0 0 0 1 0 0 0 0 0 1), Table "hmtx" (hmtx (hmtxEntry 0 0)), Table "loca" (_loca [0]), Table "maxp" (maxp 1 1 1 1 1 1 1 1 1 1 1 1 1 1), Table "name" (nameHeaderMS [MSNRecord Copyright "bacon", MSNRecord Fullname "tree", MSNRecord UUID "fish"]), Table "post" (post3 0 0 0 True) ] (headTable 1 1 0 0 0 0 1 1 0 0 0 1 0) main = do B.putStr $ fst $ compile tab
jseaton/ttasm
ttasm.hs
gpl-3.0
672
0
14
191
352
184
168
13
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.TagManager.Accounts.Containers.Variables.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a GTM Variable. -- -- /See:/ <https://developers.google.com/tag-manager/api/v1/ Tag Manager API Reference> for @tagmanager.accounts.containers.variables.create@. module Network.Google.Resource.TagManager.Accounts.Containers.Variables.Create ( -- * REST Resource AccountsContainersVariablesCreateResource -- * Creating a Request , accountsContainersVariablesCreate , AccountsContainersVariablesCreate -- * Request Lenses , acvcContainerId , acvcPayload , acvcAccountId ) where import Network.Google.Prelude import Network.Google.TagManager.Types -- | A resource alias for @tagmanager.accounts.containers.variables.create@ method which the -- 'AccountsContainersVariablesCreate' request conforms to. type AccountsContainersVariablesCreateResource = "tagmanager" :> "v1" :> "accounts" :> Capture "accountId" Text :> "containers" :> Capture "containerId" Text :> "variables" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Variable :> Post '[JSON] Variable -- | Creates a GTM Variable. -- -- /See:/ 'accountsContainersVariablesCreate' smart constructor. data AccountsContainersVariablesCreate = AccountsContainersVariablesCreate' { _acvcContainerId :: !Text , _acvcPayload :: !Variable , _acvcAccountId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountsContainersVariablesCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acvcContainerId' -- -- * 'acvcPayload' -- -- * 'acvcAccountId' accountsContainersVariablesCreate :: Text -- ^ 'acvcContainerId' -> Variable -- ^ 'acvcPayload' -> Text -- ^ 'acvcAccountId' -> AccountsContainersVariablesCreate accountsContainersVariablesCreate pAcvcContainerId_ pAcvcPayload_ pAcvcAccountId_ = AccountsContainersVariablesCreate' { _acvcContainerId = pAcvcContainerId_ , _acvcPayload = pAcvcPayload_ , _acvcAccountId = pAcvcAccountId_ } -- | The GTM Container ID. acvcContainerId :: Lens' AccountsContainersVariablesCreate Text acvcContainerId = lens _acvcContainerId (\ s a -> s{_acvcContainerId = a}) -- | Multipart request metadata. acvcPayload :: Lens' AccountsContainersVariablesCreate Variable acvcPayload = lens _acvcPayload (\ s a -> s{_acvcPayload = a}) -- | The GTM Account ID. acvcAccountId :: Lens' AccountsContainersVariablesCreate Text acvcAccountId = lens _acvcAccountId (\ s a -> s{_acvcAccountId = a}) instance GoogleRequest AccountsContainersVariablesCreate where type Rs AccountsContainersVariablesCreate = Variable type Scopes AccountsContainersVariablesCreate = '["https://www.googleapis.com/auth/tagmanager.edit.containers"] requestClient AccountsContainersVariablesCreate'{..} = go _acvcAccountId _acvcContainerId (Just AltJSON) _acvcPayload tagManagerService where go = buildClient (Proxy :: Proxy AccountsContainersVariablesCreateResource) mempty
rueshyna/gogol
gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Variables/Create.hs
mpl-2.0
4,084
0
16
894
467
279
188
78
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.ElasticBeanstalk.UpdateApplicationVersion -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Updates the specified application version to have the specified properties. -- -- <http://docs.aws.amazon.com/elasticbeanstalk/latest/api/API_UpdateApplicationVersion.html> module Network.AWS.ElasticBeanstalk.UpdateApplicationVersion ( -- * Request UpdateApplicationVersion -- ** Request constructor , updateApplicationVersion -- ** Request lenses , uavApplicationName , uavDescription , uavVersionLabel -- * Response , UpdateApplicationVersionResponse -- ** Response constructor , updateApplicationVersionResponse -- ** Response lenses , uavrApplicationVersion ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.ElasticBeanstalk.Types import qualified GHC.Exts data UpdateApplicationVersion = UpdateApplicationVersion { _uavApplicationName :: Text , _uavDescription :: Maybe Text , _uavVersionLabel :: Text } deriving (Eq, Ord, Read, Show) -- | 'UpdateApplicationVersion' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'uavApplicationName' @::@ 'Text' -- -- * 'uavDescription' @::@ 'Maybe' 'Text' -- -- * 'uavVersionLabel' @::@ 'Text' -- updateApplicationVersion :: Text -- ^ 'uavApplicationName' -> Text -- ^ 'uavVersionLabel' -> UpdateApplicationVersion updateApplicationVersion p1 p2 = UpdateApplicationVersion { _uavApplicationName = p1 , _uavVersionLabel = p2 , _uavDescription = Nothing } -- | The name of the application associated with this version. -- -- If no application is found with this name, 'UpdateApplication' returns an 'InvalidParameterValue' error. uavApplicationName :: Lens' UpdateApplicationVersion Text uavApplicationName = lens _uavApplicationName (\s a -> s { _uavApplicationName = a }) -- | A new description for this release. uavDescription :: Lens' UpdateApplicationVersion (Maybe Text) uavDescription = lens _uavDescription (\s a -> s { _uavDescription = a }) -- | The name of the version to update. -- -- If no application version is found with this label, 'UpdateApplication' -- returns an 'InvalidParameterValue' error. uavVersionLabel :: Lens' UpdateApplicationVersion Text uavVersionLabel = lens _uavVersionLabel (\s a -> s { _uavVersionLabel = a }) newtype UpdateApplicationVersionResponse = UpdateApplicationVersionResponse { _uavrApplicationVersion :: Maybe ApplicationVersionDescription } deriving (Eq, Read, Show) -- | 'UpdateApplicationVersionResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'uavrApplicationVersion' @::@ 'Maybe' 'ApplicationVersionDescription' -- updateApplicationVersionResponse :: UpdateApplicationVersionResponse updateApplicationVersionResponse = UpdateApplicationVersionResponse { _uavrApplicationVersion = Nothing } -- | The 'ApplicationVersionDescription' of the application version. uavrApplicationVersion :: Lens' UpdateApplicationVersionResponse (Maybe ApplicationVersionDescription) uavrApplicationVersion = lens _uavrApplicationVersion (\s a -> s { _uavrApplicationVersion = a }) instance ToPath UpdateApplicationVersion where toPath = const "/" instance ToQuery UpdateApplicationVersion where toQuery UpdateApplicationVersion{..} = mconcat [ "ApplicationName" =? _uavApplicationName , "Description" =? _uavDescription , "VersionLabel" =? _uavVersionLabel ] instance ToHeaders UpdateApplicationVersion instance AWSRequest UpdateApplicationVersion where type Sv UpdateApplicationVersion = ElasticBeanstalk type Rs UpdateApplicationVersion = UpdateApplicationVersionResponse request = post "UpdateApplicationVersion" response = xmlResponse instance FromXML UpdateApplicationVersionResponse where parseXML = withElement "UpdateApplicationVersionResult" $ \x -> UpdateApplicationVersionResponse <$> x .@? "ApplicationVersion"
dysinger/amazonka
amazonka-elasticbeanstalk/gen/Network/AWS/ElasticBeanstalk/UpdateApplicationVersion.hs
mpl-2.0
5,047
0
9
974
563
343
220
68
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Coordinate.Jobs.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves jobs created or modified since the given timestamp. -- -- /See:/ <https://developers.google.com/coordinate/ Google Maps Coordinate API Reference> for @coordinate.jobs.list@. module Network.Google.Resource.Coordinate.Jobs.List ( -- * REST Resource JobsListResource -- * Creating a Request , jobsList , JobsList -- * Request Lenses , jlTeamId , jlMinModifiedTimestampMs , jlOmitJobChanges , jlPageToken , jlMaxResults ) where import Network.Google.MapsCoordinate.Types import Network.Google.Prelude -- | A resource alias for @coordinate.jobs.list@ method which the -- 'JobsList' request conforms to. type JobsListResource = "coordinate" :> "v1" :> "teams" :> Capture "teamId" Text :> "jobs" :> QueryParam "minModifiedTimestampMs" (Textual Word64) :> QueryParam "omitJobChanges" Bool :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] JobListResponse -- | Retrieves jobs created or modified since the given timestamp. -- -- /See:/ 'jobsList' smart constructor. data JobsList = JobsList' { _jlTeamId :: !Text , _jlMinModifiedTimestampMs :: !(Maybe (Textual Word64)) , _jlOmitJobChanges :: !(Maybe Bool) , _jlPageToken :: !(Maybe Text) , _jlMaxResults :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'JobsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'jlTeamId' -- -- * 'jlMinModifiedTimestampMs' -- -- * 'jlOmitJobChanges' -- -- * 'jlPageToken' -- -- * 'jlMaxResults' jobsList :: Text -- ^ 'jlTeamId' -> JobsList jobsList pJlTeamId_ = JobsList' { _jlTeamId = pJlTeamId_ , _jlMinModifiedTimestampMs = Nothing , _jlOmitJobChanges = Nothing , _jlPageToken = Nothing , _jlMaxResults = Nothing } -- | Team ID jlTeamId :: Lens' JobsList Text jlTeamId = lens _jlTeamId (\ s a -> s{_jlTeamId = a}) -- | Minimum time a job was modified in milliseconds since epoch. jlMinModifiedTimestampMs :: Lens' JobsList (Maybe Word64) jlMinModifiedTimestampMs = lens _jlMinModifiedTimestampMs (\ s a -> s{_jlMinModifiedTimestampMs = a}) . mapping _Coerce -- | Whether to omit detail job history information. jlOmitJobChanges :: Lens' JobsList (Maybe Bool) jlOmitJobChanges = lens _jlOmitJobChanges (\ s a -> s{_jlOmitJobChanges = a}) -- | Continuation token jlPageToken :: Lens' JobsList (Maybe Text) jlPageToken = lens _jlPageToken (\ s a -> s{_jlPageToken = a}) -- | Maximum number of results to return in one page. jlMaxResults :: Lens' JobsList (Maybe Word32) jlMaxResults = lens _jlMaxResults (\ s a -> s{_jlMaxResults = a}) . mapping _Coerce instance GoogleRequest JobsList where type Rs JobsList = JobListResponse type Scopes JobsList = '["https://www.googleapis.com/auth/coordinate", "https://www.googleapis.com/auth/coordinate.readonly"] requestClient JobsList'{..} = go _jlTeamId _jlMinModifiedTimestampMs _jlOmitJobChanges _jlPageToken _jlMaxResults (Just AltJSON) mapsCoordinateService where go = buildClient (Proxy :: Proxy JobsListResource) mempty
rueshyna/gogol
gogol-maps-coordinate/gen/Network/Google/Resource/Coordinate/Jobs/List.hs
mpl-2.0
4,415
0
17
1,144
667
386
281
97
1
module LastDigit(lastDigit) where get :: Integer -> Int -> Integer get _ 0 = 1 get 0 _ = 0 get 1 _ = 1 get 2 n = (repeat [2, 4, 8, 6] >>= id) !! (n + 1) get 3 n = (repeat [3, 9, 7, 1] >>= id) !! (n + 1) get 4 n = (repeat [4, 6] >>= id) !! (n + 1) get 5 n = 5 get 6 n = 6 get 7 n = (repeat [7, 9, 3, 1] >>= id) !! (n + 1) get 8 n = (repeat [8, 4, 2, 6] >>= id) !! (n + 1) get 9 n = (repeat [9, 1] >>= id) !! (n + 1) lastDigit :: [Integer] -> Integer lastDigit a = foldr f 1 ((`mod` 10) <$> reverse a) where f n = get n . fromInteger --
ice1000/OI-codes
codewars/1-100/last-digit-of-a-huge-number.hs-wrong.hs
agpl-3.0
541
0
9
152
379
207
172
16
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} module Api.Services.AgdaService where import Control.Lens import Data.Aeson import Snap.Core import Snap.Snaplet import AgdaComm.TypeCheck import qualified Data.ByteString.Char8 as B import Data.Text import System.Random import qualified Data.Text.IO as D import Data.UUID import Control.Monad.IO.Class import System.Directory ( createDirectoryIfMissing ) import Type.Snippet data AgdaService = AgdaService makeLenses ''AgdaService agdaRoutes :: [(B.ByteString, Handler b AgdaService ())] agdaRoutes = [("/typecheck", method POST typeCheck)] typeCheck :: Handler b AgdaService () typeCheck = do text <- readRequestBody (2 * 1024 * 1024) -- 2 megabytes let snippet = decode text :: Maybe Snippet case snippet of Nothing -> modifyResponse $ setResponseCode 400 Just sn -> do file <- liftIO $ writeAgdaFile (code sn) err <- liftIO $ doCheck file writeLBS $ encode err writeAgdaFile :: Text -> IO String writeAgdaFile content = do uuid <- randomIO let fn = toString uuid let file = "tmp/" ++ fn ++ ".agda" D.writeFile file content return file agdaServiceInit :: SnapletInit b AgdaService agdaServiceInit = makeSnaplet "agda" "Agda Service" Nothing $ do liftIO $ createDirectoryIfMissing False "tmp" addRoutes agdaRoutes return AgdaService
qwe2/try-agda
src/Api/Services/AgdaService.hs
apache-2.0
1,401
0
16
244
403
207
196
44
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {- Copyright 2017 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module CodeWorld.CollabModel where import qualified Control.Concurrent.STM as STM import Control.OperationalTransformation.Selection (Selection) import Control.OperationalTransformation.Server (ServerState) import Control.OperationalTransformation.Text (TextOperation) import Data.Aeson import GHC.Generics (Generic) import Data.Hashable (Hashable) import qualified Data.HashMap.Strict as HM import Data.Text (Text) import Data.Time.Clock (UTCTime) data CollabServerState = CollabServerState { collabProjects :: STM.TVar CollabProjects , started :: UTCTime } type CollabProjects = HM.HashMap CollabId (STM.TVar CollabProject) data CollabProject = CollabProject { totalUsers :: !Int , collabKey :: CollabId , collabState :: ServerState Text TextOperation , users :: [CollabUserState] } data CollabUserState = CollabUserState { suserId :: !Text , suserIdent :: !Text , userSelection :: !Selection } instance ToJSON CollabUserState where toJSON (CollabUserState _ userIdent' sel) = object $ [ "name" .= userIdent' ] ++ (if sel == mempty then [] else [ "selection" .= sel ]) newtype CollabId = CollabId { unCollabId :: Text } deriving (Eq, Generic) instance Hashable CollabId
parvmor/codeworld
codeworld-collab-server/src/CodeWorld/CollabModel.hs
apache-2.0
2,021
0
10
438
321
191
130
39
0
module Sol2 where import GS import TAMO -- 2.13 c1 = logEquiv1 (\p -> False) (\p -> not True) c2 = logEquiv1 (\p -> p ==> False) (\p -> not p) c3_1 = logEquiv1 (\p -> p || True) (\p -> True) c3_2 = logEquiv1 (\p -> p && False) (\p -> False) c4_1 = logEquiv1 (\p -> p || False) id c4_2 = logEquiv1 (\p -> p && True) id c5 = logEquiv1 (\p -> p || not p) (\p -> True) c6 = logEquiv1 (\p -> p && not p) (\p -> False) -- 2.15 checkCntr1 :: (Bool -> Bool) -> Bool checkCntr1 bf = not (bf True) && not (bf False) checkCntr2 :: (Bool -> Bool -> Bool) -> Bool checkCntr2 bf = and [not(bf p q) | p <- [True, False], q <- [True, False]] checkCntr3 :: (Bool -> Bool -> Bool -> Bool) -> Bool checkCntr3 bf = and [not(bf p q r) | p <- [True, False], q <- [True, False], r <- [True, False]] -- 2.20 p1 = logEquiv2 (\p q -> not p ==> q) (\p q -> p ==> not q) p2 = logEquiv2 (\p q -> not p ==> q) (\p q -> q ==> not p) p3 = logEquiv2 (\p q -> not p ==> q) (\p q -> not q ==> p) p4 = logEquiv3 (\p q r -> p ==> (q ==> r)) (\p q r -> q ==> (p ==> r)) p5 = logEquiv3 (\p q r -> p ==> (q ==> r)) (\p q r -> (p ==> q) ==> r) p6 = logEquiv2 (\p q -> (p ==> q) ==> p) (\p q -> p) p7 = logEquiv3 (\p q r -> (p || q) ==> r) (\p q r -> (p ==> r) || (q ==> r)) -- 2.51 unique :: (a -> Bool) -> [a] -> Bool unique p xs = length (filter p xs) == 1 -- 2.52 parity :: [Bool] -> Bool parity xs = even (length (filter (\x -> x == True) xs)) -- 2.53 evenNR :: (a -> Bool) -> [a] -> Bool evenNR p xs = parity (map p xs) -- alternative: evenNRa p = parity . map p
bartolkaruza/software-testing-2014-group-W1
week1/week_1_group_w1/Sol2.hs
apache-2.0
1,780
0
12
625
965
524
441
33
1
{-# LANGUAGE DeriveDataTypeable #-} --HaskerDeux import System.Environment import System.IO import System.IO.Error import System.Process import Data.List import Data.List.Split --need to install import Data.Map import Control.Monad import Control.Applicative import Data.Maybe import Text.JSON --need to install for JSON import Text.JSON.Generic --need to install for JSON import Data.Time import System.Time import System.Locale (defaultTimeLocale) import System.Directory import Network.URI.Encode --need to install --Note to self: to run you type `runhaskell haskerdeux.hs test "me" "this" "that"`, etc dispatch :: String -> (String, [String]) -> IO() dispatch "todos" = todos dispatch "new" = new dispatch "crossoff" = crossoff dispatch "putoff" = putoff dispatch "moveto" = moveto dispatch "delete" = remove main = do (date:command:argList) <- getArgs time <- getClockTime >>= toCalendarTime --https://wiki.haskell.org/Unix_tools/Date let todays_date = formatCalendarTime defaultTimeLocale "%Y-%m-%d" time let tomorrows_date = show (addDays 1 $ read todays_date::Data.Time.Day) let todos_date | date == "today" = todays_date | date == "tomorrow" = tomorrows_date | otherwise = date when ((command `elem` ["todos"] && Data.List.null argList) || (command `elem` ["new", "crossoff", "putoff", "delete"] && length argList == 1) || (command == "moveto" && length argList == 2)) $ do token <- login dispatch command (token, todos_date:argList) readnetrc = do home <- getHomeDirectory netrc <- lines Control.Applicative.<$> readFile (home ++ "/.netrc") let netrc' = dropWhile (not . ("teuxdeux" `isInfixOf`)) netrc let (username, password) = if "login" `isInfixOf` head netrc' -- if entry is on one line then (getcred "login", getcred "password") -- if entry is on multiple lines else (last $ words $ netrc' !! 1, last $ words $ netrc' !! 2) where getcred c = dropWhile (not . (c `isInfixOf`)) (words $ head netrc') !! 1 return (username, password) curlget (token, date) = do let curlheader = "X-CSRF-Token: " ++ token body <- readProcess "curl" ["-s", "-L", "-c", "haskerdeux.cookies", "-b", "haskerdeux.cookies", "-H", curlheader, "https://teuxdeux.com/api/v1/todos/calendar?begin_date="++date++"&end_date="++date] [] let ok = not ("Invalid CSRF Token" `isInfixOf` body) if ok then do let tds = decodeJSON body :: [Teuxdeux] let tdsf = Data.List.filter (\td -> current_date td == date && not (done td)) tds return tdsf else do token <- relogin curlget (token, date) curlpost (token, [date, key, value, apiurl, okresponse]) number = do let curlheader = "X-CSRF-Token: " ++ token --Can be much improved, but will do for now: json <- if isJust number then do tdsf <- curlget (token, date) let itemid = Main.id $ tdsf!!(read (fromJust number)::Int) let modjson = "{ \"ids\" : [\""++show itemid++"\"], \""++key++"\" : \""++value++"\"}" return modjson else do --Can't just straight return these strings, need to let them first let newjson = "{ \"current_date\" : \""++date++"\", \""++key++"\" : \""++value++"\"}" return newjson body <- readProcess "curl" ["-s", "-XPOST", apiurl, "-L", "-c", "haskerdeux.cookies", "-b", "haskerdeux.cookies", "-H", curlheader, "-H", "Content-Type: application/json", "-d", json] [] let ok = not ("Invalid CSRF Token" `isInfixOf` body) if ok then if "done_updated_at" `isInfixOf` body then putStrLn okresponse else putStrLn "Uh Oh! Didn't work!" else do token <- relogin curlpost (token, [date, key, value, apiurl, okresponse]) number curldelete (token, [date, apiurl, okresponse]) number = do tdsf <- curlget (token, date) let itemid = Main.id $ tdsf!!(read number::Int) let curlheader = "X-CSRF-Token: " ++ token body <- readProcess "curl" ["-s", "-XDELETE", apiurl++show itemid, "-c", "haskerdeux.cookies", "-b", "haskerdeux.cookies", "-H", curlheader] [] let ok = not ("Invalid CSRF Token" `isInfixOf` body) if ok then if "done_updated_at" `isInfixOf` body then putStrLn okresponse else putStrLn "Uh Oh! Didn't work!" else do token <- relogin curldelete (token, [date, apiurl, okresponse]) number curlput (token, [date, json, apiurl, okresponse]) number = do tdsf <- curlget (token, date) let itemid = Main.id $ tdsf!!(read number::Int) let curlheader = "X-CSRF-Token: " ++ token body <- readProcess "curl" ["-s", "-XPUT", apiurl++show itemid, "-L", "-c", "haskerdeux.cookies", "-b", "haskerdeux.cookies", "-H", curlheader, "-H", "Content-Type: application/json", "-d", json] [] let ok = not ("Invalid CSRF Token" `isInfixOf` body) if ok then if "done_updated_at" `isInfixOf` body then putStrLn okresponse else putStrLn "Uh Oh! Didn't work!" else do token <- relogin curlput (token, [date, json, apiurl, okresponse]) number getauthtoken body = do let bodylines = lines body let authline = dropWhile (not . ("authenticity_token" `isInfixOf`)) bodylines let authwords = words $ head authline let authtokenword = stripPrefix "value=\"" $ last authwords let revauthtokenword = reverse $ fromJust authtokenword let authtoken = reverse $ fromJust $ stripPrefix ">\"" revauthtokenword return authtoken login = do username <- fmap fst readnetrc password <- fmap snd readnetrc home <- getHomeDirectory savedtoken <- doesFileExist (home ++ "/.haskerdeux-token") if savedtoken then do token <- readFile (home ++ "/.haskerdeux-token") return token else do body <- readProcess "curl" ["-s", "-L", "-c", "haskerdeux.cookies", "https://teuxdeux.com/login"] [] token <- getauthtoken body writeFile (home ++ "/.haskerdeux-token") token let curlheader = "X-CSRF-Token: " ++ token let curlpostfields = "username=" ++ username ++ "&password=" ++ password ++ "&authenticity_token=" ++ token body <- readProcess "curl" ["-s", "-L", "-c", "haskerdeux.cookies", "-b", "haskerdeux.cookies", "-H", curlheader, "-d", curlpostfields, "https://teuxdeux.com/login"] [] return token relogin = do home <- getHomeDirectory removeFile (home ++ "/.haskerdeux-token") token <- login return token todos (token, [todos_date]) = do tdsf <- curlget (token, todos_date) putStr $ unlines $ zipWith (\n td -> show n ++ " - " ++ td) [0..] $ Data.List.map text tdsf --numbering from LYAH new (token, [todos_date, todo]) = do let encodedtodo = Network.URI.Encode.encode todo curlpost (token, [todos_date, "text", todo, "https://teuxdeux.com/api/v1/todos/", "Added!"]) Nothing crossoff (token, [todos_date, number]) = curlput (token, [todos_date, "{ \"done\": true }", "https://teuxdeux.com/api/v1/todos/", "Crossed Off!"]) number putoff (token, [todos_date, number]) = do let tomorrows_date = show (addDays 1 $ read todos_date::Data.Time.Day) curlpost (token, [todos_date, "current_date", tomorrows_date, "https://teuxdeux.com/api/v1/todos/reposition/", "Put Off!"]) (Just number) moveto (token, [todos_date, number, new_date]) = --TODO: Need to figure out moving to bottom of a list curlpost (token, [todos_date, "current_date", new_date, "https://teuxdeux.com/api/v1/todos/reposition", "Moved!"]) (Just number) remove (token, [todos_date, number]) = curldelete (token, [todos_date, "https://teuxdeux.com/api/v1/todos/", "Deleted!"]) number --Thanks to http://www.amateurtopologist.com/blog/2010/11/05/a-haskell-newbies-guide-to-text-json/ and http://hpaste.org/41263/parsing_json_with_textjson data Teuxdeux = Teuxdeux { id :: Integer, current_date :: String, text :: String, done :: Bool } deriving (Eq, Show, Data, Typeable)
atomicules/HaskerDeux
haskerdeux.hs
bsd-2-clause
7,613
57
20
1,266
2,494
1,325
1,169
154
4
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} -------------------------------------------------------------------- -- | -- Copyright : (c) Edward Kmett -- License : BSD3 -- Maintainer: Edward Kmett <[email protected]> -- Stability : experimental -- Portability: non-portable -- -------------------------------------------------------------------- module Ermine.Syntax.Pattern ( Pattern(..) , _SigP , _WildcardP , _AsP , _StrictP , _LazyP , _LitP , _ConP , _TupP , _ConP' , _LitP' , PatternHead(..) , _TupH , _ConH , conventions , headName , traverseHead , PatternPath(..) , PatternPaths , fieldPP , argPP , leafPP , paths , manyPaths , Guarded(..) , Alt(..) , bitraverseAlt , patternHead , prune , forces , irrefutable -- , getAlt, putAlt, getPat, putPat , serializeAlt3 , deserializeAlt3 ) where import Bound import Control.Applicative import Control.Monad import Control.Lens import Data.Bitraversable import qualified Data.Binary as Binary import Data.Binary (Binary) import Data.Bytes.Serial import Data.Bytes.Get import Data.Bytes.Put import Data.Foldable import Data.Hashable import Data.Monoid import qualified Data.Serialize as Serialize import Data.Serialize (Serialize) import Data.Word import Ermine.Syntax import Ermine.Syntax.Convention import Ermine.Syntax.Global import Ermine.Syntax.Literal import Ermine.Syntax.Scope import GHC.Generics -- | Patterns used by 'Term' data Pattern t = SigP t | WildcardP | AsP (Pattern t) | StrictP (Pattern t) | LazyP (Pattern t) | LitP !Literal | ConP !Global [Pattern t] -- # of unboxed arguments, the constructor name, and patterns | TupP [Pattern t] deriving (Eq, Show, Functor, Foldable, Traversable) makePrisms ''Pattern _ConP' :: Global -> Prism' (Pattern t) [Pattern t] _ConP' g = prism (ConP g) $ \ xs -> case xs of ConP g' ps | g == g' -> Right ps p -> Left p _LitP' :: Literal -> Prism' (Pattern t) [Pattern t] _LitP' l = prism (\[] -> LitP l) $ \xs -> case xs of LitP l' | l == l' -> Right [] p -> Left p -- | Paths into a pattern tree. These will be used as the bound variables -- for scopes that have patterns in their binder. No effort has been made -- to enforce statically that pattern paths used in a given scope -- correspond only to well-formed paths into the particular tree; it will -- merely have to be an invariant maintained in the compiler. -- -- LeafPP represents a reference to the variable at a node that binds -- a variable. For instance, LeafPP is a valid path into SigP. It is also -- valid for AsP p for all p, because AsP binds a variable. It is invalid -- for ConP, however. -- -- No effort is made to represent paths with no decision points. This is -- primarily because it is detrimental to the compilation strategy. AsP, -- StrictP and LazyP can be thought of as annotations that are not -- full-fledged patterns in themselves. AsP signals that it is valid to -- make reference to an entire piece of substructure, while StrictP and -- LazyP inform the pattern compilation process. But it is unnecessary to -- distinguish between pointing at an AsP---which is always valid---and -- pointing at the right portion of an AsP---which is invalid unless the -- pattern contains redundancies. data PatternPath = LeafPP -- ^ refer to a variable | FieldPP {-# UNPACK #-} !Word64 PatternPath -- ^ refer to the n-th subpattern of a constructor | ArgPP {-# UNPACK #-} !Word64 PatternPath -- ^ refer to the n-th pattern of many top-level patterns deriving (Eq, Ord, Show, Read, Generic) type PatternPaths = Endo PatternPath fieldPP :: Word64 -> PatternPaths fieldPP = Endo . FieldPP argPP :: Word64 -> PatternPaths argPP = Endo . ArgPP leafPP :: PatternPaths -> PatternPath leafPP = flip appEndo LeafPP -- | Returns all the paths pointing to variables in the given pattern, in -- order from left to right. paths :: Pattern t -> [PatternPath] paths = go mempty where go pp (SigP _) = [leafPP pp] go pp (AsP p) = leafPP pp : go pp p go pp (StrictP p) = go pp p go pp (LazyP p) = go pp p go pp (ConP _ ps) = join $ zipWith (\i -> go $ pp <> fieldPP i) [0..] ps go pp (TupP ps) = join $ zipWith (\i -> go $ pp <> fieldPP i) [0..] ps go _ _ = [] -- | Returns all the paths pointing to variables in a series of patterns. -- The list is assumed to contain patterns in left-to-right order, and the -- resulting list will be in the same order. manyPaths :: [Pattern t] -> [PatternPath] manyPaths = join . zipWith (\i -> map (ArgPP i) . paths) [0..] instance Hashable PatternPath data PatternHead = TupH !Word64 | ConH [Convention] !Global | LitH !Literal deriving (Eq, Ord, Show) makePrisms ''PatternHead conventions :: PatternHead -> [Convention] conventions (TupH n) = replicate (fromIntegral n) C conventions (ConH cc _) = cc conventions LitH{} = [] headName :: Traversal' PatternHead Global headName f (ConH a g) = ConH a <$> f g headName _ h = pure h patternHead :: Fold (Pattern t) PatternHead patternHead f p@(ConP g ps) = p <$ f (ConH (C <$ ps) g) patternHead f p@(TupP ps) = p <$ f (TupH . fromIntegral $ length ps) patternHead f (AsP p) = patternHead f p patternHead f (StrictP p) = patternHead f p patternHead f p@(LitP l) = p <$ f (LitH l) patternHead _ p = pure p traverseHead :: PatternHead -> Traversal' (Pattern t) [Pattern t] traverseHead (ConH _ g) = _ConP' g traverseHead (TupH _) = _TupP traverseHead (LitH l) = _LitP' l prune :: Pattern t -> Pattern t prune (AsP p) = prune p prune (StrictP p) = prune p prune p = p forces :: Pattern t -> Bool forces ConP{} = True forces TupP{} = True forces StrictP{} = True forces LitP{} = True forces (AsP p) = forces p forces _ = False -- | A datatype for representing potentially guarded cases of a function -- or case body. data Guarded tm = Unguarded tm | Guarded [(tm, tm)] deriving (Eq, Ord, Show, Read, Functor, Foldable, Traversable, Generic) -- | One alternative of a core expression data Alt t f a = Alt !(Pattern t) (Guarded (Scope PatternPath f a)) deriving (Eq,Show,Functor,Foldable,Traversable) instance Bound (Alt t) where Alt p b >>>= f = Alt p (fmap (>>>= f) b) instance Monad f => BoundBy (Alt t f) f where boundBy f (Alt p b) = Alt p (fmap (boundBy f) b) -- | Helper function for traversing both sides of an 'Alt'. bitraverseAlt :: (Bitraversable k, Applicative f) => (t -> f t') -> (a -> f b) -> Alt t (k t) a -> f (Alt t' (k t') b) bitraverseAlt f g (Alt p b) = Alt <$> traverse f p <*> traverse (bitraverseScope f g) b irrefutable :: Pattern t -> Bool irrefutable (SigP _) = True irrefutable WildcardP = True irrefutable (LazyP _) = True irrefutable (AsP p) = irrefutable p irrefutable _ = False instance (Bifunctor p, Choice p, Applicative f) => Tup p f (Pattern t) where _Tup = prism TupP $ \p -> case p of TupP ps -> Right ps _ -> Left p {-# INLINE _Tup #-} instance (Serial t, Serial1 f) => Serial1 (Alt t f) where serializeWith pa (Alt p s) = do serialize p serializeWith (serializeWith pa) s deserializeWith ga = liftM2 Alt deserialize (deserializeWith $ deserializeWith ga) instance Serial1 Guarded where serializeWith ptm (Unguarded tm) = putWord8 0 *> ptm tm serializeWith ptm (Guarded tms) = putWord8 1 *> serializeWith putPair tms where putPair (tm1, tm2) = ptm tm1 *> ptm tm2 deserializeWith gtm = getWord8 >>= \b -> case b of 0 -> Unguarded <$> gtm 1 -> Guarded <$> deserializeWith ((,) <$> gtm <*> gtm) _ -> fail $ "getGuarded: Unexpected constructor code: " ++ show b instance Serial v => Serial (Guarded v) where serialize = serialize1 ; deserialize = deserialize1 instance Binary tm => Binary (Guarded tm) where put = serializeWith Binary.put get = deserializeWith Binary.get instance Serialize tm => Serialize (Guarded tm) where put = serializeWith Serialize.put get = deserializeWith Serialize.get instance (Serial t, Serial1 f, Serial a) => Serial (Alt t f a) where serialize = serializeWith serialize deserialize = deserializeWith deserialize serializeAlt3 :: MonadPut m => (t -> m ()) -> (forall a. (a -> m ()) -> f a -> m ()) -> (v -> m ()) -> Alt t f v -> m () serializeAlt3 pt pf pv (Alt p b) = serializeWith pt p *> serializeWith (serializeScope3 serialize pf pv) b deserializeAlt3 :: MonadGet m => m t -> (forall a. m a -> m (f a)) -> m v -> m (Alt t f v) deserializeAlt3 gt gf gv = Alt <$> deserializeWith gt <*> deserializeWith (deserializeScope3 deserialize gf gv) instance Serial1 Pattern where serializeWith pt (SigP t) = putWord8 0 >> pt t serializeWith _ WildcardP = putWord8 1 serializeWith pt (AsP p) = putWord8 2 >> serializeWith pt p serializeWith pt (StrictP p) = putWord8 3 >> serializeWith pt p serializeWith pt (LazyP p) = putWord8 4 >> serializeWith pt p serializeWith _ (LitP l) = putWord8 5 >> serialize l serializeWith pt (ConP g ps) = putWord8 6 >> serialize g >> serializeWith (serializeWith pt) ps serializeWith pt (TupP ps) = putWord8 7 >> serializeWith (serializeWith pt) ps deserializeWith gt = getWord8 >>= \b -> case b of 0 -> liftM SigP gt 1 -> return WildcardP 2 -> liftM AsP $ deserializeWith gt 3 -> liftM StrictP $ deserializeWith gt 4 -> liftM LazyP $ deserializeWith gt 5 -> liftM LitP deserialize 6 -> liftM2 ConP deserialize (deserializeWith $ deserializeWith gt) 7 -> liftM TupP $ deserializeWith (deserializeWith gt) _ -> fail $ "get Pattern: unexpected constructor tag: " ++ show b instance Serial a => Serial (Pattern a) where serialize = serializeWith serialize deserialize = deserializeWith deserialize instance Binary t => Binary (Pattern t) where put = serializeWith Binary.put get = deserializeWith Binary.get instance Serialize t => Serialize (Pattern t) where put = serializeWith Serialize.put get = deserializeWith Serialize.get instance Serial PatternPath where instance Binary PatternPath where put = serialize ; get = deserialize instance Serialize PatternPath where put = serialize ; get = deserialize
ekmett/ermine
src/Ermine/Syntax/Pattern.hs
bsd-2-clause
10,403
0
16
2,184
3,329
1,714
1,615
243
7
module Language.Modelica.Parser.Programme where import Language.Modelica.Syntax.Programme import Language.Modelica.Parser.Parser (Parser) import Language.Modelica.Parser.Lexer import Language.Modelica.Parser.Utility (until) import Prelude hiding (until) import Text.ParserCombinators.Parsec ((<|>), try, manyTill, anyChar, lookAhead, string, char, eof) import Control.Applicative (liftA) code :: Parser TextSegment code = liftA Code $ manyTill anyChar (lookAhead p) where p = string "\"" <|> try (string "//") <|> try (string "/*") <|> (eof >> return "") block :: Parser TextSegment block = (char '\"' >> Str `until` (char '\"')) <|> (try (string "//") >> LineComment `until` eol_or_eof) <|> (try (string "/*") >> BlockComment `until` try (string "*/")) <|> code modelica_programme :: Parser [TextSegment] modelica_programme = manyTill block eof
xie-dongping/modelicaparser
src/Language/Modelica/Parser/Programme.hs
bsd-3-clause
908
0
13
165
301
170
131
23
1
module Main (main) where import Data.Bits import Data.Word import Data.Int -- import Test.Framework (defaultMain, testGroup, testCase) import Test.Framework import Test.Framework.Providers.QuickCheck2 -- import Test.HUnit import Data.IntCast (intCastMaybe) -- test casting from type a to b (2nd argument is used as type-index only) -- testIntCastMaybe :: a -> b -> Bool testIntCastMaybe :: (Bits a, Integral a, Bits b, Integral b) => a -> b -> Bool testIntCastMaybe x _y = refRes == iutRes where refRes = intCastMaybeRef x `asTypeOf` (Just _y) iutRes = intCastMaybe x `asTypeOf` (Just _y) intCastMaybeRef :: (Integral a1, Integral a) => a -> Maybe a1 intCastMaybeRef x | toInteger x == toInteger y = Just y | otherwise = Nothing where y = fromIntegral x {- list generated with let intTypes = words "Int Int8 Int16 Int32 Int64 Word Word8 Word16 Word32 Word64 Integer" putStrLn $ concat [ " [ " , intercalate "\n , " [ concat [ "testProperty \"", t1, "->", t2, "\" (testIntCastMaybe :: ", t1, " -> ", t2, "-> Bool)"] | t1 <- types, t2 <- types ] , "\n ]" ] -} testGrp_intCastMaybe :: Test testGrp_intCastMaybe = testGroup "intCastMaybe" [ testProperty "Int->Int" (testIntCastMaybe :: Int -> Int-> Bool) , testProperty "Int->Int8" (testIntCastMaybe :: Int -> Int8-> Bool) , testProperty "Int->Int16" (testIntCastMaybe :: Int -> Int16-> Bool) , testProperty "Int->Int32" (testIntCastMaybe :: Int -> Int32-> Bool) , testProperty "Int->Int64" (testIntCastMaybe :: Int -> Int64-> Bool) , testProperty "Int->Word" (testIntCastMaybe :: Int -> Word-> Bool) , testProperty "Int->Word8" (testIntCastMaybe :: Int -> Word8-> Bool) , testProperty "Int->Word16" (testIntCastMaybe :: Int -> Word16-> Bool) , testProperty "Int->Word32" (testIntCastMaybe :: Int -> Word32-> Bool) , testProperty "Int->Word64" (testIntCastMaybe :: Int -> Word64-> Bool) , testProperty "Int->Integer" (testIntCastMaybe :: Int -> Integer-> Bool) , testProperty "Int8->Int" (testIntCastMaybe :: Int8 -> Int-> Bool) , testProperty "Int8->Int8" (testIntCastMaybe :: Int8 -> Int8-> Bool) , testProperty "Int8->Int16" (testIntCastMaybe :: Int8 -> Int16-> Bool) , testProperty "Int8->Int32" (testIntCastMaybe :: Int8 -> Int32-> Bool) , testProperty "Int8->Int64" (testIntCastMaybe :: Int8 -> Int64-> Bool) , testProperty "Int8->Word" (testIntCastMaybe :: Int8 -> Word-> Bool) , testProperty "Int8->Word8" (testIntCastMaybe :: Int8 -> Word8-> Bool) , testProperty "Int8->Word16" (testIntCastMaybe :: Int8 -> Word16-> Bool) , testProperty "Int8->Word32" (testIntCastMaybe :: Int8 -> Word32-> Bool) , testProperty "Int8->Word64" (testIntCastMaybe :: Int8 -> Word64-> Bool) , testProperty "Int8->Integer" (testIntCastMaybe :: Int8 -> Integer-> Bool) , testProperty "Int16->Int" (testIntCastMaybe :: Int16 -> Int-> Bool) , testProperty "Int16->Int8" (testIntCastMaybe :: Int16 -> Int8-> Bool) , testProperty "Int16->Int16" (testIntCastMaybe :: Int16 -> Int16-> Bool) , testProperty "Int16->Int32" (testIntCastMaybe :: Int16 -> Int32-> Bool) , testProperty "Int16->Int64" (testIntCastMaybe :: Int16 -> Int64-> Bool) , testProperty "Int16->Word" (testIntCastMaybe :: Int16 -> Word-> Bool) , testProperty "Int16->Word8" (testIntCastMaybe :: Int16 -> Word8-> Bool) , testProperty "Int16->Word16" (testIntCastMaybe :: Int16 -> Word16-> Bool) , testProperty "Int16->Word32" (testIntCastMaybe :: Int16 -> Word32-> Bool) , testProperty "Int16->Word64" (testIntCastMaybe :: Int16 -> Word64-> Bool) , testProperty "Int16->Integer" (testIntCastMaybe :: Int16 -> Integer-> Bool) , testProperty "Int32->Int" (testIntCastMaybe :: Int32 -> Int-> Bool) , testProperty "Int32->Int8" (testIntCastMaybe :: Int32 -> Int8-> Bool) , testProperty "Int32->Int16" (testIntCastMaybe :: Int32 -> Int16-> Bool) , testProperty "Int32->Int32" (testIntCastMaybe :: Int32 -> Int32-> Bool) , testProperty "Int32->Int64" (testIntCastMaybe :: Int32 -> Int64-> Bool) , testProperty "Int32->Word" (testIntCastMaybe :: Int32 -> Word-> Bool) , testProperty "Int32->Word8" (testIntCastMaybe :: Int32 -> Word8-> Bool) , testProperty "Int32->Word16" (testIntCastMaybe :: Int32 -> Word16-> Bool) , testProperty "Int32->Word32" (testIntCastMaybe :: Int32 -> Word32-> Bool) , testProperty "Int32->Word64" (testIntCastMaybe :: Int32 -> Word64-> Bool) , testProperty "Int32->Integer" (testIntCastMaybe :: Int32 -> Integer-> Bool) , testProperty "Int64->Int" (testIntCastMaybe :: Int64 -> Int-> Bool) , testProperty "Int64->Int8" (testIntCastMaybe :: Int64 -> Int8-> Bool) , testProperty "Int64->Int16" (testIntCastMaybe :: Int64 -> Int16-> Bool) , testProperty "Int64->Int32" (testIntCastMaybe :: Int64 -> Int32-> Bool) , testProperty "Int64->Int64" (testIntCastMaybe :: Int64 -> Int64-> Bool) , testProperty "Int64->Word" (testIntCastMaybe :: Int64 -> Word-> Bool) , testProperty "Int64->Word8" (testIntCastMaybe :: Int64 -> Word8-> Bool) , testProperty "Int64->Word16" (testIntCastMaybe :: Int64 -> Word16-> Bool) , testProperty "Int64->Word32" (testIntCastMaybe :: Int64 -> Word32-> Bool) , testProperty "Int64->Word64" (testIntCastMaybe :: Int64 -> Word64-> Bool) , testProperty "Int64->Integer" (testIntCastMaybe :: Int64 -> Integer-> Bool) , testProperty "Word->Int" (testIntCastMaybe :: Word -> Int-> Bool) , testProperty "Word->Int8" (testIntCastMaybe :: Word -> Int8-> Bool) , testProperty "Word->Int16" (testIntCastMaybe :: Word -> Int16-> Bool) , testProperty "Word->Int32" (testIntCastMaybe :: Word -> Int32-> Bool) , testProperty "Word->Int64" (testIntCastMaybe :: Word -> Int64-> Bool) , testProperty "Word->Word" (testIntCastMaybe :: Word -> Word-> Bool) , testProperty "Word->Word8" (testIntCastMaybe :: Word -> Word8-> Bool) , testProperty "Word->Word16" (testIntCastMaybe :: Word -> Word16-> Bool) , testProperty "Word->Word32" (testIntCastMaybe :: Word -> Word32-> Bool) , testProperty "Word->Word64" (testIntCastMaybe :: Word -> Word64-> Bool) , testProperty "Word->Integer" (testIntCastMaybe :: Word -> Integer-> Bool) , testProperty "Word8->Int" (testIntCastMaybe :: Word8 -> Int-> Bool) , testProperty "Word8->Int8" (testIntCastMaybe :: Word8 -> Int8-> Bool) , testProperty "Word8->Int16" (testIntCastMaybe :: Word8 -> Int16-> Bool) , testProperty "Word8->Int32" (testIntCastMaybe :: Word8 -> Int32-> Bool) , testProperty "Word8->Int64" (testIntCastMaybe :: Word8 -> Int64-> Bool) , testProperty "Word8->Word" (testIntCastMaybe :: Word8 -> Word-> Bool) , testProperty "Word8->Word8" (testIntCastMaybe :: Word8 -> Word8-> Bool) , testProperty "Word8->Word16" (testIntCastMaybe :: Word8 -> Word16-> Bool) , testProperty "Word8->Word32" (testIntCastMaybe :: Word8 -> Word32-> Bool) , testProperty "Word8->Word64" (testIntCastMaybe :: Word8 -> Word64-> Bool) , testProperty "Word8->Integer" (testIntCastMaybe :: Word8 -> Integer-> Bool) , testProperty "Word16->Int" (testIntCastMaybe :: Word16 -> Int-> Bool) , testProperty "Word16->Int8" (testIntCastMaybe :: Word16 -> Int8-> Bool) , testProperty "Word16->Int16" (testIntCastMaybe :: Word16 -> Int16-> Bool) , testProperty "Word16->Int32" (testIntCastMaybe :: Word16 -> Int32-> Bool) , testProperty "Word16->Int64" (testIntCastMaybe :: Word16 -> Int64-> Bool) , testProperty "Word16->Word" (testIntCastMaybe :: Word16 -> Word-> Bool) , testProperty "Word16->Word8" (testIntCastMaybe :: Word16 -> Word8-> Bool) , testProperty "Word16->Word16" (testIntCastMaybe :: Word16 -> Word16-> Bool) , testProperty "Word16->Word32" (testIntCastMaybe :: Word16 -> Word32-> Bool) , testProperty "Word16->Word64" (testIntCastMaybe :: Word16 -> Word64-> Bool) , testProperty "Word16->Integer" (testIntCastMaybe :: Word16 -> Integer-> Bool) , testProperty "Word32->Int" (testIntCastMaybe :: Word32 -> Int-> Bool) , testProperty "Word32->Int8" (testIntCastMaybe :: Word32 -> Int8-> Bool) , testProperty "Word32->Int16" (testIntCastMaybe :: Word32 -> Int16-> Bool) , testProperty "Word32->Int32" (testIntCastMaybe :: Word32 -> Int32-> Bool) , testProperty "Word32->Int64" (testIntCastMaybe :: Word32 -> Int64-> Bool) , testProperty "Word32->Word" (testIntCastMaybe :: Word32 -> Word-> Bool) , testProperty "Word32->Word8" (testIntCastMaybe :: Word32 -> Word8-> Bool) , testProperty "Word32->Word16" (testIntCastMaybe :: Word32 -> Word16-> Bool) , testProperty "Word32->Word32" (testIntCastMaybe :: Word32 -> Word32-> Bool) , testProperty "Word32->Word64" (testIntCastMaybe :: Word32 -> Word64-> Bool) , testProperty "Word32->Integer" (testIntCastMaybe :: Word32 -> Integer-> Bool) , testProperty "Word64->Int" (testIntCastMaybe :: Word64 -> Int-> Bool) , testProperty "Word64->Int8" (testIntCastMaybe :: Word64 -> Int8-> Bool) , testProperty "Word64->Int16" (testIntCastMaybe :: Word64 -> Int16-> Bool) , testProperty "Word64->Int32" (testIntCastMaybe :: Word64 -> Int32-> Bool) , testProperty "Word64->Int64" (testIntCastMaybe :: Word64 -> Int64-> Bool) , testProperty "Word64->Word" (testIntCastMaybe :: Word64 -> Word-> Bool) , testProperty "Word64->Word8" (testIntCastMaybe :: Word64 -> Word8-> Bool) , testProperty "Word64->Word16" (testIntCastMaybe :: Word64 -> Word16-> Bool) , testProperty "Word64->Word32" (testIntCastMaybe :: Word64 -> Word32-> Bool) , testProperty "Word64->Word64" (testIntCastMaybe :: Word64 -> Word64-> Bool) , testProperty "Word64->Integer" (testIntCastMaybe :: Word64 -> Integer-> Bool) , testProperty "Integer->Int" (testIntCastMaybe :: Integer -> Int-> Bool) , testProperty "Integer->Int8" (testIntCastMaybe :: Integer -> Int8-> Bool) , testProperty "Integer->Int16" (testIntCastMaybe :: Integer -> Int16-> Bool) , testProperty "Integer->Int32" (testIntCastMaybe :: Integer -> Int32-> Bool) , testProperty "Integer->Int64" (testIntCastMaybe :: Integer -> Int64-> Bool) , testProperty "Integer->Word" (testIntCastMaybe :: Integer -> Word-> Bool) , testProperty "Integer->Word8" (testIntCastMaybe :: Integer -> Word8-> Bool) , testProperty "Integer->Word16" (testIntCastMaybe :: Integer -> Word16-> Bool) , testProperty "Integer->Word32" (testIntCastMaybe :: Integer -> Word32-> Bool) , testProperty "Integer->Word64" (testIntCastMaybe :: Integer -> Word64-> Bool) , testProperty "Integer->Integer" (testIntCastMaybe :: Integer -> Integer-> Bool) ] main :: IO () main = defaultMain [testGrp_intCastMaybe]
hvr/int-cast
test/Suite.hs
bsd-3-clause
11,262
0
10
2,357
2,918
1,590
1,328
141
1
{-# LANGUAGE NoMonomorphismRestriction #-} -- render example to be polymorphism --{-# LANGUAGE NoMonomorphismRestriction #-} -- render example to be monomorphism module DetermineTheType where -- simple example example = 1
chengzh2008/hpffp
src/ch05-Types2/determineType.hs
bsd-3-clause
225
0
4
32
14
11
3
3
1
{-# LANGUAGE NoMonomorphismRestriction #-} module Language.Hakaru.Tests ( tests ) where import qualified Language.Hakaru.Tests.ImportanceSampler as IS import qualified Language.Hakaru.Tests.Metropolis as MH import Distribution.TestSuite import Distribution.TestSuite.QuickCheck qtest = testProperty "Chunky monkey" True tests :: IO [Test] tests = return [ qtest ]
zaxtax/hakaru-old
Language/Hakaru/Tests.hs
bsd-3-clause
368
0
6
44
76
49
27
9
1
module Text.Config.Parser ( loadConfigTmp , confTmpParser ) where import Text.Parsec import Text.Parsec.ByteString import Control.Applicative hiding (many, (<|>)) import qualified Data.ByteString.Char8 as BC import Text.Config.Lib import Text.Config.Types loadConfigTmp :: String -> IO ConfTmp loadConfigTmp filepath = do str <- readFile filepath return $ confTmpParser str confTmpParser :: String -> ConfTmp confTmpParser str = case parse confTmp "" (BC.pack str) of Left err -> error $ show err Right conf -> conf confTmp :: Parser ConfTmp confTmp = (,) <$> (commentLines *> key <* spcs <* commentLines) <*> confLines confLines :: Parser [ConfLine] confLines = commentLines *> many1 confLine <* eof confLine :: Parser ConfLine confLine = (,) <$> (spcs1 *> key <* spcs1) <*> (confType <* spcs <* commentLines) confType :: Parser ConfType confType = choice [typeByteString, typeString, typeUri, typeInt, typeList] where typeString = string "String" *> return ConfString typeUri = string "URI" *> return ConfURI typeInt = string "Int" *> return ConfInt typeByteString = string "ByteString" *> return ConfByteString typeList = ConfList <$> (char '[' *> confType) <* char ']'
yunomu/simple-config
Text/Config/Parser.hs
bsd-3-clause
1,262
0
11
259
395
210
185
35
2
{-# LANGUAGE OverloadedStrings #-} -------------------------------------------------------------------- -- | -- Module : Text.Atom.Feed.Validate -- Copyright : (c) Galois, Inc. 2008 -- License : BSD3 -- -- Maintainer: Sigbjorn Finne <[email protected]> -- Stability : provisional -- Portability: -- -------------------------------------------------------------------- module Text.Atom.Feed.Validate where import Text.Atom.Feed.Import import Text.XML import Text.Feed.Util import Data.List import Data.Maybe data VTree a = VNode [a] [VTree a] | VLeaf [a] deriving (Eq, Show) type ValidatorResult = VTree (Bool,String) advice :: String -> ValidatorResult advice s = VLeaf [(False,s)] demand :: String -> ValidatorResult demand s = VLeaf [(True,s)] valid :: ValidatorResult valid = VLeaf [] mkTree :: [(Bool,String)] -> [ValidatorResult] -> ValidatorResult mkTree as bs = VNode as bs flattenT :: VTree a -> [a] flattenT (VLeaf xs) = xs flattenT (VNode as bs) = as ++ concatMap flattenT bs validateEntry :: Element -> ValidatorResult validateEntry e = mkTree [] [ checkEntryAuthor e , checkCats e , checkContents e , checkContributor e , checkId e , checkContentLink e , checkLinks e , checkPublished e , checkRights e , checkSource e , checkSummary e , checkTitle e , checkUpdated e ] -- Sec 4.1.2, check #1 checkEntryAuthor :: Element -> ValidatorResult checkEntryAuthor e = case pNodes "author" (elementChildren e) of [] -> -- required case pNode "summary" (elementChildren e) of Nothing -> demand "Required 'author' element missing (no 'summary' either)" Just e1 -> case pNode "author" (elementChildren e1) of Just a -> checkAuthor a _ -> demand "Required 'author' element missing" xs -> mkTree [] $ map checkAuthor xs -- Sec 4.1.2, check #2 checkCats :: Element -> ValidatorResult checkCats e = mkTree [] $ map checkCat (pNodes "category" (elementChildren e)) checkContents :: Element -> ValidatorResult checkContents e = case pNodes "content" (elementChildren e) of [] -> valid [c] -> mkTree [] $ [checkContent c] cs -> mkTree (flattenT (demand ("at most one 'content' element expected inside 'entry', found: " ++ show (length cs)))) (map checkContent cs) checkContributor :: Element -> ValidatorResult checkContributor _e = valid checkContentLink :: Element -> ValidatorResult checkContentLink e = case pNodes "content" (elementChildren e) of [] -> case pNodes "link" (elementChildren e) of [] -> demand ("An 'entry' element with no 'content' element must have at least one 'link-rel' element") xs -> case filter (=="alternate") $ mapMaybe (pAttr "rel") xs of [] -> demand ("An 'entry' element with no 'content' element must have at least one 'link-rel' element") _ -> valid _ -> valid checkLinks :: Element -> ValidatorResult checkLinks e = case pNodes "link" (elementChildren e) of xs -> case map fst $ filter (\ (_,n) -> n =="alternate") $ mapMaybe (\ ex -> fmap (\x -> (ex,x)) $ pAttr "rel" ex) xs of xs1 -> let jmb (Just x) (Just y) = Just (x,y) jmb _ _ = Nothing in case mapMaybe (\ ex -> pAttr "type" ex `jmb` pAttr "hreflang" ex) xs1 of xs2 -> case any (\ x -> length x > 1) (group xs2) of True -> demand ("An 'entry' element cannot have duplicate 'link-rel-alternate-type-hreflang' elements") _ -> valid checkId :: Element -> ValidatorResult checkId e = case pNodes "id" (elementChildren e) of [] -> demand "required field 'id' missing from 'entry' element" [_] -> valid xs -> demand ("only one 'id' field expected in 'entry' element, found: " ++ show (length xs)) checkPublished :: Element -> ValidatorResult checkPublished e = case pNodes "published" (elementChildren e) of [] -> valid [_] -> valid xs -> demand ("expected at most one 'published' field in 'entry' element, found: " ++ show (length xs)) checkRights :: Element -> ValidatorResult checkRights e = case pNodes "rights" (elementChildren e) of [] -> valid [_] -> valid xs -> demand ("expected at most one 'rights' field in 'entry' element, found: " ++ show (length xs)) checkSource :: Element -> ValidatorResult checkSource e = case pNodes "source" (elementChildren e) of [] -> valid [_] -> valid xs -> demand ("expected at most one 'source' field in 'entry' element, found: " ++ show (length xs)) checkSummary :: Element -> ValidatorResult checkSummary e = case pNodes "summary" (elementChildren e) of [] -> valid [_] -> valid xs -> demand ("expected at most one 'summary' field in 'entry' element, found: " ++ show (length xs)) checkTitle :: Element -> ValidatorResult checkTitle e = case pNodes "title" (elementChildren e) of [] -> demand "required field 'title' missing from 'entry' element" [_] -> valid xs -> demand ("only one 'title' field expected in 'entry' element, found: " ++ show (length xs)) checkUpdated :: Element -> ValidatorResult checkUpdated e = case pNodes "updated" (elementChildren e) of [] -> demand "required field 'updated' missing from 'entry' element" [_] -> valid xs -> demand ("only one 'updated' field expected in 'entry' element, found: " ++ show (length xs)) checkCat :: Element -> ValidatorResult checkCat e = mkTree [] [ checkTerm e , checkScheme e , checkLabel e ] where checkScheme e' = case pAttrs "scheme" e' of [] -> valid (_:xs) | null xs -> valid | otherwise -> demand ("Expected at most one 'scheme' attribute, found: " ++ show (1+length xs)) checkLabel e' = case pAttrs "label" e' of [] -> valid (_:xs) | null xs -> valid | otherwise -> demand ("Expected at most one 'label' attribute, found: " ++ show (1+length xs)) checkContent :: Element -> ValidatorResult checkContent e = mkTree (flattenT (mkTree [] [type_valid, src_valid])) [case ty of "text" -> case onlyElems (elementNodes e) of [] -> valid _ -> demand ("content with type 'text' cannot have child elements, text only.") "html" -> case onlyElems (elementNodes e) of [] -> valid _ -> demand ("content with type 'html' cannot have child elements, text only.") "xhtml" -> case onlyElems (elementNodes e) of [] -> valid [_] -> valid -- ToDo: check that it is a 'div'. _ds -> demand ("content with type 'xhtml' should only contain one 'div' child.") _ -> valid] {- case parseMIMEType ty of Nothing -> valid Just mt | isXmlType mt -> valid | otherwise -> case onlyElems (elementNodes e) of [] -> valid -- check _ -> demand ("content with MIME type '" ++ ty ++ "' must only contain base64 data")] -} where types = pAttrs "type" e (ty, type_valid) = case types of [] -> ("text", valid) [t] -> checkTypeA t (t:ts) -> (t, demand ("Expected at most one 'type' attribute, found: " ++ show (1+length ts))) src_valid = case pAttrs "src" e of [] -> valid [_] -> case types of [] -> advice "It is advisable to provide a 'type' along with a 'src' attribute" (_:_) -> valid {- case parseMIMEType t of Just{} -> valid _ -> demand "The 'type' attribute must be a valid MIME type" -} ss -> demand ("Expected at most one 'src' attribute, found: " ++ show (length ss)) checkTypeA v | v `elem` std_types = (v, valid) | otherwise = (v,valid) {- case parseMIMEType v of Nothing -> ("text", demand ("Invalid/unknown type value " ++ v)) Just mt -> case mimeType mt of Multipart{} -> ("text", demand "Multipart MIME types not a legal 'type'") _ -> (v, valid) -} where std_types = [ "text", "xhtml", "html"] checkTerm :: Element -> ValidatorResult checkTerm e = case pNodes "term" (elementChildren e) of [] -> demand "required field 'term' missing from 'category' element" [_] -> valid xs -> demand ("only one 'term' field expected in 'category' element, found: " ++ show (length xs)) checkAuthor :: Element -> ValidatorResult checkAuthor e = checkPerson e checkPerson :: Element -> ValidatorResult checkPerson e = mkTree (flattenT $ checkName e) [ checkEmail e , checkUri e ] checkName :: Element -> ValidatorResult checkName e = case pNodes "name" (elementChildren e) of [] -> demand "required field 'name' missing from 'author' element" [_] -> valid xs -> demand ("only one 'name' expected in 'author' element, found: " ++ show (length xs)) checkEmail :: Element -> ValidatorResult checkEmail e = case pNodes "email" (elementChildren e) of [] -> valid (_:xs) | null xs -> valid | otherwise -> demand ("at most one 'email' expected in 'author' element, found: " ++ show (1+length xs)) checkUri :: Element -> ValidatorResult checkUri e = case pNodes "email" (elementChildren e) of [] -> valid (_:xs) | null xs -> valid | otherwise -> demand ("at most one 'uri' expected in 'author' element, found: " ++ show (1+length xs))
haskell-pkg-janitors/feed
Text/Atom/Feed/Validate.hs
bsd-3-clause
9,317
21
22
2,324
2,552
1,312
1,240
212
13
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} -- | This module communicates and manages the state of clients -- connected to the server. module Hulk.Client where import Hulk.Auth import Hulk.Types import Control.Applicative import Control.Monad.RWS hiding (pass) import Data.CaseInsensitive (mk) import Data.Char import Data.List import Data.List.Split import Data.Map (Map) import qualified Data.Map as M import Data.Maybe import qualified Data.Set as S import Data.Text (Text, pack) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8,encodeUtf8) import Data.Time hiding (readTime) import Network.FastIRC (Command (..), CommandArg, Message (..), UserSpec(..)) import qualified Network.FastIRC as IRC import Prelude hiding (log) -------------------------------------------------------------------------------- -- * Top-level dispatchers -- | Run the client monad. handleCommand :: Config -- ^ Server configuration. -> HulkState -- ^ Server state. -> UTCTime -- ^ Current time. -> Conn -- ^ Current client connection. -> (String,String) -- ^ Authorization info. -> Command -- ^ The command. -> ((), HulkState, [HulkWriter]) -- ^ The new transformed state and any instructions. handleCommand config state' now conn auth cmd = do runRWS (runHulk (handleCmd cmd)) (HulkReader now conn config Nothing auth) state' -- | Handle an incoming command. handleCmd :: Command -- ^ A command which shouldn't be logged (e.g. PASS). -> Hulk () handleCmd cmd = do case cmd of PassCmd (decodeUtf8 -> pass) -> do incoming cmd asUnregistered $ handlePass pass StringCmd "PINGPONG" _ -> do incoming cmd handlePingPong _ -> handleMsgSafeToLog cmd -- | Handle commands that are safe to log. handleMsgSafeToLog :: Command -- ^ A command which is safe to log -- (PONG, NICK, etc.). -> Hulk () handleMsgSafeToLog cmd = do incoming cmd updateLastPong case cmd of PongCmd{} -> handlePong NickCmd (decodeUtf8 -> nick) _ -> handleNick nick PingCmd (decodeUtf8 -> param) _ -> handlePing param UserCmd (decodeUtf8 -> user) _ _ (decodeUtf8 -> realname) -> asUnregistered $ handleUser user realname QuitCmd mmsg -> handleQuit RequestedQuit (maybe "Quit (no message given)" decodeUtf8 mmsg) StringCmd "DISCONNECT" _ -> handleQuit SocketQuit "Connection lost." _ -> handleMsgReg'd cmd -- | Handle commands that can only be used when registered. handleMsgReg'd :: Command -- ^ A command that users use after -- registration (e.g. JOIN, PART, etc.). -> Hulk () handleMsgReg'd cmd = asRegistered $ case cmd of JoinCmd names -> mapM_ handleJoin (map decodeUtf8 (M.keys names)) PartCmd names mmsg -> mapM_ (flip handlePart (maybe "" decodeUtf8 mmsg)) (map decodeUtf8 (S.toList names)) PrivMsgCmd targets msg -> mapM_ (flip handlePrivmsg (decodeUtf8 msg)) (map decodeUtf8 (S.toList targets)) TopicCmd chan (fmap decodeUtf8 -> Just topic) -> handleTopic (decodeUtf8 chan) topic NoticeCmd targets msg -> mapM_ (flip handleNotice (decodeUtf8 msg)) (map decodeUtf8 (S.toList targets)) -- TODO: Try to get these messages into the fastirc library. StringCmd "AWAY" (listToMaybe -> mmsg) -> handleAway (fmap decodeUtf8 mmsg) StringCmd "WHOIS" [nick] -> handleWhoIs (decodeUtf8 nick) StringCmd "ISON" people -> handleIsOn (map decodeUtf8 people) StringCmd "NAMES" [chan] -> handleNames (decodeUtf8 chan) _ -> invalidCmd cmd -- | Log an invalid cmd. invalidCmd :: Command -- ^ The given command that we don't know how to handle. -> Hulk () invalidCmd cmd = do errorReply $ "Invalid or unknown message type, or not" <> " enough parameters: " <> decodeUtf8 (IRC.showCommand cmd) -------------------------------------------------------------------------------- -- * Command handlers -- | Handle the AWAY command. handleAway :: Maybe Text -> Hulk () handleAway mmsg = do ref <- getRef let adjust client@Client{..} = client { clientAwayMsg = mmsg } modifyClients $ M.adjust adjust ref -- | Handle the PONG command. This updates the user's “last seen” -- value on file. handlePong :: Hulk () handlePong = do now <- asks readTime withRegistered $ \RegUser{regUserUser=user} -> do tell [UpdateUserData UserData { userDataUser = user , userDataLastSeen = now }] -- | Handle the PINGPONG event. Disconnect the client if timedout. handlePingPong :: Hulk () handlePingPong = do lastPong <- clientLastPong <$> getClient now <- asks readTime let n = diffUTCTime now lastPong if n > 60*4 then handleQuit RequestedQuit $ "Ping timeout: " <> pack (show n) <> " seconds" else do hostname <- asks (connServerName . readConn) thisCmdReply RPL_PING [hostname] -- | Handle the PASS message. handlePass :: Text -> Hulk () handlePass pass = do modifyUnregistered $ \u -> u { unregUserPass = Just pass } notice "Received password." tryRegister -- | Handle the USER message. handleUser :: Text -> Text -> Hulk () handleUser user realname = do withSentPass $ if validUser user then do modifyUnregistered $ \u -> u { unregUserUser = Just (UserName (mk user)) , unregUserName = Just realname } notice "Recieved user details." tryRegister else errorReply "Invalid user format." -- | Handle the USER message. handleNick :: Text -> Hulk () handleNick nick' = withSentPass $ withValidNick nick' $ \nick -> ifNotMyNick nick $ ifUniqueNick nick (updateNickAndTryRegistration nick) Nothing where updateNickAndTryRegistration nick = do ref <- getRef withRegistered $ \RegUser{regUserNick=rnick} -> modifyNicks $ M.delete rnick withUnregistered $ \UnregUser{unregUserNick=rnick} -> maybe (return ()) (modifyNicks . M.delete) rnick modifyNicks $ M.insert nick ref modifyUnregistered $ \u -> u { unregUserNick = Just nick } tryRegister asRegistered $ do thisClientReply RPL_NICK [nickText nick] (myChannels >>=) $ mapM_ $ \Channel{..} -> do channelReply channelName RPL_NICK [nickText nick] ExcludeMe modifyRegistered $ \u -> u { regUserNick = nick } -- | Handle the PING message. handlePing :: Text -> Hulk () handlePing p = do hostname <- asks (connServerName . readConn) thisServerReply RPL_PONG [hostname,p] -- | Handle the QUIT message. handleQuit :: QuitType -> Text -> Hulk () handleQuit quitType msg = do clearQuittedUser msg when (quitType == RequestedQuit) $ tell [Close] -- | Handle the TELL message. handleTell :: Text -> Text -> Hulk () handleTell name msg = sendMsgTo RPL_NOTICE name msg -- | Handle the NAMES list request. handleNames :: Text -> Hulk () handleNames chan = do withValidChanName chan sendNamesList -- | Handle the JOIN message. handleJoin :: Text -> Hulk () handleJoin chans = do let names = T.split (==',') chans forM_ names $ flip withValidChanName $ \name -> do exists <- M.member name <$> gets stateChannels unless exists $ insertChannel name joined <- inChannel name unless joined $ joinChannel name -- | Handle the PART message. handlePart :: Text -> Text -> Hulk () handlePart name msg = withValidChanName name $ \vname -> do removeFromChan vname channelReply vname RPL_PART [msg] IncludeMe -- | Handle the TOPIC message. handleTopic :: Text -> Text -> Hulk () handleTopic name' topic = withValidChanName name' $ \name -> do let setTopic c = c { channelTopic = Just topic } modifyChannels $ M.adjust setTopic name channelReply name RPL_TOPIC [channelNameText name,topic] IncludeMe -- | Handle the PRIVMSG message. handlePrivmsg :: Text -> Text -> Hulk () handlePrivmsg name msg = do sendMsgTo RPL_PRIVMSG name msg historyLog RPL_PRIVMSG [name,msg] -- | Handle the NOTICE message. handleNotice :: Text -> Text -> Hulk () handleNotice name msg = sendMsgTo RPL_NOTICE name msg -- | Handle WHOIS message. handleWhoIs :: Text -> Hulk () handleWhoIs nick' = withValidNick nick' $ \nick -> withClientByNick nick $ \Client{..} -> withRegUserByNick nick $ \RegUser{..} -> do thisNickServerReply RPL_WHOISUSER [nickText regUserNick ,userText regUserUser ,clientHostname ,"*" ,regUserName] thisNickServerReply RPL_ENDOFWHOIS [nickText regUserNick ,"End of WHOIS list."] -- | Handle the ISON ('is on?') message. handleIsOn :: [Text] -> Hulk () handleIsOn (catMaybes . map readNick -> nicks') = asRegistered $ do online <- catMaybes <$> mapM regUserByNick nicks' let nicks = T.unwords $ map (nickText.regUserNick) online unless (T.null nicks) $ thisNickServerReply RPL_ISON [nicks <> " "] -------------------------------------------------------------------------------- -- * General actions -- | Send a message to a user or a channel (it figures it out). sendMsgTo :: RPL -> Text -> Text -> Hulk () sendMsgTo typ name' msg = if validChannel name' then withValidChanName name' $ \name -> channelReply name typ [channelNameText name,msg] ExcludeMe else userReply name' typ [name',msg] -------------------------------------------------------------------------------- -- * Users -- | Is a username valid? validUser :: Text -> Bool validUser = validNick -- | Get the username. getUsername :: Hulk (Maybe UserName) getUsername = do user <- getUser return $ case user of Unregistered (UnregUser{unregUserUser=username}) -> username Registered (RegUser{regUserUser=username}) -> Just username -- | Get the current connection ref. getRef :: Hulk Ref getRef = connRef <$> asks readConn -- | Bump off the given nick. bumpOff :: Nick -> Hulk () bumpOff nick = ifNotMyNick nick $ do notice $ "Bumping off user " <> nickText nick <> "…" withClientByNick nick $ \Client{clientRef=ref} -> local (\r -> r { readConn = (readConn r) { connRef = ref } }) $ do clearQuittedUser msg tell [Bump ref] where msg = "Bumped off." -- | Clear a quitted user from channels and nick list, and notify -- people in channels of their leaving. clearQuittedUser :: Text -> Hulk () clearQuittedUser msg = do (myChannels >>=) $ mapM_ $ \Channel{..} -> do channelReply channelName RPL_QUIT [msg] ExcludeMe removeFromChan channelName withRegistered $ \RegUser{regUserNick=nick} -> do modifyNicks $ M.delete nick withUnregistered $ \UnregUser{unregUserNick=nick} -> do maybe (return ()) (modifyNicks . M.delete) nick ref <- getRef modifyClients $ M.delete ref notice msg -- | Update the last pong reply time. updateLastPong :: Hulk () updateLastPong = do ref <- getRef now <- asks readTime let adjust client@Client{..} = client { clientLastPong = now } modifyClients $ M.adjust adjust ref -- | Send a client reply to a user. userReply :: Text -> RPL -> [Text] -> Hulk () userReply nick' typ ps = withValidNick nick' $ \nick -> withClientByNick nick $ \Client{..} -> clientReply clientRef typ ps -- | Perform an action with a registered user by its nickname. withRegUserByNick :: Nick -> (RegUser -> Hulk ()) -> Hulk () withRegUserByNick nick m = do user <- regUserByNick nick case user of Just user' -> m user' Nothing -> sendNoSuchNick nick -- | Send the RPL_NOSUCHNICK reply. sendNoSuchNick :: Nick -> Hulk () sendNoSuchNick nick = thisServerReply ERR_NOSUCHNICK [nickText nick,"No such nick."] -- | Modify the current user. modifyUser :: (User -> User) -> Hulk () modifyUser f = do ref <- getRef let modUser c = c { clientUser = f (clientUser c) } modClient = M.adjust modUser ref modify $ \env -> env { stateClients = modClient (stateClients env) } -- | Get the current client's user. getUser :: Hulk User getUser = clientUser <$> getClient -------------------------------------------------------------------------------- -- * Clients -- | Get the current client. getClientByRef :: Ref -> Hulk (Maybe Client) getClientByRef ref = do clients <- gets stateClients return $ M.lookup ref clients -- | Get a client by nickname. clientByNick :: Nick -> Hulk (Maybe Client) clientByNick nick = do clients <- gets stateClients (M.lookup nick >=> (`M.lookup` clients)) <$> gets stateNicks -- | Perform an action with a client by nickname. withClientByNick :: Nick -> (Client -> Hulk ()) -> Hulk () withClientByNick nick m = do client' <- clientByNick nick case client' of Nothing -> sendNoSuchNick nick Just client@Client{..} | isRegistered clientUser -> m client | otherwise -> sendNoSuchNick nick -- | Get the current client. getClient :: Hulk Client getClient = do ref <- getRef clients <- gets stateClients case M.lookup ref clients of Just client -> return $ client Nothing -> makeNewClient -- | Modify the clients table. modifyClients :: (Map Ref Client -> Map Ref Client) -> Hulk () modifyClients f = modify $ \env -> env { stateClients = f (stateClients env) } -- | Make a current client based on the current connection. makeNewClient :: Hulk Client makeNewClient = do Conn{..} <- asks readConn let client = Client { clientRef = connRef , clientHostname = connHostname , clientUser = newUnregisteredUser , clientLastPong = connTime , clientAwayMsg = Nothing } modifyClients $ M.insert connRef client return client -------------------------------------------------------------------------------- -- * Registration -- | Get a registered user by nickname. regUserByNick :: Nick -> Hulk (Maybe RegUser) regUserByNick nick = do c <- clientByNick nick case clientUser <$> c of Just (Registered u) -> return $ Just u _ -> return Nothing -- | Maybe get a registered user from a client. clientRegUser :: Client -> Maybe RegUser clientRegUser Client{..} = case clientUser of Registered u -> Just u _ -> Nothing -- | Modify the current user if unregistered. modifyUnregistered :: (UnregUser -> UnregUser) -> Hulk () modifyUnregistered f = do modifyUser $ \user -> case user of Unregistered user' -> Unregistered (f user') u -> u -- | Modify the current user if registered. modifyRegistered :: (RegUser -> RegUser) -> Hulk () modifyRegistered f = do modifyUser $ \user -> case user of Registered user' -> Registered (f user') u -> u -- | Only perform command if the client is registered. asRegistered :: Hulk () -> Hulk () asRegistered m = do registered <- isRegistered <$> getUser when registered m -- | Perform command with a registered user. withRegistered :: (RegUser -> Hulk ()) -> Hulk () withRegistered m = do user <- getUser case user of Registered user' -> m user' _ -> return () -- | With sent pass. withSentPass :: Hulk () -> Hulk () withSentPass m = do asRegistered m withUnregistered $ \UnregUser{..} -> do case unregUserPass of Just{} -> m Nothing -> return () -- | Perform command with a registered user. withUnregistered :: (UnregUser -> Hulk ()) -> Hulk () withUnregistered m = do user <- getUser case user of Unregistered user' -> m user' _ -> return () -- | Only perform command if the client is registered. asUnregistered :: Hulk () -> Hulk () asUnregistered m = do registered <- isRegistered <$> getUser unless registered m -- | Is a user registered? isRegistered :: User -> Bool isRegistered Registered{} = True isRegistered _ = False -- | Make a new unregistered user. newUnregisteredUser :: User newUnregisteredUser = Unregistered $ UnregUser { unregUserName = Nothing ,unregUserNick = Nothing ,unregUserUser = Nothing ,unregUserPass = Nothing } -- | Try to register the user with the USER/NICK/PASS that have been given. tryRegister :: Hulk () tryRegister = withUnregistered $ \unreg -> do check <- isAuthentic unreg case check of (True,Just (name,user,nick)) -> do modifyUser $ \_ -> Registered $ RegUser name nick user "" sendWelcome sendMotd sendEvents (False,Just{}) -> errorReply $ "Wrong user/pass." _ -> return () isAuthentic :: UnregUser -> Hulk (Bool,Maybe (Text,UserName,Nick)) isAuthentic UnregUser{..} = do let details = (,,,) <$> unregUserName <*> unregUserNick <*> unregUserUser <*> unregUserPass case details of Nothing -> return (False,Nothing) Just (name,nick,user,pass) -> do (keystr,passwords) <- asks readAuth let authentic = authenticate keystr passwords (userText user) pass return (authentic,Just (name,user,nick)) -------------------------------------------------------------------------------- -- * Nicknames -- | Read a valid nick. readNick :: Text -> Maybe Nick readNick n | validNick n = Just $ NickName (mk n) | otherwise = Nothing -- | Modify the nicks mapping. modifyNicks :: (Map Nick Ref -> Map Nick Ref) -> Hulk () modifyNicks f = modify $ \env -> env { stateNicks = f (stateNicks env) } -- | With a valid nickname, perform an action. withValidNick :: Text -> (Nick -> Hulk ()) -> Hulk () withValidNick nick m | validNick nick = m (NickName (mk nick)) | otherwise = errorReply $ "Invalid nick format: " <> nick -- | Perform an action if a nickname is unique, otherwise send error. ifUniqueNick :: Nick -> Hulk () -> Maybe ((Text -> Hulk ()) -> Hulk ()) -> Hulk () ifUniqueNick nick then_m else_m = do clients <- gets stateClients client <- (M.lookup nick >=> (`M.lookup` clients)) <$> gets stateNicks case client of Nothing -> then_m Just{} -> do case else_m of Just else_m' -> else_m' error_reply Nothing -> error_reply "" where error_reply x = thisServerReply ERR_NICKNAMEINUSE [nickText nick,"Nick is already in use." <> x] -- | Is a nickname valid? Digit/letter or one of these: -_/\\;()[]{}?`' validNick :: Text -> Bool validNick s = T.all ok s && T.length s > 0 where ok c = isDigit c || isLetter c || elem c "-_/\\;()[]{}?`'" -- | If the given nick is not my nick name, …. ifNotMyNick :: Nick -> Hulk () -> Hulk () ifNotMyNick nick m = do user <- getUser case user of Registered RegUser{..} | regUserNick /= nick -> m Unregistered UnregUser{..} | unregUserNick /= Just nick -> m _ -> return () -------------------------------------------------------------------------------- -- * Channels -- | Valid channel name? validChannel :: Text -> Bool validChannel (T.uncons -> Just ('#',cs)) = T.all ok cs && T.length cs > 0 where ok c = isDigit c || isLetter c || elem c "-_/\\;()[]{}?`'" validChannel _ = False -- | Remove a user from a channel. removeFromChan :: ChannelName -> Hulk () removeFromChan name = do ref <- getRef let remMe c = c { channelUsers = S.delete ref (channelUsers c) } modifyChannels $ M.adjust remMe name -- | Get channels that the current client is in. myChannels :: Hulk [Channel] myChannels = do ref <- getRef filter (S.member ref . channelUsers) . map snd . M.toList <$> gets stateChannels -- | Join a channel. joinChannel :: ChannelName -> Hulk () joinChannel name = do ref <- getRef let addMe c = c { channelUsers = S.insert ref (channelUsers c) } modifyChannels $ M.adjust addMe name channelReply name RPL_JOIN [channelNameText name] IncludeMe sendNamesList name withChannel name $ \Channel{..} -> do case channelTopic of Just topic -> thisServerReply RPL_TOPIC [channelNameText name,topic] Nothing -> return () -- | Send the names list of a channel. sendNamesList :: ChannelName -> Hulk () sendNamesList name = do asRegistered $ withChannel name $ \Channel{..} -> do clients <- catMaybes <$> mapM getClientByRef (S.toList channelUsers) let nicks = map regUserNick . catMaybes . map clientRegUser $ clients forM_ (chunksOf 10 nicks) $ \nicks' -> thisNickServerReply RPL_NAMEREPLY ["@",channelNameText name ,T.unwords $ map nickText nicks'] thisNickServerReply RPL_ENDOFNAMES [channelNameText name ,"End of /NAMES list."] -- | Am I in a channel? inChannel :: ChannelName -> Hulk Bool inChannel name = do chan <- M.lookup name <$> gets stateChannels case chan of Nothing -> return False Just Channel{..} -> (`S.member` channelUsers) <$> getRef -- | Insert a new channel. insertChannel :: ChannelName -> Hulk () insertChannel name = modifyChannels $ M.insert name newChan where newChan = Channel { channelName = name , channelTopic = Nothing , channelUsers = S.empty } -- | Modify the channel map. modifyChannels :: (Map ChannelName Channel -> Map ChannelName Channel) -> Hulk () modifyChannels f = modify $ \e -> e { stateChannels = f (stateChannels e) } withValidChanName :: Text -> (ChannelName -> Hulk ()) -> Hulk () withValidChanName name m | validChannel name = m $ ChannelName (mk name) | otherwise = errorReply $ "Invalid channel name: " <> name -- | Perform an action with an existing channel, sends error if not exists. withChannel :: ChannelName -> (Channel -> Hulk ()) -> Hulk () withChannel name m = do chan <- M.lookup name <$> gets stateChannels case chan of Nothing -> thisServerReply ERR_NOSUCHCHANNEL [channelNameText name ,"No such channel."] Just chan' -> m chan' -- | Send a client reply to everyone in a channel. channelReply :: ChannelName -> RPL -> [Text] -> ChannelReplyType -> Hulk () channelReply name cmd params typ = do withChannel name $ \Channel{..} -> do ref <- getRef forM_ (S.toList channelUsers) $ \theirRef -> do unless (typ == ExcludeMe && ref == theirRef) $ clientReply theirRef cmd params -------------------------------------------------------------------------------- -- * Client replies -- | Send a client reply to the current client. thisClientReply :: RPL -> [Text] -> Hulk () thisClientReply typ params = do ref <- getRef clientReply ref typ params -- | Send a client reply of the given type with the given params, on -- the given connection reference. clientReply :: Ref -> RPL -> [Text] -> Hulk () clientReply ref typ params = do withRegistered $ \user -> do client <- getClient msg <- newClientMsg client user typ params reply ref msg -- | Make a new IRC message from the current client. newClientMsg :: Client -> RegUser -> RPL -> [Text] -> Hulk Message newClientMsg Client{..} RegUser{..} cmd ps = do return (Message (Just (User (encodeUtf8 (nickText regUserNick)) (encodeUtf8 (userText regUserUser)) (encodeUtf8 clientHostname))) (makeCommand cmd ps)) -------------------------------------------------------------------------------- -- * Server replies -- | Send the welcome message. sendWelcome :: Hulk () sendWelcome = do withRegistered $ \RegUser{..} -> do thisNickServerReply RPL_WELCOME ["Welcome."] -- | Send the MOTD. sendMotd :: Hulk () sendMotd = do asRegistered $ do thisNickServerReply RPL_MOTDSTART ["MOTD"] motd <- fmap (fmap T.lines) (asks readMotd) let motdLine line = thisNickServerReply RPL_MOTD [line] case motd of Nothing -> motdLine "None." Just lines' -> mapM_ motdLine lines' thisNickServerReply RPL_ENDOFMOTD ["/MOTD."] -- | Send events that the user missed. sendEvents :: Hulk () sendEvents = do chans <- configLogChans <$> asks readConfig unless (null chans) $ do withRegistered $ \RegUser{regUserUser=user} -> do ref <- getRef forM_ chans handleJoin tell [SendEvents ref user] -------------------------------------------------------------------------------- -- * Output functions -- | Send a message reply. notice :: Text -> Hulk () notice msg = thisServerReply RPL_NOTICE ["*",msg] thisNickServerReply :: RPL -> [Text] -> Hulk () thisNickServerReply typ params = do withRegistered $ \RegUser{regUserNick=nick} -> thisServerReply typ (nickText nick : params) -- | Send a server reply of the given type with the given params. thisServerReply :: RPL -> [Text] -> Hulk () thisServerReply typ params = do ref <- getRef serverReply ref typ params -- | Send a server reply of the given type with the given params. serverReply :: Ref -> RPL -> [Text] -> Hulk () serverReply ref typ params = do msg <- newServerMsg typ params reply ref msg -- | Make a new IRC message from the server. newServerMsg :: RPL -> [Text] -> Hulk Message newServerMsg cmd ps = do hostname <- asks (connServerName.readConn) return (Message (Just (Nick (encodeUtf8 hostname))) (makeCommand cmd ps)) -- | Send a cmd reply of the given type with the given params. thisCmdReply :: RPL -> [Text] -> Hulk () thisCmdReply typ params = do ref <- getRef cmdReply ref typ params -- | Send a cmd reply of the given type with the given params. cmdReply :: Ref -> RPL -> [Text] -> Hulk () cmdReply ref typ params = do let msg = newCmdMsg typ params reply ref msg -- | Send an error reply. errorReply :: Text -> Hulk () errorReply m = do notice $ "ERROR: " <> m log $ "ERROR: " <> m -- | Send a message reply. reply :: Ref -> Message -> Hulk () reply ref msg = do outgoing msg tell . return $ MessageReply ref msg -- | Log an incoming line. incoming :: Command -> Hulk () incoming = log . ("<- " <>) . decodeUtf8 . IRC.showCommand -- | Log an outgoing line. outgoing :: Message -> Hulk () outgoing msg = do ref <- getRef tell [outgoingWriter ref msg] -- | Log a line. log :: Text -> Hulk () log line = do ref <- getRef tell . return . LogReply $ pack (show (unRef ref)) <> ": " <> line -- | Make a writer reply. outgoingWriter :: Ref -> Message -> HulkWriter outgoingWriter ref = LogReply . (pack (show (unRef ref)) <>) . (": -> " <>) . decodeUtf8 . IRC.showMessage historyLog :: RPL -> [Text] -> Hulk () historyLog rpl params = do chans <- asks (configLogChans . readConfig) unless (null chans) $ do withRegistered $ \RegUser{regUserUser=name} -> do let send = tell [SaveLog (userText name) rpl params] case (rpl,params) of (RPL_PRIVMSG,[chan]) | chan `elem` chans -> send | otherwise -> return () _ -> send -------------------------------------------------------------------------------- -- * Command Construction -- | Make a command. makeCommand :: RPL -> [Text] -> Command makeCommand rpl xs = fromRPL rpl (map encodeUtf8 xs) -- | Convert from a reply to an appropriate protocol format. fromRPL :: RPL -> ([CommandArg] -> Command) fromRPL RPL_NICK = StringCmd "NICK" fromRPL RPL_PONG = StringCmd "PONG" fromRPL RPL_QUIT = StringCmd "QUIT" fromRPL RPL_JOIN = StringCmd "JOIN" fromRPL RPL_NOTICE = StringCmd "NOTICE" fromRPL RPL_PART = StringCmd "PART" fromRPL RPL_PRIVMSG = StringCmd "PRIVMSG" fromRPL RPL_JOINS = StringCmd "JOIN" fromRPL RPL_TOPIC = StringCmd "TOPIC" fromRPL RPL_PING = StringCmd "PING" fromRPL RPL_WHOISUSER = NumericCmd 311 fromRPL RPL_ISON = NumericCmd 303 fromRPL RPL_NAMEREPLY = NumericCmd 353 fromRPL RPL_ENDOFNAMES = NumericCmd 366 fromRPL RPL_WELCOME = NumericCmd 001 fromRPL RPL_MOTDSTART = NumericCmd 375 fromRPL RPL_MOTD = NumericCmd 372 fromRPL RPL_ENDOFMOTD = NumericCmd 376 fromRPL RPL_WHOISIDLE = NumericCmd 317 fromRPL RPL_WHOISCHANNELS = NumericCmd 319 fromRPL RPL_ENDOFWHOIS = NumericCmd 318 fromRPL ERR_NICKNAMEINUSE = NumericCmd 433 fromRPL ERR_NOSUCHNICK = NumericCmd 401 fromRPL ERR_NOSUCHCHANNEL = NumericCmd 403 -- | Make a new IRC message from the cmd. newCmdMsg :: RPL -> [Text] -> Message newCmdMsg cmd ps = Message Nothing (makeCommand cmd ps)
jtojnar/hulk
src/Hulk/Client.hs
bsd-3-clause
29,127
0
21
7,327
8,219
4,079
4,140
621
10
{-# LANGUAGE RankNTypes, ScopedTypeVariables #-} {- | Module : Language.Haskell.TH.Quote Description : Quasi-quoting support for Template Haskell Template Haskell supports quasiquoting, which permits users to construct program fragments by directly writing concrete syntax. A quasiquoter is essentially a function with takes a string to a Template Haskell AST. This module defines the 'QuasiQuoter' datatype, which specifies a quasiquoter @q@ which can be invoked using the syntax @[q| ... string to parse ... |]@ when the @QuasiQuotes@ language extension is enabled, and some utility functions for manipulating quasiquoters. Nota bene: this package does not define any parsers, that is up to you. -} module Language.Haskell.TH.Quote( QuasiQuoter(..), dataToQa, dataToExpQ, dataToPatQ, liftData, quoteFile ) where import Data.Data import Language.Haskell.TH.Lib import Language.Haskell.TH.Syntax -- | The 'QuasiQuoter' type, a value @q@ of this type can be used -- in the syntax @[q| ... string to parse ...|]@. In fact, for -- convenience, a 'QuasiQuoter' actually defines multiple quasiquoters -- to be used in different splice contexts; if you are only interested -- in defining a quasiquoter to be used for expressions, you would -- define a 'QuasiQuoter' with only 'quoteExp', and leave the other -- fields stubbed out with errors. data QuasiQuoter = QuasiQuoter { -- | Quasi-quoter for expressions, invoked by quotes like @lhs = $[q|...]@ quoteExp :: String -> Q Exp, -- | Quasi-quoter for patterns, invoked by quotes like @f $[q|...] = rhs@ quotePat :: String -> Q Pat, -- | Quasi-quoter for types, invoked by quotes like @f :: $[q|...]@ quoteType :: String -> Q Type, -- | Quasi-quoter for declarations, invoked by top-level quotes quoteDec :: String -> Q [Dec] } -- | 'dataToQa' is a generic utility function for constructing generic -- conversion functions from types with 'Data' instances to various -- quasi-quoting representations. It's used by 'dataToExpQ' and -- 'dataToPatQ' dataToQa :: forall a k q. Data a => (Name -> k) -> (Lit -> Q q) -> (k -> [Q q] -> Q q) -> (forall b . Data b => b -> Maybe (Q q)) -> a -> Q q dataToQa mkCon mkLit appCon antiQ t = case antiQ t of Nothing -> case constrRep constr of AlgConstr _ -> appCon (mkCon conName) conArgs where conName :: Name conName = case showConstr constr of "(:)" -> Name (mkOccName ":") (NameG DataName (mkPkgName "ghc-prim") (mkModName "GHC.Types")) con@"[]" -> Name (mkOccName con) (NameG DataName (mkPkgName "ghc-prim") (mkModName "GHC.Types")) con@('(':_) -> Name (mkOccName con) (NameG DataName (mkPkgName "ghc-prim") (mkModName "GHC.Tuple")) con -> mkNameG_d (tyConPackage tycon) (tyConModule tycon) con where tycon :: TyCon tycon = (typeRepTyCon . typeOf) t conArgs :: [Q q] conArgs = gmapQ (dataToQa mkCon mkLit appCon antiQ) t IntConstr n -> mkLit $ integerL n FloatConstr n -> mkLit $ rationalL n CharConstr c -> mkLit $ charL c where constr :: Constr constr = toConstr t Just y -> y -- | 'dataToExpQ' converts a value to a 'Q Exp' representation of the -- same value, in the SYB style. It is generalized to take a function -- override type-specific cases; see 'liftData' for a more commonly -- used variant. dataToExpQ :: Data a => (forall b . Data b => b -> Maybe (Q Exp)) -> a -> Q Exp dataToExpQ = dataToQa conE litE (foldl appE) -- | 'liftData' is a variant of 'lift' in the 'Lift' type class which -- works for any type with a 'Data' instance. liftData :: Data a => a -> Q Exp liftData = dataToExpQ (const Nothing) -- | 'dataToPatQ' converts a value to a 'Q Pat' representation of the same -- value, in the SYB style. It takes a function to handle type-specific cases, -- alternatively, pass @const Nothing@ to get default behavior. dataToPatQ :: Data a => (forall b . Data b => b -> Maybe (Q Pat)) -> a -> Q Pat dataToPatQ = dataToQa id litP conP -- | 'quoteFile' takes a 'QuasiQuoter' and lifts it into one that read -- the data out of a file. For example, suppose 'asmq' is an -- assembly-language quoter, so that you can write [asmq| ld r1, r2 |] -- as an expression. Then if you define @asmq_f = quoteFile asmq@, then -- the quote [asmq_f|foo.s|] will take input from file @"foo.s"@ instead -- of the inline text quoteFile :: QuasiQuoter -> QuasiQuoter quoteFile (QuasiQuoter { quoteExp = qe, quotePat = qp, quoteType = qt, quoteDec = qd }) = QuasiQuoter { quoteExp = get qe, quotePat = get qp, quoteType = get qt, quoteDec = get qd } where get :: (String -> Q a) -> String -> Q a get old_quoter file_name = do { file_cts <- runIO (readFile file_name) ; addDependentFile file_name ; old_quoter file_cts }
fmthoma/ghc
libraries/template-haskell/Language/Haskell/TH/Quote.hs
bsd-3-clause
5,436
0
20
1,623
931
496
435
68
8
module SumLazy where -- main :: IO () -- main = do -- userInput <- getContents -- mapM_ print userInput toInts :: String -> [Int] toInts = map read . lines gojo :: IO () gojo = do userInput <- getContents let numbers = toInts userInput print (mconcat["Ecco la somma dei numeri digitati: ",show (sum numbers)])
stefanocerruti/haskell-primer-alpha
src/SumLazy.hs
bsd-3-clause
332
0
13
78
93
49
44
8
1
{-# LANGUAGE Rank2Types #-} module Generics.Deriving.Data where import Generics.Deriving.Base import Data.Data -------------------------------------------------------------------------------- -- Generic Data -------------------------------------------------------------------------------- {- data T a b = C1 a b | C2 deriving (Typeable, Data) instance (Data a, Data b) => Data (T a b) where gfoldl k z (C1 a b) = z C1 `k` a `k` b gfoldl k z C2 = z C2 gunfold k z c = case constrIndex c of 1 -> k (k (z C1)) 2 -> z C2 -} class Typeable' f where typeOf' :: f a -> TypeRep class {- Typeable' f => -} Data' f where gfoldl' :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> f a -> c (f a) {- gfoldl _ z = z gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c a toConstr :: a -> Constr dataTypeOf :: a -> DataType dataCast1 :: Typeable1 t => (forall d. Data d => c (t d)) -> Maybe (c a) dataCast1 _ = Nothing dataCast2 :: Typeable2 t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c a) dataCast2 _ = Nothing -} instance Data' U1 where gfoldl' k z
ekmett/generic-deriving
src/Generics/Deriving/Data.hs
bsd-3-clause
1,401
1
15
511
150
81
69
-1
-1
module SkeletonTemplates.ZipWithVector where import AstMappings import qualified AbsCAL as C import qualified AbsRIPL as R import Debug.Trace import SkeletonTemplates.CalTypes import Types zipWithVectorActor :: String -> R.TwoVarFun -> Dimension -> Dimension -> C.Type -> C.Type -> C.Type -> C.Actor zipWithVectorActor actorName (R.TwoVarFunC pixelIdent stateIdent exp) (Dimension width height) vecDim@(Dimension vecWidth _) incomingType1 incomingType2 outgoingType = let ioSig = C.IOSg [C.PortDcl inType1 (C.Ident "In1"), C.PortDcl inType2 (C.Ident "In2")] [C.PortDcl outType (C.Ident "Out1")] inType1 = incomingType1 inType2 = incomingType2 outType = outgoingType inputPattern = [ C.InPattTagIds (C.Ident "In1") [idRiplToCal pixelIdent] , C.InPattTagIds (C.Ident "In2") [C.Ident "vectorVal"] ] outputPattern = riplExpToOutputPattern exp actionHead = C.ActnHead inputPattern [outputPattern] actions = [ receiveVectorAction vecWidth height pixelIdent stateIdent , zipStreamAction width height exp pixelIdent , doneAction width height ] in C.ActrSchd (C.PathN [C.PNameCons (C.Ident "cal")]) [] (C.Ident actorName) [] ioSig (globalVars stateIdent vecWidth) actions fsmSchedule [] -- schedule fsm s0 : -- s0 (receiveVector) --> s0; -- s0 (zipStream) --> s1; -- s1 (zipStream) --> s1; -- s1 (done) --> s0; -- end fsmSchedule :: C.ActionSchedule fsmSchedule = C.SchedfsmFSM (C.Ident "s0") [ C.StTrans (C.Ident "s0") (C.Ident "receiveVector") (C.Ident "s0") , C.StTrans (C.Ident "s0") (C.Ident "zipStream") (C.Ident "s1") , C.StTrans (C.Ident "s1") (C.Ident "zipStream") (C.Ident "s1") , C.StTrans (C.Ident "s1") (C.Ident "done") (C.Ident "s0") ] globalVars stateIdent vectorLength = [ C.GlobVarDecl (C.VDeclExpMut (intCalType 16) (idRiplToCal stateIdent) [C.BExp (mkInt vectorLength)] (initVectorState 0 vectorLength)) , C.GlobVarDecl (C.VDeclExpMut (intCalType 32) (C.Ident "count") [] (mkInt 0)) , C.GlobVarDecl (C.VDeclExpMut (intCalType 32) (C.Ident "vectorCount") [] (mkInt 0)) , C.GlobVarDecl (C.VDeclExpMut (intCalType 32) (C.Ident "vectorLength") [] (mkInt vectorLength)) ] -- receiveVector: action In1:[x] ==> -- guard (vectorCount < vectorLength) -- do vectorValue[vectorCount] := x; -- vectorCount := vectorCount + 1; -- end receiveVectorAction width height pixelIdent (R.Ident stateIdent) = C.ActionCode (C.AnActn (C.ActnTagsStmts (C.ActnTagDecl [C.Ident "receiveVector"]) actionHead statements)) where actionHead = C.ActnHeadGuarded [C.InPattTagIds (C.Ident "In2") [idRiplToCal pixelIdent]] [] guardExps statements = [ varSetExpIdxExp (stateIdent) (C.EIdent (idRiplToCal pixelIdent)) [mkVar "vectorCount"] , varIncr "vectorCount" ] guardExps = [C.BrExpCons (C.BELT (mkVar "vectorCount") (mkVar "vectorLength"))] -- statements = [ C.SemiColonSeparatedStmt (C.AssignStt (C.AssStmt (C.Ident "vectorValue") (C.EIdent (C.Ident "x")))) ] -- zipStream: action In2:[p] ==> Out1:[vectorValue[p]] -- guard count < (imageWidth * imageHeight) -- , vectorCount = vectorLength -- do -- count := count + 1; -- end zipStreamAction width height exp pixelIdent = C.ActionCode (C.AnActn (C.ActnTagsStmts (C.ActnTagDecl [C.Ident "zipStream"]) actionHead statements)) where actionHead = C.ActnHeadGuarded [C.InPattTagIds (C.Ident "In1") [idRiplToCal pixelIdent]] [riplExpToOutputPattern exp] guard guard = [ C.BELT (C.EIdent (C.Ident "count")) (mkInt (width * height)) , C.BEEQ (mkVar "vectorCount") (mkVar "vectorLength") ] statements = [varIncr "count"] -- done: action ==> -- guard count = (imageWidth * imageHeight) -- do count := 0; -- vectorCount := 0; -- end doneAction width height = C.ActionCode (C.AnActn (C.ActnTagsStmts (C.ActnTagDecl [C.Ident "done"]) actionHead statements)) where actionHead = C.ActnHeadGuarded [] [] guard guard = [C.BEEQ (C.EIdent (C.Ident "count")) (mkInt (width * height))] statements = [varSetInt "vectorCount" 0, varSetInt "count" 0] initVectorState initValue vectorLength = (C.LstExpCons (C.ListComp (C.ListExpGen [mkInt initValue] (C.GenExpr [ C.GeneratorExpr (mkUIntType 16) (C.Ident "i") (C.BEList (mkInt 0) (mkInt (vectorLength - 1))) ]))))
robstewart57/ripl
src/SkeletonTemplates/ZipWithVector.hs
bsd-3-clause
4,821
0
20
1,249
1,392
721
671
120
1
module AddressSpec where import Ssb.Address import Test.Hspec spec :: Spec spec = describe "address" $ do it "holds the dns or the ip address and the port" $ do let address = Address "localhost" 8008 host address `shouldBe` "localhost" port address `shouldBe` 8008
bkil-syslogng/haskell-scuttlebutt
test/AddressSpec.hs
bsd-3-clause
309
0
14
87
79
40
39
9
1
module BaseMon where import Control.Concurrent import Control.Monad import Frenetic.NetCore import System.IO import Frenetic.Topo import Repeater import Data.Word -- H1 -- | -- S -- / \ -- H2 H3 s = 101 h1 = 1 h2 = 2 h3 = 3 ns = [s,h1,h2,h3] el= [((Frenetic.Topo.Switch 101, 1),(Host 1,0)), ((Frenetic.Topo.Switch 101, 2), (Host 2,0)), ((Frenetic.Topo.Switch 101,3), (Host 3,0))] topo :: Graph topo = buildGraph el -- mkMonitorPolicy :: Policy -> Graph -> IO () mkMonitorPolicy addr fwd g = let monitorCallback ei ( sw, n ) = do putStrLn ("Counter for " ++ show ei ++ " on " ++ show sw ++ " is: " ++ show n) in let p = foldl (\acc h -> (DlDst (ethernetAddress 0 0 0 0 0 (fromIntegral h :: Word8)) ==> [GetPacket 0 (monitorCallback h)]) `PoUnion` acc) PoBottom (hosts g) in controller addr (fwd `PoUnion` p) --myMain :: IO () --myMain = mkMonitorPolicy (OneRes.policy) topo main addr = do mkMonitorPolicy addr (Repeater.policy) topo --main = do -- (c1, query1Act) <- countPkts 1000 -- (c2, query2Act) <- countPkts 1000 -- let monitoringOne = (DlDst (ethernetAddress 0 0 0 0 0 2) <&&> TpSrcPort 80 ==> query1Act) -- let monitoringTwo = (DlDst (ethernetAddress 0 0 0 0 0 3) <&&> TpSrcPort 80 ==> query2Act) -- let monitoringPolicy = PoUnion monitoringOne monitoringTwo -- let forwarding1 = (DlDst (ethernetAddress 0 0 0 0 0 2) ==> forward [1]) -- let forwarding2 = (DlDst (ethernetAddress 0 0 0 0 0 3) ==> forward [2]) -- let forwardingPolicy = PoUnion forwarding1 forwarding2 -- --let pol = (Any ==> allPorts unmodified) `PoUnion` (Any ==> queryAct) -- forkIO $ forever $ do -- (sw, n) <- readChan c1 -- putStrLn ("Web packets to h2: " ++ show n) -- (sw, n) <- readChan c2 -- putStrLn ("Web packets to h3: " ++ show n) -- hFlush stdout -- controller (PoUnion forwardingPolicy monitoringPolicy) --
frenetic-lang/netcore-1.0
examples/BaseMon.hs
bsd-3-clause
1,889
0
19
407
405
235
170
24
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module PeerReview.ReviewRepo.Transaction ( save , findByUserId , findById , findByTaskId , findAll , update ) where import Data.Pool (Pool, withResource) import Database.PostgreSQL.Simple (Connection, Only (..), execute, query, query_) import Database.PostgreSQL.Simple.SqlQQ (sql) import PeerReview.Types -- Save a Peer Review to db. save :: Pool Connection -> PeerReview -> IO PeerReviewID save pool pr = withResource pool (\ conn -> execute conn [sql| INSERT INTO peer_reviews (submission_id, task_id, submission_content, comment, score, reviewer_id, status) VALUES (?,?,?,?,?,?,?) |] pr) -- Find all reviews for given User ID. findByUserId :: Pool Connection -> UserID -> IO [(PeerReviewID,PeerReview)] findByUserId pool uid = withResource pool (\ conn -> do reviews <- query conn [sql| SELECT id, submission_id, task_id, submission_content, comment, score, reviewer_id, status FROM peer_reviews WHERE reviewer_id = ? |] $ Only uid return $ fmap rowToPair reviews ) -- Find peer review by id. findById :: Pool Connection -> PeerReviewID -> IO (Maybe (PeerReviewID,PeerReview)) findById pool rid = withResource pool (\ conn -> do review <- query conn [sql| SELECT id, submission_id, task_id, submission_content, comment, score, reviewer_id, status FROM peer_reviews WHERE id = ? |] $ Only rid case review of [r] -> return $ Just $ rowToPair r _ -> return Nothing ) -- Find all reviews for given Task id. findByTaskId :: Pool Connection -> TaskID -> IO [(PeerReviewID,PeerReview)] findByTaskId pool tid = withResource pool (\ conn -> do reviews <- query conn [sql| SELECT id, submission_id, task_id, submission_content, comment, score, reviewer_id, status FROM peer_reviews WHERE task_id = ? |] $ Only tid return $ fmap rowToPair reviews ) -- Find all reviews. findAll :: Pool Connection -> IO [(PeerReviewID,PeerReview)] findAll pool = withResource pool (\ conn -> do reviews <- query_ conn [sql| SELECT id, submission_id, task_id, submission_content, comment, score, reviewer_id, status FROM peer_reviews |] return $ fmap rowToPair reviews ) -- Update review score and comment. update :: Pool Connection -> PeerReviewID -> (Comment, Score) -> IO Bool update pool rid (c,s) = withResource pool (\ conn -> do modified <- execute conn [sql| UPDATE peer_reviews SET comment = ?, score = ?, status = ? WHERE id = ? |] (c, s, Reviewed, rid) case modified of 1 -> return True _ -> return False ) -- Turn a row from DB to a pair of id and review. rowToPair :: ( PeerReviewID , SubmissionID , TaskID , Content , Comment , Score , UserID , ReviewStatus ) -> (PeerReviewID, PeerReview) rowToPair (prid, sid, tid, sc, c, score, rid, status) = (prid, PeerReview sid tid sc c score rid status)
keveri/peer-review-service
src/PeerReview/ReviewRepo/Transaction.hs
bsd-3-clause
3,271
0
14
950
711
392
319
57
2