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
-- The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. -- -- Find the sum of all the primes below two million. import Utils.Primes calc :: Int calc = sum $ takeWhile (\x -> x < 2000000) $ primes main :: IO () main = do print calc
daniel-beard/projecteulerhaskell
Problems/p10.hs
mit
239
0
10
63
63
34
29
6
1
module Typed.ArithTest where import Data.Either import qualified Data.Map as M import Test.Tasty.HUnit import Preliminaries import Typed.Arith test_typeof = [ testCase "|- true : Bool" $ rights [typeof () (ArithTerm $ Ttrue)] @?= [Kbool] , testCase "|- if false then (pred 0) else (succ 0) : Nat" $ rights [typeof () (ArithTerm $ Tif Tfalse Tzero (Tsucc Tzero))] @?= [Knat] ] test_eval = [ testCase "if true then iszero (pred (succ 0)) else false -> true" $ rights [eval (ArithTerm $ Tif Ttrue (Tiszero (Tpred (Tsucc Tzero))) Tfalse)] @?= [ArithTerm Ttrue] , testCase "iszero (succ (pred 0)) -> false" $ rights [eval (ArithTerm $ Tiszero (Tsucc (Tpred Tzero)))] @?= [ArithTerm Tfalse] ]
myuon/typed
tapl/test/Typed/ArithTest.hs
mit
703
0
19
127
242
127
115
12
1
{-# LANGUAGE OverloadedStrings #-} module Joebot.Plugins.Mail.Cmds where import qualified Data.Text as T import Control.Concurrent.Chan import Joebot.Core import Joebot.Plugins.Mail.Base mail :: Chan Msg -> Command mail ch = Command "!mail" 1 (send ch) "!mail <nick> <text> -- send a message" rcv :: Chan Msg -> Command rcv ch = Command "!rcv" 0 (receive ch) "!rcv -- read all messages" inbox :: Chan Msg -> Command inbox ch = Command "!inbox" 0 (checkInbox ch) "!inbox -- check how many messages you have" mHook :: Chan Msg -> T.Text -> T.Text -> Net () mHook ch n chnl = checkInbox ch n Nothing [] runMailServer :: Chan Msg -> IO () runMailServer = mailProc
joeschmo/joebot2
src/Joebot/Plugins/Mail/Cmds.hs
mit
668
0
9
119
214
112
102
16
1
-------------------------------------------------------------------------------- -- | Defines a cleanup action that needs to be run after we're done with a slide -- or image. module Patat.Cleanup ( Cleanup ) where -------------------------------------------------------------------------------- type Cleanup = IO ()
jaspervdj/patat
lib/Patat/Cleanup.hs
gpl-2.0
326
0
6
43
26
17
9
3
0
-- Constant tag names which have special support in the runtime or the sugaring. -- Those which are supported in the runtime are repeated in JS in rts.js. module Lamdu.Builtins.Anchors ( objTag, infixlTag, infixrTag , bytesTid, floatTid, streamTid, textTid, arrayTid , headTag, tailTag, consTag, nilTag, trueTag, falseTag, justTag, nothingTag , startTag, stopTag, indexTag , valTypeParamId , Order, anchorTags ) where import Data.List.Utils (rightPad) import Data.String (IsString(..)) import Lamdu.Calc.Type (Tag) import qualified Lamdu.Calc.Type as T -- We want the translation to UUID and back to not be lossy, so we -- canonize to UUID format bi :: IsString a => String -> a bi = fromString . rightPad uuidLength '\x00' . ("BI:" ++) where uuidLength = 16 objTag :: Tag objTag = bi "object" infixlTag :: Tag infixlTag = bi "infixl" infixrTag :: Tag infixrTag = bi "infixr" indexTag :: Tag indexTag = bi "index" startTag :: Tag startTag = bi "start" stopTag :: Tag stopTag = bi "stop" bytesTid :: T.NominalId bytesTid = bi "bytes" floatTid :: T.NominalId floatTid = bi "float" streamTid :: T.NominalId streamTid = bi "stream" textTid :: T.NominalId textTid = bi "text" arrayTid :: T.NominalId arrayTid = bi "array" headTag :: Tag headTag = bi "head" tailTag :: Tag tailTag = bi "tail" consTag :: Tag consTag = bi "cons" nilTag :: Tag nilTag = bi "nil" trueTag :: Tag trueTag = bi "true" falseTag :: Tag falseTag = bi "false" justTag :: Tag justTag = bi "just" nothingTag :: Tag nothingTag = bi "nothing" valTypeParamId :: T.ParamId valTypeParamId = bi "val" type Order = Int anchorTags :: [(Order, Tag, String)] anchorTags = [ (0, objTag, "object") , (1, startTag, "start") , (2, stopTag, "stop") , (1, indexTag, "index") , (0, infixlTag, "infixl") , (1, infixrTag, "infixr") , (0, headTag, "head") , (1, tailTag, "tail") , (0, nilTag, "Empty") , (1, consTag, "NonEmpty") , (0, trueTag, "True") , (1, falseTag, "False") , (0, nothingTag, "Nothing") , (1, justTag, "Just") ]
da-x/lamdu
Lamdu/Builtins/Anchors.hs
gpl-3.0
2,131
0
7
479
637
384
253
71
1
-- Copyright 2015 Ruud van Asseldonk -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License version 3. See -- the licence file in the root of the repository. module Html ( Tag , TagProperties , makeRunIn , applyTagsWhere , classifyTags , cleanTables , concatMapTagsWhere , filterTags , getTextInTag , hasUl , hasMath , isA , isAB , isAbbr , isArchive , isArchiveLink , isArticle , isBlockQuote , isCode , isEm , isH1 , isH2 , isH3 , isHead , isHeader , isHeading , isOl , isPre , isRunIn , isScript , isSmcp , isSubtitle , isSub , isSup , isStrong , isStyle , isTable , isTeaser , isTeaserLink , isTh , isUl , isVar , mapTagsWhere , mapText , mapTextWith , maxOlLength , parseTags , renderTags ) where -- This module contains utility functions for dealing with html. import Control.Monad (join, msum) import Data.List (delete, intersperse) import Data.Maybe (catMaybes) import qualified Text.HTML.TagSoup as S type Tag = S.Tag String -- Tagsoup's default escape function escapes " to &quot;, but this is only -- required inside quoted strings and only bloats the html in other places. -- Even worse, it can render inline stylesheets invalid. I do not have -- quoted strings with quotes in them, so it is fine not to escape quotes. escapeHtml :: String -> String escapeHtml = concatMap escape where escape '&' = "&amp;" escape '<' = "&lt;" escape '>' = "&gt;" escape c = [c] -- Render options for Tagsoup that use the above escape function, and and that -- do not escape inside <style> tags in addition to the default <script> tags. renderOptions :: S.RenderOptions String renderOptions = S.RenderOptions escapeHtml minimize rawTag where minimize _ = False -- Do not omit closing tags for empty tags. rawTag tag = (tag == "script") || (tag == "style") -- Like Tagsoup's renderTags, but with the above options applied. renderTags :: [Tag] -> String renderTags = S.renderTagsOptions renderOptions -- Reexport of Tagsoup's parseTags for symmetry. parseTags :: String -> [Tag] parseTags = S.parseTags -- Applies a function to the text of a text tag. mapText :: (String -> String) -> Tag -> Tag mapText f (S.TagText str) = S.TagText (f str) mapText _ tag = tag -- Various classifications for tags: inside body, inside code, etc. data TagClass = A | AB -- Not an html tag, but an id. | Abbr | Archive -- Not an html tag, but an id. | Article | BlockQuote | Code | Em | H1 | H2 | H3 | Head | Header | Ol | Pre | RunIn -- Not an html tag, but a class. | Script | Smcp -- Not an html tag, but a class. | Style | Strong | Sub | Sup | Table | Teaser -- Not an html tag, but an id. | Th | Ul | Var deriving (Eq, Ord, Show) tagClassFromName :: String -> Maybe TagClass tagClassFromName name = case name of "a" -> Just A "abbr" -> Just Abbr "article" -> Just Article "blockquote" -> Just BlockQuote "code" -> Just Code "em" -> Just Em "h1" -> Just H1 "h2" -> Just H2 "h3" -> Just H3 "head" -> Just Head "header" -> Just Header "ol" -> Just Ol "pre" -> Just Pre "script" -> Just Script "style" -> Just Style "strong" -> Just Strong "sub" -> Just Sub "sup" -> Just Sup "table" -> Just Table "th" -> Just Th "ul" -> Just Ul "var" -> Just Var _ -> Nothing tagClassFromAttributes :: [(String, String)] -> Maybe TagClass tagClassFromAttributes = msum . fmap fromAttr where fromAttr attr = case attr of ("class", "smcp") -> Just Smcp ("class", "run-in") -> Just RunIn ("class", "archive") -> Just Archive ("id", "teaser") -> Just Teaser ("id", "ab") -> Just AB _ -> Nothing -- Try to classify the tag based on the tag name and based on the attributes. tagClass :: String -> [(String, String)] -> [TagClass] tagClass name attrs = catMaybes [tagClassFromName name, tagClassFromAttributes attrs] -- A stack of tag name (string) and classification. type TagStack = [(String, [TagClass])] updateTagStack :: TagStack -> Tag -> TagStack updateTagStack ts tag = case tag of S.TagOpen name attrs -> case tagClass name attrs of [] -> ts classification -> (name, classification) : ts S.TagClose name -> case ts of (topName, _) : more -> if topName == name then more else ts _ -> ts _ -> ts -- Determines for every tag the nested tag classifications. tagStacks :: [Tag] -> [[TagClass]] tagStacks = fmap (concatMap snd) . scanl updateTagStack [] data TagProperties = TagProperties { isA :: Bool , isAB :: Bool , isAbbr :: Bool , isArchive :: Bool , isArticle :: Bool , isBlockQuote :: Bool , isCode :: Bool , isEm :: Bool , isH1 :: Bool , isH2 :: Bool , isH3 :: Bool , isHead :: Bool , isHeader :: Bool , isOl :: Bool , isPre :: Bool , isRunIn :: Bool , isScript :: Bool , isSmcp :: Bool , isStyle :: Bool , isStrong :: Bool , isSub :: Bool , isSup :: Bool , isTable :: Bool , isTeaser :: Bool , isTh :: Bool , isUl :: Bool , isVar :: Bool } isHeading :: TagProperties -> Bool isHeading t = (isH1 t) || (isH2 t) || (isH3 t) isSubtitle :: TagProperties -> Bool isSubtitle t = (isHeader t) && (isH2 t) isArchiveLink :: TagProperties -> Bool isArchiveLink t = (isArchive t) && (isSmcp t) && (isA t) isTeaserLink :: TagProperties -> Bool isTeaserLink t = (isTeaser t) && (isA t) getProperties :: [TagClass] -> TagProperties getProperties ts = let test cls = (cls `elem` ts) in TagProperties { isA = test A , isAB = test AB , isAbbr = test Abbr , isArchive = test Archive , isArticle = test Article , isBlockQuote = test BlockQuote , isCode = test Code , isEm = test Em , isH1 = test H1 , isH2 = test H2 , isH3 = test H3 , isHead = test Head , isHeader = test Header , isOl = test Ol , isPre = test Pre , isRunIn = test RunIn , isScript = test Script , isSmcp = test Smcp , isStyle = test Style , isStrong = test Strong , isSub = test Sub , isSup = test Sup , isTable = test Table , isTeaser = test Teaser , isTh = test Th , isUl = test Ul , isVar = test Var } -- Given a list of tags, classifies them as "inside code", "inside em", etc. classifyTags :: [Tag] -> [(Tag, TagProperties)] classifyTags tags = zip tags $ fmap getProperties $ tagStacks tags -- Discards tags for which the predicate returns false. filterTags :: (TagProperties -> Bool) -> [Tag] -> [Tag] filterTags predicate = fmap fst . filter (predicate . snd) . classifyTags -- Applies a mapping function to the tags when the predicate p returns true for -- that tag. The function tmap is a way to abstract over the mapping function, -- it should not alter the length of the list. applyTagsWhere :: (TagProperties -> Bool) -> ([Tag] -> [Tag]) -> [Tag] -> [Tag] applyTagsWhere p tmap tags = fmap select $ zip (classifyTags tags) (tmap tags) where select ((orig, props), mapped) = if p props then mapped else orig -- Applies the function f to all tags for which p returns true. mapTagsWhere :: (TagProperties -> Bool) -> (Tag -> Tag) -> [Tag] -> [Tag] mapTagsWhere p f = applyTagsWhere p (fmap f) -- Applies the function f to all tags for which p returns true and flattens the result. concatMapTagsWhere :: (TagProperties -> Bool) -> (Tag -> [Tag]) -> [Tag] -> [Tag] concatMapTagsWhere p f = concatMap select . classifyTags where select (tag, props) = if (p props) then f tag else [tag] -- Returns the the text in all tags that satisfy the selector. getTextInTag :: (TagProperties -> Bool) -> String -> String getTextInTag p = join . intersperse " " . getText . (filterTags p) . parseTags where getText = fmap S.fromTagText . filter S.isTagText -- Returns a list of text in text nodes, together with a value selected by f. mapTextWith :: (TagProperties -> a) -> String -> [(String, a)] mapTextWith f = fmap select . (filter $ S.isTagText . fst) . classifyTags . parseTags where select (tag, props) = (S.fromTagText tag, f props) -- Returns whether an <ul> tag is present in the <article> in an html string. hasUl :: String -> Bool hasUl = not . null . filter (isArticle . snd) . filter (S.isTagOpenName "ul" . fst) . classifyTags . parseTags -- Returns whether an html snippet contains a <sub>, <sup>, or <var> tag. hasMath :: String -> Bool hasMath = any (\t -> isSub t || isSup t || isVar t) . fmap snd . classifyTags . parseTags -- Returns the length of the longest ordered list in an html string. maxOlLength :: String -> Int maxOlLength = maximum . foldl listLength [0] . classifyTags . parseTags where listLength ns ((S.TagOpen "ol" _), _ ) = 0 : ns listLength (n:ns) ((S.TagOpen "li" _), cls) | isOl cls = (n + 1) : ns listLength ns _ = ns -- Adds <span class="run-in"> around the first n characters of an html snippet. -- Assumes that the html starts with a <p> tag. makeRunIn :: String -> Int -> String makeRunIn html n = prefix ++ (drop 3 runIn) ++ "</span>" ++ after where (runIn, after) = splitAt (n + 3) html prefix = "<p><span class=\"run-in\">" -- Given a piece of html, strips the "align" attributes from table elements. -- Pandoc adds these alignment tags to tables, but they are deprecated in html5. -- If you tell Pandoc to write html5, it will just add style attributes instead. -- I always align left anyway, so strip the attribute altogether. Furthermore, -- I do not use the odd and even classes, so strip them to save space. cleanTables :: String -> String cleanTables = renderTags . mapTagsWhere isTable stripAttrs . parseTags where filterAlign = filter $ (/= "align") . fst filterEven = delete ("class", "even") filterOdd = delete ("class", "odd") filterAttrs = filterAlign . filterEven . filterOdd stripAttrs tag = case tag of S.TagOpen name attrs -> S.TagOpen name $ filterAttrs attrs _ -> tag
aminb/blog
src/Html.hs
gpl-3.0
12,811
0
13
5,128
2,752
1,520
1,232
258
23
module Utils (makeMap, recsearch, (?|)) where import qualified Data.Map.Lazy as Map insertPairIntoMap :: Ord k => Map.Map k v -> (k, v) -> Map.Map k v insertPairIntoMap map (key, value) = Map.insert key value map makeMap :: Ord k => [(k, v)] -> Map.Map k v makeMap xs = foldl insertPairIntoMap Map.empty xs recsearch :: (item -> Maybe item) -> [item] -> Maybe item recsearch _ [] = Nothing recsearch f (x:xs) = case f x of j@(Just something) -> j Nothing -> recsearch f xs -- x ?| y -- Evaluates to y if x is Nothing, x otherwise. (?|) :: Maybe t -> Maybe t -> Maybe t (?|) Nothing y = y (?|) x _ = x
zc1036/Compiler-project
src/Utils.hs
gpl-3.0
664
0
10
183
281
151
130
14
2
{-# 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.Games.Applications.Verify -- 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) -- -- Verifies the auth token provided with this request is for the -- application with the specified ID, and returns the ID of the player it -- was granted for. -- -- /See:/ <https://developers.google.com/games/services/ Google Play Game Services API Reference> for @games.applications.verify@. module Network.Google.Resource.Games.Applications.Verify ( -- * REST Resource ApplicationsVerifyResource -- * Creating a Request , applicationsVerify , ApplicationsVerify -- * Request Lenses , avConsistencyToken , avApplicationId ) where import Network.Google.Games.Types import Network.Google.Prelude -- | A resource alias for @games.applications.verify@ method which the -- 'ApplicationsVerify' request conforms to. type ApplicationsVerifyResource = "games" :> "v1" :> "applications" :> Capture "applicationId" Text :> "verify" :> QueryParam "consistencyToken" (Textual Int64) :> QueryParam "alt" AltJSON :> Get '[JSON] ApplicationVerifyResponse -- | Verifies the auth token provided with this request is for the -- application with the specified ID, and returns the ID of the player it -- was granted for. -- -- /See:/ 'applicationsVerify' smart constructor. data ApplicationsVerify = ApplicationsVerify' { _avConsistencyToken :: !(Maybe (Textual Int64)) , _avApplicationId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ApplicationsVerify' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'avConsistencyToken' -- -- * 'avApplicationId' applicationsVerify :: Text -- ^ 'avApplicationId' -> ApplicationsVerify applicationsVerify pAvApplicationId_ = ApplicationsVerify' { _avConsistencyToken = Nothing , _avApplicationId = pAvApplicationId_ } -- | The last-seen mutation timestamp. avConsistencyToken :: Lens' ApplicationsVerify (Maybe Int64) avConsistencyToken = lens _avConsistencyToken (\ s a -> s{_avConsistencyToken = a}) . mapping _Coerce -- | The application ID from the Google Play developer console. avApplicationId :: Lens' ApplicationsVerify Text avApplicationId = lens _avApplicationId (\ s a -> s{_avApplicationId = a}) instance GoogleRequest ApplicationsVerify where type Rs ApplicationsVerify = ApplicationVerifyResponse type Scopes ApplicationsVerify = '["https://www.googleapis.com/auth/games", "https://www.googleapis.com/auth/plus.login"] requestClient ApplicationsVerify'{..} = go _avApplicationId _avConsistencyToken (Just AltJSON) gamesService where go = buildClient (Proxy :: Proxy ApplicationsVerifyResource) mempty
rueshyna/gogol
gogol-games/gen/Network/Google/Resource/Games/Applications/Verify.hs
mpl-2.0
3,722
0
14
858
412
246
166
68
1
module Quadtree2 where import Control.Monad import Data.Bits import Data.Word data Quad a = Node !(Quad a) !(Quad a) !(Quad a) !(Quad a) | Empty | Leaf !a deriving (Eq, Show) data Direction = UP | NW | NE | SW | SE deriving (Eq, Ord, Bounded, Enum, Show) type Path = (Int, [Direction]) type Scalar = Word type Vec2 = (Scalar, Scalar) data Crumb a = Crumb !Direction !(Quad a) !(Quad a) !(Quad a) deriving (Eq, Show) data Zipper a = Zipper { quad :: !(Quad a) , height :: !Int , breadcrumbs :: ![Crumb a] } deriving (Eq, Show) collapse :: Eq a => Quad a -> Quad a collapse (Node a b c d) | all (==a) [b,c,d] = a collapse other = other expand :: Quad a -> Quad a expand Empty = Node Empty Empty Empty Empty expand (Leaf a) = Node (Leaf a) (Leaf a) (Leaf a) (Leaf a) expand other = other up :: Ord a => Zipper a -> Maybe (Zipper a) up (Zipper q h [] ) = Just $ Zipper (Node q Empty Empty Empty) (h + 1) [] up (Zipper q h (b:bs)) = let q' = (collapse . decrumb) b in Just $ Zipper q' (h + 1) bs where decrumb (Crumb NW ne sw se) = Node q ne sw se decrumb (Crumb NE nw sw se) = Node nw q sw se decrumb (Crumb SW nw ne se) = Node nw ne q se decrumb (Crumb SE nw ne sw) = Node nw ne sw q go :: Ord a => Direction -> Zipper a -> Maybe (Zipper a) go UP z = up z go _ (Zipper _ 0 _ ) = Nothing go NW (Zipper Empty h []) = Just $ Zipper Empty (h - 1) [] go d (Zipper q h bc) = case expand q of (Node nw ne sw se) -> let (q',b') = case d of NW -> (nw, Crumb NW ne sw se) NE -> (ne, Crumb NE nw sw se) SW -> (sw, Crumb SW nw ne se) SE -> (se, Crumb SE nw ne sw) in Just $ Zipper q' (h - 1) (b':bc) _ -> Nothing walk :: Ord a => Zipper a -> [Direction] -> Maybe (Zipper a) walk = foldM (flip go) step :: (Word, Word) -> Direction step (0,0) = NW step (1,0) = NE step (0,1) = SW step (1,1) = SE bits :: Vec2 -> [(Word, Word)] bits (0,0) = [] bits (x,y) = (lb x, lb y):bits (sr x, sr y) where sr i = shiftR i 1 lb j = j .&. 1 pathForPos :: Vec2 -> Path --pathForPos = foldl (\(h,d) s -> (h+1,s:d)) (0,[]) . map step . bits pathForPos = (\x -> (length x, x)) . map step . reverse . bits pathFromZipper :: Zipper a -> Path pathFromZipper (Zipper _ h bc) = (h + length bc, reverse $ map dir bc) where dir (Crumb d _ _ _) = d pathTo :: Path -> Path -> [Direction] pathTo (sh, sd) (dh, dd) | sh < dh = pathTo (sh + 1, NW:sd) (dh, dd) | sh > dh = pathTo (sh, sd) (dh + 1, NW:dd) | otherwise = pathTo' sd dd where pathTo' [] ds = ds pathTo' ss [] = map (const UP) ss pathTo' (s:ss) (d:ds) | s == d = pathTo' ss ds | otherwise = pathTo' (s:ss) [] ++ pathTo' [] (d:ds) path :: Ord a => Path -> Zipper a -> Maybe (Zipper a) path dest z = walk z $ pathTo (pathFromZipper z) dest top :: Ord a => Zipper a -> Maybe (Zipper a) top z@(Zipper _ _ []) = Just z top z = up z >>= top to :: Ord a => Vec2 -> Zipper a -> Maybe (Zipper a) to p = path (pathForPos p) view :: Zipper a -> Maybe (Quad a) view (Zipper q h _) = case h of 0 -> Just q _ -> Nothing set :: Quad a -> Zipper a -> Maybe (Zipper a) set v (Zipper _ h bc) = case h of 0 -> Just (Zipper v h bc) _ -> Nothing get :: Zipper a -> a get z = case view z of Just (Leaf a) -> a _ -> error "get didn't find leaf" getDefault :: a -> Zipper a -> a getDefault dflt z = case view z of Just (Leaf a) -> a _ -> dflt modify :: (Quad a -> Quad a) -> Zipper a -> Maybe (Zipper a) modify f (Zipper q h bc) = case h of 0 -> Just (Zipper (f q) h bc) _ -> Nothing zipper :: (Eq a, Ord a) => Zipper a zipper = Zipper Empty 0 []
bflyblue/quadtree
Quadtree2.hs
unlicense
4,235
0
16
1,603
2,110
1,066
1,044
130
5
module Main where import Control.Exception import Control.Monad import Control.Monad.Error -- happstack package import Data.Acid import Happstack.Server import Happstack.Server.ClientSession import Text.I18n.Po (L10n, getL10n) -- html pages import Html.Error import Session import State import Routes main :: IO () main = do key <- getDefaultKey acid <- openLocalState emptyBlogState (l10n,err) <- getL10n "lang" when (not $ null err) $ do putStrLn "Warning: Error parsing language files:" mapM_ print err putStrLn $ "Starting server on " ++ (show $ port hsconf) simpleHTTP hsconf $ runServerT acid (sessionconf key) $ mainRoute l10n `catchError` internalServerErrorResponse where -- happstack config hsconf = nullConf { port = 8686 } -- session config sessionconf key = (mkSessionConf key) { sessionCookieLife = oneMonth , sessionCookieName = "blog.user.session" } oneMonth = MaxAge $ 60 * 60 * 24 * 7 * 4 -- -- Start routing -- mainRoute :: L10n -> ServerT Response mainRoute l10n = msum [ dir "static" $ serveDirectory DisableBrowsing ["index.html"] "static" , dir "api" $ apiRoute , pageRoute l10n , notFoundResponse ] -- -- Error responses -- internalServerErrorResponse :: IOException -> ServerT Response internalServerErrorResponse = internalServerError . toResponse . page500InternalError notFoundResponse :: ServerT Response notFoundResponse = notFound $ toResponse $ page404NotFound
mcmaniac/blog.nils.cc
src/Main.hs
apache-2.0
1,488
0
12
290
387
207
180
40
1
{-# LANGUAGE RankNTypes #-} module Lycopene.Freer where import Control.Monad.Free (Free, foldFree, liftF, hoistFree) import Lycopene.Coyoneda (Coyoneda(..), hoistCoyoneda) -- | a.k.a. Operational Monad type Freer f = Free (Coyoneda f) liftR :: f a -> Freer f a liftR = liftF . Coyoneda id -- | Fold Freer with specified natural transformation. foldFreer :: Monad m => (forall x. f x -> m x) -> Freer f a -> m a foldFreer f = foldFree deCoyoneda where deCoyoneda (Coyoneda g b) = fmap g (f b) hoistFreer :: (forall a. f a -> g a) -> Freer f a -> Freer g a hoistFreer f = hoistFree (hoistCoyoneda f)
utky/lycopene
src/Lycopene/Freer.hs
apache-2.0
626
0
10
136
235
123
112
12
1
-- Copyright 2020 Google LLC -- -- 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. -- For the Prelude import on ghc<8.4.1: {-# OPTIONS_GHC -Wno-dodgy-imports #-} {-# LANGUAGE OverloadedStrings #-} -- | Structure and syntax of Google3 BUILD files. -- -- This isn't yet very complete; it has just enough functionality to be able -- to generate BUILD files satisfying third_party requirements. module Google.Google3.Package where import Data.List (intersperse) import Data.List.Extra (groupSort) import Data.Text (Text) import qualified Data.Text as Text import Google.Google3.Name import Text.PrettyPrint.HughesPJ import Prelude hiding ((<>)) -- Enough abstract structure of packages to get by. -- | Examples of RuleClass are "haskell_binary", "genrule" type RuleClass = Text type License = Text data Glob = Glob { globIncludes :: [Text], globExcludes :: [Text] } -- | A thing that can be mentioned in a rule's srcs attribute. This -- doesn't quite correspond to any real concept at this level of -- abstraction, but is useful for constructing concrete expressions -- that include globs. data Source = FileSource Text -- ^ A single file | LabelSource Label -- ^ Some other label | GlobSource Glob -- ^ A set of files newtype Dependency = Labelled Label -- ^ Target name fully qualified by Google3 package. -- | A single rule declaration in a BUILD file. data Rule = Rule { ruleClass :: RuleClass, ruleName :: TargetName, ruleSrcs :: [Source], ruleDeps :: [Dependency], ruleOtherAttrs :: [(Symbol, Expr)] } data PackageAttributes = PackageAttributes { packageAttributesDefaultVisibility :: [Label] } data Package = Package { packageName :: PackageName, packageComment :: Text, packageAttributes :: PackageAttributes, packageLicenses :: [License], packageLicenseFile :: Text, packageRules :: [Rule], -- | Additional statements to add. -- TODO(judahjacobson): This is a little hacky due to cabal2buildv2 -- which needs a non-standard "load". We can try to clean this up -- after we remove the old way. packageStmts :: [Stmt] } -- Enough concrete syntax of build files to get by. In due course, this could -- maybe be provided by the language-python Cabal package. type Symbol = Text data Expr = LitString Text | Var Text | LitList [Expr] | LitTuple [Expr] | Call Symbol [Expr] [(Symbol, Expr)] | BinOp Symbol Expr Expr data Stmt = SAssign Symbol Expr | SExpr Expr | SWithComment Stmt Text -- Comment attached to a statement | SComment Text -- Free-standing comment newtype BuildFile = BuildFile [Stmt] -- Lowering from abstract syntax to concrete syntax stringListSyntax = LitList . map LitString globSyntax g = Call "glob" [stringListSyntax $ globIncludes g] [("exclude", stringListSyntax ex) | not $ null ex] where ex = globExcludes g sourceSyntax :: [Source] -> Expr sourceSyntax [] = LitList [] sourceSyntax srcs = foldr1 (BinOp "+") $ foldr (collectFiles . toExpr) [] srcs where toExpr (FileSource s) = LitString s toExpr (LabelSource s) = LitString $ showText s toExpr (GlobSource s) = globSyntax s -- Collect consecutive LitString entries into LitLists collectFiles :: Expr -> [Expr] -> [Expr] collectFiles e@(LitString _) (LitList ss : es) = LitList (e:ss) : es collectFiles e@(LitString _) es = LitList [e] : es collectFiles e es = e:es dependencyExpr :: Dependency -> Expr dependencyExpr (Labelled l) = LitString (Text.pack $ show l) ruleSyntax r = SExpr $ Call (ruleClass r) [] $ [("name", LitString . unTargetName . ruleName $ r)] ++ [("srcs", sourceSyntax ss) | let ss = ruleSrcs r, not $ null ss] ++ [("deps", LitList $ map dependencyExpr ds) | let ds = ruleDeps r, not $ null ds] ++ ruleOtherAttrs r packageAttributesSyntax a = SExpr $ Call "package" [] [ ("default_visibility", stringListSyntax . map showText . packageAttributesDefaultVisibility $ a) ] commentSyntax s | Text.null s = [] | otherwise = [SComment s] packageSyntax :: Package -> BuildFile packageSyntax = BuildFile . stmts where -- Make sure to put load() statements at the top. -- Ideally we'd rely on buildifier to do that automatically, but it doesn't -- yet: https://github.com/bazelbuild/buildtools/issues/651 stmts p = commentSyntax (packageComment p) ++ loadStmtsForRules (packageRules p) ++ [packageAttributesSyntax (packageAttributes p)] ++ licenseSyntax (packageLicenses p) ++ licenseFileSyntax (packageLicenseFile p) ++ map ruleSyntax (packageRules p) ++ packageStmts p licenseSyntax ls = [licenseAssignment ls] licenseAssignment ls = SExpr $ Call "licenses" [stringListSyntax ls] [] licenseFileSyntax "" = [] licenseFileSyntax lf = [SExpr $ Call "exports_files" [stringListSyntax [lf]] []] -- Automatically adds load directives for Haskell rules. loadStmtsForRules :: [Rule] -> [Stmt] loadStmtsForRules rules = loadStmts where ruleTable = [ (hasClass "haskell_binary", "haskell_binary", mainDefFile) , (hasClass "haskell_library", "haskell_library", mainDefFile) , (hasClass "haskell_test", "haskell_test", mainDefFile) , (hasClass "cabal_haskell_package", "cabal_haskell_package", cabalDefFile) ] mainDefFile = "//tools/build_defs/haskell:def.bzl" cabalDefFile = "//tools/build_defs/haskell:cabal_package.bzl" requiredDefs = [ (defFile, def) | (p, def, defFile) <- ruleTable, any p rules ] groupedByFile = groupSort requiredDefs loadStmts = map (uncurry addLoad) groupedByFile hasClass cls = (== cls) . ruleClass addLoad :: Text -> [Text] -> Stmt addLoad defFile defs = SExpr $ Call "load" (map LitString (defFile : defs)) [] -- | Minimal duplication of the prettyclass Cabal package, so as not to have to -- depend on it. If pretty-printing becomes sufficiently involved, it might -- in the future be worth adding dependency on that package. class Pretty a where pPrint :: a -> Doc -- How to pretty-print build files. As with the concrete syntax, this could -- perhaps eventually be replaced by language-python. instance Pretty Expr where pPrint = pPrintExpr empty -- | Pretty-print an Expr, along with any previous contents of the same line. -- -- Our goal is to format like: -- foo = [ -- x, -- y, -- z, -- ] -- rather than -- foo = [x, -- y, -- z, -- ] -- Otherwise, nested constructs become too unweildy (in particular, the -- auto-generated package-description.bzl). -- -- That format is surprisingly tricky to accomplish with Text.PrettyPrint. To -- help, the first argument of pPrintExpr holds anything that should be -- prepended to the first line (e.g. "foo = " in the above example. pPrintExpr :: Doc -> Expr -> Doc pPrintExpr pre (LitString s) = pre <> doubleQuotes (text' $ Text.concatMap fixChar s) where fixChar '\n' = "\\n" fixChar '\\' = "\\\\" fixChar '"' = "\\\"" fixChar c = Text.singleton c pPrintExpr pre (Var s) = pre <> text' s pPrintExpr pre (LitList es) = commaSep (pre <> "[") "]" $ map pPrint es pPrintExpr pre (LitTuple es) = commaSep (pre <> "(") ")" $ map pPrint es pPrintExpr pre (Call f args kwargs) = commaSep (pre <> text' f <> "(") ")" argList where argList = map pPrint args ++ map ppKwarg kwargs ppKwarg (k, v) = pPrintExpr (text' k <+> "=" <> space) v -- TODO(judahjacobson): Figure out better formatting for BinOp. (I'm not sure -- if it's used anymore.) pPrintExpr pre (BinOp o l r) = pre <> sep [pPrint l, text' o, pPrint r] -- | Generate an expression separated by commas. -- E.g., @commaSep "foobar(" ")" ["x", "y", "z"]@ renders to either -- foobar(x, y, z) -- or -- foobar( -- x, -- y, -- z -- ) commaSep :: Doc -> Doc -> [Doc] -> Doc commaSep start end xs = cat [start, nest 4 (sep $ punctuate comma xs), end] commentLine l = char '#' <+> (if Text.null l then empty else text' l) instance Pretty Stmt where pPrint (SAssign v e) = pPrintExpr (text' v <+> char '=' <> space) e pPrint (SExpr e) = pPrint e pPrint (SWithComment s c) = pPrint s <> text' " " <> commentLine c pPrint (SComment c) = vcat [commentLine l | l <- Text.lines c] instance Pretty BuildFile where pPrint (BuildFile rs) = vcat $ intersperse (text' "") $ map pPrint rs showText :: (Show a) => a -> Text showText = Text.pack . show text' :: Text -> Doc text' = text . Text.unpack
google/cabal2bazel
src/Google/Google3/Package.hs
apache-2.0
9,080
0
15
1,963
2,122
1,158
964
143
5
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QAbstractItemDelegate.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:36 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QAbstractItemDelegate ( EndEditHint, eNoHint, eEditNextItem, eEditPreviousItem, eSubmitModelCache, eRevertModelCache ) where import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CEndEditHint a = CEndEditHint a type EndEditHint = QEnum(CEndEditHint Int) ieEndEditHint :: Int -> EndEditHint ieEndEditHint x = QEnum (CEndEditHint x) instance QEnumC (CEndEditHint Int) where qEnum_toInt (QEnum (CEndEditHint x)) = x qEnum_fromInt x = QEnum (CEndEditHint x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> EndEditHint -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eNoHint :: EndEditHint eNoHint = ieEndEditHint $ 0 eEditNextItem :: EndEditHint eEditNextItem = ieEndEditHint $ 1 eEditPreviousItem :: EndEditHint eEditPreviousItem = ieEndEditHint $ 2 eSubmitModelCache :: EndEditHint eSubmitModelCache = ieEndEditHint $ 3 eRevertModelCache :: EndEditHint eRevertModelCache = ieEndEditHint $ 4
uduki/hsQt
Qtc/Enums/Gui/QAbstractItemDelegate.hs
bsd-2-clause
2,659
0
18
552
640
329
311
60
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} module Language.Haskell.Liquid.Bare.GhcSpec ( GhcSpec(..) , makeGhcSpec ) where -- import Debug.Trace (trace) import Prelude hiding (error) import CoreSyn hiding (Expr) import HscTypes import Id import NameSet import Name import TyCon import Var import TysWiredIn import DataCon (DataCon) import Control.Monad.Reader import Control.Monad.State import Data.Bifunctor import Data.Maybe import Control.Monad.Except (catchError) import TypeRep (Type(TyConApp)) import qualified Control.Exception as Ex import qualified Data.List as L import qualified Data.HashMap.Strict as M import qualified Data.HashSet as S import Language.Fixpoint.Misc (thd3) import Language.Fixpoint.Types hiding (Error) import Language.Haskell.Liquid.Types.Dictionaries import Language.Haskell.Liquid.GHC.Misc (showPpr, getSourcePosE, getSourcePos, sourcePosSrcSpan, isDataConId) import Language.Haskell.Liquid.Types.PredType (makeTyConInfo) import Language.Haskell.Liquid.Types.RefType import Language.Haskell.Liquid.Types import Language.Haskell.Liquid.Misc (mapSnd) import Language.Haskell.Liquid.WiredIn import qualified Language.Haskell.Liquid.Measure as Ms import Language.Haskell.Liquid.Bare.Check import Language.Haskell.Liquid.Bare.DataType import Language.Haskell.Liquid.Bare.Env import Language.Haskell.Liquid.Bare.Existential import Language.Haskell.Liquid.Bare.Measure import Language.Haskell.Liquid.Bare.Axiom import Language.Haskell.Liquid.Bare.Misc (makeSymbols, mkVarExpr) import Language.Haskell.Liquid.Bare.Plugged import Language.Haskell.Liquid.Bare.RTEnv import Language.Haskell.Liquid.Bare.Spec import Language.Haskell.Liquid.Bare.SymSort import Language.Haskell.Liquid.Bare.RefToLogic import Language.Haskell.Liquid.Bare.Lookup (lookupGhcTyCon) -------------------------------------------------------------------------------- makeGhcSpec :: Config -> ModName -> [CoreBind] -> [Var] -> [Var] -> NameSet -> HscEnv -> Either Error LogicMap -> [(ModName,Ms.BareSpec)] -> IO GhcSpec -------------------------------------------------------------------------------- makeGhcSpec cfg name cbs vars defVars exports env lmap specs = do sp <- throwLeft =<< execBare act initEnv let renv = ghcSpecEnv sp throwLeft . checkGhcSpec specs renv $ postProcess cbs renv sp where act = makeGhcSpec' cfg cbs vars defVars exports specs throwLeft = either Ex.throw return initEnv = BE name mempty mempty mempty env lmap' mempty mempty lmap' = case lmap of {Left e -> Ex.throw e; Right x -> x `mappend` listLMap} listLMap = toLogicMap [(nilName, [], hNil), (consName, [x, xs], hCons (EVar <$> [x,xs])) ] where x = symbol "x" xs = symbol "xs" hNil = mkEApp (dummyLoc $ symbol nilDataCon ) [] hCons = mkEApp (dummyLoc $ symbol consDataCon) postProcess :: [CoreBind] -> SEnv SortedReft -> GhcSpec -> GhcSpec postProcess cbs specEnv sp@(SP {..}) = sp { tySigs = tySigs', texprs = ts, asmSigs = asmSigs', dicts = dicts', invariants = invs', meas = meas' } where (sigs, ts') = replaceLocalBinds tcEmbeds tyconEnv tySigs texprs specEnv cbs (assms, ts) = replaceLocalBinds tcEmbeds tyconEnv asmSigs ts' specEnv cbs tySigs' = mapSnd (addTyConInfo tcEmbeds tyconEnv <$>) <$> sigs asmSigs' = mapSnd (addTyConInfo tcEmbeds tyconEnv <$>) <$> assms dicts' = dmapty (addTyConInfo tcEmbeds tyconEnv) dicts invs' = (addTyConInfo tcEmbeds tyconEnv <$>) <$> invariants meas' = mapSnd (fmap (addTyConInfo tcEmbeds tyconEnv) . txRefSort tyconEnv tcEmbeds) <$> meas ghcSpecEnv :: GhcSpec -> SEnv SortedReft ghcSpecEnv sp = fromListSEnv binds where emb = tcEmbeds sp binds = [(x, rSort t) | (x, Loc _ _ t) <- meas sp] ++ [(symbol v, rSort t) | (v, Loc _ _ t) <- ctors sp] ++ [(x, vSort v) | (x, v) <- freeSyms sp, isConLikeId v] -- ++ [(val x , rSort stringrSort) | Just (ELit x s) <- mkLit <$> lconsts, isString s] rSort = rTypeSortedReft emb vSort = rSort . varRSort varRSort :: Var -> RSort varRSort = ofType . varType --lconsts = literals cbs --stringrSort :: RSort --stringrSort = ofType stringTy --isString s = rTypeSort emb stringrSort == s ------------------------------------------------------------------------------------------------ makeGhcSpec' :: Config -> [CoreBind] -> [Var] -> [Var] -> NameSet -> [(ModName, Ms.BareSpec)] -> BareM GhcSpec ------------------------------------------------------------------------------------------------ makeGhcSpec' cfg cbs vars defVars exports specs = do name <- modName <$> get makeRTEnv specs (tycons, datacons, dcSs, tyi, embs) <- makeGhcSpecCHOP1 specs makeBounds embs name defVars cbs specs modify $ \be -> be { tcEnv = tyi } (cls, mts) <- second mconcat . unzip . mconcat <$> mapM (makeClasses name cfg vars) specs (measures, cms', ms', cs', xs') <- makeGhcSpecCHOP2 cbs specs dcSs datacons cls embs (invs, ialias, sigs, asms) <- makeGhcSpecCHOP3 cfg vars defVars specs name mts embs syms <- makeSymbols (varInModule name) (vars ++ map fst cs') xs' (sigs ++ asms ++ cs') ms' (invs ++ (snd <$> ialias)) let su = mkSubst [ (x, mkVarExpr v) | (x, v) <- syms] makeGhcSpec0 cfg defVars exports name (emptySpec cfg) >>= makeGhcSpec1 vars defVars embs tyi exports name sigs asms cs' ms' cms' su >>= makeGhcSpec2 invs ialias measures su >>= makeGhcSpec3 datacons tycons embs syms >>= makeSpecDictionaries embs vars specs >>= makeGhcAxioms embs cbs name specs >>= makeExactDataCons name (exactDC cfg) (snd <$> syms) -- This step need the updated logic map, ie should happen after makeGhcAxioms >>= makeGhcSpec4 defVars specs name su >>= addProofType addProofType :: GhcSpec -> BareM GhcSpec addProofType spec = do tycon <- (Just <$> (lookupGhcTyCon $ dummyLoc proofTyConName)) `catchError` (\_ -> return Nothing) return $ spec {proofType = (`TyConApp` []) <$> tycon} makeExactDataCons :: ModName -> Bool -> [Var] -> GhcSpec -> BareM GhcSpec makeExactDataCons n flag vs spec | flag = return $ spec {tySigs = (tySigs spec) ++ xts} | otherwise = return spec where xts = makeExact <$> (filter isDataConId $ filter (varInModule n) vs) varInModule n v = L.isPrefixOf (show n) $ show v makeExact :: Var -> (Var, Located SpecType) makeExact x = (x, dummyLoc . fromRTypeRep $ trep{ty_res = res, ty_binds = xs}) where t :: SpecType t = ofType $ varType x trep = toRTypeRep t xs = zipWith (\_ i -> (symbol ("x" ++ show i))) (ty_args trep) [1..] res = ty_res trep `strengthen` MkUReft ref mempty mempty vv = vv_ x' = symbol x -- simpleSymbolVar x ref = Reft (vv, PAtom Eq (EVar vv) eq) eq | null (ty_vars trep) && null xs = EVar x' | otherwise = mkEApp (dummyLoc x') (EVar <$> xs) makeGhcAxioms :: TCEmb TyCon -> [CoreBind] -> ModName -> [(ModName, Ms.BareSpec)] -> GhcSpec -> BareM GhcSpec makeGhcAxioms tce cbs name bspecs sp = makeAxioms tce cbs sp spec where spec = fromMaybe mempty $ lookup name bspecs makeAxioms :: TCEmb TyCon -> [CoreBind] -> GhcSpec -> Ms.BareSpec -> BareM GhcSpec makeAxioms tce cbs spec sp = do lmap <- logicEnv <$> get (ms, tys, as) <- unzip3 <$> mapM (makeAxiom tce lmap cbs spec sp) (S.toList $ Ms.axioms sp) lmap' <- logicEnv <$> get return $ spec { meas = ms ++ meas spec , asmSigs = concat tys ++ asmSigs spec , axioms = concat as ++ axioms spec , logicMap = lmap' } emptySpec :: Config -> GhcSpec emptySpec cfg = SP [] [] [] [] [] [] [] [] [] mempty [] [] [] [] mempty mempty mempty cfg mempty [] mempty mempty [] mempty Nothing makeGhcSpec0 cfg defVars exports name sp = do targetVars <- makeTargetVars name defVars $ binders cfg return $ sp { config = cfg , exports = exports , tgtVars = targetVars } makeGhcSpec1 vars defVars embs tyi exports name sigs asms cs' ms' cms' su sp = do tySigs <- makePluggedSigs name embs tyi exports $ tx sigs asmSigs <- makePluggedAsmSigs embs tyi $ tx asms ctors <- makePluggedAsmSigs embs tyi $ tx cs' lmap <- logicEnv <$> get inlmap <- inlines <$> get let ctors' = [ (x, txRefToLogic lmap inlmap <$> t) | (x, t) <- ctors ] return $ sp { tySigs = filter (\(v,_) -> v `elem` vs) tySigs , asmSigs = filter (\(v,_) -> v `elem` vs) asmSigs , ctors = filter (\(v,_) -> v `elem` vs) ctors' , meas = tx' $ tx $ ms' ++ varMeasures vars ++ cms' } where tx = fmap . mapSnd . subst $ su tx' = fmap (mapSnd $ fmap uRType) vs = vars ++ defVars makeGhcSpec2 invs ialias measures su sp = return $ sp { invariants = subst su invs , ialiases = subst su ialias , measures = subst su <$> M.elems (Ms.measMap measures) ++ Ms.imeas measures } makeGhcSpec3 :: [(DataCon, DataConP)] -> [(TyCon, TyConP)] -> TCEmb TyCon -> [(t, Var)] -> GhcSpec -> BareM GhcSpec makeGhcSpec3 datacons tycons embs syms sp = do tcEnv <- tcEnv <$> get lmap <- logicEnv <$> get inlmap <- inlines <$> get let dcons' = mapSnd (txRefToLogic lmap inlmap) <$> datacons return $ sp { tyconEnv = tcEnv , dconsP = dcons' , tconsP = tycons , tcEmbeds = embs , freeSyms = [(symbol v, v) | (_, v) <- syms] } makeGhcSpec4 defVars specs name su sp = do decr' <- mconcat <$> mapM (makeHints defVars . snd) specs texprs' <- mconcat <$> mapM (makeTExpr defVars . snd) specs lazies <- mkThing makeLazy lvars' <- mkThing makeLVar asize' <- S.fromList <$> makeASize hmeas <- mkThing makeHIMeas quals <- mconcat <$> mapM makeQualifiers specs let sigs = strengthenHaskellMeasures hmeas ++ tySigs sp lmap <- logicEnv <$> get inlmap <- inlines <$> get let tx = mapSnd (fmap $ txRefToLogic lmap inlmap) let mtx = txRefToLogic lmap inlmap return $ sp { qualifiers = subst su quals , decr = decr' , texprs = texprs' , lvars = lvars' , autosize = asize' , lazy = lazies , tySigs = tx <$> sigs , asmSigs = tx <$> asmSigs sp , measures = mtx <$> measures sp } where mkThing mk = S.fromList . mconcat <$> sequence [ mk defVars s | (m, s) <- specs, m == name ] makeASize = mapM lookupGhcTyCon [v | (m, s) <- specs, m == name, v <- S.toList (Ms.autosize s)] makeGhcSpecCHOP1 specs = do (tcs, dcs) <- mconcat <$> mapM makeConTypes specs let tycons = tcs ++ wiredTyCons let tyi = makeTyConInfo tycons embs <- mconcat <$> mapM makeTyConEmbeds specs datacons <- makePluggedDataCons embs tyi (concat dcs ++ wiredDataCons) let dcSelectors = concatMap makeMeasureSelectors datacons return (tycons, second val <$> datacons, dcSelectors, tyi, embs) makeGhcSpecCHOP3 cfg vars defVars specs name mts embs = do sigs' <- mconcat <$> mapM (makeAssertSpec name cfg vars defVars) specs asms' <- mconcat <$> mapM (makeAssumeSpec name cfg vars defVars) specs invs <- mconcat <$> mapM makeInvariants specs ialias <- mconcat <$> mapM makeIAliases specs let dms = makeDefaultMethods vars mts tyi <- gets tcEnv let sigs = [ (x, txRefSort tyi embs $ fmap txExpToBind t) | (_, x, t) <- sigs' ++ mts ++ dms ] let asms = [ (x, txRefSort tyi embs $ fmap txExpToBind t) | (_, x, t) <- asms' ] return (invs, ialias, sigs, asms) makeGhcSpecCHOP2 cbs specs dcSelectors datacons cls embs = do measures' <- mconcat <$> mapM makeMeasureSpec specs tyi <- gets tcEnv name <- gets modName mapM_ (makeHaskellInlines embs cbs name) specs hmeans <- mapM (makeHaskellMeasures embs cbs name) specs let measures = mconcat (Ms.wiredInMeasures:measures':Ms.mkMSpec' dcSelectors:hmeans) let (cs, ms) = makeMeasureSpec' measures let cms = makeClassMeasureSpec measures let cms' = [ (x, Loc l l' $ cSort t) | (Loc l l' x, t) <- cms ] let ms' = [ (x, Loc l l' t) | (Loc l l' x, t) <- ms, isNothing $ lookup x cms' ] let cs' = [ (v, txRefSort' v tyi embs t) | (v, t) <- meetDataConSpec cs (datacons ++ cls)] let xs' = val . fst <$> ms return (measures, cms', ms', cs', xs') txRefSort' v tyi embs t = txRefSort tyi embs (atLoc' v t) atLoc' v = Loc (getSourcePos v) (getSourcePosE v) data ReplaceEnv = RE { _re_env :: M.HashMap Symbol Symbol , _re_fenv :: SEnv SortedReft , _re_emb :: TCEmb TyCon , _re_tyi :: M.HashMap TyCon RTyCon } type ReplaceState = ( M.HashMap Var (Located SpecType) , M.HashMap Var [Expr] ) type ReplaceM = ReaderT ReplaceEnv (State ReplaceState) replaceLocalBinds :: TCEmb TyCon -> M.HashMap TyCon RTyCon -> [(Var, Located SpecType)] -> [(Var, [Expr])] -> SEnv SortedReft -> CoreProgram -> ([(Var, Located SpecType)], [(Var, [Expr])]) replaceLocalBinds emb tyi sigs texprs senv cbs = (M.toList s, M.toList t) where (s,t) = execState (runReaderT (mapM_ (`traverseBinds` return ()) cbs) (RE M.empty senv emb tyi)) (M.fromList sigs, M.fromList texprs) traverseExprs (Let b e) = traverseBinds b (traverseExprs e) traverseExprs (Lam b e) = withExtendedEnv [b] (traverseExprs e) traverseExprs (App x y) = traverseExprs x >> traverseExprs y traverseExprs (Case e _ _ as) = traverseExprs e >> mapM_ (traverseExprs . thd3) as traverseExprs (Cast e _) = traverseExprs e traverseExprs (Tick _ e) = traverseExprs e traverseExprs _ = return () traverseBinds b k = withExtendedEnv (bindersOf b) $ do mapM_ traverseExprs (rhssOfBind b) k -- RJ: this function is incomprehensible, what does it do?! withExtendedEnv vs k = do RE env' fenv' emb tyi <- ask let env = L.foldl' (\m v -> M.insert (varShortSymbol v) (symbol v) m) env' vs fenv = L.foldl' (\m v -> insertSEnv (symbol v) (rTypeSortedReft emb (ofType $ varType v :: RSort)) m) fenv' vs withReaderT (const (RE env fenv emb tyi)) $ do mapM_ replaceLocalBindsOne vs k varShortSymbol :: Var -> Symbol varShortSymbol = symbol . takeWhile (/= '#') . showPpr . getName -- RJ: this function is incomprehensible replaceLocalBindsOne :: Var -> ReplaceM () replaceLocalBindsOne v = do mt <- gets (M.lookup v . fst) case mt of Nothing -> return () Just (Loc l l' (toRTypeRep -> t@(RTypeRep {..}))) -> do (RE env' fenv emb tyi) <- ask let f m k = M.lookupDefault k k m let (env,args) = L.mapAccumL (\e (v, t) -> (M.insert v v e, substa (f e) t)) env' (zip ty_binds ty_args) let res = substa (f env) ty_res let t' = fromRTypeRep $ t { ty_args = args, ty_res = res } let msg = ErrTySpec (sourcePosSrcSpan l) (pprint v) t' case checkTy msg emb tyi fenv (Loc l l' t') of Just err -> Ex.throw err Nothing -> modify (first $ M.insert v (Loc l l' t')) mes <- gets (M.lookup v . snd) case mes of Nothing -> return () Just es -> do let es' = substa (f env) es case checkTerminationExpr emb fenv (v, Loc l l' t', es') of Just err -> Ex.throw err Nothing -> modify (second $ M.insert v es')
ssaavedra/liquidhaskell
src/Language/Haskell/Liquid/Bare/GhcSpec.hs
bsd-3-clause
17,015
7
23
5,184
5,623
2,935
2,688
314
5
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Hooks.DebugKeyEvents -- Description : Track key events. -- Copyright : (c) 2011 Brandon S Allbery <[email protected]> -- License : BSD -- -- Maintainer : Brandon S Allbery <[email protected]> -- Stability : unstable -- Portability : unportable -- -- A debugging module to track key events, useful when you can't tell whether -- xmonad is processing some or all key events. ----------------------------------------------------------------------------- module XMonad.Hooks.DebugKeyEvents (-- * Usage -- $usage debugKeyEvents ) where import XMonad.Core import XMonad.Prelude import XMonad.Operations (cleanMask) import Graphics.X11.Xlib import Graphics.X11.Xlib.Extras import Control.Monad.State (gets) import Data.Bits import Numeric (showHex) import System.IO (hPutStrLn ,stderr) -- $usage -- Add this to your handleEventHook to print received key events to the -- log (the console if you use @startx@/@xinit@, otherwise usually -- @~/.xsession-errors@). -- -- > , handleEventHook = debugKeyEvents -- -- If you already have a handleEventHook then you should append it: -- -- > , handleEventHook = ... <+> debugKeyEvents -- -- Logged key events look like: -- -- @keycode 53 sym 120 (0x78, "x") mask 0x0 () clean 0x0 ()@ -- -- The @mask@ and @clean@ indicate the modifiers pressed along with -- the key; @mask@ is raw, and @clean@ is what @xmonad@ sees after -- sanitizing it (removing @numberLockMask@, etc.) -- -- For more detailed instructions on editing the logHook see: -- -- "XMonad.Doc.Extending#The_log_hook_and_external_status_bars" -- | Print key events to stderr for debugging debugKeyEvents :: Event -> X All debugKeyEvents KeyEvent{ev_event_type = t, ev_state = m, ev_keycode = code} | t == keyPress = withDisplay $ \dpy -> do sym <- io $ keycodeToKeysym dpy code 0 msk <- cleanMask m nl <- gets numberlockMask io $ hPutStrLn stderr $ unwords ["keycode" ,show code ,"sym" ,show sym ," (" ,hex sym ," \"" ,keysymToString sym ,"\") mask" ,hex m ,"(" ++ vmask nl m ++ ")" ,"clean" ,hex msk ,"(" ++ vmask nl msk ++ ")" ] return (All True) debugKeyEvents _ = return (All True) -- | Convenient showHex variant hex :: (Integral n, Show n) => n -> String hex v = "0x" ++ showHex v "" -- | Convert a modifier mask into a useful string vmask :: KeyMask -> KeyMask -> String vmask numLockMask msk = unwords $ reverse $ fst $ foldr vmask' ([],msk) masks where masks = map (\m -> (m,show m)) [0..toEnum (finiteBitSize msk - 1)] ++ [(numLockMask,"num" ) ,( lockMask,"lock" ) ,(controlMask,"ctrl" ) ,( shiftMask,"shift") ,( mod5Mask,"mod5" ) ,( mod4Mask,"mod4" ) ,( mod3Mask,"mod3" ) ,( mod2Mask,"mod2" ) ,( mod1Mask,"mod1" ) ] vmask' _ a@( _,0) = a vmask' (m,s) (ss,v) | v .&. m == m = (s:ss,v .&. complement m) vmask' _ r = r
xmonad/xmonad-contrib
XMonad/Hooks/DebugKeyEvents.hs
bsd-3-clause
4,136
0
15
1,732
659
380
279
56
3
{-# LANGUAGE TupleSections#-} -- | Abstract notifier definitions. module System.Hiernotify (Difference, DifferenceP (..), Configuration (..), Notifier (..) ) where import Data.Monoid (Monoid (..), mempty, mappend) import Data.List ((\\), nub, intersect) import Data.Int -- | Difference datatype containing a difference as three sets of paths. This datatype is the core content of a notification of changes in a hierarchy. data DifferenceP a = DifferenceP { created :: [a], -- ^ Files appeared deleted :: [a], -- ^ Files disappeared modified :: [a] -- ^ Files modified } deriving (Show, Eq) instance Functor DifferenceP where fmap f (DifferenceP xs ys zs) = DifferenceP (map f xs) (map f ys) (map f zs) type Difference = DifferenceP FilePath -- half correct instance. It forces files which have been deleted and created to be marked as modifications. It's not correct as a delete after a create is not a modification. But correcting this bug involves mostly comparing timestamps correctly, because it can happen inside one element of the mappend. instance Eq a => Monoid (DifferenceP a) where DifferenceP n d m `mappend` DifferenceP n' d' m' = let mm = nub $ m ++ m' nn = nub $ n ++ n' dd = nub $ d ++ d' in DifferenceP ((nn \\ dd) \\ mm) ((dd \\ nn) \\ mm) (nub $ mm ++ intersect nn dd) mempty = DifferenceP [] [] [] -- | Configuration for notifiers. Minimal configuration to build a notifier. data Configuration = Configuration { top :: FilePath -- ^ directory at the top of the hierarchy under control , silence :: Int64 -- ^ minimum time lapse in seconds where nothing changes before a difference is released , select :: FilePath -> Bool -- ^ filter for file paths, positive must be included } -- | Abstract notifiers. A Notifier is an object controlling a hierarchy. -- -- Its difference method will block until a Difference is available and at least a time of peace has elapsed. -- -- Reading a difference must result internally in deleting the difference and updating the list of paths. -- The list of paths read together with the difference is always the list of paths to which the difference will be applied. data Notifier = Notifier { difference :: IO (Difference,[FilePath]) -- ^ block until next difference , stop :: IO () -- ^ stop the notification daemon }
paolino/hiernotify
System/Hiernotify.hs
bsd-3-clause
2,373
0
12
500
441
256
185
27
0
module Database.Hitcask.SpecHelper where import Database.Hitcask import Database.Hitcask.Types import Control.Monad import System.Directory createEmpty :: FilePath -> IO Hitcask createEmpty dir = createEmptyWith dir standardSettings createEmptyWith :: FilePath -> HitcaskSettings -> IO Hitcask createEmptyWith dir options = do whenM (doesDirectoryExist dir) (removeDirectoryRecursive dir) connectWith dir options whenM :: (Monad m) => m Bool -> m () -> m () whenM t a = t >>= flip when a nTimes :: Int -> IO () -> IO () nTimes 0 a = a nTimes n a = do a nTimes (n - 1) a closeDB :: Hitcask -> IO () closeDB db = do close db removeDirectoryRecursive (dirPath db)
tcrayford/hitcask
Database/Hitcask/SpecHelper.hs
bsd-3-clause
684
0
9
129
262
128
134
23
1
module AbstractInterpreter.Constraints where import Utils.Utils import Data.Map as M import Data.Maybe import Graphs.UnionFind import Control.Monad data Constraint = SameAs Name | HasValue (Either Int String) deriving (Show, Eq) type Constraints = Map Name Constraint fromSameAsConstraint :: Constraint -> Maybe Name fromSameAsConstraint (SameAs n) = Just n fromSameAsConstraint _ = Nothing isValueConstraint :: Constraint -> Bool isValueConstraint (HasValue _) = True isValueConstraint _ = False {- - "Same as" will always point to the smallest (alphabetically) name - HasValue will always be at the smallest name {"a" --> SameAs "b"} will be rewritten as {"b" sameAs "a"} {"a" --> SameAs "b", "b" --> HasValue (Left 0)} --> {"a" --> HasValue (Left 0), "b" --> HasValue (Left 0)} -} normalizeConstraints :: Constraints -> Constraints normalizeConstraints constraints = let connected = constraints |> fromSameAsConstraint & M.toList |> sndEffect & catMaybes :: [(Name, Name)] lowestRepr = unionFind connected & M.filterWithKey (/=) |> SameAs hasV = constraints & M.filter isValueConstraint in hasV `M.union` lowestRepr addConstraint :: (Name, Constraint) -> Constraints -> Either String Constraints addConstraint (nm, SameAs nm') constraints | nm == nm' = return constraints | nm < nm' = _addConstraint (nm', SameAs nm) constraints | otherwise = _addConstraint (nm, SameAs nm') constraints addConstraint c constraints = _addConstraint c constraints _addConstraint :: (Name, Constraint) -> Constraints -> Either String Constraints _addConstraint (nm, constraint) constraints | nm `M.member` constraints = inMsg ("While adding the constraint "++show nm++": "++show constraint) $ do let c = constraints M.! nm if c == constraint then return constraints else case c of c@(HasValue v) -> Left $ "Another value was found: "++either show show v (SameAs x) -> addConstraint (x, constraint) constraints | otherwise = M.insert nm constraint constraints & return mergeConstraints :: Constraints -> Constraints -> Either String Constraints mergeConstraints a b = foldM (flip addConstraint) b (M.toList a)
pietervdvn/ALGT
src/AbstractInterpreter/Constraints.hs
bsd-3-clause
2,178
58
15
386
673
345
328
47
3
{-# LANGUAGE NamedFieldPuns #-} module Main (main) where import Network.HTTP.Client (newManager) import Network.HTTP.Client.TLS (tlsManagerSettings) import Web.Telegram.API.Bot (runClient) import Bot (bot) import Const (tokenFile, updateIdFile) import Tools (loadOffset, loadToken, putLog, tshow) main :: IO () main = do offset <- loadOffset updateIdFile token <- loadToken tokenFile manager <- newManager tlsManagerSettings res <- runClient (bot offset) token manager putLog $ tshow res
MCL1303/TaskBot
exe/Main.hs
bsd-3-clause
519
0
10
91
156
86
70
15
1
----------------------------------------------------------------------------- -- | -- Module : Data.SBV.Provers.Z3 -- Copyright : (c) Levent Erkok -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- -- The connection to the Z3 SMT solver ----------------------------------------------------------------------------- {-# LANGUAGE ScopedTypeVariables #-} module Data.SBV.Provers.Z3(z3) where import qualified Control.Exception as C import Data.Char (toLower) import Data.Function (on) import Data.List (sortBy, intercalate, isPrefixOf, groupBy) import System.Environment (getEnv) import qualified System.Info as S(os) import Data.SBV.BitVectors.AlgReals import Data.SBV.BitVectors.Data import Data.SBV.BitVectors.PrettyNum import Data.SBV.SMT.SMT import Data.SBV.SMT.SMTLib -- Choose the correct prefix character for passing options -- TBD: Is there a more foolproof way of determining this? optionPrefix :: Char optionPrefix | map toLower S.os `elem` ["linux", "darwin"] = '-' | True = '/' -- windows -- | The description of the Z3 SMT solver -- The default executable is @\"z3\"@, which must be in your path. You can use the @SBV_Z3@ environment variable to point to the executable on your system. -- The default options are @\"-in -smt2\"@, which is valid for Z3 4.1. You can use the @SBV_Z3_OPTIONS@ environment variable to override the options. z3 :: SMTSolver z3 = SMTSolver { name = Z3 , executable = "z3" , options = map (optionPrefix:) ["in", "smt2"] , engine = \cfg isSat qinps modelMap skolemMap pgm -> do execName <- getEnv "SBV_Z3" `C.catch` (\(_ :: C.SomeException) -> return (executable (solver cfg))) execOpts <- (words `fmap` getEnv "SBV_Z3_OPTIONS") `C.catch` (\(_ :: C.SomeException) -> return (options (solver cfg))) let cfg' = cfg { solver = (solver cfg) {executable = execName, options = addTimeOut (timeOut cfg) execOpts} } tweaks = case solverTweaks cfg' of [] -> "" ts -> unlines $ "; --- user given solver tweaks ---" : ts ++ ["; --- end of user given tweaks ---"] dlim = printRealPrec cfg' ppDecLim = "(set-option :pp.decimal_precision " ++ show dlim ++ ")\n" script = SMTScript {scriptBody = tweaks ++ ppDecLim ++ pgm, scriptModel = Just (cont (roundingMode cfg) skolemMap)} if dlim < 1 then error $ "SBV.Z3: printRealPrec value should be at least 1, invalid value received: " ++ show dlim else standardSolver cfg' script cleanErrs (ProofError cfg') (interpretSolverOutput cfg' (extractMap isSat qinps modelMap)) , xformExitCode = id , capabilities = SolverCapabilities { capSolverName = "Z3" , mbDefaultLogic = Nothing , supportsMacros = True , supportsProduceModels = True , supportsQuantifiers = True , supportsUninterpretedSorts = True , supportsUnboundedInts = True , supportsReals = True , supportsFloats = True , supportsDoubles = True } } where cleanErrs = intercalate "\n" . filter (not . junk) . lines junk = ("WARNING:" `isPrefixOf`) zero :: RoundingMode -> Kind -> String zero _ KBool = "false" zero _ (KBounded _ sz) = "#x" ++ replicate (sz `div` 4) '0' zero _ KUnbounded = "0" zero _ KReal = "0.0" zero rm KFloat = showSMTFloat rm 0 zero rm KDouble = showSMTDouble rm 0 zero _ (KUninterpreted s) = error $ "SBV.Z3.zero: Unexpected uninterpreted sort: " ++ s cont rm skolemMap = intercalate "\n" $ concatMap extract skolemMap where -- In the skolemMap: -- * Left's are universals: i.e., the model should be true for -- any of these. So, we simply "echo 0" for these values. -- * Right's are existentials. If there are no dependencies (empty list), then we can -- simply use get-value to extract it's value. Otherwise, we have to apply it to -- an appropriate number of 0's to get the final value. extract (Left s) = ["(echo \"((" ++ show s ++ " " ++ zero rm (kindOf s) ++ "))\")"] extract (Right (s, [])) = let g = "(get-value (" ++ show s ++ "))" in getVal (kindOf s) g extract (Right (s, ss)) = let g = "(get-value ((" ++ show s ++ concat [' ' : zero rm (kindOf a) | a <- ss] ++ ")))" in getVal (kindOf s) g getVal KReal g = ["(set-option :pp.decimal false) " ++ g, "(set-option :pp.decimal true) " ++ g] getVal _ g = [g] addTimeOut Nothing o = o addTimeOut (Just i) o | i < 0 = error $ "Z3: Timeout value must be non-negative, received: " ++ show i | True = o ++ [optionPrefix : "T:" ++ show i] extractMap :: Bool -> [(Quantifier, NamedSymVar)] -> [(String, UnintKind)] -> [String] -> SMTModel extractMap isSat qinps _modelMap solverLines = SMTModel { modelAssocs = map snd $ squashReals $ sortByNodeId $ concatMap (interpretSolverModelLine inps) solverLines , modelUninterps = [] , modelArrays = [] } where sortByNodeId :: [(Int, a)] -> [(Int, a)] sortByNodeId = sortBy (compare `on` fst) inps -- for "sat", display the prefix existentials. For completeness, we will drop -- only the trailing foralls. Exception: Don't drop anything if it's all a sequence of foralls | isSat = map snd $ if all (== ALL) (map fst qinps) then qinps else reverse $ dropWhile ((== ALL) . fst) $ reverse qinps -- for "proof", just display the prefix universals | True = map snd $ takeWhile ((== ALL) . fst) qinps squashReals :: [(Int, (String, CW))] -> [(Int, (String, CW))] squashReals = concatMap squash . groupBy ((==) `on` fst) where squash [(i, (n, cw1)), (_, (_, cw2))] = [(i, (n, mergeReals n cw1 cw2))] squash xs = xs mergeReals :: String -> CW -> CW -> CW mergeReals n (CW KReal (CWAlgReal a)) (CW KReal (CWAlgReal b)) = CW KReal (CWAlgReal (mergeAlgReals (bad n a b) a b)) mergeReals n a b = bad n a b bad n a b = error $ "SBV.Z3: Cannot merge reals for variable: " ++ n ++ " received: " ++ show (a, b)
TomMD/cryptol
sbv/Data/SBV/Provers/Z3.hs
bsd-3-clause
7,383
0
20
2,743
1,681
927
754
87
13
-------------------------------------------------------------------------------- -- | -- Module : XMonad.Prompt.FuzzyMatch -- Description : A prompt for fuzzy completion matching in prompts akin to Emacs ido-mode. -- Copyright : (C) 2015 Norbert Zeh -- License : GPL -- -- Maintainer : Norbert Zeh <[email protected]> -- Stability : unstable -- Portability : unportable -- -- A module for fuzzy completion matching in prompts akin to emacs ido mode. -- -------------------------------------------------------------------------------- module XMonad.Prompt.FuzzyMatch ( -- * Usage -- $usage fuzzyMatch , fuzzySort ) where import XMonad.Prelude import qualified Data.List.NonEmpty as NE -- $usage -- -- This module offers two aspects of fuzzy matching of completions offered by -- XMonad.Prompt. -- -- 'fuzzyMatch' can be used as the searchPredicate in the XPConfig. The effect -- is that any completion that contains the currently typed characters as a -- subsequence is a valid completion; matching is case insensitive. This means -- that the sequence of typed characters can be obtained from the completion by -- deleting an appropriate subset of its characters. Example: "spr" matches -- "FastSPR" but also "SuccinctParallelTrees" because it's a subsequence of the -- latter: "S.......P.r..........". -- -- While this type of inclusiveness is helpful most of the time, it sometimes -- also produces surprising matches. 'fuzzySort' helps sorting matches by -- relevance, using a simple heuristic for measuring relevance. The matches are -- sorted primarily by the length of the substring that contains the query -- characters and secondarily the starting position of the match. So, if the -- search string is "spr" and the matches are "FastSPR", "FasterSPR", and -- "SuccinctParallelTrees", then the order is "FastSPR", "FasterSPR", -- "SuccinctParallelTrees" because both "FastSPR" and "FasterSPR" contain "spr" -- within a substring of length 3 ("SPR") while the shortest substring of -- "SuccinctParallelTrees" that matches "spr" is "SuccinctPar", which has length -- 11. "FastSPR" is ranked before "FasterSPR" because its match starts at -- position 5 while the match in "FasterSPR" starts at position 7. -- -- To use these functions in an XPrompt, for example, for windowPrompt: -- -- > import XMonad.Prompt -- > import XMonad.Prompt.Window ( windowPrompt ) -- > import XMonad.Prompt.FuzzyMatch -- > -- > myXPConfig = def { searchPredicate = fuzzyMatch -- > , sorter = fuzzySort -- > } -- -- then add this to your keys definition: -- -- > , ((modm .|. shiftMask, xK_g), windowPrompt myXPConfig Goto allWindows) -- -- For detailed instructions on editing the key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings". -- | Returns True if the first argument is a subsequence of the second argument, -- that is, it can be obtained from the second sequence by deleting elements. fuzzyMatch :: String -> String -> Bool fuzzyMatch a b = isSubsequenceOf (map toLower a) (map toLower b) -- | Sort the given set of strings by how well they match. Match quality is -- measured first by the length of the substring containing the match and second -- by the positions of the matching characters in the string. fuzzySort :: String -> [String] -> [String] fuzzySort q = map snd . sort . map (rankMatch q) rankMatch :: String -> String -> ((Int, Int), String) rankMatch q s = (if null matches then (maxBound, maxBound) else minimum matches, s) where matches = rankMatches q s rankMatches :: String -> String -> [(Int, Int)] rankMatches [] _ = [(0, 0)] rankMatches (q:qs) s = map (\(l, r) -> (r - l, l)) $ findShortestMatches (q :| qs) s findShortestMatches :: NonEmpty Char -> String -> [(Int, Int)] findShortestMatches q s = foldl' extendMatches spans oss where (os :| oss) = NE.map (findOccurrences s) q spans = [(o, o) | o <- os] findOccurrences :: String -> Char -> [Int] findOccurrences s c = map snd $ filter ((toLower c ==) . toLower . fst) $ zip s [0..] extendMatches :: [(Int, Int)] -> [Int] -> [(Int, Int)] extendMatches spans = map last . groupBy ((==) `on` snd) . extendMatches' spans extendMatches' :: [(Int, Int)] -> [Int] -> [(Int, Int)] extendMatches' [] _ = [] extendMatches' _ [] = [] extendMatches' spans@((l, r):spans') xs@(x:xs') | r < x = (l, x) : extendMatches' spans' xs | otherwise = extendMatches' spans xs'
xmonad/xmonad-contrib
XMonad/Prompt/FuzzyMatch.hs
bsd-3-clause
4,670
0
12
1,026
724
425
299
28
2
{-# LANGUAGE RecordWildCards #-} module Beba.Process ( mkOfProtocol , mkOfDataPath ) where import Data.List (intercalate) import System.Process import Beba.Options import Numeric (showHex) mkOfProtocol :: Int -> Options -> CreateProcess mkOfDataPath :: Int -> Options -> CreateProcess mkOfProtocol idx Options{..} = (proc ofProtocol [ "tcp:127.0.0.1:" ++ show (basePort + idx) , "tcp:" ++ controllerHost ++ ":" ++ show controllerPort , "--log-file=/var/log/ofprotocol.log." ++ show idx , "--verbose=ANY:ANY:info" , "--verbose=ANY:console:emer" ]) { close_fds = True , delegate_ctlc = True } mkOfDataPath idx Options{..} = (proc ofDataPath $ [ "ptcp:" ++ show (basePort + idx) , "--no-slicing" , "-d", datapath_id idx , "--interfaces=" ++ intercalate "," interface , "--verbose=ANY:ANY:emer" ] ++ ( maybe [] (\_ -> ["-C", show (baseCore + idx)]) instances) ) { close_fds = True , delegate_ctlc = True } datapath_id :: Int -> String datapath_id n = let h = showHex (n+1) "" in take (12 - length h) "000000000000" ++ h
awgn/beba-parallel
src/Beba/Process.hs
bsd-3-clause
1,313
0
15
448
341
186
155
32
1
module ECEFRef where import Datum import Ellipsoid import qualified LatLng as L import MathExtensions {- | ECEF (earth-centred, earth-fixed) Cartesian co-ordinates are used to define a point in three-dimensional space. ECEF co-ordinates are defined relative to an x-axis (the intersection of the equatorial plane and the plane defined by the prime meridian), a y-axis (at 90&deg; to the x-axis and its intersection with the equator) and a z-axis (intersecting the North Pole). All the axes intersect at the point defined by the centre of mass of the Earth. -} data ECEFRef = ECEFRef { x :: Double , y :: Double , z :: Double , datum :: Datum } deriving (Show) -- | Create a new earth-centred, earth-fixed reference from the given latitude and longitude. toECEFRef :: L.LatLng -> ECEFRef toECEFRef (L.LatLng latitude longitude height datum) = do let el = ellipsoid datum a = semiMajorAxis el f = flattening el eSquared = f * (2 - f) phi = toRadians latitude nphi = a / sqrt (1 - eSquared * sinSquared phi) lambda = toRadians longitude ECEFRef { x = (nphi + height) * cos phi * cos lambda , y = (nphi + height) * cos phi * sin lambda , z = (nphi * (1 - eSquared) + height) * sin phi , datum = datum } -- | Convert this ECEFRef object to a LatLng. toLatLng :: ECEFRef -> L.LatLng toLatLng (ECEFRef x y z datum) = do let el = ellipsoid datum a = semiMajorAxis el b = semiMinorAxis el e2Squared = (a / b) ** 2 - 1 f = flattening el eSquared = f * (2 - f) p = sqrt (x ** 2 + y ** 2) theta = atan (z * a / (p * b)) phi = atan $ (z + (e2Squared * b * sinCubed theta )) / (p - eSquared * a * cosCubed theta) lambda = atan2 y x nphi = a / sqrt(1 - eSquared * sinSquared phi ) h = (p / cos phi ) - nphi L.LatLng (toDegrees phi) (toDegrees lambda) h wgs84Datum
danfran/hcoord
src/ECEFRef.hs
bsd-3-clause
2,042
0
16
643
562
299
263
41
1
module Main where import Control.Monad import Data.Monoid import qualified Data.Text.IO as T import Options.Applicative import System.Exit import qualified Language.Grass.Transpiler.Untyped as G import Data.Version import Paths_Grassy (version) data Options = Options { optOptimize :: Bool , optWide :: Bool , optWidth :: Maybe Int , optOutput :: Maybe FilePath , optInputs :: [FilePath] } parserInfo :: ParserInfo Options parserInfo = info (helper <*> versionP <*> optionsP) $ fullDesc <> header "plant - Untyped lambda calculus to Grass transpiler" where versionP = infoOption (showVersion version) $ short 'v' <> long "version" <> help "Print version number" <> hidden optimizeP = switch $ short 'O' <> long "optimize" <> help "Optimize generated code" wideP = switch $ short 'W' <> long "wide" <> help "Use wide (full-width) characters" widthP = optional . option auto $ short 'w' <> long "width" <> metavar "INT" <> help "Specify maximum width of lines" outputP = optional . strOption $ short 'o' <> long "output" <> metavar "OUTFILE" <> help "Write output to OUTFILE" inputsP = some . strArgument $ metavar "INFILES..." <> help "Source files" optionsP = Options <$> optimizeP <*> wideP <*> widthP <*> outputP <*> inputsP parseOptions :: IO Options parseOptions = execParser parserInfo main :: IO () main = do opts <- parseOptions let -- input files is = optInputs opts -- optimizer opt | optOptimize opts = fullOpt | otherwise = G.noOpt -- character set (wide or narrow) cs | optWide opts = G.wideCharSet | otherwise = G.defaultCharSet -- formatting function format = case optWidth opts of Nothing -> id Just width | width <= 0 -> id | otherwise -> split width -- output function write = case optOutput opts of Nothing -> putStrLn Just output -> writeFile output . (++ "\n") -- read source files srcs <- mapM T.readFile is -- parse case concat <$> zipWithM G.parse is srcs of Left err -> die $ "ParseError at " ++ show err Right defs -> -- transpile case G.plant ctx defs opt cs of Left err -> die err Right code -> write (format code) where fullOpt = G.Optimizer { G.globalOpt = G.elimUnused effs , G.localOpt = G.elimDuplicate' } -- context ctx = [ G.DefInfo "Out" 1 , G.DefInfo "Succ" 1 , G.DefInfo "w" 1 , G.DefInfo "In" 1 ] -- side-effects of primitives (used in optimization) effs = [G.Eff, G.NoEff, G.NoEff, G.Eff] -- split output into lines split _ "" = "" split width code = case drop width code of "" -> take width code rest -> take width code ++ '\n' : split width rest
susisu/Grassy
plant/Main.hs
bsd-3-clause
3,133
0
16
1,073
836
422
414
92
7
{-# LANGUAGE CPP #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} #include "thyme.h" #if HLINT #include "cabal_macros.h" #endif -- | Vague textual descriptions of time durations. module Data.Thyme.Format.Human ( humanTimeDiff , humanTimeDiffs , humanRelTime , humanRelTimes ) where import Prelude #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif import Control.Arrow import Control.Lens import Control.Monad import Data.AdditiveGroup import Data.AffineSpace import Data.Foldable import Data.Thyme.Internal.Micro import Data.Monoid import Data.Thyme.Clock.Internal import Data.VectorSpace data Unit = Unit { unit :: Micro , single :: ShowS , plural :: ShowS } LENS(Unit,plural,ShowS) -- | Display 'DiffTime' or 'NominalDiffTime' in a human-readable form. {-# INLINE humanTimeDiff #-} humanTimeDiff :: (TimeDiff d) => d -> String humanTimeDiff d = humanTimeDiffs d "" -- | Display 'DiffTime' or 'NominalDiffTime' in a human-readable form. {-# ANN humanTimeDiffs "HLint: ignore Use fromMaybe" #-} humanTimeDiffs :: (TimeDiff d) => d -> ShowS humanTimeDiffs td = (if signed < 0 then (:) '-' else id) . diff where signed@(Micro . abs -> us) = td ^. microseconds diff = maybe id id . getFirst . fold $ zipWith (approx us . unit) (tail units) units -- | Display one 'UTCTime' relative to another, in a human-readable form. {-# INLINE humanRelTime #-} humanRelTime :: UTCTime -> UTCTime -> String humanRelTime ref time = humanRelTimes ref time "" -- | Display one 'UTCTime' relative to another, in a human-readable form. humanRelTimes :: UTCTime -> UTCTime -> ShowS humanRelTimes ref time = thence $ humanTimeDiffs diff where (diff, thence) = case compare delta zeroV of LT -> (negateV delta, ((++) "in " .)) EQ -> (zeroV, const $ (++) "right now") GT -> (delta, (. (++) " ago")) where delta = time .-. ref approx :: Micro -> Micro -> Unit -> First ShowS approx us next Unit {..} = First $ shows n . inflection <$ guard (us < next) where n = fst $ microQuotRem (us ^+^ half) unit where half = Micro . fst $ microQuotRem unit (Micro 2) inflection = if n == 1 then single else plural units :: [Unit] units = scanl (&) (Unit (Micro 1) (" microsecond" ++) (" microseconds" ++)) [ times "millisecond" 1000 , times "second" 1000 , times "minute" 60 , times "hour" 60 , times "day" 24 , times "week" 7 , times "month" (30.4368 / 7) , times "year" 12 , times "decade" 10 , times "century" 10 >>> set _plural (" centuries" ++) , times "millennium" 10 >>> set _plural (" millennia" ++) , const (Unit maxBound id id) -- upper bound needed for humanTimeDiffs.diff ] where times :: String -> Rational -> Unit -> Unit times ((++) . (:) ' ' -> single) r Unit {unit} = Unit {unit = r *^ unit, plural = single . (:) 's', ..}
liyang/thyme
src/Data/Thyme/Format/Human.hs
bsd-3-clause
3,036
0
12
732
854
476
378
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} module Bugzilla ( bzRequests , BzRequest (..) , reqBug , reqComments , BugzillaSession , newBzSession ) where import Control.Applicative import Control.Arrow ((&&&), second) import Control.Monad import Data.Function import Data.Hashable (Hashable) import qualified Data.HashMap.Strict as H import Data.List import Data.SafeCopy (base, contain, deriveSafeCopy, getCopy, putCopy, safeGet, safePut, SafeCopy) import qualified Data.Text as T import Data.Typeable (Typeable) import Web.Bugzilla import Web.Bugzilla.Search newBzSession :: UserEmail -> Maybe T.Text -> IO BugzillaSession newBzSession user mPassword = do ctx <- newBugzillaContext "bugzilla.mozilla.org" case mPassword of Just password -> do mSession <- loginSession ctx user password case mSession of Just session -> return session Nothing -> return $ anonymousSession ctx Nothing -> return $ anonymousSession ctx data BzRequest = NeedinfoRequest Bug [Comment] Flag | ReviewRequest Bug [Comment] Attachment | FeedbackRequest Bug [Comment] Attachment | AssignedRequest Bug [Comment] [Attachment] | PendingRequest Bug [Comment] [Attachment] -- Assigned bugs waiting on r? or f? | ReviewedRequest Bug [Comment] [Attachment] -- Assigned bugs with r+/r-/f+/f- deriving (Eq, Show, Typeable) -- Manually implement SafeCopy for HashMap. We need this to derive it -- for Bug below. instance (SafeCopy a, Eq a, Hashable a, SafeCopy b) => SafeCopy (H.HashMap a b) where getCopy = contain $ fmap H.fromList safeGet putCopy = contain . safePut . H.toList deriveSafeCopy 0 'base ''Attachment deriveSafeCopy 0 'base ''User deriveSafeCopy 0 'base ''Bug deriveSafeCopy 0 'base ''Comment deriveSafeCopy 0 'base ''Flag deriveSafeCopy 0 'base ''BzRequest reqBug :: BzRequest -> Bug reqBug (NeedinfoRequest bug _ _) = bug reqBug (ReviewRequest bug _ _) = bug reqBug (FeedbackRequest bug _ _) = bug reqBug (AssignedRequest bug _ _) = bug reqBug (PendingRequest bug _ _) = bug reqBug (ReviewedRequest bug _ _) = bug reqComments :: BzRequest -> [Comment] reqComments (NeedinfoRequest _ cs _) = cs reqComments (ReviewRequest _ cs _) = cs reqComments (FeedbackRequest _ cs _) = cs reqComments (AssignedRequest _ cs _) = cs reqComments (PendingRequest _ cs _) = cs reqComments (ReviewedRequest _ cs _) = cs takeLastReversed :: Int -> [a] -> [a] takeLastReversed n = take n . reverse recentComments :: [Comment] -> [Comment] recentComments = takeLastReversed 10 . filter ((/= "[email protected]") . commentCreator) categorize :: (Ord b) => (a -> b) -> [a] -> [(b, [a])] categorize f = map (fst . head &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst) . map (f &&& id) bzRequests :: BugzillaSession -> UserEmail -> IO [BzRequest] bzRequests session user = do let needinfoSearch = FlagRequesteeField .==. user .&&. FlagsField `contains` "needinfo" needinfoBugs <- searchBugs session needinfoSearch needinfoReqs <- forM needinfoBugs $ \bug -> do putStrLn $ "Getting comments for needinfo bug " ++ show (bugId bug) let flags = filter hasNeedinfoFlag (bugFlags bug) case flags of [flag] -> do comments <- recentComments <$> getComments session (bugId bug) return [NeedinfoRequest bug comments flag] _ -> return [] let reviewSearch = FlagRequesteeField .==. user .&&. (FlagsField `contains` "review" .||. FlagsField `contains` "feedback") reviewBugs <- searchBugs session reviewSearch rAndFReqs <- forM reviewBugs $ \bug -> do putStrLn $ "Getting metadata for review/feedback bug " ++ show (bugId bug) attachments <- filter attachmentIsPatch <$> getAttachments session (bugId bug) comments <- recentComments <$> getComments session (bugId bug) let reviewAttachments = filter (any hasReviewFlag . attachmentFlags) attachments reviewReqs :: [BzRequest] reviewReqs = map (ReviewRequest bug comments ) reviewAttachments feedbackAttachments = filter (any hasFeedbackFlag . attachmentFlags) attachments feedbackReqs :: [BzRequest] feedbackReqs = map (FeedbackRequest bug comments) feedbackAttachments return $ reviewReqs ++ feedbackReqs let assignedSearch = AssignedToField .==. user .&&. (StatusField .==. "NEW" .||. StatusField .==. "ASSIGNED" .||. StatusField .==. "REOPENED") assignedBugs <- searchBugs session assignedSearch assignedReqs <- forM assignedBugs $ \bug -> do putStrLn $ "Getting metadata for assigned bug " ++ show (bugId bug) comments <- recentComments <$> getComments session (bugId bug) attachments <- filter attachmentIsPatch <$> getAttachments session (bugId bug) let attsByFile = attachmentsByFile attachments newestAtts = map snd . newestNonobsoleteByFile $ attsByFile hasPendingAtts = any hasPendingFlags attsByFile hasReviewedAtts = (not . null $ attsByFile) && all hasReviewedFlags attsByFile return $ case (hasPendingAtts, hasReviewedAtts) of (True, _) -> PendingRequest bug comments newestAtts (_, True) -> ReviewedRequest bug comments newestAtts _ -> AssignedRequest bug comments newestAtts return $ (concat needinfoReqs) ++ (concat rAndFReqs) ++ assignedReqs where hasNeedinfoFlag f = flagRequestee f == Just user && flagName f == "needinfo" hasReviewFlag f = flagRequestee f == Just user && flagName f == "review" hasFeedbackFlag f = flagRequestee f == Just user && flagName f == "feedback" attachmentsByFile = categorize attachmentFileName . filter (not . attachmentIsObsolete) newestAttachment = head . sortBy (flip (compare `on` attachmentCreationTime)) newestNonobsoleteByFile = filter (not . attachmentIsObsolete . snd) . map (second newestAttachment) hasPendingFlags :: (T.Text, [Attachment]) -> Bool hasPendingFlags (_, atts) = (`any` atts) $ \att -> (`any` attachmentFlags att) $ \f -> isRequestedFlag f && (isReviewFlag f || isFeedbackFlag f) -- TODO: This doesn't handle the 'unset review' idiom. Need to -- look at history for that. We want cases where the requestee -- unset the flag. hasReviewedFlags :: (T.Text, [Attachment]) -> Bool hasReviewedFlags (_, atts) = (`any` atts) $ \att -> (`any` attachmentFlags att) $ \f -> (isPositiveFlag f || isNegativeFlag f) && (isReviewFlag f || isFeedbackFlag f) isRequestedFlag = (== "?") . flagStatus isNegativeFlag = (== "-") . flagStatus isPositiveFlag = (== "+") . flagStatus isReviewFlag = (== "review") . flagName isFeedbackFlag = (== "feedback") . flagName
sethfowler/bzbeaver
src/Bugzilla.hs
bsd-3-clause
7,189
0
21
1,759
2,096
1,092
1,004
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE Trustworthy #-} module GHC.Constants where -- TODO: This used to include HaskellConstants.hs, but that has now gone. -- We probably want to include the constants in platformConstants somehow -- instead. import GHC.Base () -- dummy dependency
jstolarek/ghc
libraries/base/GHC/Constants.hs
bsd-3-clause
293
0
4
45
20
15
5
4
0
-- ----------------------------------------------------------------------------- -- ALEX TEMPLATE -- -- This code is in the PUBLIC DOMAIN; you may copy it freely and use -- it for any purpose whatsoever. -- ----------------------------------------------------------------------------- -- INTERNALS and main scanner engine #ifdef ALEX_GHC #define ILIT(n) n# #define FAST_INT_BINDING(n) !(n) #define IBOX(n) (I# (n)) #define FAST_INT Int# #define LT(n,m) (n <# m) #define GTE(n,m) (n >=# m) #define EQ(n,m) (n ==# m) #define PLUS(n,m) (n +# m) #define MINUS(n,m) (n -# m) #define TIMES(n,m) (n *# m) #define NEGATE(n) (negateInt# (n)) #define IF_GHC(x) (x) #else #define ILIT(n) (n) #define FAST_INT_BINDING(n) (n) #define IBOX(n) (n) #define FAST_INT Int #define LT(n,m) (n < m) #define GTE(n,m) (n >= m) #define EQ(n,m) (n == m) #define PLUS(n,m) (n + m) #define MINUS(n,m) (n - m) #define TIMES(n,m) (n * m) #define NEGATE(n) (negate (n)) #define IF_GHC(x) #endif #ifdef ALEX_GHC #undef __GLASGOW_HASKELL__ #define ALEX_IF_GHC_GT_500 #if __GLASGOW_HASKELL__ > 500 #define ALEX_IF_GHC_LT_503 #if __GLASGOW_HASKELL__ < 503 #define ALEX_ELIF_GHC_500 #elif __GLASGOW_HASKELL__ == 500 #define ALEX_IF_BIGENDIAN #ifdef WORDS_BIGENDIAN #define ALEX_ELSE #else #define ALEX_ENDIF #endif #endif #ifdef ALEX_GHC data AlexAddr = AlexA# Addr# ALEX_IF_GHC_LT_503 uncheckedShiftL# = shiftL# ALEX_ENDIF {-# INLINE alexIndexInt16OffAddr #-} alexIndexInt16OffAddr (AlexA# arr) off = ALEX_IF_BIGENDIAN narrow16Int# i where i = word2Int# ((high `uncheckedShiftL#` 8#) `or#` low) high = int2Word# (ord# (indexCharOffAddr# arr (off' +# 1#))) low = int2Word# (ord# (indexCharOffAddr# arr off')) off' = off *# 2# ALEX_ELSE indexInt16OffAddr# arr off ALEX_ENDIF #else alexIndexInt16OffAddr arr off = arr ! off #endif #ifdef ALEX_GHC {-# INLINE alexIndexInt32OffAddr #-} alexIndexInt32OffAddr (AlexA# arr) off = ALEX_IF_BIGENDIAN narrow32Int# i where i = word2Int# ((b3 `uncheckedShiftL#` 24#) `or#` (b2 `uncheckedShiftL#` 16#) `or#` (b1 `uncheckedShiftL#` 8#) `or#` b0) b3 = int2Word# (ord# (indexCharOffAddr# arr (off' +# 3#))) b2 = int2Word# (ord# (indexCharOffAddr# arr (off' +# 2#))) b1 = int2Word# (ord# (indexCharOffAddr# arr (off' +# 1#))) b0 = int2Word# (ord# (indexCharOffAddr# arr off')) off' = off *# 4# ALEX_ELSE indexInt32OffAddr# arr off ALEX_ENDIF #else alexIndexInt32OffAddr arr off = arr ! off #endif #ifdef ALEX_GHC ALEX_IF_GHC_LT_503 quickIndex arr i = arr ! i ALEX_ELSE -- GHC >= 503, unsafeAt is available from Data.Array.Base. quickIndex = unsafeAt ALEX_ENDIF #else quickIndex arr i = arr ! i #endif -- ----------------------------------------------------------------------------- -- Main lexing routines data AlexReturn a = AlexEOF | AlexError !AlexInput | AlexSkip !AlexInput !Int | AlexToken !AlexInput !Int a -- alexScan :: AlexInput -> StartCode -> AlexReturn a alexScan input IBOX(sc) = alexScanUser undefined input IBOX(sc) alexScanUser user input IBOX(sc) = case alex_scan_tkn user input ILIT(0) input sc AlexNone of (AlexNone, input') -> case alexGetChar input of Nothing -> #ifdef ALEX_DEBUG trace ("End of input.") $ #endif AlexEOF Just _ -> #ifdef ALEX_DEBUG trace ("Error.") $ #endif AlexError input' (AlexLastSkip input'' len, _) -> #ifdef ALEX_DEBUG trace ("Skipping.") $ #endif AlexSkip input'' len (AlexLastAcc k input''' len, _) -> #ifdef ALEX_DEBUG trace ("Accept.") $ #endif AlexToken input''' len k -- Push the input through the DFA, remembering the most recent accepting -- state it encountered. alex_scan_tkn user orig_input len input s last_acc = input `seq` -- strict in the input let new_acc = check_accs (alex_accept `quickIndex` IBOX(s)) in new_acc `seq` case alexGetChar input of Nothing -> (new_acc, input) Just (c, new_input) -> #ifdef ALEX_DEBUG trace ("State: " ++ show IBOX(s) ++ ", char: " ++ show c) $ #endif let FAST_INT_BINDING(base) = alexIndexInt32OffAddr alex_base s FAST_INT_BINDING(IBOX(ord_c)) = ord c FAST_INT_BINDING(offset) = PLUS(base,ord_c) FAST_INT_BINDING(check) = alexIndexInt16OffAddr alex_check offset FAST_INT_BINDING(new_s) = if GTE(offset,ILIT(0)) && EQ(check,ord_c) then alexIndexInt16OffAddr alex_table offset else alexIndexInt16OffAddr alex_deflt s in case new_s of ILIT(-1) -> (new_acc, input) -- on an error, we want to keep the input *before* the -- character that failed, not after. _ -> alex_scan_tkn user orig_input PLUS(len,ILIT(1)) new_input new_s new_acc where check_accs [] = last_acc check_accs (AlexAcc a : _) = AlexLastAcc a input IBOX(len) check_accs (AlexAccSkip : _) = AlexLastSkip input IBOX(len) check_accs (AlexAccPred a predx : rest) | predx user orig_input IBOX(len) input = AlexLastAcc a input IBOX(len) check_accs (AlexAccSkipPred predx : rest) | predx user orig_input IBOX(len) input = AlexLastSkip input IBOX(len) check_accs (_ : rest) = check_accs rest data AlexLastAcc a = AlexNone | AlexLastAcc a !AlexInput !Int | AlexLastSkip !AlexInput !Int data AlexAcc a user = AlexAcc a | AlexAccSkip | AlexAccPred a (AlexAccPred user) | AlexAccSkipPred (AlexAccPred user) type AlexAccPred user = user -> AlexInput -> Int -> AlexInput -> Bool -- ----------------------------------------------------------------------------- -- Predicates on a rule alexAndPred p1 p2 user in1 len in2 = p1 user in1 len in2 && p2 user in1 len in2 --alexPrevCharIsPred :: Char -> AlexAccPred _ alexPrevCharIs c _ input _ _ = c == alexInputPrevChar input --alexPrevCharIsOneOfPred :: Array Char Bool -> AlexAccPred _ alexPrevCharIsOneOf arr _ input _ _ = arr ! alexInputPrevChar input --alexRightContext :: Int -> AlexAccPred _ alexRightContext IBOX(sc) user _ _ input = case alex_scan_tkn user input ILIT(0) input sc AlexNone of (AlexNone, _) -> False _ -> True -- TODO: there's no need to find the longest -- match when checking the right context, just -- the first match will do. -- used by wrappers iUnbox IBOX(i) = i
ekmett/luthor
Text/Luthor.hs
bsd-3-clause
6,175
39
23
1,132
1,473
788
685
89
9
module TinyControl.Packet ( DataPacket(..) , FeedbackPacket(..) , s , dataPacketSize , isLastDataPacket) where import Data.List(replicate) import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as BLC import Data.Time (UTCTime) import Data.Binary (decode, encode) import Debug.Trace (trace) data DataPacket = DataPacket { seqNum :: Int , timeStamp :: UTCTime , rtt :: Int , payload :: ByteString } defaultPacket = DataPacket { seqNum = 0 , timeStamp = read "0000-00-00 00:00:00" , rtt = 1 , payload = BC.pack (replicate 1000 'm') } instance Show DataPacket where show DataPacket { seqNum = s , timeStamp = t , rtt = r , payload = p } = (\x -> trace (show (length x)) x) $ BLC.unpack ( encode (s, r, p) ) instance Read DataPacket where readsPrec _ b = let (s, r, p) = decode $ BLC.pack $ b in [(DataPacket { seqNum = s , timeStamp = read "0000-00-00 00:00:00" , rtt = r , payload = p }, "")] data FeedbackPacket = FeedbackPacket { t_recvdata :: UTCTime , t_delay :: Int , x_recv :: Int , p :: Float } instance Show FeedbackPacket where show FeedbackPacket { t_recvdata = r , t_delay = d , x_recv = x , p = l} = (\x -> (trace (show (length x))) x) $ BLC.unpack ( encode (d, x, l) ) instance Read FeedbackPacket where readsPrec _ b = let (d, x, l) = decode $ BLC.pack $ b in [(FeedbackPacket { t_recvdata = read "0000-00-00 00:00:00" , t_delay = d , x_recv = x , p = l}, "")] -- s = payload size s::Int s = 1000 dataPacketSize :: Int dataPacketSize = 1008 + 8 + 8 --payload + encoding payload + int + float isLastDataPacket :: DataPacket -> Bool isLastDataPacket p = (B.length $ payload p) < s
Josh211ua/TinyControl
TinyControl/Packet.hs
bsd-3-clause
2,508
0
15
1,077
658
387
271
60
1
module Core.Parser.Utils where import Core.Types import Data.Char (isDigit, isLetter) digit :: Char -> Bool digit = isDigit letter :: Char -> Bool letter = isLetter alpha :: Char -> Bool alpha '_' = True alpha c = letter c type Parser a = [Token] -> [(a, [Token])] pLit :: [Char] -> Parser [Char] pLit s = pSat (== s) pVar :: Parser [Char] pVar [] = [] pVar (tok:toks) | tok `elem` keywords = [] | letter (head tok) = pSat (all (\x -> digit x || alpha x)) (tok : toks) | otherwise = [] -- pSat (\x -> letter (head x) && x `notElem` keywords) -- Exercise 1.17 keywords :: [String] keywords = ["let", "letrec", "case", "in", "of", "Pack"] pAlt :: Parser a -> Parser a -> Parser a pAlt p1 p2 toks = p1 toks ++ p2 toks pThen :: (a -> b -> c) -> Parser a -> Parser b -> Parser c pThen combine p1 p2 toks = [ (combine v1 v2, toks2) | (v1, toks1) <- p1 toks , (v2, toks2) <- p2 toks1 ] -- Exercise 1.12 pThen3 :: (a -> b -> c -> d) -> Parser a -> Parser b -> Parser c -> Parser d pThen3 combine p1 p2 p3 toks = [ (v1 v2, toks2) | (v1, toks1) <- pThen combine p1 p2 toks , (v2, toks2) <- p3 toks1 ] pThen4 :: (a -> b -> c -> d -> e) -> Parser a -> Parser b -> Parser c -> Parser d -> Parser e pThen4 combine p1 p2 p3 p4 toks = [ (v1 v2, toks2) | (v1, toks1) <- pThen3 combine p1 p2 p3 toks , (v2, toks2) <- p4 toks1 ] pZeroOrMore :: Parser a -> Parser [a] pZeroOrMore p = pOneOrMore p `pAlt` pEmpty [] -- Exercise 1.13 pEmpty :: a -> Parser a pEmpty x toks = [(x, toks)] pOneOrMore :: Parser a -> Parser [a] pOneOrMore p = pThen (:) p (pZeroOrMore p) -- Exercise 1.14 pApply :: Parser a -> (a -> b) -> Parser b pApply p f toks = [ (f t, toks1) | (t, toks1) <- p toks ] -- Exercise 1.15 pOneOrMoreWithSep :: Parser a -> Parser b -> Parser [a] pOneOrMoreWithSep p1 p2 = p1 `j` (pThen k1 p2 (ps p1 p2) `pAlt` pEmpty []) where j = pThen (:) ps = pOneOrMoreWithSep k1 x y = y -- Exercise 1.16 pSat :: ([Char] -> Bool) -> Parser [Char] pSat f [] = [] pSat f (tok:toks) | f tok = [(tok, toks)] | otherwise = [] -- Exercise 1.18 pNum :: Parser Number pNum = pApply (pSat $ all digit) read
Fuuzetsu/hcore
src/Core/Parser/Utils.hs
bsd-3-clause
2,323
0
12
697
1,075
565
510
55
1
-- © 2002 Peter Thiemann module Main where import WASH.CGI.CGI hiding (map, div, span, head) import DiskImages import Control.Monad helloCGI = standardQuery "Welcome to TinyShop" $ table $ do tr (td (attr "colspan" "2" ## text "If you are already a customer, \ \enter your email address and password")) emailF <- promptedInput "Email Address" (fieldSIZE 40) passwF <- promptedPassword "Password" (fieldSIZE 40) tr (td (submit (F2 emailF passwF) loginCGI (fieldVALUE "LOGIN"))) tr (td (submit0 newCustomerCGI (fieldVALUE "REGISTER NEW"))) promptedInput txt attrs = tr (td (text txt) >> td (inputField attrs)) promptedPassword txt attrs = tr (td (text txt) >> td (passwordInputField attrs)) -- --------------------------------------------------------- newCustomerCGI = standardQuery "TinyShop: New Customer" $ table $ do nameF <- promptedInput "Name " (fieldSIZE 40) strtF <- promptedInput "Street " (fieldSIZE 40) townF <- promptedInput "Town " (fieldSIZE 40) stateF<- promptedInput "State " (fieldSIZE 20) zipcF <- promptedInput "Zip " (fieldSIZE 10) countF<- promptedInput "Country " (fieldSIZE 20) birthF<- promptedInput "Date of Birth " (fieldSIZE 10) emailF<- promptedInput "Email address " (fieldSIZE 40) passF <- promptedPassword "Password " (fieldSIZE 40) tr $ td $ submit (F5 nameF (F5 strtF townF stateF zipcF countF) birthF emailF passF) registerCGI empty -- ------------------------------------------------------- registerCGI (F5 nameF (F5 strtF townF stateF zipcF countF) birthF emailF passF) = let name = unNonEmpty (value nameF) street = unNonEmpty (value strtF) town = unNonEmpty (value townF) state = unText (value stateF) zipc = unNonEmpty (value zipcF) country = unNonEmpty (value countF) birthdate = unNonEmpty (value birthF) email = unEmailAddress (value emailF) pass = unNonEmpty (value passF) in -- verify and store information salesCGI email -- ------------------------------------------------------- loginCGI (F2 emailF passF) = let email = unEmailAddress $ value emailF passw = unNonEmpty $ value passF in -- verify login information salesCGI email -- ------------------------------------------------------- salesCGI email = standardQuery "Current Sales Items" $ do p (do text "Hi, " text email text " here are today's specials for you!") salesItems <- table $ do attr "frame" "border" attr "border" "2" thead $ tr (th (text "amount") ## th (text "image") ## th (text "unit price")) mapM listItem inventory >>= (return . FL) p (text "Enter your selection and press FINISH to proceed to the cashier") submit salesItems billingCGI (fieldVALUE "FINISH") listItem diskDesc = let ffImage = diskImage diskDesc in tr $ do im <- internalImage ffImage (ffName ffImage) amountF <- td (inputField (fieldSIZE 5 ## fieldVALUE 0)) td (makeImg im empty) td (text $ showCurrency (diskPrice diskDesc)) return amountF -- ------------------------------------------------------- billingCGI salesItemsF = let FL salesItemsH = salesItemsF salesItems = map value $ salesItemsH in standardQuery "Your bill" $ do p (text "modified items are listed in red") hdl <- table $ do attr "frame" "border" attr "border" "2" thead $ tr (th (text "amount") ## th (text "image") ## th (text "unit price") ## th (text "total price")) prices <- mapM billItem (zip salesItems inventory) let totalPrice = sum prices tr (td empty ## td (text "total price") ## td empty ## td (text $ showCurrency totalPrice)) tr empty rg <- radioGroup tr (td (radioButton rg PayCredit empty) ## td (text "Pay by Credit Card")) ccnrF <- tr ((td empty >> td (inputField (fieldSIZE 16))) ## td (text "Card No")) ccexF <- tr ((td empty >> td (inputField (fieldSIZE 5))) ## td (text "Expires")) tr (td (radioButton rg PayTransfer empty) ## td (text "Pay by Bank Transfer")) acctF <- tr ((td empty >> td (inputField (fieldSIZE 10))) ## td (text "Acct No")) routF <- tr ((td empty >> td (inputField (fieldSIZE 8))) ## td (text "Routing")) let next paymodeF = case value paymodeF of PayCredit -> dtnode (F2 ccnrF ccexF) (dtleaf . payCredit totalPrice) PayTransfer -> dtnode (F2 acctF routF) (dtleaf . payTransfer totalPrice) return $ dtnode rg next submitx hdl empty billItem (amount, diskDesc) = let actualAmount = max 0 (min amount (diskInStock diskDesc)) actualPrice = fromIntegral actualAmount * diskPrice diskDesc amountStyle | actualAmount == amount = ("color" :=: "blue") | otherwise = ("color" :=: "red") in tr $ do using amountStyle td (text $ show actualAmount) im <- internalImage (diskImage diskDesc) (ffName (diskImage diskDesc)) td (makeImg im empty) td (text $ showCurrency (diskPrice diskDesc)) when (actualAmount > 0) $ td (text $ showCurrency actualPrice) return actualPrice -- ------------------------------------------------------- payCredit amount (F2 ccnrF ccexF) = let ccnr = unCreditCardNumber (value ccnrF) expMonth = cceMonth (value ccexF) in standardQuery "Confirm Credit Payment" $ do p $ do text "Received credit card payment of " text $ showCurrency amount p $ text "Thanks for shopping at TinyShop.Com!" payTransfer amount (F2 acctF routF) = let acct = unAllDigits (value acctF) rout = unAllDigits (value routF) in standardQuery "Confirm Transfer Payment" $ do p $ do text "Received transfer payment of " text $ showCurrency amount p $ text "Thanks for shopping at TinyShop.Com!" -- ------------------------------------------------------- main = runWithHook [] (docTranslator (map diskImage inventory) lastTranslator) helloCGI data ModeOfPayment = PayCredit | PayTransfer deriving (Read, Show) showCurrency n = show (n `div` 100) ++ '.' : reverse (take 2 (reverse (show (n+100))))
nh2/WashNGo
Examples/old/TinyShop.hs
bsd-3-clause
6,266
10
24
1,523
2,113
989
1,124
139
2
{-# LANGUAGE OverloadedStrings #-} {- Copyright (C) 2011-2014 John MacFarlane <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.SelfContained Copyright : Copyright (C) 2011-2014 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable Functions for converting an HTML file into one that can be viewed offline, by incorporating linked images, CSS, and scripts into the HTML using data URIs. -} module Text.Pandoc.SelfContained ( makeSelfContained ) where import Text.HTML.TagSoup import Network.URI (isURI, escapeURIString, URI(..), parseURI) import Data.ByteString.Base64 import qualified Data.ByteString.Char8 as B import Data.ByteString (ByteString) import System.FilePath (takeExtension, takeDirectory, (</>)) import Data.Char (toLower, isAscii, isAlphaNum) import Codec.Compression.GZip as Gzip import qualified Data.ByteString.Lazy as L import Text.Pandoc.Shared (renderTags', err, fetchItem') import Text.Pandoc.MediaBag (MediaBag) import Text.Pandoc.MIME (MimeType) import Text.Pandoc.UTF8 (toString, fromString) import Text.Pandoc.Options (WriterOptions(..)) isOk :: Char -> Bool isOk c = isAscii c && isAlphaNum c convertTag :: MediaBag -> Maybe String -> Tag String -> IO (Tag String) convertTag media sourceURL t@(TagOpen tagname as) | tagname `elem` ["img", "embed", "video", "input", "audio", "source", "track"] = do as' <- mapM processAttribute as return $ TagOpen tagname as' where processAttribute (x,y) = if x == "src" || x == "href" || x == "poster" then do (raw, mime) <- getRaw media sourceURL (fromAttrib "type" t) y let enc = "data:" ++ mime ++ ";base64," ++ toString (encode raw) return (x, enc) else return (x,y) convertTag media sourceURL t@(TagOpen "script" as) = case fromAttrib "src" t of [] -> return t src -> do (raw, mime) <- getRaw media sourceURL (fromAttrib "type" t) src let enc = "data:" ++ mime ++ "," ++ escapeURIString isOk (toString raw) return $ TagOpen "script" (("src",enc) : [(x,y) | (x,y) <- as, x /= "src"]) convertTag media sourceURL t@(TagOpen "link" as) = case fromAttrib "href" t of [] -> return t src -> do (raw, mime) <- getRaw media sourceURL (fromAttrib "type" t) src let enc = "data:" ++ mime ++ "," ++ escapeURIString isOk (toString raw) return $ TagOpen "link" (("href",enc) : [(x,y) | (x,y) <- as, x /= "href"]) convertTag _ _ t = return t -- NOTE: This is really crude, it doesn't respect CSS comments. cssURLs :: MediaBag -> Maybe String -> FilePath -> ByteString -> IO ByteString cssURLs media sourceURL d orig = case B.breakSubstring "url(" orig of (x,y) | B.null y -> return orig | otherwise -> do let (u,v) = B.breakSubstring ")" $ B.drop 4 y let url = toString $ case B.take 1 u of "\"" -> B.takeWhile (/='"') $ B.drop 1 u "'" -> B.takeWhile (/='\'') $ B.drop 1 u _ -> u let url' = if isURI url then url else d </> url (raw, mime) <- getRaw media sourceURL "" url' rest <- cssURLs media sourceURL d v let enc = "data:" `B.append` fromString mime `B.append` ";base64," `B.append` (encode raw) return $ x `B.append` "url(" `B.append` enc `B.append` rest getRaw :: MediaBag -> Maybe String -> MimeType -> String -> IO (ByteString, MimeType) getRaw media sourceURL mimetype src = do let ext = map toLower $ takeExtension src fetchResult <- fetchItem' media sourceURL src (raw, respMime) <- case fetchResult of Left msg -> err 67 $ "Could not fetch " ++ src ++ "\n" ++ show msg Right x -> return x let raw' = if ext == ".gz" then B.concat $ L.toChunks $ Gzip.decompress $ L.fromChunks $ [raw] else raw let mime = case (mimetype, respMime) of ("",Nothing) -> error $ "Could not determine mime type for `" ++ src ++ "'" (x, Nothing) -> x (_, Just x ) -> x let cssSourceURL = case parseURI src of Just u | uriScheme u `elem` ["http:","https:"] -> Just $ show u{ uriPath = "", uriQuery = "", uriFragment = "" } _ -> Nothing result <- if mime == "text/css" then cssURLs media cssSourceURL (takeDirectory src) raw' else return raw' return (result, mime) -- | Convert HTML into self-contained HTML, incorporating images, -- scripts, and CSS using data: URIs. makeSelfContained :: WriterOptions -> String -> IO String makeSelfContained opts inp = do let tags = parseTags inp out' <- mapM (convertTag (writerMediaBag opts) (writerSourceURL opts)) tags return $ renderTags' out'
rgaiacs/pandoc
src/Text/Pandoc/SelfContained.hs
gpl-2.0
6,126
0
20
1,949
1,606
838
768
100
7
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="en-GB"> <title>SOAP Scanner | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help/helpset.hs
apache-2.0
986
82
67
172
423
216
207
-1
-1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="fr-FR"> <title>SOAP Scanner | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help_fr_FR/helpset_fr_FR.hs
apache-2.0
974
80
66
160
415
210
205
-1
-1
module Snap.Loader.Dynamic.TreeWatcher ( TreeStatus , getTreeStatus , checkTreeStatus ) where #ifndef MIN_VERSION_directory #define MIN_VERSION_directory(x,y,z) 1 #endif ------------------------------------------------------------------------------ import Control.Applicative import System.Directory import System.Directory.Tree #if MIN_VERSION_directory(1,2,0) import Data.Time.Clock #else import System.Time #endif ------------------------------------------------------------------------------ -- | An opaque representation of the contents and last modification -- times of a forest of directory trees. #if MIN_VERSION_directory(1,2,0) data TreeStatus = TS [FilePath] [AnchoredDirTree UTCTime] #else data TreeStatus = TS [FilePath] [AnchoredDirTree ClockTime] #endif ------------------------------------------------------------------------------ -- | Create a 'TreeStatus' for later checking with 'checkTreeStatus' getTreeStatus :: [FilePath] -> IO TreeStatus getTreeStatus = liftA2 (<$>) TS readModificationTimes ------------------------------------------------------------------------------ -- | Checks that all the files present in the initial set of paths are -- the exact set of files currently present, with unchanged modifcations times checkTreeStatus :: TreeStatus -> IO Bool checkTreeStatus (TS paths entries) = check <$> readModificationTimes paths where check = and . zipWith (==) entries ------------------------------------------------------------------------------ -- | This is the core of the functions in this module. It converts a -- list of filepaths into a list of 'AnchoredDirTree' annotated with -- the modification times of the files located in those paths. #if MIN_VERSION_directory(1,2,0) readModificationTimes :: [FilePath] -> IO [AnchoredDirTree UTCTime] #else readModificationTimes :: [FilePath] -> IO [AnchoredDirTree ClockTime] #endif readModificationTimes = mapM $ readDirectoryWith getModificationTime
snapframework/snap-loader-dynamic
src/Snap/Loader/Dynamic/TreeWatcher.hs
bsd-3-clause
1,961
0
8
231
201
123
78
16
1
module Compiler where import Syntax import PatComp (compilePatternMatch) import PPrint () -- for (Show Expr) programToExpr :: Program -> Expr programToExpr bgs = foldr Let (mainExpr (last bgs)) bgs' where bgs' = regroup (init bgs) mainExpr :: BindGroup -> Expr mainExpr bg = case bindings bg of [("@main", [([], Rhs e)])] -> e _ -> error "Illegal program entry point" regroup :: [BindGroup] -> [BindGroup] regroup bgs = [([], [is]) | is <- iss] where iss = dependency (concat (map bindings bgs)) expandCon :: Expr -> Expr expandCon e@(Var _) = e expandCon e@(Lit _) = e expandCon (Ap e1 e2) = Ap (expandCon e1) (expandCon e2) expandCon (Let bg e) = Let (expandConBG bg) (expandCon e) expandCon (Lambda (vs, Rhs e)) = Lambda (vs, Rhs (expandCon e)) expandCon (ESign e sc) = (ESign (expandCon e) sc) expandCon (Con con) = Lambda ([PVar v | v <- as++fs], Rhs body) where as = ["@a" ++ show i | i <- [1..conArity con]] fs = ["@f" ++ show i | i <- [1..(tyconNumCon $ conTycon con)]] body = ap (Var $ fs !! (tag - 1)) [Var v | v <- as] tag = if conTag con < 1 then error ("bad tag " ++ conName con) else conTag con expandConBG :: BindGroup -> BindGroup expandConBG (es, iss) = (es', map expandConImpls iss) where es' = [(i, sc, map expandConAlt alts) | (i, sc, alts) <- es] expandConImpls is = [(i, map expandConAlt alts) | (i, alts) <- is] expandConAlt (ps, rhs) = (ps, expandConRhs rhs) expandConRhs (Rhs e) = Rhs (expandCon e) expandConRhs (Where bg rhs) = Where (expandConBG bg) (expandConRhs rhs) expandConRhs (Guarded pairs) = Guarded [(expandCon c, expandCon e) | (c, e) <- pairs] skiCompile :: Expr -> SKI skiCompile = compileExpr compileExpr :: Expr -> SKI compileExpr (Ap e1 e2) = compileExpr e1 `SAp` compileExpr e2 compileExpr (Let bg e) = case map compileDef (bindings bg) of [(i, v)] -> case (abstract i e') of SVar "K" `SAp` _ -> e' e'' -> e'' `SAp` removeSelfRec i v defs -> compileMultipleDefs e' defs where e' = compileExpr e compileExpr (Lambda a) = compileAlt a compileExpr (Var i) = SVar i compileExpr (Lit l) = SLit l compileExpr (Con con) = SCon (conTag con) (conArity con) compileExpr e = error ("compileExpr: " ++ show e) compileDef :: (Id, [Alt]) -> (Id, SKI) compileDef (i, [a]) = (i, compileAlt a) removeSelfRec :: Id -> SKI -> SKI removeSelfRec i e | refers i e = SVar "Y" `SAp` abstract i e | otherwise = e compileMultipleDefs :: SKI -> [(Id, SKI)] -> SKI compileMultipleDefs e defs | not $ any (flip refers e) (map fst defs) = e | otherwise = SAp lhs rhs where (is, vals) = unzip defs lhs = uAbs is e rhs = SVar "Y" `SAp` uAbs is (mklist vals) mklist [] = SVar "nil" mklist (x:xs) = SVar "cons" `SAp` x `SAp` mklist xs uAbs :: [Id] -> SKI -> SKI uAbs [] e = SVar "K" `SAp` e uAbs (i:is) e = SVar "U" `SAp` abstract i (uAbs is e) compileAlt :: Alt -> SKI compileAlt ([], Rhs e) = compileExpr e compileAlt (PVar v : as, e) = abstract v (compileAlt (as, e)) compileAlt (p:ps, e) = error ("malformed pattern " ++ show p) abstract :: Id -> SKI -> SKI abstract i v@(SVar i') | i == i' = SVar "I" | otherwise = SVar "K" `SAp` v abstract i (SAp e1 e2) | refers i e1 || refers i e2 = sap (SVar "S") [abstract i e1, abstract i e2] | otherwise = SAp (SVar "K") (SAp e1 e2) abstract i l@(SLit _) = SVar "K" `SAp` l abstract i c@(SCon _ _) = SVar "K" `SAp` c refers :: Id -> SKI -> Bool refers i (SVar i') = i == i' refers i (SAp e1 e2) = refers i e1 || refers i e2 refers i (SLit _) = False refers i (SCon _ _) = False
irori/hs2lazy
Compiler.hs
bsd-3-clause
3,774
11
13
1,011
1,836
948
888
89
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module T13398a where data Nat data Rate data StaticTicks where (:/:) :: Nat -> Rate -> StaticTicks type ticks :/ rate = ticks ':/: rate class HasStaticDuration (s :: k) where type SetStaticDuration s (pt :: StaticTicks) :: k instance HasStaticDuration (t :/ r) where type SetStaticDuration (t :/ r) (t' :/ r') = t' :/ r'
ezyang/ghc
testsuite/tests/indexed-types/should_compile/T13398a.hs
bsd-3-clause
509
0
7
96
123
76
47
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Main where type family F a :: * type instance F Int = (Int, ()) class C a instance C () instance (C (F a), C b) => C (a, b) f :: C (F a) => a -> Int f _ = 2 main :: IO () main = print (f (3 :: Int))
ezyang/ghc
testsuite/tests/typecheck/should_run/T3500a.hs
bsd-3-clause
318
0
8
78
144
79
65
-1
-1
{-# LANGUAGE TypeFamilies #-} module Main where import Prelude hiding (lookup) import Data.Char (ord) import qualified Data.Map as Map -- Generic maps as toplevel indexed data types ---------------------------------------------- data family GMap k :: * -> * data instance GMap Int v = GMapInt (Map.Map Int v) data instance GMap Char v = GMapChar (GMap Int v) data instance GMap () v = GMapUnit (Maybe v) data instance GMap (a, b) v = GMapPair (GMap a (GMap b v)) data instance GMap (Either a b) v = GMapEither (GMap a v) (GMap b v) class GMapKey k where empty :: GMap k v lookup :: k -> GMap k v -> Maybe v insert :: k -> v -> GMap k v -> GMap k v instance GMapKey Int where empty = GMapInt Map.empty lookup k (GMapInt m) = Map.lookup k m insert k v (GMapInt m) = GMapInt (Map.insert k v m) instance GMapKey Char where empty = GMapChar empty lookup k (GMapChar m) = lookup (ord k) m insert k v (GMapChar m) = GMapChar (insert (ord k) v m) instance GMapKey () where empty = GMapUnit Nothing lookup () (GMapUnit v) = v insert () v (GMapUnit _) = GMapUnit $ Just v instance (GMapKey a, GMapKey b) => GMapKey (a, b) where empty = GMapPair empty lookup (a, b) (GMapPair gm) = lookup a gm >>= lookup b insert (a, b) v (GMapPair gm) = GMapPair $ case lookup a gm of Nothing -> insert a (insert b v empty) gm Just gm2 -> insert a (insert b v gm2 ) gm instance (GMapKey a, GMapKey b) => GMapKey (Either a b) where empty = GMapEither empty empty lookup (Left a) (GMapEither gm1 _gm2) = lookup a gm1 lookup (Right b) (GMapEither _gm1 gm2 ) = lookup b gm2 insert (Left a) v (GMapEither gm1 gm2) = GMapEither (insert a v gm1) gm2 insert (Right a) v (GMapEither gm1 gm2) = GMapEither gm1 (insert a v gm2) -- Test code -- --------- nonsence :: GMap Bool String nonsence = undefined myGMap :: GMap (Int, Either Char ()) String myGMap = insert (5, Left 'c') "(5, Left 'c')" $ insert (4, Right ()) "(4, Right ())" $ insert (5, Right ()) "This is the one!" $ insert (5, Right ()) "This is the two!" $ insert (6, Right ()) "(6, Right ())" $ insert (5, Left 'a') "(5, Left 'a')" $ empty main = putStrLn $ maybe "Couldn't find key!" id $ lookup (5, Right ()) myGMap
urbanslug/ghc
testsuite/tests/indexed-types/should_run/GMapTop.hs
bsd-3-clause
2,416
14
14
691
1,031
523
508
50
1
{-# LANGUAGE CPP #-} module Cover5(choose5) where import Data.Random.Extras(choiceExtract) import Data.Random(RVar) import Data.Maybe import Data.List import Control.Monad.State(StateT, evalStateT, get, put, lift) import Control.Monad(replicateM) import Cover5.Internals -- The follow two imports are not needed -- in ghc 8.0 which I wrote this in -- However travis ci is still at 7.8 and therfore -- needs them. Also the CPP option at top of file -- is just for this #if #if __GLASGOW_HASKELL__ <= 708 import Data.Functor ((<$>)) #endif -- | Takes as input the number of games in a given week -- and returns a random list of 5 game identifiers and -- team identifiers choose5 :: Int -> RVar [(GameId,TeamId)] choose5 numGames = sort <$> evalStateT makePicks [1..numGames]
michaelgwelch/cover5
src/Cover5.hs
mit
783
0
8
128
144
91
53
12
1
{-# htermination isSuffixOf :: [Bool] -> [Bool] -> Bool #-} import List
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/List_isSuffixOf_6.hs
mit
72
0
3
12
5
3
2
1
0
{-# LANGUAGE BangPatterns, OverloadedStrings #-} module Main where import Data.List (unfoldr) import Data.ByteString.Char8 (ByteString, foldl') import qualified Data.ByteString.Char8 as BS type Data = ByteString checkSumFor :: Data -> Int -> Data checkSumFor from len = checkSum $ random from len checkSum :: Data -> Data checkSum = BS.pack . checkSum' . BS.unpack checkSum' :: String -> String checkSum' dt = let dt' = reduce dt in if even (length dt') then checkSum' dt' else dt' reduce :: String -> String reduce (x:y:xs) | x == y = '1' : reduce xs | otherwise = '0' : reduce xs reduce _ = [] random :: Data -> Int -> Data random from len = BS.take len $ fillUp from len fillUp :: Data -> Int -> Data fillUp from len = snd . head . dropWhile (\ (l,_) -> l < len) $ dragons from dragons :: Data -> [(Int, Data)] dragons from = unfoldr uf (BS.length from, from) where uf x = Just (x, dragon x) dragon :: (Int, Data) -> (Int, Data) dragon (len, xs) = (2*len+1, xs `BS.append` ('0' `BS.cons` revInvert xs)) revInvert :: Data -> Data revInvert = BS.map inv . BS.reverse where inv '1' = '0' inv _ = '1' testInput :: Data testInput = "10000" input :: Data input = "10001001100000001" testTargetLength :: Int testTargetLength = 20 targetLength :: Int targetLength = 272 targetLength2 :: Int targetLength2 = 35651584 main :: IO () main = do putStrLn $ "Part 1: " ++ show (checkSumFor input targetLength) putStrLn $ "Part 2: " ++ show (checkSumFor input targetLength2) putStrLn "all done"
CarstenKoenig/AdventOfCode2016
Day16/Main.hs
mit
1,555
0
10
337
613
326
287
52
2
module Protop.Core.NaturalSpec (spec) where import Protop.Core import Test.Hspec spec :: Spec spec = do addSpec mulSpec addSpec :: Spec addSpec = describe "add" $ it "should add natural numbers" $ (add .$. (42, 8)) `shouldBe` 50 mulSpec :: Spec mulSpec = describe "mul" $ it "should multiply natural numbers" $ (mul .$. (11, 12)) `shouldBe` 132
brunjlar/protop
test/Protop/Core/NaturalSpec.hs
mit
383
0
9
94
124
70
54
15
1
data Tree a = Empty | Node a (Tree a) (Tree a) data Empty' = Empty' -- 1 data Node' a = Node' (a, Tree' a, Tree' a) -- a * T(a) * T(a) type Tree' a = Either Empty' (Node' a) -- 1 + a * T(a) * T(a) {- https://chris-taylor.github.io/images/tree.png -} data TZTrace a = TZTrace { tztcurr :: a , tztleft :: Tree a , tztright :: Tree a } data TreeZipper a = TZ { curr :: a , lchild :: Tree a , rchild :: Tree a , btrace :: [TZTrace a] } left :: TreeZipper a -> TreeZipper a left (TZ _ Empty _ _) = error "empty on left" left (TZ cur (Node n ll lr) r bt) = TZ { curr = n , lchild = ll , rchild = lr , btrace = (TZTrace { tztcurr = cur , tztleft = Empty , tztright = r }):bt } right :: TreeZipper a -> TreeZipper a right (TZ _ _ Empty _) = error "empty on right" right (TZ cur l (Node n rl rr) bt) = TZ { curr = n , lchild = rl , rchild = rr , btrace = (TZTrace { tztcurr = cur , tztleft = l , tztright = Empty }):bt } up :: TreeZipper a -> TreeZipper a up (TZ _ _ _ []) = error "already on the top" up (TZ cur l r ((TZTrace tztcur Empty tztr):bt)) = TZ { curr = tztcur , lchild = Node cur l r , rchild = tztr , btrace = bt } up (TZ cur l r ((TZTrace tztcur tztl Empty):bt)) = TZ { curr = tztcur , lchild = tztl , rchild = Node cur l r , btrace = bt } up (TZ _ _ _ ((TZTrace _ _ _):_)) = error "invalid backtrace"
shouya/thinking-dumps
alg-adts/treezipper.hs
mit
1,766
0
11
769
626
346
280
44
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverlappingInstances #-} module Y2020.M11.D25.Solution where {-- So, we're TOTALLY going to publish all airbases and all alliances and correct that the USA is not in NATO, even though the USA is in the graph database... ... but that's not what we're doing today. TODAY! How do airbases communicate? WITH A DICK TRACY SUPER-SECRET CODE! WHAT SUPER-SECRET CODE? Well, obviously, in a super-secret code nobody knows and nobody uses. Morse code. (My Uncle Roy, a licensed HAM radio owner/operator will now find me and kill me) Now, morse code is this: https://en.wikipedia.org/wiki/Morse_code (I'm not going to type out the morse code. You can follow the link.) Now, you can hand-represent each letter with each da-dit, 'by hand,' but earlier this week there was a graph representation of the same. I've added that graph to the repository here as morse-code.png. Either way you wanna do it: have a plain-text-to-morse-code translator. --} import Control.Arrow (second) import qualified Data.ByteString.Lazy.Char8 as BL import Data.Char (toUpper) import Data.Aeson (decode) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (mapMaybe) import Graph.Query import Graph.JSON.Cypher.Read.Rows data Morse = DA | DIT | SPACE -- ... the final frontier, or nah? deriving Eq type MorseTable = Map Char [Morse] instance Show Morse where show DA = "-" show DIT = "." show SPACE = " " instance Show [Morse] where show [] = "" show (h:t) = show h ++ concat (map show t) instance Read Morse where readsPrec _ (c:har) = return (c' c, har) where c' '-' = DA c' '.' = DIT c' ' ' = SPACE morseTable :: MorseTable morseTable = Map.fromList $ map (second (map (read . return))) [('A', ".-"), ('B', "-..."), ('C', "-.-."),('D', "-.."), ('E', "."), ('F', "..-."),('G', "--."),('H', "...."),('I',".."),('J',".---"), ('K', "-.-"),('L', ".-.."),('M',"--"),('N',"-."),('O',"---"),('P',".--."), ('Q', "--.-"),('R', ".-."),('S',"..."),('T',"-"),('U',"..-"),('V',"...-"), ('W', ".--"),('X', "-..-"),('Y',"-.--"),('Z',"--.."),(' '," ")] morse :: MorseTable -> Char -> Maybe [Morse] morse = flip Map.lookup -- what is the morse code of: ciceroOnPain :: String ciceroOnPain = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..." morseCodify :: MorseTable -> String -> [[Morse]] morseCodify mt = mapMaybe (morse mt) . map toUpper {-- >>> morseCodify morseTable ciceroOnPain [-.,.,--.-,..-,., ,.--.,---,.-.,.-.,---, ,--.-,..-,..,...,--.-,..-,.-,--, , .,...,-, ,--.-,..-,.., ,-..,---,.-..,---,.-.,.,--, ,..,.--.,...,..-,--, ,--.-, ..-,..,.-, ,-..,---,.-..,---,.-., ,...,..,-, ,.-,--,.,-, ,-.-.,---,-.,...,., -.-.,-,.,-,..-,.-., ,.-,-..,..,.--.,..,...,-.-.,.., ,...-,.,.-..,..,-] --}
geophf/1HaskellADay
exercises/HAD/Y2020/M11/D25/Solution.hs
mit
2,867
0
12
491
639
384
255
40
1
module Expr where -- simplified version of compiler/coreSyn/coreSyn.hs -- This file demonstrates the Coq 8.6 issue with universes. -- -- Anomaly: Unable to handle arbitrary u+k <= v constraints. Please report at -- http://coq.inria.fr/bugs/. -- -- UGH, this file randomly started working when I added links to base. -- It is not showing the Coq 8.6 error anymore data Id data Expr b = Var Id | App (Expr b) (Arg b) | Lam b (Expr b) -- | Type synonym for expressions that occur in function argument positions. -- Only 'Arg' should contain a 'Type' at top level, general 'Expr' should not type Arg b = Expr b
antalsz/hs-to-coq
examples/base-tests/Expr.hs
mit
625
0
8
127
69
44
25
-1
-1
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, OverlappingInstances, TypeSynonymInstances #-} module HarmLang.Types where import Data.Typeable import Data.Data import Data.List import Data.Ratio -- An absolute class of pitches (element of Z12). data PitchClass = PitchClass Int deriving (Data, Typeable) instance Eq PitchClass where (==) (PitchClass a) (PitchClass b) = (Prelude.==) (mod a 12) (mod b 12) instance Enum PitchClass where toEnum intval = PitchClass $ mod intval 12 fromEnum (PitchClass p) = p instance Show PitchClass where show (PitchClass p) = ["A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"] !! (mod p 12) -- A relative change in pitches. data Interval = Interval Int --TODO Better show? deriving (Data, Typeable) instance Show Interval where show (Interval interval) = show interval --TODO How? Won't work with the other == instance Eq Interval where (==) (Interval a) (Interval b) = (Prelude.==) (mod a 12) (mod b 12) instance Ord Interval where (<=) (Interval a) (Interval b) = (Prelude.<=) (mod a 12) (mod b 12) instance Enum Interval where toEnum intval = Interval $ mod intval 12 fromEnum (Interval p) = p data Octave = Octave Int deriving (Eq, Ord, Data, Typeable) instance Show Octave where show (Octave o) = show o instance Enum Octave where toEnum = Octave fromEnum (Octave o) = o -- A pitchclass and an octave. data Pitch = Pitch PitchClass Octave deriving (Eq, Data, Typeable) instance Ord Pitch where (<=) (Pitch (PitchClass pc1) (Octave oct1)) (Pitch (PitchClass pc2) (Octave oct2)) = (Prelude.<=) (pc1 + (oct1 * 12)) (pc2 + (oct2 * 12)) instance Show Pitch where show (Pitch pc oct) = (show pc) ++ "@" ++ (show oct) -- Time is expressed as a fraction of a whole note. data Time = Time (Ratio Int) deriving (Eq, Data, Typeable) instance Show Time where show (Time rat) = (show (numerator rat)) ++ "/" ++ (show (denominator rat)) instance Ord Time where (<=) (Time t0) (Time t1) = (Prelude.<=) t0 t1 data Note = Note Pitch Time deriving (Eq, Data, Typeable) --TODO At some point we want to add the option for a rest in here as well. instance Show Note where show (Note pitch time) = (show pitch) ++ ":" ++ (show time) -- Chord datatype is represented as a root and a list of intervals from the root or a special case. -- The intervals are expected to be ordered and without repetition. data Chord = Harmony PitchClass [Interval] | Other String deriving (Eq, Data, Typeable) instance Show Chord where show (Harmony pc ints) = (show pc) ++ (show ints) show (Other str) = str data TimedChord = TimedChord Chord Time deriving (Eq, Data, Typeable) instance Show TimedChord where show (TimedChord chord time) = (show chord) ++ ":" ++ (show time) type ChordProgression = [Chord] type TimedChordProgression = [TimedChord] type NoteProgression = [Note] type ChordType = [Interval] --TODO should be a fully fledged Data, and should check conditions. hlArrayStr :: (Show a) => [a] -> String hlArrayStr arr = "[" ++ (intercalate " " (map show arr)) ++ "]" --Boilerplate to override default list show, to get HarmLang types to show values that can be interpreted. instance Show ChordType where show arr = hlArrayStr arr instance Show ChordProgression where --TODO TypeSynonymInstances? show arr = hlArrayStr arr instance Show TimedChordProgression where show arr = hlArrayStr arr instance Show NoteProgression where show arr = hlArrayStr arr
cyruscousins/HarmLang
src/HarmLang/Types.hs
mit
3,478
0
11
653
1,188
632
556
69
1
module MLUtil.Random ( ExtractIndices (eiC, eiIs, eiN) , choiceExtract , choiceExtractIndices , choiceExtractIndices' , extract , isValidExtractIndices , mkExtractIndices ) where import Control.Monad import MLUtil.Util import System.Random import Debug.Trace data ExtractIndices = ExtractIndices { eiC :: Int , eiN :: Int , eiIs :: [Int] } deriving Show -- |Make fixed c elements from n mkExtractIndices :: Int -> [Int] -> Maybe ExtractIndices mkExtractIndices n is = let ei = ExtractIndices (length is) n is in if isValidExtractIndices ei then Just ei else Nothing -- |Is extract indices value valid or not isValidExtractIndices :: ExtractIndices -> Bool isValidExtractIndices ei = helper (eiC ei) (eiN ei) (eiIs ei) where helper c n is | length is /= c = False | otherwise = helper' n is where helper' n (i : is) | i < 0 || i >= n = False | otherwise = helper' (n - 1) is helper' n [] = True -- |Extract elements extract :: ExtractIndices -> [a] -> Maybe ([a], [a]) extract ei values = helper (eiN ei) (eiIs ei) values where helper n is values | length values /= n = Nothing | otherwise = let (residual', xs') = foldr (\i (xs, ys) -> let Just (xs', x) = removeAt i xs in (xs', x : ys)) (values, []) (reverse is) in Just (residual', reverse xs') -- |Random choice of c elements from n -- TODO: Rename to choiceExtractIndicesIO choiceExtractIndices :: Int -> Int -> Maybe (IO ExtractIndices) choiceExtractIndices c n | c < 0 || n < 0 || c > n = Nothing | c == 0 = (Just . return) $ ExtractIndices c n [] | otherwise = Just $ do is <- foldM (\xs i -> randomRIO (0, i) >>= \x -> return $ x : xs) [] [0 .. c - 1] return $ ExtractIndices c n is -- |Random choice of c elements from n -- TODO: Rename to choiceExtractIndices -- TODO: Consolidate with choiceExtractIndices choiceExtractIndices' :: RandomGen g => g -> Int -> Int -> Maybe (ExtractIndices, g) choiceExtractIndices' g c n | c < 0 || n < 0 || c > n = Nothing | c == 0 = Just (ExtractIndices c n [], g) | otherwise = let (is, g') = foldl (\(xs, g) i -> let (x, g') = randomR (0, i) g in (x : xs, g')) ([], g) [0 .. c - 1] in Just (ExtractIndices c n is, g') -- |Removes and returns n random elements from list choiceExtract :: Int -> [a] -> IO (Maybe ([a], [a])) choiceExtract c values = do case choiceExtractIndices c (length values) of Nothing -> return Nothing Just action -> action >>= \ei -> return (extract ei values)
rcook/mlutil
mlutil/src/MLUtil/Random.hs
mit
2,875
0
20
949
1,026
533
493
66
2
{-# LANGUAGE RecordWildCards #-} import Data.Foldable (for_) import GHC.Exts (fromList, toList) import Test.Hspec (Spec, describe, it, shouldMatchList) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import Anagram (anagramsFor) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "anagramsFor" $ for_ cases test where test Case{..} = it description $ expression `shouldMatchList` expected where expression = map toList . toList . anagramsFor (fromList subject) . fromList . map fromList $ candidates data Case = Case { description :: String , subject :: String , candidates :: [String] , expected :: [String] } cases :: [Case] cases = [ Case { description = "no matches" , subject = "diaper" , candidates = [ "hello", "world", "zombies", "pants"] , expected = [] } , Case { description = "detects two anagrams" , subject = "master" , candidates = ["stream", "pigeon", "maters"] , expected = ["stream", "maters"] } , Case { description = "does not detect anagram subsets" , subject = "good" , candidates = ["dog", "goody"] , expected = [] } , Case { description = "detects anagram" , subject = "listen" , candidates = ["enlists", "google", "inlets", "banana"] , expected = ["inlets"] } , Case { description = "detects three anagrams" , subject = "allergy" , candidates = ["gallery", "ballerina", "regally", "clergy", "largely", "leading"] , expected = ["gallery", "regally", "largely"] } , Case { description = "does not detect non-anagrams with identical checksum" , subject = "mass" , candidates = ["last"] , expected = [] } , Case { description = "detects anagrams case-insensitively" , subject = "Orchestra" , candidates = ["cashregister", "Carthorse", "radishes"] , expected = ["Carthorse"] } , Case { description = "detects anagrams using case-insensitive subject" , subject = "Orchestra" , candidates = ["cashregister", "carthorse", "radishes"] , expected = ["carthorse"] } , Case { description = "detects anagrams using case-insensitive possible matches" , subject = "orchestra" , candidates = ["cashregister", "Carthorse", "radishes"] , expected = ["Carthorse"] } , Case { description = "does not detect a anagram if the original word is repeated" , subject = "go" , candidates = ["go Go GO"] , expected = [] } , Case { description = "anagrams must use all letters exactly once" , subject = "tapper" , candidates = ["patter"] , expected = [] } , Case { description = "words are not anagrams of themselves (case-insensitive)" , subject = "BANANA" , candidates = ["BANANA", "Banana", "banana"] , expected = [] } ] -- 6227f55f7cd0567e01fef54561e0511ff8331f41
exercism/xhaskell
exercises/practice/anagram/test/Tests.hs
mit
3,772
0
15
1,543
732
458
274
70
1
module Main where import Language.Java.Lexer import Language.Java.Parser import System.Environment import System.IO main :: IO () main = getArgs >>= lexAndParse lexAndParse :: [String] -> IO () lexAndParse [fs] = do content <- readFile fs let tokens = lexJava content writeFile (fs ++ ".tok") (show tokens) let parsed = parseTokens tokens writeFile (fs ++ ".pt") (show parsed) lexAndParse ["lexonly", fs] = do content <- readFile fs let tokens = lexJava content writeFile (fs ++ ".tok") (show tokens) lexAndParse _ = putStrLn "Usage : jasper <file.java>"
evansb/jasper
src/Main.hs
mit
625
0
10
154
217
108
109
19
1
{-# LANGUAGE Rank2Types #-} module Control.SimpleLens where import Data.Functor.Identity -- Grab a few things from Control.Lens so that we don't incur the dependency {- Copyright 2012-2013 Edward Kmett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} type Lens' s a = forall f. Functor f => (a -> f a) -> s -> f s over :: Lens' s a -> (a -> a) -> s -> s over l f = runIdentity . l (Identity . f) set :: Lens' s a -> a -> s -> s set l b = runIdentity . l (\_ -> Identity b)
asivitz/layer
Control/SimpleLens.hs
mit
1,857
0
10
336
159
85
74
8
1
module Part1 where import Control.Monad import Data.Char data StudentInfo = StudentInfo { name :: String, korScore :: Int, engScore :: Int, matScore :: Int } deriving (Show) type StudentInfos = [StudentInfo] main :: IO () main = start [] start :: StudentInfos -> IO () start studentInfos = do printMenu input <- getLine s <- play (read input) studentInfos Control.Monad.unless (read input == 3) $ start s printMenu :: IO () printMenu = do putStrLn "\n- Menu Select -" putStrLn " 1. Input Student's grade" putStrLn " 2. Print Student's grade" putStrLn " 3. Exit\n" putStr "Select : " return () play :: Int -> StudentInfos -> IO StudentInfos play n studentInfos | n == 1 = readStudentInformation studentInfos | n == 2 = do printScoreTable studentInfos return studentInfos | n == 3 = return studentInfos | otherwise = do putStrLn "\nInvalid number! Try again.\n" return studentInfos readStudentInformation :: StudentInfos -> IO StudentInfos readStudentInformation studentInfos = do putStr "> Name : " name <- getLine putStr "> Korean : " koreanScore <- getLine putStr "> English : " englishScore <- getLine putStr "> Math : " mathScore <- getLine let updated = StudentInfo name (read koreanScore) (read englishScore) (read mathScore):studentInfos putStr "> Do you continue to input (Y/N)? " answer <- getLine if map toUpper answer == "Y" then readStudentInformation updated else return updated printScoreTable :: StudentInfos -> IO () printScoreTable studentInfos = do putStrLn "Name\t\tKor\tEng\tMath\tSum\tAvg\tRank" putStrLn "=========================================================" mapM_ (putStrLn . (`makeInfo` rankResult)) studentInfos putStrLn "=========================================================" putStrLn $ "Sum\t\t" ++ show (sumOfKorScore studentInfos) ++ "\t" ++ show (sumOfEngScore studentInfos) ++ "\t" ++ show (sumOfMatScore studentInfos) ++ "\t" ++ show (sumOfTotalScore studentInfos) putStrLn $ "Avg\t\t" ++ show (avgOfKorScore studentInfos) ++ "\t" ++ show (avgOfEngScore studentInfos) ++ "\t" ++ show (avgOfMatScore studentInfos) ++ "\t" ++ show (avgOfTotalScore studentInfos) where rankResult = (qsort . sums) studentInfos makeInfo :: StudentInfo -> [Int] -> String makeInfo info rankResult = name info ++ "\t\t" ++ show (korScore info) ++ "\t" ++ show (engScore info) ++ "\t" ++ show (matScore info) ++ "\t" ++ show totalSum ++ "\t" ++ show (average info) ++ "\t" ++ show (rank rankResult totalSum) where totalSum = sum' info -- studentInfos :: StudentInfos -- studentInfos = [ StudentInfo { name = "John", korScore = 96, engScore = 92, matScore = 98 }, -- StudentInfo { name = "Chris", korScore = 88, engScore = 90, matScore = 68 }, -- StudentInfo { name = "James", korScore = 98, engScore = 80, matScore = 75 }, -- StudentInfo { name = "Tom", korScore = 64, engScore = 70, matScore = 72 }, -- StudentInfo { name = "Jane", korScore = 80, engScore = 88, matScore = 94 } -- ] sum' :: StudentInfo -> Int sum' (StudentInfo _ korScore engScore matScore) = korScore + engScore + matScore sums :: StudentInfos -> [Int] sums = map sum' average :: StudentInfo -> Float average info = fromIntegral (sum' info) / 3.0 rank :: [Int] -> Int -> Int rank xs index = 1 + findIndex xs index qsort :: Ord a => [a] -> [a] qsort [] = [] qsort (x:xs) = qsort [a | a <- xs, a > x] ++ x : qsort [a | a <- xs, x >= a] findIndex :: [Int] -> Int -> Int findIndex (x:xs) index | x == index = 0 | otherwise = 1+ findIndex xs index sumOfKorScore :: StudentInfos -> Int sumOfKorScore = foldr (\(StudentInfo _ korScore _ _) acc -> korScore + acc) 0 sumOfEngScore :: StudentInfos -> Int sumOfEngScore = foldr (\(StudentInfo _ _ engScore _) acc -> engScore + acc) 0 sumOfMatScore :: StudentInfos -> Int sumOfMatScore = foldr (\(StudentInfo _ _ _ matScore) acc -> matScore + acc) 0 sumOfTotalScore :: StudentInfos -> Int sumOfTotalScore = foldr (\info acc -> sum' info + acc) 0 avgOfKorScore :: StudentInfos -> Float avgOfKorScore info = fromIntegral (sumOfKorScore info) / fromIntegral (length info) avgOfEngScore :: StudentInfos -> Float avgOfEngScore info = fromIntegral (sumOfEngScore info) / fromIntegral (length info) avgOfMatScore :: StudentInfos -> Float avgOfMatScore info = fromIntegral (sumOfMatScore info) / fromIntegral (length info) avgOfTotalScore :: StudentInfos -> Float avgOfTotalScore info = fromIntegral (sumOfTotalScore info) / fromIntegral (length info * 3)
utilForever/ProgrammingPractice
Solutions/MoNaDDu/Grade Management System/2/Part2.hs
mit
4,782
0
18
1,106
1,443
706
737
93
2
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-} {-| GDP and infant mortality <http://vincentarelbundock.github.io/Rdatasets/doc/car/UN.html> -} module Numeric.Datasets.UN where import Numeric.Datasets import Data.Csv import GHC.Generics import Control.Applicative data GdpMortality = GdpMortality { country :: String , infantMortality :: Maybe Int , gdp :: Maybe Int } deriving (Show, Read, Generic) instance FromNamedRecord GdpMortality where parseNamedRecord m = GdpMortality <$> m .: "" <*> (m .: "infant.mortality" <|> return Nothing) <*> (m .: "gdp" <|> return Nothing) gdpMortalityUN :: Dataset GdpMortality gdpMortalityUN = csvHdrDataset $ URL "http://vincentarelbundock.github.io/Rdatasets/csv/car/UN.csv"
glutamate/datasets
datasets/src/Numeric/Datasets/UN.hs
mit
816
0
10
182
157
86
71
19
1
module MiniCore.Transforms.Lambdas ( liftLambdas ) where import MiniCore.Types import MiniCore.Transforms.Utils import qualified Data.Set as Set import qualified Data.Map as Map import Control.Monad.State import Control.Applicative import Data.List (partition, foldl') -- Lift lambdas to top level as supercombinators and turn free variables into -- extra formal parameters liftLambdas :: Program -> Stage Program liftLambdas program = collectCombinators =<< rename =<< abstract =<< freeVars program -- Partially apply lambda expressions to pass in "free" variables abstract :: FVProgram -> Stage Program abstract = mapM abstract' where abstract' (name, args, body) = Combinator name args <$> walk body walk :: FVExpr -> Stage Expr walk (free, AVar v) = return (Var v) walk (free, ANum n) = return (Num n) walk (free, ACons tag arity) = return (Cons tag arity) walk (free, AApp e1 e2) = App <$> walk e1 <*> walk e2 walk (free, ALet recursive defs body) = do let names = bindersOf defs exprs <- mapM walk (bindeesOf defs) body' <- walk body return (Let recursive (zip names exprs) body') walk (free, ACase expr alts) = let walkAlt (tag, args, rhs) = (,,) tag args <$> walk rhs in Case <$> walk expr <*> mapM walkAlt alts walk (free, ALambda args body) = do body' <- walk body let vars = Set.toList free rhs = Lambda (vars ++ args) body' sc = Let False [(lambda, rhs)] (Var lambda) return (foldl' App sc (map Var vars)) -- Wrap an integer used to generate new names data NameSupply = NameSupply { suffix :: Int } -- Keep track of name supply and be able to throw an error type Lift a = StateT NameSupply Stage a -- Generate a new name from the NameSupply fresh :: Name -> Lift Name fresh name = do n <- gets suffix modify (\s -> s { suffix = n + 1 }) return (name ++ "_$" ++ show n) -- Prefix for lifted lambdas lambda = "$lambda" -- Do we need to rename this variable? shouldReplace :: Map.Map Name Name -> Name -> Bool shouldReplace env name = name `Map.member` env || name == lambda -- Take a list of old names and return a list of new names and a mapping -- from the old names to the new names newNames :: Map.Map Name Name -> [Name] -> Lift ([Name], Map.Map Name Name) newNames env [] = return ([], env) newNames env (x:xs) = do arg <- if shouldReplace env x then fresh x else return x let env' = Map.insert x arg env (args, env') <- newNames env' xs return (arg:args, env') -- Rename variables in the program that might clash rename :: Program -> Stage Program rename program = evalStateT (mapM renameSC program) $ NameSupply 1 where renameSC :: Declaration -> Lift Declaration renameSC (Combinator name args body) = do (args', env) <- newNames Map.empty args body' <- walk env body return (Combinator name args' body') walk :: Map.Map Name Name -> Expr -> Lift Expr walk env (Var v) = case Map.lookup v env of Just x -> return (Var x) Nothing -> return (Var v) walk env x@(Num _) = return x walk env x@(Cons _ _) = return x walk env (App e1 e2) = App <$> walk env e1 <*> walk env e2 walk env (Lambda args body) = do (args', env') <- newNames env args body' <- walk (env' `Map.union` env) body return (Lambda args' body') walk env (Let recursive defs body) = do let binders = bindersOf defs (binders', env') <- newNames env binders let bodyEnv = env' `Map.union` env body' <- walk bodyEnv body let rhsEnv | recursive = bodyEnv | otherwise = env rhs' <- mapM (walk rhsEnv) (bindeesOf defs) return (Let recursive (zip binders' rhs') body') walk env (Case expr alts) = Case <$> walk env expr <*> mapM (walkAlt env) alts walkAlt :: Map.Map Name Name -> Alt -> Lift Alt walkAlt env (tag, args, rhs) = do (args', env') <- newNames env args rhs' <- walk (env' `Map.union` env) rhs return $ (tag, args', rhs') -- Keep track of new combinators type Collect a = StateT [Declaration] Stage a -- Find lambda expressions and promote them to supercombinators collectCombinators :: Program -> Stage Program collectCombinators = liftM concat . mapM go where go :: Declaration -> Stage Program go c = execStateT (collectCombinator c) [] collectCombinator :: Declaration -> Collect () collectCombinator (Combinator name args body) = do body' <- walk body modify (\cs -> Combinator name args body':cs) walk :: Expr -> Collect Expr walk (App e1 e2) = App <$> walk e1 <*> walk e2 walk (Lambda args body) = Lambda args <$> walk body walk (Case expr alts) = Case <$> walk expr <*> mapM walkAlt alts walk (Let recursive defs body) = do defs' <- mapM walkDef defs body' <- walk body let (combinators, bindings) = partition (isLambda . snd) defs' lifted = map toCombinator combinators modify (\cs -> lifted ++ cs) case bindings of [] -> return body' _ -> return $ Let recursive bindings body' walk x = return x walkDef :: (Name, Expr) -> Collect (Name, Expr) walkDef (name, expr) = (,) name <$> walk expr walkAlt :: Alt -> Collect Alt walkAlt (tag, args, rhs) = (,,) tag args <$> walk rhs isLambda :: Expr -> Bool isLambda (Lambda _ _) = True isLambda _ = False toCombinator :: (Name, Expr) -> Declaration toCombinator (name, Lambda args body) = Combinator name args body
cdparks/mini-core
src/MiniCore/Transforms/Lambdas.hs
mit
5,495
0
14
1,354
2,081
1,043
1,038
133
8
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE RankNTypes #-} {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} module Data.Histogram.Util where import Control.Foldl (fold) import qualified Control.Foldl as L import Data.Histogram (Histogram) import qualified Data.Histogram as H import Data.Histogram.Fill import Data.Monoid import qualified Data.Vector.Unboxed as V import Statistics.Distribution import qualified Statistics.Distribution.Combo as OC import Statistics.Distribution.Exponential import Statistics.Distribution.Gamma import qualified Statistics.Distribution.Laplace as OL import Statistics.Distribution.Normal import Statistics.Distribution.Poisson bin :: BinD bin = binDn (-10.5) 1 10.5 hist :: BinD -> V.Vector Double -> H.Histogram BinD Double hist b = fillBuilderVec (forceDouble -<< mkSimple b) -- | make a percentile histogram perc :: Histogram BinD Double -> Histogram BinD Double perc h = H.map (\x -> x / H.sum h) h -- reversing out mean and stdev -- calculating mean using the trick that the Bin boundaries are constructed to be isomorphic to actual values meanH :: Histogram BinD Double -> Double meanH h = let t = H.sum h in H.bfoldl step begin h / t where begin = 0.0 step b bv v = b + bv * v meanSqH :: Histogram BinD Double -> Double meanSqH h = let t = H.sum h in H.bfoldl step begin h / t where begin = 0.0 step b bv v = b + (bv ^ (2 :: Int)) * v type Pdf = BinD -> [Double] -> V.Vector Double pdfBin :: (Double -> Double) -> BinD -> V.Vector Double pdfBin cdf h = V.map (\(x,y) -> cdf y - cdf x) binsV where binsV = binsList h :: V.Vector (Double,Double) pdfBinNormal :: Pdf pdfBinNormal b [] = pdfBin (cumulative $ normalDistr 0.0 1.0) b pdfBinNormal b [s] = pdfBin (cumulative $ normalDistr 0.0 s') b where s' = max 1.0e-5 s pdfBinNormal b (m:s:_) = pdfBin (cumulative $ normalDistr m s') b where s' = max 1.0e-5 s pdfBinLaplace :: Pdf pdfBinLaplace b (r:l:sl:glue:_) = pdfBin (cumulative $ OL.laplace r' l' sl' glue) b where l' = max 1.0e-5 l r' = max 1.0e-5 r sl' = max 1.0e-4 sl pdfBinLaplace _ _ = mempty pdfBinExponential :: Pdf pdfBinExponential b (e:_) = pdfBin (cumulative $ exponential e') b where e' = max 1.0e-5 e pdfBinExponential _ _ = mempty pdfBinPoisson :: Pdf pdfBinPoisson b (e:_) = pdfBin (cumulative $ poisson e') b where e' = max 1.0e-5 e pdfBinPoisson _ _ = mempty pdfBinGamma :: Pdf pdfBinGamma b (m:k:v:_) = V.map (m *) $ pdfBin (cumulative $ gammaDistr k' v') b where k' = max 1.0e-5 k v' = max 1.0e-5 v pdfBinGamma _ _ = mempty pdfBinCombo :: Pdf pdfBinCombo b (split:m:s:r:l:sl:_) = pdfBin (cumulative $ OC.combo split' m s' r' l' sl') b where split' = max 1.0e-5 split s' = max 1.0e-5 s l' = max 1.0e-5 l r' = max 1.0e-5 r sl' = max 1.0e-4 sl pdfBinCombo _ _ = mempty err :: Histogram BinD Double -> Pdf -> [Double] -> Double err h pdf p = do let pdfT = pdf (H.bins h) p pdfE = H.histData (perc h) errV = zipWith (-) (V.toList pdfE) (V.toList pdfT) err' = fold L.sum (fmap abs errV) err'
tonyday567/maths-extended
src/Data/Histogram/Util.hs
mit
3,408
0
13
930
1,211
635
576
114
1
xor :: [Bool] -> Bool xor = foldr ((==) . const False) False . filter (== True) fun1 :: [Integer] -> Integer fun1 [] = 1 fun1 (x:xs) | even x = (x - 2) * fun1 xs | otherwise = fun1 xs fun1' :: [Integer] -> Integer fun1' = product . map (subtract 2) . filter even fun2 :: Integer -> Integer fun2 1 = 0 fun2 n | even n = n + fun2 (n `div` 2) | otherwise = fun2 (3 * n + 1) fun2' :: Integer -> Integer fun2' = sum . filter even . takeWhile (/=1) . iterate (\n -> if even n then n `div` 2 else 3 * n + 1) map' :: (a -> b) -> [a] -> [b] -- map' f = foldr (\x y -> (f x):y) [] -- (\x y -> f x : y) can be written like this: (\x -> (:) (f x)). -- which we can further reduce to: ((:) . f) map' f = foldr ((:) . f) [] data Tree a = Leaf | Node Integer (Tree a) a (Tree a) deriving (Show, Eq) foldTree :: Eq a => [a] -> Tree a foldTree xs = foldr (insert first) Leaf xs where first = floor (logBase 2 $ fromIntegral(length xs)::Double) insert :: Int -> a -> Tree a -> Tree a insert _ _ _ = Leaf
tamasgal/haskell_exercises
CIS-194/homework-04/HW04.hs
mit
1,045
0
12
293
505
262
243
26
2
{-# LANGUAGE StandaloneDeriving, DeriveGeneric, TypeSynonymInstances, FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Core.Context( GameSession , GameWire , GameWireI , GameMonad , GameActor , GameContext , EventManager(..) , InputEvent(..) , ClientContext(..) , newEventManager , getEventMng , putEventMng -- | Resource management (background loading) , ClientResourceManager(..) , ResourceId , ResourceTQueue , getResourceMng , putResourceMng , updateResourceMng , enqueuResourceLoader , enqueuResourceLoaderSync , runResourceLoaders , readResourceResults , getNextResourceMngCounter -- | Viewport API , viewportSizeM , viewportSize ) where import Core.Monad import Core.Indexed import Core.Input import Assets.Manager import GHC.Generics (Generic) import Control.Monad.State.Strict import Control.DeepSeq import Data.Dynamic import Control.Concurrent.STM.TQueue import qualified Data.HashMap.Strict as H import System.IO.Unsafe (unsafePerformIO) import Util.Concurrent import qualified Data.Foldable as F import Data.Vec(Vec2) import Util.Vec() import Network.Protocol.Message import Data.Text (Text) type GameContext = GameContextG ClientContext type GameMonad a = GameMonadG ClientContext a type GameWire a b = GameWireG ClientContext a b type GameWireI a b = GameWireGI ClientContext a b type GameActor i a b = GameActorG ClientContext i a b instance GameContextClass ClientContext where newCustomContext = newClientContext -- | Context specific for client data ClientContext = ClientContext { -- | Current asset manager clientResMng :: !ClientResourceManager -- | Current event manager , clientEventMng :: !EventManager -- | Current size of vieport , clientViewportSize :: !(Vec2 Int) -- | Is cursor locked? , clientCursorLock :: Bool } deriving (Generic) instance NFData ClientContext newClientContext :: ClientContext newClientContext = ClientContext newClientResourceManager newEventManager 0 False -- =========================================================================== -- Resource management (background loading) -- | Id of resource -- Each resource acquires an unique id to find it -- when loaded. type ResourceId = Int type ResourceTQueue = TQueue (ResourceId, Either Text Dynamic, ResourceManager) instance NFData ResourceTQueue where rnf = (`seq` ()) data ClientResourceManager = ClientResourceManager { -- | Current resource manager clientResMngInner :: !ResourceManager -- | Client channel where resource loaders loads resources to and -- game engine gets resulted resources from. , clientResMngTQueue :: !ResourceTQueue -- | Stack of queued actions to load resources -- All actions are executed in separate thread and should -- emit resulted resource into TQueue , clientResMngStack :: ![ResourceManager -> ResourceTQueue -> IO ()] -- | Stack of queued actions to modify resource manager (e.x. register resource pack) -- all actions in this queue should perform before ones from clientResMngStack , clientResMngStackSynch :: ![ResourceManager -> IO ResourceManager] -- | Stack of finished resources , clientResMngFinished :: !(H.HashMap ResourceId (Either Text Dynamic)) -- | Counter that holds next id off resource , clientResMngCounter :: ResourceId } deriving (Generic) instance NFData ClientResourceManager -- | Creates semantically empty client resource manager newClientResourceManager :: ClientResourceManager newClientResourceManager = ClientResourceManager { clientResMngInner = emptyResourceManager , clientResMngTQueue = unsafePerformIO newTQueueIO , clientResMngStack = [] , clientResMngStackSynch = [] , clientResMngFinished = H.empty , clientResMngCounter = 0 } -- | Returns current client resource manager getResourceMng :: GameMonad ClientResourceManager getResourceMng = fmap (clientResMng . gameCustomContext) get -- | Sets current client resource manager putResourceMng :: ClientResourceManager -> GameMonad () putResourceMng rmng = do cntx <- get put $ cntx { gameCustomContext = (gameCustomContext cntx) { clientResMng = rmng } } -- | Helper function that updates current client resource manager with f updateResourceMng :: (ClientResourceManager -> ClientResourceManager) -> GameMonad () updateResourceMng f = putResourceMng =<< (f <$> getResourceMng) -- | Places resource loading action into queue -- The loader should load desired resource and place it into -- concurrent channel-queue passed as first parameter. enqueuResourceLoader :: (ResourceManager -> ResourceTQueue -> IO ()) -> GameMonad () enqueuResourceLoader loader = do updateResourceMng $ \mng -> mng { clientResMngStack = loader : (clientResMngStack mng) } -- | Place resource manager updating action into queue -- The loader should update resource manager (e.x. register new resource pack) enqueuResourceLoaderSync :: (ResourceManager -> IO ResourceManager) -> GameMonad () enqueuResourceLoaderSync loader = do updateResourceMng $ \mng -> mng { clientResMngStackSynch = loader : (clientResMngStackSynch mng) } -- | Executes all enqueued resource loaders -- Note: list of actions are cleaned after call of this function runResourceLoaders :: ClientResourceManager -> IO ClientResourceManager runResourceLoaders mng = do imng' <- F.foldrM ($) (clientResMngInner mng) (clientResMngStackSynch mng) forM_ (clientResMngStack mng) $ \loader -> loader imng' (clientResMngTQueue mng) -- Cannot use forkIO due OpenGL resource loading bug return $ mng { clientResMngInner = imng' , clientResMngStack = [] , clientResMngStackSynch = [] } -- | Checks results of resource loading -- Note: old results are overwritten with new, as events should capture result -- as soon as it appears in result set. readResourceResults :: ClientResourceManager -> IO ClientResourceManager readResourceResults mng = do res <- readTQueueWhileCould $ clientResMngTQueue mng let (pairs, mngs) = foldl (\(acc1, acc2) (a, b, c) -> ((a,b):acc1, c:acc2)) ([], []) res let newInner = mconcat (clientResMngInner mng : mngs) return $ mng { clientResMngInner = newInner , clientResMngFinished = H.fromList pairs } -- | Returns next index and saves update counter at context getNextResourceMngCounter :: GameMonad ResourceId getNextResourceMngCounter = do mng <- getResourceMng putResourceMng $ mng { clientResMngCounter = clientResMngCounter mng + 1 } return $ clientResMngCounter mng -- ==================================================================== -- Event manager definition -- | TODO: OutputEvent for manual disconnects data EventManager = EventManager { -- | Holds network messages from server eventMngNetMessages :: ![NetworkMessage] -- | Holds other input events for simulation , eventMngInputEvents :: ![InputEvent] -- | Holds messages that should be sent to client side -- Note: first message in list - the last message in time , eventMngMessages2Send :: ![NetworkMessage] } deriving (Generic) instance NFData EventManager newEventManager :: EventManager newEventManager = EventManager [] [] [] getEventMng :: GameMonad EventManager getEventMng = fmap (clientEventMng . gameCustomContext) get putEventMng :: EventManager -> GameMonad () putEventMng emng = do cntx <- get put $ cntx { gameCustomContext = (gameCustomContext cntx) { clientEventMng = emng } } -- Viewport API -- ============================================================ -- | Returns current viewport size viewportSizeM :: GameMonad (Vec2 Int) viewportSizeM = fmap (clientViewportSize . gameCustomContext) get -- | Returns current viewport size viewportSize :: GameWire a (Vec2 Int) viewportSize = liftGameMonad viewportSizeM
NCrashed/sinister
src/client/Core/Context.hs
mit
7,798
0
15
1,280
1,435
820
615
162
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} module Data.Tuple.PolyParts.List where import Data.Tuple.PolyParts.OneTuple (OneTuple (..)) import Prelude (error) import Data.Tuple.PolyParts.Modification (extendTupleR, TupleExtendedR, TupleExtendR) -- | This module provide easy convertion to list and from list: -- -- @ -- tupleToList ("d","s") == ["d","s"] -- stepTFromList . stepTFromList $ ( (), ["d","s"] ) == ( ("d","s") , [] ) -- @ -- -- -- | One step to convert list to tuple. It extend tuple to right the head of list and remain tail of list. If list is empty function throw an error -- -- @ -- stepTFromList ( (), ["s","d","f"] ) == ( OneTuple "s", ["d","f"] ) -- @ -- -- Function could replicated: -- -- @ -- stepTFromList . stepTFromList . stepTFromList $ ( (), ["s","d","f"] ) == ( ("s","d","f"), [] ) -- @ -- stepTFromList :: TupleExtendR a b => (a, [b]) -> (TupleExtendedR a b, [b]) stepTFromList (t, (x:xs)) = (t `extendTupleR` x, xs) stepTFromList (t, []) = error "stepTFromList: empty list" --type MonoTuple0 a = () type MonoTuple1 a = OneTuple a type MonoTuple2 a = (a, a) type MonoTuple3 a = (a, a, a) type MonoTuple4 a = (a, a, a, a) type MonoTuple5 a = (a, a, a, a, a) type MonoTuple6 a = (a, a, a, a, a, a) type MonoTuple7 a = (a, a, a, a, a, a, a) type MonoTuple8 a = (a, a, a, a, a, a, a, a) type MonoTuple9 a = (a, a, a, a, a, a, a, a, a) type MonoTuple10 a = (a, a, a, a, a, a, a, a, a, a) type MonoTuple11 a = (a, a, a, a, a, a, a, a, a, a, a) type MonoTuple12 a = (a, a, a, a, a, a, a, a, a, a, a, a) type MonoTuple13 a = (a, a, a, a, a, a, a, a, a, a, a, a, a) type MonoTuple14 a = (a, a, a, a, a, a, a, a, a, a, a, a, a, a) type MonoTuple15 a = (a, a, a, a, a, a, a, a, a, a, a, a, a, a, a) -- | tupleToList converts mono-tuple to list -- -- @ -- tupleToList ("s","d","f") == ["s","d","f"] -- tupleToList ('H','e','l','l','o') == "Hello" -- tupleToList ((1,2) :: Num a => (a,a)) == [1,2] :: Num a => [a] -- @ -- class TupleFromList a where type PartTupleList a tupleFromList :: [PartTupleList a] -> a instance (PartTupleList a ~ a) => TupleFromList (MonoTuple1 a) where type PartTupleList (MonoTuple1 a) = a tupleFromList (a:_) = OneTuple a tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple1" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple2 a) where type PartTupleList (MonoTuple2 a) = a tupleFromList (a:b:_) = (a, b) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple2" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple3 a) where type PartTupleList (MonoTuple3 a) = a tupleFromList (a1:a2:a3:_) = (a1, a2, a3) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple3" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple4 a) where type PartTupleList (MonoTuple4 a) = a tupleFromList (a1:a2:a3:a4:_) = (a1, a2, a3, a4) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple4" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple5 a) where type PartTupleList (MonoTuple5 a) = a tupleFromList (a1:a2:a3:a4:a5:_) = (a1, a2, a3, a4, a5) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple5" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple6 a) where type PartTupleList (MonoTuple6 a) = a tupleFromList (a1:a2:a3:a4:a5:a6:_) = (a1, a2, a3, a4, a5, a6) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple6" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple7 a) where type PartTupleList (MonoTuple7 a) = a tupleFromList (a1:a2:a3:a4:a5:a6:a7:_) = (a1, a2, a3, a4, a5, a6, a7) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple7" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple8 a) where type PartTupleList (MonoTuple8 a) = a tupleFromList (a1:a2:a3:a4:a5:a6:a7:a8:_) = (a1, a2, a3, a4, a5, a6, a7, a8) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple8" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple9 a) where type PartTupleList (MonoTuple9 a) = a tupleFromList (a1:a2:a3:a4:a5:a6:a7:a8:a9:_) = (a1, a2, a3, a4, a5, a6, a7, a8, a9) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple9" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple10 a) where type PartTupleList (MonoTuple10 a) = a tupleFromList (a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:_) = (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple10" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple11 a) where type PartTupleList (MonoTuple11 a) = a tupleFromList (a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:_) = (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple11" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple12 a) where type PartTupleList (MonoTuple12 a) = a tupleFromList (a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:_) = (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple12" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple13 a) where type PartTupleList (MonoTuple13 a) = a tupleFromList (a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:_) = (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple13" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple14 a) where type PartTupleList (MonoTuple14 a) = a tupleFromList (a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:a14:_) = (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple14" instance (PartTupleList a ~ a) => TupleFromList (MonoTuple15 a) where type PartTupleList (MonoTuple15 a) = a tupleFromList (a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:a14:a15:_) = (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) tupleFromList _ = error "TupleToList: not enoght elements in list for MonoTuple15" -- | tupleToList converts mono-tuple to list -- -- @ -- tupleToList ("s","d","f") == ["s","d","f"] -- tupleToList ('H','e','l','l','o') == "Hello" -- tupleToList ((1,2) :: Num a => (a,a)) == [1,2] :: Num a => [a] -- @ -- class TupleToList a where type PartTupleMono a tupleToList :: a -> [PartTupleMono a] instance (PartTupleMono () ~ () ) => TupleToList () where type PartTupleMono () = () tupleToList () = [] instance (PartTupleMono (OneTuple a) ~ a ) => TupleToList (OneTuple a) where type PartTupleMono (OneTuple a) = a tupleToList (OneTuple a) =[a] instance (PartTupleMono (a, a) ~ a ) => TupleToList (a, a) where type PartTupleMono (a, a) = a tupleToList (a, b) = [a, b] instance (PartTupleMono (a, a, a) ~ a ) => TupleToList (a, a, a) where type PartTupleMono (a, a, a) = a tupleToList (a1, a2, a3) = [a1, a2, a3] instance (PartTupleMono (a, a, a, a) ~ a ) => TupleToList (a, a, a, a) where type PartTupleMono (a, a, a, a) = a tupleToList (a1, a2, a3, a4) = [a1, a2, a3, a4] instance (PartTupleMono (a, a, a, a, a) ~ a ) => TupleToList (a, a, a, a, a) where type PartTupleMono (a, a, a, a, a) = a tupleToList (a1, a2, a3, a4, a5) = [a1, a2, a3, a4, a5] instance (PartTupleMono (a, a, a, a, a, a) ~ a ) => TupleToList (a, a, a, a, a, a) where type PartTupleMono (a, a, a, a, a, a) = a tupleToList (a1, a2, a3, a4, a5, a6) = [a1, a2, a3, a4, a5, a6] instance (PartTupleMono (a, a, a, a, a, a, a) ~ a ) => TupleToList (a, a, a, a, a, a, a) where type PartTupleMono (a, a, a, a, a, a, a) = a tupleToList (a1, a2, a3, a4, a5, a6, a7) = [a1, a2, a3, a4, a5, a6, a7] instance (PartTupleMono (a, a, a, a, a, a, a, a) ~ a ) => TupleToList (a, a, a, a, a, a, a, a) where type PartTupleMono (a, a, a, a, a, a, a, a) = a tupleToList (a1, a2, a3, a4, a5, a6, a7, a8) = [a1, a2, a3, a4, a5, a6, a7, a8] instance (PartTupleMono (a, a, a, a, a, a, a, a, a) ~ a ) => TupleToList (a, a, a, a, a, a, a, a, a) where type PartTupleMono (a, a, a, a, a, a, a, a, a) = a tupleToList (a1, a2, a3, a4, a5, a6, a7, a8, a9) = [a1, a2, a3, a4, a5, a6, a7, a8, a9] instance (PartTupleMono (a, a, a, a, a, a, a, a, a, a) ~ a ) => TupleToList (a, a, a, a, a, a, a, a, a, a) where type PartTupleMono (a, a, a, a, a, a, a, a, a, a) = a tupleToList (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10] instance (PartTupleMono (a, a, a, a, a, a, a, a, a, a, a) ~ a ) => TupleToList (a, a, a, a, a, a, a, a, a, a, a) where type PartTupleMono (a, a, a, a, a, a, a, a, a, a, a) = a tupleToList (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11] instance (PartTupleMono (a, a, a, a, a, a, a, a, a, a, a, a) ~ a ) => TupleToList (a, a, a, a, a, a, a, a, a, a, a, a) where type PartTupleMono (a, a, a, a, a, a, a, a, a, a, a, a) = a tupleToList (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) =[a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12] instance (PartTupleMono (a, a, a, a, a, a, a, a, a, a, a, a, a) ~ a ) => TupleToList (a, a, a, a, a, a, a, a, a, a, a, a, a) where type PartTupleMono (a, a, a, a, a, a, a, a, a, a, a, a, a) = a tupleToList (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13] instance (PartTupleMono (a, a, a, a, a, a, a, a, a, a, a, a, a, a) ~ a ) => TupleToList (a, a, a, a, a, a, a, a, a, a, a, a, a, a) where type PartTupleMono (a, a, a, a, a, a, a, a, a, a, a, a, a, a) = a tupleToList (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14] instance (PartTupleMono (a, a, a, a, a, a, a, a, a, a, a, a, a, a, a) ~ a ) => TupleToList (a, a, a, a, a, a, a, a, a, a, a, a, a, a, a) where type PartTupleMono (a, a, a, a, a, a, a, a, a, a, a, a, a, a, a) = a tupleToList (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15]
vww/easyTuples
Data/Tuple/PolyParts/List.hs
mit
10,701
8
22
2,491
4,979
2,981
1,998
140
1
{-# LANGUAGE ScopedTypeVariables #-} module Handler.Tutorial where import Import getTutorialShowR :: TutorialId -> Handler Html getTutorialShowR tutorialId = do tutorial <- runDB $ get404 tutorialId defaultLayout $ do $(widgetFile "tutorials/show")
lambdacms/lambdacms.org
lambdacmsorg-base/Handler/Tutorial.hs
mit
279
0
12
60
61
30
31
-1
-1
module Main where main :: IO () main = print (42 :: Int)
ruicc/structured-concurrent
examples/Example.hs
mit
58
0
6
14
28
16
12
3
1
{-# LANGUAGE OverloadedStrings #-} module Vaultaire.Collector.Nagios.Perfdata.Util where import Data.Bifunctor (bimap, second) import Data.Binary.IEEE754 (doubleToWord) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as C import qualified Data.HashMap.Strict as HashMap (fromList) import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Data.Word import Data.Nagios.Perfdata import Data.Nagios.Perfdata.Metric import Marquise.Client -- | Returns the Vaultaire SourceDict for the supplied metric in datum, -- or an error if the relevant values have invalid characters (',' or -- ':'). getSourceDict :: [(Text, Text)] -> Either String SourceDict getSourceDict = makeSourceDict . HashMap.fromList type MetricThresholds = (Threshold, Threshold, Threshold, Threshold) perfdatumToThresholds :: Perfdata -> [(String, MetricThresholds)] perfdatumToThresholds perfdata = map (second metricThresholds) metricList where metricList = perfdataMetrics perfdata metricThresholds m = (warnValue m, critValue m, minValue m, maxValue m) thresholdsToList :: MetricThresholds -> [(String, String)] thresholdsToList (warn, crit, minThreshold, maxThreshold) = foldl filterOutNoThreshold [] $ zip nagiosPerfdataKeys [warn, crit, minThreshold, maxThreshold] where filterOutNoThreshold acc (_, NoThreshold) = acc filterOutNoThreshold acc (k, DoubleThreshold v) = (k, show v):acc nagiosPerfdataKeys = [ "_nagios_warn", "_nagios_crit", "_nagios_min", "_nagios_max" ] -- | Builds an association list for conversion into a SourceDict buildList :: Perfdata -> String -> UOM -> Bool -> [(Text, Text)] buildList datum metricName uom normalise = convert $ concat [baseList, counter, unit, nagiosThresholds] where counter | uom == Counter = [("_counter", "1")] | otherwise = [] unit | normalise = [("_normalised", "1")] | otherwise = [] isInteresting = (== metricName) . fst interestingThresholds = map snd $ filter isInteresting $ perfdatumToThresholds datum nagiosThresholds = concatMap thresholdsToList interestingThresholds -- host, metricName and service are collectively the primary key for -- this metric. As the nagios-perfdata package currently treats -- all values as floats, we also specify this as metadata for -- the presentation layer. host = perfdataHostname datum service = C.unpack $ perfdataServiceDescription datum baseList = zip ["host", "metric", "service", "_float", "_uom"] [host, metricName, service, "1", show uom] convert = map $ bimap T.pack fmtTag fmtTag :: String -> Text fmtTag = T.pack . map ensureValid ensureValid :: Char -> Char ensureValid ',' = '-' ensureValid ':' = '-' ensureValid x = x -- | Returns the unique identifier for the named metric in the supplied -- perfdatum. This is used to calculate the address. getMetricId :: Perfdata -> String -> S.ByteString getMetricId datum metric = let host = perfdataHostname datum in let service = S.unpack $ perfdataServiceDescription datum in "host:" <> C.pack host <> ",metric:" <> C.pack metric <> ",service:" <> S.pack service <> "," -- | Returns the Vaultaire address for the specified metric. getAddress :: Perfdata -> String -> Address getAddress p = hashIdentifier . getMetricId p -- | Given a Perfdata object, extract each metric into a list of -- (address,value) tuples. unpackMetrics :: Perfdata -> [(Address, Either String Word64)] unpackMetrics datum = map (bimap (getAddress datum) extractValueWord) (perfdataMetrics datum) where extractValueWord :: Metric -> Either String Word64 extractValueWord m = if unknownMetricValue m then Left "unknown metric value" else Right . doubleToWord $ metricValueDefault m 0.0
anchor/vaultaire-collector-nagios
lib/Vaultaire/Collector/Nagios/Perfdata/Util.hs
mit
3,982
0
16
847
934
518
416
64
2
module Fourier_Motzkin.ToDoc where import Fourier_Motzkin.Data import Autolib.ToDoc import Data.Ratio import qualified Data.Map as M instance ToDoc v => ToDoc (Linear v) where toDoc (Linear m) = hsep $ do (mv,co) <- M.toList m let sign = if co>0 then text "+ " else empty co_times_var = case mv of Nothing -> toDoc co Just v -> (if co /= 1 then toDoc co <+> text "*" else empty ) <+> toDoc v return $ sign <> co_times_var instance ToDoc v => ToDoc (Atom v) where toDoc a = text "0" <+> (if strict a then text "<" else text "<=" ) <+> toDoc (linear a) instance ToDoc v => Show (Linear v) where show = render . toDoc instance ToDoc v => Show (Atom v) where show = render . toDoc
marcellussiegburg/autotool
collection/src/Fourier_Motzkin/ToDoc.hs
gpl-2.0
759
0
19
213
309
156
153
17
0
{-# LANGUAGE FlexibleInstances , TypeSynonymInstances #-} {- | Module : $Header$ Description : OMDoc-XML conversion Copyright : (c) Ewaryst Schulz, DFKI 2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable The transformation of the OMDoc intermediate representation to and from xml. The import from xml does not validate the xml, hence if you encounter strange errors, do not forget to check the xml structure first. -} module OMDoc.XmlInterface where import OMDoc.DataTypes import Common.Utils (splitBy) import Common.Result import Common.IRI (isUnescapedInIRI, escapeIRIString, unEscapeString) import Data.Maybe import Data.List import Control.Monad (liftM, when) import Common.XmlParser (XmlParseable, parseXml) import Text.XML.Light -- * Names and other constants -- | The implemented OMDoc version omdoc_current_version :: String omdoc_current_version = "1.6" toQN :: String -> QName toQN s = blank_name { qName = s } toQNOM :: String -> QName toQNOM s = blank_name { qName = s , qPrefix = Just "om" } -- | often used element names el_omdoc, el_theory, el_view, el_structure, el_type, el_adt, el_sortdef , el_constructor, el_argument, el_insort, el_selector, el_open, el_component , el_conass, el_constant, el_notation, el_text, el_definition, el_omobj , el_ombind, el_oms, el_ombvar, el_omattr, el_omatp, el_omv, el_oma :: QName el_omdoc = toQN "omdoc" el_theory = toQN "theory" el_view = toQN "view" el_structure = toQN "structure" el_type = toQN "type" el_adt = toQN "adt" el_sortdef = toQN "sortdef" el_constructor = toQN "constructor" el_argument = toQN "argument" el_insort = toQN "insort" el_selector = toQN "selector" el_conass = toQN "conass" el_open = toQN "open" el_constant = toQN "constant" el_notation = toQN "notation" el_text = toQN "text" el_definition = toQN "definition" el_component = toQN "component" el_omobj = toQN "OMOBJ" el_ombind = toQNOM "OMBIND" el_oms = toQNOM "OMS" el_ombvar = toQNOM "OMBVAR" el_omattr = toQNOM "OMATTR" el_omatp = toQNOM "OMATP" el_omv = toQNOM "OMV" el_oma = toQNOM "OMA" at_version, at_module, at_name, at_meta, at_role, at_type, at_total, at_for , at_from, at_to, at_value, at_base, at_as, at_precedence, at_fixity, at_index , at_associativity, at_style, at_implicit :: QName at_version = toQN "version" at_module = toQN "module" at_name = toQN "name" at_meta = toQN "meta" at_role = toQN "role" at_type = toQN "type" at_total = toQN "total" at_for = toQN "for" at_from = toQN "from" at_to = toQN "to" at_value = toQN "value" at_base = toQN "base" at_as = toQN "as" at_precedence = toQN "precedence" at_fixity = toQN "fixity" at_associativity = toQN "associativity" at_style = toQN "style" at_implicit = toQN "implicit" at_index = toQN "index" attr_om :: Attr attr_om = Attr (blank_name { qName = "om" , qPrefix = Just "xmlns" }) "http://www.openmath.org/OpenMath" -- * Top level from/to xml functions {- | This class defines the interface to read from and write to XML -} class XmlRepresentable a where -- | render instance to an XML Element toXml :: a -> Content -- | read instance from an XML Element fromXml :: Element -> Result (Maybe a) {- -- for testing the performance without the xml lib we use the show and read funs xmlOut :: Show a => a -> String xmlOut = show xmlIn :: String -> Result OMDoc xmlIn = return . read -} xmlOut :: XmlRepresentable a => a -> String xmlOut obj = case toXml obj of Elem e -> ppTopElement e c -> ppContent c xmlIn :: XmlParseable a => a -> IO (Result OMDoc) xmlIn s = do res <- parseXml s return $ case res of Right e -> fromXml e >>= maybe (fail "xmlIn") return Left msg -> fail msg listToXml :: XmlRepresentable a => [a] -> [Content] listToXml = map toXml listFromXml :: XmlRepresentable a => [Content] -> Result [a] listFromXml elms = fmap catMaybes $ mapR fromXml (onlyElems elms) mkElement :: QName -> [Attr] -> [Content] -> Content mkElement qn atts elems = Elem $ Element qn atts elems Nothing makeComment :: String -> Content makeComment s = Text $ CData CDataRaw ("<!-- " ++ s ++ " -->") Nothing inAContent :: QName -> [Attr] -> Maybe Content -> Content inAContent qn a c = mkElement qn a $ maybeToList c inContent :: QName -> Maybe Content -> Content inContent qn = inAContent qn [] toOmobj :: Content -> Content toOmobj c = inAContent el_omobj [attr_om] $ Just c -- * Encoding/Decoding {- url escaping and unescaping. We use ? and / as special characters, so we need them to be encoded in names -} urlEscape :: String -> String urlEscape = escapeIRIString isUnescapedInIRI urlUnescape :: String -> String urlUnescape = unEscapeString -- to- and from-string functions showCDName :: OMCD -> OMName -> String showCDName omcd omname = concat [showCD omcd, "?", showOMName omname] showCD :: OMCD -> String showCD cd = let [x, y] = cdToList cd in concat [x, "?", y] showOMName :: OMName -> String showOMName on = intercalate "/" $ path on ++ [name on] readCD :: Show a => a -> String -> OMCD readCD _ s = case splitBy '?' s of [b, cd] -> cdFromList [b, cd] _ -> error $ "readCD: The value " ++ "has to contain exactly one '?'" readCDName :: String -> OMQualName readCDName s = case splitBy '?' s of (b : cd : n : []) -> ( cdFromList [b, cd] , readOMName n) _ -> error $ "readCDName: The value " ++ "has to contain exactly two '?'" readOMName :: String -> OMName readOMName s = let l = splitBy '/' s in OMName (last l) $ init l -- encoding {- only uri-fields need to be %-encoded, the following attribs are uri-fields: theory@meta include@from structure@from view@from view@to @base -} tripleEncodeOMS :: OMCD -> OMName -> [Attr] tripleEncodeOMS omcd omname = pairEncodeCD omcd ++ [Attr at_name $ showOMName omname] pairEncodeCD :: OMCD -> [Attr] pairEncodeCD cd = let [base, modl] = cdToMaybeList cd in catMaybes [ fmap (Attr at_base . urlEscape) base , fmap (Attr at_module) modl] -- decoding tripleDecodeOMS :: String -> String -> String -> (OMCD, OMName) tripleDecodeOMS cd base nm = let cdl = filter (not . null) [cd, urlUnescape base] in if null cd && not (null base) then error "tripleDecodeOMS: base not empty but cd not given!" else (CD cdl, readOMName nm) warnIfNothing :: String -> (Maybe a -> b) -> Maybe a -> Result b warnIfNothing s f v = do warnIf s $ isNothing v return $ f v warnIf :: String -> Bool -> Result () warnIf s b = when b $ justWarn () s elemIsOf :: Element -> QName -> Bool elemIsOf e qn = let en = elName e in (qName en, qPrefix en) == (qName qn, qPrefix qn) oneOfMsg :: Element -> [QName] -> String oneOfMsg e l = let printName = qName in concat [ "Couldn't find expected element {" , intercalate ", " (map printName l), "}" , maybe "" ((" at line " ++) . show) (elLine e) , " but found ", printName $ elName e, "." ] -- * Monad and Maybe interaction justReturn :: Monad m => a -> m (Maybe a) justReturn = return . Just fmapMaybe :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b) fmapMaybe f v = encapsMaybe $ fmap f v fmapFromMaybe :: Monad m => (a -> m (Maybe b)) -> Maybe a -> m (Maybe b) fmapFromMaybe f = flattenMaybe . fmapMaybe f encapsMaybe :: Monad m => Maybe (m a) -> m (Maybe a) encapsMaybe v = case v of Just x -> x >>= justReturn _ -> return Nothing flattenMaybe :: Monad m => m (Maybe (Maybe a)) -> m (Maybe a) flattenMaybe = liftM (fromMaybe Nothing) {- | Function to extract the Just values from maybes with a default missing error in case of Nothing -} missingMaybe :: String -> String -> Maybe a -> a missingMaybe el misses = fromMaybe (error $ el ++ " element must have a " ++ misses ++ ".") -- -- -- -- -- XmlRepresentable Class instances for OMDoc types -- -- -- -- -- -- | The root instance for representing OMDoc in XML instance XmlRepresentable OMDoc where toXml (OMDoc omname elms) = mkElement el_omdoc [Attr at_version omdoc_current_version, Attr at_name omname] $ listToXml elms fromXml e | elemIsOf e el_omdoc = do nm <- warnIfNothing "No name in omdoc element." (fromMaybe "") $ findAttr at_name e vs <- warnIfNothing "No version in omdoc element." (fromMaybe "1.6") $ findAttr at_version e warnIf "Wrong OMDoc version." $ vs /= omdoc_current_version tls <- listFromXml $ elContent e justReturn $ OMDoc nm tls | otherwise = fail "OMDoc fromXml: toplevel element is no omdoc." -- | toplevel OMDoc elements to XML and back instance XmlRepresentable TLElement where toXml (TLTheory tname meta elms) = mkElement el_theory (Attr at_name tname : case meta of Nothing -> [] Just mtcd -> [Attr at_meta $ urlEscape $ showCD mtcd]) $ listToXml elms toXml (TLView nm from to morph) = mkElement el_view [Attr at_name nm, Attr at_from $ urlEscape $ showCD from, Attr at_to $ urlEscape $ showCD to] $ map assignmentToXml morph fromXml e | elemIsOf e el_theory = let nm = missingMaybe "Theory" "name" $ findAttr at_name e mt = fmap (readCD (elLine e) . urlUnescape) $ findAttr at_meta e in do tcl <- listFromXml $ elContent e justReturn $ TLTheory nm mt tcl | elemIsOf e el_view = let musthave at s = missingMaybe "View" s $ findAttr at e nm = musthave at_name "name" from = readCD (elLine e) $ urlUnescape $ musthave at_from "from" to = readCD (elLine e) $ urlUnescape $ musthave at_to "to" in do morph <- mapR xmlToAssignment (findChildren el_conass e) justReturn $ TLView nm from to morph | otherwise = return Nothing -- | theory constitutive OMDoc elements to XML and back instance XmlRepresentable TCElement where toXml (TCSymbol sname symtype role defn) = constantToXml sname (show role) symtype defn toXml (TCNotation (cd, nm) val mStl) = inAContent el_notation ( [Attr at_for $ urlEscape $ showCDName cd nm, Attr at_role "constant"] ++ maybe [] ((: []) . Attr at_style) mStl ) $ Just $ inAContent el_text [Attr at_value val] Nothing toXml (TCSmartNotation (cd, nm) fixity assoc prec implicit) = inAContent el_notation ( [ Attr at_for $ urlEscape $ showCDName cd nm , Attr at_role "application", Attr at_fixity $ show fixity , Attr at_precedence $ show prec ] ++ (if implicit == 0 then [] else [Attr at_implicit $ show implicit]) ++ (if assoc == NoneAssoc then [] else [Attr at_associativity $ show assoc]) ) Nothing toXml (TCFlexibleNotation (cd, nm) prec comps) = mkElement el_notation [ Attr at_for $ urlEscape $ showCDName cd nm, Attr at_role "application" , Attr at_precedence $ show prec ] $ map notationComponentToXml comps toXml (TCADT sds) = mkElement el_adt [] $ listToXml sds toXml (TCComment c) = makeComment c toXml (TCImport nm from morph) = mkElement el_structure [Attr at_name nm, Attr at_from $ urlEscape $ showCD from] $ map assignmentToXml morph fromXml e | elemIsOf e el_constant = let musthave = missingMaybe "Constant" nm = musthave "name" $ findAttr at_name e role = maybe Obj read $ findAttr at_role e in do typ <- fmap (musthave "typ") $ omelementFrom el_type e defn <- omelementFrom el_definition e justReturn $ TCSymbol nm typ role defn | elemIsOf e el_notation = let musthave = missingMaybe "Notation" nm = urlUnescape $ musthave "for" $ findAttr at_for e role = musthave "role" $ findAttr at_role e mStl = findAttr at_style e text = musthave "text" $ findChild el_text e val = musthave "value" $ findAttr at_value text in if role == "constant" then justReturn $ TCNotation (readCDName nm) val mStl else return Nothing | elemIsOf e el_structure = let musthave at s = missingMaybe "Structure" s $ findAttr at e nm = musthave at_name "name" from = readCD (elLine e) $ urlUnescape $ musthave at_from "from" in do morph <- mapR xmlToAssignment $ filterChildrenName (`elem` [el_conass, el_open]) e justReturn $ TCImport nm from morph | elemIsOf e el_adt = do sds <- listFromXml $ elContent e justReturn $ TCADT sds | otherwise = fail $ oneOfMsg e [el_constant, el_structure, el_adt, el_notation] -- | OMDoc - Algebraic Data Types instance XmlRepresentable OmdADT where toXml (ADTSortDef n b cs) = mkElement el_sortdef [Attr at_name n, Attr at_type $ show b] $ listToXml cs toXml (ADTConstr n args) = mkElement el_constructor [Attr at_name n] $ listToXml args toXml (ADTArg t sel) = mkElement el_argument [] $ typeToXml t : case sel of Nothing -> [] Just s -> [toXml s] toXml (ADTSelector n total) = mkElement el_selector [Attr at_name n, Attr at_total $ show total] [] toXml (ADTInsort (d, n)) = mkElement el_insort [Attr at_for $ showCDName d n] [] fromXml e | elemIsOf e el_sortdef = let musthave s at = missingMaybe "Sortdef" s $ findAttr at e nm = musthave "name" at_name typ = read $ musthave "type" at_type in do entries <- listFromXml $ elContent e justReturn $ ADTSortDef nm typ entries | elemIsOf e el_constructor = do let nm = missingMaybe "Constructor" "name" $ findAttr at_name e entries <- listFromXml $ elContent e justReturn $ ADTConstr nm entries | elemIsOf e el_argument = do typ <- fmap (missingMaybe "Argument" "typ") $ omelementFrom el_type e sel <- fmapFromMaybe fromXml $ findChild el_selector e justReturn $ ADTArg typ sel | elemIsOf e el_selector = let musthave s at = missingMaybe "Selector" s $ findAttr at e nm = musthave "name" at_name total = read $ musthave "total" at_total in justReturn $ ADTSelector nm total | elemIsOf e el_insort = do let nm = missingMaybe "Insort" "for" $ findAttr at_for e justReturn $ ADTInsort $ readCDName nm | otherwise = fail $ oneOfMsg e [ el_sortdef, el_constructor, el_argument , el_selector, el_insort] -- | OpenMath elements to XML and back instance XmlRepresentable OMElement where toXml (OMS (d, n)) = mkElement el_oms (tripleEncodeOMS d n) [] toXml (OMV n) = mkElement el_omv [Attr at_name (name n)] [] toXml (OMATTT elm attr) = mkElement el_omattr [] [toXml attr, toXml elm] toXml (OMA args) = mkElement el_oma [] $ listToXml args toXml (OMBIND symb vars body) = mkElement el_ombind [] [ toXml symb , mkElement el_ombvar [] $ listToXml vars , toXml body] fromXml e | elemIsOf e el_oms = let nm = missingMaybe "OMS" "name" $ findAttr at_name e omcd = fromMaybe "" $ findAttr at_module e cdb = fromMaybe "" $ findAttr at_base e in justReturn $ OMS $ tripleDecodeOMS omcd cdb nm | elemIsOf e el_omv = let nm = missingMaybe "OMV" "name" $ findAttr at_name e in justReturn $ OMV $ readOMName nm | elemIsOf e el_omattr = let [atp, el] = elChildren e musthave = missingMaybe "OMATTR" in do atp' <- fromXml atp el' <- fromXml el justReturn $ OMATTT (musthave "attributed value" el') (musthave "attribution" atp') | elemIsOf e el_oma = do entries <- listFromXml $ elContent e justReturn $ OMA entries | elemIsOf e el_ombind = let [bd, bvar, body] = elChildren e musthave = missingMaybe "OMBIND" in do bd' <- fromXml bd bvar' <- listFromXml $ elContent bvar body' <- fromXml body justReturn $ OMBIND (musthave "binder" bd') bvar' (musthave "body" body') | otherwise = fail $ oneOfMsg e [el_oms, el_omv, el_omattr, el_oma, el_ombind] -- | Helper instance for OpenMath attributes instance XmlRepresentable OMAttribute where toXml (OMAttr e1 e2) = mkElement el_omatp [] [toXml e1, toXml e2] fromXml e | elemIsOf e el_omatp = do [key, val] <- listFromXml $ elContent e justReturn $ OMAttr key val | otherwise = fail $ oneOfMsg e [el_omatp] -- * fromXml methods {- | If the child element with given name contains an OMOBJ xml element, this is transformed to an OMElement. -} omelementFrom :: QName -> Element -> Result (Maybe OMElement) omelementFrom qn e = fmapFromMaybe omelementFromOmobj $ findChild qn e omelementFromOmobj :: Element -> Result (Maybe OMElement) omelementFromOmobj e = fmapMaybe omobjToOMElement $ findChild el_omobj e -- | Get an OMElement from an OMOBJ xml element omobjToOMElement :: Element -> Result OMElement omobjToOMElement e = case elChildren e of [om] -> do omelem <- fromXml om case omelem of Nothing -> fail $ "omobjToOMElement: " ++ "No OpenMath element found." Just x -> return x _ -> fail "OMOBJ element must have a unique child." -- | The input is assumed to be a conass element xmlToAssignment :: Element -> Result (OMName, OMImage) xmlToAssignment e | elName e == el_open = let musthave = missingMaybe "Open" nm = musthave "name" $ findAttr at_name e alias = musthave "as" $ findAttr at_as e in return (readOMName nm, Left alias) | elName e == el_conass = let musthave = missingMaybe "Conass" nm = musthave "name" $ findAttr at_name e in do omel <- omelementFromOmobj e return (readOMName nm, Right $ musthave "OMOBJ element" omel) | otherwise = fail $ oneOfMsg e [el_conass, el_open] -- * toXml methods typeToXml :: OMElement -> Content typeToXml t = inContent el_type $ Just $ toOmobj $ toXml t assignmentToXml :: (OMName, OMImage) -> Content assignmentToXml (from, to) = case to of Left s -> mkElement el_open [Attr at_name $ showOMName from, Attr at_as s] [] Right obj -> inAContent el_conass [Attr at_name $ showOMName from] $ Just . toOmobj . toXml $ obj constantToXml :: String -> String -> OMElement -> Maybe OMElement -> Content constantToXml n r tp prf = Elem $ Element el_constant [Attr at_name n, Attr at_role r] (typeToXml tp : map (inContent el_definition . Just . toOmobj . toXml) (maybeToList prf)) Nothing notationComponentToXml :: NotationComponent -> Content notationComponentToXml (TextComp val) = mkElement el_text [Attr at_value val] [] notationComponentToXml (ArgComp ind prec) = mkElement el_component [ Attr at_index $ show ind , Attr at_precedence $ show prec] []
nevrenato/HetsAlloy
OMDoc/XmlInterface.hs
gpl-2.0
20,563
0
17
6,347
5,991
2,953
3,038
425
3
{-# LANGUAGE DeriveDataTypeable, MultiParamTypeClasses #-} module Sortier.Netz.Check where import Sortier.Netz.Type import Sortier.Netz.Rechnung import Sortier.Netz.Example import Sortier.Netz.Bild import Autolib.Util.Bild import qualified Autolib.Util.Wort ( alle ) import Data.List ( tails) import Data.Typeable import Autolib.Reporter import Autolib.ToDoc import qualified Challenger as C import Inter.Types import Autolib.Size check :: Int -> Netz -> Reporter () check soll n = do let verify xs = do let xss = rechnung n xs when ( not $ is_increasing $ last xss ) $ reject $ vcat [ text "Diese Eingabe wird nicht korrekt geordnet:" , nest 4 $ toDoc xs , text "Das Netz berechnet die Ausgabe:" , nest 4 $ toDoc $ last xss , text "Die Rechung des Netzes ist:" , nest 4 $ toDoc $ toBild ( n , xss ) ] mapM_ verify $ testing soll inform $ text "Das Netz hat alle möglichen Eingaben korrekt geordnet." return () -- | es gilt ja der satz: -- alle 0-1-folgen sortiert <=> überhaupt alle folgen sortiert. -- also generiere ich 0-1-folgen (weil das weniger sind) -- aber um die studenten nicht unnötig aufzuregen, -- rechne ich es in folgen aus lauter verschiedenen elementen um testing :: Int -> [ State ] testing soll = do w <- Autolib.Util.Wort.alle [ 0, 1 ] soll return $ umrech w -- | 0-1-Folge zu Zahlenfolge -- mit gleicher Steigung, aber lauter verschiedenen Zahlen -- dabei alle 0 aufsteigend, dann alle 1 aufsteigend umrech :: [ Int ] -> [ Int ] umrech w = um w 1 (1 + length w - sum w ) where um [] _ _ = [] um (0 : xs) low high = low : um xs (succ low) high um (1 : xs) low high = high : um xs low (succ high) is_increasing :: Ord a => [a] -> Bool is_increasing xs = and $ do x : y : rest <- tails xs return $ x <= y data Sortier = Sortier deriving ( Eq, Ord, Show, Read, Typeable ) instance C.Verify Sortier Int where verify p i = assert ( i > 0) $ text "die Breite soll eine positive Zahl sein" instance OrderScore Sortier where scoringOrder _ = Increasing instance C.Partial Sortier Int Netz where describe p i = vcat [ text "Finden Sie ein Sortiernetz für" <+> toDoc i <+> text "Eingänge" , text "mit weniger als" <+> toDoc ( size $ bubble i ) <+> text "Komparatoren." ] initial p i = bubble i partial p i b = do inform $ text "Ihr Netz ist:" <+> toDoc ( toBild b ) let ist = high b - low b + 1 when ( i /= ist ) $ reject $ vcat [ text "Das Netz soll Breite" <+> toDoc i <+> text "haben" , text "es hat aber" <+> toDoc ist ] total p i b = do check i b when ( size b >= size ( bubble i ) ) $ reject $ vcat [ text "Das sind zuviele Komparatoren." ] make :: Make make = direct Sortier (5 :: Int)
Erdwolf/autotool-bonn
src/Sortier/Netz/Check.hs
gpl-2.0
2,885
32
20
785
727
409
318
69
3
class X a where f :: a -> Int instance X Char where f _ = 5 main = f 3
Helium4Haskell/helium
test/typeClasses/ClassInstaneError2.hs
gpl-3.0
80
0
7
30
43
21
22
5
1
{-# LANGUAGE TupleSections, OverloadedStrings #-} module Handler.RefString where import Import import Quran.RefParser import qualified Data.Text as T import qualified Data.Map as M import Data.List ( head ) -- This is a handler function for the GET request method on the HomeR -- resource pattern. All of your resource patterns are defined in -- config/routes -- -- The majority of the code you will write in Yesod lives in these handler -- functions. You can spread them across multiple files if you are so -- inclined, or create a single monolithic file. getRefStringR :: Text -> Handler RepJson getRefStringR refs = do case parseRefRngs refs of Left errs -> do invalidArgs ["Could not parse '" `T.append` refs] -- FIXME msg no visible in response Right refRngs -> do yesod <- getYesod qtfMap <- liftIO $ readIORef $ getQtfMap yesod paramTxtIDs <- lookupGetParam "t" let qtfs = case paramTxtIDs of Nothing -> [head $ M.elems qtfMap] Just xs -> map ((!) qtfMap) $ (T.split (== ',')) xs qpfMap <- liftIO $ readIORef $ getQpfMap yesod paramParID <- lookupGetParam "p" let qpf = case paramParID of Nothing -> head $ M.elems qpfMap Just x -> qpfMap ! x paramGrpStyle <- lookupGetParam "g" let grpStyle = case paramGrpStyle of Nothing -> RefRangesOnly Just x -> case x of "r" -> RefRangesOnly "b" -> BigBreaks "a" -> AllBreaks _ -> ByVerse -- option "g=v", but also the catch-all let result = map (\refRng -> (show refRng, map (\qtf -> qtfRngToQlf qpf defaultBrkToText qtf refRng) qtfs)) (concat $ map (applyGrpStyleToRng grpStyle qpf) refRngs) return . RepJson . toContent . toJSON $ map (\(k, v) -> [toJSON k, toJSON v]) result getIDsR :: Handler RepJson getIDsR = do yesod <- getYesod qtfMap <- liftIO $ readIORef $ getQtfMap yesod qpfMap <- liftIO $ readIORef $ getQpfMap yesod return . RepJson . toContent . toJSON . object $ ["qtfs" .= (M.keys qtfMap), "qpfs" .= (M.keys qpfMap)]
oqc/oqs
Handler/RefString.hs
gpl-3.0
2,180
0
22
616
587
296
291
40
8
module Network.SimpleServer.Examples.ChatServer(main, run) where import Data.Char import Data.List import System.Environment import qualified Network.SimpleServer as S -- Constants -- -- A Welcome message to send to clients when they connect. welcomeMessage = "Welcome to the Simple Chat Server.\n" ++ "Commands:\n" ++ "/message [message] - Broadcast a message to all users.\n" ++ "/name [newname] - Change your name to newname.\n" ++ "/ping - Let's the server know you're still there.\n" ++ "/who - Displays a list of users connected to the server.\n" ++ "/disconnect - Disconnect from Simple Chat Server.\n" -- Keys -- The display name for a ClientConn username = "username" -- Handlers -- The Connection Handler sets a newly connected -- users username to "user #{cid}" broadcasts -- that they have connected and then sends them the welcome message connHandler :: S.ConnectionHandler connHandler server client = do let name = "user #" ++ (show (S.cid client)) msg = name ++ " connected." S.modify client username name S.broadcast server msg S.respond client welcomeMessage -- The Disconnection Handler responds to the client "disconnected" -- Then broadcasts to the room that the user has disconnected dissHandler :: S.DisconnectHandler dissHandler server client = do name <- S.lookup client username let msg = name ++ " disconnected." S.respond client "disconnected" S.broadcast server msg -- Commands -- The name command sets the username to the value specified -- by the user as long as it is not the empty string. If -- the name is the empty string, the client is notified that -- the name is not valid. Otherwise, a message is broadcast -- stating the user changed their name nameCmd = "/name" nameHandler :: S.CmdHandler nameHandler (_:msg) server client = do case msg of [] -> S.respond client "You did not provide a name to change to." msg -> do before <- S.lookup client username let name = intercalate " " msg message = before ++ " is now known as " ++ name S.modify client username (intercalate " " msg) S.broadcast server message -- The ping command notifies the server that the user is still connected -- so they don't time out. If the /ping command is followed by "silent" -- the server does not respond. Otherwise, the server responds with -- a received message. pingCmd = "/ping" pingHandler :: S.CmdHandler pingHandler (_:flag) _ client = do case flag of ("silent":_) -> return () _ -> S.respond client "Ping received." -- If the message command is received, any text following it is -- broadcast to all users. msgCmd = "/message" msgHandler :: S.CmdHandler msgHandler (cmd:msg) server client = do name <- S.lookup client username S.broadcast server $ name ++ "> " ++ (unwords msg) -- The disconnect command causes the message "Goodbye!" to be sent to -- the client. Then they are disconnected from the server. disCmd = "/disconnect" disHandler :: S.CmdHandler disHandler _ server client = do S.respond client "Goodbye!" S.disconnect client -- The who command responds to the client with -- a list of usernames whoCmd = "/who" whoHandler :: S.CmdHandler whoHandler _ server client = do clients <- S.clientList server usernames <- mapM (flip S.lookup username) clients let message = "Users:\n" ++ (intercalate "\n" usernames) S.respond client message -- Builds a server on the given port, adds the commands -- starts the server, and waits for the word stop to be entered run :: Int -> IO () run port = do server <- S.new connHandler dissHandler port S.addCommand server whoCmd whoHandler S.addCommand server nameCmd nameHandler S.addCommand server disCmd disHandler S.addCommand server msgCmd msgHandler S.addCommand server pingCmd pingHandler S.start server putStrLn $ "Chat Server Started on Port: " ++ (show port) putStrLn $ "Type 'stop' to stop the server." waitStop server S.stop server putStrLn "Server Stopped" -- Waits for the word 'stop' to be entered waitStop :: S.Server -> IO () waitStop server = do string <- getLine case string of "stop" -> return () _ -> waitStop server -- Starts a server on the specified port or prints the usage message main = do args <- getArgs case args of [] -> printUsage (x:_) -> if isInt x then (return (read x)) >>= run else printUsage printUsage :: IO () printUsage = putStrLn "Usage ./ChatServer [port]" isInt :: [Char] -> Bool isInt = (== []) . (filter (not . isDigit))
jcollard/simple-server
Network/SimpleServer/Examples/ChatServer.hs
gpl-3.0
4,599
0
16
976
986
494
492
89
3
module Main (main) where import System.Console.GetOpt import System.Environment (getArgs) import System.Exit import Control.Monad import Regex.Enumerator -- Flag data type data Options = Options { offset :: [String] -> [String] , fetch :: [String] -> [String] , longer :: [String] -> [String] , shorter :: [String] -> [String] } defaultOptions = Options { offset = id , fetch = id , longer = id , shorter = id } options :: [OptDescr (Options -> Options)] options = [ Option ['o'] ["offset"] (ReqArg (\a o -> o {offset = drop (read a)}) "NUM") "NUM of words to skip" , Option ['f'] ["fetch"] (ReqArg (\a o -> o {fetch = take (read a)}) "NUM") "NUM of words to print" , Option ['l'] ["longer"] (ReqArg (\a o -> o {longer = dropWhile (\x -> read a > length x)}) "NUM") "print only words longer than NUM characters" , Option ['s'] ["shorter"] (ReqArg (\a o -> o {shorter = takeWhile (\x -> read a > length x)}) "NUM") "print only words shorter than NUM characters" ] getOptions :: [String] -> IO (Options, String) getOptions argv = case getOpt Permute options argv of (o, [e], []) -> return (foldl (flip id) defaultOptions o, e) (_, _ , es) -> ioError $ userError $ concat es ++ usageInfo header options where header = "Usage: listlang [OPTION...] regex" adjust :: Options -> [String] -> [String] adjust opts = (fetch opts) . (offset opts) . (longer opts) . (shorter opts) printWords opts expr = case enumerate expr of Left e -> putStrLn e Right ws -> mapM_ putStrLn $ adjust opts ws main = do argv <- getArgs (opts, expr) <- getOptions argv printWords opts expr
tadeboro/reglang
src/listlang.hs
gpl-3.0
1,685
0
17
403
677
370
307
46
2
toLst :: [a] -> Lst a toLst as = \f -> foldMap f as fromLst :: Lst a -> [a] fromLst f = f (\a -> [a])
hmemcpy/milewski-ctfp-pdf
src/content/3.11/code/haskell/snippet05.hs
gpl-3.0
102
0
8
27
71
37
34
4
1
{---------------------------------------------------------------------} {- Copyright 2015, 2016 Nathan Bloomfield -} {- -} {- This file is part of Feivel. -} {- -} {- Feivel is free software: you can redistribute it and/or modify -} {- it under the terms of the GNU General Public License version 3, -} {- as published by the Free Software Foundation. -} {- -} {- Feivel is distributed in the hope that it will be useful, but -} {- WITHOUT ANY WARRANTY; without even the implied warranty of -} {- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -} {- GNU General Public License for more details. -} {- -} {- You should have received a copy of the GNU General Public License -} {- along with Feivel. If not, see <http://www.gnu.org/licenses/>. -} {---------------------------------------------------------------------} module Feivel.Parse.ZZMod ( pZZModConst, pZZModExpr ) where import Feivel.Grammar import Feivel.Parse.Util import Feivel.Parse.ParseM import Carl.Data.ZZMod (zzmod) import Text.Parsec.Expr (buildExpressionParser, Operator(..), Assoc(..)) pZZModConst :: Integer -> ParseM ZZModExpr pZZModConst n = fmap ZZModExpr $ pAtLocus (pZZModConst' n) pZZModConst' :: Integer -> ParseM (OfType ZZModExprLeafS) pZZModConst' n = do a <- pInteger return (ZZModConst (a `zzmod` n) :# (ZZMod n)) pZZModExpr :: (Type -> ParseM Expr) -> Integer -> ParserDict -> ParseM ZZModExpr pZZModExpr pE n dict = spaced $ buildExpressionParser zzModOpTable pZZModTerm where pBOOL = parseBOOL dict pINT = parseINT dict pLIST = parseLIST dict pMAT = parseMAT dict pMOD = parseZZMOD dict pTUPLE = parseTUPLE dict pZZModTerm = pTerm (pZZModConst' n) ZZModExpr (pMOD n) "integer expression" [ pVarExpr ((:# typ) `o` ZZModVar) (ZZMod n) , pMacroExprT pE ((:# typ) `oo` ZZModMacro) , pIfThenElseExprT pBOOL (pMOD n) ((:# typ) `ooo` ZZModIfThenElse) (ZZMod n) , pFun1 "int" (pE ZZ) ((:# typ) `o` ZZModCast) , pFun1 "Sum" (pLIST typ) ((:# typ) `o` ZZModSum) , pFun1 "Prod" (pLIST typ) ((:# typ) `o` ZZModProd) , pFun2 "AtPos" (pLIST typ) pINT ((:# typ) `oo` ZZModAtPos) , pFun2 "Pow" (pMOD n) pINT ((:# typ) `oo` ZZModPow) , pFun3 "AtIdx" (pMAT (ZZMod n)) pINT pINT ((:# typ) `ooo` ZZModAtIdx) , pAtSlot "AtSlot" pTUPLE pINT ((:# typ) `oo` ZZModAtSlot) ] zzModOpTable = [ [ Infix (opParser2 ((:# typ) `oo` ZZModMult) ZZModExpr "*") AssocLeft ] , [ Prefix (opParser1 ((:# typ) `o` ZZModNeg) ZZModExpr "neg") , Prefix (opParser1 ((:# typ) `o` ZZModInv) ZZModExpr "inv") ] , [ Infix (opParser2 ((:# typ) `oo` ZZModAdd) ZZModExpr "+") AssocLeft , Infix (opParser2 ((:# typ) `oo` ZZModSub) ZZModExpr "-") AssocLeft ] ] typ = ZZMod n
nbloomf/feivel
src/Feivel/Parse/ZZMod.hs
gpl-3.0
3,248
0
14
1,028
785
450
335
39
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleContexts #-} -- {-# LANGUAGE ScopedTypeVariables #-} module DB ( module DB.Config ,module DB.Types ,module DB ,module DB.ORMLinker ) where import DB.Config import DB.Types import DB.ORMLinker -- import Data.Aeson(Value(Null,String), ToJSON(toJSON)) notImplemented = error "not implemented"
shinjiro-itagaki/shinjirecs
shinjirecs-api/src/DB.hs
gpl-3.0
552
0
5
112
59
40
19
15
1
module HEP.Automation.MadGraph.Dataset.Set20110715set1 where import HEP.Storage.WebDAV.Type import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Machine import HEP.Automation.MadGraph.UserCut import HEP.Automation.MadGraph.SetupType import HEP.Automation.MadGraph.Model.FU8C1V import HEP.Automation.MadGraph.Dataset.Processes import HEP.Automation.JobQueue.JobType processSetup :: ProcessSetup FU8C1V processSetup = PS { model = FU8C1V , process = preDefProcess TTBar0or1J , processBrief = "TTBar0or1J" , workname = "715_FU8C1V_TTBar0or1J_LHC" } paramSet :: [ModelParam FU8C1V] paramSet = [ FU8C1VParam { mMFV = m, dmMFV = 0, gMFV = 0.5, eta = e } | m <- [300, 350, 450, 500, 550, 650, 700 ] , e <- [0.0,0.5..3.0] ] -- | m <- [ 200,400..800] , e <- [ 0.0,0.5..3.0 ] ] sets :: [Int] sets = [1] ucut :: UserCut ucut = UserCut { uc_metcut = 15.0 , uc_etacutlep = 2.7 , uc_etcutlep = 18.0 , uc_etacutjet = 2.7 , uc_etcutjet = 15.0 } eventsets :: [EventSet] eventsets = [ EventSet processSetup (RS { param = p , numevent = 100000 , machine = LHC7 ATLAS , rgrun = Fixed , rgscale = 200.0 , match = MLM , cut = DefCut , pythia = RunPYTHIA , usercut = UserCutDef ucut , pgs = RunPGS , jetalgo = AntiKTJet 0.4 , uploadhep = NoUploadHEP , setnum = num }) | p <- paramSet , num <- sets ] webdavdir :: WebDAVRemoteDir webdavdir = WebDAVRemoteDir "paper3/ttbar_LHC_FU8C1V_pgsscan"
wavewave/madgraph-auto-dataset
src/HEP/Automation/MadGraph/Dataset/Set20110715set1.hs
gpl-3.0
1,743
0
10
569
400
252
148
47
1
{- Copyright 2014 Bas Bossink ([email protected]). -} module Bob (responseFor) where import Data.Char responseFor :: String -> String responseFor a | all isSpace a = "Fine. Be that way!" | and [map toUpper a == a, any isLetter a] = "Woah, chill out!" | last a == '?' = "Sure." | otherwise = "Whatever."
basbossink/exercism
haskell/bob/Bob.hs
gpl-3.0
334
0
11
81
100
49
51
8
1
-- FilterFastaList module. -- By Gregory W. Schwartz -- -- Collection of functions for the filtering of a pipesFasta {-# LANGUAGE BangPatterns, OverloadedStrings, FlexibleContexts #-} module FilterCloneList ( filterHighlyMutatedEntry ) where -- Built in import Data.List import Data.Maybe import Data.Either import Text.Regex.TDFA import Text.Regex.TDFA.Text import qualified Data.Text as T -- Cabal import Data.Fasta.Text -- Local import Types -- | Remove highly mutated sequences (sequences with more than a third of -- their sequence being mutated). filterHighlyMutatedEntry :: GeneticUnit -> CodonTable -> CloneEntry -> CloneEntry filterHighlyMutatedEntry !genUnit !table = newEntry where newEntry (!germline, !fseqs) = ( germline , map snd . filter (not . fst) . rights . assignMutated germline $ fseqs ) assignMutated k = map (isHighlyMutated k) isHighlyMutated !k !x = case (readSeq genUnit k, readSeq genUnit x) of ((Right a), (Right b)) -> (\n -> Right (n, b)) $ ( (fromIntegral (T.length (fastaSeq a)) :: Double) / 3 ) <= ( ( genericLength . realMutations (fastaSeq a) $ fastaSeq b ) ) ((Left a), (Right _)) -> error ("Error in germline: " ++ T.unpack a) ((Right _), (Left b)) -> error ("Error in sequence: " ++ T.unpack b) ((Left a), (Left b)) -> error (unwords [ "Error in sequence:" , T.unpack b , "with germline:" , T.unpack a ] ) realMutations k x = filterCodonMutStab (\(!y, !z) -> y /= z) . map snd . mutation k $ x filterCodonMutStab isWhat = filter (filterRules genUnit isWhat) filterRules AminoAcid isWhat x = isWhat x && not (inTuple '-' x) && not (inTuple '.' x) && not (inTuple '~' x) filterRules Nucleotide isWhat x = isWhat x && not (inTuple '-' x) && not (inTuple '.' x) && not (inTuple '~' x) && not (inTuple 'N' x) inTuple c (x, y) | c == x || c == y = True | otherwise = False mutation x y = zip [1..] . T.zip x $ y readSeq Nucleotide x = Right x readSeq AminoAcid x = customTranslate table 1 x
GregorySchwartz/modify-fasta
src/FilterCloneList.hs
gpl-3.0
3,053
0
19
1,459
743
382
361
56
6
{-# 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.Monitoring.Services.Patch -- 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) -- -- Update this Service. -- -- /See:/ <https://cloud.google.com/monitoring/api/ Cloud Monitoring API Reference> for @monitoring.services.patch@. module Network.Google.Resource.Monitoring.Services.Patch ( -- * REST Resource ServicesPatchResource -- * Creating a Request , servicesPatch , ServicesPatch -- * Request Lenses , spXgafv , spUploadProtocol , spUpdateMask , spAccessToken , spUploadType , spPayload , spName , spCallback ) where import Network.Google.Monitoring.Types import Network.Google.Prelude -- | A resource alias for @monitoring.services.patch@ method which the -- 'ServicesPatch' request conforms to. type ServicesPatchResource = "v3" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "updateMask" GFieldMask :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Service :> Patch '[JSON] Service -- | Update this Service. -- -- /See:/ 'servicesPatch' smart constructor. data ServicesPatch = ServicesPatch' { _spXgafv :: !(Maybe Xgafv) , _spUploadProtocol :: !(Maybe Text) , _spUpdateMask :: !(Maybe GFieldMask) , _spAccessToken :: !(Maybe Text) , _spUploadType :: !(Maybe Text) , _spPayload :: !Service , _spName :: !Text , _spCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ServicesPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'spXgafv' -- -- * 'spUploadProtocol' -- -- * 'spUpdateMask' -- -- * 'spAccessToken' -- -- * 'spUploadType' -- -- * 'spPayload' -- -- * 'spName' -- -- * 'spCallback' servicesPatch :: Service -- ^ 'spPayload' -> Text -- ^ 'spName' -> ServicesPatch servicesPatch pSpPayload_ pSpName_ = ServicesPatch' { _spXgafv = Nothing , _spUploadProtocol = Nothing , _spUpdateMask = Nothing , _spAccessToken = Nothing , _spUploadType = Nothing , _spPayload = pSpPayload_ , _spName = pSpName_ , _spCallback = Nothing } -- | V1 error format. spXgafv :: Lens' ServicesPatch (Maybe Xgafv) spXgafv = lens _spXgafv (\ s a -> s{_spXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). spUploadProtocol :: Lens' ServicesPatch (Maybe Text) spUploadProtocol = lens _spUploadProtocol (\ s a -> s{_spUploadProtocol = a}) -- | A set of field paths defining which fields to use for the update. spUpdateMask :: Lens' ServicesPatch (Maybe GFieldMask) spUpdateMask = lens _spUpdateMask (\ s a -> s{_spUpdateMask = a}) -- | OAuth access token. spAccessToken :: Lens' ServicesPatch (Maybe Text) spAccessToken = lens _spAccessToken (\ s a -> s{_spAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). spUploadType :: Lens' ServicesPatch (Maybe Text) spUploadType = lens _spUploadType (\ s a -> s{_spUploadType = a}) -- | Multipart request metadata. spPayload :: Lens' ServicesPatch Service spPayload = lens _spPayload (\ s a -> s{_spPayload = a}) -- | Resource name for this Service. The format is: -- projects\/[PROJECT_ID_OR_NUMBER]\/services\/[SERVICE_ID] spName :: Lens' ServicesPatch Text spName = lens _spName (\ s a -> s{_spName = a}) -- | JSONP spCallback :: Lens' ServicesPatch (Maybe Text) spCallback = lens _spCallback (\ s a -> s{_spCallback = a}) instance GoogleRequest ServicesPatch where type Rs ServicesPatch = Service type Scopes ServicesPatch = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/monitoring"] requestClient ServicesPatch'{..} = go _spName _spXgafv _spUploadProtocol _spUpdateMask _spAccessToken _spUploadType _spCallback (Just AltJSON) _spPayload monitoringService where go = buildClient (Proxy :: Proxy ServicesPatchResource) mempty
brendanhay/gogol
gogol-monitoring/gen/Network/Google/Resource/Monitoring/Services/Patch.hs
mpl-2.0
5,057
0
17
1,200
858
499
359
119
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.Calendar.Calendars.Patch -- 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) -- -- Updates metadata for a calendar. This method supports patch semantics. -- -- /See:/ <https://developers.google.com/google-apps/calendar/firstapp Calendar API Reference> for @calendar.calendars.patch@. module Network.Google.Resource.Calendar.Calendars.Patch ( -- * REST Resource CalendarsPatchResource -- * Creating a Request , calendarsPatch , CalendarsPatch -- * Request Lenses , cpCalendarId , cpPayload ) where import Network.Google.AppsCalendar.Types import Network.Google.Prelude -- | A resource alias for @calendar.calendars.patch@ method which the -- 'CalendarsPatch' request conforms to. type CalendarsPatchResource = "calendar" :> "v3" :> "calendars" :> Capture "calendarId" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Calendar :> Patch '[JSON] Calendar -- | Updates metadata for a calendar. This method supports patch semantics. -- -- /See:/ 'calendarsPatch' smart constructor. data CalendarsPatch = CalendarsPatch' { _cpCalendarId :: !Text , _cpPayload :: !Calendar } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CalendarsPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cpCalendarId' -- -- * 'cpPayload' calendarsPatch :: Text -- ^ 'cpCalendarId' -> Calendar -- ^ 'cpPayload' -> CalendarsPatch calendarsPatch pCpCalendarId_ pCpPayload_ = CalendarsPatch' {_cpCalendarId = pCpCalendarId_, _cpPayload = pCpPayload_} -- | Calendar identifier. To retrieve calendar IDs call the calendarList.list -- method. If you want to access the primary calendar of the currently -- logged in user, use the \"primary\" keyword. cpCalendarId :: Lens' CalendarsPatch Text cpCalendarId = lens _cpCalendarId (\ s a -> s{_cpCalendarId = a}) -- | Multipart request metadata. cpPayload :: Lens' CalendarsPatch Calendar cpPayload = lens _cpPayload (\ s a -> s{_cpPayload = a}) instance GoogleRequest CalendarsPatch where type Rs CalendarsPatch = Calendar type Scopes CalendarsPatch = '["https://www.googleapis.com/auth/calendar"] requestClient CalendarsPatch'{..} = go _cpCalendarId (Just AltJSON) _cpPayload appsCalendarService where go = buildClient (Proxy :: Proxy CalendarsPatchResource) mempty
brendanhay/gogol
gogol-apps-calendar/gen/Network/Google/Resource/Calendar/Calendars/Patch.hs
mpl-2.0
3,241
0
13
689
384
232
152
59
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.TargetTCPProxies.SetProxyHeader -- 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) -- -- Changes the ProxyHeaderType for TargetTcpProxy. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetTcpProxies.setProxyHeader@. module Network.Google.Resource.Compute.TargetTCPProxies.SetProxyHeader ( -- * REST Resource TargetTCPProxiesSetProxyHeaderResource -- * Creating a Request , targetTCPProxiesSetProxyHeader , TargetTCPProxiesSetProxyHeader -- * Request Lenses , ttpsphRequestId , ttpsphProject , ttpsphPayload , ttpsphTargetTCPProxy ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.targetTcpProxies.setProxyHeader@ method which the -- 'TargetTCPProxiesSetProxyHeader' request conforms to. type TargetTCPProxiesSetProxyHeaderResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "targetTcpProxies" :> Capture "targetTcpProxy" Text :> "setProxyHeader" :> QueryParam "requestId" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] TargetTCPProxiesSetProxyHeaderRequest :> Post '[JSON] Operation -- | Changes the ProxyHeaderType for TargetTcpProxy. -- -- /See:/ 'targetTCPProxiesSetProxyHeader' smart constructor. data TargetTCPProxiesSetProxyHeader = TargetTCPProxiesSetProxyHeader' { _ttpsphRequestId :: !(Maybe Text) , _ttpsphProject :: !Text , _ttpsphPayload :: !TargetTCPProxiesSetProxyHeaderRequest , _ttpsphTargetTCPProxy :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TargetTCPProxiesSetProxyHeader' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ttpsphRequestId' -- -- * 'ttpsphProject' -- -- * 'ttpsphPayload' -- -- * 'ttpsphTargetTCPProxy' targetTCPProxiesSetProxyHeader :: Text -- ^ 'ttpsphProject' -> TargetTCPProxiesSetProxyHeaderRequest -- ^ 'ttpsphPayload' -> Text -- ^ 'ttpsphTargetTCPProxy' -> TargetTCPProxiesSetProxyHeader targetTCPProxiesSetProxyHeader pTtpsphProject_ pTtpsphPayload_ pTtpsphTargetTCPProxy_ = TargetTCPProxiesSetProxyHeader' { _ttpsphRequestId = Nothing , _ttpsphProject = pTtpsphProject_ , _ttpsphPayload = pTtpsphPayload_ , _ttpsphTargetTCPProxy = pTtpsphTargetTCPProxy_ } -- | An optional request ID to identify requests. Specify a unique request ID -- so that if you must retry your request, the server will know to ignore -- the request if it has already been completed. For example, consider a -- situation where you make an initial request and the request times out. -- If you make the request again with the same request ID, the server can -- check if original operation with the same request ID was received, and -- if so, will ignore the second request. This prevents clients from -- accidentally creating duplicate commitments. The request ID must be a -- valid UUID with the exception that zero UUID is not supported -- (00000000-0000-0000-0000-000000000000). ttpsphRequestId :: Lens' TargetTCPProxiesSetProxyHeader (Maybe Text) ttpsphRequestId = lens _ttpsphRequestId (\ s a -> s{_ttpsphRequestId = a}) -- | Project ID for this request. ttpsphProject :: Lens' TargetTCPProxiesSetProxyHeader Text ttpsphProject = lens _ttpsphProject (\ s a -> s{_ttpsphProject = a}) -- | Multipart request metadata. ttpsphPayload :: Lens' TargetTCPProxiesSetProxyHeader TargetTCPProxiesSetProxyHeaderRequest ttpsphPayload = lens _ttpsphPayload (\ s a -> s{_ttpsphPayload = a}) -- | Name of the TargetTcpProxy resource whose ProxyHeader is to be set. ttpsphTargetTCPProxy :: Lens' TargetTCPProxiesSetProxyHeader Text ttpsphTargetTCPProxy = lens _ttpsphTargetTCPProxy (\ s a -> s{_ttpsphTargetTCPProxy = a}) instance GoogleRequest TargetTCPProxiesSetProxyHeader where type Rs TargetTCPProxiesSetProxyHeader = Operation type Scopes TargetTCPProxiesSetProxyHeader = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient TargetTCPProxiesSetProxyHeader'{..} = go _ttpsphProject _ttpsphTargetTCPProxy _ttpsphRequestId (Just AltJSON) _ttpsphPayload computeService where go = buildClient (Proxy :: Proxy TargetTCPProxiesSetProxyHeaderResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/TargetTCPProxies/SetProxyHeader.hs
mpl-2.0
5,479
0
18
1,191
561
335
226
94
1
module AlecSequences.A271504Spec (main, spec) where import Test.Hspec import AlecSequences.A271504 (a271504) main :: IO () main = hspec spec spec :: Spec spec = describe "A271504" $ it "correctly computes the first 10 elements" $ take 10 (map a271504 [1..]) `shouldBe` expectedValue where expectedValue = [1,1,2,6,2,60,2,210,2,630]
peterokagey/haskellOEIS
test/AlecSequences/A271504Spec.hs
apache-2.0
346
0
10
59
130
75
55
10
1
{-| Module : IntMapOrd Description : Bidirectionalization Copyright : (c) Urska, 2015; Melanija, 2015 License : GPL-3 Stability : experimental -- A variant of the regular 'Data.IntMap'. -} module IntMapOrd (IntMapOrd, fromAscPairList, empty, insert, checkInsert, union, lookup, lookupR, toAscList) where import qualified Data.Map.Strict as Map import Prelude hiding (lookup) import Data.Maybe import Data.List as List hiding (insert, union, lookup, find) newtype IntMapOrd b = IntMapOrd (Map.Map Int b) instance Show b => Show (IntMapOrd b) where show b = show (toAscList b) -- | Check if the keys in the map are in ascending order. valid :: Ord b => IntMapOrd b -> Bool valid (IntMapOrd map) = Map.valid map -- | Check if the values in the map are in ascending order. validR :: Ord b => IntMapOrd b -> Bool validR map = let s1 = List.map (\(_,y) -> y) (toAscList map) in if (check_list s1) then True else False -- | Check if the values in the list are in ascending order. check_list :: Ord b => [b] -> Bool check_list [] = True check_list [x] = True check_list (x:y:xs) = if x < y then check_list (y:xs) else False -- | Build a map from an ascending list of key and value pairs. -- If the list if not ascending, an error is signalled. fromAscPairList :: Ord b => [(Int, b)] -> IntMapOrd b fromAscPairList list = let map1 = (List.map (\(x, y) -> x) list) map2 = (List.map (\(x, y) -> y) list) in if ((check_list map1) && (check_list map2)) then ((IntMapOrd) (Map.fromAscList list)) else error "Input list is not ascending." -- | Convert to an ascending list. toAscList :: IntMapOrd b -> [(Int, b)] toAscList (IntMapOrd map) = Map.toAscList map -- | The empty map. empty :: IntMapOrd b empty = (IntMapOrd) Map.empty -- | Insert a new key and value pair in map. An error is signalled, -- if the order is violated. insert :: (Ord b) => Int -> b -> IntMapOrd b -> IntMapOrd b insert key value (IntMapOrd map) = let m1 = Map.insert key value map in if (valid (IntMapOrd m1)) && (validR (IntMapOrd m1)) then (IntMapOrd) m1 else error "Update violates order" -- | Insert a new key and value pair in map. The key must be new or its value has -- to be equal to the present value, if not, an error is signalled. -- An error is also signalled, if the order is violated. checkInsert :: Ord b => Int -> b -> IntMapOrd b -> Either String (IntMapOrd b) checkInsert key value map = case lookup key map of Nothing -> case lookupR value map of Nothing -> Right (insert key value map) Just m -> Left "Update violates equality" Just c -> case lookupR value map of Nothing -> Left "Update violates equality" Just a -> if key == a && value == c then Right map else Left "Update violates equality" -- | The union of two maps. When duplicate keys are present, it prefers the first map. -- An error is signalled, if the order is violated. union :: Ord b => IntMapOrd b -> IntMapOrd b -> Either String (IntMapOrd b) union (IntMapOrd map1) (IntMapOrd map2) = let s1 = Map.filterWithKey (\key _ -> Map.notMember key map1) (map2) s2 = Map.foldr (\value init -> (notMemberR value (IntMapOrd map1)) && init) True s1 s3 = IntMapOrd (Map.union map1 s1) in if s2 && (valid s3) && (validR s3) then Right s3 else Left "Update violates order" -- | Check if the value is not a member of the map. notMemberR :: Ord b => b -> IntMapOrd b -> Bool notMemberR value map = case lookupR value map of Nothing -> True Just _ -> False -- | Lookup the value at a key in the map. lookup :: Ord b => Int -> IntMapOrd b -> Maybe b lookup key (IntMapOrd map) = Map.lookup key map -- | Lookup the key at a value in the map. lookupR :: Ord b => b -> IntMapOrd b -> Maybe Int lookupR value map = find value (toAscList map) -- | Given a key find the value in a list of the key and value pairs. find :: Ord b => b -> [(Int, b)] -> Maybe Int find value [] = Nothing find value ((x, y):xs) = if (y == value) then Just (x) else (find value xs)
urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav
IntMapOrd.hs
apache-2.0
4,139
71
16
993
1,353
705
648
83
5
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QHeaderView.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:35 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QHeaderView ( QHeaderViewResizeMode, eInteractive, eStretch, eResizeToContents ) where import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CQHeaderViewResizeMode a = CQHeaderViewResizeMode a type QHeaderViewResizeMode = QEnum(CQHeaderViewResizeMode Int) ieQHeaderViewResizeMode :: Int -> QHeaderViewResizeMode ieQHeaderViewResizeMode x = QEnum (CQHeaderViewResizeMode x) instance QEnumC (CQHeaderViewResizeMode Int) where qEnum_toInt (QEnum (CQHeaderViewResizeMode x)) = x qEnum_fromInt x = QEnum (CQHeaderViewResizeMode x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> QHeaderViewResizeMode -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eInteractive :: QHeaderViewResizeMode eInteractive = ieQHeaderViewResizeMode $ 0 eStretch :: QHeaderViewResizeMode eStretch = ieQHeaderViewResizeMode $ 1 instance QeFixed QHeaderViewResizeMode where eFixed = ieQHeaderViewResizeMode $ 2 eResizeToContents :: QHeaderViewResizeMode eResizeToContents = ieQHeaderViewResizeMode $ 3 instance QeCustom QHeaderViewResizeMode where eCustom = ieQHeaderViewResizeMode $ 2
uduki/hsQt
Qtc/Enums/Gui/QHeaderView.hs
bsd-2-clause
2,817
0
18
554
640
327
313
60
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QErrorMessage_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.QErrorMessage_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 (QErrorMessage ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QErrorMessage_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QErrorMessage_unSetUserMethod" qtc_QErrorMessage_unSetUserMethod :: Ptr (TQErrorMessage a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QErrorMessageSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QErrorMessage_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QErrorMessage ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QErrorMessage_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QErrorMessageSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QErrorMessage_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QErrorMessage ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QErrorMessage_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QErrorMessageSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QErrorMessage_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QErrorMessage ()) (QErrorMessage x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QErrorMessage setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QErrorMessage_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QErrorMessage_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQErrorMessage 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_QErrorMessage_setUserMethod" qtc_QErrorMessage_setUserMethod :: Ptr (TQErrorMessage a) -> CInt -> Ptr (Ptr (TQErrorMessage x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QErrorMessage :: (Ptr (TQErrorMessage x0) -> IO ()) -> IO (FunPtr (Ptr (TQErrorMessage x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QErrorMessage_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QErrorMessageSc a) (QErrorMessage x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QErrorMessage setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QErrorMessage_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QErrorMessage_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQErrorMessage 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 (QErrorMessage ()) (QErrorMessage x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QErrorMessage setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QErrorMessage_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QErrorMessage_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQErrorMessage 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_QErrorMessage_setUserMethodVariant" qtc_QErrorMessage_setUserMethodVariant :: Ptr (TQErrorMessage a) -> CInt -> Ptr (Ptr (TQErrorMessage x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QErrorMessage :: (Ptr (TQErrorMessage x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQErrorMessage x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QErrorMessage_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QErrorMessageSc a) (QErrorMessage x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QErrorMessage setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QErrorMessage_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QErrorMessage_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQErrorMessage 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 (QErrorMessage ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QErrorMessage_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QErrorMessage_unSetHandler" qtc_QErrorMessage_unSetHandler :: Ptr (TQErrorMessage a) -> CWString -> IO (CBool) instance QunSetHandler (QErrorMessageSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QErrorMessage_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QErrorMessage ()) (QErrorMessage x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qErrorMessageFromPtr 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_QErrorMessage_setHandler1" qtc_QErrorMessage_setHandler1 :: Ptr (TQErrorMessage a) -> CWString -> Ptr (Ptr (TQErrorMessage x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QErrorMessage1 :: (Ptr (TQErrorMessage x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQErrorMessage x0) -> Ptr (TQEvent t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QErrorMessage1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QErrorMessageSc a) (QErrorMessage x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qErrorMessageFromPtr 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 QchangeEvent_h (QErrorMessage ()) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_changeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_changeEvent" qtc_QErrorMessage_changeEvent :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent_h (QErrorMessageSc a) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_changeEvent cobj_x0 cobj_x1 instance QsetHandler (QErrorMessage ()) (QErrorMessage x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> IO () setHandlerWrapper x0 = do x0obj <- qErrorMessageFromPtr 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_QErrorMessage_setHandler2" qtc_QErrorMessage_setHandler2 :: Ptr (TQErrorMessage a) -> CWString -> Ptr (Ptr (TQErrorMessage x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QErrorMessage2 :: (Ptr (TQErrorMessage x0) -> IO ()) -> IO (FunPtr (Ptr (TQErrorMessage x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QErrorMessage2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QErrorMessageSc a) (QErrorMessage x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> IO () setHandlerWrapper x0 = do x0obj <- qErrorMessageFromPtr 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 (QErrorMessage ()) (()) where accept_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_accept cobj_x0 foreign import ccall "qtc_QErrorMessage_accept" qtc_QErrorMessage_accept :: Ptr (TQErrorMessage a) -> IO () instance Qaccept_h (QErrorMessageSc a) (()) where accept_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_accept cobj_x0 instance QcloseEvent_h (QErrorMessage ()) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_closeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_closeEvent" qtc_QErrorMessage_closeEvent :: Ptr (TQErrorMessage a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent_h (QErrorMessageSc a) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_closeEvent cobj_x0 cobj_x1 instance QcontextMenuEvent_h (QErrorMessage ()) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_contextMenuEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_contextMenuEvent" qtc_QErrorMessage_contextMenuEvent :: Ptr (TQErrorMessage a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent_h (QErrorMessageSc a) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_contextMenuEvent cobj_x0 cobj_x1 instance QsetHandler (QErrorMessage ()) (QErrorMessage x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qErrorMessageFromPtr 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_QErrorMessage_setHandler3" qtc_QErrorMessage_setHandler3 :: Ptr (TQErrorMessage a) -> CWString -> Ptr (Ptr (TQErrorMessage x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QErrorMessage3 :: (Ptr (TQErrorMessage x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQErrorMessage x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QErrorMessage3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QErrorMessageSc a) (QErrorMessage x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qErrorMessageFromPtr 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 (QErrorMessage ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_event cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_event" qtc_QErrorMessage_event :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QErrorMessageSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_event cobj_x0 cobj_x1 instance QkeyPressEvent_h (QErrorMessage ()) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_keyPressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_keyPressEvent" qtc_QErrorMessage_keyPressEvent :: Ptr (TQErrorMessage a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent_h (QErrorMessageSc a) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_keyPressEvent cobj_x0 cobj_x1 instance QsetHandler (QErrorMessage ()) (QErrorMessage x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qErrorMessageFromPtr 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_QErrorMessage_setHandler4" qtc_QErrorMessage_setHandler4 :: Ptr (TQErrorMessage a) -> CWString -> Ptr (Ptr (TQErrorMessage x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QErrorMessage4 :: (Ptr (TQErrorMessage x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQErrorMessage x0) -> IO (Ptr (TQSize t0)))) foreign import ccall "wrapper" wrapSetHandler_QErrorMessage4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QErrorMessageSc a) (QErrorMessage x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qErrorMessageFromPtr 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 (QErrorMessage ()) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_minimumSizeHint cobj_x0 foreign import ccall "qtc_QErrorMessage_minimumSizeHint" qtc_QErrorMessage_minimumSizeHint :: Ptr (TQErrorMessage a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint_h (QErrorMessageSc a) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_minimumSizeHint cobj_x0 instance QminimumSizeHint_h (QErrorMessage ()) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QErrorMessage_minimumSizeHint_qth" qtc_QErrorMessage_minimumSizeHint_qth :: Ptr (TQErrorMessage a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint_h (QErrorMessageSc a) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance Qreject_h (QErrorMessage ()) (()) where reject_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_reject cobj_x0 foreign import ccall "qtc_QErrorMessage_reject" qtc_QErrorMessage_reject :: Ptr (TQErrorMessage a) -> IO () instance Qreject_h (QErrorMessageSc a) (()) where reject_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_reject cobj_x0 instance QresizeEvent_h (QErrorMessage ()) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_resizeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_resizeEvent" qtc_QErrorMessage_resizeEvent :: Ptr (TQErrorMessage a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent_h (QErrorMessageSc a) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_resizeEvent cobj_x0 cobj_x1 instance QsetHandler (QErrorMessage ()) (QErrorMessage x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qErrorMessageFromPtr 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_QErrorMessage_setHandler5" qtc_QErrorMessage_setHandler5 :: Ptr (TQErrorMessage a) -> CWString -> Ptr (Ptr (TQErrorMessage x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QErrorMessage5 :: (Ptr (TQErrorMessage x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQErrorMessage x0) -> CBool -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QErrorMessage5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QErrorMessageSc a) (QErrorMessage x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qErrorMessageFromPtr 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 (QErrorMessage ()) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_setVisible cobj_x0 (toCBool x1) foreign import ccall "qtc_QErrorMessage_setVisible" qtc_QErrorMessage_setVisible :: Ptr (TQErrorMessage a) -> CBool -> IO () instance QsetVisible_h (QErrorMessageSc a) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_setVisible cobj_x0 (toCBool x1) instance QshowEvent_h (QErrorMessage ()) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_showEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_showEvent" qtc_QErrorMessage_showEvent :: Ptr (TQErrorMessage a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent_h (QErrorMessageSc a) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_showEvent cobj_x0 cobj_x1 instance QqsizeHint_h (QErrorMessage ()) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_sizeHint cobj_x0 foreign import ccall "qtc_QErrorMessage_sizeHint" qtc_QErrorMessage_sizeHint :: Ptr (TQErrorMessage a) -> IO (Ptr (TQSize ())) instance QqsizeHint_h (QErrorMessageSc a) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_sizeHint cobj_x0 instance QsizeHint_h (QErrorMessage ()) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QErrorMessage_sizeHint_qth" qtc_QErrorMessage_sizeHint_qth :: Ptr (TQErrorMessage a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint_h (QErrorMessageSc a) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QactionEvent_h (QErrorMessage ()) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_actionEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_actionEvent" qtc_QErrorMessage_actionEvent :: Ptr (TQErrorMessage a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent_h (QErrorMessageSc a) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_actionEvent cobj_x0 cobj_x1 instance QsetHandler (QErrorMessage ()) (QErrorMessage x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qErrorMessageFromPtr 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_QErrorMessage_setHandler6" qtc_QErrorMessage_setHandler6 :: Ptr (TQErrorMessage a) -> CWString -> Ptr (Ptr (TQErrorMessage x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QErrorMessage6 :: (Ptr (TQErrorMessage x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQErrorMessage x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QErrorMessage6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QErrorMessageSc a) (QErrorMessage x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qErrorMessageFromPtr 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 QdevType_h (QErrorMessage ()) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_devType cobj_x0 foreign import ccall "qtc_QErrorMessage_devType" qtc_QErrorMessage_devType :: Ptr (TQErrorMessage a) -> IO CInt instance QdevType_h (QErrorMessageSc a) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_devType cobj_x0 instance QdragEnterEvent_h (QErrorMessage ()) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_dragEnterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_dragEnterEvent" qtc_QErrorMessage_dragEnterEvent :: Ptr (TQErrorMessage a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent_h (QErrorMessageSc a) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_dragEnterEvent cobj_x0 cobj_x1 instance QdragLeaveEvent_h (QErrorMessage ()) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_dragLeaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_dragLeaveEvent" qtc_QErrorMessage_dragLeaveEvent :: Ptr (TQErrorMessage a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent_h (QErrorMessageSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_dragLeaveEvent cobj_x0 cobj_x1 instance QdragMoveEvent_h (QErrorMessage ()) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_dragMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_dragMoveEvent" qtc_QErrorMessage_dragMoveEvent :: Ptr (TQErrorMessage a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent_h (QErrorMessageSc a) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_dragMoveEvent cobj_x0 cobj_x1 instance QdropEvent_h (QErrorMessage ()) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_dropEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_dropEvent" qtc_QErrorMessage_dropEvent :: Ptr (TQErrorMessage a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent_h (QErrorMessageSc a) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_dropEvent cobj_x0 cobj_x1 instance QenterEvent_h (QErrorMessage ()) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_enterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_enterEvent" qtc_QErrorMessage_enterEvent :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent_h (QErrorMessageSc a) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_enterEvent cobj_x0 cobj_x1 instance QfocusInEvent_h (QErrorMessage ()) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_focusInEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_focusInEvent" qtc_QErrorMessage_focusInEvent :: Ptr (TQErrorMessage a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent_h (QErrorMessageSc a) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_focusInEvent cobj_x0 cobj_x1 instance QfocusOutEvent_h (QErrorMessage ()) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_focusOutEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_focusOutEvent" qtc_QErrorMessage_focusOutEvent :: Ptr (TQErrorMessage a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent_h (QErrorMessageSc a) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_focusOutEvent cobj_x0 cobj_x1 instance QsetHandler (QErrorMessage ()) (QErrorMessage x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qErrorMessageFromPtr 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_QErrorMessage_setHandler7" qtc_QErrorMessage_setHandler7 :: Ptr (TQErrorMessage a) -> CWString -> Ptr (Ptr (TQErrorMessage x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QErrorMessage7 :: (Ptr (TQErrorMessage x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQErrorMessage x0) -> CInt -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QErrorMessage7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QErrorMessageSc a) (QErrorMessage x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qErrorMessageFromPtr 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 (QErrorMessage ()) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_heightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QErrorMessage_heightForWidth" qtc_QErrorMessage_heightForWidth :: Ptr (TQErrorMessage a) -> CInt -> IO CInt instance QheightForWidth_h (QErrorMessageSc a) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_heightForWidth cobj_x0 (toCInt x1) instance QhideEvent_h (QErrorMessage ()) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_hideEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_hideEvent" qtc_QErrorMessage_hideEvent :: Ptr (TQErrorMessage a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent_h (QErrorMessageSc a) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_hideEvent cobj_x0 cobj_x1 instance QsetHandler (QErrorMessage ()) (QErrorMessage x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qErrorMessageFromPtr 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_QErrorMessage_setHandler8" qtc_QErrorMessage_setHandler8 :: Ptr (TQErrorMessage a) -> CWString -> Ptr (Ptr (TQErrorMessage x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QErrorMessage8 :: (Ptr (TQErrorMessage x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQErrorMessage x0) -> CLong -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QErrorMessage8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QErrorMessageSc a) (QErrorMessage x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qErrorMessageFromPtr 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 (QErrorMessage ()) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QErrorMessage_inputMethodQuery" qtc_QErrorMessage_inputMethodQuery :: Ptr (TQErrorMessage a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery_h (QErrorMessageSc a) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyReleaseEvent_h (QErrorMessage ()) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_keyReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_keyReleaseEvent" qtc_QErrorMessage_keyReleaseEvent :: Ptr (TQErrorMessage a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent_h (QErrorMessageSc a) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_keyReleaseEvent cobj_x0 cobj_x1 instance QleaveEvent_h (QErrorMessage ()) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_leaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_leaveEvent" qtc_QErrorMessage_leaveEvent :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent_h (QErrorMessageSc a) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_leaveEvent cobj_x0 cobj_x1 instance QmouseDoubleClickEvent_h (QErrorMessage ()) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_mouseDoubleClickEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_mouseDoubleClickEvent" qtc_QErrorMessage_mouseDoubleClickEvent :: Ptr (TQErrorMessage a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent_h (QErrorMessageSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_mouseDoubleClickEvent cobj_x0 cobj_x1 instance QmouseMoveEvent_h (QErrorMessage ()) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_mouseMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_mouseMoveEvent" qtc_QErrorMessage_mouseMoveEvent :: Ptr (TQErrorMessage a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent_h (QErrorMessageSc a) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_mouseMoveEvent cobj_x0 cobj_x1 instance QmousePressEvent_h (QErrorMessage ()) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_mousePressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_mousePressEvent" qtc_QErrorMessage_mousePressEvent :: Ptr (TQErrorMessage a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent_h (QErrorMessageSc a) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_mousePressEvent cobj_x0 cobj_x1 instance QmouseReleaseEvent_h (QErrorMessage ()) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_mouseReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_mouseReleaseEvent" qtc_QErrorMessage_mouseReleaseEvent :: Ptr (TQErrorMessage a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent_h (QErrorMessageSc a) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_mouseReleaseEvent cobj_x0 cobj_x1 instance QmoveEvent_h (QErrorMessage ()) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_moveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_moveEvent" qtc_QErrorMessage_moveEvent :: Ptr (TQErrorMessage a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent_h (QErrorMessageSc a) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_moveEvent cobj_x0 cobj_x1 instance QsetHandler (QErrorMessage ()) (QErrorMessage x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qErrorMessageFromPtr 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_QErrorMessage_setHandler9" qtc_QErrorMessage_setHandler9 :: Ptr (TQErrorMessage a) -> CWString -> Ptr (Ptr (TQErrorMessage x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QErrorMessage9 :: (Ptr (TQErrorMessage x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQErrorMessage x0) -> IO (Ptr (TQPaintEngine t0)))) foreign import ccall "wrapper" wrapSetHandler_QErrorMessage9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QErrorMessageSc a) (QErrorMessage x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QErrorMessage9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QErrorMessage9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QErrorMessage_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQErrorMessage x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qErrorMessageFromPtr 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 (QErrorMessage ()) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_paintEngine cobj_x0 foreign import ccall "qtc_QErrorMessage_paintEngine" qtc_QErrorMessage_paintEngine :: Ptr (TQErrorMessage a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine_h (QErrorMessageSc a) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QErrorMessage_paintEngine cobj_x0 instance QpaintEvent_h (QErrorMessage ()) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_paintEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_paintEvent" qtc_QErrorMessage_paintEvent :: Ptr (TQErrorMessage a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent_h (QErrorMessageSc a) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_paintEvent cobj_x0 cobj_x1 instance QtabletEvent_h (QErrorMessage ()) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_tabletEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_tabletEvent" qtc_QErrorMessage_tabletEvent :: Ptr (TQErrorMessage a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent_h (QErrorMessageSc a) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_tabletEvent cobj_x0 cobj_x1 instance QwheelEvent_h (QErrorMessage ()) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_wheelEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QErrorMessage_wheelEvent" qtc_QErrorMessage_wheelEvent :: Ptr (TQErrorMessage a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent_h (QErrorMessageSc a) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QErrorMessage_wheelEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QErrorMessage_h.hs
bsd-2-clause
57,911
0
18
12,032
18,570
8,964
9,606
-1
-1
module Datum where import Ellipsoid {- | To represent a set of parameters for describing a particular datum, including a name, the reference ellipsoid used and the seven parameters required to translate co-ordinates in this datum to the WGS84 datum. -} data Datum = Datum { name :: String -- ^ The name of this Datum. , ellipsoid :: Ellipsoid -- ^ The reference ellipsoid associated with this Datum. {-| Translation along the x-axis for use in 7-parameter Helmert transformations. This value should be used to convert a co-ordinate in a given datum to the WGS84 datum. -} , dx :: Double {-| Translation along the y-axis for use in 7-parameter Helmert transformations. This value should be used to convert a co-ordinate in a given datum to the WGS84 datum. -} , dy :: Double {-| Translation along the z-axis for use in 7-parameter Helmert transformations. This value should be used to convert a co-ordinate in a given datum to the WGS84 datum. -} , dz :: Double {-| Scale factor for use in 7-parameter Helmert transformations. This value should be used to convert a co-ordinate in a given datum to the WGS84 datum. -} , ds :: Double {-| Rotation about the x-axis for use in 7-parameter Helmert transformations. This value should be used to convert a co-ordinate in a given datum to the WGS84 datum. -} , rx :: Double {-| Rotation about the y-axis for use in 7-parameter Helmert transformations. This value should be used to convert a co-ordinate in a given datum to the WGS84 datum. -} , ry :: Double {-| Rotation about the z-axis for use in 7-parameter Helmert transformations. This value should be used to convert a co-ordinate in a given datum to the WGS84 datum. -} , rz :: Double } deriving (Eq, Show) -- instance Show Datum where -- show Datum{name = n, ellipsoid = ell, dx = dx, dy = dy, dz = dz, -- ds = ds, rx = rx, ry = ry, rz = rz} = -- n ++ " " ++ show ell ++ " dx=" ++ show dx ++ " dy=" ++ show dy ++ -- " dz=" ++ show dz ++ " ds=" ++ show ds ++ " rx=" ++ show rx ++ " ry=" ++ show ry ++ " rz=" ++ show rz -- | Pre-determined data: etrf89Datum :: Datum etrf89Datum = Datum { name = "European Terrestrial Reference Frame (ETRF89)" , ellipsoid = wgs84Ellipsoid , dx = 0.0 , dy = 0.0 , dz = 0.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } ireland1965Datum :: Datum ireland1965Datum = Datum { name = "Ireland 1965" , ellipsoid = modifiedAiryEllipsoid , dx = 482.53 , dy = -130.596 , dz = 564.557 , ds = 8.15 , rx = -1.042 , ry = -0.214 , rz = -0.631 } osgb36Datum :: Datum osgb36Datum = Datum { name = "Ordnance Survey of Great Britain 1936 (OSGB36)" , ellipsoid = airy1830Ellipsoid , dx = 446.448 , dy = -125.157 , dz = 542.06 , ds = -20.4894 , rx = 0.1502 , ry = 0.2470 , rz = 0.8421 } wgs84Datum :: Datum wgs84Datum = Datum { name = "World Geodetic System 1984 (WGS84)" , ellipsoid = wgs84Ellipsoid , dx = 0.0 , dy = 0.0 , dz = 0.0 , ds = 1.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27GreenlandDatum :: Datum nad27GreenlandDatum = Datum { name = "North American Datum 1927 (NAD27) - Greenland" , ellipsoid = clarke1866Ellipsoid , dx = 11.0 , dy = 114.0 , dz = 195.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27WesternUSDatum :: Datum nad27WesternUSDatum = Datum { name = "North American Datum 1927 (NAD27) - Western US" , ellipsoid = clarke1866Ellipsoid , dx = -8.0 , dy = 159.0 , dz = 175.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27AlaskaDatum :: Datum nad27AlaskaDatum = Datum { name = "North American Datum 1927 (NAD27) - Alaska" , ellipsoid = clarke1866Ellipsoid , dx = -5.0 , dy = 135.0 , dz = 172.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27CentralAmericaDatum :: Datum nad27CentralAmericaDatum = Datum { name = "North American Datum 1927 (NAD27) - Central America" , ellipsoid = clarke1866Ellipsoid , dx = 0.0 , dy = 125.0 , dz = 194.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27SanSalvadorDatum :: Datum nad27SanSalvadorDatum = Datum { name = "North American Datum 1927 (NAD27) - San Salvador" , ellipsoid = clarke1866Ellipsoid , dx = 1.0 , dy = 140.0 , dz = 165.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27AlbertaBritishColumbiaDatum :: Datum nad27AlbertaBritishColumbiaDatum = Datum { name = "North American Datum 1927 (NAD27) - Alberta and British Columbia" , ellipsoid = clarke1866Ellipsoid , dx = -7.0 , dy = 162.0 , dz = 188.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27CanadaEastDatum :: Datum nad27CanadaEastDatum = Datum { name = "North American Datum 1927 (NAD27) - Canada East" , ellipsoid = clarke1866Ellipsoid , dx = -22.0 , dy = 160.0 , dz = 190.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27ContiguousUSDatum :: Datum nad27ContiguousUSDatum = Datum { name = "North American Datum 1927 (NAD27) - Contiguous United States" , ellipsoid = clarke1866Ellipsoid , dx = -8.0 , dy = 160.0 , dz = 176.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27MexicoDatum :: Datum nad27MexicoDatum = Datum { name = "North American Datum 1927 (NAD27) - Mexico" , ellipsoid = clarke1866Ellipsoid , dx = -12.0 , dy = 130.0 , dz = 190.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27BahamasDatum :: Datum nad27BahamasDatum = Datum { name = "North American Datum 1927 (NAD27) - Bahamas" , ellipsoid = clarke1866Ellipsoid , dx = -4.0 , dy = 154.0 , dz = 178.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27CanadaNWTerritoryDatum :: Datum nad27CanadaNWTerritoryDatum = Datum { name = "North American Datum 1927 (NAD27) - Canada NW Territory" , ellipsoid = clarke1866Ellipsoid , dx = 4.0 , dy = 159.0 , dz = 188.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27CanadaManitobaOntarioDatum :: Datum nad27CanadaManitobaOntarioDatum = Datum { name = "North American Datum 1927 (NAD27) - Canada Manitoba/Ontario" , ellipsoid = clarke1866Ellipsoid , dx = -9.0 , dy = 157.0 , dz = 184.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27CanadaDatum :: Datum nad27CanadaDatum = Datum { name = "North American Datum 1927 (NAD27) - Canada" , ellipsoid = clarke1866Ellipsoid , dx = -10.0 , dy = 158.0 , dz = 187.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27CanadaYukonDatum :: Datum nad27CanadaYukonDatum = Datum { name = "North American Datum 1927 (NAD27) - Canada Yukon" , ellipsoid = clarke1866Ellipsoid , dx = -7.0 , dy = 139.0 , dz = 181.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27CubaDatum :: Datum nad27CubaDatum = Datum { name = "North American Datum 1927 (NAD27) - Cuba" , ellipsoid = clarke1866Ellipsoid , dx = -9.0 , dy = 152.0 , dz = 178.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27AleutianWestDatum :: Datum nad27AleutianWestDatum = Datum { name = "North American Datum 1927 (NAD27) - Aleutian West" , ellipsoid = clarke1866Ellipsoid , dx = 2.0 , dy = 204.0 , dz = 105.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27AleutianEastDatum :: Datum nad27AleutianEastDatum = Datum { name = "North American Datum 1927 (NAD27) - Aleutian East" , ellipsoid = clarke1866Ellipsoid , dx = -2.0 , dy = 152.0 , dz = 149.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27CanalZoneDatum :: Datum nad27CanalZoneDatum = Datum { name = "North American Datum 1927 (NAD27) - Canal Zone" , ellipsoid = clarke1866Ellipsoid , dx = 0.0 , dy = 125.0 , dz = 201.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27EasternUSDatum :: Datum nad27EasternUSDatum = Datum { name = "North American Datum 1927 (NAD27) - Eastern US" , ellipsoid = clarke1866Ellipsoid , dx = -9.0 , dy = 161.0 , dz = 179.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 } nad27CaribbeanDatum :: Datum nad27CaribbeanDatum = Datum { name = "North American Datum 1927 (NAD27) - Caribbean" , ellipsoid = clarke1866Ellipsoid , dx = -3.0 , dy = 142.0 , dz = 183.0 , ds = 0.0 , rx = 0.0 , ry = 0.0 , rz = 0.0 }
danfran/hcoord
src/Datum.hs
bsd-3-clause
14,739
0
8
8,648
1,721
1,120
601
252
1
-- | This module contains very basic definitions for Futhark - so basic, -- that they can be shared between the internal and external -- representation. module Language.Futhark.Core ( Uniqueness(..) , StreamOrd(..) , Commutativity(..) -- * Location utilities , locStr -- * Name handling , Name , QualName , nameToString , nameFromString , longnameToString , longnameToName , nameToText , nameFromText , blankLongname , ID(..) , baseTag , baseName , baseString , VName , textual -- * Special identifiers , defaultEntryPoint -- * Integer re-export , Int8, Int16, Int32, Int64 ) where import Data.Monoid import Data.Hashable import Data.Int (Int8, Int16, Int32, Int64) import Data.Loc import Data.List import qualified Data.Text as T import Prelude import Futhark.Util.Pretty -- | The uniqueness attribute of a type. This essentially indicates -- whether or not in-place modifications are acceptable. With respect -- to ordering, 'Unique' is greater than 'Nonunique'. data Uniqueness = Nonunique -- ^ May have references outside current function. | Unique -- ^ No references outside current function. deriving (Eq, Ord, Show) instance Monoid Uniqueness where mempty = Unique _ `mappend` Nonunique = Nonunique Nonunique `mappend` _ = Nonunique u `mappend` _ = u instance Pretty Uniqueness where ppr Unique = star ppr Nonunique = empty instance Hashable Uniqueness where hashWithSalt salt Unique = salt hashWithSalt salt Nonunique = salt * 2 data StreamOrd = InOrder | Disorder deriving (Eq, Ord, Show) -- | Whether some operator is commutative or not. The 'Monoid' -- instance returns the least commutative of its arguments. data Commutativity = Noncommutative | Commutative deriving (Eq, Ord, Show) instance Monoid Commutativity where mempty = Commutative mappend = min -- | The name of the default program entry point (main). defaultEntryPoint :: Name defaultEntryPoint = nameFromString "main" -- | The abstract (not really) type representing names in the Futhark -- compiler. 'String's, being lists of characters, are very slow, -- while 'T.Text's are based on byte-arrays. newtype Name = Name T.Text deriving (Show, Eq, Ord) type QualName = ([Name], Name) instance Pretty Name where ppr = text . nameToString instance Hashable Name where hashWithSalt salt (Name t) = hashWithSalt salt t instance Monoid Name where Name t1 `mappend` Name t2 = Name $ t1 <> t2 mempty = Name mempty -- | Convert a name to the corresponding list of characters. nameToString :: Name -> String nameToString (Name t) = T.unpack t longnameToString :: QualName -> String longnameToString ([], name) = nameToString name longnameToString (names, name) = let names' = Data.List.intercalate "." $ map nameToString names name' = nameToString name in names' ++ "." ++ name' longnameToName :: QualName -> Name longnameToName = nameFromString . longnameToString -- | Convert a list of characters to the corresponding name. nameFromString :: String -> Name nameFromString = Name . T.pack -- | Convert a name to the corresponding 'T.Text'. nameToText :: Name -> T.Text nameToText (Name t) = t -- | Convert a 'T.Text' to the corresponding name. nameFromText :: T.Text -> Name nameFromText = Name blankLongname :: QualName blankLongname = ([], nameFromString "") -- | A human-readable location string, of the form -- @filename:lineno:columnno@. locStr :: SrcLoc -> String locStr (SrcLoc NoLoc) = "unknown location" locStr (SrcLoc (Loc (Pos file line1 col1 _) (Pos _ line2 col2 _))) = -- Assume that both positions are in the same file (what would the -- alternative mean?) file ++ ":" ++ show line1 ++ ":" ++ show col1 ++ "-" ++ show line2 ++ ":" ++ show col2 -- | An arbitrary value tagged with some integer. Only the integer is -- used in comparisons, no matter the type of @vn@. newtype ID vn = ID (vn, Int) deriving (Show) -- | Alias for a tagged 'Name'. This is used as the name -- representation in most the compiler. type VName = ID Name -- | Return the tag contained in the 'ID'. baseTag :: ID vn -> Int baseTag (ID (_, tag)) = tag -- | Return the name contained in the 'ID'. baseName :: ID vn -> vn baseName (ID (vn, _)) = vn -- | Return the base 'Name' converted to a string. baseString :: VName -> String baseString = nameToString . baseName instance Eq (ID vn) where ID (_, x) == ID (_, y) = x == y instance Ord (ID vn) where ID (_, x) `compare` ID (_, y) = x `compare` y instance Pretty vn => Pretty (ID vn) where ppr (ID (vn, i)) = ppr vn <> text "_" <> text (show i) instance Hashable (ID vn) where hashWithSalt salt (ID (_,i)) = salt * i textual :: VName -> String textual = pretty
mrakgr/futhark
src/Language/Futhark/Core.hs
bsd-3-clause
4,854
0
12
1,060
1,183
660
523
107
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} module Test.ZM.ADT.ByPattern.Kcf6c76b3f808 (ByPattern(..)) where import qualified Prelude(Eq,Ord,Show) import qualified GHC.Generics import qualified Flat import qualified Data.Model import qualified Test.ZM.ADT.List.Kb8cd13187198 import qualified Test.ZM.ADT.Match.Kc23b20389114 import qualified Test.ZM.ADT.Bit.K65149ce3b366 newtype ByPattern a = ByPattern (Test.ZM.ADT.List.Kb8cd13187198.List (Test.ZM.ADT.Match.Kc23b20389114.Match (Test.ZM.ADT.List.Kb8cd13187198.List Test.ZM.ADT.Bit.K65149ce3b366.Bit))) deriving (Prelude.Eq, Prelude.Ord, Prelude.Show, GHC.Generics.Generic, Flat.Flat) instance ( Data.Model.Model a ) => Data.Model.Model ( ByPattern a )
tittoassini/typed
test/Test/ZM/ADT/ByPattern/Kcf6c76b3f808.hs
bsd-3-clause
728
0
12
65
191
125
66
13
0
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude, MagicHash, ExistentialQuantification #-} {-# OPTIONS_GHC -funbox-strict-fields #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.Exception -- Copyright : (c) The University of Glasgow, 2009 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable -- -- IO-related Exception types and functions -- ----------------------------------------------------------------------------- module GHC.IO.Exception ( BlockedIndefinitelyOnMVar(..), blockedIndefinitelyOnMVar, BlockedIndefinitelyOnSTM(..), blockedIndefinitelyOnSTM, Deadlock(..), AllocationLimitExceeded(..), allocationLimitExceeded, AssertionFailed(..), SomeAsyncException(..), asyncExceptionToException, asyncExceptionFromException, AsyncException(..), stackOverflow, heapOverflow, ArrayException(..), ExitCode(..), ioException, ioError, IOError, IOException(..), IOErrorType(..), userError, assertError, unsupportedOperation, untangle, ) where import GHC.Base import GHC.List import GHC.IO import GHC.Show import GHC.Read import GHC.Exception import GHC.IO.Handle.Types import Foreign.C.Types import Data.Typeable ( cast ) -- ------------------------------------------------------------------------ -- Exception datatypes and operations -- |The thread is blocked on an @MVar@, but there are no other references -- to the @MVar@ so it can't ever continue. data BlockedIndefinitelyOnMVar = BlockedIndefinitelyOnMVar instance Exception BlockedIndefinitelyOnMVar instance Show BlockedIndefinitelyOnMVar where showsPrec _ BlockedIndefinitelyOnMVar = showString "thread blocked indefinitely in an MVar operation" blockedIndefinitelyOnMVar :: SomeException -- for the RTS blockedIndefinitelyOnMVar = toException BlockedIndefinitelyOnMVar ----- -- |The thread is waiting to retry an STM transaction, but there are no -- other references to any @TVar@s involved, so it can't ever continue. data BlockedIndefinitelyOnSTM = BlockedIndefinitelyOnSTM instance Exception BlockedIndefinitelyOnSTM instance Show BlockedIndefinitelyOnSTM where showsPrec _ BlockedIndefinitelyOnSTM = showString "thread blocked indefinitely in an STM transaction" blockedIndefinitelyOnSTM :: SomeException -- for the RTS blockedIndefinitelyOnSTM = toException BlockedIndefinitelyOnSTM ----- -- |There are no runnable threads, so the program is deadlocked. -- The @Deadlock@ exception is raised in the main thread only. data Deadlock = Deadlock instance Exception Deadlock instance Show Deadlock where showsPrec _ Deadlock = showString "<<deadlock>>" ----- -- |This thread has exceeded its allocation limit. See -- 'GHC.Conc.setAllocationCounter' and -- 'GHC.Conc.enableAllocationLimit'. -- -- @since 4.8.0.0 data AllocationLimitExceeded = AllocationLimitExceeded instance Exception AllocationLimitExceeded where toException = asyncExceptionToException fromException = asyncExceptionFromException instance Show AllocationLimitExceeded where showsPrec _ AllocationLimitExceeded = showString "allocation limit exceeded" allocationLimitExceeded :: SomeException -- for the RTS allocationLimitExceeded = toException AllocationLimitExceeded ----- -- |'assert' was applied to 'False'. data AssertionFailed = AssertionFailed String instance Exception AssertionFailed instance Show AssertionFailed where showsPrec _ (AssertionFailed err) = showString err ----- -- |Superclass for asynchronous exceptions. -- -- @since 4.7.0.0 data SomeAsyncException = forall e . Exception e => SomeAsyncException e instance Show SomeAsyncException where show (SomeAsyncException e) = show e instance Exception SomeAsyncException -- |@since 4.7.0.0 asyncExceptionToException :: Exception e => e -> SomeException asyncExceptionToException = toException . SomeAsyncException -- |@since 4.7.0.0 asyncExceptionFromException :: Exception e => SomeException -> Maybe e asyncExceptionFromException x = do SomeAsyncException a <- fromException x cast a -- |Asynchronous exceptions. data AsyncException = StackOverflow -- ^The current thread\'s stack exceeded its limit. -- Since an exception has been raised, the thread\'s stack -- will certainly be below its limit again, but the -- programmer should take remedial action -- immediately. | HeapOverflow -- ^The program\'s heap is reaching its limit, and -- the program should take action to reduce the amount of -- live data it has. Notes: -- -- * It is undefined which thread receives this exception. -- -- * GHC currently does not throw 'HeapOverflow' exceptions. | ThreadKilled -- ^This exception is raised by another thread -- calling 'Control.Concurrent.killThread', or by the system -- if it needs to terminate the thread for some -- reason. | UserInterrupt -- ^This exception is raised by default in the main thread of -- the program when the user requests to terminate the program -- via the usual mechanism(s) (e.g. Control-C in the console). deriving (Eq, Ord) instance Exception AsyncException where toException = asyncExceptionToException fromException = asyncExceptionFromException -- | Exceptions generated by array operations data ArrayException = IndexOutOfBounds String -- ^An attempt was made to index an array outside -- its declared bounds. | UndefinedElement String -- ^An attempt was made to evaluate an element of an -- array that had not been initialized. deriving (Eq, Ord) instance Exception ArrayException -- for the RTS stackOverflow, heapOverflow :: SomeException stackOverflow = toException StackOverflow heapOverflow = toException HeapOverflow instance Show AsyncException where showsPrec _ StackOverflow = showString "stack overflow" showsPrec _ HeapOverflow = showString "heap overflow" showsPrec _ ThreadKilled = showString "thread killed" showsPrec _ UserInterrupt = showString "user interrupt" instance Show ArrayException where showsPrec _ (IndexOutOfBounds s) = showString "array index out of range" . (if not (null s) then showString ": " . showString s else id) showsPrec _ (UndefinedElement s) = showString "undefined array element" . (if not (null s) then showString ": " . showString s else id) -- ----------------------------------------------------------------------------- -- The ExitCode type -- We need it here because it is used in ExitException in the -- Exception datatype (above). -- | Defines the exit codes that a program can return. data ExitCode = ExitSuccess -- ^ indicates successful termination; | ExitFailure Int -- ^ indicates program failure with an exit code. -- The exact interpretation of the code is -- operating-system dependent. In particular, some values -- may be prohibited (e.g. 0 on a POSIX-compliant system). deriving (Eq, Ord, Read, Show) instance Exception ExitCode ioException :: IOException -> IO a ioException err = throwIO err -- | Raise an 'IOError' in the 'IO' monad. ioError :: IOError -> IO a ioError = ioException -- --------------------------------------------------------------------------- -- IOError type -- | The Haskell 2010 type for exceptions in the 'IO' monad. -- Any I\/O operation may raise an 'IOError' instead of returning a result. -- For a more general type of exception, including also those that arise -- in pure code, see 'Control.Exception.Exception'. -- -- In Haskell 2010, this is an opaque type. type IOError = IOException -- |Exceptions that occur in the @IO@ monad. -- An @IOException@ records a more specific error type, a descriptive -- string and maybe the handle that was used when the error was -- flagged. data IOException = IOError { ioe_handle :: Maybe Handle, -- the handle used by the action flagging -- the error. ioe_type :: IOErrorType, -- what it was. ioe_location :: String, -- location. ioe_description :: String, -- error type specific information. ioe_errno :: Maybe CInt, -- errno leading to this error, if any. ioe_filename :: Maybe FilePath -- filename the error is related to. } instance Exception IOException instance Eq IOException where (IOError h1 e1 loc1 str1 en1 fn1) == (IOError h2 e2 loc2 str2 en2 fn2) = e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && en1==en2 && fn1==fn2 -- | An abstract type that contains a value for each variant of 'IOError'. data IOErrorType -- Haskell 2010: = AlreadyExists | NoSuchThing | ResourceBusy | ResourceExhausted | EOF | IllegalOperation | PermissionDenied | UserError -- GHC only: | UnsatisfiedConstraints | SystemError | ProtocolError | OtherError | InvalidArgument | InappropriateType | HardwareFault | UnsupportedOperation | TimeExpired | ResourceVanished | Interrupted instance Eq IOErrorType where x == y = isTrue# (getTag x ==# getTag y) instance Show IOErrorType where showsPrec _ e = showString $ case e of AlreadyExists -> "already exists" NoSuchThing -> "does not exist" ResourceBusy -> "resource busy" ResourceExhausted -> "resource exhausted" EOF -> "end of file" IllegalOperation -> "illegal operation" PermissionDenied -> "permission denied" UserError -> "user error" HardwareFault -> "hardware fault" InappropriateType -> "inappropriate type" Interrupted -> "interrupted" InvalidArgument -> "invalid argument" OtherError -> "failed" ProtocolError -> "protocol error" ResourceVanished -> "resource vanished" SystemError -> "system error" TimeExpired -> "timeout" UnsatisfiedConstraints -> "unsatisfied constraints" -- ultra-precise! UnsupportedOperation -> "unsupported operation" -- | Construct an 'IOError' value with a string describing the error. -- The 'fail' method of the 'IO' instance of the 'Monad' class raises a -- 'userError', thus: -- -- > instance Monad IO where -- > ... -- > fail s = ioError (userError s) -- userError :: String -> IOError userError str = IOError Nothing UserError "" str Nothing Nothing -- --------------------------------------------------------------------------- -- Showing IOErrors instance Show IOException where showsPrec p (IOError hdl iot loc s _ fn) = (case fn of Nothing -> case hdl of Nothing -> id Just h -> showsPrec p h . showString ": " Just name -> showString name . showString ": ") . (case loc of "" -> id _ -> showString loc . showString ": ") . showsPrec p iot . (case s of "" -> id _ -> showString " (" . showString s . showString ")") -- Note the use of "lazy". This means that -- assert False (throw e) -- will throw the assertion failure rather than e. See trac #5561. assertError :: Addr# -> Bool -> a -> a assertError str predicate v | predicate = lazy v | otherwise = throw (AssertionFailed (untangle str "Assertion failed")) unsupportedOperation :: IOError unsupportedOperation = (IOError Nothing UnsupportedOperation "" "Operation is not supported" Nothing Nothing) {- (untangle coded message) expects "coded" to be of the form "location|details" It prints location message details -} untangle :: Addr# -> String -> String untangle coded message = location ++ ": " ++ message ++ details ++ "\n" where coded_str = unpackCStringUtf8# coded (location, details) = case (span not_bar coded_str) of { (loc, rest) -> case rest of ('|':det) -> (loc, ' ' : det) _ -> (loc, "") } not_bar c = c /= '|'
gcampax/ghc
libraries/base/GHC/IO/Exception.hs
bsd-3-clause
12,307
0
17
2,730
1,844
1,028
816
209
2
{-# LANGUAGE UnicodeSyntax #-} module Main where import Lib main ∷ IO () main = playGame
eallik/haskell-hangman
app/Main.hs
bsd-3-clause
94
0
6
19
23
14
9
5
1
{- (c) The University of Glasgow 2006 (c) The AQUA Project, Glasgow University, 1996-1998 TcHsSyn: Specialisations of the @HsSyn@ syntax for the typechecker This module is an extension of @HsSyn@ syntax, for use in the type checker. -} {-# LANGUAGE CPP, TupleSections #-} module TcHsSyn ( mkHsDictLet, mkHsApp, hsLitType, hsLPatType, hsPatType, mkHsAppTy, mkHsCaseAlt, nlHsIntLit, shortCutLit, hsOverLitName, conLikeResTy, -- * re-exported from TcMonad TcId, TcIdSet, -- * Zonking -- | For a description of "zonking", see Note [What is zonking?] -- in TcMType zonkTopDecls, zonkTopExpr, zonkTopLExpr, zonkTopBndrs, zonkTyBndrsX, zonkTyVarBindersX, zonkTyVarBinderX, emptyZonkEnv, mkEmptyZonkEnv, zonkTcTypeToType, zonkTcTypeToTypes, zonkTyVarOcc, zonkCoToCo, zonkSigType, zonkEvBinds, -- * Validity checking checkForRepresentationPolymorphism ) where #include "HsVersions.h" import HsSyn import Id import TcRnMonad import PrelNames import TcType import TcMType import TcEvidence import TysPrim import TysWiredIn import Type import TyCon import Coercion import ConLike import DataCon import HscTypes import Name import NameEnv import Var import VarSet import VarEnv import DynFlags import Literal import BasicTypes import Maybes import SrcLoc import Bag import Outputable import Util import UniqFM import Control.Monad import Data.List ( partition ) import Control.Arrow ( second ) {- ************************************************************************ * * \subsection[mkFailurePair]{Code for pattern-matching and other failures} * * ************************************************************************ Note: If @hsLPatType@ doesn't bear a strong resemblance to @exprType@, then something is wrong. -} hsLPatType :: OutPat Id -> Type hsLPatType (L _ pat) = hsPatType pat hsPatType :: Pat Id -> Type hsPatType (ParPat pat) = hsLPatType pat hsPatType (WildPat ty) = ty hsPatType (VarPat (L _ var)) = idType var hsPatType (BangPat pat) = hsLPatType pat hsPatType (LazyPat pat) = hsLPatType pat hsPatType (LitPat lit) = hsLitType lit hsPatType (AsPat var _) = idType (unLoc var) hsPatType (ViewPat _ _ ty) = ty hsPatType (ListPat _ ty Nothing) = mkListTy ty hsPatType (ListPat _ _ (Just (ty,_))) = ty hsPatType (PArrPat _ ty) = mkPArrTy ty hsPatType (TuplePat _ bx tys) = mkTupleTy bx tys hsPatType (SumPat _ _ _ tys) = mkSumTy tys hsPatType (ConPatOut { pat_con = L _ con, pat_arg_tys = tys }) = conLikeResTy con tys hsPatType (SigPatOut _ ty) = ty hsPatType (NPat _ _ _ ty) = ty hsPatType (NPlusKPat _ _ _ _ _ ty) = ty hsPatType (CoPat _ _ ty) = ty hsPatType p = pprPanic "hsPatType" (ppr p) hsLitType :: HsLit -> TcType hsLitType (HsChar _ _) = charTy hsLitType (HsCharPrim _ _) = charPrimTy hsLitType (HsString _ _) = stringTy hsLitType (HsStringPrim _ _) = addrPrimTy hsLitType (HsInt _ _) = intTy hsLitType (HsIntPrim _ _) = intPrimTy hsLitType (HsWordPrim _ _) = wordPrimTy hsLitType (HsInt64Prim _ _) = int64PrimTy hsLitType (HsWord64Prim _ _) = word64PrimTy hsLitType (HsInteger _ _ ty) = ty hsLitType (HsRat _ ty) = ty hsLitType (HsFloatPrim _) = floatPrimTy hsLitType (HsDoublePrim _) = doublePrimTy -- Overloaded literals. Here mainly because it uses isIntTy etc shortCutLit :: DynFlags -> OverLitVal -> TcType -> Maybe (HsExpr TcId) shortCutLit dflags (HsIntegral src i) ty | isIntTy ty && inIntRange dflags i = Just (HsLit (HsInt src i)) | isWordTy ty && inWordRange dflags i = Just (mkLit wordDataCon (HsWordPrim src i)) | isIntegerTy ty = Just (HsLit (HsInteger src i ty)) | otherwise = shortCutLit dflags (HsFractional (integralFractionalLit i)) ty -- The 'otherwise' case is important -- Consider (3 :: Float). Syntactically it looks like an IntLit, -- so we'll call shortCutIntLit, but of course it's a float -- This can make a big difference for programs with a lot of -- literals, compiled without -O shortCutLit _ (HsFractional f) ty | isFloatTy ty = Just (mkLit floatDataCon (HsFloatPrim f)) | isDoubleTy ty = Just (mkLit doubleDataCon (HsDoublePrim f)) | otherwise = Nothing shortCutLit _ (HsIsString src s) ty | isStringTy ty = Just (HsLit (HsString src s)) | otherwise = Nothing mkLit :: DataCon -> HsLit -> HsExpr Id mkLit con lit = HsApp (nlHsVar (dataConWrapId con)) (nlHsLit lit) ------------------------------ hsOverLitName :: OverLitVal -> Name -- Get the canonical 'fromX' name for a particular OverLitVal hsOverLitName (HsIntegral {}) = fromIntegerName hsOverLitName (HsFractional {}) = fromRationalName hsOverLitName (HsIsString {}) = fromStringName {- ************************************************************************ * * \subsection[BackSubst-HsBinds]{Running a substitution over @HsBinds@} * * ************************************************************************ The rest of the zonking is done *after* typechecking. The main zonking pass runs over the bindings a) to convert TcTyVars to TyVars etc, dereferencing any bindings etc b) convert unbound TcTyVar to Void c) convert each TcId to an Id by zonking its type The type variables are converted by binding mutable tyvars to immutable ones and then zonking as normal. The Ids are converted by binding them in the normal Tc envt; that way we maintain sharing; eg an Id is zonked at its binding site and they all occurrences of that Id point to the common zonked copy It's all pretty boring stuff, because HsSyn is such a large type, and the environment manipulation is tiresome. -} -- Confused by zonking? See Note [What is zonking?] in TcMType. type UnboundTyVarZonker = TcTyVar -> TcM Type -- How to zonk an unbound type variable -- The TcTyVar is -- (a) a MetaTv -- (b) Flexi and -- (c) its kind is already zonked -- Note [Zonking the LHS of a RULE] -- | A ZonkEnv carries around several bits. -- The UnboundTyVarZonker just zaps unbouned meta-tyvars to Any (as -- defined in zonkTypeZapping), except on the LHS of rules. See -- Note [Zonking the LHS of a RULE]. -- -- The (TyCoVarEnv TyVar) and is just an optimisation: when binding a -- tyvar or covar, we zonk the kind right away and add a mapping to -- the env. This prevents re-zonking the kind at every occurrence. But -- this is *just* an optimisation. -- -- The final (IdEnv Var) optimises zonking for Ids. It is -- knot-tied. We must be careful never to put coercion variables -- (which are Ids, after all) in the knot-tied env, because coercions -- can appear in types, and we sometimes inspect a zonked type in this -- module. -- -- Confused by zonking? See Note [What is zonking?] in TcMType. data ZonkEnv = ZonkEnv UnboundTyVarZonker (TyCoVarEnv TyVar) (IdEnv Var) -- What variables are in scope -- Maps an Id or EvVar to its zonked version; both have the same Name -- Note that all evidence (coercion variables as well as dictionaries) -- are kept in the ZonkEnv -- Only *type* abstraction is done by side effect -- Is only consulted lazily; hence knot-tying instance Outputable ZonkEnv where ppr (ZonkEnv _ _ty_env var_env) = pprUFM var_env (vcat . map ppr) -- The EvBinds have to already be zonked, but that's usually the case. emptyZonkEnv :: ZonkEnv emptyZonkEnv = mkEmptyZonkEnv zonkTypeZapping mkEmptyZonkEnv :: UnboundTyVarZonker -> ZonkEnv mkEmptyZonkEnv zonker = ZonkEnv zonker emptyVarEnv emptyVarEnv -- | Extend the knot-tied environment. extendIdZonkEnvRec :: ZonkEnv -> [Var] -> ZonkEnv extendIdZonkEnvRec (ZonkEnv zonk_ty ty_env id_env) ids -- NB: Don't look at the var to decide which env't to put it in. That -- would end up knot-tying all the env'ts. = ZonkEnv zonk_ty ty_env (extendVarEnvList id_env [(id,id) | id <- ids]) -- Given coercion variables will actually end up here. That's OK though: -- coercion variables are never looked up in the knot-tied env't, so zonking -- them simply doesn't get optimised. No one gets hurt. An improvement (?) -- would be to do SCC analysis in zonkEvBinds and then only knot-tie the -- recursive groups. But perhaps the time it takes to do the analysis is -- more than the savings. extendZonkEnv :: ZonkEnv -> [Var] -> ZonkEnv extendZonkEnv (ZonkEnv zonk_ty tyco_env id_env) vars = ZonkEnv zonk_ty (extendVarEnvList tyco_env [(tv,tv) | tv <- tycovars]) (extendVarEnvList id_env [(id,id) | id <- ids]) where (tycovars, ids) = partition isTyCoVar vars extendIdZonkEnv1 :: ZonkEnv -> Var -> ZonkEnv extendIdZonkEnv1 (ZonkEnv zonk_ty ty_env id_env) id = ZonkEnv zonk_ty ty_env (extendVarEnv id_env id id) extendTyZonkEnv1 :: ZonkEnv -> TyVar -> ZonkEnv extendTyZonkEnv1 (ZonkEnv zonk_ty ty_env id_env) tv = ZonkEnv zonk_ty (extendVarEnv ty_env tv tv) id_env setZonkType :: ZonkEnv -> UnboundTyVarZonker -> ZonkEnv setZonkType (ZonkEnv _ ty_env id_env) zonk_ty = ZonkEnv zonk_ty ty_env id_env zonkEnvIds :: ZonkEnv -> TypeEnv zonkEnvIds (ZonkEnv _ _ id_env) = mkNameEnv [(getName id, AnId id) | id <- nonDetEltsUFM id_env] -- It's OK to use nonDetEltsUFM here because we forget the ordering -- immediately by creating a TypeEnv zonkIdOcc :: ZonkEnv -> TcId -> Id -- Ids defined in this module should be in the envt; -- ignore others. (Actually, data constructors are also -- not LocalVars, even when locally defined, but that is fine.) -- (Also foreign-imported things aren't currently in the ZonkEnv; -- that's ok because they don't need zonking.) -- -- Actually, Template Haskell works in 'chunks' of declarations, and -- an earlier chunk won't be in the 'env' that the zonking phase -- carries around. Instead it'll be in the tcg_gbl_env, already fully -- zonked. There's no point in looking it up there (except for error -- checking), and it's not conveniently to hand; hence the simple -- 'orElse' case in the LocalVar branch. -- -- Even without template splices, in module Main, the checking of -- 'main' is done as a separate chunk. zonkIdOcc (ZonkEnv _zonk_ty _ty_env id_env) id | isLocalVar id = lookupVarEnv id_env id `orElse` id | otherwise = id zonkIdOccs :: ZonkEnv -> [TcId] -> [Id] zonkIdOccs env ids = map (zonkIdOcc env) ids -- zonkIdBndr is used *after* typechecking to get the Id's type -- to its final form. The TyVarEnv give zonkIdBndr :: ZonkEnv -> TcId -> TcM Id zonkIdBndr env id = do ty' <- zonkTcTypeToType env (idType id) ensureNotRepresentationPolymorphic ty' (text "In the type of binder" <+> quotes (ppr id)) return (setIdType id ty') zonkIdBndrs :: ZonkEnv -> [TcId] -> TcM [Id] zonkIdBndrs env ids = mapM (zonkIdBndr env) ids zonkTopBndrs :: [TcId] -> TcM [Id] zonkTopBndrs ids = zonkIdBndrs emptyZonkEnv ids zonkFieldOcc :: ZonkEnv -> FieldOcc TcId -> TcM (FieldOcc Id) zonkFieldOcc env (FieldOcc lbl sel) = fmap (FieldOcc lbl) $ zonkIdBndr env sel zonkEvBndrsX :: ZonkEnv -> [EvVar] -> TcM (ZonkEnv, [Var]) zonkEvBndrsX = mapAccumLM zonkEvBndrX zonkEvBndrX :: ZonkEnv -> EvVar -> TcM (ZonkEnv, EvVar) -- Works for dictionaries and coercions zonkEvBndrX env var = do { var' <- zonkEvBndr env var ; return (extendZonkEnv env [var'], var') } zonkEvBndr :: ZonkEnv -> EvVar -> TcM EvVar -- Works for dictionaries and coercions -- Does not extend the ZonkEnv zonkEvBndr env var = do { let var_ty = varType var ; ty <- {-# SCC "zonkEvBndr_zonkTcTypeToType" #-} zonkTcTypeToType env var_ty ; return (setVarType var ty) } zonkEvVarOcc :: ZonkEnv -> EvVar -> TcM EvTerm zonkEvVarOcc env v | isCoVar v = EvCoercion <$> zonkCoVarOcc env v | otherwise = return (EvId $ zonkIdOcc env v) zonkTyBndrsX :: ZonkEnv -> [TcTyVar] -> TcM (ZonkEnv, [TyVar]) zonkTyBndrsX = mapAccumLM zonkTyBndrX zonkTyBndrX :: ZonkEnv -> TcTyVar -> TcM (ZonkEnv, TyVar) -- This guarantees to return a TyVar (not a TcTyVar) -- then we add it to the envt, so all occurrences are replaced zonkTyBndrX env tv = ASSERT( isImmutableTyVar tv ) do { ki <- zonkTcTypeToType env (tyVarKind tv) -- Internal names tidy up better, for iface files. ; let tv' = mkTyVar (tyVarName tv) ki ; return (extendTyZonkEnv1 env tv', tv') } zonkTyVarBindersX :: ZonkEnv -> [TyVarBndr TcTyVar vis] -> TcM (ZonkEnv, [TyVarBndr TyVar vis]) zonkTyVarBindersX = mapAccumLM zonkTyVarBinderX zonkTyVarBinderX :: ZonkEnv -> TyVarBndr TcTyVar vis -> TcM (ZonkEnv, TyVarBndr TyVar vis) -- Takes a TcTyVar and guarantees to return a TyVar zonkTyVarBinderX env (TvBndr tv vis) = do { (env', tv') <- zonkTyBndrX env tv ; return (env', TvBndr tv' vis) } zonkTopExpr :: HsExpr TcId -> TcM (HsExpr Id) zonkTopExpr e = zonkExpr emptyZonkEnv e zonkTopLExpr :: LHsExpr TcId -> TcM (LHsExpr Id) zonkTopLExpr e = zonkLExpr emptyZonkEnv e zonkTopDecls :: Bag EvBind -> LHsBinds TcId -> [LRuleDecl TcId] -> [LVectDecl TcId] -> [LTcSpecPrag] -> [LForeignDecl TcId] -> TcM (TypeEnv, Bag EvBind, LHsBinds Id, [LForeignDecl Id], [LTcSpecPrag], [LRuleDecl Id], [LVectDecl Id]) zonkTopDecls ev_binds binds rules vects imp_specs fords = do { (env1, ev_binds') <- zonkEvBinds emptyZonkEnv ev_binds ; (env2, binds') <- zonkRecMonoBinds env1 binds -- Top level is implicitly recursive ; rules' <- zonkRules env2 rules ; vects' <- zonkVects env2 vects ; specs' <- zonkLTcSpecPrags env2 imp_specs ; fords' <- zonkForeignExports env2 fords ; return (zonkEnvIds env2, ev_binds', binds', fords', specs', rules', vects') } --------------------------------------------- zonkLocalBinds :: ZonkEnv -> HsLocalBinds TcId -> TcM (ZonkEnv, HsLocalBinds Id) zonkLocalBinds env EmptyLocalBinds = return (env, EmptyLocalBinds) zonkLocalBinds _ (HsValBinds (ValBindsIn {})) = panic "zonkLocalBinds" -- Not in typechecker output zonkLocalBinds env (HsValBinds (ValBindsOut binds sigs)) = do { (env1, new_binds) <- go env binds ; return (env1, HsValBinds (ValBindsOut new_binds sigs)) } where go env [] = return (env, []) go env ((r,b):bs) = do { (env1, b') <- zonkRecMonoBinds env b ; (env2, bs') <- go env1 bs ; return (env2, (r,b'):bs') } zonkLocalBinds env (HsIPBinds (IPBinds binds dict_binds)) = do new_binds <- mapM (wrapLocM zonk_ip_bind) binds let env1 = extendIdZonkEnvRec env [ n | L _ (IPBind (Right n) _) <- new_binds] (env2, new_dict_binds) <- zonkTcEvBinds env1 dict_binds return (env2, HsIPBinds (IPBinds new_binds new_dict_binds)) where zonk_ip_bind (IPBind n e) = do n' <- mapIPNameTc (zonkIdBndr env) n e' <- zonkLExpr env e return (IPBind n' e') --------------------------------------------- zonkRecMonoBinds :: ZonkEnv -> LHsBinds TcId -> TcM (ZonkEnv, LHsBinds Id) zonkRecMonoBinds env binds = fixM (\ ~(_, new_binds) -> do { let env1 = extendIdZonkEnvRec env (collectHsBindsBinders new_binds) ; binds' <- zonkMonoBinds env1 binds ; return (env1, binds') }) --------------------------------------------- zonkMonoBinds :: ZonkEnv -> LHsBinds TcId -> TcM (LHsBinds Id) zonkMonoBinds env binds = mapBagM (zonk_lbind env) binds zonk_lbind :: ZonkEnv -> LHsBind TcId -> TcM (LHsBind Id) zonk_lbind env = wrapLocM (zonk_bind env) zonk_bind :: ZonkEnv -> HsBind TcId -> TcM (HsBind Id) zonk_bind env bind@(PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty}) = do { (_env, new_pat) <- zonkPat env pat -- Env already extended ; new_grhss <- zonkGRHSs env zonkLExpr grhss ; new_ty <- zonkTcTypeToType env ty ; return (bind { pat_lhs = new_pat, pat_rhs = new_grhss, pat_rhs_ty = new_ty }) } zonk_bind env (VarBind { var_id = var, var_rhs = expr, var_inline = inl }) = do { new_var <- zonkIdBndr env var ; new_expr <- zonkLExpr env expr ; return (VarBind { var_id = new_var, var_rhs = new_expr, var_inline = inl }) } zonk_bind env bind@(FunBind { fun_id = L loc var, fun_matches = ms , fun_co_fn = co_fn }) = do { new_var <- zonkIdBndr env var ; (env1, new_co_fn) <- zonkCoFn env co_fn ; new_ms <- zonkMatchGroup env1 zonkLExpr ms ; return (bind { fun_id = L loc new_var, fun_matches = new_ms , fun_co_fn = new_co_fn }) } zonk_bind env (AbsBinds { abs_tvs = tyvars, abs_ev_vars = evs , abs_ev_binds = ev_binds , abs_exports = exports , abs_binds = val_binds }) = ASSERT( all isImmutableTyVar tyvars ) do { (env0, new_tyvars) <- zonkTyBndrsX env tyvars ; (env1, new_evs) <- zonkEvBndrsX env0 evs ; (env2, new_ev_binds) <- zonkTcEvBinds_s env1 ev_binds ; (new_val_bind, new_exports) <- fixM $ \ ~(new_val_binds, _) -> do { let env3 = extendIdZonkEnvRec env2 (collectHsBindsBinders new_val_binds) ; new_val_binds <- zonkMonoBinds env3 val_binds ; new_exports <- mapM (zonkExport env3) exports ; return (new_val_binds, new_exports) } ; return (AbsBinds { abs_tvs = new_tyvars, abs_ev_vars = new_evs , abs_ev_binds = new_ev_binds , abs_exports = new_exports, abs_binds = new_val_bind }) } where zonkExport env (ABE{ abe_wrap = wrap , abe_poly = poly_id , abe_mono = mono_id, abe_prags = prags }) = do new_poly_id <- zonkIdBndr env poly_id (_, new_wrap) <- zonkCoFn env wrap new_prags <- zonkSpecPrags env prags return (ABE{ abe_wrap = new_wrap , abe_poly = new_poly_id , abe_mono = zonkIdOcc env mono_id , abe_prags = new_prags }) zonk_bind env outer_bind@(AbsBindsSig { abs_tvs = tyvars , abs_ev_vars = evs , abs_sig_export = poly , abs_sig_prags = prags , abs_sig_ev_bind = ev_bind , abs_sig_bind = lbind }) | L bind_loc bind@(FunBind { fun_id = L loc local , fun_matches = ms , fun_co_fn = co_fn }) <- lbind = ASSERT( all isImmutableTyVar tyvars ) do { (env0, new_tyvars) <- zonkTyBndrsX env tyvars ; (env1, new_evs) <- zonkEvBndrsX env0 evs ; (env2, new_ev_bind) <- zonkTcEvBinds env1 ev_bind -- Inline zonk_bind (FunBind ...) because we wish to skip -- the check for representation-polymorphic binders. The -- local binder in the FunBind in an AbsBindsSig is never actually -- bound in Core -- indeed, that's the whole point of AbsBindsSig. -- just calling zonk_bind causes #11405. ; new_local <- updateVarTypeM (zonkTcTypeToType env2) local ; (env3, new_co_fn) <- zonkCoFn env2 co_fn ; new_ms <- zonkMatchGroup env3 zonkLExpr ms -- If there is a representation polymorphism problem, it will -- be caught here: ; new_poly_id <- zonkIdBndr env2 poly ; new_prags <- zonkSpecPrags env2 prags ; let new_val_bind = L bind_loc (bind { fun_id = L loc new_local , fun_matches = new_ms , fun_co_fn = new_co_fn }) ; return (AbsBindsSig { abs_tvs = new_tyvars , abs_ev_vars = new_evs , abs_sig_export = new_poly_id , abs_sig_prags = new_prags , abs_sig_ev_bind = new_ev_bind , abs_sig_bind = new_val_bind }) } | otherwise = pprPanic "zonk_bind" (ppr outer_bind) zonk_bind env (PatSynBind bind@(PSB { psb_id = L loc id , psb_args = details , psb_def = lpat , psb_dir = dir })) = do { id' <- zonkIdBndr env id ; details' <- zonkPatSynDetails env details ; (env1, lpat') <- zonkPat env lpat ; (_env2, dir') <- zonkPatSynDir env1 dir ; return $ PatSynBind $ bind { psb_id = L loc id' , psb_args = details' , psb_def = lpat' , psb_dir = dir' } } zonkPatSynDetails :: ZonkEnv -> HsPatSynDetails (Located TcId) -> TcM (HsPatSynDetails (Located Id)) zonkPatSynDetails env = traverse (wrapLocM $ zonkIdBndr env) zonkPatSynDir :: ZonkEnv -> HsPatSynDir TcId -> TcM (ZonkEnv, HsPatSynDir Id) zonkPatSynDir env Unidirectional = return (env, Unidirectional) zonkPatSynDir env ImplicitBidirectional = return (env, ImplicitBidirectional) zonkPatSynDir env (ExplicitBidirectional mg) = do mg' <- zonkMatchGroup env zonkLExpr mg return (env, ExplicitBidirectional mg') zonkSpecPrags :: ZonkEnv -> TcSpecPrags -> TcM TcSpecPrags zonkSpecPrags _ IsDefaultMethod = return IsDefaultMethod zonkSpecPrags env (SpecPrags ps) = do { ps' <- zonkLTcSpecPrags env ps ; return (SpecPrags ps') } zonkLTcSpecPrags :: ZonkEnv -> [LTcSpecPrag] -> TcM [LTcSpecPrag] zonkLTcSpecPrags env ps = mapM zonk_prag ps where zonk_prag (L loc (SpecPrag id co_fn inl)) = do { (_, co_fn') <- zonkCoFn env co_fn ; return (L loc (SpecPrag (zonkIdOcc env id) co_fn' inl)) } {- ************************************************************************ * * \subsection[BackSubst-Match-GRHSs]{Match and GRHSs} * * ************************************************************************ -} zonkMatchGroup :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> MatchGroup TcId (Located (body TcId)) -> TcM (MatchGroup Id (Located (body Id))) zonkMatchGroup env zBody (MG { mg_alts = L l ms, mg_arg_tys = arg_tys , mg_res_ty = res_ty, mg_origin = origin }) = do { ms' <- mapM (zonkMatch env zBody) ms ; arg_tys' <- zonkTcTypeToTypes env arg_tys ; res_ty' <- zonkTcTypeToType env res_ty ; return (MG { mg_alts = L l ms', mg_arg_tys = arg_tys' , mg_res_ty = res_ty', mg_origin = origin }) } zonkMatch :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> LMatch TcId (Located (body TcId)) -> TcM (LMatch Id (Located (body Id))) zonkMatch env zBody (L loc (Match mf pats _ grhss)) = do { (env1, new_pats) <- zonkPats env pats ; new_grhss <- zonkGRHSs env1 zBody grhss ; return (L loc (Match mf new_pats Nothing new_grhss)) } ------------------------------------------------------------------------- zonkGRHSs :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> GRHSs TcId (Located (body TcId)) -> TcM (GRHSs Id (Located (body Id))) zonkGRHSs env zBody (GRHSs grhss (L l binds)) = do (new_env, new_binds) <- zonkLocalBinds env binds let zonk_grhs (GRHS guarded rhs) = do (env2, new_guarded) <- zonkStmts new_env zonkLExpr guarded new_rhs <- zBody env2 rhs return (GRHS new_guarded new_rhs) new_grhss <- mapM (wrapLocM zonk_grhs) grhss return (GRHSs new_grhss (L l new_binds)) {- ************************************************************************ * * \subsection[BackSubst-HsExpr]{Running a zonkitution over a TypeCheckedExpr} * * ************************************************************************ -} zonkLExprs :: ZonkEnv -> [LHsExpr TcId] -> TcM [LHsExpr Id] zonkLExpr :: ZonkEnv -> LHsExpr TcId -> TcM (LHsExpr Id) zonkExpr :: ZonkEnv -> HsExpr TcId -> TcM (HsExpr Id) zonkLExprs env exprs = mapM (zonkLExpr env) exprs zonkLExpr env expr = wrapLocM (zonkExpr env) expr zonkExpr env (HsVar (L l id)) = return (HsVar (L l (zonkIdOcc env id))) zonkExpr _ (HsIPVar id) = return (HsIPVar id) zonkExpr _ (HsOverLabel l) = return (HsOverLabel l) zonkExpr env (HsLit (HsRat f ty)) = do new_ty <- zonkTcTypeToType env ty return (HsLit (HsRat f new_ty)) zonkExpr _ (HsLit lit) = return (HsLit lit) zonkExpr env (HsOverLit lit) = do { lit' <- zonkOverLit env lit ; return (HsOverLit lit') } zonkExpr env (HsLam matches) = do new_matches <- zonkMatchGroup env zonkLExpr matches return (HsLam new_matches) zonkExpr env (HsLamCase matches) = do new_matches <- zonkMatchGroup env zonkLExpr matches return (HsLamCase new_matches) zonkExpr env (HsApp e1 e2) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 return (HsApp new_e1 new_e2) zonkExpr env (HsAppTypeOut e t) = do new_e <- zonkLExpr env e return (HsAppTypeOut new_e t) -- NB: the type is an HsType; can't zonk that! zonkExpr _ e@(HsRnBracketOut _ _) = pprPanic "zonkExpr: HsRnBracketOut" (ppr e) zonkExpr env (HsTcBracketOut body bs) = do bs' <- mapM zonk_b bs return (HsTcBracketOut body bs') where zonk_b (PendingTcSplice n e) = do e' <- zonkLExpr env e return (PendingTcSplice n e') zonkExpr _ (HsSpliceE s) = WARN( True, ppr s ) -- Should not happen return (HsSpliceE s) zonkExpr env (OpApp e1 op fixity e2) = do new_e1 <- zonkLExpr env e1 new_op <- zonkLExpr env op new_e2 <- zonkLExpr env e2 return (OpApp new_e1 new_op fixity new_e2) zonkExpr env (NegApp expr op) = do (env', new_op) <- zonkSyntaxExpr env op new_expr <- zonkLExpr env' expr return (NegApp new_expr new_op) zonkExpr env (HsPar e) = do new_e <- zonkLExpr env e return (HsPar new_e) zonkExpr env (SectionL expr op) = do new_expr <- zonkLExpr env expr new_op <- zonkLExpr env op return (SectionL new_expr new_op) zonkExpr env (SectionR op expr) = do new_op <- zonkLExpr env op new_expr <- zonkLExpr env expr return (SectionR new_op new_expr) zonkExpr env (ExplicitTuple tup_args boxed) = do { new_tup_args <- mapM zonk_tup_arg tup_args ; return (ExplicitTuple new_tup_args boxed) } where zonk_tup_arg (L l (Present e)) = do { e' <- zonkLExpr env e ; return (L l (Present e')) } zonk_tup_arg (L l (Missing t)) = do { t' <- zonkTcTypeToType env t ; return (L l (Missing t')) } zonkExpr env (ExplicitSum alt arity expr args) = do new_args <- mapM (zonkTcTypeToType env) args new_expr <- zonkLExpr env expr return (ExplicitSum alt arity new_expr new_args) zonkExpr env (HsCase expr ms) = do new_expr <- zonkLExpr env expr new_ms <- zonkMatchGroup env zonkLExpr ms return (HsCase new_expr new_ms) zonkExpr env (HsIf Nothing e1 e2 e3) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 new_e3 <- zonkLExpr env e3 return (HsIf Nothing new_e1 new_e2 new_e3) zonkExpr env (HsIf (Just fun) e1 e2 e3) = do (env1, new_fun) <- zonkSyntaxExpr env fun new_e1 <- zonkLExpr env1 e1 new_e2 <- zonkLExpr env1 e2 new_e3 <- zonkLExpr env1 e3 return (HsIf (Just new_fun) new_e1 new_e2 new_e3) zonkExpr env (HsMultiIf ty alts) = do { alts' <- mapM (wrapLocM zonk_alt) alts ; ty' <- zonkTcTypeToType env ty ; return $ HsMultiIf ty' alts' } where zonk_alt (GRHS guard expr) = do { (env', guard') <- zonkStmts env zonkLExpr guard ; expr' <- zonkLExpr env' expr ; return $ GRHS guard' expr' } zonkExpr env (HsLet (L l binds) expr) = do (new_env, new_binds) <- zonkLocalBinds env binds new_expr <- zonkLExpr new_env expr return (HsLet (L l new_binds) new_expr) zonkExpr env (HsDo do_or_lc (L l stmts) ty) = do (_, new_stmts) <- zonkStmts env zonkLExpr stmts new_ty <- zonkTcTypeToType env ty return (HsDo do_or_lc (L l new_stmts) new_ty) zonkExpr env (ExplicitList ty wit exprs) = do (env1, new_wit) <- zonkWit env wit new_ty <- zonkTcTypeToType env1 ty new_exprs <- zonkLExprs env1 exprs return (ExplicitList new_ty new_wit new_exprs) where zonkWit env Nothing = return (env, Nothing) zonkWit env (Just fln) = second Just <$> zonkSyntaxExpr env fln zonkExpr env (ExplicitPArr ty exprs) = do new_ty <- zonkTcTypeToType env ty new_exprs <- zonkLExprs env exprs return (ExplicitPArr new_ty new_exprs) zonkExpr env expr@(RecordCon { rcon_con_expr = con_expr, rcon_flds = rbinds }) = do { new_con_expr <- zonkExpr env con_expr ; new_rbinds <- zonkRecFields env rbinds ; return (expr { rcon_con_expr = new_con_expr , rcon_flds = new_rbinds }) } zonkExpr env (RecordUpd { rupd_expr = expr, rupd_flds = rbinds , rupd_cons = cons, rupd_in_tys = in_tys , rupd_out_tys = out_tys, rupd_wrap = req_wrap }) = do { new_expr <- zonkLExpr env expr ; new_in_tys <- mapM (zonkTcTypeToType env) in_tys ; new_out_tys <- mapM (zonkTcTypeToType env) out_tys ; new_rbinds <- zonkRecUpdFields env rbinds ; (_, new_recwrap) <- zonkCoFn env req_wrap ; return (RecordUpd { rupd_expr = new_expr, rupd_flds = new_rbinds , rupd_cons = cons, rupd_in_tys = new_in_tys , rupd_out_tys = new_out_tys, rupd_wrap = new_recwrap }) } zonkExpr env (ExprWithTySigOut e ty) = do { e' <- zonkLExpr env e ; return (ExprWithTySigOut e' ty) } zonkExpr env (ArithSeq expr wit info) = do (env1, new_wit) <- zonkWit env wit new_expr <- zonkExpr env expr new_info <- zonkArithSeq env1 info return (ArithSeq new_expr new_wit new_info) where zonkWit env Nothing = return (env, Nothing) zonkWit env (Just fln) = second Just <$> zonkSyntaxExpr env fln zonkExpr env (PArrSeq expr info) = do new_expr <- zonkExpr env expr new_info <- zonkArithSeq env info return (PArrSeq new_expr new_info) zonkExpr env (HsSCC src lbl expr) = do new_expr <- zonkLExpr env expr return (HsSCC src lbl new_expr) zonkExpr env (HsTickPragma src info srcInfo expr) = do new_expr <- zonkLExpr env expr return (HsTickPragma src info srcInfo new_expr) -- hdaume: core annotations zonkExpr env (HsCoreAnn src lbl expr) = do new_expr <- zonkLExpr env expr return (HsCoreAnn src lbl new_expr) -- arrow notation extensions zonkExpr env (HsProc pat body) = do { (env1, new_pat) <- zonkPat env pat ; new_body <- zonkCmdTop env1 body ; return (HsProc new_pat new_body) } -- StaticPointers extension zonkExpr env (HsStatic fvs expr) = HsStatic fvs <$> zonkLExpr env expr zonkExpr env (HsWrap co_fn expr) = do (env1, new_co_fn) <- zonkCoFn env co_fn new_expr <- zonkExpr env1 expr return (HsWrap new_co_fn new_expr) zonkExpr _ e@(HsUnboundVar {}) = return e zonkExpr _ expr = pprPanic "zonkExpr" (ppr expr) ------------------------------------------------------------------------- {- Note [Skolems in zonkSyntaxExpr] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider rebindable syntax with something like (>>=) :: (forall x. blah) -> (forall y. blah') -> blah'' The x and y become skolems that are in scope when type-checking the arguments to the bind. This means that we must extend the ZonkEnv with these skolems when zonking the arguments to the bind. But the skolems are different between the two arguments, and so we should theoretically carry around different environments to use for the different arguments. However, this becomes a logistical nightmare, especially in dealing with the more exotic Stmt forms. So, we simplify by making the critical assumption that the uniques of the skolems are different. (This assumption is justified by the use of newUnique in TcMType.instSkolTyCoVarX.) Now, we can safely just extend one environment. -} -- See Note [Skolems in zonkSyntaxExpr] zonkSyntaxExpr :: ZonkEnv -> SyntaxExpr TcId -> TcM (ZonkEnv, SyntaxExpr Id) zonkSyntaxExpr env (SyntaxExpr { syn_expr = expr , syn_arg_wraps = arg_wraps , syn_res_wrap = res_wrap }) = do { (env0, res_wrap') <- zonkCoFn env res_wrap ; expr' <- zonkExpr env0 expr ; (env1, arg_wraps') <- mapAccumLM zonkCoFn env0 arg_wraps ; return (env1, SyntaxExpr { syn_expr = expr' , syn_arg_wraps = arg_wraps' , syn_res_wrap = res_wrap' }) } ------------------------------------------------------------------------- zonkLCmd :: ZonkEnv -> LHsCmd TcId -> TcM (LHsCmd Id) zonkCmd :: ZonkEnv -> HsCmd TcId -> TcM (HsCmd Id) zonkLCmd env cmd = wrapLocM (zonkCmd env) cmd zonkCmd env (HsCmdWrap w cmd) = do { (env1, w') <- zonkCoFn env w ; cmd' <- zonkCmd env1 cmd ; return (HsCmdWrap w' cmd') } zonkCmd env (HsCmdArrApp e1 e2 ty ho rl) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 new_ty <- zonkTcTypeToType env ty return (HsCmdArrApp new_e1 new_e2 new_ty ho rl) zonkCmd env (HsCmdArrForm op fixity args) = do new_op <- zonkLExpr env op new_args <- mapM (zonkCmdTop env) args return (HsCmdArrForm new_op fixity new_args) zonkCmd env (HsCmdApp c e) = do new_c <- zonkLCmd env c new_e <- zonkLExpr env e return (HsCmdApp new_c new_e) zonkCmd env (HsCmdLam matches) = do new_matches <- zonkMatchGroup env zonkLCmd matches return (HsCmdLam new_matches) zonkCmd env (HsCmdPar c) = do new_c <- zonkLCmd env c return (HsCmdPar new_c) zonkCmd env (HsCmdCase expr ms) = do new_expr <- zonkLExpr env expr new_ms <- zonkMatchGroup env zonkLCmd ms return (HsCmdCase new_expr new_ms) zonkCmd env (HsCmdIf eCond ePred cThen cElse) = do { (env1, new_eCond) <- zonkWit env eCond ; new_ePred <- zonkLExpr env1 ePred ; new_cThen <- zonkLCmd env1 cThen ; new_cElse <- zonkLCmd env1 cElse ; return (HsCmdIf new_eCond new_ePred new_cThen new_cElse) } where zonkWit env Nothing = return (env, Nothing) zonkWit env (Just w) = second Just <$> zonkSyntaxExpr env w zonkCmd env (HsCmdLet (L l binds) cmd) = do (new_env, new_binds) <- zonkLocalBinds env binds new_cmd <- zonkLCmd new_env cmd return (HsCmdLet (L l new_binds) new_cmd) zonkCmd env (HsCmdDo (L l stmts) ty) = do (_, new_stmts) <- zonkStmts env zonkLCmd stmts new_ty <- zonkTcTypeToType env ty return (HsCmdDo (L l new_stmts) new_ty) zonkCmdTop :: ZonkEnv -> LHsCmdTop TcId -> TcM (LHsCmdTop Id) zonkCmdTop env cmd = wrapLocM (zonk_cmd_top env) cmd zonk_cmd_top :: ZonkEnv -> HsCmdTop TcId -> TcM (HsCmdTop Id) zonk_cmd_top env (HsCmdTop cmd stack_tys ty ids) = do new_cmd <- zonkLCmd env cmd new_stack_tys <- zonkTcTypeToType env stack_tys new_ty <- zonkTcTypeToType env ty new_ids <- mapSndM (zonkExpr env) ids return (HsCmdTop new_cmd new_stack_tys new_ty new_ids) ------------------------------------------------------------------------- zonkCoFn :: ZonkEnv -> HsWrapper -> TcM (ZonkEnv, HsWrapper) zonkCoFn env WpHole = return (env, WpHole) zonkCoFn env (WpCompose c1 c2) = do { (env1, c1') <- zonkCoFn env c1 ; (env2, c2') <- zonkCoFn env1 c2 ; return (env2, WpCompose c1' c2') } zonkCoFn env (WpFun c1 c2 t1) = do { (env1, c1') <- zonkCoFn env c1 ; (env2, c2') <- zonkCoFn env1 c2 ; t1' <- zonkTcTypeToType env2 t1 ; return (env2, WpFun c1' c2' t1') } zonkCoFn env (WpCast co) = do { co' <- zonkCoToCo env co ; return (env, WpCast co') } zonkCoFn env (WpEvLam ev) = do { (env', ev') <- zonkEvBndrX env ev ; return (env', WpEvLam ev') } zonkCoFn env (WpEvApp arg) = do { arg' <- zonkEvTerm env arg ; return (env, WpEvApp arg') } zonkCoFn env (WpTyLam tv) = ASSERT( isImmutableTyVar tv ) do { (env', tv') <- zonkTyBndrX env tv ; return (env', WpTyLam tv') } zonkCoFn env (WpTyApp ty) = do { ty' <- zonkTcTypeToType env ty ; return (env, WpTyApp ty') } zonkCoFn env (WpLet bs) = do { (env1, bs') <- zonkTcEvBinds env bs ; return (env1, WpLet bs') } ------------------------------------------------------------------------- zonkOverLit :: ZonkEnv -> HsOverLit TcId -> TcM (HsOverLit Id) zonkOverLit env lit@(OverLit { ol_witness = e, ol_type = ty }) = do { ty' <- zonkTcTypeToType env ty ; e' <- zonkExpr env e ; return (lit { ol_witness = e', ol_type = ty' }) } ------------------------------------------------------------------------- zonkArithSeq :: ZonkEnv -> ArithSeqInfo TcId -> TcM (ArithSeqInfo Id) zonkArithSeq env (From e) = do new_e <- zonkLExpr env e return (From new_e) zonkArithSeq env (FromThen e1 e2) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 return (FromThen new_e1 new_e2) zonkArithSeq env (FromTo e1 e2) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 return (FromTo new_e1 new_e2) zonkArithSeq env (FromThenTo e1 e2 e3) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 new_e3 <- zonkLExpr env e3 return (FromThenTo new_e1 new_e2 new_e3) ------------------------------------------------------------------------- zonkStmts :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> [LStmt TcId (Located (body TcId))] -> TcM (ZonkEnv, [LStmt Id (Located (body Id))]) zonkStmts env _ [] = return (env, []) zonkStmts env zBody (s:ss) = do { (env1, s') <- wrapLocSndM (zonkStmt env zBody) s ; (env2, ss') <- zonkStmts env1 zBody ss ; return (env2, s' : ss') } zonkStmt :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> Stmt TcId (Located (body TcId)) -> TcM (ZonkEnv, Stmt Id (Located (body Id))) zonkStmt env _ (ParStmt stmts_w_bndrs mzip_op bind_op bind_ty) = do { (env1, new_bind_op) <- zonkSyntaxExpr env bind_op ; new_bind_ty <- zonkTcTypeToType env1 bind_ty ; new_stmts_w_bndrs <- mapM (zonk_branch env1) stmts_w_bndrs ; let new_binders = [b | ParStmtBlock _ bs _ <- new_stmts_w_bndrs, b <- bs] env2 = extendIdZonkEnvRec env1 new_binders ; new_mzip <- zonkExpr env2 mzip_op ; return (env2, ParStmt new_stmts_w_bndrs new_mzip new_bind_op new_bind_ty) } where zonk_branch env1 (ParStmtBlock stmts bndrs return_op) = do { (env2, new_stmts) <- zonkStmts env1 zonkLExpr stmts ; (env3, new_return) <- zonkSyntaxExpr env2 return_op ; return (ParStmtBlock new_stmts (zonkIdOccs env3 bndrs) new_return) } zonkStmt env zBody (RecStmt { recS_stmts = segStmts, recS_later_ids = lvs, recS_rec_ids = rvs , recS_ret_fn = ret_id, recS_mfix_fn = mfix_id , recS_bind_fn = bind_id, recS_bind_ty = bind_ty , recS_later_rets = later_rets, recS_rec_rets = rec_rets , recS_ret_ty = ret_ty }) = do { (env1, new_bind_id) <- zonkSyntaxExpr env bind_id ; (env2, new_mfix_id) <- zonkSyntaxExpr env1 mfix_id ; (env3, new_ret_id) <- zonkSyntaxExpr env2 ret_id ; new_bind_ty <- zonkTcTypeToType env3 bind_ty ; new_rvs <- zonkIdBndrs env3 rvs ; new_lvs <- zonkIdBndrs env3 lvs ; new_ret_ty <- zonkTcTypeToType env3 ret_ty ; let env4 = extendIdZonkEnvRec env3 new_rvs ; (env5, new_segStmts) <- zonkStmts env4 zBody segStmts -- Zonk the ret-expressions in an envt that -- has the polymorphic bindings in the envt ; new_later_rets <- mapM (zonkExpr env5) later_rets ; new_rec_rets <- mapM (zonkExpr env5) rec_rets ; return (extendIdZonkEnvRec env3 new_lvs, -- Only the lvs are needed RecStmt { recS_stmts = new_segStmts, recS_later_ids = new_lvs , recS_rec_ids = new_rvs, recS_ret_fn = new_ret_id , recS_mfix_fn = new_mfix_id, recS_bind_fn = new_bind_id , recS_bind_ty = new_bind_ty , recS_later_rets = new_later_rets , recS_rec_rets = new_rec_rets, recS_ret_ty = new_ret_ty }) } zonkStmt env zBody (BodyStmt body then_op guard_op ty) = do (env1, new_then_op) <- zonkSyntaxExpr env then_op (env2, new_guard_op) <- zonkSyntaxExpr env1 guard_op new_body <- zBody env2 body new_ty <- zonkTcTypeToType env2 ty return (env2, BodyStmt new_body new_then_op new_guard_op new_ty) zonkStmt env zBody (LastStmt body noret ret_op) = do (env1, new_ret) <- zonkSyntaxExpr env ret_op new_body <- zBody env1 body return (env, LastStmt new_body noret new_ret) zonkStmt env _ (TransStmt { trS_stmts = stmts, trS_bndrs = binderMap , trS_by = by, trS_form = form, trS_using = using , trS_ret = return_op, trS_bind = bind_op , trS_bind_arg_ty = bind_arg_ty , trS_fmap = liftM_op }) = do { ; (env1, bind_op') <- zonkSyntaxExpr env bind_op ; bind_arg_ty' <- zonkTcTypeToType env1 bind_arg_ty ; (env2, stmts') <- zonkStmts env1 zonkLExpr stmts ; by' <- fmapMaybeM (zonkLExpr env2) by ; using' <- zonkLExpr env2 using ; (env3, return_op') <- zonkSyntaxExpr env2 return_op ; binderMap' <- mapM (zonkBinderMapEntry env3) binderMap ; liftM_op' <- zonkExpr env3 liftM_op ; let env3' = extendIdZonkEnvRec env3 (map snd binderMap') ; return (env3', TransStmt { trS_stmts = stmts', trS_bndrs = binderMap' , trS_by = by', trS_form = form, trS_using = using' , trS_ret = return_op', trS_bind = bind_op' , trS_bind_arg_ty = bind_arg_ty' , trS_fmap = liftM_op' }) } where zonkBinderMapEntry env (oldBinder, newBinder) = do let oldBinder' = zonkIdOcc env oldBinder newBinder' <- zonkIdBndr env newBinder return (oldBinder', newBinder') zonkStmt env _ (LetStmt (L l binds)) = do (env1, new_binds) <- zonkLocalBinds env binds return (env1, LetStmt (L l new_binds)) zonkStmt env zBody (BindStmt pat body bind_op fail_op bind_ty) = do { (env1, new_bind) <- zonkSyntaxExpr env bind_op ; new_bind_ty <- zonkTcTypeToType env1 bind_ty ; new_body <- zBody env1 body ; (env2, new_pat) <- zonkPat env1 pat ; (_, new_fail) <- zonkSyntaxExpr env1 fail_op ; return (env2, BindStmt new_pat new_body new_bind new_fail new_bind_ty) } -- Scopes: join > ops (in reverse order) > pats (in forward order) -- > rest of stmts zonkStmt env _zBody (ApplicativeStmt args mb_join body_ty) = do { (env1, new_mb_join) <- zonk_join env mb_join ; (env2, new_args) <- zonk_args env1 args ; new_body_ty <- zonkTcTypeToType env2 body_ty ; return (env2, ApplicativeStmt new_args new_mb_join new_body_ty) } where zonk_join env Nothing = return (env, Nothing) zonk_join env (Just j) = second Just <$> zonkSyntaxExpr env j get_pat (_, ApplicativeArgOne pat _) = pat get_pat (_, ApplicativeArgMany _ _ pat) = pat replace_pat pat (op, ApplicativeArgOne _ a) = (op, ApplicativeArgOne pat a) replace_pat pat (op, ApplicativeArgMany a b _) = (op, ApplicativeArgMany a b pat) zonk_args env args = do { (env1, new_args_rev) <- zonk_args_rev env (reverse args) ; (env2, new_pats) <- zonkPats env1 (map get_pat args) ; return (env2, zipWith replace_pat new_pats (reverse new_args_rev)) } -- these need to go backward, because if any operators are higher-rank, -- later operators may introduce skolems that are in scope for earlier -- arguments zonk_args_rev env ((op, arg) : args) = do { (env1, new_op) <- zonkSyntaxExpr env op ; new_arg <- zonk_arg env1 arg ; (env2, new_args) <- zonk_args_rev env1 args ; return (env2, (new_op, new_arg) : new_args) } zonk_args_rev env [] = return (env, []) zonk_arg env (ApplicativeArgOne pat expr) = do { new_expr <- zonkLExpr env expr ; return (ApplicativeArgOne pat new_expr) } zonk_arg env (ApplicativeArgMany stmts ret pat) = do { (env1, new_stmts) <- zonkStmts env zonkLExpr stmts ; new_ret <- zonkExpr env1 ret ; return (ApplicativeArgMany new_stmts new_ret pat) } ------------------------------------------------------------------------- zonkRecFields :: ZonkEnv -> HsRecordBinds TcId -> TcM (HsRecordBinds TcId) zonkRecFields env (HsRecFields flds dd) = do { flds' <- mapM zonk_rbind flds ; return (HsRecFields flds' dd) } where zonk_rbind (L l fld) = do { new_id <- wrapLocM (zonkFieldOcc env) (hsRecFieldLbl fld) ; new_expr <- zonkLExpr env (hsRecFieldArg fld) ; return (L l (fld { hsRecFieldLbl = new_id , hsRecFieldArg = new_expr })) } zonkRecUpdFields :: ZonkEnv -> [LHsRecUpdField TcId] -> TcM [LHsRecUpdField TcId] zonkRecUpdFields env = mapM zonk_rbind where zonk_rbind (L l fld) = do { new_id <- wrapLocM (zonkFieldOcc env) (hsRecUpdFieldOcc fld) ; new_expr <- zonkLExpr env (hsRecFieldArg fld) ; return (L l (fld { hsRecFieldLbl = fmap ambiguousFieldOcc new_id , hsRecFieldArg = new_expr })) } ------------------------------------------------------------------------- mapIPNameTc :: (a -> TcM b) -> Either (Located HsIPName) a -> TcM (Either (Located HsIPName) b) mapIPNameTc _ (Left x) = return (Left x) mapIPNameTc f (Right x) = do r <- f x return (Right r) {- ************************************************************************ * * \subsection[BackSubst-Pats]{Patterns} * * ************************************************************************ -} zonkPat :: ZonkEnv -> OutPat TcId -> TcM (ZonkEnv, OutPat Id) -- Extend the environment as we go, because it's possible for one -- pattern to bind something that is used in another (inside or -- to the right) zonkPat env pat = wrapLocSndM (zonk_pat env) pat zonk_pat :: ZonkEnv -> Pat TcId -> TcM (ZonkEnv, Pat Id) zonk_pat env (ParPat p) = do { (env', p') <- zonkPat env p ; return (env', ParPat p') } zonk_pat env (WildPat ty) = do { ty' <- zonkTcTypeToType env ty ; ensureNotRepresentationPolymorphic ty' (text "In a wildcard pattern") ; return (env, WildPat ty') } zonk_pat env (VarPat (L l v)) = do { v' <- zonkIdBndr env v ; return (extendIdZonkEnv1 env v', VarPat (L l v')) } zonk_pat env (LazyPat pat) = do { (env', pat') <- zonkPat env pat ; return (env', LazyPat pat') } zonk_pat env (BangPat pat) = do { (env', pat') <- zonkPat env pat ; return (env', BangPat pat') } zonk_pat env (AsPat (L loc v) pat) = do { v' <- zonkIdBndr env v ; (env', pat') <- zonkPat (extendIdZonkEnv1 env v') pat ; return (env', AsPat (L loc v') pat') } zonk_pat env (ViewPat expr pat ty) = do { expr' <- zonkLExpr env expr ; (env', pat') <- zonkPat env pat ; ty' <- zonkTcTypeToType env ty ; return (env', ViewPat expr' pat' ty') } zonk_pat env (ListPat pats ty Nothing) = do { ty' <- zonkTcTypeToType env ty ; (env', pats') <- zonkPats env pats ; return (env', ListPat pats' ty' Nothing) } zonk_pat env (ListPat pats ty (Just (ty2,wit))) = do { (env', wit') <- zonkSyntaxExpr env wit ; ty2' <- zonkTcTypeToType env' ty2 ; ty' <- zonkTcTypeToType env' ty ; (env'', pats') <- zonkPats env' pats ; return (env'', ListPat pats' ty' (Just (ty2',wit'))) } zonk_pat env (PArrPat pats ty) = do { ty' <- zonkTcTypeToType env ty ; (env', pats') <- zonkPats env pats ; return (env', PArrPat pats' ty') } zonk_pat env (TuplePat pats boxed tys) = do { tys' <- mapM (zonkTcTypeToType env) tys ; (env', pats') <- zonkPats env pats ; return (env', TuplePat pats' boxed tys') } zonk_pat env (SumPat pat alt arity tys) = do { tys' <- mapM (zonkTcTypeToType env) tys ; (env', pat') <- zonkPat env pat ; return (env', SumPat pat' alt arity tys') } zonk_pat env p@(ConPatOut { pat_arg_tys = tys, pat_tvs = tyvars , pat_dicts = evs, pat_binds = binds , pat_args = args, pat_wrap = wrapper }) = ASSERT( all isImmutableTyVar tyvars ) do { new_tys <- mapM (zonkTcTypeToType env) tys ; (env0, new_tyvars) <- zonkTyBndrsX env tyvars -- Must zonk the existential variables, because their -- /kind/ need potential zonking. -- cf typecheck/should_compile/tc221.hs ; (env1, new_evs) <- zonkEvBndrsX env0 evs ; (env2, new_binds) <- zonkTcEvBinds env1 binds ; (env3, new_wrapper) <- zonkCoFn env2 wrapper ; (env', new_args) <- zonkConStuff env3 args ; return (env', p { pat_arg_tys = new_tys, pat_tvs = new_tyvars, pat_dicts = new_evs, pat_binds = new_binds, pat_args = new_args, pat_wrap = new_wrapper}) } zonk_pat env (LitPat lit) = return (env, LitPat lit) zonk_pat env (SigPatOut pat ty) = do { ty' <- zonkTcTypeToType env ty ; (env', pat') <- zonkPat env pat ; return (env', SigPatOut pat' ty') } zonk_pat env (NPat (L l lit) mb_neg eq_expr ty) = do { (env1, eq_expr') <- zonkSyntaxExpr env eq_expr ; (env2, mb_neg') <- case mb_neg of Nothing -> return (env1, Nothing) Just n -> second Just <$> zonkSyntaxExpr env1 n ; lit' <- zonkOverLit env2 lit ; ty' <- zonkTcTypeToType env2 ty ; return (env2, NPat (L l lit') mb_neg' eq_expr' ty') } zonk_pat env (NPlusKPat (L loc n) (L l lit1) lit2 e1 e2 ty) = do { (env1, e1') <- zonkSyntaxExpr env e1 ; (env2, e2') <- zonkSyntaxExpr env1 e2 ; n' <- zonkIdBndr env2 n ; lit1' <- zonkOverLit env2 lit1 ; lit2' <- zonkOverLit env2 lit2 ; ty' <- zonkTcTypeToType env2 ty ; return (extendIdZonkEnv1 env2 n', NPlusKPat (L loc n') (L l lit1') lit2' e1' e2' ty') } zonk_pat env (CoPat co_fn pat ty) = do { (env', co_fn') <- zonkCoFn env co_fn ; (env'', pat') <- zonkPat env' (noLoc pat) ; ty' <- zonkTcTypeToType env'' ty ; return (env'', CoPat co_fn' (unLoc pat') ty') } zonk_pat _ pat = pprPanic "zonk_pat" (ppr pat) --------------------------- zonkConStuff :: ZonkEnv -> HsConDetails (OutPat TcId) (HsRecFields id (OutPat TcId)) -> TcM (ZonkEnv, HsConDetails (OutPat Id) (HsRecFields id (OutPat Id))) zonkConStuff env (PrefixCon pats) = do { (env', pats') <- zonkPats env pats ; return (env', PrefixCon pats') } zonkConStuff env (InfixCon p1 p2) = do { (env1, p1') <- zonkPat env p1 ; (env', p2') <- zonkPat env1 p2 ; return (env', InfixCon p1' p2') } zonkConStuff env (RecCon (HsRecFields rpats dd)) = do { (env', pats') <- zonkPats env (map (hsRecFieldArg . unLoc) rpats) ; let rpats' = zipWith (\(L l rp) p' -> L l (rp { hsRecFieldArg = p' })) rpats pats' ; return (env', RecCon (HsRecFields rpats' dd)) } -- Field selectors have declared types; hence no zonking --------------------------- zonkPats :: ZonkEnv -> [OutPat TcId] -> TcM (ZonkEnv, [OutPat Id]) zonkPats env [] = return (env, []) zonkPats env (pat:pats) = do { (env1, pat') <- zonkPat env pat ; (env', pats') <- zonkPats env1 pats ; return (env', pat':pats') } {- ************************************************************************ * * \subsection[BackSubst-Foreign]{Foreign exports} * * ************************************************************************ -} zonkForeignExports :: ZonkEnv -> [LForeignDecl TcId] -> TcM [LForeignDecl Id] zonkForeignExports env ls = mapM (wrapLocM (zonkForeignExport env)) ls zonkForeignExport :: ZonkEnv -> ForeignDecl TcId -> TcM (ForeignDecl Id) zonkForeignExport env (ForeignExport { fd_name = i, fd_co = co, fd_fe = spec }) = return (ForeignExport { fd_name = fmap (zonkIdOcc env) i , fd_sig_ty = undefined, fd_co = co , fd_fe = spec }) zonkForeignExport _ for_imp = return for_imp -- Foreign imports don't need zonking zonkRules :: ZonkEnv -> [LRuleDecl TcId] -> TcM [LRuleDecl Id] zonkRules env rs = mapM (wrapLocM (zonkRule env)) rs zonkRule :: ZonkEnv -> RuleDecl TcId -> TcM (RuleDecl Id) zonkRule env (HsRule name act (vars{-::[RuleBndr TcId]-}) lhs fv_lhs rhs fv_rhs) = do { (env_inside, new_bndrs) <- mapAccumLM zonk_bndr env vars ; let env_lhs = setZonkType env_inside zonkTvSkolemising -- See Note [Zonking the LHS of a RULE] ; new_lhs <- zonkLExpr env_lhs lhs ; new_rhs <- zonkLExpr env_inside rhs ; return (HsRule name act new_bndrs new_lhs fv_lhs new_rhs fv_rhs) } where zonk_bndr env (L l (RuleBndr (L loc v))) = do { (env', v') <- zonk_it env v ; return (env', L l (RuleBndr (L loc v'))) } zonk_bndr _ (L _ (RuleBndrSig {})) = panic "zonk_bndr RuleBndrSig" zonk_it env v | isId v = do { v' <- zonkIdBndr env v ; return (extendIdZonkEnvRec env [v'], v') } | otherwise = ASSERT( isImmutableTyVar v) zonkTyBndrX env v -- DV: used to be return (env,v) but that is plain -- wrong because we may need to go inside the kind -- of v and zonk there! zonkVects :: ZonkEnv -> [LVectDecl TcId] -> TcM [LVectDecl Id] zonkVects env = mapM (wrapLocM (zonkVect env)) zonkVect :: ZonkEnv -> VectDecl TcId -> TcM (VectDecl Id) zonkVect env (HsVect s v e) = do { v' <- wrapLocM (zonkIdBndr env) v ; e' <- zonkLExpr env e ; return $ HsVect s v' e' } zonkVect env (HsNoVect s v) = do { v' <- wrapLocM (zonkIdBndr env) v ; return $ HsNoVect s v' } zonkVect _env (HsVectTypeOut s t rt) = return $ HsVectTypeOut s t rt zonkVect _ (HsVectTypeIn _ _ _ _) = panic "TcHsSyn.zonkVect: HsVectTypeIn" zonkVect _env (HsVectClassOut c) = return $ HsVectClassOut c zonkVect _ (HsVectClassIn _ _) = panic "TcHsSyn.zonkVect: HsVectClassIn" zonkVect _env (HsVectInstOut i) = return $ HsVectInstOut i zonkVect _ (HsVectInstIn _) = panic "TcHsSyn.zonkVect: HsVectInstIn" {- ************************************************************************ * * Constraints and evidence * * ************************************************************************ -} zonkEvTerm :: ZonkEnv -> EvTerm -> TcM EvTerm zonkEvTerm env (EvId v) = ASSERT2( isId v, ppr v ) zonkEvVarOcc env v zonkEvTerm env (EvCoercion co) = do { co' <- zonkCoToCo env co ; return (EvCoercion co') } zonkEvTerm env (EvCast tm co) = do { tm' <- zonkEvTerm env tm ; co' <- zonkCoToCo env co ; return (mkEvCast tm' co') } zonkEvTerm _ (EvLit l) = return (EvLit l) zonkEvTerm env (EvTypeable ty ev) = do { ev' <- zonkEvTypeable env ev ; ty' <- zonkTcTypeToType env ty ; return (EvTypeable ty' ev') } zonkEvTerm env (EvCallStack cs) = case cs of EvCsEmpty -> return (EvCallStack cs) EvCsPushCall n l tm -> do { tm' <- zonkEvTerm env tm ; return (EvCallStack (EvCsPushCall n l tm')) } zonkEvTerm env (EvSuperClass d n) = do { d' <- zonkEvTerm env d ; return (EvSuperClass d' n) } zonkEvTerm env (EvDFunApp df tys tms) = do { tys' <- zonkTcTypeToTypes env tys ; tms' <- mapM (zonkEvTerm env) tms ; return (EvDFunApp (zonkIdOcc env df) tys' tms') } zonkEvTerm env (EvDelayedError ty msg) = do { ty' <- zonkTcTypeToType env ty ; return (EvDelayedError ty' msg) } zonkEvTypeable :: ZonkEnv -> EvTypeable -> TcM EvTypeable zonkEvTypeable env (EvTypeableTyCon ts) = do { ts' <- mapM (zonkEvTerm env) ts ; return $ EvTypeableTyCon ts' } zonkEvTypeable env (EvTypeableTyApp t1 t2) = do { t1' <- zonkEvTerm env t1 ; t2' <- zonkEvTerm env t2 ; return (EvTypeableTyApp t1' t2') } zonkEvTypeable env (EvTypeableTyLit t1) = do { t1' <- zonkEvTerm env t1 ; return (EvTypeableTyLit t1') } zonkTcEvBinds_s :: ZonkEnv -> [TcEvBinds] -> TcM (ZonkEnv, [TcEvBinds]) zonkTcEvBinds_s env bs = do { (env, bs') <- mapAccumLM zonk_tc_ev_binds env bs ; return (env, [EvBinds (unionManyBags bs')]) } zonkTcEvBinds :: ZonkEnv -> TcEvBinds -> TcM (ZonkEnv, TcEvBinds) zonkTcEvBinds env bs = do { (env', bs') <- zonk_tc_ev_binds env bs ; return (env', EvBinds bs') } zonk_tc_ev_binds :: ZonkEnv -> TcEvBinds -> TcM (ZonkEnv, Bag EvBind) zonk_tc_ev_binds env (TcEvBinds var) = zonkEvBindsVar env var zonk_tc_ev_binds env (EvBinds bs) = zonkEvBinds env bs zonkEvBindsVar :: ZonkEnv -> EvBindsVar -> TcM (ZonkEnv, Bag EvBind) zonkEvBindsVar env (EvBindsVar { ebv_binds = ref }) = do { bs <- readMutVar ref ; zonkEvBinds env (evBindMapBinds bs) } zonkEvBinds :: ZonkEnv -> Bag EvBind -> TcM (ZonkEnv, Bag EvBind) zonkEvBinds env binds = {-# SCC "zonkEvBinds" #-} fixM (\ ~( _, new_binds) -> do { let env1 = extendIdZonkEnvRec env (collect_ev_bndrs new_binds) ; binds' <- mapBagM (zonkEvBind env1) binds ; return (env1, binds') }) where collect_ev_bndrs :: Bag EvBind -> [EvVar] collect_ev_bndrs = foldrBag add [] add (EvBind { eb_lhs = var }) vars = var : vars zonkEvBind :: ZonkEnv -> EvBind -> TcM EvBind zonkEvBind env bind@(EvBind { eb_lhs = var, eb_rhs = term }) = do { var' <- {-# SCC "zonkEvBndr" #-} zonkEvBndr env var -- Optimise the common case of Refl coercions -- See Note [Optimise coercion zonking] -- This has a very big effect on some programs (eg Trac #5030) ; term' <- case getEqPredTys_maybe (idType var') of Just (r, ty1, ty2) | ty1 `eqType` ty2 -> return (EvCoercion (mkTcReflCo r ty1)) _other -> zonkEvTerm env term ; return (bind { eb_lhs = var', eb_rhs = term' }) } {- ************************************************************************ * * Zonking types * * ************************************************************************ Note [Zonking mutable unbound type or kind variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In zonkTypeZapping, we zonk mutable but unbound type or kind variables to an arbitrary type. We know if they are unbound even though we don't carry an environment, because at the binding site for a variable we bind the mutable var to a fresh immutable one. So the mutable store plays the role of an environment. If we come across a mutable variable that isn't so bound, it must be completely free. We zonk the expected kind to make sure we don't get some unbound meta variable as the kind. Note that since we have kind polymorphism, zonk_unbound_tyvar will handle both type and kind variables. Consider the following datatype: data Phantom a = Phantom Int The type of Phantom is (forall (k : *). forall (a : k). Int). Both `a` and `k` are unbound variables. We want to zonk this to (forall (k : Any *). forall (a : Any (Any *)). Int). Note [Optimise coercion zonking] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When optimising evidence binds we may come across situations where a coercion looks like cv = ReflCo ty or cv1 = cv2 where the type 'ty' is big. In such cases it is a waste of time to zonk both * The variable on the LHS * The coercion on the RHS Rather, we can zonk the variable, and if its type is (ty ~ ty), we can just use Refl on the right, ignoring the actual coercion on the RHS. This can have a very big effect, because the constraint solver sometimes does go to a lot of effort to prove Refl! (Eg when solving 10+3 = 10+3; cf Trac #5030) -} zonkTyVarOcc :: ZonkEnv -> TyVar -> TcM TcType zonkTyVarOcc env@(ZonkEnv zonk_unbound_tyvar tv_env _) tv | isTcTyVar tv = case tcTyVarDetails tv of SkolemTv {} -> lookup_in_env RuntimeUnk {} -> lookup_in_env FlatSkol ty -> zonkTcTypeToType env ty MetaTv { mtv_ref = ref } -> do { cts <- readMutVar ref ; case cts of Flexi -> do { kind <- {-# SCC "zonkKind1" #-} zonkTcTypeToType env (tyVarKind tv) ; zonk_unbound_tyvar (setTyVarKind tv kind) } Indirect ty -> do { zty <- zonkTcTypeToType env ty -- Small optimisation: shortern-out indirect steps -- so that the old type may be more easily collected. ; writeMutVar ref (Indirect zty) ; return zty } } | otherwise = lookup_in_env where lookup_in_env -- Look up in the env just as we do for Ids = case lookupVarEnv tv_env tv of Nothing -> mkTyVarTy <$> updateTyVarKindM (zonkTcTypeToType env) tv Just tv' -> return (mkTyVarTy tv') zonkCoVarOcc :: ZonkEnv -> CoVar -> TcM Coercion zonkCoVarOcc env@(ZonkEnv _ tyco_env _) cv | Just cv' <- lookupVarEnv tyco_env cv -- don't look in the knot-tied env = return $ mkCoVarCo cv' | otherwise = mkCoVarCo <$> updateVarTypeM (zonkTcTypeToType env) cv zonkCoHole :: ZonkEnv -> CoercionHole -> Role -> Type -> Type -- these are all redundant with -- the details in the hole, -- unzonked -> TcM Coercion zonkCoHole env h r t1 t2 = do { contents <- unpackCoercionHole_maybe h ; case contents of Just co -> do { co <- zonkCoToCo env co ; checkCoercionHole co h r t1 t2 } -- This next case should happen only in the presence of -- (undeferred) type errors. Originally, I put in a panic -- here, but that caused too many uses of `failIfErrsM`. Nothing -> do { traceTc "Zonking unfilled coercion hole" (ppr h) ; when debugIsOn $ whenNoErrs $ MASSERT2( False , text "Type-correct unfilled coercion hole" <+> ppr h ) ; t1 <- zonkTcTypeToType env t1 ; t2 <- zonkTcTypeToType env t2 ; return $ mkHoleCo h r t1 t2 } } zonk_tycomapper :: TyCoMapper ZonkEnv TcM zonk_tycomapper = TyCoMapper { tcm_smart = True -- Establish type invariants -- See Note [Type-checking inside the knot] in TcHsType , tcm_tyvar = zonkTyVarOcc , tcm_covar = zonkCoVarOcc , tcm_hole = zonkCoHole , tcm_tybinder = \env tv _vis -> zonkTyBndrX env tv } -- Confused by zonking? See Note [What is zonking?] in TcMType. zonkTcTypeToType :: ZonkEnv -> TcType -> TcM Type zonkTcTypeToType = mapType zonk_tycomapper zonkTcTypeToTypes :: ZonkEnv -> [TcType] -> TcM [Type] zonkTcTypeToTypes env tys = mapM (zonkTcTypeToType env) tys zonkCoToCo :: ZonkEnv -> Coercion -> TcM Coercion zonkCoToCo = mapCoercion zonk_tycomapper zonkSigType :: TcType -> TcM Type -- Zonk the type obtained from a user type signature -- We want to turn any quantified (forall'd) variables into TyVars -- but we may find some free TcTyVars, and we want to leave them -- completely alone. They may even have unification variables inside -- e.g. f (x::a) = ...(e :: a -> a).... -- The type sig for 'e' mentions a free 'a' which will be a -- unification SigTv variable. zonkSigType = zonkTcTypeToType (mkEmptyZonkEnv zonk_unbound_tv) where zonk_unbound_tv :: UnboundTyVarZonker zonk_unbound_tv tv = return (mkTyVarTy tv) zonkTvSkolemising :: UnboundTyVarZonker -- This variant is used for the LHS of rules -- See Note [Zonking the LHS of a RULE]. zonkTvSkolemising tv = do { let tv' = mkTyVar (tyVarName tv) (tyVarKind tv) -- NB: the kind of tv is already zonked ty = mkTyVarTy tv' -- Make a proper TyVar (remember we -- are now done with type checking) ; writeMetaTyVar tv ty ; return ty } zonkTypeZapping :: UnboundTyVarZonker -- This variant is used for everything except the LHS of rules -- It zaps unbound type variables to Any, except for RuntimeRep -- vars which it zonks to PtrRepLIfted -- Works on both types and kinds zonkTypeZapping tv = do { let ty | isRuntimeRepVar tv = ptrRepLiftedTy | otherwise = anyTypeOfKind (tyVarKind tv) ; writeMetaTyVar tv ty ; return ty } --------------------------------------- {- Note [Zonking the LHS of a RULE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See also DsBinds Note [Free tyvars on rule LHS] We need to gather the type variables mentioned on the LHS so we can quantify over them. Example: data T a = C foo :: T a -> Int foo C = 1 {-# RULES "myrule" foo C = 1 #-} After type checking the LHS becomes (foo alpha (C alpha)) and we do not want to zap the unbound meta-tyvar 'alpha' to Any, because that limits the applicability of the rule. Instead, we want to quantify over it! We do this in two stages. * During zonking, we skolemise the TcTyVar 'alpha' to TyVar 'a'. We do this by using zonkTvSkolemising as the UnboundTyVarZonker in the ZonkEnv. (This is in fact the whole reason that the ZonkEnv has a UnboundTyVarZonker.) * In DsBinds, we quantify over it. See DsBinds Note [Free tyvars on rule LHS] Quantifying here is awkward because (a) the data type is big and (b) finding the free type vars of an expression is necessarily monadic operation. (consider /\a -> f @ b, where b is side-effected to a) Note [Unboxed tuples in representation polymorphism check] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Recall that all types that have values (that is, lifted and unlifted types) have kinds that look like (TYPE rep), where (rep :: RuntimeRep) tells how the values are represented at runtime. Lifted types have kind (TYPE PtrRepLifted) (for which * is just a synonym) and, say, Int# has kind (TYPE IntRep). It would be terrible if the code generator came upon a binder of a type whose kind is something like TYPE r, where r is a skolem type variable. The code generator wouldn't know what to do. So we eliminate that case here. Although representation polymorphism and the RuntimeRep type catch most ways of abusing unlifted types, it still isn't quite satisfactory around unboxed tuples. That's because all unboxed tuple types have kind TYPE UnboxedTupleRep, which is clearly a lie: it doesn't actually tell you what the representation is. Naively, when checking for representation polymorphism, you might think we can just look for free variables in a type's RuntimeRep. But this misses the UnboxedTupleRep case. So, instead, we handle unboxed tuples specially. Only after unboxed tuples are handled do we look for free tyvars in a RuntimeRep. We must still be careful in the UnboxedTupleRep case. A binder whose type has kind UnboxedTupleRep is OK -- only as long as the type is really an unboxed tuple, which the code generator treats specially. So we do this: 1. Check if the type is an unboxed tuple. If so, recur. 2. Check if the kind is TYPE UnboxedTupleRep. If so, error. 3. Check if the kind has any free variables. If so, error. In case 1, we have a type that looks like (# , #) PtrRepLifted IntRep Bool Int# recalling that (# , #) :: forall (r1 :: RuntimeRep) (r2 :: RuntimeRep). TYPE r1 -> TYPE r2 -> TYPE UnboxedTupleRep It's tempting just to look at the RuntimeRep arguments to make sure that they are devoid of free variables and not UnboxedTupleRep. This naive check, though, fails on nested unboxed tuples, like (# Int#, (# Bool, Void# #) #). Thus, instead of looking at the RuntimeRep args to the unboxed tuple constructor, we look at the types themselves. Here are a few examples: type family F r :: TYPE r x :: (F r :: TYPE r) -- REJECTED: simple representation polymorphism where r is an in-scope type variable of kind RuntimeRep x :: (F PtrRepLifted :: TYPE PtrRepLifted) -- OK x :: (F IntRep :: TYPE IntRep) -- OK x :: (F UnboxedTupleRep :: TYPE UnboxedTupleRep) -- REJECTED x :: ((# Int, Bool #) :: TYPE UnboxedTupleRep) -- OK -} -- | According to the rules around representation polymorphism -- (see https://ghc.haskell.org/trac/ghc/wiki/NoSubKinds), no binder -- can have a representation-polymorphic type. This check ensures -- that we respect this rule. It is a bit regrettable that this error -- occurs in zonking, after which we should have reported all errors. -- But it's hard to see where else to do it, because this can be discovered -- only after all solving is done. And, perhaps most importantly, this -- isn't really a compositional property of a type system, so it's -- not a terrible surprise that the check has to go in an awkward spot. ensureNotRepresentationPolymorphic :: Type -- its zonked type -> SDoc -- where this happened -> TcM () ensureNotRepresentationPolymorphic ty doc = whenNoErrs $ -- sometimes we end up zonking bogus definitions of type -- forall a. a. See, for example, test ghci/scripts/T9140 checkForRepresentationPolymorphism doc ty -- See Note [Unboxed tuples in representation polymorphism check] checkForRepresentationPolymorphism :: SDoc -> Type -> TcM () checkForRepresentationPolymorphism extra ty | Just (tc, tys) <- splitTyConApp_maybe ty , isUnboxedTupleTyCon tc || isUnboxedSumTyCon tc = mapM_ (checkForRepresentationPolymorphism extra) (dropRuntimeRepArgs tys) | tuple_rep || sum_rep = addErr (vcat [ text "The type" <+> quotes (ppr tidy_ty) <+> (text "is not an unboxed" <+> tuple_or_sum <> comma) , text "and yet its kind suggests that it has the representation" , text "of an unboxed" <+> tuple_or_sum <> text ". This is not allowed." ] $$ extra) | not (isEmptyVarSet (tyCoVarsOfType runtime_rep)) = addErr $ hang (text "A representation-polymorphic type is not allowed here:") 2 (vcat [ text "Type:" <+> ppr tidy_ty , text "Kind:" <+> ppr tidy_ki ]) $$ extra | otherwise = return () where tuple_rep = runtime_rep `eqType` unboxedTupleRepDataConTy sum_rep = runtime_rep `eqType` unboxedSumRepDataConTy tuple_or_sum = text (if tuple_rep then "tuple" else "sum") ki = typeKind ty runtime_rep = getRuntimeRepFromKind "check_type" ki (tidy_env, tidy_ty) = tidyOpenType emptyTidyEnv ty tidy_ki = tidyType tidy_env (typeKind ty)
mettekou/ghc
compiler/typecheck/TcHsSyn.hs
bsd-3-clause
74,238
40
19
21,085
19,097
9,699
9,398
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} #if !MIN_VERSION_base(4,8,0) {-# LANGUAGE OverlappingInstances #-} #endif -- | This module provides 'client' which can automatically generate -- querying functions for each endpoint just from the type representing your -- API. module Servant.Client ( client , HasClient(..) , ServantError(..) , module Servant.Common.BaseUrl ) where #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>)) #endif import Control.Monad import Control.Monad.Trans.Either import Data.ByteString.Lazy (ByteString) import Data.List import Data.Proxy import Data.String.Conversions import Data.Text (unpack) import GHC.TypeLits import Network.HTTP.Media import qualified Network.HTTP.Types as H import qualified Network.HTTP.Types.Header as HTTP import Servant.API import Servant.Common.BaseUrl import Servant.Common.Req -- * Accessing APIs as a Client -- | 'client' allows you to produce operations to query an API from a client. -- -- > type MyApi = "books" :> Get '[JSON] [Book] -- GET /books -- > :<|> "books" :> ReqBody '[JSON] Book :> Post Book -- POST /books -- > -- > myApi :: Proxy MyApi -- > myApi = Proxy -- > -- > getAllBooks :: EitherT String IO [Book] -- > postNewBook :: Book -> EitherT String IO Book -- > (getAllBooks :<|> postNewBook) = client myApi host -- > where host = BaseUrl Http "localhost" 8080 client :: HasClient layout => Proxy layout -> Maybe BaseUrl -> Client layout client p baseurl = clientWithRoute p defReq baseurl -- | This class lets us define how each API combinator -- influences the creation of an HTTP request. It's mostly -- an internal class, you can just use 'client'. class HasClient layout where type Client layout :: * clientWithRoute :: Proxy layout -> Req -> Maybe BaseUrl -> Client layout {-type Client layout = Client layout-} -- | A client querying function for @a ':<|>' b@ will actually hand you -- one function for querying @a@ and another one for querying @b@, -- stitching them together with ':<|>', which really is just like a pair. -- -- > type MyApi = "books" :> Get '[JSON] [Book] -- GET /books -- > :<|> "books" :> ReqBody '[JSON] Book :> Post Book -- POST /books -- > -- > myApi :: Proxy MyApi -- > myApi = Proxy -- > -- > getAllBooks :: EitherT String IO [Book] -- > postNewBook :: Book -> EitherT String IO Book -- > (getAllBooks :<|> postNewBook) = client myApi host -- > where host = BaseUrl Http "localhost" 8080 instance (HasClient a, HasClient b) => HasClient (a :<|> b) where type Client (a :<|> b) = Client a :<|> Client b clientWithRoute Proxy req baseurl = clientWithRoute (Proxy :: Proxy a) req baseurl :<|> clientWithRoute (Proxy :: Proxy b) req baseurl -- | If you use a 'Capture' in one of your endpoints in your API, -- the corresponding querying function will automatically take -- an additional argument of the type specified by your 'Capture'. -- That function will take care of inserting a textual representation -- of this value at the right place in the request path. -- -- You can control how values for this type are turned into -- text by specifying a 'ToText' instance for your type. -- -- Example: -- -- > type MyApi = "books" :> Capture "isbn" Text :> Get '[JSON] Book -- > -- > myApi :: Proxy MyApi -- > myApi = Proxy -- > -- > getBook :: Text -> EitherT String IO Book -- > getBook = client myApi host -- > where host = BaseUrl Http "localhost" 8080 -- > -- then you can just use "getBook" to query that endpoint instance (KnownSymbol capture, ToText a, HasClient sublayout) => HasClient (Capture capture a :> sublayout) where type Client (Capture capture a :> sublayout) = a -> Client sublayout clientWithRoute Proxy req baseurl val = clientWithRoute (Proxy :: Proxy sublayout) (appendToPath p req) baseurl where p = unpack (toText val) -- | If you have a 'Delete' endpoint in your API, the client -- side querying function that is created when calling 'client' -- will just require an argument that specifies the scheme, host -- and port to send the request to. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPABLE #-} #endif -- See https://downloads.haskell.org/~ghc/7.8.2/docs/html/users_guide/type-class-extensions.html#undecidable-instances (MimeUnrender ct a, cts' ~ (ct ': cts)) => HasClient (Delete cts' a) where type Client (Delete cts' a) = EitherT ServantError IO a clientWithRoute Proxy req baseurl = snd <$> performRequestCT (Proxy :: Proxy ct) H.methodDelete req [200, 202] baseurl -- | If you have a 'Delete xs ()' endpoint, the client expects a 204 No Content -- HTTP header. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPING #-} #endif HasClient (Delete cts ()) where type Client (Delete cts ()) = EitherT ServantError IO () clientWithRoute Proxy req baseurl = void $ performRequestNoBody H.methodDelete req [204] baseurl -- | If you have a 'Delete xs (Headers ls x)' endpoint, the client expects the -- corresponding headers. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPING #-} #endif -- See https://downloads.haskell.org/~ghc/7.8.2/docs/html/users_guide/type-class-extensions.html#undecidable-instances ( MimeUnrender ct a, BuildHeadersTo ls, cts' ~ (ct ': cts) ) => HasClient (Delete cts' (Headers ls a)) where type Client (Delete cts' (Headers ls a)) = EitherT ServantError IO (Headers ls a) clientWithRoute Proxy req baseurl = do (hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) H.methodDelete req [200, 202] baseurl return $ Headers { getResponse = resp , getHeadersHList = buildHeadersTo hdrs } -- | If you have a 'Get' endpoint in your API, the client -- side querying function that is created when calling 'client' -- will just require an argument that specifies the scheme, host -- and port to send the request to. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPABLE #-} #endif (MimeUnrender ct result) => HasClient (Get (ct ': cts) result) where type Client (Get (ct ': cts) result) = EitherT ServantError IO result clientWithRoute Proxy req baseurl = snd <$> performRequestCT (Proxy :: Proxy ct) H.methodGet req [200, 203] baseurl -- | If you have a 'Get xs ()' endpoint, the client expects a 204 No Content -- HTTP status. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPING #-} #endif HasClient (Get (ct ': cts) ()) where type Client (Get (ct ': cts) ()) = EitherT ServantError IO () clientWithRoute Proxy req baseurl = performRequestNoBody H.methodGet req [204] baseurl -- | If you have a 'Get xs (Headers ls x)' endpoint, the client expects the -- corresponding headers. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPING #-} #endif ( MimeUnrender ct a, BuildHeadersTo ls ) => HasClient (Get (ct ': cts) (Headers ls a)) where type Client (Get (ct ': cts) (Headers ls a)) = EitherT ServantError IO (Headers ls a) clientWithRoute Proxy req baseurl = do (hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) H.methodGet req [200, 203, 204] baseurl return $ Headers { getResponse = resp , getHeadersHList = buildHeadersTo hdrs } -- | If you use a 'Header' in one of your endpoints in your API, -- the corresponding querying function will automatically take -- an additional argument of the type specified by your 'Header', -- wrapped in Maybe. -- -- That function will take care of encoding this argument as Text -- in the request headers. -- -- All you need is for your type to have a 'ToText' instance. -- -- Example: -- -- > newtype Referer = Referer { referrer :: Text } -- > deriving (Eq, Show, Generic, FromText, ToText) -- > -- > -- GET /view-my-referer -- > type MyApi = "view-my-referer" :> Header "Referer" Referer :> Get '[JSON] Referer -- > -- > myApi :: Proxy MyApi -- > myApi = Proxy -- > -- > viewReferer :: Maybe Referer -> EitherT String IO Book -- > viewReferer = client myApi host -- > where host = BaseUrl Http "localhost" 8080 -- > -- then you can just use "viewRefer" to query that endpoint -- > -- specifying Nothing or e.g Just "http://haskell.org/" as arguments instance (KnownSymbol sym, ToText a, HasClient sublayout) => HasClient (Header sym a :> sublayout) where type Client (Header sym a :> sublayout) = Maybe a -> Client sublayout clientWithRoute Proxy req baseurl mval = clientWithRoute (Proxy :: Proxy sublayout) (maybe req (\value -> Servant.Common.Req.addHeader hname value req) mval ) baseurl where hname = symbolVal (Proxy :: Proxy sym) -- | If you have a 'Post' endpoint in your API, the client -- side querying function that is created when calling 'client' -- will just require an argument that specifies the scheme, host -- and port to send the request to. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPABLE #-} #endif (MimeUnrender ct a) => HasClient (Post (ct ': cts) a) where type Client (Post (ct ': cts) a) = EitherT ServantError IO a clientWithRoute Proxy req baseurl = snd <$> performRequestCT (Proxy :: Proxy ct) H.methodPost req [200,201] baseurl -- | If you have a 'Post xs ()' endpoint, the client expects a 204 No Content -- HTTP header. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPING #-} #endif HasClient (Post (ct ': cts) ()) where type Client (Post (ct ': cts) ()) = EitherT ServantError IO () clientWithRoute Proxy req baseurl = void $ performRequestNoBody H.methodPost req [204] baseurl -- | If you have a 'Post xs (Headers ls x)' endpoint, the client expects the -- corresponding headers. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPING #-} #endif ( MimeUnrender ct a, BuildHeadersTo ls ) => HasClient (Post (ct ': cts) (Headers ls a)) where type Client (Post (ct ': cts) (Headers ls a)) = EitherT ServantError IO (Headers ls a) clientWithRoute Proxy req baseurl = do (hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) H.methodPost req [200, 201] baseurl return $ Headers { getResponse = resp , getHeadersHList = buildHeadersTo hdrs } -- | If you have a 'Put' endpoint in your API, the client -- side querying function that is created when calling 'client' -- will just require an argument that specifies the scheme, host -- and port to send the request to. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPABLE #-} #endif (MimeUnrender ct a) => HasClient (Put (ct ': cts) a) where type Client (Put (ct ': cts) a) = EitherT ServantError IO a clientWithRoute Proxy req baseurl = snd <$> performRequestCT (Proxy :: Proxy ct) H.methodPut req [200,201] baseurl -- | If you have a 'Put xs ()' endpoint, the client expects a 204 No Content -- HTTP header. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPING #-} #endif HasClient (Put (ct ': cts) ()) where type Client (Put (ct ': cts) ()) = EitherT ServantError IO () clientWithRoute Proxy req baseurl = void $ performRequestNoBody H.methodPut req [204] baseurl -- | If you have a 'Put xs (Headers ls x)' endpoint, the client expects the -- corresponding headers. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPING #-} #endif ( MimeUnrender ct a, BuildHeadersTo ls ) => HasClient (Put (ct ': cts) (Headers ls a)) where type Client (Put (ct ': cts) (Headers ls a)) = EitherT ServantError IO (Headers ls a) clientWithRoute Proxy req baseurl = do (hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) H.methodPut req [200, 201] baseurl return $ Headers { getResponse = resp , getHeadersHList = buildHeadersTo hdrs } -- | If you have a 'Patch' endpoint in your API, the client -- side querying function that is created when calling 'client' -- will just require an argument that specifies the scheme, host -- and port to send the request to. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPABLE #-} #endif (MimeUnrender ct a) => HasClient (Patch (ct ': cts) a) where type Client (Patch (ct ': cts) a) = EitherT ServantError IO a clientWithRoute Proxy req baseurl = snd <$> performRequestCT (Proxy :: Proxy ct) H.methodPatch req [200,201] baseurl -- | If you have a 'Patch xs ()' endpoint, the client expects a 204 No Content -- HTTP header. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPING #-} #endif HasClient (Patch (ct ': cts) ()) where type Client (Patch (ct ': cts) ()) = EitherT ServantError IO () clientWithRoute Proxy req baseurl = void $ performRequestNoBody H.methodPatch req [204] baseurl -- | If you have a 'Patch xs (Headers ls x)' endpoint, the client expects the -- corresponding headers. instance #if MIN_VERSION_base(4,8,0) {-# OVERLAPPING #-} #endif ( MimeUnrender ct a, BuildHeadersTo ls ) => HasClient (Patch (ct ': cts) (Headers ls a)) where type Client (Patch (ct ': cts) (Headers ls a)) = EitherT ServantError IO (Headers ls a) clientWithRoute Proxy req baseurl = do (hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) H.methodPatch req [200, 201, 204] baseurl return $ Headers { getResponse = resp , getHeadersHList = buildHeadersTo hdrs } -- | If you use a 'QueryParam' in one of your endpoints in your API, -- the corresponding querying function will automatically take -- an additional argument of the type specified by your 'QueryParam', -- enclosed in Maybe. -- -- If you give Nothing, nothing will be added to the query string. -- -- If you give a non-'Nothing' value, this function will take care -- of inserting a textual representation of this value in the query string. -- -- You can control how values for your type are turned into -- text by specifying a 'ToText' instance for your type. -- -- Example: -- -- > type MyApi = "books" :> QueryParam "author" Text :> Get '[JSON] [Book] -- > -- > myApi :: Proxy MyApi -- > myApi = Proxy -- > -- > getBooksBy :: Maybe Text -> EitherT String IO [Book] -- > getBooksBy = client myApi host -- > where host = BaseUrl Http "localhost" 8080 -- > -- then you can just use "getBooksBy" to query that endpoint. -- > -- 'getBooksBy Nothing' for all books -- > -- 'getBooksBy (Just "Isaac Asimov")' to get all books by Isaac Asimov instance (KnownSymbol sym, ToText a, HasClient sublayout) => HasClient (QueryParam sym a :> sublayout) where type Client (QueryParam sym a :> sublayout) = Maybe a -> Client sublayout -- if mparam = Nothing, we don't add it to the query string clientWithRoute Proxy req baseurl mparam = clientWithRoute (Proxy :: Proxy sublayout) (maybe req (flip (appendToQueryString pname) req . Just) mparamText ) baseurl where pname = cs pname' pname' = symbolVal (Proxy :: Proxy sym) mparamText = fmap toText mparam -- | If you use a 'QueryParams' in one of your endpoints in your API, -- the corresponding querying function will automatically take -- an additional argument, a list of values of the type specified -- by your 'QueryParams'. -- -- If you give an empty list, nothing will be added to the query string. -- -- Otherwise, this function will take care -- of inserting a textual representation of your values in the query string, -- under the same query string parameter name. -- -- You can control how values for your type are turned into -- text by specifying a 'ToText' instance for your type. -- -- Example: -- -- > type MyApi = "books" :> QueryParams "authors" Text :> Get '[JSON] [Book] -- > -- > myApi :: Proxy MyApi -- > myApi = Proxy -- > -- > getBooksBy :: [Text] -> EitherT String IO [Book] -- > getBooksBy = client myApi host -- > where host = BaseUrl Http "localhost" 8080 -- > -- then you can just use "getBooksBy" to query that endpoint. -- > -- 'getBooksBy []' for all books -- > -- 'getBooksBy ["Isaac Asimov", "Robert A. Heinlein"]' -- > -- to get all books by Asimov and Heinlein instance (KnownSymbol sym, ToText a, HasClient sublayout) => HasClient (QueryParams sym a :> sublayout) where type Client (QueryParams sym a :> sublayout) = [a] -> Client sublayout clientWithRoute Proxy req baseurl paramlist = clientWithRoute (Proxy :: Proxy sublayout) (foldl' (\ req' -> maybe req' (flip (appendToQueryString pname) req' . Just)) req paramlist' ) baseurl where pname = cs pname' pname' = symbolVal (Proxy :: Proxy sym) paramlist' = map (Just . toText) paramlist -- | If you use a 'QueryFlag' in one of your endpoints in your API, -- the corresponding querying function will automatically take -- an additional 'Bool' argument. -- -- If you give 'False', nothing will be added to the query string. -- -- Otherwise, this function will insert a value-less query string -- parameter under the name associated to your 'QueryFlag'. -- -- Example: -- -- > type MyApi = "books" :> QueryFlag "published" :> Get '[JSON] [Book] -- > -- > myApi :: Proxy MyApi -- > myApi = Proxy -- > -- > getBooks :: Bool -> EitherT String IO [Book] -- > getBooks = client myApi host -- > where host = BaseUrl Http "localhost" 8080 -- > -- then you can just use "getBooks" to query that endpoint. -- > -- 'getBooksBy False' for all books -- > -- 'getBooksBy True' to only get _already published_ books instance (KnownSymbol sym, HasClient sublayout) => HasClient (QueryFlag sym :> sublayout) where type Client (QueryFlag sym :> sublayout) = Bool -> Client sublayout clientWithRoute Proxy req baseurl flag = clientWithRoute (Proxy :: Proxy sublayout) (if flag then appendToQueryString paramname Nothing req else req ) baseurl where paramname = cs $ symbolVal (Proxy :: Proxy sym) -- | If you use a 'MatrixParam' in one of your endpoints in your API, -- the corresponding querying function will automatically take -- an additional argument of the type specified by your 'MatrixParam', -- enclosed in Maybe. -- -- If you give Nothing, nothing will be added to the query string. -- -- If you give a non-'Nothing' value, this function will take care -- of inserting a textual representation of this value in the query string. -- -- You can control how values for your type are turned into -- text by specifying a 'ToText' instance for your type. -- -- Example: -- -- > type MyApi = "books" :> MatrixParam "author" Text :> Get '[JSON] [Book] -- > -- > myApi :: Proxy MyApi -- > myApi = Proxy -- > -- > getBooksBy :: Maybe Text -> EitherT String IO [Book] -- > getBooksBy = client myApi host -- > where host = BaseUrl Http "localhost" 8080 -- > -- then you can just use "getBooksBy" to query that endpoint. -- > -- 'getBooksBy Nothing' for all books -- > -- 'getBooksBy (Just "Isaac Asimov")' to get all books by Isaac Asimov instance (KnownSymbol sym, ToText a, HasClient sublayout) => HasClient (MatrixParam sym a :> sublayout) where type Client (MatrixParam sym a :> sublayout) = Maybe a -> Client sublayout -- if mparam = Nothing, we don't add it to the query string clientWithRoute Proxy req baseurl mparam = clientWithRoute (Proxy :: Proxy sublayout) (maybe req (flip (appendToMatrixParams pname . Just) req) mparamText ) baseurl where pname = symbolVal (Proxy :: Proxy sym) mparamText = fmap (cs . toText) mparam -- | If you use a 'MatrixParams' in one of your endpoints in your API, -- the corresponding querying function will automatically take an -- additional argument, a list of values of the type specified by your -- 'MatrixParams'. -- -- If you give an empty list, nothing will be added to the query string. -- -- Otherwise, this function will take care of inserting a textual -- representation of your values in the path segment string, under the -- same matrix string parameter name. -- -- You can control how values for your type are turned into text by -- specifying a 'ToText' instance for your type. -- -- Example: -- -- > type MyApi = "books" :> MatrixParams "authors" Text :> Get '[JSON] [Book] -- > -- > myApi :: Proxy MyApi -- > myApi = Proxy -- > -- > getBooksBy :: [Text] -> EitherT String IO [Book] -- > getBooksBy = client myApi host -- > where host = BaseUrl Http "localhost" 8080 -- > -- then you can just use "getBooksBy" to query that endpoint. -- > -- 'getBooksBy []' for all books -- > -- 'getBooksBy ["Isaac Asimov", "Robert A. Heinlein"]' -- > -- to get all books by Asimov and Heinlein instance (KnownSymbol sym, ToText a, HasClient sublayout) => HasClient (MatrixParams sym a :> sublayout) where type Client (MatrixParams sym a :> sublayout) = [a] -> Client sublayout clientWithRoute Proxy req baseurl paramlist = clientWithRoute (Proxy :: Proxy sublayout) (foldl' (\ req' value -> maybe req' (flip (appendToMatrixParams pname) req' . Just . cs) value) req paramlist' ) baseurl where pname = cs pname' pname' = symbolVal (Proxy :: Proxy sym) paramlist' = map (Just . toText) paramlist -- | If you use a 'MatrixFlag' in one of your endpoints in your API, -- the corresponding querying function will automatically take an -- additional 'Bool' argument. -- -- If you give 'False', nothing will be added to the path segment. -- -- Otherwise, this function will insert a value-less matrix parameter -- under the name associated to your 'MatrixFlag'. -- -- Example: -- -- > type MyApi = "books" :> MatrixFlag "published" :> Get '[JSON] [Book] -- > -- > myApi :: Proxy MyApi -- > myApi = Proxy -- > -- > getBooks :: Bool -> EitherT String IO [Book] -- > getBooks = client myApi host -- > where host = BaseUrl Http "localhost" 8080 -- > -- then you can just use "getBooks" to query that endpoint. -- > -- 'getBooksBy False' for all books -- > -- 'getBooksBy True' to only get _already published_ books instance (KnownSymbol sym, HasClient sublayout) => HasClient (MatrixFlag sym :> sublayout) where type Client (MatrixFlag sym :> sublayout) = Bool -> Client sublayout clientWithRoute Proxy req baseurl flag = clientWithRoute (Proxy :: Proxy sublayout) (if flag then appendToMatrixParams paramname Nothing req else req ) baseurl where paramname = cs $ symbolVal (Proxy :: Proxy sym) -- | Pick a 'Method' and specify where the server you want to query is. You get -- back the full `Response`. instance HasClient Raw where type Client Raw = H.Method -> EitherT ServantError IO (Int, ByteString, MediaType, [HTTP.Header]) clientWithRoute :: Proxy Raw -> Req -> Maybe BaseUrl -> Client Raw clientWithRoute Proxy req baseurl httpMethod = do performRequest httpMethod req (const True) baseurl -- | If you use a 'ReqBody' in one of your endpoints in your API, -- the corresponding querying function will automatically take -- an additional argument of the type specified by your 'ReqBody'. -- That function will take care of encoding this argument as JSON and -- of using it as the request body. -- -- All you need is for your type to have a 'ToJSON' instance. -- -- Example: -- -- > type MyApi = "books" :> ReqBody '[JSON] Book :> Post '[JSON] Book -- > -- > myApi :: Proxy MyApi -- > myApi = Proxy -- > -- > addBook :: Book -> EitherT String IO Book -- > addBook = client myApi host -- > where host = BaseUrl Http "localhost" 8080 -- > -- then you can just use "addBook" to query that endpoint instance (MimeRender ct a, HasClient sublayout) => HasClient (ReqBody (ct ': cts) a :> sublayout) where type Client (ReqBody (ct ': cts) a :> sublayout) = a -> Client sublayout clientWithRoute Proxy req baseurl body = clientWithRoute (Proxy :: Proxy sublayout) (let ctProxy = Proxy :: Proxy ct in setRQBody (mimeRender ctProxy body) (contentType ctProxy) req ) baseurl -- | Make the querying function append @path@ to the request path. instance (KnownSymbol path, HasClient sublayout) => HasClient (path :> sublayout) where type Client (path :> sublayout) = Client sublayout clientWithRoute Proxy req baseurl = clientWithRoute (Proxy :: Proxy sublayout) (appendToPath p req) baseurl where p = symbolVal (Proxy :: Proxy path)
meiersi/ghcjs-servant-client
src/Servant/Client.hs
bsd-3-clause
25,506
0
17
6,155
4,198
2,354
1,844
247
1
module LiveJournal.Request where data LJRequestParam = RequestParam { name, value :: String } data LJRequest = Request { params :: [LJRequestParam] } makeRequest :: [(String, String)] -> LJRequest makeRequest = Request . fmap ( uncurry RequestParam ) makeRequestParams :: [(String, String)] -> [LJRequestParam] makeRequestParams = fmap ( uncurry RequestParam )
jdevelop/hslj
LiveJournal/Request.hs
bsd-3-clause
365
0
9
54
112
66
46
7
1
%dll form_decode %ver 3.3 %date 2009/08/01 %author onitama %url http://hsp.tv/ %note form_decode.as‚ðƒCƒ“ƒNƒ‹[ƒh‚·‚邱‚ƁB %type ƒ†[ƒU[’è‹`–½—ß %group •¶Žš—ñ‘€ì–½—ß %port Win Cli Let %index form_decode ƒeƒLƒXƒg‚ðƒfƒR[ƒh %prm p1, p2, p3 p1=•ϐ” : •ÏŠ·Œ‹‰Ê‚ðŠi”[‚·‚é•¶Žš—ñŒ^•ϐ” p2=•ϐ” : •ÏŠ·‚·‚é•¶Žš—ñ‚ð‘ã“ü‚µ‚½•¶Žš—ñŒ^•ϐ” p3=0`(0) : •ÏŠ·ƒXƒCƒbƒ`(0) %inst ‘—M—p‚ɃGƒ“ƒR[ƒh‚³‚ꂽƒeƒLƒXƒg‚ðŒ³‚Ì“ú–{Œê‚ɃfƒR[ƒh‚µ‚Ü‚·B p3‚ð1‚É‚·‚邯'&'‚ð‰üs‚ɕϊ·‚µA2‚É‚·‚邯'+'‚ð‹ó”’‚ɕϊ·‚µ‚Ü‚·B 3‚É‚·‚邯—¼•û•ÏŠ·‚µ‚Ü‚·B •¶ŽšƒR[ƒh‚̕ϊ·‚͍s‚¢‚Ü‚¹‚ñ‚̂ŁA•¶ŽšƒR[ƒh•ÏŠ·‚ª•K—v‚ȏꍇ‚̓fƒR[ƒhŒã‚ɍs‚¤•K—v‚ª‚ ‚è‚Ü‚·B %sample #include "form_decode.as" #include "encode.as" // ƒEƒBƒLƒyƒfƒBƒA‚́uƒEƒBƒLƒyƒfƒBƒAv‚ÉŠÖ‚·‚éƒy[ƒW‚ÌURL before = "http://ja.wikipedia.org/wiki/%E3%82%A6%E3%82%A3%E3%82%AD%E3%83%9A%E3%83%87%E3%82%A3%E3%82%A2" // ƒfƒR[ƒh‚ÌŽÀs result = "" form_decode result, before // Œ‹‰Ê‚Ì•\ަiUTF-8‚ðƒVƒtƒgJIS‚Ö•ÏŠ·j mes utf8n2sjis(result) stop
zakki/openhsp
package/hsphelp/form_decode.hs
bsd-3-clause
1,035
356
7
147
836
447
389
-1
-1
{-# LANGUAGE BangPatterns #-} module Main (main) where import Control.Applicative import Control.Lens (view) import Criterion.Main import Data.Accessor ((^=)) import Data.Colour (opaque) import Data.Colour.Names import qualified Data.Foldable as F import Data.Random.Normal (normalsIO') import Data.Vector.Storable (Vector) import qualified Data.Vector.Storable as V import Linear import Numeric.Ransac type Point = V2 Float fitLine :: Vector Point -> Maybe (V2 Float) fitLine pts = (!* b) <$> inv22 a where sx = V.sum $ V.map (view _x) pts a = V2 (V2 (V.sum (V.map ((^2).view _x) pts)) sx) (V2 sx (fromIntegral $ V.length pts)) b = V2 (V.sum (V.map F.product pts)) (V.sum (V.map (view _y) pts)) ptError :: V2 Float -> Point -> Float ptError (V2 m b) (V2 x y) = sq $ y - (m*x+b) where sq x = x * x main = do noise <- v2Cast . V.fromList . take (n*2) <$> normalsIO' (0,0.3) let !pts' = V.zipWith (+) noise pts ran = ransac 100 2 0.6 fitLine ptError (< 1) pts' putStr $ "Sanity " ran >>= putStrLn . show . fmap fst defaultMain [ bench "linear fit" $ fmap (quadrance . fst) <$> ran ] where n = 10000 !pts = V.generate n mkPt mkPt :: Int -> V2 Float mkPt i = let x = fromIntegral i / 500 in V2 x (3*x + 2) v2Cast :: Vector Float -> Vector Point v2Cast = V.unsafeCast
acowley/RANSAC
tests/Perf.hs
bsd-3-clause
1,439
0
17
403
620
325
295
38
1
{-# language CPP #-} -- | = Name -- -- VK_AMD_rasterization_order - device extension -- -- == VK_AMD_rasterization_order -- -- [__Name String__] -- @VK_AMD_rasterization_order@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 19 -- -- [__Revision__] -- 1 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- [__Contact__] -- -- - Daniel Rakos -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_AMD_rasterization_order] @drakos-amd%0A<<Here describe the issue or question you have about the VK_AMD_rasterization_order extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2016-04-25 -- -- [__IP Status__] -- No known IP claims. -- -- [__Contributors__] -- -- - Matthaeus G. Chajdas, AMD -- -- - Jaakko Konttinen, AMD -- -- - Daniel Rakos, AMD -- -- - Graham Sellers, AMD -- -- - Dominik Witczak, AMD -- -- == Description -- -- This extension introduces the possibility for the application to control -- the order of primitive rasterization. In unextended Vulkan, the -- following stages are guaranteed to execute in /API order/: -- -- - depth bounds test -- -- - stencil test, stencil op, and stencil write -- -- - depth test and depth write -- -- - occlusion queries -- -- - blending, logic op, and color write -- -- This extension enables applications to opt into a relaxed, -- implementation defined primitive rasterization order that may allow -- better parallel processing of primitives and thus enabling higher -- primitive throughput. It is applicable in cases where the primitive -- rasterization order is known to not affect the output of the rendering -- or any differences caused by a different rasterization order are not a -- concern from the point of view of the application’s purpose. -- -- A few examples of cases when using the relaxed primitive rasterization -- order would not have an effect on the final rendering: -- -- - If the primitives rendered are known to not overlap in framebuffer -- space. -- -- - If depth testing is used with a comparison operator of -- 'Vulkan.Core10.Enums.CompareOp.COMPARE_OP_LESS', -- 'Vulkan.Core10.Enums.CompareOp.COMPARE_OP_LESS_OR_EQUAL', -- 'Vulkan.Core10.Enums.CompareOp.COMPARE_OP_GREATER', or -- 'Vulkan.Core10.Enums.CompareOp.COMPARE_OP_GREATER_OR_EQUAL', and the -- primitives rendered are known to not overlap in clip space. -- -- - If depth testing is not used and blending is enabled for all -- attachments with a commutative blend operator. -- -- == New Structures -- -- - Extending -- 'Vulkan.Core10.Pipeline.PipelineRasterizationStateCreateInfo': -- -- - 'PipelineRasterizationStateRasterizationOrderAMD' -- -- == New Enums -- -- - 'RasterizationOrderAMD' -- -- == New Enum Constants -- -- - 'AMD_RASTERIZATION_ORDER_EXTENSION_NAME' -- -- - 'AMD_RASTERIZATION_ORDER_SPEC_VERSION' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD' -- -- == Issues -- -- 1) How is this extension useful to application developers? -- -- __RESOLVED__: Allows them to increase primitive throughput for cases -- when strict API order rasterization is not important due to the nature -- of the content, the configuration used, or the requirements towards the -- output of the rendering. -- -- 2) How does this extension interact with content optimizations aiming to -- reduce overdraw by appropriately ordering the input primitives? -- -- __RESOLVED__: While the relaxed rasterization order might somewhat limit -- the effectiveness of such content optimizations, most of the benefits of -- it are expected to be retained even when the relaxed rasterization order -- is used, so applications /should/ still apply these optimizations even -- if they intend to use the extension. -- -- 3) Are there any guarantees about the primitive rasterization order when -- using the new relaxed mode? -- -- __RESOLVED__: No. In this case the rasterization order is completely -- implementation-dependent, but in practice it is expected to partially -- still follow the order of incoming primitives. -- -- 4) Does the new relaxed rasterization order have any adverse effect on -- repeatability and other invariance rules of the API? -- -- __RESOLVED__: Yes, in the sense that it extends the list of exceptions -- when the repeatability requirement does not apply. -- -- == Examples -- -- None -- -- == Issues -- -- None -- -- == Version History -- -- - Revision 1, 2016-04-25 (Daniel Rakos) -- -- - Initial draft. -- -- == See Also -- -- 'PipelineRasterizationStateRasterizationOrderAMD', -- 'RasterizationOrderAMD' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_AMD_rasterization_order Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_AMD_rasterization_order ( PipelineRasterizationStateRasterizationOrderAMD(..) , RasterizationOrderAMD( RASTERIZATION_ORDER_STRICT_AMD , RASTERIZATION_ORDER_RELAXED_AMD , .. ) , AMD_RASTERIZATION_ORDER_SPEC_VERSION , pattern AMD_RASTERIZATION_ORDER_SPEC_VERSION , AMD_RASTERIZATION_ORDER_EXTENSION_NAME , pattern AMD_RASTERIZATION_ORDER_EXTENSION_NAME ) where import Vulkan.Internal.Utils (enumReadPrec) import Vulkan.Internal.Utils (enumShowsPrec) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import GHC.Show (showsPrec) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero) import Vulkan.Zero (Zero(..)) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import Data.Int (Int32) import Foreign.Ptr (Ptr) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import Data.Kind (Type) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD)) -- | VkPipelineRasterizationStateRasterizationOrderAMD - Structure defining -- rasterization order for a graphics pipeline -- -- == Valid Usage (Implicit) -- -- If the @VK_AMD_rasterization_order@ device extension is not enabled or -- the application does not request a particular rasterization order -- through specifying a 'PipelineRasterizationStateRasterizationOrderAMD' -- structure then the rasterization order used by the graphics pipeline -- defaults to 'RASTERIZATION_ORDER_STRICT_AMD'. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_AMD_rasterization_order VK_AMD_rasterization_order>, -- 'RasterizationOrderAMD', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data PipelineRasterizationStateRasterizationOrderAMD = PipelineRasterizationStateRasterizationOrderAMD { -- | @rasterizationOrder@ is a 'RasterizationOrderAMD' value specifying the -- primitive rasterization order to use. -- -- #VUID-VkPipelineRasterizationStateRasterizationOrderAMD-rasterizationOrder-parameter# -- @rasterizationOrder@ /must/ be a valid 'RasterizationOrderAMD' value rasterizationOrder :: RasterizationOrderAMD } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (PipelineRasterizationStateRasterizationOrderAMD) #endif deriving instance Show PipelineRasterizationStateRasterizationOrderAMD instance ToCStruct PipelineRasterizationStateRasterizationOrderAMD where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p PipelineRasterizationStateRasterizationOrderAMD{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr RasterizationOrderAMD)) (rasterizationOrder) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr RasterizationOrderAMD)) (zero) f instance FromCStruct PipelineRasterizationStateRasterizationOrderAMD where peekCStruct p = do rasterizationOrder <- peek @RasterizationOrderAMD ((p `plusPtr` 16 :: Ptr RasterizationOrderAMD)) pure $ PipelineRasterizationStateRasterizationOrderAMD rasterizationOrder instance Storable PipelineRasterizationStateRasterizationOrderAMD where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PipelineRasterizationStateRasterizationOrderAMD where zero = PipelineRasterizationStateRasterizationOrderAMD zero -- | VkRasterizationOrderAMD - Specify rasterization order for a graphics -- pipeline -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_AMD_rasterization_order VK_AMD_rasterization_order>, -- 'PipelineRasterizationStateRasterizationOrderAMD' newtype RasterizationOrderAMD = RasterizationOrderAMD Int32 deriving newtype (Eq, Ord, Storable, Zero) -- | 'RASTERIZATION_ORDER_STRICT_AMD' specifies that operations for each -- primitive in a subpass /must/ occur in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#drawing-primitive-order primitive order>. pattern RASTERIZATION_ORDER_STRICT_AMD = RasterizationOrderAMD 0 -- | 'RASTERIZATION_ORDER_RELAXED_AMD' specifies that operations for each -- primitive in a subpass /may/ not occur in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#drawing-primitive-order primitive order>. pattern RASTERIZATION_ORDER_RELAXED_AMD = RasterizationOrderAMD 1 {-# complete RASTERIZATION_ORDER_STRICT_AMD, RASTERIZATION_ORDER_RELAXED_AMD :: RasterizationOrderAMD #-} conNameRasterizationOrderAMD :: String conNameRasterizationOrderAMD = "RasterizationOrderAMD" enumPrefixRasterizationOrderAMD :: String enumPrefixRasterizationOrderAMD = "RASTERIZATION_ORDER_" showTableRasterizationOrderAMD :: [(RasterizationOrderAMD, String)] showTableRasterizationOrderAMD = [(RASTERIZATION_ORDER_STRICT_AMD, "STRICT_AMD"), (RASTERIZATION_ORDER_RELAXED_AMD, "RELAXED_AMD")] instance Show RasterizationOrderAMD where showsPrec = enumShowsPrec enumPrefixRasterizationOrderAMD showTableRasterizationOrderAMD conNameRasterizationOrderAMD (\(RasterizationOrderAMD x) -> x) (showsPrec 11) instance Read RasterizationOrderAMD where readPrec = enumReadPrec enumPrefixRasterizationOrderAMD showTableRasterizationOrderAMD conNameRasterizationOrderAMD RasterizationOrderAMD type AMD_RASTERIZATION_ORDER_SPEC_VERSION = 1 -- No documentation found for TopLevel "VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION" pattern AMD_RASTERIZATION_ORDER_SPEC_VERSION :: forall a . Integral a => a pattern AMD_RASTERIZATION_ORDER_SPEC_VERSION = 1 type AMD_RASTERIZATION_ORDER_EXTENSION_NAME = "VK_AMD_rasterization_order" -- No documentation found for TopLevel "VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME" pattern AMD_RASTERIZATION_ORDER_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern AMD_RASTERIZATION_ORDER_EXTENSION_NAME = "VK_AMD_rasterization_order"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_AMD_rasterization_order.hs
bsd-3-clause
12,583
1
14
2,336
1,253
799
454
-1
-1
{-# language CPP #-} -- | = Name -- -- VK_EXT_image_view_min_lod - device extension -- -- == VK_EXT_image_view_min_lod -- -- [__Name String__] -- @VK_EXT_image_view_min_lod@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 392 -- -- [__Revision__] -- 1 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- - Requires @VK_KHR_get_physical_device_properties2@ -- -- [__Contact__] -- -- - Joshua Ashton -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_image_view_min_lod] @Joshua-Ashton%0A<<Here describe the issue or question you have about the VK_EXT_image_view_min_lod extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2021-11-09 -- -- [__IP Status__] -- No known IP claims. -- -- [__Contributors__] -- -- - Joshua Ashton, Valve -- -- - Hans-Kristian Arntzen, Valve -- -- - Samuel Iglesias Gonsalvez, Igalia -- -- - Tobias Hector, AMD -- -- - Jason Ekstrand, Intel -- -- - Tom Olson, ARM -- -- == Description -- -- This extension allows applications to clamp the minimum LOD value during -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures-image-level-selection Image Level(s) Selection> -- and -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures-integer-coordinate-operations Integer Texel Coordinate Operations> -- with a given 'Vulkan.Core10.Handles.ImageView' by -- 'ImageViewMinLodCreateInfoEXT'::@minLod@. -- -- This extension may be useful to restrict a -- 'Vulkan.Core10.Handles.ImageView' to only mips which have been uploaded, -- and the use of fractional @minLod@ can be useful for smoothly -- introducing new mip levels when using linear mipmap filtering. -- -- == New Structures -- -- - Extending 'Vulkan.Core10.ImageView.ImageViewCreateInfo': -- -- - 'ImageViewMinLodCreateInfoEXT' -- -- - Extending -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2', -- 'Vulkan.Core10.Device.DeviceCreateInfo': -- -- - 'PhysicalDeviceImageViewMinLodFeaturesEXT' -- -- == New Enum Constants -- -- - 'EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME' -- -- - 'EXT_IMAGE_VIEW_MIN_LOD_SPEC_VERSION' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_MIN_LOD_FEATURES_EXT' -- -- == Version History -- -- - Revision 1, 2021-07-06 (Joshua Ashton) -- -- - Initial version -- -- == See Also -- -- 'ImageViewMinLodCreateInfoEXT', -- 'PhysicalDeviceImageViewMinLodFeaturesEXT' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_image_view_min_lod Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_EXT_image_view_min_lod ( PhysicalDeviceImageViewMinLodFeaturesEXT(..) , ImageViewMinLodCreateInfoEXT(..) , EXT_IMAGE_VIEW_MIN_LOD_SPEC_VERSION , pattern EXT_IMAGE_VIEW_MIN_LOD_SPEC_VERSION , EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME , pattern EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME ) where import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Data.Coerce (coerce) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.C.Types (CFloat) import Foreign.C.Types (CFloat(..)) import Foreign.C.Types (CFloat(CFloat)) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import Foreign.Ptr (Ptr) import Data.Kind (Type) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_MIN_LOD_FEATURES_EXT)) -- | VkPhysicalDeviceImageViewMinLodFeaturesEXT - Structure describing -- whether clamping the min lod of a image view is supported by the -- implementation -- -- = Members -- -- This structure describes the following features: -- -- = Description -- -- If the 'PhysicalDeviceImageViewMinLodFeaturesEXT' structure is included -- in the @pNext@ chain of the -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2' -- structure passed to -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2', -- it is filled in to indicate whether each corresponding feature is -- supported. 'PhysicalDeviceImageViewMinLodFeaturesEXT' /can/ also be used -- in the @pNext@ chain of 'Vulkan.Core10.Device.DeviceCreateInfo' to -- selectively enable these features. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_image_view_min_lod VK_EXT_image_view_min_lod>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data PhysicalDeviceImageViewMinLodFeaturesEXT = PhysicalDeviceImageViewMinLodFeaturesEXT { -- | #features-minLod# @minLod@ indicates whether the implementation supports -- clamping the minimum LOD value during -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures-image-level-selection Image Level(s) Selection> -- and -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures-integer-coordinate-operations Integer Texel Coordinate Operations> -- with a given 'Vulkan.Core10.Handles.ImageView' by -- 'ImageViewMinLodCreateInfoEXT'::@minLod@. minLod :: Bool } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (PhysicalDeviceImageViewMinLodFeaturesEXT) #endif deriving instance Show PhysicalDeviceImageViewMinLodFeaturesEXT instance ToCStruct PhysicalDeviceImageViewMinLodFeaturesEXT where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p PhysicalDeviceImageViewMinLodFeaturesEXT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_MIN_LOD_FEATURES_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (minLod)) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_MIN_LOD_FEATURES_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct PhysicalDeviceImageViewMinLodFeaturesEXT where peekCStruct p = do minLod <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) pure $ PhysicalDeviceImageViewMinLodFeaturesEXT (bool32ToBool minLod) instance Storable PhysicalDeviceImageViewMinLodFeaturesEXT where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PhysicalDeviceImageViewMinLodFeaturesEXT where zero = PhysicalDeviceImageViewMinLodFeaturesEXT zero -- | VkImageViewMinLodCreateInfoEXT - Structure describing the minimum lod of -- an image view -- -- == Valid Usage -- -- - #VUID-VkImageViewMinLodCreateInfoEXT-minLod-06455# If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-minLod minLod> -- feature is not enabled, @minLod@ /must/ be @0.0@. -- -- - #VUID-VkImageViewMinLodCreateInfoEXT-minLod-06456# @minLod@ /must/ -- be less or equal to the index of the last mipmap level accessible to -- the view. -- -- == Valid Usage (Implicit) -- -- - #VUID-VkImageViewMinLodCreateInfoEXT-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_image_view_min_lod VK_EXT_image_view_min_lod>, -- 'Vulkan.Core10.Enums.StructureType.StructureType' data ImageViewMinLodCreateInfoEXT = ImageViewMinLodCreateInfoEXT { -- | @minLod@ is the value to clamp the minimum LOD accessible by this -- 'Vulkan.Core10.Handles.ImageView'. minLod :: Float } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (ImageViewMinLodCreateInfoEXT) #endif deriving instance Show ImageViewMinLodCreateInfoEXT instance ToCStruct ImageViewMinLodCreateInfoEXT where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p ImageViewMinLodCreateInfoEXT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr CFloat)) (CFloat (minLod)) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr CFloat)) (CFloat (zero)) f instance FromCStruct ImageViewMinLodCreateInfoEXT where peekCStruct p = do minLod <- peek @CFloat ((p `plusPtr` 16 :: Ptr CFloat)) pure $ ImageViewMinLodCreateInfoEXT (coerce @CFloat @Float minLod) instance Storable ImageViewMinLodCreateInfoEXT where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero ImageViewMinLodCreateInfoEXT where zero = ImageViewMinLodCreateInfoEXT zero type EXT_IMAGE_VIEW_MIN_LOD_SPEC_VERSION = 1 -- No documentation found for TopLevel "VK_EXT_IMAGE_VIEW_MIN_LOD_SPEC_VERSION" pattern EXT_IMAGE_VIEW_MIN_LOD_SPEC_VERSION :: forall a . Integral a => a pattern EXT_IMAGE_VIEW_MIN_LOD_SPEC_VERSION = 1 type EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME = "VK_EXT_image_view_min_lod" -- No documentation found for TopLevel "VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME" pattern EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME = "VK_EXT_image_view_min_lod"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_EXT_image_view_min_lod.hs
bsd-3-clause
11,231
0
14
1,791
1,557
939
618
-1
-1
module Problem41 where import Control.Applicative import Data.Char import Prime main :: IO () main = print . maximum . filter isPandigital $ getPrimesUpto 7654321 isPandigital :: Int -> Bool isPandigital n = and $ liftA2 elem ['1' .. (chr $ ord '0' + length n')] [n'] where n' = show n
adityagupta1089/Project-Euler-Haskell
src/problems/Problem41.hs
bsd-3-clause
293
0
11
58
114
60
54
9
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} import Control.Monad.Trans.Either import System.IO import qualified Data.ByteString.Lazy.Char8 as LBS import Control.Monad.Trans.AWS as AWS import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.Sign.V4 import Data.Aeson.Encode.Pretty data APIGW = APIGW newtype APIGWResponse = APIGWResponse Value deriving (Show, ToJSON) pprint :: ToJSON a => a -> IO () pprint = LBS.putStrLn . encodePretty apigw :: Service apigw = Service { _svcAbbrev = "APIGateway" , _svcSigner = v4 , _svcPrefix = "apigateway" , _svcVersion = "" , _svcEndpoint = defaultEndpoint apigw , _svcTimeout = Just 70 , _svcCheck = statusSuccess , _svcError = parseJSONError , _svcRetry = retry } where retry = Exponential { _retryBase = 5.0e-2 , _retryGrowth = 2 , _retryAttempts = 5 , _retryCheck = check } check e | has (hasCode "ThrottlingException" . hasStatus 400) e = Just "throttling_exception" | has (hasCode "Throttling" . hasStatus 400) e = Just "throttling" | has (hasStatus 503) e = Just "service_unavailable" | has (hasStatus 500) e = Just "general_server_error" | has (hasStatus 509) e = Just "limit_exceeded" | otherwise = Nothing us x = do logger <- AWS.newLogger AWS.Trace stdout env <- AWS.newEnv NorthVirginia Discover <&> AWS.envLogger .~ logger runResourceT $ runAWST env x instance AWSRequest APIGW where type Rs APIGW = APIGWResponse request = get apigw response = receiveJSON (\ s h x -> APIGWResponse <$> eitherParseJSON x) instance ToHeaders APIGW where toHeaders = const (mconcat ["Content-Type" =# ("application/x-amz-json-1.0" :: ByteString)]) instance ToJSON APIGW where toJSON APIGW = object [] instance ToPath APIGW where toPath = const "/" instance ToQuery APIGW where toQuery = const mempty
proger/unhal
Amazonka.hs
bsd-3-clause
2,228
0
13
595
575
308
267
67
1
-- currently bothballed, will probably be never needed module Main where import System.Environment import System.Exit import System.Directory import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.List as List main = do args <- getArgs inFileNames <- checkArgs args recordLists <- mapM readCSV inFileNames let benchRecords = concat $ map snd recordLists let outputData = processData $ map separateImprecision benchRecords let outFileNames = map makeOutFileName $ map fst outputData mapM_ writeOutputFile $ zip outFileNames outputData writeFile "plotAll.gnuplot" $ makeGnuplot inFileNames outFileNames checkArgs [] = usageAndQuit checkArgs inFileNames = do results <- mapM doesFileExist inFileNames case and results of True -> return inFileNames False -> usageAndQuit usageAndQuit = do progName <- getProgName putStrLn $ "usage: " ++ progName ++ " <file1>.csv [<file2>.csv ...]" exitFailure slash2dash '/' = '-' slash2dash c = c writeOutputFile (outFileName, (name, benchRecords)) = do putStrLn outFileName writeCSV outFileName (["Imprecision", "Mean"], benchRecords) makeOutFileName name = (map space2underscore name) ++ ".csv" space2underscore ' ' = '_' space2underscore c = c separateImprecision record = Map.insert "Name" name $ Map.insert "Imprecision" imprecision $ record where name = map slash2dash nameSlashes imprecision = tail slashImprecision (nameSlashes, slashImprecision) = splitAt slashIndex nameSlashImprecision slashIndex = last $ List.elemIndices '/' nameSlashImprecision nameSlashImprecision = lookupKey record "Name" processData benchRecords = map extractName names where names = Set.toList $ Set.fromList $ map (\r -> lookupKey r "Name") benchRecords extractName name = (name, filter (\r -> lookupKey r "Name" == name) benchRecords) makeGnuplot inFileNames outFileNames = unlines $ [ "# AUTO GENERATED FROM " ++ (List.intercalate ", " inFileNames) ,"set term postscript eps enhanced" ,"set output \"plotAll.eps\"" ,"set title 'computation time based on result imprecision'" ,"set key right bottom" ,"set key box linestyle 1" ,"set key spacing 1.5" ,"set logscale x" ,"set logscale y" ,"set xlabel 'imprecision'" ,"set ylabel 'time'" ,"set datafile separator \",\"" ] ++ [makePlotLine outFileNames] where makePlotLine outFileNames = "plot" ++ (List.intercalate "," (map makePlotImport outFileNames)) makePlotImport outFileName = " \"" ++ outFileName ++ "\" using 1:2" type Record = Map.Map String String type Sheet = ([String], [Record]) lookupKey :: Record -> String -> String lookupKey record key = case Map.lookup key record of Nothing -> "" -- error $ "key " ++ show key ++ " not found in record " ++ show record Just value -> value writeCSV :: FilePath -> Sheet -> IO () writeCSV filePath (keys, records) = do writeFile filePath $ unlines $ map formatLine $ (keys : dataLists) where dataLists = map makeDataItems records makeDataItems record = [lookupKey record key | key <- keys ] formatLine items = separateWith "," $ map show items -- must not contain a comma separateWith sep [] = "" separateWith sep [a] = a separateWith sep (h:t) = h ++ sep ++ (separateWith sep t) readCSV :: FilePath -> IO Sheet readCSV filePath = do contents <- readFile filePath return $ processContents contents where processContents contents = (header, recordMaps) where hdrRecords@(header : records) = parseCSV contents recordMaps = map snd $ indexRecordsByKeysAndHeader [] hdrRecords indexRecordsByKeysAndHeader keys (header : records) = map getKeysAndMap records where getKeysAndMap record = (getKeys record, getMap record) getKeys record = map getKey keyIndices where getKey keyIx = record !! keyIx keyIndices = map keyIndex keys keyIndex key = case List.elemIndex key header of Nothing -> error $ "key " ++ show key ++ " not found in the header " ++ show header Just ix -> ix getMap record = Map.fromList $ zip header record -- | parse records and their fields from the contents of a CSV file parseCSV :: String -> [[String]] parseCSV contents = records where records = map parseLine $ lines contents parseLine line = state1 0 [] "" line where -- expecting new field or end of line; initial state state1 pos revPrevItems revPrevOutput [] = reverse $ reverse revPrevOutput : revPrevItems state1 pos revPrevItems revPrevOutput "\x0D" = -- DOS end of line reverse $ reverse revPrevOutput : revPrevItems state1 pos revPrevItems revPrevOutput (',' : cs) = state1 (pos + 1) (reverse revPrevOutput : revPrevItems) "" cs state1 pos revPrevItems revPrevOutput ('"' : cs) = state3 (pos + 1) revPrevItems revPrevOutput cs state1 pos revPrevItems revPrevOutput (c : cs) = state2 (pos + 1) revPrevItems (c : revPrevOutput) cs -- reading a field with no double quotes state2 pos revPrevItems revPrevOutput [] = reverse $ reverse revPrevOutput : revPrevItems state2 pos revPrevItems revPrevOutput "\x0D" = -- DOS end of line reverse $ reverse revPrevOutput : revPrevItems state2 pos revPrevItems revPrevOutput (',' : cs) = state1 (pos + 1) (reverse revPrevOutput : revPrevItems) "" cs state2 pos revPrevItems revPrevOutput (c : cs) = state2 (pos + 1) revPrevItems (c : revPrevOutput) cs -- reading a field in double quotes state3 pos revPrevItems revPrevOutput [] = parseerror pos state3 pos revPrevItems revPrevOutput ('"' : cs) = state4 (pos + 1) revPrevItems revPrevOutput cs state3 pos revPrevItems revPrevOutput (c : cs) = state3 (pos + 1) revPrevItems (c : revPrevOutput) cs -- reading a field in double quotes and just found a double quote -- that could be the closing one or an inner one state4 pos revPrevItems revPrevOutput [] = reverse $ reverse revPrevOutput : revPrevItems state4 pos revPrevItems revPrevOutput "\x0D" = -- DOS end of line reverse $ reverse revPrevOutput : revPrevItems state4 pos revPrevItems revPrevOutput (',' : cs) = state1 (pos + 1) (reverse revPrevOutput : revPrevItems) "" cs state4 pos revPrevItems revPrevOutput (c : cs) = state3 (pos + 1) revPrevItems (c : revPrevOutput) cs parseerror pos = error $ "parse error in CVS file at pos:\n" ++ take pos line ++ "\n" ++ replicate pos ' ' ++ drop pos line
michalkonecny/aern
aern-order/tools/BenchCsvToGnuplot.hs
bsd-3-clause
7,193
0
13
2,061
1,838
931
907
165
13
-------------------------------------------------------------------------------- -- Copyright © 2011 National Institute of Aerospace / Galois, Inc. -------------------------------------------------------------------------------- -- | Comparison operators. {-# LANGUAGE Trustworthy #-} module Copilot.Language.Operators.Ord ( (<=) , (>=) , (<) , (>) ) where import Copilot.Core (Typed, typeOf) import qualified Copilot.Core as Core import Copilot.Language.Prelude import Copilot.Language.Stream import qualified Prelude as P -------------------------------------------------------------------------------- (<=) :: (P.Ord a, Typed a) => Stream a -> Stream a -> Stream Bool (Const x) <= (Const y) = Const (x P.<= y) x <= y = Op2 (Core.Le typeOf) x y (>=) :: (P.Ord a, Typed a) => Stream a -> Stream a -> Stream Bool (Const x) >= (Const y) = Const (x P.>= y) x >= y = Op2 (Core.Ge typeOf) x y (<) :: (P.Ord a, Typed a) => Stream a -> Stream a -> Stream Bool (Const x) < (Const y) = Const (x P.< y) x < y = Op2 (Core.Lt typeOf) x y (>) :: (P.Ord a, Typed a) => Stream a -> Stream a -> Stream Bool (Const x) > (Const y) = Const (x P.> y) x > y = Op2 (Core.Gt typeOf) x y --------------------------------------------------------------------------------
leepike/copilot-language
src/Copilot/Language/Operators/Ord.hs
bsd-3-clause
1,331
0
8
273
484
257
227
23
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RankNTypes #-} module Gfx.Engine where import Control.DeepSeq import Control.Monad.State.Strict import qualified Data.Map as M import Graphics.Rendering.OpenGL ( BlendingFactor ( One , OneMinusSrcAlpha , SrcAlpha ) , GLfloat ) import Lens.Simple ( (^.) , makeLenses , over , set ) import Linear.Matrix ( (!*!) , M44 , identity ) import Linear.V3 ( V3(..) ) import Gfx.Geometries ( Geometries , createAllGeometries ) import Gfx.Materials ( MaterialLibrary , MaterialsConfig(..) ) import Gfx.Matrices ( projectionMat , viewMat ) import Gfx.PostProcessing ( AnimationStyle(NormalStyle) , PostProcessingConfig , filterVars ) import Gfx.TextRendering ( TextRenderer ) import Gfx.Textures ( TextureLibrary ) import Gfx.Types ( Colour(..) ) import Language.Ast ( Value ) import qualified Util.Setting as S import qualified Util.SettingMap as SM import Configuration ( ImprovizConfig ) import qualified Configuration as C import qualified Configuration.Screen as CS import Util ( (/.) ) data GFXFillStyling = GFXFillColour !Colour | GFXNoFill deriving (Eq, Show) instance NFData GFXFillStyling where rnf = rwhnf data GFXTextureStyling = GFXTextureStyling String !Int deriving (Eq, Show) instance NFData GFXTextureStyling where rnf = rwhnf data GFXStrokeStyling = GFXStrokeColour !Colour | GFXNoStroke deriving (Eq, Show) instance NFData GFXStrokeStyling where rnf = rwhnf data SavableState = SavableState { _savedMatrixStack :: [M44 GLfloat] , _savedFillStyles :: !GFXFillStyling , _savedStrokeStyles :: !GFXStrokeStyling , _savedTextureStyles :: !GFXTextureStyling , _savedMaterials :: String , _savedMaterialVars :: !(M.Map String Value) } deriving Show instance NFData SavableState where rnf s = rnf (rwhnf s, _savedMatrixStack s) makeLenses ''SavableState data GfxEngine = GfxEngine { _fillStyle :: S.Setting GFXFillStyling , _strokeStyle :: S.Setting GFXStrokeStyling , _textureStyle :: S.Setting GFXTextureStyling , _material :: S.Setting String , _geometryBuffers :: Geometries , _textureLibrary :: TextureLibrary , _materialLibrary :: MaterialLibrary , _materialVars :: SM.SettingMap String Value , _viewMatrix :: !(M44 GLfloat) , _projectionMatrix :: !(M44 GLfloat) , _aspectRatio :: Float , _postFX :: PostProcessingConfig , _postFXVars :: SM.SettingMap String Value , _textRenderer :: TextRenderer , _matrixStack :: [M44 GLfloat] , _scopeStack :: [SavableState] , _animationStyle :: S.Setting AnimationStyle , _backgroundColor :: S.Setting Colour , _depthChecking :: S.Setting Bool , _blendFunction :: S.Setting ((BlendingFactor, BlendingFactor), (BlendingFactor, BlendingFactor)) } deriving (Show) instance NFData GfxEngine where rnf g = rnf ((_fillStyle g, _strokeStyle g, _textureStyle g, _material g), (_matrixStack g, _scopeStack g)) makeLenses '' GfxEngine type GraphicsEngine v = StateT GfxEngine IO v createGfxEngine :: ImprovizConfig -> Int -> Int -> PostProcessingConfig -> TextRenderer -> TextureLibrary -> MaterialsConfig -> IO GfxEngine createGfxEngine config width height pprocess trender textLib matCfg = let ratio = width /. height front = config ^. C.screen . CS.front back = config ^. C.screen . CS.back projection = projectionMat front back (pi / 4) ratio view = viewMat (V3 0 0 10) (V3 0 0 0) (V3 0 1 0) in do gbos <- createAllGeometries (config ^. C.geometryDirectories) return GfxEngine { _fillStyle = S.create $ GFXFillColour $ Colour 1 1 1 1 , _strokeStyle = S.create $ GFXStrokeColour $ Colour 0 0 0 1 , _textureStyle = S.create $ GFXTextureStyling "" 0 , _material = S.create "basic" , _geometryBuffers = gbos , _textureLibrary = textLib , _materialLibrary = materialsLibrary matCfg , _materialVars = SM.create $ varDefaults matCfg , _viewMatrix = view , _projectionMatrix = projection , _aspectRatio = ratio , _postFX = pprocess , _postFXVars = pprocess ^. filterVars , _textRenderer = trender , _matrixStack = [identity] , _scopeStack = [] , _animationStyle = S.create NormalStyle , _backgroundColor = S.create (Colour 1 1 1 1) , _depthChecking = S.create True , _blendFunction = S.create ((SrcAlpha, OneMinusSrcAlpha), (One, One)) } resizeGfxEngine :: ImprovizConfig -> Int -> Int -> PostProcessingConfig -> TextRenderer -> GfxEngine -> GfxEngine resizeGfxEngine config newWidth newHeight newPP newTR = let front = config ^. C.screen . CS.front back = config ^. C.screen . CS.back newRatio = newWidth /. newHeight newProj = projectionMat front back (pi / 4) newRatio in set projectionMatrix newProj . set postFX newPP . set textRenderer newTR . set aspectRatio newRatio resetGfxEngine :: GfxEngine -> GfxEngine resetGfxEngine ge = ge { _fillStyle = S.reset (_fillStyle ge) , _strokeStyle = S.reset (_strokeStyle ge) , _material = S.reset (_material ge) , _materialVars = SM.reset (_materialVars ge) , _postFXVars = SM.reset (_postFXVars ge) , _matrixStack = [identity] , _scopeStack = [] , _animationStyle = S.resetIfUnused (_animationStyle ge) , _backgroundColor = S.resetIfUnused (_backgroundColor ge) , _depthChecking = S.resetIfUnused (_depthChecking ge) , _blendFunction = S.resetIfUnused (_blendFunction ge) } pushMatrix :: M44 Float -> GfxEngine -> GfxEngine pushMatrix mat = over matrixStack (\stack -> (head stack !*! mat) : stack) popMatrix :: GfxEngine -> GfxEngine popMatrix = over matrixStack tail multMatrix :: M44 Float -> GfxEngine -> GfxEngine multMatrix mat = over matrixStack (\stack -> (head stack !*! mat) : tail stack)
rumblesan/improviz
src/Gfx/Engine.hs
bsd-3-clause
7,625
0
14
2,971
1,689
941
748
-1
-1
{-# LANGUAGE RecordWildCards, GeneralizedNewtypeDeriving, TupleSections, CPP #-} {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} -- time changed incompatibly, use the functions that work everywhere module General.Extra( UTCTime, getCurrentTime, addSeconds, showRelativeTime, relativeTime, showUTCTime, readDate, showDate, timeToDate, dateToTime, createDir, withFileLock, pick, memoIO0, memoIO1, encryptish, catMaybesSet, whenLeft, whenRight, timeInit, timed, time, time_, eitherToMaybe, newCVar, readCVar, modifyCVar, modifyCVar_, registerMaster, forkSlave, Worker, newWorker, makeRelativeEx, transitiveClosure, findCycle, putBlock, maybe', withs, commas, commasLimit, unwordsLimit ) where import Data.Time.Clock import Data.Time.Calendar import System.Time.Extra import System.IO.Unsafe import System.IO.Extra import Data.IORef import Data.List.Extra import System.Directory.Extra import Data.Hashable import Numeric import System.FilePath import Control.Exception.Extra import Control.Applicative import Control.Monad.Extra import Control.Concurrent.Extra import Development.Shake.Command import Data.Maybe import System.Random import Data.Either.Extra import Data.Time.Format #if __GLASGOW_HASKELL__< 710 import System.Locale #endif import qualified Data.HashMap.Strict as HashMap import qualified Data.Set as Set import Prelude addSeconds :: Seconds -> UTCTime -> UTCTime addSeconds x = addUTCTime (fromRational $ toRational x) relativeTime :: IO (UTCTime -> Seconds) relativeTime = do now <- getCurrentTime return $ \old -> subtractTime now old showRelativeTime :: IO (UTCTime -> String) showRelativeTime = do now <- getCurrentTime return $ \old -> let secs = subtractTime now old in if timeToDate now /= timeToDate old then showDate (timeToDate old) else if secs < 60 then show (max 1 $ floor secs) ++ "s ago" -- 4.32s is too precise, 0s feels wrong else showDuration secs ++ " ago" showUTCTime :: String -> UTCTime -> String showUTCTime = formatTime defaultTimeLocale timeToDate :: UTCTime -> Day timeToDate = utctDay dateToTime :: Day -> UTCTime dateToTime = flip UTCTime 0 readDate :: String -> Day readDate = readTime defaultTimeLocale (iso8601DateFormat Nothing) showDate :: Day -> String showDate = formatTime defaultTimeLocale (iso8601DateFormat Nothing) -- | One way function used for encrypting encryptish :: String -> String encryptish x = upper $ showHex (abs $ hash x) "" {-# NOINLINE logTime #-} logTime :: IO Seconds logTime = unsafePerformIO offsetTime timeInit :: IO () timeInit = void $ evaluate =<< logTime {-# NOINLINE createDirLock #-} createDirLock :: Lock createDirLock = unsafePerformIO newLock createDir :: String -> [String] -> IO FilePath createDir prefix info = do let name = prefix ++ (if null info then "" else "-" ++ show (abs $ hash info)) createDirectoryIfMissing True name withLock createDirLock $ writeFile (name </> ".bake.name") $ unlines info return name eitherToMaybe :: Either a b -> Maybe b eitherToMaybe = either (const Nothing) Just pick :: [a] -> IO a pick xs = randomRIO (0, (length xs - 1)) >>= return . (xs !!) timed :: String -> IO a -> IO a timed msg act = do (tim,res) <- duration act tot <- logTime putStrLn $ "[BAKE-TIME] " ++ showDuration tim ++ " (total of " ++ showDuration tot ++ "): " ++ msg return res time_ :: IO (CmdLine, CmdTime) -> IO () time_ act = time $ do (a,b) <- act; return (a,b,()) time :: IO (CmdLine, CmdTime, a) -> IO a time act = do (CmdLine msg, CmdTime tim, res) <- act tot <- logTime putStrLn $ "[BAKE-TIME] " ++ showDuration tim ++ " (total of " ++ showDuration tot ++ "): " ++ msg return res makeRelativeEx :: FilePath -> FilePath -> IO FilePath makeRelativeEx x y = do x <- splitDirectories <$> canonicalizePath x y <- splitDirectories <$> canonicalizePath y return $ joinPath $ if take 1 x /= take 1 y then y else f x y where f (x:xs) (y:ys) | x == y = f xs ys | otherwise = ".." : f xs (y:ys) f _ ys = ys -- Might be better off using the 'filelock' package withFileLock :: FilePath -> IO a -> IO a withFileLock lock act = do -- important to canonicalize everything as the act might change the current directory createDirectoryIfMissing True $ takeDirectory lock lock <- (</> takeFileName lock) <$> canonicalizePath (takeDirectory lock) let stamp = lock <.> "stamp" let touch = do t <- show <$> getCurrentTime; ignore $ writeFile stamp t; return t unlessM (doesFileExist stamp) $ void touch (t,_) <- duration $ whileM $ do b <- try_ $ createDirectory lock if isRight b then do return False else do sleep 10 now <- getCurrentTime mtime <- try_ $ getModificationTime stamp case mtime of Right x | addSeconds 30 x > now -> return True _ -> do -- try and take ownership of the stamp me <- touch sleep 10 -- wait for the stamp to settle down src <- try_ $ readFile' stamp return $ either (const True) (/= me) src putStrLn $ "Waited " ++ showDuration t ++ " to acquire the file lock " ++ lock active <- newVar True touch thread <- forkSlave $ forever $ do sleep 10 withVar active $ \b -> when b $ void touch act `finally` do modifyVar_ active $ const $ return False killThread thread ignore $ removeDirectory lock {- tester :: IO () tester = do forM_ [1..2] $ \i -> do forkIO $ withFileLock "mylock" $ do print ("start", i) sleep 60 print ("stop",i) sleep 1000 -} --------------------------------------------------------------------- -- CVAR -- | A Var, but where readCVar returns the last cached value data CVar a = CVar {cvarCache :: Var a, cvarReal :: Var a} newCVar :: a -> IO (CVar a) newCVar x = liftM2 CVar (newVar x) (newVar x) readCVar :: CVar a -> IO a readCVar = readVar . cvarCache modifyCVar :: CVar a -> (a -> IO (a, b)) -> IO b modifyCVar CVar{..} f = modifyVar cvarReal $ \a -> do (a,b) <- f a modifyVar_ cvarCache $ const $ return a return (a,b) modifyCVar_ :: CVar a -> (a -> IO a) -> IO () modifyCVar_ cvar f = modifyCVar cvar $ fmap (,()) . f --------------------------------------------------------------------- -- SLAVE/MASTER {-# NOINLINE master #-} master :: IORef (Maybe ThreadId) master = unsafePerformIO $ newIORef Nothing registerMaster :: IO () registerMaster = writeIORef master . Just =<< myThreadId forkSlave :: IO () -> IO ThreadId forkSlave act = forkFinally act $ \v -> case v of Left e | fromException e /= Just ThreadKilled -> do m <- readIORef master whenJust m $ flip throwTo e _ -> return () type Worker = IO () -> IO () newWorker :: IO Worker newWorker = do lock <- newLock return $ \act -> void $ forkIO $ withLock lock act --------------------------------------------------------------------- -- UTILITIES -- | Given a relation and a starting value, find the transitive closure. -- The resulting list will be a set. transitiveClosure :: Ord a => (a -> [a]) -> [a] -> [a] transitiveClosure follow xs = f Set.empty xs where f seen [] = [] f seen (t:odo) | t `Set.member` seen = f seen odo | otherwise = t : f (Set.insert t seen) (follow t ++ odo) -- | Given a relation and a starting list, find a cycle if there is one. -- The resulting list will be a set, and will contain a cycle (but not necessarily be minimal). findCycle :: Ord a => (a -> [a]) -> [a] -> Maybe [a] findCycle follow = firstJust $ \x -> let children = transitiveClosure follow (follow x) -- if there is a cycle, make the element we know is cyclic first, so its easier to debug in if x `elem` children then Just (x : delete x children) else Nothing memoIO0 :: IO b -> IO (IO b) memoIO0 act = return $ unsafeInterleaveIO act memoIO1 :: (Hashable a, Eq a) => (a -> IO b) -> IO (a -> IO b) memoIO1 op = do var <- newVar HashMap.empty return $ \k -> modifyVar var $ \mp -> case HashMap.lookup k mp of Just v -> return (mp, v) Nothing -> do v <- op k return (HashMap.insert k v mp, v) catMaybesSet :: Ord a => Set.Set (Maybe a) -> Set.Set a catMaybesSet = Set.mapMonotonic fromJust . Set.delete Nothing whenLeft :: Applicative m => Either a b -> (a -> m ()) -> m () whenLeft x f = either f (const $ pure ()) x whenRight :: Applicative m => Either a b -> (b -> m ()) -> m () whenRight x f = either (const $ pure ()) f x --------------------------------------------------------------------- -- FORMATTING putBlock :: String -> [String] -> IO () putBlock title body = putStrLn $ unlines $ let s = "-- " ++ title ++ " --" in (s ++ replicate (70 - length s) '-') : body ++ [replicate 70 '-'] commas :: [String] -> String commas = intercalate ", " commasLimit :: Int -> [String] -> String commasLimit = limit commas unwordsLimit :: Int -> [String] -> String unwordsLimit = limit unwords limit :: ([String] -> String) -> Int -> [String] -> String limit rejoin i xs = rejoin a ++ (if null b then "" else "...") where (a,b) = splitAt i xs maybe' :: Maybe a -> b -> (a -> b) -> b maybe' x nothing just = maybe nothing just x withs :: [(a -> r) -> r] -> ([a] -> r) -> r withs [] act = act [] withs (f:fs) act = f $ \a -> withs fs $ \as -> act $ a:as
Pitometsu/bake
src/General/Extra.hs
bsd-3-clause
9,709
0
22
2,408
3,263
1,656
1,607
221
3
module Print2 where main :: IO () main = do putStrLn "Count to four for me: " putStr "one, two" putStr ", three, and " putStrLn "four!"
chengzh2008/hpffp
src/ch03-Strings/print2.hs
bsd-3-clause
145
0
7
36
43
19
24
7
1