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
-- GenI surface realiser -- Copyright (C) 2011 SRI -- -- 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. {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} module NLP.GenI.Test.TreeSchema where import Data.Tree import Test.HUnit import Test.QuickCheck hiding (collect, Failure) import Test.Framework import Test.Framework.Providers.HUnit import Test.Framework.Providers.QuickCheck2 import qualified Data.Text as T import NLP.GenI.FeatureStructure import NLP.GenI.GeniVal import NLP.GenI.TreeSchema import NLP.GenI.Test.GeniVal hiding ( suite ) suite :: Test.Framework.Test suite = testGroup "NLP.GenI.Tags" [] sillyTree :: Tree (GNode GeniVal) sillyTree = Node r [ Node s1 [] , Node l [] , Node s2 [] ] where r = emptyGN { gnname = "r" , gup = [ catAv "a", idxAv "rbad" ] , gdown = [ idxAv "r" ] } s x = emptyGN { gnname = x , gup = [ catAv "b", idxAv "s" ] , gdown = [ idxAv "sbad" ] , gtype = Subs } s1 = s "b1" s2 = s "b2" l = sillyLexNode sillyTreeAux :: Tree (GNode GeniVal) sillyTreeAux = Node r [ Node f [] , Node l [] , Node s [] ] where r = (emptyNodeCat "a") { gdown = [ idxAv "r" ] } f = emptyGN { gnname = "a2" , gup = [catAv "a", idxAv "f"] , gtype = Foot } s = emptyGN { gnname = "b" , gup = [catAv "b", idxAv "s"] , gtype = Subs } l = sillyLexNode emptyNodeCat x = emptyGN { gnname = x , gup = [catAv (mkGConstNone x)] } sillyLexNode = emptyGN { gnname = "l" , gup = [catAv "l"] , ganchor = True , gtype = Lex } catAv = AvPair "cat" idxAv = AvPair "idx" emptyGN = GN { gnname = "" , gup = [] , gdown = [] , ganchor = False , glexeme = [] , gtype = Other , gaconstr = False , gorigin = "test" } toSchemaTree :: Ttree (GNode GeniVal) -> SchemaTree toSchemaTree st = TT { params = params st , pfamily = pfamily st , pidname = pidname st , ptype = ptype st , ptrace = ptrace st , pinterface = pinterface st , psemantics = psemantics st , tree = fmap toSchemaNode (tree st) } toSchemaNode :: GNode GeniVal -> GNode SchemaVal toSchemaNode gn = GN { gup = map promote (gup gn) , gdown = map promote (gdown gn) , gnname = gnname gn , ganchor = ganchor gn , glexeme = glexeme gn , gtype = gtype gn , gaconstr = gaconstr gn , gorigin = gorigin gn } where promote (AvPair a v) = AvPair a (SchemaVal [v])
kowey/GenI
geni-test/NLP/GenI/Test/TreeSchema.hs
gpl-2.0
3,543
0
10
1,204
861
496
365
88
1
-- GenI surface realiser -- Copyright (C) 2005 Carlos Areces and Eric Kow -- -- 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. {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module NLP.GenI.Simple.SimpleGui where import Control.Applicative ( (<$>) ) import Control.Arrow ( (***) ) import Control.Monad.Trans.Error import Data.IORef import Data.List ( sort, partition ) import Data.Maybe ( fromMaybe ) import qualified Data.Map as Map import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.GraphViz as GV import qualified Data.GraphViz.Attributes.Complete as GV import Graphics.UI.WX import NLP.GenI ( ProgState(pa), runGeni , GeniResults(..) , GeniResult(..) , GeniSuccess(..), GeniError(..), isSuccess ) import NLP.GenI.Configuration ( Params(..) ) import NLP.GenI.FeatureStructure ( AvPair(..) ) import NLP.GenI.General ( snd3, buckets ) import NLP.GenI.GeniVal ( mkGConstNone, GeniVal ) import NLP.GenI.Graphviz ( GraphvizShow(..), gvUnlines ) import NLP.GenI.GraphvizShow ( graphvizShowDerivation, GvItem(..) , gvItemSetFlag, GNodeHighlights, Highlights ) import NLP.GenI.GuiHelper ( messageGui, tagViewerGui, maybeSaveAsFile, debuggerPanel , Debugger (..) , DebuggerItemBar, GvIO, newGvRef, GraphvizGuiSt(..), viewTagWidgets , XMGDerivation(getSourceTrees), modifyGvItems ) import NLP.GenI.LexicalSelection ( CustomSem(..) ) import NLP.GenI.Morphology (LemmaPlus(..)) import NLP.GenI.Polarity hiding ( finalSt ) import NLP.GenI.Pretty import NLP.GenI.Simple.SimpleBuilder ( simpleBuilder, SimpleStatus, SimpleItem(..), SimpleGuiItem(..) , unpackResult ,step , theResults, theAgenda, theHoldingPen, theChart, theTrash ) import NLP.GenI.Statistics (Statistics, showFinalStats, emptyStats) import NLP.GenI.TestSuite import NLP.GenI.Tag (dsChild, TagItem(..)) import NLP.GenI.TreeSchema ( GNode(..), GType(..) ) import qualified NLP.GenI.Builder as B import qualified NLP.GenI.BuilderGui as BG -- -------------------------------------------------------------------- -- Interface -- -------------------------------------------------------------------- simpleGui2p, simpleGui1p :: BG.BuilderGui simpleGui2p = simpleGui True simpleGui1p = simpleGui False simpleGui :: Bool -> BG.BuilderGui simpleGui twophase = BG.BuilderGui { BG.resultsPnl = resultsPnl twophase , BG.summaryPnl = summaryGui , BG.debuggerPnl = simpleDebuggerTab twophase } resultsPnl :: Bool -> ProgState -> CustomSem sem -> Window a -> TestCase sem -> IO ([GeniResult], Statistics, Layout, Layout) resultsPnl twophase pst wrangler f tc = do mresults <- runErrorT $ runGeni pst wrangler (simpleBuilder twophase) tc case mresults of Left err -> do (resultsL, _, _) <- realisationsGui pst f [] summaryL <- messageGui f err return ([], emptyStats, summaryL, resultsL) Right (gresults, finalSt) -> do let sentences = grResults gresults stats = grStatistics gresults (resultsL, _, _) <- realisationsGui pst f $ theResults finalSt summaryL <- summaryGui pst f sentences stats return (sentences, stats, summaryL, resultsL) -- -------------------------------------------------------------------- -- Results -- -------------------------------------------------------------------- -- Derived Trees -- | Browser for derived/derivation trees, except if there are no results, we show a -- message box realisationsGui :: ProgState -> Window a -> [SimpleItem] -> GvIO () (GvItem Bool SimpleItem) realisationsGui _ f [] = do m <- messageGui f "No results found" g <- newGvRef () "" return (m, g, return ()) realisationsGui pst f resultsRaw = do tagViewerGui config f tip "derived" itNlabl where config = pa pst tip = "result" mkItNLabl x = GvItem (siToSentence x) False x itNlabl = map mkItNLabl resultsRaw summaryGui :: ProgState -> Window a -> [GeniResult] -> Statistics -> IO Layout summaryGui _ f results stats = do p <- panel f [] statsTxt <- textCtrl p [ text := showFinalStats stats ] t <- textCtrl p [ text := T.unpack msg ] saveBt <- button p [ text := "Save to file" , on command := maybeSaveAsFile f msg ] return $ fill $ container p $ column 1 [ hfill $ label "Performance data" , hfill $ widget statsTxt , hfill $ label $ "Realisations (" ++ show totalResults ++ " found)" , fill $ widget t , hfloatRight $ widget saveBt ] where (succeses, errors) = partitionGeniResult results taggedResults = concatMap sentences succeses resultBuckets = buckets snd taggedResults sentences gr = map (\r -> (grOrigin gr, r)) (grRealisations gr) prettyBucket (s, xys) = s <+> parens instances where instances = if length ys == 1 then ys_str else pretty (length ys) <+> "instances:" <+> ys_str ys = map fst xys ys_str = T.intercalate ", " . map pretty . sort $ ys msg = T.unlines $ concatMap fromError errors ++ (if null succeses then [ "(none)" ] else map prettyBucket resultBuckets) totalResults = length taggedResults fromError (GeniError e) = e partitionGeniResult :: [GeniResult] -> ([GeniSuccess],[GeniError]) partitionGeniResult results = (map unSucc *** map unErr) $ partition isSuccess results where unSucc (GSuccess x) = x unSucc _ = error "NLP.GenI.Simple.SimpleGui unSucc" unErr (GError x) = x unErr _ = error "NLP.GenI.Simple.SimpleGui unErr" -- -------------------------------------------------------------------- -- Debugger -- -------------------------------------------------------------------- simpleDebuggerTab :: Bool -> ProgState -> Window a -> B.Input -> String -> ([GeniResult] -> Statistics -> IO ()) -> IO Layout simpleDebuggerTab twophase pst f input name job = do debuggerPanel dbg pst f input where dbg :: Debugger SimpleStatus Bool SimpleItem dbg = Debugger { dBuilder = simpleBuilder twophase , dToGv = stToGraphviz , dControlPnl = simpleItemBar (pa pst) , dNext = job , dCacheDir = name } stToGraphviz :: SimpleStatus -> [GvItem Bool SimpleItem] stToGraphviz st = concat [ agenda, auxAgenda, chart, trash, results ] where agenda = section "AGENDA" $ theAgenda st auxAgenda = section "HOLDING" $ theHoldingPen st trash = section "TRASH" $ theTrash st chart = section "CHART" $ theChart st results = section "RESULTS" $ theResults st -- section n i = hd : map tlFn i where hd = GvHeader ("___" <> n <> "___") tlFn x = GvItem (siToSentence x <+> prettyPaths x) False x prettyPaths = parens . prettyPolPaths . siPolpaths simpleItemBar :: Params -> DebuggerItemBar SimpleStatus Bool SimpleItem simpleItemBar config f gvRef updaterFn = do ib <- panel f [] phaseTxt <- staticText ib [ text := "" ] detailsChk <- checkBox ib [ text := "Show features" , checked := False ] viewTagLay <- viewTagWidgets ib gvRef config -- handlers let onDetailsChk = do isDetailed <- get detailsChk checked modifyGvItems gvRef (gvItemSetFlag isDetailed) updaterFn set detailsChk [ on command := onDetailsChk ] -- let lay = hfloatCentre . container ib . row 5 $ [ hspace 5 , widget phaseTxt , hglue , widget detailsChk , hglue , viewTagLay , hspace 5 ] let onUpdate = do status <- gvcore `fmap` readIORef gvRef set phaseTxt [ text := show (step status) ] return (lay, onUpdate) -- -------------------------------------------------------------------- -- Miscellaneous -- ------------------------------------------------------------------- -- to have the basic GraphvizShow functionality newtype SimpleItemWrapper = SimpleItemWrapper { fromSimpleItemWrapper :: SimpleItem } instance TagItem SimpleItemWrapper where tgIdName = siIdname . siGuiStuff . fromSimpleItemWrapper tgIdNum = siId . fromSimpleItemWrapper tgSemantics = siFullSem . siGuiStuff . fromSimpleItemWrapper tgTree si = lookupOrBug <$> siDerived (fromSimpleItemWrapper si) where lookupOrBug k = fromMaybe (buggyNode k) $ Map.lookup k nodeMap nodeMap = fromListUsingKey gnname (siNodes (fromSimpleItemWrapper si)) buggyNode k = GN { gup = [ AvPair "cat" (mkGConstNone $ "ERROR looking up" <+> k) ] , gdown = [] , gnname = "ERROR" , glexeme = [] , gtype = Other , ganchor = False , gaconstr = False , gorigin = "ERROR" } fromListUsingKey :: Ord k => (a -> k) -> [a] -> Map.Map k a fromListUsingKey f xs = Map.fromList [ (f x, x) | x <- xs ] instance XMGDerivation SimpleItem where -- Note: this is XMG-related stuff getSourceTrees it = map dsChild (siDerivation it) instance GraphvizShow (GvItem Bool SimpleItem) where graphvizLabel (GvHeader _) = "" graphvizLabel g@(GvItem _ _ c) = gvUnlines $ graphvizLabel (highlightSimpleItem g) : map TL.pack (siDiagnostic (siGuiStuff c)) graphvizParams = graphvizParams . highlightSimpleItem graphvizShowAsSubgraph _ (GvHeader _) = [] graphvizShowAsSubgraph p g@(GvItem _ _ it) = graphvizShowAsSubgraph (p `TL.append` "TagElem") (highlightSimpleItem g) ++ graphvizShowDerivation (siDerivation it) highlightSimpleItem :: GvItem Bool SimpleItem -> GvItem GNodeHighlights SimpleItemWrapper highlightSimpleItem (GvHeader h) = GvHeader h highlightSimpleItem (GvItem l f it) = GvItem l (f, highlights) (SimpleItemWrapper it) where highlights :: Highlights (GNode GeniVal) highlights n = if gnname n `elem` siHighlight (siGuiStuff it) then Just (GV.X11Color GV.Red) else Nothing siToSentence :: SimpleItem -> T.Text siToSentence si = case unpackResult si of [] -> siIdname . siGuiStuff $ si (h:_) -> T.unwords ((idstr <> ".") : map lpLemma (snd3 h)) where idstr = pretty (siId si)
kowey/GenI
geni-gui/src/NLP/GenI/Simple/SimpleGui.hs
gpl-2.0
11,525
0
17
3,063
2,962
1,598
1,364
225
3
-- #hide -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.IOState -- Copyright : (c) Sven Panne 2002-2009 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : sven.panne@aedion.de -- Stability : stable -- Portability : portable -- -- This is a purely internal module for an IO monad with a pointer as an -- additional state, basically a /StateT (Ptr s) IO a/. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.IOState ( IOState(..), getIOState, peekIOState, evalIOState, nTimes ) where import Foreign.Ptr ( Ptr, plusPtr ) import Foreign.Storable ( Storable(sizeOf,peek) ) -------------------------------------------------------------------------------- newtype IOState s a = IOState { runIOState :: Ptr s -> IO (a, Ptr s) } instance Functor (IOState s) where fmap f m = IOState $ \s -> do (x, s') <- runIOState m s ; return (f x, s') instance Monad (IOState s) where return a = IOState $ \s -> return (a, s) m >>= k = IOState $ \s -> do (a, s') <- runIOState m s ; runIOState (k a) s' fail str = IOState $ \_ -> fail str getIOState :: IOState s (Ptr s) getIOState = IOState $ \s -> return (s, s) putIOState :: Ptr s -> IOState s () putIOState s = IOState $ \_ -> return ((), s) peekIOState :: Storable a => IOState a a peekIOState = do ptr <- getIOState x <- liftIOState $ peek ptr putIOState (ptr `plusPtr` sizeOf x) return x liftIOState :: IO a -> IOState s a liftIOState m = IOState $ \s -> do a <- m ; return (a, s) evalIOState :: IOState s a -> Ptr s -> IO a evalIOState m s = do (a, _) <- runIOState m s ; return a nTimes :: Integral a => a -> IOState b c -> IOState b [c] nTimes n = sequence . replicate (fromIntegral n)
ducis/haAni
hs/common/Graphics/Rendering/OpenGL/GL/IOState.hs
gpl-2.0
1,866
0
12
365
609
324
285
27
1
{-| Module : Devel.Paths Description : For filepath related matters. Copyright : (c) License : GPL-3 Maintainer : njagi@urbanslug.com Stability : experimental Portability : POSIX Uses the GHC package to parse .hi files. Will hopefully be moved upstream to ide-backend. -} {-# LANGUAGE OverloadedStrings #-} module Devel.Paths ( getFilesToWatch , getCabalFile ) where -- local imports import Devel.Modules (getCompiledFiles) import IdeSession import System.FilePath.Glob import Data.List ((\\)) import System.FilePath ((</>)) import System.Directory (getCurrentDirectory, doesDirectoryExist, getDirectoryContents) import Control.Monad (forM) import Control.Concurrent (forkIO) import System.FilePath.Posix (replaceExtension, dropExtension, takeExtensions) import Control.Monad.IO.Class (liftIO) import System.FilePath (pathSeparator) import System.Directory (removeFile) import qualified Data.ByteString.Char8 as C8 getFilesToWatch :: IdeSession -> IO [FilePath] getFilesToWatch session = do dir <- getCurrentDirectory srcPaths <- getPathsForCompiledFiles session let replaceWithHiDump :: FilePath -> FilePath replaceWithHiDump srcFile = replaceExtension srcFile ".dump-hi" withHiDumpExt = map replaceWithHiDump srcPaths thDeps' <- mapM parseHi withHiDumpExt -- Removing quotes. mixedThDeps <- return $ map (takeWhile (/='\"') . dropWhile (=='\"') . dropWhile (/='\"')) $ concat thDeps' -- make rel paths absolute and leave the absolute ones intact -- mixedThDeps meaning there are both absolute and relative paths here. let makePathsAbsolute :: FilePath -> FilePath makePathsAbsolute [] = dir ++ [pathSeparator] makePathsAbsolute fp@(x:_) | x == pathSeparator = fp | otherwise = dir ++ [pathSeparator] ++ fp thDeps = map makePathsAbsolute mixedThDeps -- Add the cabal file path to paths to watch for. cabalFile <- getCabalFile -- Clean up after GHC _ <- forkIO $ delitter return $ cabalFile : srcPaths ++ thDeps getCabalFile :: IO FilePath getCabalFile = do list <- glob "*cabal" case list of [] -> fail "No cabal file." (cabalFile:_) -> return cabalFile parseHi :: FilePath -> IO [FilePath] parseHi path = do dumpHI <- liftIO $ fmap C8.lines (C8.readFile path) let thDeps' = -- The dependent file path is surrounded by quotes but is not escaped. -- It can be an absolute or relative path. filter ("addDependentFile \"" `C8.isPrefixOf`) dumpHI return $ map C8.unpack thDeps' -- | Match the possible compiled files agaist the actual source files. -- Gives you the actual source files. getPathsForCompiledFiles :: IdeSession -> IO [FilePath] getPathsForCompiledFiles session = do compiledNoExt <- getCompiledFiles session allSourceFiles <- getManagedFiles' -- With extensions return $ matchCompiledFiles compiledNoExt allSourceFiles where matchCompiledFiles :: [FilePath] -> [FilePath] -> [FilePath] matchCompiledFiles _ [] = [] matchCompiledFiles [] _ = [] matchCompiledFiles list@(x:xs) (y:ys) | x == (dropExtension y) = y : matchCompiledFiles xs ys | otherwise = matchCompiledFiles list (ys ++ [y]) -- | These are the source and data files. -- Not related or to be confused with ide-backend's -- getManagedFiles getManagedFiles' :: IO [FilePath] getManagedFiles' = do cwd <- getCurrentDirectory getRecursiveContents cwd -- | Get the files that actually exist in the given dir. -- In this case it's called with the source dirs getRecursiveContents :: FilePath -> IO [FilePath] getRecursiveContents topdir = do names <- getDirectoryContents topdir -- We want to take these files out. let patterns = [ (compile "*.*~") , (compile "*.hi") , (compile "*.dump-hi") , (compile "*.o") , (compile "*.dyn_o") , (compile "*.dyn_hi") , (compile "*.so") , (compile "*.conf") , (compile "*.h") , (compile "*.a") , (compile "*.inplace") , (compile "*.cache") , (compile "*.*.el") ] (x, _) <- globDir patterns topdir let properNames = filter (`notElem` [".", ".."]) names paths <- forM properNames $ \name -> do let path = topdir </> name isDirectory <- doesDirectoryExist path if isDirectory then getRecursiveContents path else return $ [path] \\ (concat x) return (concat paths) -- Clean up after ghc -ddump-hi -ddump-to-file delitter :: IO () delitter = do cwd <- getCurrentDirectory litter <- getLitter cwd mapM_ del litter where getLitter :: FilePath -> IO [FilePath] getLitter topdir = do names <- getDirectoryContents topdir -- We want to leave these files out of the list let patterns = [ (compile "*.*~") , (compile "*.hs") , (compile "*.txt") , (compile "*.o") , (compile "*.img") , (compile "*.ico") , (compile "*.so") , (compile "*.conf") , (compile "*.h") , (compile "*.a") , (compile "*.lhs") , (compile "*.inplace") , (compile "*.cache") , (compile "*.*.el") ] (x, _) <- globDir patterns topdir let properNames = filter (`notElem` [".", ".."]) names paths <- forM properNames $ \name -> do let path = topdir </> name isDirectory <- doesDirectoryExist path if isDirectory then getRecursiveContents path else return $ [path] \\ (concat x) return (concat paths) del :: FilePath -> IO () del fp = do case ((takeExtensions fp) == ".dump-hi" ) || ((takeExtensions fp) == ".dyn_o" ) || ((takeExtensions fp) == ".o" ) || ((takeExtensions fp) == ".dyn_hi" ) || ((takeExtensions fp) == ".hi" ) of True -> removeFile fp False -> return ()
bitemyapp/wai-devel
src/Devel/Paths.hs
gpl-3.0
6,347
0
17
1,881
1,542
806
736
126
3
{-# LANGUAGE OverloadedStrings #-} {-| Module : Network.Gopher Stability : experimental Portability : POSIX = Overview This is the main module of the spacecookie library. It allows to write gopher applications by taking care of handling gopher requests while leaving the application logic to a user-supplied function. For a small tutorial an example of a trivial pure gopher application: @ {-# LANGUAGE OverloadedStrings #-} import "Network.Gopher" import "Network.Gopher.Util" cfg :: 'GopherConfig' cfg = 'defaultConfig' { cServerName = "localhost" , cServerPort = 7000 } handler :: 'GopherRequest' -> 'GopherResponse' handler request = case 'requestSelector' request of "hello" -> 'FileResponse' "Hello, stranger!" "" -> rootMenu "/" -> rootMenu _ -> 'ErrorResponse' "Not found" where rootMenu = 'MenuResponse' [ 'Item' 'File' "greeting" "hello" Nothing Nothing ] main :: IO () main = 'runGopherPure' cfg handler @ There are three possibilities for a 'GopherResponse': * 'FileResponse': file type agnostic file response, takes a 'ByteString' to support both text and binary files. * 'MenuResponse': a gopher menu (“directory listing”) consisting of a list of 'GopherMenuItem's * 'ErrorResponse': gopher way to show an error (e. g. if a file is not found). An 'ErrorResponse' results in a menu response with a single entry. If you use 'runGopher', it is the same story like in the example above, but you can do 'IO' effects. To see a more elaborate example, have a look at the server code in this package. -} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Network.Gopher ( -- * Main API -- $runGopherVariants runGopher , runGopherPure , runGopherManual , GopherConfig (..) , defaultConfig -- ** Requests , GopherRequest (..) -- ** Responses , GopherResponse (..) , GopherMenuItem (..) , GopherFileType (..) -- * Helper Functions -- ** Logging -- $loggingDoc , GopherLogHandler , module Network.Gopher.Log -- ** Networking , setupGopherSocket -- ** Gophermaps -- $gophermapDoc , gophermapToDirectoryResponse , Gophermap , GophermapEntry (..) ) where import Prelude hiding (log) import Network.Gopher.Log import Network.Gopher.Types import Network.Gopher.Util import Network.Gopher.Util.Gophermap import Network.Gopher.Util.Socket import Control.Concurrent (forkIO, ThreadId (), threadDelay) import Control.Concurrent.Async (race) import Control.Exception (bracket, catch, throw, SomeException (), Exception ()) import Control.Monad (forever, when, void) import Control.Monad.IO.Class (liftIO, MonadIO (..)) import Control.Monad.Reader (ask, runReaderT, MonadReader (..), ReaderT (..)) import Data.Bifunctor (second) import Data.ByteString (ByteString ()) import qualified Data.ByteString as B import qualified Data.ByteString.Builder as BB import Data.Maybe (fromMaybe) import Data.Word (Word16 ()) import System.Socket hiding (Error (..)) import System.Socket.Family.Inet6 import System.Socket.Type.Stream (Stream, sendAllBuilder) import System.Socket.Protocol.TCP -- | Necessary information to handle gopher requests data GopherConfig = GopherConfig { cServerName :: ByteString -- ^ Public name of the server (either ip address or dns name). -- Gopher clients will use this name to fetch any resources -- listed in gopher menus located on the same server. , cListenAddr :: Maybe ByteString -- ^ Address or hostname to listen on (resolved by @getaddrinfo@). -- If 'Nothing', listen on all addresses. , cServerPort :: Integer -- ^ Port to listen on , cLogHandler :: Maybe GopherLogHandler -- ^ 'IO' action spacecookie will call to output its log messages. -- If it is 'Nothing', logging is disabled. See [the logging section](#logging) -- for an overview on how to implement a log handler. } -- | Default 'GopherConfig' describing a server on @localhost:70@ with -- no registered log handler. defaultConfig :: GopherConfig defaultConfig = GopherConfig "localhost" Nothing 70 Nothing -- | Type for an user defined 'IO' action which handles logging a -- given 'GopherLogStr' of a given 'GopherLogLevel'. It may -- process the string and format in any way desired, but it must -- be thread safe and should not block (too long) since it -- is called syncronously. type GopherLogHandler = GopherLogLevel -> GopherLogStr -> IO () -- $loggingDoc -- #logging# -- Logging may be enabled by providing 'GopherConfig' with an optional -- 'GopherLogHandler' which implements processing, formatting and -- outputting of log messages. While this requires extra work for the -- library user it also allows the maximum freedom in used logging -- mechanisms. -- -- A trivial log handler could look like this: -- -- @ -- logHandler :: 'GopherLogHandler' -- logHandler level str = do -- putStr $ show level ++ \": \" -- putStrLn $ 'fromGopherLogStr' str -- @ -- -- If you only want to log errors you can use the 'Ord' instance of -- 'GopherLogLevel': -- -- @ -- logHandler' :: 'GopherLogHandler' -- logHandler' level str = when (level <= 'GopherLogLevelError') -- $ logHandler level str -- @ -- -- The library marks parts of 'GopherLogStr' which contain user -- related data like IP addresses as sensitive using 'makeSensitive'. -- If you don't want to e. g. write personal information to disk in -- plain text, you can use 'hideSensitive' to transparently remove -- that information. Here's a quick example in GHCi: -- -- >>> hideSensitive $ "Look at my " <> makeSensitive "secret" -- "Look at my [redacted]" -- $gophermapDoc -- Helper functions for converting 'Gophermap's into 'MenuResponse's. -- For parsing gophermap files, refer to "Network.Gopher.Util.Gophermap". data GopherRequest = GopherRequest { requestRawSelector :: ByteString -- ^ raw selector sent by the client (without the terminating @\\r\\n@ , requestSelector :: ByteString -- ^ only the request selector minus the search expression if present , requestSearchString :: Maybe ByteString -- ^ raw search string if the clients sends a search transaction , requestClientAddr :: (Word16, Word16, Word16, Word16, Word16, Word16, Word16, Word16) -- ^ IPv6 address of the client which sent the request. IPv4 addresses are -- <https://en.wikipedia.org/wiki/IPv6#IPv4-mapped_IPv6_addresses mapped> -- to an IPv6 address. } deriving (Show, Eq) data Env = Env { serverConfig :: GopherConfig , serverFun :: GopherRequest -> IO GopherResponse } newtype GopherM a = GopherM { runGopherM :: ReaderT Env IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadReader Env) gopherM :: Env -> GopherM a -> IO a gopherM env action = (runReaderT . runGopherM) action env -- call given log handler if it is Just logIO :: Maybe GopherLogHandler -> GopherLogLevel -> GopherLogStr -> IO () logIO h l = fromMaybe (const (pure ())) $ ($ l) <$> h logInfo :: GopherLogStr -> GopherM () logInfo = log GopherLogLevelInfo logError :: GopherLogStr -> GopherM () logError = log GopherLogLevelError log :: GopherLogLevel -> GopherLogStr -> GopherM () log l m = do h <- cLogHandler . serverConfig <$> ask liftIO $ logIO h l m logException :: Exception e => Maybe GopherLogHandler -> GopherLogStr -> e -> IO () logException logger msg e = logIO logger GopherLogLevelError $ msg <> toGopherLogStr (show e) -- | Read request from a client socket. -- The complexity of this function is caused by the -- following design features: -- -- * Requests may be terminated by either "\n\r" or "\n" -- * After the terminating newline no extra data is accepted -- * Give up on waiting on a request from the client after -- a certain amount of time (request timeout) -- * Don't accept selectors bigger than a certain size to -- avoid DoS attacks filling up our memory. receiveRequest :: Socket Inet6 Stream TCP -> IO (Either ByteString ByteString) receiveRequest sock = fmap (either id id) $ race (threadDelay reqTimeout >> pure (Left "Request Timeout")) $ do req <- loop mempty 0 pure $ case B.break newline req of (r, "\r\n") -> Right r (r, "\n") -> Right r (_, "") -> Left "Request too big or unterminated" _ -> Left "Unexpected data after newline" where newline = (||) <$> (== asciiOrd '\n') <*> (== asciiOrd '\r') reqTimeout = 10000000 -- 10s maxSize = 1024 * 1024 loop bs size = do part <- receive sock maxSize msgNoSignal let newSize = size + B.length part if newSize >= maxSize || part == mempty || B.elem (asciiOrd '\n') part then pure $ bs `mappend` part else loop (bs `mappend` part) newSize -- | Auxiliary function that sets up the listening socket for -- 'runGopherManual' correctly and starts to listen. -- -- May throw a 'SocketException' if an error occurs while -- setting up the socket. setupGopherSocket :: GopherConfig -> IO (Socket Inet6 Stream TCP) setupGopherSocket cfg = do sock <- (socket :: IO (Socket Inet6 Stream TCP)) setSocketOption sock (ReuseAddress True) setSocketOption sock (V6Only False) addr <- case cListenAddr cfg of Nothing -> pure $ SocketAddressInet6 inet6Any (fromInteger (cServerPort cfg)) 0 0 Just a -> do let port = uEncode . show $ cServerPort cfg let flags = aiV4Mapped <> aiNumericService addrs <- (getAddressInfo (Just a) (Just port) flags :: IO [AddressInfo Inet6 Stream TCP]) -- should be done by getAddressInfo already when (null addrs) $ throw eaiNoName pure . socketAddress $ head addrs bind sock addr listen sock 5 pure sock -- $runGopherVariants -- The @runGopher@ function variants will generally not throw exceptions, -- but handle them somehow (usually by logging that a non-fatal exception -- occurred) except if the exception occurrs in the setup step of -- 'runGopherManual'. -- -- You'll have to handle those exceptions yourself. To see which exceptions -- can be thrown by 'runGopher' and 'runGopherPure', read the documentation -- of 'setupGopherSocket'. -- | Run a gopher application that may cause effects in 'IO'. -- The application function is given the 'GopherRequest' -- sent by the client and must produce a GopherResponse. runGopher :: GopherConfig -> (GopherRequest -> IO GopherResponse) -> IO () runGopher cfg f = runGopherManual (setupGopherSocket cfg) (pure ()) close cfg f -- | Same as 'runGopher', but allows you to setup the 'Socket' manually -- and calls an user provided action soon as the server is ready -- to accept requests. When the server terminates, it calls the given -- clean up action which must close the socket and may perform other -- shutdown tasks (like notifying a supervisor it is stopping). -- -- Spacecookie assumes the 'Socket' is properly set up to listen on the -- port and host specified in the 'GopherConfig' (i. e. 'bind' and -- 'listen' have been called). This can be achieved using 'setupGopherSocket'. -- Especially note that spacecookie does /not/ check if the listening -- address and port of the given socket match 'cListenAddr' and -- 'cServerPort'. -- -- This is intended for supporting systemd socket activation and storage, -- but may also be used to support other use cases where more control is -- necessary. Always use 'runGopher' if possible, as it offers less ways -- of messing things up. runGopherManual :: IO (Socket Inet6 Stream TCP) -- ^ action to set up listening socket -> IO () -- ^ ready action called after startup -> (Socket Inet6 Stream TCP -> IO ()) -- ^ socket clean up action -> GopherConfig -- ^ server config -> (GopherRequest -> IO GopherResponse) -- ^ request handler -> IO () runGopherManual sockAction ready term cfg f = bracket sockAction term (\sock -> do gopherM (Env cfg f) $ do addr <- liftIO $ getAddress sock logInfo $ "Listening on " <> toGopherLogStr addr liftIO $ ready forever $ acceptAndHandle sock) forkGopherM :: GopherM () -> IO () -> GopherM ThreadId forkGopherM action cleanup = do env <- ask liftIO $ forkIO $ do gopherM env action `catch` (logException (cLogHandler $ serverConfig env) "Thread failed with exception: " :: SomeException -> IO ()) cleanup -- | Split an selector in the actual search selector and -- an optional search expression as documented in the -- RFC1436 appendix. splitSelector :: ByteString -> (ByteString, Maybe ByteString) splitSelector = second checkSearch . B.breakSubstring "\t" where checkSearch search = if B.length search > 1 then Just $ B.tail search else Nothing handleIncoming :: Socket Inet6 Stream TCP -> SocketAddress Inet6 -> GopherM () handleIncoming clientSock addr@(SocketAddressInet6 cIpv6 _ _ _) = do request <- liftIO $ receiveRequest clientSock logger <- cLogHandler . serverConfig <$> ask intermediateResponse <- case request of Left e -> pure $ ErrorResponse e Right rawSelector -> do let (onlySel, search) = splitSelector rawSelector req = GopherRequest { requestRawSelector = rawSelector , requestSelector = onlySel , requestSearchString = search , requestClientAddr = inet6AddressToTuple cIpv6 } logInfo $ "New Request \"" <> toGopherLogStr rawSelector <> "\" from " <> makeSensitive (toGopherLogStr addr) fun <- serverFun <$> ask liftIO $ fun req `catch` \e -> do let msg = "Unhandled exception in handler: " <> toGopherLogStr (show (e :: SomeException)) logIO logger GopherLogLevelError msg pure $ ErrorResponse "Unknown error occurred" rawResponse <- response intermediateResponse liftIO $ void (sendAllBuilder clientSock 10240 rawResponse msgNoSignal) `catch` \e -> logException logger "Exception while sending response to client: " (e :: SocketException) acceptAndHandle :: Socket Inet6 Stream TCP -> GopherM () acceptAndHandle sock = do connection <- liftIO $ fmap Right (accept sock) `catch` (pure . Left) case connection of Left e -> logError $ "Failure while accepting connection " <> toGopherLogStr (show (e :: SocketException)) Right (clientSock, addr) -> do logInfo $ "New connection from " <> makeSensitive (toGopherLogStr addr) void $ forkGopherM (handleIncoming clientSock addr) (gracefulClose clientSock) -- | Like 'runGopher', but may not cause effects in 'IO' (or anywhere else). runGopherPure :: GopherConfig -> (GopherRequest -> GopherResponse) -> IO () runGopherPure cfg f = runGopher cfg (fmap pure f) response :: GopherResponse -> GopherM BB.Builder response (FileResponse str) = pure $ BB.byteString str response (ErrorResponse reason) = response . MenuResponse $ [ Item Error reason "Err" Nothing Nothing ] response (MenuResponse items) = let appendItem cfg acc (Item fileType title path host port) = acc <> BB.word8 (fileTypeToChar fileType) <> mconcat [ BB.byteString title , BB.charUtf8 '\t' , BB.byteString path , BB.charUtf8 '\t' , BB.byteString $ fromMaybe (cServerName cfg) host , BB.charUtf8 '\t' , BB.intDec . fromIntegral $ fromMaybe (cServerPort cfg) port , BB.byteString "\r\n" ] in do cfg <- serverConfig <$> ask pure $ foldl (appendItem cfg) mempty items
sternenseemann/spacecookie
src/Network/Gopher.hs
gpl-3.0
15,692
0
24
3,439
2,775
1,496
1,279
202
5
{-# LANGUAGE DeriveDataTypeable #-} module InnerEar.Types.Request where import Text.JSON import Text.JSON.Generic import Text.JSON.String (runGetJSON) import InnerEar.Types.Utility import InnerEar.Types.Handle import InnerEar.Types.Password import InnerEar.Types.Data import InnerEar.Types.ExerciseId data Request = CreateUser Handle Password | Authenticate Handle Password | Deauthenticate | PostPoint Point | GetUserList | GetAllRecords Handle | GetAllExerciseEvents Handle ExerciseId deriving (Eq,Show,Data,Typeable) instance JSON Request where showJSON = toJSON readJSON = fromJSON -- | decodeRequest probably shouldn't be necessary but we need to do this -- in order to avoid "unknown constructor" errors when decoding JSON requests -- for no obvious reason. A small price to pay for auto-derived JSON instances though... -- *** note: maybe it is no longer necessary with JSON instance above though?? decodeRequest :: String -> Result Request decodeRequest = either Error fromJSON . runGetJSON readJSValue
d0kt0r0/InnerEar
src/InnerEar/Types/Request.hs
gpl-3.0
1,037
0
6
154
171
102
69
24
1
module Testimonial (testimonial) where import Test.QuickCheck.Gen -- https://blog.hubspot.com/marketing/testimonial-page-examples#sm.0000126iyiq2p6dxtvgw5la1hbhvc testimonial = oneof [ action <++> space <++> term <++> space <++> result , temporal <++> pure ", I was " <++> action <++> space <++> term , pure "I was " <++> action <++> space <++> term <++> pure ", and it " <++> result , term <++> space <++> prescription , term <++> pure " are " <++> attribute ] action = elements [ "working with" , "implementing" , "adopting" , "studying" , "getting to know" , "learning about" , "concentrating on" , "catching a glimpse of" , "appreciating" ] result = oneof [ pure "transformed both my professional, as well as my private life" , pure "made my job worthwhile" , pure "started the transition we were looking for" , pure "had a " <++> adj <++> pure " impact on our business" , pure "impressed our " <++> whom <++> pure " like no other technology" , pure "raised our revenues by over " <++> number <++> pure "0 percent" , pure "helped us reach all our business goals" , pure "changed my thinking" , pure "was " <++> attribute ] where whom = elements [ "business partners" , "shareholders" , "customers" ] adj = elements [ "enormous" , "huge" , "tremendeous" , "impressive" , "unprecedented" ] prescription = oneof [ pure "should be part of any C.S. curriculum" , pure "should be taught in elementary school" , pure "are an opportunity everyone should take" , pure "give you so many more options" , pure "can no longer be ignored" , pure "are not going to stop us" , pure "is just another definition of success" , pure "are " <++> attribute ] attribute = oneof [ pure "an experience I don't want to miss" , pure "intimidating at first, but definitely worth the ride" , pure "incredible" , pure "a game changer" , pure "quite something" , pure "something anyone can learn" , pure "a true privilege" , pure "a boost for my career" , pure "the next big thing" , pure "my greatest accomplishment" , pure "exactly what I was looking for" , adverb <++> elements [ " magnificient" , " inspiring" , " awesome" , " amazing" , " empowering" , " wonderful" , " easy to master" ] ] where adverb = elements [ "truly" , "genuinely" , "overwhelmingly" , "really" , "incredibly" , "just" ] temporal = oneof [ pure "for the last " <++> number <++> space <++> timeUnit , pure "every " <++> number <++> space <++> timeUnit , pure "in a few " <++> timeUnit , pure "every day" , pure "every morning" , pure "on mondays" , pure "on my coffee breaks" , pure "at lunchtime" ] timeUnit = elements [ "decades" , "years" , "months" , "weeks" , "days" , "hours" , "minutes" , "seconds" , "milliseconds" , "fractions of a second" ] space = pure " " number = elements $ map show [2..10] plural = (==) 's' . last adverb = elements [ "extremely" , "continuously" , "completely" , "eventually" , "seamlessly" , "immediately" , "transparently" , "independently" , "reliably" , "modularly" , "next-generation" , "truly" ] adjective = elements [ "reactive" , "resiliant" , "intuitive" , "scalable" , "effective" , "stateless" , "dependency-aware" , "non-blocking" , "redundant" , "correlated" , "agile" , "improved" , "integrated" , "technical" , "lightweight" , "certified" , "external" , "feature-driven" , "highly available" , "fine granular" , "actor-based" , "configurable" , "parallel" , "persistent" , "radical" ] noun = noun1 <++> space <++> noun2 where noun1 = elements [ "meta" , "hypervisor" , "activator" , "client" , "process" , "consumer" , "dynamic" , "enterprise" , "application" , "quality" , "cloud" , "full-stack" , "core" , "business" , "virtual" , "marketing" , "key" ] noun2 = elements [ "infrastructures" , "networks" , "architectures" , "clusters" , "engines" , "frameworks" , "systems" , "platforms" , "metrics" , "resources" , "interfaces" , "distributions" , "toolchains" , "redesigns" , "milestones" ] term = adverb <++> space <++> adjective <++> space <++> noun (<++>) :: Monoid a => Gen a -> Gen a -> Gen a (<++>) a b = mappend <$> a <*> b
941design/bs-gen
src/Testimonial.hs
gpl-3.0
7,297
0
12
3,965
977
548
429
159
1
{-| Module : Util.Blaze Description : Contains methods for setting various HTML attributes. -} module Util.Blaze (toStylesheet, toScript, toLink, mdToHTML) where import qualified Data.Text as T import Data.Text.Lazy (Text) import Text.Blaze ((!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Text.Markdown (def, markdown) -- |Sets the html attributes to the href of the style sheet. toStylesheet :: T.Text -> H.Html toStylesheet href = H.link ! A.rel "stylesheet" ! A.type_ "text/css" ! A.href (H.textValue href) -- |Sets the script attributes. toScript :: T.Text -> H.Html toScript src = H.script ! A.src (H.textValue src) $ "" -- |Creates a link by setting the href attribute. toLink :: T.Text -> T.Text -> H.Html toLink link content = H.a ! A.href (H.textValue link) $ H.toHtml content -- | mdToHTML takes in the contents of a file written in Mark Down and converts it to -- blaze-HTML. mdToHTML :: Text -> H.Html mdToHTML = markdown def
Courseography/courseography
app/Util/Blaze.hs
gpl-3.0
1,101
0
10
263
267
151
116
22
1
module Main where import System.Random import Control.Monad.State (get, gets, StateT(..), evalStateT, put, MonadState(..), liftIO) data Player = Player { name :: String , awards :: [Maybe String] } data GameData = GameData { totalScore :: Int, try :: Int, players :: [Player] } type GS a = (StateT GameData IO a) getAward 20 = Just "Awesome!!!" getAward 19 = Just "Great!" getAward n | n > 16 = Just "Very well." getAward _ = Nothing turn :: Int -> GS (Maybe String) turn player = do dice <- liftIO $ randomRIO (1, 20) :: IO Int let award = getAward dice putStrLn $ "Award: " ++ show award (GameData score try players) <- get put (GameData score (try + 1) players) return award
graninas/Haskell-Algorithms
Tests/StateTransformerTest2.hs
gpl-3.0
870
0
11
315
295
157
138
23
1
{-# LANGUAGE UnicodeSyntax #-} import Prelude.Unicode import Data.List import Development.Shake import Development.Shake.FilePath import Paths opts = shakeOptions { shakeFiles = shakeTmpDir </> "" } --, shakeVerbosity = Diagnostic } main ∷ IO () main = shakeArgs opts $ do want ["installation-guide"] "installation-guide" ~> (need [binDir, hakyllTmpDir, shakeTmpDir, siteBuilder] >> buildSite) binDir %> mkdir hakyllTmpDir %> mkdir shakeTmpDir %> mkdir siteBuilder %> compileSiteBuilder "clean" ~> deleteOutput compileSiteBuilder ∷ FilePath → Action () compileSiteBuilder _ = cmd "ghc --make" [ buildDir </> "Site.hs" , "-o", siteBuilder , "-outputdir", baseTmpDir ] buildSite ∷ Action () buildSite = cmd siteBuilder ["build"] mkdir ∷ FilePath → Action () mkdir d = cmd "mkdir -p" [d] deleteOutput ∷ Action () deleteOutput = cmd "rm -rf" [binDir, baseTmpDir] --liftIO ∘ mapM_ (flip removeFiles $ ["//*"]) $ [binDir, baseTmpDir]
c0c0n3/archlinux
vm/src/build/Shakefile.hs
gpl-3.0
1,152
0
12
339
265
140
125
28
1
import Data.Complex import qualified Data.List as Dat import Notation.QuantumState -------------------------------------------------------------------------------- -- Infix operators for nice and simple notation -- -------------------------------------------------------------------------------- infixl 5 +| -- Addition of Kets infixl 5 +< -- Addition of Bras infix 6 *| -- Scalar multiplication with Ket infix 6 *< -- Scalar multiplication with Bra infixl 7 >| -- Ket tensor product infixl 7 |< -- Bra tensor product infix 4 |.| -- Inner product -- infix 5 >< -- Outer product data Ket a = KetZero | Ket [a] | Scalar :*| Ket a | Ket a :+| Ket a -------------------------------------------------------------------------------- -- Make our Ket vectors instances of the QuantumState type class -- -- and define appropriate functions on Kets -- -------------------------------------------------------------------------------- instance Eq a => QuantumState (Ket a) where add = (+|) scale = (*|) reduce = reduceKet basis = ketBasis components x = [bracket e x | e <- basis x] compose coeffs v = Dat.foldl1' (:+|) [uncurry (:*|) z | z <- zip coeffs v] norm KetZero = 0 norm x = sqrt $ realPart (bracketKet x x) bracket = bracketKet reduceKet :: Eq a => Ket a -> Ket a reduceKet x = compose coeff z where z = ketBasis x coeff = [bracketKet z x | z <- ketBasis x] ketBasis :: Eq a => Ket a -> [Ket a] ketBasis KetZero = [KetZero] ketBasis (Ket k) = [Ket k] ketBasis (_ :*| x) = ketBasis x ketBasis (x :+| y) = Dat.nub (ketBasis x ++ ketBasis y) bracketKet :: Eq a => Ket a -> Ket a -> Scalar bracketKet KetZero _ = 0 bracketKet _ KetZero = 0 bracketKet (s :*| x) y = conjugate s * bracketKet x y bracketKet x (s :*| y) = s * bracketKet x y bracketKet (x1 :+| x2) y= bracketKet x1 y + bracketKet x2 y bracketKet x (y1 :+| y2)= bracketKet x y1 + bracketKet x y2 bracketKet (Ket a) (Ket b) = d a b d :: Eq a => a -> a -> Scalar d i j | i == j = 1 | otherwise = 0 instance Eq a => Eq (Ket a) where x == y = and [coeff v x == coeff v y | v <- ketBasis x] where coeff = bracketKet (>|) :: Eq a => Ket a -> Ket a -> Ket a KetZero >| _ = KetZero _ >| KetZero = KetZero k >| l = Dat.foldl1' (:+|) [bracketKet (Ket a) k * bracketKet (Ket b) l *| Ket (a ++ b) | Ket a <- ketBasis k, Ket b <- ketBasis l] (+|) ::Eq a => Ket a -> Ket a -> Ket a KetZero +| x = x x +| KetZero = x x +| y | Dat.length xs == Dat.length ys = reduceKet (x :+| y) | otherwise = error "Trying to add two states of different length!" where Ket xs = head $ ketBasis x Ket ys = head $ ketBasis y (*|) :: Eq a =>Scalar -> Ket a -> Ket a _ *| KetZero = KetZero 0 *| _ = KetZero (0 :+ 0) *| _ = KetZero s *| (x :+| y) = s *| x +| s *| y s *| (t :*| x) = (s * t) *| x s *| x = s :*| x -------------------------------------------------------------------------------- -- Define Bra vectors as the dual vectors of Kets -- -------------------------------------------------------------------------------- data Bra a = Bra { braBracket :: Ket a -> Scalar, toKet :: Ket a } -------------------------------------------------------------------------------- -- Convert Ket vectors into Bra vectors -- -------------------------------------------------------------------------------- toBra :: (Eq a) => Ket a -> Bra a toBra k = Bra (bracketKet k) k instance Eq a => QuantumState (Bra a) where add = (+<) scale = (*<) reduce = reduceBra basis = braBasis components x = [bracket e x | e <- basis x] compose coeffs v = toBra (Dat.foldl1' (:+|) [uncurry (:*|) z | z <- zip coeffs (map toKet v)]) norm x = norm (toKet x) bracket = bracketBra (|<) :: Eq a => Bra a -> Bra a -> Bra a x |< y = toBra $ toKet x >| toKet y (+<) :: Eq a => Bra a -> Bra a -> Bra a x +< y = toBra $ toKet x +| toKet y (*<) :: Eq a => Scalar -> Bra a -> Bra a s *< x = toBra $ s *| toKet x reduceBra :: Eq a => Bra a -> Bra a reduceBra x = toBra $ reduceKet (toKet x) braBasis :: Eq a => Bra a -> [Bra a] braBasis x = map toBra $ ketBasis (toKet x) bracketBra :: Eq a => Bra a -> Bra a -> Scalar bracketBra x y = braBracket x $ toKet y (|.|) :: Eq a => Bra a -> Ket a -> Scalar x |.| y = braBracket x y creationOp :: (Integral a) => Int -> Ket a -> Ket a creationOp _ KetZero = KetZero creationOp n (s :*| a) = s *| creationOp n a creationOp n (a :+| b) = creationOp n a +| creationOp n b creationOp n (Ket xs) | occ >= 2 = KetZero |otherwise = c *| (Ket $ create' n xs) where create' i (y:ys) | i == 0 = occ : ys | otherwise = y : create' (i - 1) ys c = sqrt $ fromIntegral occ occ = (xs !! n) + 1 annihilationOp :: (Integral a) => Int -> Ket a -> Ket a annihilationOp _ KetZero = KetZero annihilationOp n (s :*| a) = s *| annihilationOp n a annihilationOp n (a :+| b) = annihilationOp n a +| annihilationOp n b annihilationOp n (Ket xs) | occ < 0 = KetZero | otherwise = c *| (Ket $ annihilate' n xs) where occ = (xs !! n) - 1 annihilate' i (y:ys) | i == 0 = occ : ys | otherwise = y : annihilate' (i - 1) ys c = sqrt $ fromIntegral (occ + 1) occupancyOp :: (Integral a) => Int -> Ket a -> Ket a occupancyOp _ KetZero = KetZero occupancyOp n (s :*| a) = s *| occupancyOp n a occupancyOp n (a :+| b) = occupancyOp n a +| occupancyOp n b occupancyOp n k@(Ket xs) | occ < 0 = KetZero | otherwise = fromIntegral occ *| k where occ = xs !! n numberOp :: Integral a => Ket a -> Ket a numberOp KetZero = KetZero numberOp (s :*| k) = s *| numberOp k numberOp (k :+| l) = numberOp k +| numberOp l numberOp k@(Ket xs) = n *| k where n = fromIntegral $ sum xs a :: Integral a => Int -> Ket a -> Ket a a = annihilationOp a' :: Integral a => Int -> Ket a -> Ket a a' = creationOp occ :: Integral a => Int -> Ket a -> Ket a occ = occupancyOp num :: Integral a => Ket a -> Ket a num = numberOp -------------------------------------------------------------------------------- -- Make Ket a an instance of Show, in order to print Ket vectors in a pretty -- -- way. Since Bra vectors are functions in Haskell they cannot be made an -- -- instance of Show and thus cannot be printed -- -------------------------------------------------------------------------------- instance (Show a, Eq a) => Show (Ket a) where showsPrec _ KetZero = showString "Zero-Ket" showsPrec _ (Ket []) = showString "Zero-Ket" showsPrec _ (Ket j) = showString "|" . showString (concatMap show j) . showString ">" showsPrec n (x :*| k) = showScalar n x . showsPrec n k showsPrec n (j :+| k) = showsPrec n j . showSign k . showsPrec n k -------------------------------------------------------------------------------- -- Function to improve the prettyness of the printing. -- -- This function fixes the printing of negative coefficients. -- -------------------------------------------------------------------------------- showSign :: (Show a, Eq a) => Ket a -> String -> String showSign (s@(a :+ b) :*| k) | b == 0, a < 0 = showString "" | otherwise = showString " + " showSign (Ket j) = showString " + " -- showStates :: (Show a) => [a] -> ShowS -- showStates n = concatMap (showsPrec n) main = do let a = Ket [1,1,0] let b = Ket [0,0,1] let c = a :+| b print a
johanjoensson/QuantumHaskell
FockState.hs
agpl-3.0
8,410
0
14
2,779
2,954
1,466
1,488
159
1
{-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving #-} module App where import Web.Scotty.Trans import Network.Wai.Middleware.Static import Network.Wai.Middleware.RequestLogger import Data.Default import Data.String import Data.Text.Lazy (Text, pack) import qualified Data.ByteString.Lazy.Char8 as B import Data.Aeson (encode) import Network.HTTP.Types import Database import Types hiding (text) app :: ScottyT WebM () app = do middleware logStdoutDev middleware $ staticPolicy (noDots >-> addBase "static") get "/" $ do file "./static/html/index.html" get "/todos" $ do todoItems <- webM getTodos json todoItems get "/:todoId" $ do todoId <- param "todoId" todo <- webM $ findTodoById todoId case todo of Nothing -> do status status404 text $ fromString $ "No item found for id " ++ show todoId Just t -> json $ todo post "/todo" $ do requestBody <- body let requestBodyAsString = B.unpack requestBody let (result, w) = addTodoItem requestBodyAsString case result of Success -> do webM w status status200 identifier <- webM $ gets nextId setHeader "Location" (pack (show identifier)) Failure errorMessage -> do status status404 text $ fromString $ show errorMessage
karun012/scotty-todo-sample
src/App.hs
unlicense
1,513
0
19
501
394
190
204
43
3
-- 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. {-# LANGUAGE ForeignFunctionInterface #-} module CDep () where foreign import ccall "plus_42" plus42 :: Int -> Int foreign export ccall plus43 :: Int -> Int plus43 :: Int -> Int plus43 x = 1 + plus42 x
google/cabal2bazel
bzl/tests/dep_on_haskell/CDep.hs
apache-2.0
793
0
6
140
75
48
27
6
1
{-# LANGUAGE Haskell2010 #-} module DeprecatedClass where -- | some class class SomeClass a where -- | documentation for foo foo :: a -> a {-# DEPRECATED SomeClass "SomeClass" #-} {-# DEPRECATED foo "foo" #-} class SomeOtherClass a where bar :: a -> a {-# DEPRECATED SomeOtherClass "SomeOtherClass" #-} {-# DEPRECATED bar "bar" #-}
haskell/haddock
html-test/src/DeprecatedClass.hs
bsd-2-clause
342
0
7
64
47
28
19
10
0
{-# OPTIONS -fglasgow-exts -#include "../include/gui/qtc_hs_QAbstractItemDelegate.h" #-} ----------------------------------------------------------------------------- {-| Module : QAbstractItemDelegate.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:30 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QAbstractItemDelegate ( QqAbstractItemDelegate(..) ,qAbstractItemDelegateElidedText ,qAbstractItemDelegate_delete ,qAbstractItemDelegate_deleteLater ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QuserMethod (QAbstractItemDelegate ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QAbstractItemDelegate_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QAbstractItemDelegate_userMethod" qtc_QAbstractItemDelegate_userMethod :: Ptr (TQAbstractItemDelegate a) -> CInt -> IO () instance QuserMethod (QAbstractItemDelegateSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QAbstractItemDelegate_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QAbstractItemDelegate ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QAbstractItemDelegate_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QAbstractItemDelegate_userMethodVariant" qtc_QAbstractItemDelegate_userMethodVariant :: Ptr (TQAbstractItemDelegate a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QAbstractItemDelegateSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QAbstractItemDelegate_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqAbstractItemDelegate x1 where qAbstractItemDelegate :: x1 -> IO (QAbstractItemDelegate ()) instance QqAbstractItemDelegate (()) where qAbstractItemDelegate () = withQAbstractItemDelegateResult $ qtc_QAbstractItemDelegate foreign import ccall "qtc_QAbstractItemDelegate" qtc_QAbstractItemDelegate :: IO (Ptr (TQAbstractItemDelegate ())) instance QqAbstractItemDelegate ((QObject t1)) where qAbstractItemDelegate (x1) = withQAbstractItemDelegateResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractItemDelegate1 cobj_x1 foreign import ccall "qtc_QAbstractItemDelegate1" qtc_QAbstractItemDelegate1 :: Ptr (TQObject t1) -> IO (Ptr (TQAbstractItemDelegate ())) instance QcreateEditor (QAbstractItemDelegate ()) ((QWidget t1, QStyleOptionViewItem t2, QModelIndex t3)) where createEditor x0 (x1, x2, x3) = withQWidgetResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractItemDelegate_createEditor_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QAbstractItemDelegate_createEditor_h" qtc_QAbstractItemDelegate_createEditor_h :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQWidget t1) -> Ptr (TQStyleOptionViewItem t2) -> Ptr (TQModelIndex t3) -> IO (Ptr (TQWidget ())) instance QcreateEditor (QAbstractItemDelegateSc a) ((QWidget t1, QStyleOptionViewItem t2, QModelIndex t3)) where createEditor x0 (x1, x2, x3) = withQWidgetResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractItemDelegate_createEditor_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 instance QeditorEvent (QAbstractItemDelegate ()) ((QEvent t1, QAbstractItemModel t2, QStyleOptionViewItem t3, QModelIndex t4)) where editorEvent x0 (x1, x2, x3, x4) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> withObjectPtr x4 $ \cobj_x4 -> qtc_QAbstractItemDelegate_editorEvent_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 cobj_x4 foreign import ccall "qtc_QAbstractItemDelegate_editorEvent_h" qtc_QAbstractItemDelegate_editorEvent_h :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQEvent t1) -> Ptr (TQAbstractItemModel t2) -> Ptr (TQStyleOptionViewItem t3) -> Ptr (TQModelIndex t4) -> IO CBool instance QeditorEvent (QAbstractItemDelegateSc a) ((QEvent t1, QAbstractItemModel t2, QStyleOptionViewItem t3, QModelIndex t4)) where editorEvent x0 (x1, x2, x3, x4) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> withObjectPtr x4 $ \cobj_x4 -> qtc_QAbstractItemDelegate_editorEvent_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 cobj_x4 qAbstractItemDelegateElidedText :: ((QFontMetrics t1, Int, TextElideMode, String)) -> IO (String) qAbstractItemDelegateElidedText (x1, x2, x3, x4) = withStringResult $ withObjectPtr x1 $ \cobj_x1 -> withCWString x4 $ \cstr_x4 -> qtc_QAbstractItemDelegate_elidedText cobj_x1 (toCInt x2) (toCLong $ qEnum_toInt x3) cstr_x4 foreign import ccall "qtc_QAbstractItemDelegate_elidedText" qtc_QAbstractItemDelegate_elidedText :: Ptr (TQFontMetrics t1) -> CInt -> CLong -> CWString -> IO (Ptr (TQString ())) instance QhelpEvent (QAbstractItemDelegate a) ((QHelpEvent t1, QAbstractItemView t2, QStyleOptionViewItem t3, QModelIndex t4)) (IO (Bool)) where helpEvent x0 (x1, x2, x3, x4) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> withObjectPtr x4 $ \cobj_x4 -> qtc_QAbstractItemDelegate_helpEvent cobj_x0 cobj_x1 cobj_x2 cobj_x3 cobj_x4 foreign import ccall "qtc_QAbstractItemDelegate_helpEvent" qtc_QAbstractItemDelegate_helpEvent :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQHelpEvent t1) -> Ptr (TQAbstractItemView t2) -> Ptr (TQStyleOptionViewItem t3) -> Ptr (TQModelIndex t4) -> IO CBool instance Qpaint (QAbstractItemDelegate ()) ((QPainter t1, QStyleOptionViewItem t2, QModelIndex t3)) where paint x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractItemDelegate_paint_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QAbstractItemDelegate_paint_h" qtc_QAbstractItemDelegate_paint_h :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionViewItem t2) -> Ptr (TQModelIndex t3) -> IO () instance Qpaint (QAbstractItemDelegateSc a) ((QPainter t1, QStyleOptionViewItem t2, QModelIndex t3)) where paint x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractItemDelegate_paint_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 instance QsetEditorData (QAbstractItemDelegate ()) ((QWidget t1, QModelIndex t2)) where setEditorData x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractItemDelegate_setEditorData_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QAbstractItemDelegate_setEditorData_h" qtc_QAbstractItemDelegate_setEditorData_h :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQWidget t1) -> Ptr (TQModelIndex t2) -> IO () instance QsetEditorData (QAbstractItemDelegateSc a) ((QWidget t1, QModelIndex t2)) where setEditorData x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractItemDelegate_setEditorData_h cobj_x0 cobj_x1 cobj_x2 instance QsetModelData (QAbstractItemDelegate ()) ((QWidget t1, QAbstractItemModel t2, QModelIndex t3)) where setModelData x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractItemDelegate_setModelData_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QAbstractItemDelegate_setModelData_h" qtc_QAbstractItemDelegate_setModelData_h :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQWidget t1) -> Ptr (TQAbstractItemModel t2) -> Ptr (TQModelIndex t3) -> IO () instance QsetModelData (QAbstractItemDelegateSc a) ((QWidget t1, QAbstractItemModel t2, QModelIndex t3)) where setModelData x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractItemDelegate_setModelData_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 instance QqsizeHint (QAbstractItemDelegate ()) ((QStyleOptionViewItem t1, QModelIndex t2)) where qsizeHint x0 (x1, x2) = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractItemDelegate_sizeHint_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QAbstractItemDelegate_sizeHint_h" qtc_QAbstractItemDelegate_sizeHint_h :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQStyleOptionViewItem t1) -> Ptr (TQModelIndex t2) -> IO (Ptr (TQSize ())) instance QqsizeHint (QAbstractItemDelegateSc a) ((QStyleOptionViewItem t1, QModelIndex t2)) where qsizeHint x0 (x1, x2) = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractItemDelegate_sizeHint_h cobj_x0 cobj_x1 cobj_x2 instance QsizeHint (QAbstractItemDelegate ()) ((QStyleOptionViewItem t1, QModelIndex t2)) where sizeHint x0 (x1, x2) = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractItemDelegate_sizeHint_qth_h cobj_x0 cobj_x1 cobj_x2 csize_ret_w csize_ret_h foreign import ccall "qtc_QAbstractItemDelegate_sizeHint_qth_h" qtc_QAbstractItemDelegate_sizeHint_qth_h :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQStyleOptionViewItem t1) -> Ptr (TQModelIndex t2) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint (QAbstractItemDelegateSc a) ((QStyleOptionViewItem t1, QModelIndex t2)) where sizeHint x0 (x1, x2) = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractItemDelegate_sizeHint_qth_h cobj_x0 cobj_x1 cobj_x2 csize_ret_w csize_ret_h instance QupdateEditorGeometry (QAbstractItemDelegate ()) ((QWidget t1, QStyleOptionViewItem t2, QModelIndex t3)) where updateEditorGeometry x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractItemDelegate_updateEditorGeometry_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QAbstractItemDelegate_updateEditorGeometry_h" qtc_QAbstractItemDelegate_updateEditorGeometry_h :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQWidget t1) -> Ptr (TQStyleOptionViewItem t2) -> Ptr (TQModelIndex t3) -> IO () instance QupdateEditorGeometry (QAbstractItemDelegateSc a) ((QWidget t1, QStyleOptionViewItem t2, QModelIndex t3)) where updateEditorGeometry x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractItemDelegate_updateEditorGeometry_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 qAbstractItemDelegate_delete :: QAbstractItemDelegate a -> IO () qAbstractItemDelegate_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractItemDelegate_delete cobj_x0 foreign import ccall "qtc_QAbstractItemDelegate_delete" qtc_QAbstractItemDelegate_delete :: Ptr (TQAbstractItemDelegate a) -> IO () qAbstractItemDelegate_deleteLater :: QAbstractItemDelegate a -> IO () qAbstractItemDelegate_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractItemDelegate_deleteLater cobj_x0 foreign import ccall "qtc_QAbstractItemDelegate_deleteLater" qtc_QAbstractItemDelegate_deleteLater :: Ptr (TQAbstractItemDelegate a) -> IO () instance QchildEvent (QAbstractItemDelegate ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractItemDelegate_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractItemDelegate_childEvent" qtc_QAbstractItemDelegate_childEvent :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QAbstractItemDelegateSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractItemDelegate_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QAbstractItemDelegate ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractItemDelegate_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractItemDelegate_connectNotify" qtc_QAbstractItemDelegate_connectNotify :: Ptr (TQAbstractItemDelegate a) -> CWString -> IO () instance QconnectNotify (QAbstractItemDelegateSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractItemDelegate_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QAbstractItemDelegate ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractItemDelegate_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractItemDelegate_customEvent" qtc_QAbstractItemDelegate_customEvent :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QAbstractItemDelegateSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractItemDelegate_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QAbstractItemDelegate ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractItemDelegate_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractItemDelegate_disconnectNotify" qtc_QAbstractItemDelegate_disconnectNotify :: Ptr (TQAbstractItemDelegate a) -> CWString -> IO () instance QdisconnectNotify (QAbstractItemDelegateSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractItemDelegate_disconnectNotify cobj_x0 cstr_x1 instance Qevent (QAbstractItemDelegate ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractItemDelegate_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractItemDelegate_event_h" qtc_QAbstractItemDelegate_event_h :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QAbstractItemDelegateSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractItemDelegate_event_h cobj_x0 cobj_x1 instance QeventFilter (QAbstractItemDelegate ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractItemDelegate_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QAbstractItemDelegate_eventFilter_h" qtc_QAbstractItemDelegate_eventFilter_h :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QAbstractItemDelegateSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractItemDelegate_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QAbstractItemDelegate ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractItemDelegate_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractItemDelegate_receivers" qtc_QAbstractItemDelegate_receivers :: Ptr (TQAbstractItemDelegate a) -> CWString -> IO CInt instance Qreceivers (QAbstractItemDelegateSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractItemDelegate_receivers cobj_x0 cstr_x1 instance Qsender (QAbstractItemDelegate ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractItemDelegate_sender cobj_x0 foreign import ccall "qtc_QAbstractItemDelegate_sender" qtc_QAbstractItemDelegate_sender :: Ptr (TQAbstractItemDelegate a) -> IO (Ptr (TQObject ())) instance Qsender (QAbstractItemDelegateSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractItemDelegate_sender cobj_x0 instance QtimerEvent (QAbstractItemDelegate ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractItemDelegate_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractItemDelegate_timerEvent" qtc_QAbstractItemDelegate_timerEvent :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QAbstractItemDelegateSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractItemDelegate_timerEvent cobj_x0 cobj_x1
uduki/hsQt
Qtc/Gui/QAbstractItemDelegate.hs
bsd-2-clause
18,001
0
16
2,701
5,176
2,627
2,549
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} module Bead.Domain.Entities ( Submission(..) , submissionCata , withSubmission , SubmissionValue(..) , submissionValue , withSubmissionValue , CourseName , UsersFullname , evaluationResultCata , allBinaryEval , allPercentEval , Evaluation(..) , evaluationCata , withEvaluation , resultString , evaluationToFeedback , CourseCode(..) , CGInfo(..) , cgInfoCata , Course(..) , courseCata , courseAppAna , Group(..) , groupCata , Workflow(..) , Role(..) , roleCata , roles , groupAdmin , OutsideRole(..) , parseRole , printRole , atLeastCourseAdmin , InRole(..) , Permission(..) , canOpen , canCreate , canModify , canDelete , PermissionObject(..) , PermissionObj(..) , ObjectPermissions(..) , Username(..) , usernameCata , withUsername , AsUsername(..) , Password , AsPassword(..) , passwordCata , Email(..) , emailFold , parseEmail , email' , emailCata , TimeZoneName(..) , timeZoneName , showDate , UserRegInfo(..) , userRegInfoCata , Language(..) , languageCata , Uid(..) , uid , User(..) , userCata , withUser , userAna , PersonalInfo(..) , personalInfoCata , withPersonalInfo , UserDesc(..) , mkUserDescription , UserRegistration(..) , userRegistration , TestScriptType(..) , testScriptTypeCata , TestScript(..) , testScriptCata , withTestScript , testScriptAppAna , TestCase(..) , testCaseCata , withTestCase , testCaseAppAna , UsersFile(..) , usersFile , FileInfo(..) , fileInfoCata , withFileInfo , fileInfoAppAna , Score(..) , score , CompareHun(..) , StatusMessage(..) , statusMessage , module Bead.Domain.Entity.Assessment , module Bead.Domain.Entity.Assignment , module Bead.Domain.Entity.Comment , module Bead.Domain.Entity.Feedback , module Bead.Domain.Entity.TestCase #ifdef TEST , entityTests #endif ) where import Control.Applicative import Data.ByteString.Char8 (ByteString) import Data.Data import Data.List (findIndex) import Data.Time (UTCTime(..), LocalTime) import Data.Time.Format (formatTime) import System.Locale (defaultTimeLocale) import Bead.Domain.Entity.Assessment import Bead.Domain.Entity.Assignment import Bead.Domain.Entity.Comment import Bead.Domain.Entity.Feedback import Bead.Domain.Entity.TestCase import Bead.Domain.Evaluation import Bead.View.Translation #ifdef TEST import Test.Tasty.Arbitrary import Test.Tasty.TestSet hiding (shrink) #endif data SubmissionValue = SimpleSubmission String | ZippedSubmission ByteString deriving (Eq, Show) submissionValue simple zipped v = case v of SimpleSubmission s -> simple s ZippedSubmission z -> zipped z withSubmissionValue v simple zipped = submissionValue simple zipped v -- | Solution for one exercise data Submission = Submission { solution :: SubmissionValue , solutionPostDate :: UTCTime } deriving (Eq, Show) -- | Template function for submission submissionCata f (Submission sub subPostDate) = f sub subPostDate -- | Template function for submission with flipped arguments withSubmission s f = submissionCata f s type CourseName = String type UsersFullname = String evaluationResultCata binary percentage e = case e of BinEval b -> binary b PctEval p -> percentage p allBinaryEval :: [EvaluationData b p] -> Maybe [b] allBinaryEval = sequence . map binaryEval allPercentEval :: [EvaluationData b p] -> Maybe [p] allPercentEval = sequence . map percentEval -- | Evaluation of a submission data Evaluation = Evaluation { evaluationResult :: EvResult , writtenEvaluation :: String } deriving (Eq, Show) -- | Template function for the evaluation evaluationCata f (Evaluation result written) = f result written -- | Template function with flipped parameter for the evaluation withEvaluation e f = evaluationCata f e resultString :: EvResult -> TransMsg resultString (EvResult (BinEval (Binary Passed))) = TransMsg $ msg_Domain_EvalPassed "Passed" resultString (EvResult (BinEval (Binary Failed))) = TransMsg $ msg_Domain_EvalFailed "Failed" resultString (EvResult (PctEval p)) = case point p of Nothing -> TransMsg $ msg_Domain_EvalNoResultError "No evaluation result, some internal error happened!" Just q -> TransPrmMsg (msg_Domain_EvalPercentage "%s%%") (show . round $ 100.0 * q) evaluationToFeedback :: UTCTime -> User -> Evaluation -> Feedback evaluationToFeedback t u e = Feedback info t where info = Evaluated (evaluationResult e) (writtenEvaluation e) (u_name u) newtype CourseCode = CourseCode String deriving (Eq, Ord, Show) -- Course or Group info. Some information is attached to -- course or group data CGInfo a = CourseInfo a | GroupInfo a deriving (Show) -- Template function for the course or group info value cgInfoCata course group cg = case cg of CourseInfo x -> course x GroupInfo x -> group x -- | A course represent a course at the university data Course = Course { courseName :: String , courseDesc :: String , courseTestScriptType :: TestScriptType } deriving (Eq, Show, Ord) courseCata script course (Course name desc scriptType) = course name desc (script scriptType) courseAppAna name desc test = Course <$> name <*> desc <*> test -- | Groups are registered under the courses data Group = Group { groupName :: String , groupDesc :: String } deriving (Eq, Show, Ord) groupCata group (Group name desc) = group name desc -- | Workflows can happen to exams data Workflow = W_Created | W_Open | W_Closed | W_Expired deriving (Eq, Show) -- * Authorization and authentication -- | Login roles data Role = Student | GroupAdmin | CourseAdmin | Admin deriving (Data, Enum, Eq, Ord, Show, Typeable) roleCata student groupAdmin courseAdmin admin r = case r of Student -> student GroupAdmin -> groupAdmin CourseAdmin -> courseAdmin Admin -> admin #ifdef TEST instance Arbitrary Role where arbitrary = elements roles shrink = roleCata [GroupAdmin, CourseAdmin, Admin] [CourseAdmin, Admin] [Admin] [] #endif roles = [Student, GroupAdmin, CourseAdmin, Admin] -- Decides if the given role can admninstrate groups -- Returns True if yes, otherwise False groupAdmin = roleCata False True True False data OutsideRole = EmptyRole | RegRole | TestAgentRole deriving (Eq, Ord) parseRole :: String -> Maybe Role parseRole "Student" = Just Student parseRole "Group Admin" = Just GroupAdmin parseRole "Course Admin" = Just CourseAdmin parseRole "Admin" = Just Admin parseRole _ = Nothing printRole = roleCata "Student" "Group Admin" "Course Admin" "Admin" atLeastCourseAdmin Admin = True atLeastCourseAdmin CourseAdmin = True atLeastCourseAdmin _ = False class InRole r where isAdmin :: r -> Bool isCourseAdmin :: r -> Bool isGroupAdmin :: r -> Bool isStudent :: r -> Bool instance InRole Role where isAdmin = (== Admin) isCourseAdmin = (>= CourseAdmin) isGroupAdmin = (>= GroupAdmin) isStudent = (== Student) -- * Permissions -- | Granted permission on a given operation data Permission = P_Open | P_Create | P_Modify | P_Delete deriving (Show, Eq, Enum) canOpen, canCreate, canModify, canDelete :: Permission -> Bool canOpen = flip elem [P_Open, P_Create, P_Modify, P_Delete] canCreate = flip elem [P_Create, P_Modify, P_Delete] canModify = flip elem [P_Modify, P_Delete] canDelete = flip elem [P_Delete] -- | Permissions are allowed on the following objects data PermissionObject = P_Assignment | P_UserReg | P_Submission | P_Evaluation | P_Comment | P_Feedback | P_Statistics | P_Password | P_GroupAdmin | P_User | P_Course | P_Group | P_CourseAdmin | P_AdminPage | P_PlainPage | P_TestScript | P_File | P_TestIncoming | P_TestCase | P_StudentPassword deriving (Eq, Ord, Show, Enum) -- Permission Objects are dynamically associated with values class PermissionObj p where permissionObject :: p -> PermissionObject newtype ObjectPermissions = ObjectPermissions { permissions :: [(Permission, PermissionObject)] } newtype Username = Username String deriving (Data, Eq, Ord, Read, Show, Typeable) usernameCata :: (String -> a) -> Username -> a usernameCata f (Username u) = f u withUsername :: Username -> (String -> a) -> a withUsername (Username u) f = f u class AsUsername c where asUsername :: c -> Username type Password = String class AsPassword p where asPassword :: p -> Password passwordCata :: (String -> a) -> Password -> a passwordCata f p = f p newtype Email = Email String deriving (Eq, Ord, Read) emailFold :: (String -> a) -> Email -> a emailFold f (Email e) = f e parseEmail :: String -> Maybe Email parseEmail = Just . Email instance Show Email where show (Email e) = e -- TODO: throw exception if email string is unacceptable email' :: String -> Email email' = Email emailCata :: (String -> a) -> Email -> a emailCata f (Email e) = f e -- | Represents a name of a time zone based on the -- location for the given time zone. -- E.g: ZoneInfo "Europe/Budapest" newtype TimeZoneName = TimeZoneName { unTzn :: String } deriving (Data, Eq, Ord, Read, Show, Typeable) timeZoneName f (TimeZoneName z) = f z #ifdef TEST instance Arbitrary TimeZoneName where arbitrary = TimeZoneName <$> arbitrary shrink = fmap TimeZoneName . timeZoneName shrink #endif showDate :: LocalTime -> String showDate = formatTime defaultTimeLocale "%F, %T" -- UserRegInfo is a User Registration Info that consists of -- a Username, a Password, an Email Address, a Full Name, and a time zone newtype UserRegInfo = UserRegInfo (String, String, String, String, TimeZoneName) userRegInfoCata f (UserRegInfo (username, password, email, fullName, timeZoneName)) = f username password email fullName timeZoneName -- The language what the dictionary represents. newtype Language = Language String deriving (Data, Eq, Ord, Read, Show, Typeable) languageCata f (Language l) = f l -- User ID is unique identifier for the user, which -- can be different than the username newtype Uid = Uid String deriving (Data, Eq, Ord, Read, Show, Typeable) uid f (Uid x) = f x -- | Logged in user data User = User { u_role :: Role , u_username :: Username , u_email :: Email , u_name :: String , u_timezone :: TimeZoneName , u_language :: Language , u_uid :: Uid } deriving (Eq, Ord, Show) userCata f (User role username email name timezone language uid) = f role username email name timezone language uid withUser = flip userCata userAna role username email name timezone language = User <$> role <*> username <*> email <*> name <*> timezone <*> language newtype PersonalInfo = PersonalInfo (Role, String, TimeZoneName, Uid) personalInfoCata f (PersonalInfo (role, name, timezone, uid)) = f role name timezone uid withPersonalInfo p f = personalInfoCata f p data UserDesc = UserDesc { ud_username :: Username , ud_fullname :: String , ud_uid :: Uid } deriving (Eq, Ord, Show) mkUserDescription :: User -> UserDesc mkUserDescription u = UserDesc { ud_username = u_username u , ud_fullname = u_name u , ud_uid = u_uid u } -- | User awaiting for registration data UserRegistration = UserRegistration { reg_username :: String , reg_email :: String , reg_name :: String -- User's full name , reg_token :: String -- Token for identification , reg_timeout :: UTCTime } deriving (Eq, Show, Read) -- | Template function for the UserRegistration userRegistration f (UserRegistration username email name token timeout) = f username email name token timeout -- Test Script Type represents a choice: The test cases for the -- test script will be uploaded as plain text or a zip file data TestScriptType = TestScriptSimple | TestScriptZipped deriving (Eq, Ord, Enum, Show, Read, Data, Typeable) -- Template function for the TestScriptType testScriptTypeCata simple zipped t = case t of TestScriptSimple -> simple TestScriptZipped -> zipped #ifdef TEST instance Arbitrary TestScriptType where arbitrary = elements [TestScriptSimple, TestScriptZipped] shrink = testScriptTypeCata [TestScriptZipped] [] #endif -- Test Script defines a scripts that can be integrated with the -- testing framework for the given course. data TestScript = TestScript { tsName :: String -- The name of the script , tsDescription :: String -- The short description of the script , tsNotes :: String -- The notes for the creator of the test cases, which are associated with the script , tsScript :: String -- The script itself that will be subsctituated to the test frameworks shell script , tsType :: TestScriptType -- The type of the test script } deriving (Eq, Show, Read) -- Template function for the TestScript testScriptCata tc -- Transformation of the test script type f (TestScript name description notes script type_) = f name description notes script (tc type_) -- Template function for the TestScript with flipped parameters withTestScript t tc f = testScriptCata tc f t -- Applicative functor based TestScript value creation testScriptAppAna name desc notes script type_ = TestScript <$> name <*> desc <*> notes <*> script <*> type_ -- Name of the file that a user can upload data UsersFile = UsersPublicFile String | UsersPrivateFile String deriving (Data, Eq, Ord, Read, Show, Typeable) -- Template function for User's file usersFile public private f = case f of UsersPublicFile x -> public x UsersPrivateFile x -> private x -- File information that will be displayed on the UI data FileInfo = FileInfo { fiSize :: Int -- The size of the file in bytes , fiDate :: UTCTime -- The last modifcation date of the file } -- Template function for the FileInfo value fileInfoCata f (FileInfo size date) = f size date -- Template function for the FileInfo value withFileInfo (FileInfo size date) f = f size date -- Applicative functor based FileInfo construction fileInfoAppAna size date = FileInfo <$> size <*> date data Score = Score () deriving (Data, Eq, Ord, Read, Show, Typeable) #ifdef TEST instance Arbitrary Score where arbitrary = return (Score ()) shrink _ = [] #endif -- * PermObjs instance instance PermissionObj Course where permissionObject _ = P_Course instance PermissionObj Assignment where permissionObject _ = P_Assignment instance PermissionObj UserRegistration where permissionObject _ = P_UserReg -- * Ordering -- Hungarian related charecter comparing, for special characters -- uses the given list otherwise the normal comparism is called -- capitals and non capitals are different characters class CompareHun c where compareHun :: c -> c -> Ordering instance CompareHun Char where compareHun c c' = maybe (compare c c') id ((compare <$> idxSmall c <*> idxSmall c') <|> (compare <$> idxCapital c <*> idxCapital c')) where idxSmall x = findIndex (x==) hunSmall idxCapital x = findIndex (x==) hunCapital hunSmall = "aábcdeéfghiíjklmnoóöőpqrstuúüűvwxyz" hunCapital = "AÁBCDEÉFGHIÍJKLMNOÓÖŐPQRSTUÚÜŰVWXYZ" instance CompareHun c => CompareHun [c] where compareHun [] [] = EQ compareHun [] (_:_) = LT compareHun (_:_) [] = GT compareHun (x:xs) (y:ys) = case compareHun x y of EQ -> compareHun xs ys other -> other instance CompareHun Username where compareHun (Username u) (Username u') = compareHun u u' instance CompareHun UserDesc where compareHun (UserDesc username fullname uid) (UserDesc username' fullname' uid') = case compareHun fullname fullname' of EQ -> compareHun username username' other -> other -- Status message is shown for the user on the UI data StatusMessage a = SmNormal a -- Normal message | SmError a -- Some none several error happened, the user needs to be informed about. deriving (Show, Eq) statusMessage normal err sm = case sm of SmNormal x -> normal x SmError x -> err x #ifdef TEST entityTests = do compareHunTests roleTest compareHunTests = group "compareHun" $ eqPartitions compareHun' [ Partition "Small normal letters a-a" ('a', 'a') EQ "" , Partition "Small normal letters d-z" ('d', 'z') LT "" , Partition "Small normal letters z-a" ('z', 'a') GT "" , Partition "Capital normal letters A-A" ('A', 'A') EQ "" , Partition "Capital normal letters D-Z" ('D', 'Z') LT "" , Partition "Capital normal letters Z-A" ('Z', 'A') GT "" , Partition "Small accented letters á-á" ('á', 'á') EQ "" , Partition "Small accented letters é-ú" ('é', 'ú') LT "" , Partition "Small accented letters ű-á" ('ű', 'á') GT "" , Partition "Capital accented letters Á-Á" ('á', 'á') EQ "" , Partition "Capital accented letters É-Ú" ('É', 'Ú') LT "" , Partition "Capital accented letters Ű-Á" ('Ű', 'Á') GT "" ] where compareHun' = uncurry compareHun roleTest = assertProperty "parse and print role are inverse functions" (\r -> ((Just r) ==) . parseRole . printRole $ r) enumGen "printRole roles must generate string parseable by parseRole" #endif
pgj/bead
src/Bead/Domain/Entities.hs
bsd-3-clause
17,550
0
13
3,738
4,453
2,500
1,953
453
4
{-# LANGUAGE UnicodeSyntax, OverloadedStrings, TupleSections #-} ----------------------------------------------------------------------------------------------------------------------- -- | -- Module : Massive.Database.MongoDB.Types -- Copyright : (C) 2012 Massive Tactical Limited -- License : BSD3 -- Maintainer : Blake Rain <blake.rain@massivetactical.com> -- -- Various useful types. -- ----------------------------------------------------------------------------------------------------------------------- module Massive.Database.MongoDB.Types ( Entity (..) , Collection (..) , toList ) where import Prelude.Unicode import Control.Applicative import Control.Monad import qualified Data.Aeson as Aeson import qualified Data.HashMap.Strict as HM import qualified Data.Text as T import Text.Printf import Text.Read (readMaybe) import Massive.Database.MongoDB.MongoEntity ----------------------------------------------------------------------------------------------------------------------- -- | The 'Entity' data type is used to pair a type serialised from the database -- with it's unique key. data Entity α = Entity { entityKey ∷ Key α , entityVal ∷ α } -- | A show instance exist for any specialisation of 'Entity' to some type @α@ -- that is both an instance of 'MongoEntity' and 'Show'. This instance will -- display the entity in the form @key: <show x>@. instance (MongoEntity α, Show α) ⇒ Show (Entity α) where show (Entity key val) = show (fromKey key) ++ ": " ++ show val instance (MongoEntity α, Aeson.ToJSON α) ⇒ Aeson.ToJSON (Entity α) where toJSON (Entity key val) = let valJ = Aeson.toJSON val in case valJ of (Aeson.Object obj) → Aeson.Object $ HM.insert "id" (Aeson.toJSON key) obj other → Aeson.object [ "id" Aeson..= key , "value" Aeson..= other ] instance (MongoEntity a, Aeson.FromJSON a) => Aeson.FromJSON (Entity a) where parseJSON val @ (Aeson.Object obj) = do objId <- obj Aeson..: "id" Entity objId <$> Aeson.parseJSON val parseJSON _ = fail "expected object for entity" ----------------------------------------------------------------------------------------------------------------------- -- | A collection of some type. This is represented as a list of 'Entity'. newtype Collection α = Collection { unCollection ∷ [Entity α] } -- | Given a collection, convert it to a list of tuples. toList ∷ (MongoEntity α) ⇒ Collection α → [(Key α, α)] toList = map (\(Entity key val) → (key, val)) ∘ unCollection -- | Much like the 'Entity' type, there exists a 'Show' instance for a -- 'Collection' of some type @α@ that is both an instance of the 'MongoEntity' -- and 'Show' type clases. instance (MongoEntity α, Show α) ⇒ Show (Collection α) where show (Collection parts) = show parts -- | Provide a convenient means of serialising a collection to JSON. The -- collection is serialised as an object, where each field of the object is an -- ID and the value is the serialisation of the entity. instance (MongoEntity α, Aeson.ToJSON α) ⇒ Aeson.ToJSON (Collection α) where toJSON (Collection parts) = Aeson.object $ map (\e → (T.pack ∘ show ∘ fromKey ∘ entityKey $ e, Aeson.toJSON ∘ entityVal $ e)) parts -- | Provide a convenient deserialisation of a collection from JSON. instance (MongoEntity α, Aeson.FromJSON α) ⇒ Aeson.FromJSON (Collection α) where parseJSON (Aeson.Object obj) = Collection <$> mapM fromPair (HM.toList obj) where fromPair (key, val) = case readMaybe (T.unpack key) of Just oid → Entity (toKey oid) <$> Aeson.parseJSON val Nothing → fail $ printf "failed to parse '%s' as an ObjectID" (T.unpack key) parseJSON _ = mzero
HalfWayMan/mt-mongodb
src/Massive/Database/MongoDB/Types.hs
bsd-3-clause
4,209
1
15
1,086
821
447
374
46
1
{-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards, DisambiguateRecordFields #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE FlexibleContexts, FlexibleInstances #-} {-# LANGUAGE OverlappingInstances, UndecidableInstances, TypeSynonymInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} module Narradar.Framework.GraphViz ( module Narradar.Framework.GraphViz, module MuTerm.Framework.GraphViz, module MuTerm.Framework.DotRep, ) where import Control.Applicative import Control.Monad import Data.Graph import Data.Foldable (toList, Foldable) import qualified Data.Map as Map import qualified Data.Set as Set import Data.List hiding (unlines) import Data.Maybe import Data.Monoid import Data.Traversable (Traversable) import Prelude hiding (unlines) #ifdef DEBUG import System.Process import Text.Printf #endif import qualified Data.Term.Var as Term import qualified Language.Prolog.Syntax as Prolog import Narradar.Framework import MuTerm.Framework.DotRep import MuTerm.Framework.GraphViz import MuTerm.Framework.Proof import MuTerm.Framework.Problem import Narradar.Types.ArgumentFiltering (fromAF) import Narradar.Types.Problem import Narradar.Types.Problem.Infinitary as Inf import Narradar.Types.Problem.NarrowingGen as Gen import Narradar.Types import Narradar.Utils -- instance Ppr a => DotRep a where dotSimple x = Text (showPpr x)[] {- proofnode done (SomeInfo (DependencyGraph gr)) par | done || showFailedPaths = do (cl, nn) <- cluster (attribute ("shape", "ellipse") >> pprGraph gr []) case nn of [] -> return par me:_ -> do case par of N n -> edge n me ([("lhead", show cl)] ++ doneEdge done) Cluster (cl',n) -> edge (getParentNode n) me [("ltail", show cl'), ("lhead", show cl)] return (Cluster (cl, N me)) proofnode done (SomeInfo (SCCGraph gr sccs)) par = do (cl, nn) <- cluster ( attribute ("shape", "ellipse") >> pprGraph gr (zip sccs (cycle ["yellow","darkorange" , "hotpink", "hotpink4", "purple", "brown","red","green"]))) case (nn,par) of ([] , _ ) -> return par (me:_, N n) -> edge n me ([("lhead", show cl)] ++ doneEdge done) >> return (Cluster (cl, N me)) (me:_, Cluster (cl',n)) -> edge (getParentNode n) me [("ltail", show cl'), ("lhead", show cl)] >> return (Cluster (cl, N me)) proofnode done (SomeInfo (UsableGraph gr reachable)) par = do (cl, nn) <- cluster (attribute ("shape", "ellipse") >> (pprGraph gr [(reachable,"blue")])) case (nn,par) of ([] , _ ) -> return par (me:_, N n) -> edge n me ([("lhead", show cl)] ++ doneEdge done) >> return (Cluster (cl, N me)) (me:_, Cluster (cl',n)) -> edge (getParentNode n) me ([("ltail", show cl'), ("lhead", show cl)] ++ doneEdge done) >> return (Cluster (cl, N me)) -} instance (PprTPDB (Problem typ trs), ProblemColor (Problem typ trs)) => DotRep (Problem typ trs) where dot p = Text (pprTPDB p) [ Color [problemColor p] , Shape BoxShape , Style (Stl Bold Nothing) , FontName "monospace" , FontSize 10 , Margin (PVal (PointD 0.2 0.2))] instance DotRep PrologProblem where dot PrologProblem{..} = Text pgm [ Shape BoxShape , Style (Stl Bold Nothing) , FontName "monospace" , FontSize 10 , Margin (PVal (PointD 0.2 0.2))] where pgm = pPrint program $$ vcat [text "%Query: " <+> (pPrint g) | g <- goals] class ProblemColor p where problemColor :: p -> Color instance ProblemColor typ where problemColor _ = ColorName "black" instance (IsDPProblem typ, ProblemColor typ) => ProblemColor (Problem typ trs) where problemColor = problemColor . getFramework instance ProblemColor (Problem (Prolog id) trs) where problemColor _ = ColorName "#F6D106" instance ProblemColor Rewriting where problemColor _ = ColorName "#EAAAFF" instance ProblemColor Narrowing where problemColor _ = ColorName "#4488C9" instance ProblemColor CNarrowing where problemColor _ = ColorName "#FD6802" #ifdef DEBUG --debugDot x = let t = "temp" in writeFile (t ++ ".dot") (pprDot' (PprDot True) x) >> system (printf "dot %s.dot -O -Tpdf && open %s.dot.pdf" t t) #endif
pepeiborra/narradar
src/Narradar/Framework/GraphViz.hs
bsd-3-clause
4,666
0
13
1,235
649
367
282
60
0
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[TcType]{Types used in the typechecker} This module provides the Type interface for front-end parts of the compiler. These parts * treat "source types" as opaque: newtypes, and predicates are meaningful. * look through usage types The "tc" prefix is for "TypeChecker", because the type checker is the principal client. -} {-# LANGUAGE CPP #-} module TcType ( -------------------------------- -- Types TcType, TcSigmaType, TcRhoType, TcTauType, TcPredType, TcThetaType, TcTyVar, TcTyVarSet, TcKind, TcCoVar, -- TcLevel TcLevel(..), topTcLevel, pushTcLevel, strictlyDeeperThan, sameDepthAs, fskTcLevel, -------------------------------- -- MetaDetails UserTypeCtxt(..), pprUserTypeCtxt, pprSigCtxt, TcTyVarDetails(..), pprTcTyVarDetails, vanillaSkolemTv, superSkolemTv, MetaDetails(Flexi, Indirect), MetaInfo(..), isImmutableTyVar, isSkolemTyVar, isMetaTyVar, isMetaTyVarTy, isTyVarTy, isSigTyVar, isOverlappableTyVar, isTyConableTyVar, isFskTyVar, isFmvTyVar, isFlattenTyVar, isAmbiguousTyVar, metaTvRef, metaTyVarInfo, isFlexi, isIndirect, isRuntimeUnkSkol, isTypeVar, isKindVar, metaTyVarTcLevel, setMetaTyVarTcLevel, metaTyVarTcLevel_maybe, isTouchableMetaTyVar, isTouchableOrFmv, isFloatedTouchableMetaTyVar, canUnifyWithPolyType, -------------------------------- -- Builders mkPhiTy, mkSigmaTy, mkTcEqPred, mkTcReprEqPred, mkTcEqPredRole, -------------------------------- -- Splitters -- These are important because they do not look through newtypes tcView, tcSplitForAllTys, tcSplitPhiTy, tcSplitPredFunTy_maybe, tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy, tcSplitFunTysN, tcSplitTyConApp, tcSplitTyConApp_maybe, tcTyConAppTyCon, tcTyConAppArgs, tcSplitAppTy_maybe, tcSplitAppTy, tcSplitAppTys, repSplitAppTy_maybe, tcInstHeadTyNotSynonym, tcInstHeadTyAppAllTyVars, tcGetTyVar_maybe, tcGetTyVar, nextRole, tcSplitSigmaTy, tcDeepSplitSigmaTy_maybe, --------------------------------- -- Predicates. -- Again, newtypes are opaque eqType, eqTypes, eqPred, cmpType, cmpTypes, cmpPred, eqTypeX, pickyEqType, tcEqType, tcEqKind, isSigmaTy, isRhoTy, isOverloadedTy, isDoubleTy, isFloatTy, isIntTy, isWordTy, isStringTy, isIntegerTy, isBoolTy, isUnitTy, isCharTy, isTauTy, isTauTyCon, tcIsTyVarTy, tcIsForAllTy, isPredTy, isTyVarClassPred, isTyVarExposed, --------------------------------- -- Misc type manipulators deNoteType, occurCheckExpand, OccCheckResult(..), orphNamesOfType, orphNamesOfDFunHead, orphNamesOfCo, orphNamesOfTypes, orphNamesOfCoCon, getDFunTyKey, evVarPred_maybe, evVarPred, --------------------------------- -- Predicate types mkMinimalBySCs, transSuperClasses, immSuperClasses, -- * Finding type instances tcTyFamInsts, -- * Finding "exact" (non-dead) type variables exactTyVarsOfType, exactTyVarsOfTypes, --------------------------------- -- Foreign import and export isFFIArgumentTy, -- :: DynFlags -> Safety -> Type -> Bool isFFIImportResultTy, -- :: DynFlags -> Type -> Bool isFFIExportResultTy, -- :: Type -> Bool isFFIExternalTy, -- :: Type -> Bool isFFIDynTy, -- :: Type -> Type -> Bool isFFIPrimArgumentTy, -- :: DynFlags -> Type -> Bool isFFIPrimResultTy, -- :: DynFlags -> Type -> Bool isFFILabelTy, -- :: Type -> Bool isFFITy, -- :: Type -> Bool isFunPtrTy, -- :: Type -> Bool tcSplitIOType_maybe, -- :: Type -> Maybe Type -------------------------------- -- Rexported from Kind Kind, typeKind, unliftedTypeKind, liftedTypeKind, openTypeKind, constraintKind, mkArrowKind, mkArrowKinds, isLiftedTypeKind, isUnliftedTypeKind, isSubOpenTypeKind, tcIsSubKind, splitKindFunTys, defaultKind, -------------------------------- -- Rexported from Type Type, PredType, ThetaType, mkForAllTy, mkForAllTys, mkFunTy, mkFunTys, zipFunTys, mkTyConApp, mkAppTy, mkAppTys, applyTy, applyTys, mkTyVarTy, mkTyVarTys, mkTyConTy, isClassPred, isEqPred, isIPPred, mkClassPred, isDictLikeTy, tcSplitDFunTy, tcSplitDFunHead, mkEqPred, -- Type substitutions TvSubst(..), -- Representation visible to a few friends TvSubstEnv, emptyTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst, unionTvSubst, getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope, Type.lookupTyVar, Type.extendTvSubst, Type.substTyVarBndr, extendTvSubstList, isInScope, mkTvSubst, zipTyEnv, Type.substTy, substTys, substTyWith, substTheta, substTyVar, substTyVars, isUnLiftedType, -- Source types are always lifted isUnboxedTupleType, -- Ditto isPrimitiveType, tyVarsOfType, tyVarsOfTypes, closeOverKinds, tcTyVarsOfType, tcTyVarsOfTypes, pprKind, pprParendKind, pprSigmaType, pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTheta, pprThetaArrowTy, pprClassPred ) where #include "HsVersions.h" -- friends: import Kind import TypeRep import Class import Var import ForeignCall import VarSet import Coercion import Type import TyCon import CoAxiom -- others: import DynFlags import Name -- hiding (varName) -- We use this to make dictionaries for type literals. -- Perhaps there's a better way to do this? import NameSet import VarEnv import PrelNames import TysWiredIn import BasicTypes import Util import Maybes import ListSetOps import Outputable import FastString import ErrUtils( Validity(..), isValid ) import Data.IORef import Control.Monad (liftM, ap) #if __GLASGOW_HASKELL__ < 709 import Control.Applicative (Applicative(..)) #endif {- ************************************************************************ * * \subsection{Types} * * ************************************************************************ The type checker divides the generic Type world into the following more structured beasts: sigma ::= forall tyvars. phi -- A sigma type is a qualified type -- -- Note that even if 'tyvars' is empty, theta -- may not be: e.g. (?x::Int) => Int -- Note that 'sigma' is in prenex form: -- all the foralls are at the front. -- A 'phi' type has no foralls to the right of -- an arrow phi :: theta => rho rho ::= sigma -> rho | tau -- A 'tau' type has no quantification anywhere -- Note that the args of a type constructor must be taus tau ::= tyvar | tycon tau_1 .. tau_n | tau_1 tau_2 | tau_1 -> tau_2 -- In all cases, a (saturated) type synonym application is legal, -- provided it expands to the required form. -} type TcTyVar = TyVar -- Used only during type inference type TcCoVar = CoVar -- Used only during type inference; mutable type TcType = Type -- A TcType can have mutable type variables -- Invariant on ForAllTy in TcTypes: -- forall a. T -- a cannot occur inside a MutTyVar in T; that is, -- T is "flattened" before quantifying over a -- These types do not have boxy type variables in them type TcPredType = PredType type TcThetaType = ThetaType type TcSigmaType = TcType type TcRhoType = TcType -- Note [TcRhoType] type TcTauType = TcType type TcKind = Kind type TcTyVarSet = TyVarSet {- Note [TcRhoType] ~~~~~~~~~~~~~~~~ A TcRhoType has no foralls or contexts at the top, or to the right of an arrow YES (forall a. a->a) -> Int NO forall a. a -> Int NO Eq a => a -> a NO Int -> forall a. a -> Int ************************************************************************ * * \subsection{TyVarDetails} * * ************************************************************************ TyVarDetails gives extra info about type variables, used during type checking. It's attached to mutable type variables only. It's knot-tied back to Var.lhs. There is no reason in principle why Var.lhs shouldn't actually have the definition, but it "belongs" here. Note [Signature skolems] ~~~~~~~~~~~~~~~~~~~~~~~~ Consider this f :: forall a. [a] -> Int f (x::b : xs) = 3 Here 'b' is a lexically scoped type variable, but it turns out to be the same as the skolem 'a'. So we have a special kind of skolem constant, SigTv, which can unify with other SigTvs. They are used *only* for pattern type signatures. Similarly consider data T (a:k1) = MkT (S a) data S (b:k2) = MkS (T b) When doing kind inference on {S,T} we don't want *skolems* for k1,k2, because they end up unifying; we want those SigTvs again. Note [ReturnTv] ~~~~~~~~~~~~~~~ We sometimes want to convert a checking algorithm into an inference algorithm. An easy way to do this is to "check" that a term has a metavariable as a type. But, we must be careful to allow that metavariable to unify with *anything*. (Well, anything that doesn't fail an occurs-check.) This is what ReturnTv means. For example, if we have (undefined :: (forall a. TF1 a ~ TF2 a => a)) x we'll call (tcInfer . tcExpr) on the function expression. tcInfer will create a ReturnTv to represent the expression's type. We really need this ReturnTv to become set to (forall a. TF1 a ~ TF2 a => a) despite the fact that this type mentions type families and is a polytype. However, we must also be careful to make sure that the ReturnTvs really always do get unified with something -- we don't want these floating around in the solver. So, we check after running the checker to make sure the ReturnTv is filled. If it's not, we set it to a TauTv. We can't ASSERT that no ReturnTvs hit the solver, because they can if there's, say, a kind error that stops checkTauTvUpdate from working. This happens in test case typecheck/should_fail/T5570, for example. See also the commentary on #9404. -} -- A TyVarDetails is inside a TyVar data TcTyVarDetails = SkolemTv -- A skolem Bool -- True <=> this skolem type variable can be overlapped -- when looking up instances -- See Note [Binding when looking up instances] in InstEnv | FlatSkol -- A flatten-skolem. It stands for the TcType, and zonking TcType -- will replace it by that type. -- See Note [The flattening story] in TcFlatten | RuntimeUnk -- Stands for an as-yet-unknown type in the GHCi -- interactive context | MetaTv { mtv_info :: MetaInfo , mtv_ref :: IORef MetaDetails , mtv_tclvl :: TcLevel } -- See Note [TcLevel and untouchable type variables] vanillaSkolemTv, superSkolemTv :: TcTyVarDetails -- See Note [Binding when looking up instances] in InstEnv vanillaSkolemTv = SkolemTv False -- Might be instantiated superSkolemTv = SkolemTv True -- Treat this as a completely distinct type ----------------------------- data MetaDetails = Flexi -- Flexi type variables unify to become Indirects | Indirect TcType instance Outputable MetaDetails where ppr Flexi = ptext (sLit "Flexi") ppr (Indirect ty) = ptext (sLit "Indirect") <+> ppr ty data MetaInfo = TauTv Bool -- This MetaTv is an ordinary unification variable -- A TauTv is always filled in with a tau-type, which -- never contains any ForAlls. -- The boolean is true when the meta var originates -- from a wildcard. | ReturnTv -- Can unify with *anything*. Used to convert a -- type "checking" algorithm into a type inference algorithm. -- See Note [ReturnTv] | SigTv -- A variant of TauTv, except that it should not be -- unified with a type, only with a type variable -- SigTvs are only distinguished to improve error messages -- see Note [Signature skolems] -- The MetaDetails, if filled in, will -- always be another SigTv or a SkolemTv | FlatMetaTv -- A flatten meta-tyvar -- It is a meta-tyvar, but it is always untouchable, with level 0 -- See Note [The flattening story] in TcFlatten ------------------------------------- -- UserTypeCtxt describes the origin of the polymorphic type -- in the places where we need to an expression has that type data UserTypeCtxt = FunSigCtxt Name -- Function type signature -- Also used for types in SPECIALISE pragmas | InfSigCtxt Name -- Inferred type for function | ExprSigCtxt -- Expression type signature | ConArgCtxt Name -- Data constructor argument | TySynCtxt Name -- RHS of a type synonym decl | PatSigCtxt -- Type sig in pattern -- eg f (x::t) = ... -- or (x::t, y) = e | RuleSigCtxt Name -- LHS of a RULE forall -- RULE "foo" forall (x :: a -> a). f (Just x) = ... | ResSigCtxt -- Result type sig -- f x :: t = .... | ForSigCtxt Name -- Foreign import or export signature | DefaultDeclCtxt -- Types in a default declaration | InstDeclCtxt -- An instance declaration | SpecInstCtxt -- SPECIALISE instance pragma | ThBrackCtxt -- Template Haskell type brackets [t| ... |] | GenSigCtxt -- Higher-rank or impredicative situations -- e.g. (f e) where f has a higher-rank type -- We might want to elaborate this | GhciCtxt -- GHCi command :kind <type> | ClassSCCtxt Name -- Superclasses of a class | SigmaCtxt -- Theta part of a normal for-all type -- f :: <S> => a -> a | DataTyCtxt Name -- Theta part of a data decl -- data <S> => T a = MkT a {- -- Notes re TySynCtxt -- We allow type synonyms that aren't types; e.g. type List = [] -- -- If the RHS mentions tyvars that aren't in scope, we'll -- quantify over them: -- e.g. type T = a->a -- will become type T = forall a. a->a -- -- With gla-exts that's right, but for H98 we should complain. ************************************************************************ * * Untoucable type variables * * ************************************************************************ -} newtype TcLevel = TcLevel Int deriving( Eq ) -- See Note [TcLevel and untouchable type variables] for what this Int is {- Note [TcLevel and untouchable type variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Each unification variable (MetaTv) and each Implication has a level number (of type TcLevel) * INVARIANTS. In a tree of Implications, (ImplicInv) The level number of an Implication is STRICTLY GREATER THAN that of its parent (MetaTvInv) The level number of a unification variable is LESS THAN OR EQUAL TO that of its parent implication * A unification variable is *touchable* if its level number is EQUAL TO that of its immediate parent implication. * INVARIANT (GivenInv) The free variables of the ic_given of an implication are all untouchable; ie their level numbers are LESS THAN the ic_tclvl of the implication Note [Skolem escape prevention] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We only unify touchable unification variables. Because of (MetaTvInv), there can be no occurrences of he variable further out, so the unification can't cause the kolems to escape. Example: data T = forall a. MkT a (a->Int) f x (MkT v f) = length [v,x] We decide (x::alpha), and generate an implication like [1]forall a. (a ~ alpha[0]) But we must not unify alpha:=a, because the skolem would escape. For the cases where we DO want to unify, we rely on floating the equality. Example (with same T) g x (MkT v f) = x && True We decide (x::alpha), and generate an implication like [1]forall a. (Bool ~ alpha[0]) We do NOT unify directly, bur rather float out (if the constraint does not mention 'a') to get (Bool ~ alpha[0]) /\ [1]forall a.() and NOW we can unify alpha. The same idea of only unifying touchables solves another problem. Suppose we had (F Int ~ uf[0]) /\ [1](forall a. C a => F Int ~ beta[1]) In this example, beta is touchable inside the implication. The first solveSimpleWanteds step leaves 'uf' un-unified. Then we move inside the implication where a new constraint uf ~ beta emerges. If we (wrongly) spontaneously solved it to get uf := beta, the whole implication disappears but when we pop out again we are left with (F Int ~ uf) which will be unified by our final zonking stage and uf will get unified *once more* to (F Int). -} fskTcLevel :: TcLevel fskTcLevel = TcLevel 0 -- 0 = Outside the outermost level: -- flatten skolems topTcLevel :: TcLevel topTcLevel = TcLevel 1 -- 1 = outermost level pushTcLevel :: TcLevel -> TcLevel pushTcLevel (TcLevel us) = TcLevel (us+1) strictlyDeeperThan :: TcLevel -> TcLevel -> Bool strictlyDeeperThan (TcLevel tv_tclvl) (TcLevel ctxt_tclvl) = tv_tclvl > ctxt_tclvl sameDepthAs :: TcLevel -> TcLevel -> Bool sameDepthAs (TcLevel ctxt_tclvl) (TcLevel tv_tclvl) = ctxt_tclvl == tv_tclvl -- NB: invariant ctxt_tclvl >= tv_tclvl -- So <= would be equivalent checkTcLevelInvariant :: TcLevel -> TcLevel -> Bool -- Checks (MetaTvInv) from Note [TcLevel and untouchable type variables] checkTcLevelInvariant (TcLevel ctxt_tclvl) (TcLevel tv_tclvl) = ctxt_tclvl >= tv_tclvl instance Outputable TcLevel where ppr (TcLevel us) = ppr us {- ************************************************************************ * * Pretty-printing * * ************************************************************************ -} pprTcTyVarDetails :: TcTyVarDetails -> SDoc -- For debugging pprTcTyVarDetails (SkolemTv True) = ptext (sLit "ssk") pprTcTyVarDetails (SkolemTv False) = ptext (sLit "sk") pprTcTyVarDetails (RuntimeUnk {}) = ptext (sLit "rt") pprTcTyVarDetails (FlatSkol {}) = ptext (sLit "fsk") pprTcTyVarDetails (MetaTv { mtv_info = info, mtv_tclvl = tclvl }) = pp_info <> colon <> ppr tclvl where pp_info = case info of ReturnTv -> ptext (sLit "ret") TauTv True -> ptext (sLit "twc") TauTv False -> ptext (sLit "tau") SigTv -> ptext (sLit "sig") FlatMetaTv -> ptext (sLit "fuv") pprUserTypeCtxt :: UserTypeCtxt -> SDoc pprUserTypeCtxt (InfSigCtxt n) = ptext (sLit "the inferred type for") <+> quotes (ppr n) pprUserTypeCtxt (FunSigCtxt n) = ptext (sLit "the type signature for") <+> quotes (ppr n) pprUserTypeCtxt (RuleSigCtxt n) = ptext (sLit "a RULE for") <+> quotes (ppr n) pprUserTypeCtxt ExprSigCtxt = ptext (sLit "an expression type signature") pprUserTypeCtxt (ConArgCtxt c) = ptext (sLit "the type of the constructor") <+> quotes (ppr c) pprUserTypeCtxt (TySynCtxt c) = ptext (sLit "the RHS of the type synonym") <+> quotes (ppr c) pprUserTypeCtxt ThBrackCtxt = ptext (sLit "a Template Haskell quotation [t|...|]") pprUserTypeCtxt PatSigCtxt = ptext (sLit "a pattern type signature") pprUserTypeCtxt ResSigCtxt = ptext (sLit "a result type signature") pprUserTypeCtxt (ForSigCtxt n) = ptext (sLit "the foreign declaration for") <+> quotes (ppr n) pprUserTypeCtxt DefaultDeclCtxt = ptext (sLit "a type in a `default' declaration") pprUserTypeCtxt InstDeclCtxt = ptext (sLit "an instance declaration") pprUserTypeCtxt SpecInstCtxt = ptext (sLit "a SPECIALISE instance pragma") pprUserTypeCtxt GenSigCtxt = ptext (sLit "a type expected by the context") pprUserTypeCtxt GhciCtxt = ptext (sLit "a type in a GHCi command") pprUserTypeCtxt (ClassSCCtxt c) = ptext (sLit "the super-classes of class") <+> quotes (ppr c) pprUserTypeCtxt SigmaCtxt = ptext (sLit "the context of a polymorphic type") pprUserTypeCtxt (DataTyCtxt tc) = ptext (sLit "the context of the data type declaration for") <+> quotes (ppr tc) pprSigCtxt :: UserTypeCtxt -> SDoc -> SDoc -> SDoc -- (pprSigCtxt ctxt <extra> <type>) -- prints In <extra> the type signature for 'f': -- f :: <type> -- The <extra> is either empty or "the ambiguity check for" pprSigCtxt ctxt extra pp_ty = sep [ ptext (sLit "In") <+> extra <+> pprUserTypeCtxt ctxt <> colon , nest 2 (pp_sig ctxt) ] where pp_sig (FunSigCtxt n) = pp_n_colon n pp_sig (ConArgCtxt n) = pp_n_colon n pp_sig (ForSigCtxt n) = pp_n_colon n pp_sig _ = pp_ty pp_n_colon n = pprPrefixOcc n <+> dcolon <+> pp_ty {- ************************************************************************ * * Finding type family instances * * ************************************************************************ -} -- | Finds outermost type-family applications occuring in a type, -- after expanding synonyms. tcTyFamInsts :: Type -> [(TyCon, [Type])] tcTyFamInsts ty | Just exp_ty <- tcView ty = tcTyFamInsts exp_ty tcTyFamInsts (TyVarTy _) = [] tcTyFamInsts (TyConApp tc tys) | isTypeFamilyTyCon tc = [(tc, tys)] | otherwise = concat (map tcTyFamInsts tys) tcTyFamInsts (LitTy {}) = [] tcTyFamInsts (FunTy ty1 ty2) = tcTyFamInsts ty1 ++ tcTyFamInsts ty2 tcTyFamInsts (AppTy ty1 ty2) = tcTyFamInsts ty1 ++ tcTyFamInsts ty2 tcTyFamInsts (ForAllTy _ ty) = tcTyFamInsts ty {- ************************************************************************ * * The "exact" free variables of a type * * ************************************************************************ Note [Silly type synonym] ~~~~~~~~~~~~~~~~~~~~~~~~~ Consider type T a = Int What are the free tyvars of (T x)? Empty, of course! Here's the example that Ralf Laemmel showed me: foo :: (forall a. C u a -> C u a) -> u mappend :: Monoid u => u -> u -> u bar :: Monoid u => u bar = foo (\t -> t `mappend` t) We have to generalise at the arg to f, and we don't want to capture the constraint (Monad (C u a)) because it appears to mention a. Pretty silly, but it was useful to him. exactTyVarsOfType is used by the type checker to figure out exactly which type variables are mentioned in a type. It's also used in the smart-app checking code --- see TcExpr.tcIdApp On the other hand, consider a *top-level* definition f = (\x -> x) :: T a -> T a If we don't abstract over 'a' it'll get fixed to GHC.Prim.Any, and then if we have an application like (f "x") we get a confusing error message involving Any. So the conclusion is this: when generalising - at top level use tyVarsOfType - in nested bindings use exactTyVarsOfType See Trac #1813 for example. -} exactTyVarsOfType :: Type -> TyVarSet -- Find the free type variables (of any kind) -- but *expand* type synonyms. See Note [Silly type synonym] above. exactTyVarsOfType ty = go ty where go ty | Just ty' <- tcView ty = go ty' -- This is the key line go (TyVarTy tv) = unitVarSet tv go (TyConApp _ tys) = exactTyVarsOfTypes tys go (LitTy {}) = emptyVarSet go (FunTy arg res) = go arg `unionVarSet` go res go (AppTy fun arg) = go fun `unionVarSet` go arg go (ForAllTy tyvar ty) = delVarSet (go ty) tyvar exactTyVarsOfTypes :: [Type] -> TyVarSet exactTyVarsOfTypes = mapUnionVarSet exactTyVarsOfType {- ************************************************************************ * * Predicates * * ************************************************************************ -} isTouchableOrFmv :: TcLevel -> TcTyVar -> Bool isTouchableOrFmv ctxt_tclvl tv = ASSERT2( isTcTyVar tv, ppr tv ) case tcTyVarDetails tv of MetaTv { mtv_tclvl = tv_tclvl, mtv_info = info } -> ASSERT2( checkTcLevelInvariant ctxt_tclvl tv_tclvl, ppr tv $$ ppr tv_tclvl $$ ppr ctxt_tclvl ) case info of FlatMetaTv -> True _ -> tv_tclvl `sameDepthAs` ctxt_tclvl _ -> False isTouchableMetaTyVar :: TcLevel -> TcTyVar -> Bool isTouchableMetaTyVar ctxt_tclvl tv = ASSERT2( isTcTyVar tv, ppr tv ) case tcTyVarDetails tv of MetaTv { mtv_tclvl = tv_tclvl } -> ASSERT2( checkTcLevelInvariant ctxt_tclvl tv_tclvl, ppr tv $$ ppr tv_tclvl $$ ppr ctxt_tclvl ) tv_tclvl `sameDepthAs` ctxt_tclvl _ -> False isFloatedTouchableMetaTyVar :: TcLevel -> TcTyVar -> Bool isFloatedTouchableMetaTyVar ctxt_tclvl tv = ASSERT2( isTcTyVar tv, ppr tv ) case tcTyVarDetails tv of MetaTv { mtv_tclvl = tv_tclvl } -> tv_tclvl `strictlyDeeperThan` ctxt_tclvl _ -> False isImmutableTyVar :: TyVar -> Bool isImmutableTyVar tv | isTcTyVar tv = isSkolemTyVar tv | otherwise = True isTyConableTyVar, isSkolemTyVar, isOverlappableTyVar, isMetaTyVar, isAmbiguousTyVar, isFmvTyVar, isFskTyVar, isFlattenTyVar :: TcTyVar -> Bool isTyConableTyVar tv -- True of a meta-type variable that can be filled in -- with a type constructor application; in particular, -- not a SigTv = ASSERT( isTcTyVar tv) case tcTyVarDetails tv of MetaTv { mtv_info = SigTv } -> False _ -> True isFmvTyVar tv = ASSERT2( isTcTyVar tv, ppr tv ) case tcTyVarDetails tv of MetaTv { mtv_info = FlatMetaTv } -> True _ -> False -- | True of both given and wanted flatten-skolems (fak and usk) isFlattenTyVar tv = ASSERT2( isTcTyVar tv, ppr tv ) case tcTyVarDetails tv of FlatSkol {} -> True MetaTv { mtv_info = FlatMetaTv } -> True _ -> False -- | True of FlatSkol skolems only isFskTyVar tv = ASSERT2( isTcTyVar tv, ppr tv ) case tcTyVarDetails tv of FlatSkol {} -> True _ -> False isSkolemTyVar tv = ASSERT2( isTcTyVar tv, ppr tv ) case tcTyVarDetails tv of MetaTv {} -> False _other -> True isOverlappableTyVar tv = ASSERT( isTcTyVar tv ) case tcTyVarDetails tv of SkolemTv overlappable -> overlappable _ -> False isMetaTyVar tv = ASSERT2( isTcTyVar tv, ppr tv ) case tcTyVarDetails tv of MetaTv {} -> True _ -> False -- isAmbiguousTyVar is used only when reporting type errors -- It picks out variables that are unbound, namely meta -- type variables and the RuntimUnk variables created by -- RtClosureInspect.zonkRTTIType. These are "ambiguous" in -- the sense that they stand for an as-yet-unknown type isAmbiguousTyVar tv = ASSERT2( isTcTyVar tv, ppr tv ) case tcTyVarDetails tv of MetaTv {} -> True RuntimeUnk {} -> True _ -> False isMetaTyVarTy :: TcType -> Bool isMetaTyVarTy (TyVarTy tv) = isMetaTyVar tv isMetaTyVarTy _ = False metaTyVarInfo :: TcTyVar -> MetaInfo metaTyVarInfo tv = ASSERT( isTcTyVar tv ) case tcTyVarDetails tv of MetaTv { mtv_info = info } -> info _ -> pprPanic "metaTyVarInfo" (ppr tv) metaTyVarTcLevel :: TcTyVar -> TcLevel metaTyVarTcLevel tv = ASSERT( isTcTyVar tv ) case tcTyVarDetails tv of MetaTv { mtv_tclvl = tclvl } -> tclvl _ -> pprPanic "metaTyVarTcLevel" (ppr tv) metaTyVarTcLevel_maybe :: TcTyVar -> Maybe TcLevel metaTyVarTcLevel_maybe tv = ASSERT( isTcTyVar tv ) case tcTyVarDetails tv of MetaTv { mtv_tclvl = tclvl } -> Just tclvl _ -> Nothing setMetaTyVarTcLevel :: TcTyVar -> TcLevel -> TcTyVar setMetaTyVarTcLevel tv tclvl = ASSERT( isTcTyVar tv ) case tcTyVarDetails tv of details@(MetaTv {}) -> setTcTyVarDetails tv (details { mtv_tclvl = tclvl }) _ -> pprPanic "metaTyVarTcLevel" (ppr tv) isSigTyVar :: Var -> Bool isSigTyVar tv = ASSERT( isTcTyVar tv ) case tcTyVarDetails tv of MetaTv { mtv_info = SigTv } -> True _ -> False metaTvRef :: TyVar -> IORef MetaDetails metaTvRef tv = ASSERT2( isTcTyVar tv, ppr tv ) case tcTyVarDetails tv of MetaTv { mtv_ref = ref } -> ref _ -> pprPanic "metaTvRef" (ppr tv) isFlexi, isIndirect :: MetaDetails -> Bool isFlexi Flexi = True isFlexi _ = False isIndirect (Indirect _) = True isIndirect _ = False isRuntimeUnkSkol :: TyVar -> Bool -- Called only in TcErrors; see Note [Runtime skolems] there isRuntimeUnkSkol x | isTcTyVar x, RuntimeUnk <- tcTyVarDetails x = True | otherwise = False {- ************************************************************************ * * \subsection{Tau, sigma and rho} * * ************************************************************************ -} mkSigmaTy :: [TyVar] -> [PredType] -> Type -> Type mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkPhiTy theta tau) mkPhiTy :: [PredType] -> Type -> Type mkPhiTy theta ty = foldr mkFunTy ty theta mkTcEqPred :: TcType -> TcType -> Type -- During type checking we build equalities between -- type variables with OpenKind or ArgKind. Ultimately -- they will all settle, but we want the equality predicate -- itself to have kind '*'. I think. -- -- But for now we call mkTyConApp, not mkEqPred, because the invariants -- of the latter might not be satisfied during type checking. -- Notably when we form an equalty (a : OpenKind) ~ (Int : *) -- -- But this is horribly delicate: what about type variables -- that turn out to be bound to Int#? mkTcEqPred ty1 ty2 = mkTyConApp eqTyCon [k, ty1, ty2] where k = typeKind ty1 -- | Make a representational equality predicate mkTcReprEqPred :: TcType -> TcType -> Type mkTcReprEqPred ty1 ty2 = mkTyConApp coercibleTyCon [k, ty1, ty2] where k = typeKind ty1 -- | Make an equality predicate at a given role. The role must not be Phantom. mkTcEqPredRole :: Role -> TcType -> TcType -> Type mkTcEqPredRole Nominal = mkTcEqPred mkTcEqPredRole Representational = mkTcReprEqPred mkTcEqPredRole Phantom = panic "mkTcEqPredRole Phantom" -- @isTauTy@ tests for nested for-alls. It should not be called on a boxy type. isTauTy :: Type -> Bool isTauTy ty | Just ty' <- tcView ty = isTauTy ty' isTauTy (TyVarTy _) = True isTauTy (LitTy {}) = True isTauTy (TyConApp tc tys) = all isTauTy tys && isTauTyCon tc isTauTy (AppTy a b) = isTauTy a && isTauTy b isTauTy (FunTy a b) = isTauTy a && isTauTy b isTauTy (ForAllTy {}) = False isTauTyCon :: TyCon -> Bool -- Returns False for type synonyms whose expansion is a polytype isTauTyCon tc | Just (_, rhs) <- synTyConDefn_maybe tc = isTauTy rhs | otherwise = True --------------- getDFunTyKey :: Type -> OccName -- Get some string from a type, to be used to -- construct a dictionary function name getDFunTyKey ty | Just ty' <- tcView ty = getDFunTyKey ty' getDFunTyKey (TyVarTy tv) = getOccName tv getDFunTyKey (TyConApp tc _) = getOccName tc getDFunTyKey (LitTy x) = getDFunTyLitKey x getDFunTyKey (AppTy fun _) = getDFunTyKey fun getDFunTyKey (FunTy _ _) = getOccName funTyCon getDFunTyKey (ForAllTy _ t) = getDFunTyKey t getDFunTyLitKey :: TyLit -> OccName getDFunTyLitKey (NumTyLit n) = mkOccName Name.varName (show n) getDFunTyLitKey (StrTyLit n) = mkOccName Name.varName (show n) -- hm {- ************************************************************************ * * \subsection{Expanding and splitting} * * ************************************************************************ These tcSplit functions are like their non-Tc analogues, but *) they do not look through newtypes However, they are non-monadic and do not follow through mutable type variables. It's up to you to make sure this doesn't matter. -} tcSplitForAllTys :: Type -> ([TyVar], Type) tcSplitForAllTys ty = split ty ty [] where split orig_ty ty tvs | Just ty' <- tcView ty = split orig_ty ty' tvs split _ (ForAllTy tv ty) tvs = split ty ty (tv:tvs) split orig_ty _ tvs = (reverse tvs, orig_ty) tcIsForAllTy :: Type -> Bool tcIsForAllTy ty | Just ty' <- tcView ty = tcIsForAllTy ty' tcIsForAllTy (ForAllTy {}) = True tcIsForAllTy _ = False tcSplitPredFunTy_maybe :: Type -> Maybe (PredType, Type) -- Split off the first predicate argument from a type tcSplitPredFunTy_maybe ty | Just ty' <- tcView ty = tcSplitPredFunTy_maybe ty' tcSplitPredFunTy_maybe (FunTy arg res) | isPredTy arg = Just (arg, res) tcSplitPredFunTy_maybe _ = Nothing tcSplitPhiTy :: Type -> (ThetaType, Type) tcSplitPhiTy ty = split ty [] where split ty ts = case tcSplitPredFunTy_maybe ty of Just (pred, ty) -> split ty (pred:ts) Nothing -> (reverse ts, ty) tcSplitSigmaTy :: Type -> ([TyVar], ThetaType, Type) tcSplitSigmaTy ty = case tcSplitForAllTys ty of (tvs, rho) -> case tcSplitPhiTy rho of (theta, tau) -> (tvs, theta, tau) ----------------------- tcDeepSplitSigmaTy_maybe :: TcSigmaType -> Maybe ([TcType], [TyVar], ThetaType, TcSigmaType) -- Looks for a *non-trivial* quantified type, under zero or more function arrows -- By "non-trivial" we mean either tyvars or constraints are non-empty tcDeepSplitSigmaTy_maybe ty | Just (arg_ty, res_ty) <- tcSplitFunTy_maybe ty , Just (arg_tys, tvs, theta, rho) <- tcDeepSplitSigmaTy_maybe res_ty = Just (arg_ty:arg_tys, tvs, theta, rho) | (tvs, theta, rho) <- tcSplitSigmaTy ty , not (null tvs && null theta) = Just ([], tvs, theta, rho) | otherwise = Nothing ----------------------- tcTyConAppTyCon :: Type -> TyCon tcTyConAppTyCon ty = case tcSplitTyConApp_maybe ty of Just (tc, _) -> tc Nothing -> pprPanic "tcTyConAppTyCon" (pprType ty) tcTyConAppArgs :: Type -> [Type] tcTyConAppArgs ty = case tcSplitTyConApp_maybe ty of Just (_, args) -> args Nothing -> pprPanic "tcTyConAppArgs" (pprType ty) tcSplitTyConApp :: Type -> (TyCon, [Type]) tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of Just stuff -> stuff Nothing -> pprPanic "tcSplitTyConApp" (pprType ty) tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type]) tcSplitTyConApp_maybe ty | Just ty' <- tcView ty = tcSplitTyConApp_maybe ty' tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys) tcSplitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res]) -- Newtypes are opaque, so they may be split -- However, predicates are not treated -- as tycon applications by the type checker tcSplitTyConApp_maybe _ = Nothing ----------------------- tcSplitFunTys :: Type -> ([Type], Type) tcSplitFunTys ty = case tcSplitFunTy_maybe ty of Nothing -> ([], ty) Just (arg,res) -> (arg:args, res') where (args,res') = tcSplitFunTys res tcSplitFunTy_maybe :: Type -> Maybe (Type, Type) tcSplitFunTy_maybe ty | Just ty' <- tcView ty = tcSplitFunTy_maybe ty' tcSplitFunTy_maybe (FunTy arg res) | not (isPredTy arg) = Just (arg, res) tcSplitFunTy_maybe _ = Nothing -- Note the typeKind guard -- Consider (?x::Int) => Bool -- We don't want to treat this as a function type! -- A concrete example is test tc230: -- f :: () -> (?p :: ()) => () -> () -- -- g = f () () tcSplitFunTysN :: TcRhoType -> Arity -- N: Number of desired args -> ([TcSigmaType], -- Arg types (N or fewer) TcSigmaType) -- The rest of the type tcSplitFunTysN ty n_args | n_args == 0 = ([], ty) | Just (arg,res) <- tcSplitFunTy_maybe ty = case tcSplitFunTysN res (n_args - 1) of (args, res) -> (arg:args, res) | otherwise = ([], ty) tcSplitFunTy :: Type -> (Type, Type) tcSplitFunTy ty = expectJust "tcSplitFunTy" (tcSplitFunTy_maybe ty) tcFunArgTy :: Type -> Type tcFunArgTy ty = fst (tcSplitFunTy ty) tcFunResultTy :: Type -> Type tcFunResultTy ty = snd (tcSplitFunTy ty) ----------------------- tcSplitAppTy_maybe :: Type -> Maybe (Type, Type) tcSplitAppTy_maybe ty | Just ty' <- tcView ty = tcSplitAppTy_maybe ty' tcSplitAppTy_maybe ty = repSplitAppTy_maybe ty tcSplitAppTy :: Type -> (Type, Type) tcSplitAppTy ty = case tcSplitAppTy_maybe ty of Just stuff -> stuff Nothing -> pprPanic "tcSplitAppTy" (pprType ty) tcSplitAppTys :: Type -> (Type, [Type]) tcSplitAppTys ty = go ty [] where go ty args = case tcSplitAppTy_maybe ty of Just (ty', arg) -> go ty' (arg:args) Nothing -> (ty,args) ----------------------- tcGetTyVar_maybe :: Type -> Maybe TyVar tcGetTyVar_maybe ty | Just ty' <- tcView ty = tcGetTyVar_maybe ty' tcGetTyVar_maybe (TyVarTy tv) = Just tv tcGetTyVar_maybe _ = Nothing tcGetTyVar :: String -> Type -> TyVar tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty) tcIsTyVarTy :: Type -> Bool tcIsTyVarTy ty = isJust (tcGetTyVar_maybe ty) ----------------------- tcSplitDFunTy :: Type -> ([TyVar], [Type], Class, [Type]) -- Split the type of a dictionary function -- We don't use tcSplitSigmaTy, because a DFun may (with NDP) -- have non-Pred arguments, such as -- df :: forall m. (forall b. Eq b => Eq (m b)) -> C m -- -- Also NB splitFunTys, not tcSplitFunTys; -- the latter specifically stops at PredTy arguments, -- and we don't want to do that here tcSplitDFunTy ty = case tcSplitForAllTys ty of { (tvs, rho) -> case splitFunTys rho of { (theta, tau) -> case tcSplitDFunHead tau of { (clas, tys) -> (tvs, theta, clas, tys) }}} tcSplitDFunHead :: Type -> (Class, [Type]) tcSplitDFunHead = getClassPredTys tcInstHeadTyNotSynonym :: Type -> Bool -- Used in Haskell-98 mode, for the argument types of an instance head -- These must not be type synonyms, but everywhere else type synonyms -- are transparent, so we need a special function here tcInstHeadTyNotSynonym ty = case ty of TyConApp tc _ -> not (isTypeSynonymTyCon tc) _ -> True tcInstHeadTyAppAllTyVars :: Type -> Bool -- Used in Haskell-98 mode, for the argument types of an instance head -- These must be a constructor applied to type variable arguments. -- But we allow kind instantiations. tcInstHeadTyAppAllTyVars ty | Just ty' <- tcView ty -- Look through synonyms = tcInstHeadTyAppAllTyVars ty' | otherwise = case ty of TyConApp _ tys -> ok (filter (not . isKind) tys) -- avoid kinds FunTy arg res -> ok [arg, res] _ -> False where -- Check that all the types are type variables, -- and that each is distinct ok tys = equalLength tvs tys && hasNoDups tvs where tvs = mapMaybe get_tv tys get_tv (TyVarTy tv) = Just tv -- through synonyms get_tv _ = Nothing tcEqKind :: TcKind -> TcKind -> Bool tcEqKind = tcEqType tcEqType :: TcType -> TcType -> Bool -- tcEqType is a proper, sensible type-equality function, that does -- just what you'd expect The function Type.eqType (currently) has a -- grotesque hack that makes OpenKind = *, and that is NOT what we -- want in the type checker! Otherwise, for example, TcCanonical.reOrient -- thinks the LHS and RHS have the same kinds, when they don't, and -- fails to re-orient. That in turn caused Trac #8553. tcEqType ty1 ty2 = go init_env ty1 ty2 where init_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2)) go env t1 t2 | Just t1' <- tcView t1 = go env t1' t2 | Just t2' <- tcView t2 = go env t1 t2' go env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 == rnOccR env tv2 go _ (LitTy lit1) (LitTy lit2) = lit1 == lit2 go env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = go env (tyVarKind tv1) (tyVarKind tv2) && go (rnBndr2 env tv1 tv2) t1 t2 go env (AppTy s1 t1) (AppTy s2 t2) = go env s1 s2 && go env t1 t2 go env (FunTy s1 t1) (FunTy s2 t2) = go env s1 s2 && go env t1 t2 go env (TyConApp tc1 ts1) (TyConApp tc2 ts2) = (tc1 == tc2) && gos env ts1 ts2 go _ _ _ = False gos _ [] [] = True gos env (t1:ts1) (t2:ts2) = go env t1 t2 && gos env ts1 ts2 gos _ _ _ = False pickyEqType :: TcType -> TcType -> Bool -- Check when two types _look_ the same, _including_ synonyms. -- So (pickyEqType String [Char]) returns False pickyEqType ty1 ty2 = go init_env ty1 ty2 where init_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2)) go env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 == rnOccR env tv2 go _ (LitTy lit1) (LitTy lit2) = lit1 == lit2 go env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = go env (tyVarKind tv1) (tyVarKind tv2) && go (rnBndr2 env tv1 tv2) t1 t2 go env (AppTy s1 t1) (AppTy s2 t2) = go env s1 s2 && go env t1 t2 go env (FunTy s1 t1) (FunTy s2 t2) = go env s1 s2 && go env t1 t2 go env (TyConApp tc1 ts1) (TyConApp tc2 ts2) = (tc1 == tc2) && gos env ts1 ts2 go _ _ _ = False gos _ [] [] = True gos env (t1:ts1) (t2:ts2) = go env t1 t2 && gos env ts1 ts2 gos _ _ _ = False {- Note [Occurs check expansion] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (occurCheckExpand tv xi) expands synonyms in xi just enough to get rid of occurrences of tv outside type function arguments, if that is possible; otherwise, it returns Nothing. For example, suppose we have type F a b = [a] Then occurCheckExpand b (F Int b) = Just [Int] but occurCheckExpand a (F a Int) = Nothing We don't promise to do the absolute minimum amount of expanding necessary, but we try not to do expansions we don't need to. We prefer doing inner expansions first. For example, type F a b = (a, Int, a, [a]) type G b = Char We have occurCheckExpand b (F (G b)) = F Char even though we could also expand F to get rid of b. See also Note [occurCheckExpand] in TcCanonical -} data OccCheckResult a = OC_OK a | OC_Forall | OC_NonTyVar | OC_Occurs instance Functor OccCheckResult where fmap = liftM instance Applicative OccCheckResult where pure = return (<*>) = ap instance Monad OccCheckResult where return x = OC_OK x OC_OK x >>= k = k x OC_Forall >>= _ = OC_Forall OC_NonTyVar >>= _ = OC_NonTyVar OC_Occurs >>= _ = OC_Occurs occurCheckExpand :: DynFlags -> TcTyVar -> Type -> OccCheckResult Type -- See Note [Occurs check expansion] -- Check whether -- a) the given variable occurs in the given type. -- b) there is a forall in the type (unless we have -XImpredicativeTypes -- or it's a ReturnTv -- c) if it's a SigTv, ty should be a tyvar -- -- We may have needed to do some type synonym unfolding in order to -- get rid of the variable (or forall), so we also return the unfolded -- version of the type, which is guaranteed to be syntactically free -- of the given type variable. If the type is already syntactically -- free of the variable, then the same type is returned. occurCheckExpand dflags tv ty | MetaTv { mtv_info = SigTv } <- details = go_sig_tv ty | fast_check ty = return ty | otherwise = go ty where details = ASSERT2( isTcTyVar tv, ppr tv ) tcTyVarDetails tv impredicative = canUnifyWithPolyType dflags details (tyVarKind tv) -- Check 'ty' is a tyvar, or can be expanded into one go_sig_tv ty@(TyVarTy {}) = OC_OK ty go_sig_tv ty | Just ty' <- tcView ty = go_sig_tv ty' go_sig_tv _ = OC_NonTyVar -- True => fine fast_check (LitTy {}) = True fast_check (TyVarTy tv') = tv /= tv' fast_check (TyConApp _ tys) = all fast_check tys fast_check (FunTy arg res) = fast_check arg && fast_check res fast_check (AppTy fun arg) = fast_check fun && fast_check arg fast_check (ForAllTy tv' ty) = impredicative && fast_check (tyVarKind tv') && (tv == tv' || fast_check ty) go t@(TyVarTy tv') | tv == tv' = OC_Occurs | otherwise = return t go ty@(LitTy {}) = return ty go (AppTy ty1 ty2) = do { ty1' <- go ty1 ; ty2' <- go ty2 ; return (mkAppTy ty1' ty2') } go (FunTy ty1 ty2) = do { ty1' <- go ty1 ; ty2' <- go ty2 ; return (mkFunTy ty1' ty2') } go ty@(ForAllTy tv' body_ty) | not impredicative = OC_Forall | not (fast_check (tyVarKind tv')) = OC_Occurs -- Can't expand away the kinds unless we create -- fresh variables which we don't want to do at this point. -- In principle fast_check might fail because of a for-all -- but we don't yet have poly-kinded tyvars so I'm not -- going to worry about that now | tv == tv' = return ty | otherwise = do { body' <- go body_ty ; return (ForAllTy tv' body') } -- For a type constructor application, first try expanding away the -- offending variable from the arguments. If that doesn't work, next -- see if the type constructor is a type synonym, and if so, expand -- it and try again. go ty@(TyConApp tc tys) = case do { tys <- mapM go tys; return (mkTyConApp tc tys) } of OC_OK ty -> return ty -- First try to eliminate the tyvar from the args bad | Just ty' <- tcView ty -> go ty' | otherwise -> bad -- Failing that, try to expand a synonym canUnifyWithPolyType :: DynFlags -> TcTyVarDetails -> TcKind -> Bool canUnifyWithPolyType dflags details kind = case details of MetaTv { mtv_info = ReturnTv } -> True -- See Note [ReturnTv] MetaTv { mtv_info = SigTv } -> False MetaTv { mtv_info = TauTv _ } -> xopt Opt_ImpredicativeTypes dflags || isOpenTypeKind kind -- Note [OpenTypeKind accepts foralls] _other -> True -- We can have non-meta tyvars in given constraints {- Note [OpenTypeKind accepts foralls] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is a common paradigm: foo :: (forall a. a -> a) -> Int foo = error "urk" To make this work we need to instantiate 'error' with a polytype. A similar case is bar :: Bool -> (forall a. a->a) -> Int bar True = \x. (x 3) bar False = error "urk" Here we need to instantiate 'error' with a polytype. But 'error' has an OpenTypeKind type variable, precisely so that we can instantiate it with Int#. So we also allow such type variables to be instantiated with foralls. It's a bit of a hack, but seems straightforward. ************************************************************************ * * \subsection{Predicate types} * * ************************************************************************ Deconstructors and tests on predicate types -} isTyVarClassPred :: PredType -> Bool isTyVarClassPred ty = case getClassPredTys_maybe ty of Just (_, tys) -> all isTyVarTy tys _ -> False evVarPred_maybe :: EvVar -> Maybe PredType evVarPred_maybe v = if isPredTy ty then Just ty else Nothing where ty = varType v evVarPred :: EvVar -> PredType evVarPred var | debugIsOn = case evVarPred_maybe var of Just pred -> pred Nothing -> pprPanic "tcEvVarPred" (ppr var <+> ppr (varType var)) | otherwise = varType var -- Superclasses mkMinimalBySCs :: [PredType] -> [PredType] -- Remove predicates that can be deduced from others by superclasses mkMinimalBySCs ptys = [ ploc | ploc <- ptys , ploc `not_in_preds` rec_scs ] where rec_scs = concatMap trans_super_classes ptys not_in_preds p ps = not (any (eqPred p) ps) trans_super_classes pred -- Superclasses of pred, excluding pred itself = case classifyPredType pred of ClassPred cls tys -> transSuperClasses cls tys TuplePred ts -> concatMap trans_super_classes ts _ -> [] transSuperClasses :: Class -> [Type] -> [PredType] transSuperClasses cls tys -- Superclasses of (cls tys), -- excluding (cls tys) itself = concatMap trans_sc (immSuperClasses cls tys) where trans_sc :: PredType -> [PredType] -- (trans_sc p) returns (p : p's superclasses) trans_sc p = case classifyPredType p of ClassPred cls tys -> p : transSuperClasses cls tys TuplePred ps -> concatMap trans_sc ps _ -> [p] immSuperClasses :: Class -> [Type] -> [PredType] immSuperClasses cls tys = substTheta (zipTopTvSubst tyvars tys) sc_theta where (tyvars,sc_theta,_,_) = classBigSig cls {- ************************************************************************ * * \subsection{Predicates} * * ************************************************************************ -} isSigmaTy :: TcType -> Bool -- isSigmaTy returns true of any qualified type. It doesn't -- *necessarily* have any foralls. E.g -- f :: (?x::Int) => Int -> Int isSigmaTy ty | Just ty' <- tcView ty = isSigmaTy ty' isSigmaTy (ForAllTy _ _) = True isSigmaTy (FunTy a _) = isPredTy a isSigmaTy _ = False isRhoTy :: TcType -> Bool -- True of TcRhoTypes; see Note [TcRhoType] isRhoTy ty | Just ty' <- tcView ty = isRhoTy ty' isRhoTy (ForAllTy {}) = False isRhoTy (FunTy a r) = not (isPredTy a) && isRhoTy r isRhoTy _ = True isOverloadedTy :: Type -> Bool -- Yes for a type of a function that might require evidence-passing -- Used only by bindLocalMethods isOverloadedTy ty | Just ty' <- tcView ty = isOverloadedTy ty' isOverloadedTy (ForAllTy _ ty) = isOverloadedTy ty isOverloadedTy (FunTy a _) = isPredTy a isOverloadedTy _ = False isFloatTy, isDoubleTy, isIntegerTy, isIntTy, isWordTy, isBoolTy, isUnitTy, isCharTy, isAnyTy :: Type -> Bool isFloatTy = is_tc floatTyConKey isDoubleTy = is_tc doubleTyConKey isIntegerTy = is_tc integerTyConKey isIntTy = is_tc intTyConKey isWordTy = is_tc wordTyConKey isBoolTy = is_tc boolTyConKey isUnitTy = is_tc unitTyConKey isCharTy = is_tc charTyConKey isAnyTy = is_tc anyTyConKey isStringTy :: Type -> Bool isStringTy ty = case tcSplitTyConApp_maybe ty of Just (tc, [arg_ty]) -> tc == listTyCon && isCharTy arg_ty _ -> False is_tc :: Unique -> Type -> Bool -- Newtypes are opaque to this is_tc uniq ty = case tcSplitTyConApp_maybe ty of Just (tc, _) -> uniq == getUnique tc Nothing -> False -- | Does the given tyvar appear in the given type outside of any -- non-newtypes? Assume we're looking for @a@. Says "yes" for -- @a@, @N a@, @b a@, @a b@, @b (N a)@. Says "no" for -- @[a]@, @Maybe a@, @T a@, where @N@ is a newtype and @T@ is a datatype. isTyVarExposed :: TcTyVar -> TcType -> Bool isTyVarExposed tv (TyVarTy tv') = tv == tv' isTyVarExposed tv (TyConApp tc tys) | isNewTyCon tc = any (isTyVarExposed tv) tys | otherwise = False isTyVarExposed _ (LitTy {}) = False isTyVarExposed _ (FunTy {}) = False isTyVarExposed tv (AppTy fun arg) = isTyVarExposed tv fun || isTyVarExposed tv arg isTyVarExposed _ (ForAllTy {}) = False {- ************************************************************************ * * \subsection{Misc} * * ************************************************************************ -} deNoteType :: Type -> Type -- Remove all *outermost* type synonyms and other notes deNoteType ty | Just ty' <- tcView ty = deNoteType ty' deNoteType ty = ty tcTyVarsOfType :: Type -> TcTyVarSet -- Just the *TcTyVars* free in the type -- (Types.tyVarsOfTypes finds all free TyVars) tcTyVarsOfType (TyVarTy tv) = if isTcTyVar tv then unitVarSet tv else emptyVarSet tcTyVarsOfType (TyConApp _ tys) = tcTyVarsOfTypes tys tcTyVarsOfType (LitTy {}) = emptyVarSet tcTyVarsOfType (FunTy arg res) = tcTyVarsOfType arg `unionVarSet` tcTyVarsOfType res tcTyVarsOfType (AppTy fun arg) = tcTyVarsOfType fun `unionVarSet` tcTyVarsOfType arg tcTyVarsOfType (ForAllTy tyvar ty) = tcTyVarsOfType ty `delVarSet` tyvar -- We do sometimes quantify over skolem TcTyVars tcTyVarsOfTypes :: [Type] -> TyVarSet tcTyVarsOfTypes = mapUnionVarSet tcTyVarsOfType {- Find the free tycons and classes of a type. This is used in the front end of the compiler. -} orphNamesOfTyCon :: TyCon -> NameSet orphNamesOfTyCon tycon = unitNameSet (getName tycon) `unionNameSet` case tyConClass_maybe tycon of Nothing -> emptyNameSet Just cls -> unitNameSet (getName cls) orphNamesOfType :: Type -> NameSet orphNamesOfType ty | Just ty' <- tcView ty = orphNamesOfType ty' -- Look through type synonyms (Trac #4912) orphNamesOfType (TyVarTy _) = emptyNameSet orphNamesOfType (LitTy {}) = emptyNameSet orphNamesOfType (TyConApp tycon tys) = orphNamesOfTyCon tycon `unionNameSet` orphNamesOfTypes tys orphNamesOfType (FunTy arg res) = orphNamesOfTyCon funTyCon -- NB! See Trac #8535 `unionNameSet` orphNamesOfType arg `unionNameSet` orphNamesOfType res orphNamesOfType (AppTy fun arg) = orphNamesOfType fun `unionNameSet` orphNamesOfType arg orphNamesOfType (ForAllTy _ ty) = orphNamesOfType ty orphNamesOfThings :: (a -> NameSet) -> [a] -> NameSet orphNamesOfThings f = foldr (unionNameSet . f) emptyNameSet orphNamesOfTypes :: [Type] -> NameSet orphNamesOfTypes = orphNamesOfThings orphNamesOfType orphNamesOfDFunHead :: Type -> NameSet -- Find the free type constructors and classes -- of the head of the dfun instance type -- The 'dfun_head_type' is because of -- instance Foo a => Baz T where ... -- The decl is an orphan if Baz and T are both not locally defined, -- even if Foo *is* locally defined orphNamesOfDFunHead dfun_ty = case tcSplitSigmaTy dfun_ty of (_, _, head_ty) -> orphNamesOfType head_ty orphNamesOfCo :: Coercion -> NameSet orphNamesOfCo (Refl _ ty) = orphNamesOfType ty orphNamesOfCo (TyConAppCo _ tc cos) = unitNameSet (getName tc) `unionNameSet` orphNamesOfCos cos orphNamesOfCo (AppCo co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2 orphNamesOfCo (ForAllCo _ co) = orphNamesOfCo co orphNamesOfCo (CoVarCo _) = emptyNameSet orphNamesOfCo (AxiomInstCo con _ cos) = orphNamesOfCoCon con `unionNameSet` orphNamesOfCos cos orphNamesOfCo (UnivCo _ _ ty1 ty2) = orphNamesOfType ty1 `unionNameSet` orphNamesOfType ty2 orphNamesOfCo (SymCo co) = orphNamesOfCo co orphNamesOfCo (TransCo co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2 orphNamesOfCo (NthCo _ co) = orphNamesOfCo co orphNamesOfCo (LRCo _ co) = orphNamesOfCo co orphNamesOfCo (InstCo co ty) = orphNamesOfCo co `unionNameSet` orphNamesOfType ty orphNamesOfCo (SubCo co) = orphNamesOfCo co orphNamesOfCo (AxiomRuleCo _ ts cs) = orphNamesOfTypes ts `unionNameSet` orphNamesOfCos cs orphNamesOfCos :: [Coercion] -> NameSet orphNamesOfCos = orphNamesOfThings orphNamesOfCo orphNamesOfCoCon :: CoAxiom br -> NameSet orphNamesOfCoCon (CoAxiom { co_ax_tc = tc, co_ax_branches = branches }) = orphNamesOfTyCon tc `unionNameSet` orphNamesOfCoAxBranches branches orphNamesOfCoAxBranches :: BranchList CoAxBranch br -> NameSet orphNamesOfCoAxBranches = brListFoldr (unionNameSet . orphNamesOfCoAxBranch) emptyNameSet orphNamesOfCoAxBranch :: CoAxBranch -> NameSet orphNamesOfCoAxBranch (CoAxBranch { cab_lhs = lhs, cab_rhs = rhs }) = orphNamesOfTypes lhs `unionNameSet` orphNamesOfType rhs {- ************************************************************************ * * \subsection[TysWiredIn-ext-type]{External types} * * ************************************************************************ The compiler's foreign function interface supports the passing of a restricted set of types as arguments and results (the restricting factor being the ) -} tcSplitIOType_maybe :: Type -> Maybe (TyCon, Type) -- (tcSplitIOType_maybe t) returns Just (IO,t',co) -- if co : t ~ IO t' -- returns Nothing otherwise tcSplitIOType_maybe ty = case tcSplitTyConApp_maybe ty of Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey -> Just (io_tycon, io_res_ty) _ -> Nothing isFFITy :: Type -> Bool -- True for any TyCon that can possibly be an arg or result of an FFI call isFFITy ty = isValid (checkRepTyCon legalFFITyCon ty empty) isFFIArgumentTy :: DynFlags -> Safety -> Type -> Validity -- Checks for valid argument type for a 'foreign import' isFFIArgumentTy dflags safety ty = checkRepTyCon (legalOutgoingTyCon dflags safety) ty empty isFFIExternalTy :: Type -> Validity -- Types that are allowed as arguments of a 'foreign export' isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty empty isFFIImportResultTy :: DynFlags -> Type -> Validity isFFIImportResultTy dflags ty = checkRepTyCon (legalFIResultTyCon dflags) ty empty isFFIExportResultTy :: Type -> Validity isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty empty isFFIDynTy :: Type -> Type -> Validity -- The type in a foreign import dynamic must be Ptr, FunPtr, or a newtype of -- either, and the wrapped function type must be equal to the given type. -- We assume that all types have been run through normaliseFfiType, so we don't -- need to worry about expanding newtypes here. isFFIDynTy expected ty -- Note [Foreign import dynamic] -- In the example below, expected would be 'CInt -> IO ()', while ty would -- be 'FunPtr (CDouble -> IO ())'. | Just (tc, [ty']) <- splitTyConApp_maybe ty , tyConUnique tc `elem` [ptrTyConKey, funPtrTyConKey] , eqType ty' expected = IsValid | otherwise = NotValid (vcat [ ptext (sLit "Expected: Ptr/FunPtr") <+> pprParendType expected <> comma , ptext (sLit " Actual:") <+> ppr ty ]) isFFILabelTy :: Type -> Validity -- The type of a foreign label must be Ptr, FunPtr, or a newtype of either. isFFILabelTy ty = checkRepTyCon ok ty extra where ok tc = tc `hasKey` funPtrTyConKey || tc `hasKey` ptrTyConKey extra = ptext (sLit "A foreign-imported address (via &foo) must have type (Ptr a) or (FunPtr a)") isFFIPrimArgumentTy :: DynFlags -> Type -> Validity -- Checks for valid argument type for a 'foreign import prim' -- Currently they must all be simple unlifted types, or the well-known type -- Any, which can be used to pass the address to a Haskell object on the heap to -- the foreign function. isFFIPrimArgumentTy dflags ty | isAnyTy ty = IsValid | otherwise = checkRepTyCon (legalFIPrimArgTyCon dflags) ty empty isFFIPrimResultTy :: DynFlags -> Type -> Validity -- Checks for valid result type for a 'foreign import prim' -- Currently it must be an unlifted type, including unboxed tuples. isFFIPrimResultTy dflags ty = checkRepTyCon (legalFIPrimResultTyCon dflags) ty empty isFunPtrTy :: Type -> Bool isFunPtrTy ty = isValid (checkRepTyCon (`hasKey` funPtrTyConKey) ty empty) -- normaliseFfiType gets run before checkRepTyCon, so we don't -- need to worry about looking through newtypes or type functions -- here; that's already been taken care of. checkRepTyCon :: (TyCon -> Bool) -> Type -> SDoc -> Validity checkRepTyCon check_tc ty extra = case splitTyConApp_maybe ty of Just (tc, tys) | isNewTyCon tc -> NotValid (hang msg 2 (mk_nt_reason tc tys $$ nt_fix)) | check_tc tc -> IsValid | otherwise -> NotValid (msg $$ extra) Nothing -> NotValid (quotes (ppr ty) <+> ptext (sLit "is not a data type") $$ extra) where msg = quotes (ppr ty) <+> ptext (sLit "cannot be marshalled in a foreign call") mk_nt_reason tc tys | null tys = ptext (sLit "because its data construtor is not in scope") | otherwise = ptext (sLit "because the data construtor for") <+> quotes (ppr tc) <+> ptext (sLit "is not in scope") nt_fix = ptext (sLit "Possible fix: import the data constructor to bring it into scope") {- Note [Foreign import dynamic] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A dynamic stub must be of the form 'FunPtr ft -> ft' where ft is any foreign type. Similarly, a wrapper stub must be of the form 'ft -> IO (FunPtr ft)'. We use isFFIDynTy to check whether a signature is well-formed. For example, given a (illegal) declaration like: foreign import ccall "dynamic" foo :: FunPtr (CDouble -> IO ()) -> CInt -> IO () isFFIDynTy will compare the 'FunPtr' type 'CDouble -> IO ()' with the curried result type 'CInt -> IO ()', and return False, as they are not equal. ---------------------------------------------- These chaps do the work; they are not exported ---------------------------------------------- -} legalFEArgTyCon :: TyCon -> Bool legalFEArgTyCon tc -- It's illegal to make foreign exports that take unboxed -- arguments. The RTS API currently can't invoke such things. --SDM 7/2000 = boxedMarshalableTyCon tc legalFIResultTyCon :: DynFlags -> TyCon -> Bool legalFIResultTyCon dflags tc | tc == unitTyCon = True | otherwise = marshalableTyCon dflags tc legalFEResultTyCon :: TyCon -> Bool legalFEResultTyCon tc | tc == unitTyCon = True | otherwise = boxedMarshalableTyCon tc legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool -- Checks validity of types going from Haskell -> external world legalOutgoingTyCon dflags _ tc = marshalableTyCon dflags tc legalFFITyCon :: TyCon -> Bool -- True for any TyCon that can possibly be an arg or result of an FFI call legalFFITyCon tc | isUnLiftedTyCon tc = True | tc == unitTyCon = True | otherwise = boxedMarshalableTyCon tc marshalableTyCon :: DynFlags -> TyCon -> Bool marshalableTyCon dflags tc | (xopt Opt_UnliftedFFITypes dflags && isUnLiftedTyCon tc && not (isUnboxedTupleTyCon tc) && case tyConPrimRep tc of -- Note [Marshalling VoidRep] VoidRep -> False _ -> True) = True | otherwise = boxedMarshalableTyCon tc boxedMarshalableTyCon :: TyCon -> Bool boxedMarshalableTyCon tc | getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey , int32TyConKey, int64TyConKey , wordTyConKey, word8TyConKey, word16TyConKey , word32TyConKey, word64TyConKey , floatTyConKey, doubleTyConKey , ptrTyConKey, funPtrTyConKey , charTyConKey , stablePtrTyConKey , boolTyConKey ] = True | otherwise = False legalFIPrimArgTyCon :: DynFlags -> TyCon -> Bool -- Check args of 'foreign import prim', only allow simple unlifted types. -- Strictly speaking it is unnecessary to ban unboxed tuples here since -- currently they're of the wrong kind to use in function args anyway. legalFIPrimArgTyCon dflags tc | xopt Opt_UnliftedFFITypes dflags && isUnLiftedTyCon tc && not (isUnboxedTupleTyCon tc) = True | otherwise = False legalFIPrimResultTyCon :: DynFlags -> TyCon -> Bool -- Check result type of 'foreign import prim'. Allow simple unlifted -- types and also unboxed tuple result types '... -> (# , , #)' legalFIPrimResultTyCon dflags tc | xopt Opt_UnliftedFFITypes dflags && isUnLiftedTyCon tc && (isUnboxedTupleTyCon tc || case tyConPrimRep tc of -- Note [Marshalling VoidRep] VoidRep -> False _ -> True) = True | otherwise = False {- Note [Marshalling VoidRep] ~~~~~~~~~~~~~~~~~~~~~~~~~~ We don't treat State# (whose PrimRep is VoidRep) as marshalable. In turn that means you can't write foreign import foo :: Int -> State# RealWorld Reason: the back end falls over with panic "primRepHint:VoidRep"; and there is no compelling reason to permit it -}
bitemyapp/ghc
compiler/typecheck/TcType.hs
bsd-3-clause
66,783
0
14
17,825
12,208
6,389
5,819
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Main where import Control.Monad import Control.Monad.Primitive import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BSC import Data.Maybe import Data.Time.Clock import Data.Time.Format import Options.Applicative import Pipes import qualified Pipes.ByteString as P (toHandle) import Pipes.Csv import qualified Pipes.Prelude as P hiding (toHandle) import System.IO import System.Locale import System.Random.MWC import System.Random.MWC.Distributions import Conversion import Parsing import Types import Util -- | We roughly model the balloon system stepwise -- TimeStamps -> Some constant time step -- Location -> Basic brownian-like motion with a tendency -- Temperature -> Minor fluctuations each step -- Observatory -> Each step send to observatories within a set range -- Data Quality -> Randomly have it such that an observatory logs poorly -- We spread the values using a normal distribution -- All values must be non-negative bar the location drift values and time -- steps. Negative time steps can be used to simulate out-of-order data data GenSettings = GenSettings { genStartTime :: TimeStamp -- Initial TimeStamp for generated data , genTimeStep :: Double -- Average timestep in minutes , genLocStepX :: Double -- Average x-coord distance to travel per timestep , genLocStepY :: Double -- Average y-coord distance to travel per timestep , genTempStep :: Double -- Variance in temperature for each timestep , genBalloonRange :: Double -- Range of balloon broadcast , genFailRate :: Double -- Failure rate at which to generate invalid data , genSystemSize :: Int -- Size of the system , genNumLines :: Int -- Number of lines to generate , genFile :: FilePath -- File to write output to } parseGenSettings :: Parser GenSettings parseGenSettings = GenSettings <$> option auto ( long "start-time" <> short 's' <> value defaultStartTime <> metavar "START_TIME" <> help ("Time to start generating data from in format: " <> tsFormat)) <*> option auto ( long "time-step" <> short 't' <> value defaultTimeStep <> metavar "TIME_STEP" <> help "Average time step in minutes") <*> option auto ( long "x-drift" <> short 'x' <> value defaultLocXStep <> metavar "X_DRIFT" <> help "Average x-coord drift per time step in metres") <*> option auto ( long "y-drift" <> short 'y' <> value defaultLocYStep <> metavar "Y_DRIFT" <> help "Average y-coord drift per time step in metres") <*> (nonNegative "temp-variance" <$> option auto ( long "temp-variance" <> short 'p' <> value defaultTempStep <> metavar "TEMP_VARIANCE" <> help "Variance in temperature in kelvin")) <*> pure defaultBalloonRange <*> (nonNegative "fail-rate" <$> option auto ( long "fail-rate" <> short 'r' <> value defaultFailRate <> metavar "FAIL_RATE" <> help "Rate at which observatories produce rubbish output [0,1)")) <*> pure defaultSystemSize <*> option auto ( long "num-lines" <> short 'n' <> value defaultNumLines <> metavar "NUM_LINES" <> help "Number of lines to output") <*> strOption ( long "output-file" <> short 'f' <> value defaultOutputFile <> metavar "OUTPUT_FILE" <> help "File to output generated data to") nonNegative :: String -> Double -> Double nonNegative name x = if x >= 0 then x else error (name ++ " must be non-negative") defaultStartTime :: TimeStamp defaultTimeStep, defaultLocXStep, defaultLocYStep, defaultTempStep, defaultBalloonRange, defaultFailRate :: Double defaultSystemSize, defaultNumLines :: Int defaultOutputFile :: String defaultStartTime = TimeStamp $ fromJust $ parseTime defaultTimeLocale tsFormat "2014-06-08T10:30" defaultTimeStep = 15 defaultLocXStep = 1200 defaultLocYStep = -1800 defaultTempStep = 0.1 defaultBalloonRange = 30000 defaultFailRate = 0.08 defaultSystemSize = 100000 defaultNumLines = 100000 defaultOutputFile = "gen-weather-sample.csv" data ObservatoryOutput = Valid LogLine | Invalid ByteString instance ToRecord ObservatoryOutput where toRecord (Valid ll) = toRecord ll toRecord (Invalid x) = toRecord [x] -- We use Metres and Kelvin for the System internally data System = System { systemTime :: TimeStamp , balloonLoc :: Location , balloonRange :: Double , systemTemp :: Temperature , systemObss :: [(Observatory, Location)] , systemSize :: Int } type Mutator x = Gen (PrimState IO) -> x -> IO x data Mutators = Mutators { mutTime :: Mutator TimeStamp , mutLoc :: Mutator Location , mutTemp :: Mutator Temperature , mutLine :: Mutator ObservatoryOutput } observatoryLocs :: [(Observatory, Location)] observatoryLocs = [ (Observatory "AU", Location 10000 10000) , (Observatory "FR", Location 80000 40000) , (Observatory "US", Location 30000 50000) , (Observatory "NZ", Location 10000 30000) ] initialise :: GenSettings -> (Mutators, System) initialise GenSettings{..} = let mutTime g (TimeStamp x) = do v <- normal genTimeStep (genTimeStep / 4) g return $ TimeStamp $ addUTCTime (fromIntegral $ floor $ v * 60) x mutLoc g (Location x y) = do dx <- normal genLocStepX (abs genLocStepX / 4) g dy <- normal genLocStepY (abs genLocStepY / 4) g let x' = genSystemSize + x + round (dx :: Double) let y' = genSystemSize + y + round dy return $ Location (x' `mod` genSystemSize) (y' `mod` genSystemSize) mutTemp g x = do dx <- normal 0 genTempStep g return $ x + round dx mutLine g x = do c <- uniform g return $ if c < genFailRate then Invalid "th1s1s1nv4l1d" else x systemTime = genStartTime balloonLoc = Location (genSystemSize `div` 2) (genSystemSize `div` 2) balloonRange = genBalloonRange systemTemp = 300 systemObss = observatoryLocs systemSize = genSystemSize in (Mutators{..}, System{..}) stepSystem :: GenIO -> Mutators -> System -> IO System stepSystem g Mutators{..} System{..} = do newTime <- mutTime g systemTime newLoc <- mutLoc g balloonLoc newTemp <- mutTemp g systemTemp return $ System newTime newLoc balloonRange newTemp systemObss systemSize runSystem :: GenIO -> Mutators -> System -> Producer System IO () runSystem g m s = do yield s s' <- liftIO $ stepSystem g m s runSystem g m s' outputSystem :: GenIO -> Mutators -> Pipe System ByteString IO () outputSystem g Mutators{..} = forever $ do System{..} <- await let systemBounds = Location systemSize systemSize let inBounds x = distanceSquared (Just systemBounds) balloonLoc x < (balloonRange * balloonRange) let inRange = filter (inBounds . snd) systemObss let obsLine = LogLine systemTime balloonLoc systemTemp let rawLines = map (Valid . convertMetreKelvinToObservatory . obsLine . fst) inRange logLines <- liftIO $ mapM (mutLine g) rawLines -- We filter because Data.Csv is fickle when dealing with commas regardless of delimeter -- A custom encoder might be faster, but current speed seems more than adequate each logLines >-> encodeWith weatherEncodeOptions >-> P.map (BSC.filter (/= '"')) main :: IO () main = do settings <- execParser (info parseGenSettings fullDesc) g <- createSystemRandom let (m, s) = initialise settings withFile (genFile settings) WriteMode $ \h -> runEffect $ runSystem g m s >-> outputSystem g m >-> P.take (genNumLines settings) >-> P.toHandle h
oswynb/weather
src/Generate.hs
bsd-3-clause
8,414
0
21
2,418
1,952
1,015
937
179
2
{-# LANGUAGE FlexibleContexts #-} module Reduction where import Obsidian import Prelude hiding (zipWith) import Control.Monad import Data.Word --------------------------------------------------------------------------- -- reduceLocalSilly --------------------------------------------------------------------------- sumUp :: Pull Word32 EWord32 -> EWord32 sumUp arr | len arr == 1 = arr ! 0 | otherwise = let (a1,a2) = halve arr arr' = zipWith (+) a1 a2 in sumUp arr' sumUp' :: Pull Word32 EWord32 -> Program Block EWord32 sumUp' arr | len arr == 1 = return (arr ! 0) | otherwise = do let (a1,a2) = halve arr arr' <- forcePull (zipWith (+) a1 a2) sumUp' arr' sumUpT :: Pull Word32 EWord32 -> Program Thread EWord32 sumUpT arr | len arr == 1 = return (arr ! 0) | otherwise = do let (a1,a2) = halve arr arr' <- forcePull (zipWith (+) a1 a2) sumUpT arr' mapSumUp :: Pull EWord32 (SPull EWord32) -> Push Grid EWord32 EWord32 mapSumUp arr = pConcat (fmap body arr) where body arr = singletonPush (return (sumUp arr)) mapSumUp' :: Pull EWord32 (SPull EWord32) -> Push Grid EWord32 EWord32 mapSumUp' arr = pConcat (fmap body arr) where body arr = singletonPush (sumUp' arr) -- {{{0,1,2,3,4,5,6,7}},{{8,9,10,11,12,13,14,15}}} mapSumUpT :: Pull EWord32 (SPull (SPull EWord32)) -> Push Grid EWord32 EWord32 mapSumUpT arr = pConcat (fmap body arr) where body arr = tConcat (fmap bodyThread arr) bodyThread arr = singletonPush (sumUpT arr) --------------------------------------------------------------------------- -- --------------------------------------------------------------------------- reduceLocal :: (Forceable t, Storable a, Pushable t ) => (a -> a -> a) -> SPull a -> Program t (SPush t a) reduceLocal f arr | len arr == 1 = return $ push arr | otherwise = do let (a1,a2) = halve arr arr' <- force $ push $ zipWith f a1 a2 reduceLocal f arr' reduceLocal' :: (Forceable t, Storable a, Pushable t ) => (a -> a -> a) -> SPull a -> Program t a reduceLocal' f arr | len arr == 1 = return (arr ! 0) | otherwise = do let (a1,a2) = halve arr arr' <- force $ push $ zipWith f a1 a2 reduceLocal' f arr' -- local = pJoin reduceBlocks :: Storable a => (a -> a -> a) -> SPull a -> Program Block a reduceBlocks f arr = do imm <- force $ pConcat (fmap body (splitUp 32 arr)) reduceLocal' f imm where body arr = singletonPush (reduceLocal' f arr) reduceGrid :: Storable a => (a -> a -> a) -> DPull a -> DPush Grid a reduceGrid f arr = pConcat $ fmap body (splitUp 4096 arr) where body arr = singletonPush (reduceBlocks f arr) reduce :: Storable a => (a -> a -> a) -> DPull a -> DPush Grid a reduce = reduceGrid -- reduce :: MemoryOps a -- => (a -> a -> a) -- -> DPull a -> DPush Grid a -- -- reduce f = pConcatMap $ pJoin . liftM push . reduceLocal f -- reduce f arr = pConcat (fmap (reduceLocal f) (splitUp 256 arr)) -- reduceExperiment :: MemoryOps a -- => (a -> a -> a) -- -> DPull a -> DPush Grid a -- reduceExperiment f arr = -- pJoin $ do -- imm <- force <- pConcat $ fmap (reduceWarps f) (splitUp 256 arr) -- -- imm :: SPull (SPush a) -- undefined -- pConcat (fmap (reduceLocal f) imm ) input :: DPull EInt32 input = undefinedGlobal (variable "X") -- getReduce = putStrLn $ genKernel "reduce" (reduce (+) . splitUp 256) (input :- ())
svenssonjoel/ObsidianGFX
Examples/Simple/Reduction.hs
bsd-3-clause
3,701
0
13
1,047
1,127
551
576
78
1
{-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module Reflex.Dom.Builder.InputDisabled where import Control.Lens import Control.Monad.Fix import Control.Monad.Ref import Control.Monad.Trans import Control.Monad.Trans.Control import qualified Data.Map as Map import Foreign.JavaScript.TH import Reflex import Reflex.Deletable.Class import Reflex.Dom.Builder.Class import Reflex.Host.Class -- | A DomBuilder transformer that disables all 'inputElement's, -- 'textAreaElement's, and 'selectElement's by adding the "disabled" HTML -- attribute. Note that 'element's that happen to have "input", "textarea", or -- "select" as their tag will NOT be disabled. newtype InputDisabledT m a = InputDisabledT { runInputDisabledT :: m a } deriving (Functor, Applicative, Monad, MonadAtomicRef, MonadFix, MonadIO) deriving instance MonadSample t m => MonadSample t (InputDisabledT m) deriving instance MonadHold t m => MonadHold t (InputDisabledT m) instance MonadTrans InputDisabledT where lift = InputDisabledT instance MonadTransControl InputDisabledT where type StT InputDisabledT a = a liftWith f = InputDisabledT $ f runInputDisabledT restoreT = InputDisabledT instance MonadRef m => MonadRef (InputDisabledT m) where type Ref (InputDisabledT m) = Ref m newRef = lift . newRef readRef = lift . readRef writeRef ref = lift . writeRef ref instance PerformEvent t m => PerformEvent t (InputDisabledT m) where type Performable (InputDisabledT m) = Performable m performEvent_ = lift . performEvent_ performEvent = lift . performEvent disableElementConfig :: Reflex t => ElementConfig er t m -> ElementConfig er t m disableElementConfig cfg = cfg { _elementConfig_initialAttributes = Map.insert "disabled" "disabled" $ _elementConfig_initialAttributes cfg , _elementConfig_modifyAttributes = Map.delete "disabled" <$> _elementConfig_modifyAttributes cfg } instance Deletable t m => Deletable t (InputDisabledT m) where deletable d = liftThrough $ deletable d instance PostBuild t m => PostBuild t (InputDisabledT m) where getPostBuild = lift getPostBuild deriving instance TriggerEvent t m => TriggerEvent t (InputDisabledT m) instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (InputDisabledT m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger f = lift $ newFanEventWithTrigger f instance DomBuilder t m => DomBuilder t (InputDisabledT m) where type DomBuilderSpace (InputDisabledT m) = DomBuilderSpace m placeholder cfg = lift $ placeholder $ cfg & placeholderConfig_insertAbove %~ fmap runInputDisabledT inputElement cfg = lift $ inputElement $ cfg { _inputElementConfig_elementConfig = liftElementConfig $ disableElementConfig $ _inputElementConfig_elementConfig cfg } textAreaElement cfg = lift $ textAreaElement $ cfg { _textAreaElementConfig_elementConfig = liftElementConfig $ disableElementConfig $ _textAreaElementConfig_elementConfig cfg } selectElement cfg child = do let cfg' = cfg { _selectElementConfig_elementConfig = liftElementConfig $ disableElementConfig $ _selectElementConfig_elementConfig cfg } lift $ selectElement cfg' $ runInputDisabledT child instance HasWebView m => HasWebView (InputDisabledT m) where type WebViewPhantom (InputDisabledT m) = WebViewPhantom m askWebView = lift askWebView instance HasJS js m => HasJS js (InputDisabledT m) where type JSM (InputDisabledT m) = JSM m liftJS = lift . liftJS
manyoo/reflex-dom
src/Reflex/Dom/Builder/InputDisabled.hs
bsd-3-clause
3,696
0
14
570
884
460
424
67
1
import Test.Tasty import Test.Tasty.HUnit as HU main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "MVC Service test suite" [ testGroup "HUnit Tests" [hunitTest] ] hunitTest :: TestTree hunitTest = HU.testCase "HUnit test case" $ assertEqual "HUnit test failed" () ()
cmahon/mvc-service
test-suite/Tasty.hs
bsd-3-clause
300
0
8
54
88
47
41
9
1
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies , FlexibleInstances, FlexibleContexts #-} module Llvm.Hir.Internalization where import Llvm.Hir.Data import Llvm.Hir.Cast import Llvm.Hir.Composer import Control.Monad () import Control.Monad.State import qualified Data.Map as M import qualified Data.Set as S {- Internalization converts a "metadata" value to a first class value that can be referred by LLVM code. v-} class (Monad m, MonadState (M.Map (Dtype, Const) (DefAndRef a)) m) => LlvmGlobalGenMonad a m where newGlobalId :: m GlobalId getDefAndRef :: (Dtype, Const) -> m (Maybe (DefAndRef a)) cacheToplevel :: (Dtype, Const) -> DefAndRef a -> m () data DefAndRef a = DefAndRef { llvmDef :: Toplevel a , llvmRef :: T (Type ScalarB P) Const } class (Ord x, Eq x) => Internalization x where internalize :: LlvmGlobalGenMonad a m => x -> m (DefAndRef a) instance Internalization String where internalize c = let str = (fmap (\x -> case x of '\\' -> '_' '"' -> '_' _ -> x) c) ++ ['\00'] strType = ucast (Tarray (fromIntegral $ length str) (ucast i8)) in do { mdef <- getDefAndRef (strType, C_str str) ; case mdef of Just defref -> return defref Nothing -> do { lhs <- newGlobalId ; let dr = DefAndRef { llvmDef = ToplevelGlobal $ TlGlobalDtype { tlg_lhs = lhs , tlg_linkage = Just LinkagePrivate , tlg_visibility = Nothing , tlg_dllstorage = Nothing , tlg_tls = Nothing , tlg_addrnaming = UnnamedAddr , tlg_addrspace = Nothing , tlg_externallyInitialized = IsNot ExternallyInitialized , tlg_globalType = GlobalType "constant" , tlg_dtype = strType , tlg_const = Just $ C_str str , tlg_section = Nothing , tlg_comdat = Nothing , tlg_alignment = Just (AlignInByte 1) } , llvmRef = T (ptr0 i8) $ C_getelementptr (Is InBounds) (T (ucast $ Tpointer (ucast strType) 0) (C_globalAddr lhs)) (i32sToTcs [0,0]) } ; cacheToplevel (strType, C_str str) dr ; return dr } } instance LlvmGlobalGenMonad a (StateT (M.Map (Dtype, Const) (DefAndRef a)) (State (String, Int))) where newGlobalId = do { (prefix, cnt) <- lift get ; lift $ put (prefix, cnt+1) ; return $ GlobalIdAlphaNum (prefix ++ show cnt) } cacheToplevel k v = modify (M.insert k v) getDefAndRef k = do { s <- get ; return $ M.lookup k s } runSimpleLlvmGlobalGen :: String -> Int -> (StateT (M.Map (Dtype, Const) (DefAndRef a)) (State (String, Int))) x -> (x, (M.Map (Dtype, Const) (DefAndRef a))) runSimpleLlvmGlobalGen prefix initCnt f = evalState (runStateT f M.empty) (prefix, initCnt)
sanjoy/hLLVM
src/Llvm/Hir/Internalization.hs
bsd-3-clause
4,190
0
28
2,134
950
512
438
-1
-1
{-#OPTIONS_GHC -fno-warn-orphans #-} {-#Language FlexibleInstances #-} module ETests.Utils where import Control.Monad (unless) import Text.Parsec.Pos import Text.Parsec.Error import Language.TheExperiment.AST.Type import Language.TheExperiment.AST.Expression import Language.TheExperiment.AST.Statement import Test.HUnit class (Eq a) => TestComp a where testComp :: a -> a -> Bool testComp a b = a == b instance (TestComp a) => TestComp [a] where testComp a b = and $ zipWith testComp a b instance TestComp Char instance TestComp ParsedType where testComp (TypeName _ n) (TypeName _ n') = n `testComp` n' testComp (TypeVariable _ v) (TypeVariable _ v') = v `testComp` v' testComp (TypeCall _ f p) (TypeCall _ f' p') = (f `testComp` f') && (p `testComp` p') testComp (FunctionType _ a r) (FunctionType _ a' r') = (a `testComp` a') && (r `testComp` r') testComp _ _ = False instance TestComp TypeSignature where testComp (TypeSignature as a) (TypeSignature bs b) = testComp as bs && testComp a b instance TestComp TypeConstraint where testComp (TypeConstraint a as) (TypeConstraint b bs) = a == b && testComp as bs instance TestComp Literal instance TestComp () instance TestComp OpFormat instance TestComp (Expr ()) where testComp (Call _ a af as) (Call _ b bf bs) = testComp a b && testComp af bf && testComp as bs testComp (Identifier _ a as aOp) (Identifier _ b bs bOp) = testComp a b && testComp as bs && testComp aOp bOp testComp (Literal _ a aLit) (Literal _ b bLit) = testComp a b && testComp aLit bLit testComp _ _ = False instance (TestComp a, TestComp b) => TestComp (Either a b) where testComp (Left a) (Left b) = testComp a b testComp (Right a) (Right b) = testComp a b testComp _ _ = False instance (TestComp a) => TestComp (Maybe a) where testComp (Just a) (Just a') = testComp a a' testComp Nothing Nothing = True testComp _ _ = False instance TestComp Message instance TestComp (Statement ()) where testComp (Return _ a b) (Return _ a' b') = and [ testComp a a' , testComp b b' ] testComp (Assign _ a b c) (Assign _ a' b' c') = and [ testComp a a' , testComp b b' , testComp c c' ] testComp (CallStmt _ a b) (CallStmt _ a' b') = and [ testComp a a' , testComp b b' ] testComp (Block _ a b) (Block _ a' b') = and [ testComp a a' , testComp b b' ] testComp (If _ a b c d) (If _ a' b' c' d') = and [ testComp a a' , testComp b b' , testComp c c' , testComp d d' ] testComp (While _ a b c) (While _ a' b' c') = and [ testComp a a' , testComp b b' , testComp c c' ] testComp _ _ = False instance TestComp (DefOrStatement ()) where testComp (Def a) (Def a') = testComp a a' testComp (Stmt a) (Stmt a') = testComp a a' testComp _ _ = False instance TestComp (Definition ()) where testComp (TypeDef _ a b c) (TypeDef _ a' b' c') = and [ testComp a a' , testComp b b' , testComp c c' ] testComp _ _ = False instance Show Message where show (SysUnExpect s) = "SysUnExpect " ++ s show (UnExpect s) = "UnExpect " ++ s show (Expect s) = "Expect " ++ s show (Message s) = "Message " ++ s eTestAssertEqual :: (TestComp a, Show a) => String -> a -> a -> Assertion eTestAssertEqual preface expected actual = unless (actual `testComp` expected) (assertFailure msg) where msg = (if null preface then "" else preface ++ "\n") ++ "expected: " ++ show expected ++ "\n but got: " ++ show actual mapLeft :: (a -> b) -> Either a c -> Either b c mapLeft f (Left a) = Left $ f a mapLeft _ (Right a) = Right a eTestParse :: (TestComp a, Show a) => String -> Either [Message] a -> Either ParseError a -> Assertion eTestParse preface expected actual = unless ((mapLeft errorMessages actual) `testComp` expected) (assertFailure msg) where msg = (if null preface then "" else preface ++ "\n") ++ "expected: " ++ show expected ++ "\n but got: " ++ show (mapLeft errorMessages actual) --actual blankPos :: SourcePos blankPos = initialPos "tests"
jvranish/TheExperiment
test/ETests/Utils.hs
bsd-3-clause
4,112
0
13
1,000
1,761
891
870
97
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE TemplateHaskell #-} module Hop.Schwifty.Swift.M105.Types where import Data.Text (Text) import Control.Applicative import Data.Ratio import Control.Lens newtype Code = Code {_unCode :: Text} deriving (Eq, Show, Ord) $(makeLenses ''Code) newtype Time = Time {_unTime :: String } deriving (Read,Show,Eq) $(makeLenses ''Time) data Value = Value { _vWhole :: !Int ,_vPart :: !(Ratio Int) } deriving (Read,Show,Eq) $(makeLenses ''Value) newtype SendersRef = SendersRef { _unSendersRef :: Text } deriving (Show,Eq) $(makeLenses ''SendersRef) data TimeIndication = TimeIndication { _tiCode :: !Text ,_tiTime :: !Text ,_tiSign :: !Text ,_tiOffset :: !Text } deriving (Show,Eq) $(makeLenses ''TimeIndication) data BankOperationCode = NormalCreditTransfer | TestMessage | SWIFTPay | Priority | Standard deriving (Show,Eq) data InstructionCode = CorporateTrade (Maybe Text) | IntraCompanyPayment (Maybe Text) | RelatedPayment (Maybe Text) | SameDayValue (Maybe Text) deriving (Show,Eq) newtype TransactionTypeCode = TransactionTypeCode { _unTransactionTypeCode :: Text } deriving (Show,Eq) $(makeLenses ''TransactionTypeCode) data VDateCurSetl = VDateCurSetl { _vcsValueDate :: !Time ,_vcsCurrency :: !Text ,_vcsSettlementAmount :: !Value } deriving (Show,Eq) $(makeLenses ''VDateCurSetl) data CurrencyInstructedAmt = CurrencyInstructedAmt { _ciaCurrency :: !Text ,_ciaAmount :: !Value } deriving (Show,Eq) $(makeLenses ''CurrencyInstructedAmt) newtype SettleAmount = SettleAmount { _unSettleAmount :: Double } deriving (Show,Eq) $(makeLenses ''SettleAmount) newtype ExchangeRate = ExchangeRate { _unExchangeRate :: Value } deriving (Show,Eq) $(makeLenses ''ExchangeRate) newtype SendingInstitution = SendingInstitution { _unSendingInstitution :: Text } deriving (Show,Eq) $(makeLenses ''SendingInstitution) newtype Account = Account { _unAccount :: Text} deriving (Show, Eq) $(makeLenses ''Account) newtype IdentifierCode = IdentifierCode { _unIdentifierCode :: Text} deriving (Show,Eq) $(makeLenses ''IdentifierCode) data IdType = AlienReg | Passport | CustomerId | DriversLicence | Employer | NationalId | SocialSecurity | TaxId deriving (Show, Eq, Enum) data PartyId = PartyId { _piCode :: !IdType ,_piCountry :: !Text ,_piIdentifier :: !Text } deriving (Show, Eq) $(makeLenses ''PartyId) data Field50FExtra = F50F_1_NameOrdCustomer {_f50FNameOrdCust :: !Text} | F50F_2_AddressLine {_f50FAddressLine :: !Text} | F50F_3_CountryAndTown {_f50FCountryAndTown :: !Text} | F50F_4_DateOfBirth {_f50FDateOfBirth :: !Text} | F50F_5_PlaceOfBirth {_f50FPlaceOfBirth :: !Text} | F50F_6_CustIdNum {_f50FCustIdNum :: !Text} | F50F_7_NationalIdNum {_f50FNationalIdNum :: !Text} | F50F_8_AdditionalInfo {_f50FAdditionalInfo :: !Text} deriving (Show, Eq) $(makeLenses ''Field50FExtra) data Field50FIdentifier = F50F_PartyId { _unF50F_PartyId :: !PartyId } | F50F_Account { _unF50F_Account :: !Account} deriving (Show, Eq) $(makeLenses ''Field50FIdentifier) data OrderingCustomer = Field50A { _ocA_Account :: !Account , _ocA_IdCode :: !IdentifierCode , _ocA_remainder :: !(Maybe [Text]) } | Field50F { _ocF_Account :: !Field50FIdentifier , _ocF_extra :: !(Maybe [Field50FExtra]) , _ocF_remainder :: !(Maybe [Text]) } | Field50K { _ocK_Account :: !Account , _ocK_extra :: !(Maybe [Field50FExtra]) , _ocK_remainder :: !(Maybe [Text]) } deriving (Show,Eq) $(makeLenses ''OrderingCustomer) --data OrderingCustomer = OrderingCustomer { -- _ocAccount :: !Text -- this is wrong and should distinguish between acct and id -- ,_ocDetails :: !Text -- } deriving (Show,Eq) newtype OrderingInstitution = OrderingInstitution { _unOrderingInstitution :: Text } deriving (Show,Eq) $(makeLenses ''OrderingInstitution) newtype SendersCorrespondent = SendersCorrespondent { _unSendersCorrespondent :: Text } deriving (Show,Eq) $(makeLenses ''SendersCorrespondent) newtype ReceiversCorrespondent = ReceiversCorrespondent { _unReceiversCorrespondent :: Text } deriving (Show,Eq) $(makeLenses ''ReceiversCorrespondent) newtype ThirdReimbursementInstitution = ThirdReimbursementInstitution { _unThirdReimbursementInstitution :: Text } deriving (Show,Eq) $(makeLenses ''ThirdReimbursementInstitution) newtype IntermediaryInstitution = IntermediaryInstitution { _unIntermediaryInstitution :: Text } deriving (Show,Eq) $(makeLenses ''IntermediaryInstitution) newtype AccountWithInstitution = AccountWithInstitution { _unAccountWithInstitution :: Text } deriving (Show,Eq) $(makeLenses ''AccountWithInstitution) data BeneficiaryCustomer = BeneficiaryCustomer { _bcAccount :: !Text -- this is wrong and should distinguish between acct and id ,_bcDetails :: !Text } deriving (Show,Eq) $(makeLenses ''BeneficiaryCustomer) newtype RemittanceInformation = RemittanceInformation { _unRemittanceInformation :: Text } deriving (Show,Eq) $(makeLenses ''RemittanceInformation) data DetailsOfCharges = Beneficiary | OurCustomerCharged | SharedCharges deriving (Show,Eq) newtype SendersCharges = SendersCharges { _unSendersCharges :: Text } deriving (Show,Eq) $(makeLenses ''SendersCharges) newtype ReceiversCharges = ReceiversCharges { _unReceiversCharges :: Text } deriving (Show,Eq) $(makeLenses ''ReceiversCharges) newtype SenderToReceiverInfo = SenderToReceiverInfo { _unSenderToReceiverInfo :: Text } deriving (Show,Eq) $(makeLenses ''SenderToReceiverInfo) newtype RegulatoryReporting = RegulatoryReporting { _unRegulatoryReporting :: Text } deriving (Show,Eq) $(makeLenses ''RegulatoryReporting) data SWIFT = SWIFT { _sCode20 :: !SendersRef ,_sCode13C :: !(Maybe TimeIndication) ,_sCode23B :: !BankOperationCode ,_sCode23E :: !(Maybe InstructionCode) ,_sCode26T :: !(Maybe TransactionTypeCode) ,_sCode32A :: !VDateCurSetl ,_sCode33B :: !(Maybe CurrencyInstructedAmt) ,_sCode36 :: !(Maybe ExchangeRate) ,_sCode50a :: !OrderingCustomer ,_sCode51A :: !(Maybe SendingInstitution) ,_sCode52A :: !(Maybe OrderingInstitution) ,_sCode53a :: !(Maybe SendersCorrespondent) ,_sCode54A :: !(Maybe ReceiversCorrespondent) ,_sCode55A :: !(Maybe ThirdReimbursementInstitution) ,_sCode56A :: !(Maybe IntermediaryInstitution) ,_sCode57A :: !(Maybe AccountWithInstitution) ,_sCode59a :: !BeneficiaryCustomer ,_sCode70 :: !(Maybe RemittanceInformation) ,_sCode71A :: !DetailsOfCharges ,_sCode71F :: !(Maybe SendersCharges) ,_sCode71G :: !(Maybe ReceiversCharges) ,_sCode72 :: !(Maybe SenderToReceiverInfo) ,_sCode77B :: !(Maybe RegulatoryReporting) } deriving (Show, Eq) $(makeLenses ''SWIFT) data MaybeSWIFT = MaybeSWIFT { _msCode20 :: !(Maybe SendersRef) ,_msCode13C :: !(Maybe TimeIndication) ,_msCode23B :: !(Maybe BankOperationCode) ,_msCode23E :: !(Maybe InstructionCode) ,_msCode26T :: !(Maybe TransactionTypeCode) ,_msCode32A :: !(Maybe VDateCurSetl) ,_msCode33B :: !(Maybe CurrencyInstructedAmt) ,_msCode36 :: !(Maybe ExchangeRate) ,_msCode50a :: !(Maybe OrderingCustomer) ,_msCode51A :: !(Maybe SendingInstitution) ,_msCode52A :: !(Maybe OrderingInstitution) ,_msCode53a :: !(Maybe SendersCorrespondent) ,_msCode54A :: !(Maybe ReceiversCorrespondent) ,_msCode55A :: !(Maybe ThirdReimbursementInstitution) ,_msCode56A :: !(Maybe IntermediaryInstitution) ,_msCode57A :: !(Maybe AccountWithInstitution) ,_msCode59a :: !(Maybe BeneficiaryCustomer) ,_msCode70 :: !(Maybe RemittanceInformation) ,_msCode71A :: !(Maybe DetailsOfCharges) ,_msCode71F :: !(Maybe SendersCharges) ,_msCode71G :: !(Maybe ReceiversCharges) ,_msCode72 :: !(Maybe SenderToReceiverInfo) ,_msCode77B :: !(Maybe RegulatoryReporting) } deriving (Show, Eq) $(makeLenses ''MaybeSWIFT) instance Monoid MaybeSWIFT where mempty = MaybeSWIFT { _msCode20 = Nothing ,_msCode13C = Nothing ,_msCode23B = Nothing ,_msCode23E = Nothing ,_msCode26T = Nothing ,_msCode32A = Nothing ,_msCode33B = Nothing ,_msCode36 = Nothing ,_msCode50a = Nothing ,_msCode51A = Nothing ,_msCode52A = Nothing ,_msCode53a = Nothing ,_msCode54A = Nothing ,_msCode55A = Nothing ,_msCode56A = Nothing ,_msCode57A = Nothing ,_msCode59a = Nothing ,_msCode70 = Nothing ,_msCode71A = Nothing ,_msCode71F = Nothing ,_msCode71G = Nothing ,_msCode72 = Nothing ,_msCode77B = Nothing } (MaybeSWIFT msCode20' msCode13C' msCode23B' msCode23E' msCode26T' msCode32A' msCode33B' msCode36' msCode50a' msCode51A' msCode52A' msCode53a' msCode54A' msCode55A' msCode56A' msCode57A' msCode59a' msCode70' msCode71A' msCode71F' msCode71G' msCode72' msCode77B' ) `mappend` ( MaybeSWIFT msCode20'' msCode13C'' msCode23B'' msCode23E'' msCode26T'' msCode32A'' msCode33B'' msCode36'' msCode50a'' msCode51A'' msCode52A'' msCode53a'' msCode54A'' msCode55A'' msCode56A'' msCode57A'' msCode59a'' msCode70'' msCode71A'' msCode71F'' msCode71G'' msCode72'' msCode77B'') = MaybeSWIFT { _msCode20 = msCode20' <|> msCode20'' ,_msCode13C = msCode13C' <|> msCode13C'' ,_msCode23B = msCode23B' <|> msCode23B'' ,_msCode23E = msCode23E' <|> msCode23E'' ,_msCode26T = msCode26T' <|> msCode26T'' ,_msCode32A = msCode32A' <|> msCode32A'' ,_msCode33B = msCode33B' <|> msCode33B'' ,_msCode36 = msCode36' <|> msCode36'' ,_msCode50a = msCode50a' <|> msCode50a'' ,_msCode51A = msCode51A' <|> msCode51A'' ,_msCode52A = msCode52A' <|> msCode52A'' ,_msCode53a = msCode53a' <|> msCode53a'' ,_msCode54A = msCode54A' <|> msCode54A'' ,_msCode55A = msCode55A' <|> msCode55A'' ,_msCode56A = msCode56A' <|> msCode56A'' ,_msCode57A = msCode57A' <|> msCode57A'' ,_msCode59a = msCode59a' <|> msCode59a'' ,_msCode70 = msCode70' <|> msCode70'' ,_msCode71A = msCode71A' <|> msCode71A'' ,_msCode71F = msCode71F' <|> msCode71F'' ,_msCode71G = msCode71G' <|> msCode71G'' ,_msCode72 = msCode72' <|> msCode72'' ,_msCode77B = msCode77B' <|> msCode77B'' }
haroldcarr/juno
z-no-longer-used/src/Hop/Schwifty/Swift/M105/Types.hs
bsd-3-clause
11,250
0
12
2,693
2,688
1,500
1,188
460
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Data.Monoid.Bounds where import Data.Monoid newtype Minimum n = Minimum { getMinimum :: n } deriving (Eq, Ord, Bounded) newtype Maximum n = Maximum { getMaximum :: n } deriving (Eq, Ord, Bounded) instance (Ord n, Bounded n) => Monoid (Minimum n) where mempty = maxBound mappend = min instance (Ord n, Bounded n) => Monoid (Maximum n) where mempty = minBound mappend = max
sebastiaanvisser/fixpoints
src/Data/Monoid/Bounds.hs
bsd-3-clause
438
0
7
84
149
87
62
11
0
{-# LANGUAGE NoMonadFailDesugaring #-} module Language.Haskell.GHC.DumpTree ( treesForTargetsIO , treesForTargets , treesForSession , treeDumpFlags , dumpJson , treesToDoc , dumpText , Trees(..) ) where import Prelude hiding (mod) import Control.Arrow (second) import Control.Exception import Control.Monad import Data.Aeson (ToJSON(..), object, (.=)) import Data.Data (Data, cast, toConstr, showConstr, gmapQ) import Data.List (isInfixOf, isPrefixOf) import Data.String (fromString) import System.Process (readProcess) import Text.Show.Pretty (Value(..),valToDoc) import Text.PrettyPrint import qualified Data.Aeson as Aeson import qualified Data.ByteString.Lazy as B.Lazy import qualified Data.HashMap.Strict as HashMap import Bag import Exception import GHC import HscTypes import Module import MonadUtils import Name import Outputable (Outputable, showSDoc, ppr) import RdrName import TcEvidence import Var import qualified OccName as Occ {------------------------------------------------------------------------------- Translate AST to Value -------------------------------------------------------------------------------} pretty :: (Outputable a, GhcMonad m) => a -> m String pretty x = ghandle (handleException id) $ do dynFlags <- getSessionDynFlags return $! showSDoc dynFlags (ppr x) pretty' :: (Outputable a, GhcMonad m) => a -> m Value pretty' = liftM String . pretty -- | Construct a `Value` from any term implementing `data` -- -- We have a number of special cases, solving two different kinds of problems: -- -- * Some datatypes in GHC don't have an informative Data instance but are -- marked as "abstract". We test for these types specifically so that we can -- use a custom pretty-printer rather than just showing "{abstract}". -- * Some subterms in ghc contain error values. We try to catch these and -- show them as more readable strings (defaulting to showing the exception). -- -- Moreover, for a few types we show both the pretty-printed form and the -- actual tree; we are careful to do this only for top-level occurrences of -- these types. valueFromData :: (Data a, GhcMonad m) => a -> m Value valueFromData = go False where -- Bool indicates if we just added a pretty-printed form as well -- (so that we don't do it for directly recursive values) go :: (Data a, GhcMonad m) => Bool -> a -> m Value go b x -- Types where we want to show both a pretty-printed value and a tree | Just x' <- cast x :: Maybe (HsType GhcPs) = withPretty b x' | Just x' <- cast x :: Maybe (HsType GhcRn) = withPretty b x' | Just x' <- cast x :: Maybe (HsType GhcTc) = withPretty b x' | Just x' <- cast x :: Maybe Type = withPretty b x' -- Abstract types we cannot traverse | Just x' <- cast x :: Maybe SrcSpan = pretty' x' | Just x' <- cast x :: Maybe TyCon = pretty' x' -- We cannot traverse names either, but we don't want to just call -- the pretty-printer because we would lose too much information | Just x' <- cast x :: Maybe Module = prettyModule x' | Just x' <- cast x :: Maybe ModuleName = prettyModuleName x' | Just x' <- cast x :: Maybe Name = prettyName x' | Just x' <- cast x :: Maybe OccName = prettyOccName x' | Just x' <- cast x :: Maybe RdrName = prettyRdrName x' | Just x' <- cast x :: Maybe TcEvBinds = prettyTcEvBinds x' | Just x' <- cast x :: Maybe Var = prettyVar x' -- Otherwise just construct a generic value | otherwise = generic False x generic :: (Data a, GhcMonad m) => Bool -> a -> m Value generic b x = ghandle (handleException String) $ do constrName <- eval $ showConstr $ toConstr x Con constrName <$> sequence (gmapQ (go b) x) withPretty :: (Data a, Outputable a, GhcMonad m) => Bool -> a -> m Value withPretty True x = generic True x withPretty False x = ghandle (handleException String) $ do prettied <- pretty x tree <- generic True x return $! Rec "" [(prettied, tree)] handleException :: GhcMonad m => (String -> e) -> SomeException -> m e handleException f e = case isKnownPanic (show e) of Just panic -> return $! f $ "<<" ++ panic ++ ">>" Nothing -> return $! f $ show e where isKnownPanic :: String -> Maybe String isKnownPanic s = msum $ map aux knownPanics where aux panic | panic `isInfixOf` s = Just panic | otherwise = Nothing knownPanics :: [String] knownPanics = [ "PostTcExpr" , "PostTcKind" , "PostTcType" , "fixity" , "placeHolderNames" ] eval :: GhcMonad m => a -> m a eval = liftIO . evaluate -- | Clean up a value generated by valueFromData cleanupValue :: Value -> Value cleanupValue (Con nm vals) | nm == "[]" = case vals of [] -> List [] _ -> error "cleanupValue: invalid tree" | nm == "(:)" = case vals of [x, xs] -> case cleanupValue xs of List xs' -> List (cleanupValue x : xs') _ -> error "cleanupValue: invalid tree" _ -> error "cleanupValue: invalid tree" | isTuple nm = Tuple (map cleanupValue vals) | isBag nm = case vals of [contents] -> Con "Bag.listToBag" [cleanupValue contents] _ -> error "cleanupValue: invalid tree" | otherwise = Con nm (map cleanupValue vals) where isTuple :: String -> Bool isTuple ('(' : nm') = all (== ',') (init nm') && last nm' == ')' isTuple _ = False isBag :: String -> Bool isBag = isPrefixOf "{abstract:Bag" cleanupValue (String s) = String s cleanupValue (Rec nm flds) = Rec nm $ map (second cleanupValue) flds cleanupValue _ = error "cleanupValue: unexpected Value" {------------------------------------------------------------------------------- Specialized functions for the different kinds of names * OccName most primitive type: just a string and namespace (variable, data constructor, etc.) * RdrName come directly from the parser * Name after renaming * Var after typechecking * Id alias for Var -------------------------------------------------------------------------------} prettyOccName :: GhcMonad m => OccName -> m Value prettyOccName nm | occNameSpace nm == Occ.varName = mk "VarName" | occNameSpace nm == Occ.dataName = mk "DataName" | occNameSpace nm == Occ.tvName = mk "TvName" | occNameSpace nm == Occ.tcClsName = mk "TcClsName" | otherwise = error "unexpected OccName" where mk :: GhcMonad m => String -> m Value mk namespace = return $! Rec "" [(namespace, String (occNameString nm))] prettyTcEvBinds :: GhcMonad m => TcEvBinds -> m Value prettyTcEvBinds (TcEvBinds mut) = pretty' mut prettyTcEvBinds (EvBinds bagOfEvBind) = do let evBinds = bagToList bagOfEvBind fmap (Con "TcEvBinds") $! mapM prettyEvBind evBinds prettyEvBind :: GhcMonad m => EvBind -> m Value prettyEvBind (EvBind var term isGiven) = do pVar <- prettyVar var pTerm <- pretty' term pGiven <- pretty' isGiven return $! Rec "" [("ev_var", pVar), ("ev_term", pTerm), ("ev_is_given", pGiven)] prettyRdrName :: GhcMonad m => RdrName -> m Value prettyRdrName (Unqual nm) = prettyOccName nm prettyRdrName (Exact nm) = prettyName nm prettyRdrName (Qual mod nm) = do Rec "" fields <- prettyOccName nm qual <- prettyModuleName mod return $! Rec "" (("Qual", qual):fields) prettyRdrName (Orig mod nm) = do Rec "" fields <- prettyOccName nm orig <- prettyModule mod return $! Rec "" (("Orig", orig):fields) prettyName :: GhcMonad m => Name -> m Value prettyName nm = do Rec "" fields <- prettyOccName (nameOccName nm) loc <- pretty' (nameSrcSpan nm) sort <- prettyNameSort uniq <- pretty' $ nameUnique nm return $! Rec "" (("n_loc",loc):("n_sort",sort):("n_uniq",uniq):fields) where prettyNameSort :: GhcMonad m => m Value prettyNameSort | Just _tyThing <- wiredInNameTyThing_maybe nm = do mod <- prettyModule (nameModule nm) -- TODO: Do somethng with tyThing return $! Rec "" [("WiredIn", mod)] | isExternalName nm = do mod <- prettyModule (nameModule nm) return $! Rec "" [("External", mod)] | isInternalName nm = do return $! String "Internal" | isSystemName nm = do return $! String "System" | otherwise = error "Unexpected NameSort" prettyVar :: GhcMonad m => Var -> m Value prettyVar nm = do Rec "" fields <- prettyName $ Var.varName nm typ <- valueFromData $ varType nm -- TODO: There is more information we could extract about Vars return $! Rec "" (("varType", typ):fields) prettyModuleName :: GhcMonad m => ModuleName -> m Value prettyModuleName = return . String . moduleNameString prettyModule :: GhcMonad m => Module -> m Value prettyModule mod = do pkg <- prettyUnitId $ moduleUnitId mod nm <- prettyModuleName $ moduleName mod return $! Con "Module" [pkg, nm] prettyUnitId :: GhcMonad m => UnitId -> m Value prettyUnitId = return . String . unitIdString {------------------------------------------------------------------------------- Extracting ASTs from a set of targets -------------------------------------------------------------------------------} data Trees = Trees { treeModule :: String , treeParsed :: Value , treeRenamed :: Value , treeTypechecked :: Value , treeExports :: Value } deriving (Eq,Show) treesForModSummary :: GhcMonad m => ModSummary -> m Trees treesForModSummary modSummary = do parsed <- parseModule modSummary let wrapErr se = return $ Left $ show $ bagToList $ srcErrorMessages se eTypechecked <- handleSourceError wrapErr (Right <$> typecheckModule parsed) treeModule <- pretty (ms_mod_name modSummary) treeParsed <- mkTree (pm_parsed_source parsed) treeRenamed <- mkRenamedTree eTypechecked treeTypechecked <- mkTypeCheckedTree eTypechecked treeExports <- mkExportTree eTypechecked return Trees{..} where mkTree :: (Data a,GhcMonad m) => a -> m Value mkTree = liftM cleanupValue . valueFromData mkRenamedTree (Right typechecked) = case tm_renamed_source typechecked of Just renamed -> mkTree renamed Nothing -> return $ String $ show treeNotAvailable mkRenamedTree (Left errors) = return (String errors) mkTypeCheckedTree (Right typechecked) = mkTree $ tm_typechecked_source typechecked mkTypeCheckedTree (Left errors) = return (String errors) mkExportTree (Right typechecked) = mkTree $ modInfoExports $ tm_checked_module_info typechecked mkExportTree (Left _) = return $ String $ show treeNotAvailable treeNotAvailable :: String treeNotAvailable = "<<NOT AVAILABLE>>" -- | Get dyn flags: Don't compile anything treeDumpFlags :: DynFlags -> DynFlags treeDumpFlags dynFlags = dynFlags { hscTarget = HscNothing , ghcLink = NoLink } -- | Generate trees for modules in session treesForSession :: GhcMonad m => m [Trees] treesForSession = do hscEnv <- getSession mapM treesForModSummary . mgModSummaries $ hsc_mod_graph hscEnv -- | Generate trees for given files, when already in GHC treesForTargets :: GhcMonad m => [FilePath] -> m [Trees] treesForTargets targets = do liftIO $ putStrLn "in treesForTargets" gbracket getSessionDynFlags setSessionDynFlags $ \dynFlags -> do let dynFlags' = treeDumpFlags dynFlags void $ setSessionDynFlags dynFlags' -- Construct module graph setTargets (map mkTarget targets) void $ load LoadAllTargets -- -- generate each module treesForSession where mkTarget :: FilePath -> Target mkTarget fp = Target { targetId = TargetFile fp Nothing , targetAllowObjCode = False , targetContents = Nothing } -- | Generate trees for given files, starting a GHC session -- "ghc" needs to be in the PATH treesForTargetsIO :: [FilePath] -> IO [Trees] treesForTargetsIO targets = do libdir:_ <- lines <$> readProcess "ghc" ["--print-libdir"] "" runGhc (Just libdir) (treesForTargets targets) -- | Convert Trees to Doc treesToDoc :: Trees -> Doc treesToDoc Trees{..} = do text ("# " ++ treeModule) $$ text "" $$ sectionV "## Parsed" treeParsed $$ sectionV "## Renamed" treeRenamed $$ sectionV "## Typechecked" treeTypechecked $$ sectionV "## Exports" treeExports where sectionV title v = text title $$ valToDoc v $$ text "" {------------------------------------------------------------------------------- Dump the trees to stdout in text format -------------------------------------------------------------------------------} dumpText :: [Trees] -> IO () dumpText = mapM_ (putStrLn . render . treesToDoc) -- where -- go :: Trees -> IO () -- go Trees{..} = do -- section ("# " ++ treesModule) $ do -- section "## Parsed" $ showTree treeParsed -- section "## Renamed" $ showTree treeRenamed -- section "## Typechecked" $ showTree treeTypechecked -- section "## Exports" $ showTree treeExports -- -- section :: String -> IO () -> IO () -- section title = bracket_ (putStrLn title) (putStrLn "") -- -- showTree :: Value -> IO () -- showTree = putStrLn . valToStr {------------------------------------------------------------------------------- Dump in JSON format -------------------------------------------------------------------------------} instance ToJSON Value where -- Special cases toJSON (Con "False" []) = Aeson.Bool False toJSON (Con "True" []) = Aeson.Bool True toJSON (Con "Bag.listToBag" [xs]) = toJSON xs toJSON (Con "L" [loc, x]) = case toJSON x of Aeson.Object obj' -> Aeson.Object (HashMap.insert "location" (toJSON loc) obj') nonObject -> nonObject -- we lose the location information in this case -- Rest toJSON (Con nm []) = Aeson.String (fromString nm) toJSON (Con nm vals) = object [ fromString nm .= vals ] toJSON (Tuple vals) = toJSON vals toJSON (List vals) = toJSON vals toJSON (String s) = Aeson.String (fromString s) toJSON (Rec "" flds) = object $ map (\(fld, val) -> fromString fld .= val) flds toJSON _ = error "toJSON: Unexpected Value" instance ToJSON Trees where toJSON Trees{..} = object [ "module" .= treeModule , "parsed" .= treeParsed , "renamed" .= treeRenamed , "typechecked" .= treeTypechecked , "exports" .= treeExports ] dumpJson :: [Trees] -> IO () dumpJson = B.Lazy.putStr . Aeson.encode {------------------------------------------------------------------------------- Orphans -------------------------------------------------------------------------------}
edsko/ghc-dump-tree
src/Language/Haskell/GHC/DumpTree.hs
bsd-3-clause
15,163
13
15
3,696
4,014
2,003
2,011
-1
-1
{-| Some utility functions, based on the Confd client, providing data in a ready-to-use way. -} {- Copyright (C) 2013 Google Inc. 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.Confd.ClientFunctions ( getInstances , getInstanceDisks ) where import Control.Monad (liftM) import qualified Text.JSON as J import Ganeti.BasicTypes as BT import Ganeti.Confd.Types import Ganeti.Confd.Client import Ganeti.Objects -- | Get the list of instances the given node is ([primary], [secondary]) for. -- The server address and the server port parameters are mainly intended -- for testing purposes. If they are Nothing, the default values will be used. getInstances :: String -> Maybe String -> Maybe Int -> BT.ResultT String IO ([Ganeti.Objects.Instance], [Ganeti.Objects.Instance]) getInstances node srvAddr srvPort = do client <- liftIO $ getConfdClient srvAddr srvPort reply <- liftIO . query client ReqNodeInstances $ PlainQuery node case fmap (J.readJSON . confdReplyAnswer) reply of Just (J.Ok instances) -> return instances Just (J.Error msg) -> fail msg Nothing -> fail "No answer from the Confd server" -- | Get the list of disks that belong to a given instance -- The server address and the server port parameters are mainly intended -- for testing purposes. If they are Nothing, the default values will be used. getDisks :: Ganeti.Objects.Instance -> Maybe String -> Maybe Int -> BT.ResultT String IO [Ganeti.Objects.Disk] getDisks inst srvAddr srvPort = do client <- liftIO $ getConfdClient srvAddr srvPort reply <- liftIO . query client ReqInstanceDisks . PlainQuery . instUuid $ inst case fmap (J.readJSON . confdReplyAnswer) reply of Just (J.Ok disks) -> return disks Just (J.Error msg) -> fail msg Nothing -> fail "No answer from the Confd server" -- | Get the list of instances on the given node along with their disks -- The server address and the server port parameters are mainly intended -- for testing purposes. If they are Nothing, the default values will be used. getInstanceDisks :: String -> Maybe String -> Maybe Int -> BT.ResultT String IO [(Ganeti.Objects.Instance, [Ganeti.Objects.Disk])] getInstanceDisks node srvAddr srvPort = liftM (uncurry (++)) (getInstances node srvAddr srvPort) >>= mapM (\i -> liftM ((,) i) (getDisks i srvAddr srvPort))
kawamuray/ganeti
src/Ganeti/Confd/ClientFunctions.hs
gpl-2.0
2,998
0
13
541
530
275
255
41
3
{- | Module : ./HasCASL/PrintSubst.hs Description : pretty printing substitutions Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : ewaryst.schulz@dfki.de Stability : experimental Portability : portable pretty printing substitutions -} module HasCASL.PrintSubst where import HasCASL.Subst import HasCASL.As import HasCASL.Le import HasCASL.PrintAs () import HasCASL.SimplifyTerm import Common.Doc import Common.DocUtils import qualified Data.Map as Map class PrettyInEnv a where prettyInEnv :: Env -> a -> Doc {- instance Pretty a => PrettyInEnv a where prettyInEnv _ x = pretty x -} instance Pretty SubstConst where pretty (SConst i _) = pretty i instance Pretty a => Pretty (SRule a) where pretty (Blocked x) = mapsto <+> pretty x <+> parens (text "BLOCKED") pretty (Ready x) = mapsto <+> pretty x instance Pretty Subst where pretty (Subst (a, b, _)) = text "Subs" <> vcat [ text "titution" , prettyRuleMap "Terms" a, prettyRuleMap "Types" b] prettyRuleMap :: (Pretty key, Pretty val) => String -> Map.Map key (SRule val) -> Doc prettyRuleMap t m | Map.null m = empty | otherwise = vcat $ (if null t then [] else [ text t <+> colon , text $ map (const '-') [0 .. length t + 1]]) ++ map prettyRule (Map.toList m) prettyRule :: (Pretty key, Pretty val) => (key, SRule val) -> Doc prettyRule (k, v) = pretty k <+> pretty v instance PrettyInEnv Term where prettyInEnv e t = pretty $ simplifyTerm e t instance PrettyInEnv Type where prettyInEnv = const pretty instance PrettyInEnv a => PrettyInEnv (SRule a) where prettyInEnv e (Blocked x) = mapsto <+> prettyInEnv e x <+> parens (text "BLOCKED") prettyInEnv e (Ready x) = mapsto <+> prettyInEnv e x instance PrettyInEnv Subst where prettyInEnv e (Subst (a, b, _)) = text "Subs" <> vcat [ text "titution" , prettyInEnvRuleMap e "Terms" a , prettyInEnvRuleMap e "Types" b] prettyInEnvRuleMap :: (Pretty key, PrettyInEnv val) => Env -> String -> Map.Map key (SRule val) -> Doc prettyInEnvRuleMap e t m | Map.null m = empty | otherwise = vcat $ (if null t then [] else [ text t <+> colon , text $ map (const '-') [0 .. length t + 1]]) ++ map (prettyInEnvRule e) (Map.toList m) prettyInEnvRule :: (Pretty key, PrettyInEnv val) => Env -> (key, SRule val) -> Doc prettyInEnvRule e (k, v) = pretty k <+> prettyInEnv e v prettyTermMapping :: Env -> [(Term, Term)] -> Doc prettyTermMapping e l = vcat $ map f l where f (t1, t2) = prettyInEnv e t1 <+> text "=" <+> prettyInEnv e t2
spechub/Hets
HasCASL/PrintSubst.hs
gpl-2.0
2,929
0
15
880
948
481
467
59
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.ECS.CreateService -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Runs and maintains a desired number of tasks from a specified task -- definition. If the number of tasks running in a service drops below -- 'desiredCount', Amazon ECS will spawn another instantiation of the task -- in the specified cluster. -- -- /See:/ <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html AWS API Reference> for CreateService. module Network.AWS.ECS.CreateService ( -- * Creating a Request createService , CreateService -- * Request Lenses , cCluster , cClientToken , cLoadBalancers , cRole , cServiceName , cTaskDefinition , cDesiredCount -- * Destructuring the Response , createServiceResponse , CreateServiceResponse -- * Response Lenses , csrsService , csrsResponseStatus ) where import Network.AWS.ECS.Types import Network.AWS.ECS.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'createService' smart constructor. data CreateService = CreateService' { _cCluster :: !(Maybe Text) , _cClientToken :: !(Maybe Text) , _cLoadBalancers :: !(Maybe [LoadBalancer]) , _cRole :: !(Maybe Text) , _cServiceName :: !Text , _cTaskDefinition :: !Text , _cDesiredCount :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateService' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cCluster' -- -- * 'cClientToken' -- -- * 'cLoadBalancers' -- -- * 'cRole' -- -- * 'cServiceName' -- -- * 'cTaskDefinition' -- -- * 'cDesiredCount' createService :: Text -- ^ 'cServiceName' -> Text -- ^ 'cTaskDefinition' -> Int -- ^ 'cDesiredCount' -> CreateService createService pServiceName_ pTaskDefinition_ pDesiredCount_ = CreateService' { _cCluster = Nothing , _cClientToken = Nothing , _cLoadBalancers = Nothing , _cRole = Nothing , _cServiceName = pServiceName_ , _cTaskDefinition = pTaskDefinition_ , _cDesiredCount = pDesiredCount_ } -- | The short name or full Amazon Resource Name (ARN) of the cluster that -- you want to run your service on. If you do not specify a cluster, the -- default cluster is assumed. cCluster :: Lens' CreateService (Maybe Text) cCluster = lens _cCluster (\ s a -> s{_cCluster = a}); -- | Unique, case-sensitive identifier you provide to ensure the idempotency -- of the request. Up to 32 ASCII characters are allowed. cClientToken :: Lens' CreateService (Maybe Text) cClientToken = lens _cClientToken (\ s a -> s{_cClientToken = a}); -- | A list of load balancer objects, containing the load balancer name, the -- container name (as it appears in a container definition), and the -- container port to access from the load balancer. cLoadBalancers :: Lens' CreateService [LoadBalancer] cLoadBalancers = lens _cLoadBalancers (\ s a -> s{_cLoadBalancers = a}) . _Default . _Coerce; -- | The name or full Amazon Resource Name (ARN) of the IAM role that allows -- your Amazon ECS container agent to make calls to your load balancer on -- your behalf. This parameter is only required if you are using a load -- balancer with your service. cRole :: Lens' CreateService (Maybe Text) cRole = lens _cRole (\ s a -> s{_cRole = a}); -- | The name of your service. Up to 255 letters (uppercase and lowercase), -- numbers, hyphens, and underscores are allowed. Service names must be -- unique within a cluster, but you can have similarly named services in -- multiple clusters within a region or across multiple regions. cServiceName :: Lens' CreateService Text cServiceName = lens _cServiceName (\ s a -> s{_cServiceName = a}); -- | The 'family' and 'revision' ('family:revision') or full Amazon Resource -- Name (ARN) of the task definition that you want to run in your service. -- If a 'revision' is not specified, the latest 'ACTIVE' revision is used. cTaskDefinition :: Lens' CreateService Text cTaskDefinition = lens _cTaskDefinition (\ s a -> s{_cTaskDefinition = a}); -- | The number of instantiations of the specified task definition that you -- would like to place and keep running on your cluster. cDesiredCount :: Lens' CreateService Int cDesiredCount = lens _cDesiredCount (\ s a -> s{_cDesiredCount = a}); instance AWSRequest CreateService where type Rs CreateService = CreateServiceResponse request = postJSON eCS response = receiveJSON (\ s h x -> CreateServiceResponse' <$> (x .?> "service") <*> (pure (fromEnum s))) instance ToHeaders CreateService where toHeaders = const (mconcat ["X-Amz-Target" =# ("AmazonEC2ContainerServiceV20141113.CreateService" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON CreateService where toJSON CreateService'{..} = object (catMaybes [("cluster" .=) <$> _cCluster, ("clientToken" .=) <$> _cClientToken, ("loadBalancers" .=) <$> _cLoadBalancers, ("role" .=) <$> _cRole, Just ("serviceName" .= _cServiceName), Just ("taskDefinition" .= _cTaskDefinition), Just ("desiredCount" .= _cDesiredCount)]) instance ToPath CreateService where toPath = const "/" instance ToQuery CreateService where toQuery = const mempty -- | /See:/ 'createServiceResponse' smart constructor. data CreateServiceResponse = CreateServiceResponse' { _csrsService :: !(Maybe ContainerService) , _csrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateServiceResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'csrsService' -- -- * 'csrsResponseStatus' createServiceResponse :: Int -- ^ 'csrsResponseStatus' -> CreateServiceResponse createServiceResponse pResponseStatus_ = CreateServiceResponse' { _csrsService = Nothing , _csrsResponseStatus = pResponseStatus_ } -- | The full description of your service following the create call. csrsService :: Lens' CreateServiceResponse (Maybe ContainerService) csrsService = lens _csrsService (\ s a -> s{_csrsService = a}); -- | The response status code. csrsResponseStatus :: Lens' CreateServiceResponse Int csrsResponseStatus = lens _csrsResponseStatus (\ s a -> s{_csrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-ecs/gen/Network/AWS/ECS/CreateService.hs
mpl-2.0
7,425
0
13
1,672
1,086
650
436
130
1
-- | Database administrative functions {-# LANGUAGE FlexibleContexts, OverloadedStrings, RecordWildCards #-} module Database.MongoDB.Admin ( -- * Admin -- ** Collection CollectionOption(..), createCollection, renameCollection, dropCollection, validateCollection, -- ** Index Index(..), IndexName, index, ensureIndex, createIndex, dropIndex, getIndexes, dropIndexes, -- ** User allUsers, addUser, removeUser, -- ** Database admin, cloneDatabase, copyDatabase, dropDatabase, repairDatabase, -- ** Server serverBuildInfo, serverVersion, -- * Diagnotics -- ** Collection collectionStats, dataSize, storageSize, totalIndexSize, totalSize, -- ** Profiling ProfilingLevel(..), getProfilingLevel, MilliSec, setProfilingLevel, -- ** Database dbStats, OpNum, currentOp, killOp, -- ** Server serverStatus ) where import Prelude hiding (lookup) import Control.Applicative ((<$>)) import Database.MongoDB.Internal.Protocol (pwHash, pwKey) import Database.MongoDB.Connection (Host, showHostPort) import Database.MongoDB.Query import Data.Bson import Data.UString (pack, append, intercalate) import Control.Monad.Reader import qualified Data.HashTable as T import Data.IORef import qualified Data.Set as S import System.IO.Unsafe (unsafePerformIO) import Control.Concurrent (forkIO, threadDelay) import Database.MongoDB.Internal.Util (MonadIO', (<.>), true1) import Control.Monad.Trans.Control (MonadBaseControl) -- * Admin -- ** Collection data CollectionOption = Capped | MaxByteSize Int | MaxItems Int deriving (Show, Eq) coptElem :: CollectionOption -> Field coptElem Capped = "capped" =: True coptElem (MaxByteSize n) = "size" =: n coptElem (MaxItems n) = "max" =: n createCollection :: (MonadIO' m) => [CollectionOption] -> Collection -> Action m Document -- ^ Create collection with given options. You only need to call this to set options, otherwise a collection is created automatically on first use with no options. createCollection opts col = runCommand $ ["create" =: col] ++ map coptElem opts renameCollection :: (MonadIO' m) => Collection -> Collection -> Action m Document -- ^ Rename first collection to second collection renameCollection from to = do db <- thisDatabase useDb admin $ runCommand ["renameCollection" =: db <.> from, "to" =: db <.> to, "dropTarget" =: True] dropCollection :: (MonadIO' m) => Collection -> Action m Bool -- ^ Delete the given collection! Return True if collection existed (and was deleted); return False if collection did not exist (and no action). dropCollection coll = do resetIndexCache r <- runCommand ["drop" =: coll] if true1 "ok" r then return True else do if at "errmsg" r == ("ns not found" :: UString) then return False else fail $ "dropCollection failed: " ++ show r validateCollection :: (MonadIO' m) => Collection -> Action m Document -- ^ This operation takes a while validateCollection coll = runCommand ["validate" =: coll] -- ** Index type IndexName = UString data Index = Index { iColl :: Collection, iKey :: Order, iName :: IndexName, iUnique :: Bool, iDropDups :: Bool } deriving (Show, Eq) idxDocument :: Index -> Database -> Document idxDocument Index{..} db = [ "ns" =: db <.> iColl, "key" =: iKey, "name" =: iName, "unique" =: iUnique, "dropDups" =: iDropDups ] index :: Collection -> Order -> Index -- ^ Spec of index of ordered keys on collection. Name is generated from keys. Unique and dropDups are False. index coll keys = Index coll keys (genName keys) False False genName :: Order -> IndexName genName keys = intercalate "_" (map f keys) where f (k := v) = k `append` "_" `append` pack (show v) ensureIndex :: (MonadIO' m) => Index -> Action m () -- ^ Create index if we did not already create one. May be called repeatedly with practically no performance hit, because we remember if we already called this for the same index (although this memory gets wiped out every 15 minutes, in case another client drops the index and we want to create it again). ensureIndex idx = let k = (iColl idx, iName idx) in do icache <- fetchIndexCache set <- liftIO (readIORef icache) unless (S.member k set) $ do accessMode master (createIndex idx) liftIO $ writeIORef icache (S.insert k set) createIndex :: (MonadIO' m) => Index -> Action m () -- ^ Create index on the server. This call goes to the server every time. createIndex idx = insert_ "system.indexes" . idxDocument idx =<< thisDatabase dropIndex :: (MonadIO' m) => Collection -> IndexName -> Action m Document -- ^ Remove the index dropIndex coll idxName = do resetIndexCache runCommand ["deleteIndexes" =: coll, "index" =: idxName] getIndexes :: (MonadIO m, MonadBaseControl IO m, Functor m) => Collection -> Action m [Document] -- ^ Get all indexes on this collection getIndexes coll = do db <- thisDatabase rest =<< find (select ["ns" =: db <.> coll] "system.indexes") dropIndexes :: (MonadIO' m) => Collection -> Action m Document -- ^ Drop all indexes on this collection dropIndexes coll = do resetIndexCache runCommand ["deleteIndexes" =: coll, "index" =: ("*" :: UString)] -- *** Index cache type DbIndexCache = T.HashTable Database IndexCache -- ^ Cache the indexes we create so repeatedly calling ensureIndex only hits database the first time. Clear cache every once in a while so if someone else deletes index we will recreate it on ensureIndex. type IndexCache = IORef (S.Set (Collection, IndexName)) dbIndexCache :: DbIndexCache -- ^ initialize cache and fork thread that clears it every 15 minutes dbIndexCache = unsafePerformIO $ do table <- T.new (==) (T.hashString . unpack) _ <- forkIO . forever $ threadDelay 900000000 >> clearDbIndexCache return table {-# NOINLINE dbIndexCache #-} clearDbIndexCache :: IO () clearDbIndexCache = do keys <- map fst <$> T.toList dbIndexCache mapM_ (T.delete dbIndexCache) keys fetchIndexCache :: (MonadIO m) => Action m IndexCache -- ^ Get index cache for current database fetchIndexCache = do db <- thisDatabase liftIO $ do mc <- T.lookup dbIndexCache db maybe (newIdxCache db) return mc where newIdxCache db = do idx <- newIORef S.empty T.insert dbIndexCache db idx return idx resetIndexCache :: (MonadIO m) => Action m () -- ^ reset index cache for current database resetIndexCache = do icache <- fetchIndexCache liftIO (writeIORef icache S.empty) -- ** User allUsers :: (MonadIO m, MonadBaseControl IO m, Functor m) => Action m [Document] -- ^ Fetch all users of this database allUsers = map (exclude ["_id"]) <$> (rest =<< find (select [] "system.users") {sort = ["user" =: (1 :: Int)], project = ["user" =: (1 :: Int), "readOnly" =: (1 :: Int)]}) addUser :: (MonadIO' m) => Bool -> Username -> Password -> Action m () -- ^ Add user with password with read-only access if bool is True or read-write access if bool is False addUser readOnly user pass = do mu <- findOne (select ["user" =: user] "system.users") let usr = merge ["readOnly" =: readOnly, "pwd" =: pwHash user pass] (maybe ["user" =: user] id mu) save "system.users" usr removeUser :: (MonadIO m) => Username -> Action m () removeUser user = delete (select ["user" =: user] "system.users") -- ** Database admin :: Database -- ^ \"admin\" database admin = "admin" cloneDatabase :: (MonadIO' m) => Database -> Host -> Action m Document -- ^ Copy database from given host to the server I am connected to. Fails and returns @"ok" = 0@ if we don't have permission to read from given server (use copyDatabase in this case). cloneDatabase db fromHost = useDb db $ runCommand ["clone" =: showHostPort fromHost] copyDatabase :: (MonadIO' m) => Database -> Host -> Maybe (Username, Password) -> Database -> Action m Document -- ^ Copy database from given host to the server I am connected to. If username & password is supplied use them to read from given host. copyDatabase fromDb fromHost mup toDb = do let c = ["copydb" =: (1 :: Int), "fromhost" =: showHostPort fromHost, "fromdb" =: fromDb, "todb" =: toDb] useDb admin $ case mup of Nothing -> runCommand c Just (usr, pss) -> do n <- at "nonce" <$> runCommand ["copydbgetnonce" =: (1 :: Int), "fromhost" =: showHostPort fromHost] runCommand $ c ++ ["username" =: usr, "nonce" =: n, "key" =: pwKey n usr pss] dropDatabase :: (MonadIO' m) => Database -> Action m Document -- ^ Delete the given database! dropDatabase db = useDb db $ runCommand ["dropDatabase" =: (1 :: Int)] repairDatabase :: (MonadIO' m) => Database -> Action m Document -- ^ Attempt to fix any corrupt records. This operation takes a while. repairDatabase db = useDb db $ runCommand ["repairDatabase" =: (1 :: Int)] -- ** Server serverBuildInfo :: (MonadIO' m) => Action m Document serverBuildInfo = useDb admin $ runCommand ["buildinfo" =: (1 :: Int)] serverVersion :: (MonadIO' m) => Action m UString serverVersion = at "version" <$> serverBuildInfo -- * Diagnostics -- ** Collection collectionStats :: (MonadIO' m) => Collection -> Action m Document collectionStats coll = runCommand ["collstats" =: coll] dataSize :: (MonadIO' m) => Collection -> Action m Int dataSize c = at "size" <$> collectionStats c storageSize :: (MonadIO' m) => Collection -> Action m Int storageSize c = at "storageSize" <$> collectionStats c totalIndexSize :: (MonadIO' m) => Collection -> Action m Int totalIndexSize c = at "totalIndexSize" <$> collectionStats c totalSize :: (MonadIO m, MonadBaseControl IO m, MonadIO' m) => Collection -> Action m Int totalSize coll = do x <- storageSize coll xs <- mapM isize =<< getIndexes coll return (foldl (+) x xs) where isize idx = at "storageSize" <$> collectionStats (coll `append` ".$" `append` at "name" idx) -- ** Profiling data ProfilingLevel = Off | Slow | All deriving (Show, Enum, Eq) getProfilingLevel :: (MonadIO' m) => Action m ProfilingLevel getProfilingLevel = toEnum . at "was" <$> runCommand ["profile" =: (-1 :: Int)] type MilliSec = Int setProfilingLevel :: (MonadIO' m) => ProfilingLevel -> Maybe MilliSec -> Action m () setProfilingLevel p mSlowMs = runCommand (["profile" =: fromEnum p] ++ ("slowms" =? mSlowMs)) >> return () -- ** Database dbStats :: (MonadIO' m) => Action m Document dbStats = runCommand ["dbstats" =: (1 :: Int)] currentOp :: (MonadIO m) => Action m (Maybe Document) -- ^ See currently running operation on the database, if any currentOp = findOne (select [] "$cmd.sys.inprog") type OpNum = Int killOp :: (MonadIO m) => OpNum -> Action m (Maybe Document) killOp op = findOne (select ["op" =: op] "$cmd.sys.killop") -- ** Server serverStatus :: (MonadIO' m) => Action m Document serverStatus = useDb admin $ runCommand ["serverStatus" =: (1 :: Int)] {- Authors: Tony Hannan <tony@10gen.com> Copyright 2011 10gen Inc. 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. -}
mongodb/mongoDB-haskell
Database/MongoDB/Admin.hs
apache-2.0
11,209
46
18
1,911
3,130
1,666
1,464
173
3
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} -- Data.ByteString.Unsafe #endif {-# LANGUAGE BangPatterns #-} -- | -- Module : Data.Attoparsec.Zepto -- Copyright : Bryan O'Sullivan 2007-2015 -- License : BSD3 -- -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : unknown -- -- A tiny, highly specialized combinator parser for 'B.ByteString' -- strings. -- -- While the main attoparsec module generally performs well, this -- module is particularly fast for simple non-recursive loops that -- should not normally result in failed parses. -- -- /Warning/: on more complex inputs involving recursion or failure, -- parsers based on this module may be as much as /ten times slower/ -- than regular attoparsec! You should /only/ use this module when you -- have benchmarks that prove that its use speeds your code up. module Data.Attoparsec.Zepto ( Parser , ZeptoT , parse , parseT , atEnd , string , take , takeWhile ) where import Control.Applicative import Control.Monad (MonadPlus(..), ap) import Control.Monad.IO.Class (MonadIO(..)) import Data.ByteString (ByteString) import Data.Functor.Identity (Identity(runIdentity)) import Data.Word (Word8) import Prelude hiding (take, takeWhile) import qualified Data.ByteString as B import qualified Data.ByteString.Unsafe as B #if !MIN_VERSION_base(4,8,0) import Data.Monoid (Monoid(..)) #endif newtype S = S { input :: ByteString } data Result a = Fail String | OK !a S -- | A simple parser. -- -- This monad is strict in its state, and the monadic bind operator -- ('>>=') evaluates each result to weak head normal form before -- passing it along. newtype ZeptoT m a = Parser { runParser :: S -> m (Result a) } type Parser a = ZeptoT Identity a instance Monad m => Functor (ZeptoT m) where fmap f m = Parser $ \s -> do result <- runParser m s case result of OK a s' -> return (OK (f a) s') Fail err -> return (Fail err) {-# INLINE fmap #-} instance MonadIO m => MonadIO (ZeptoT m) where liftIO act = Parser $ \s -> do result <- liftIO act return (OK result s) {-# INLINE liftIO #-} instance Monad m => Monad (ZeptoT m) where return a = Parser $ \s -> return (OK a s) {-# INLINE return #-} m >>= k = Parser $ \s -> do result <- runParser m s case result of OK a s' -> runParser (k a) s' Fail err -> return (Fail err) {-# INLINE (>>=) #-} fail msg = Parser $ \_ -> return (Fail msg) {-# INLINE fail #-} instance Monad m => MonadPlus (ZeptoT m) where mzero = fail "mzero" {-# INLINE mzero #-} mplus a b = Parser $ \s -> do result <- runParser a s case result of ok@(OK _ _) -> return ok _ -> runParser b s {-# INLINE mplus #-} instance (Monad m) => Applicative (ZeptoT m) where pure = return {-# INLINE pure #-} (<*>) = ap {-# INLINE (<*>) #-} gets :: Monad m => (S -> a) -> ZeptoT m a gets f = Parser $ \s -> return (OK (f s) s) {-# INLINE gets #-} put :: Monad m => S -> ZeptoT m () put s = Parser $ \_ -> return (OK () s) {-# INLINE put #-} -- | Run a parser. parse :: Parser a -> ByteString -> Either String a parse p bs = case runIdentity (runParser p (S bs)) of (OK a _) -> Right a (Fail err) -> Left err {-# INLINE parse #-} -- | Run a parser on top of the given base monad. parseT :: Monad m => ZeptoT m a -> ByteString -> m (Either String a) parseT p bs = do result <- runParser p (S bs) case result of OK a _ -> return (Right a) Fail err -> return (Left err) {-# INLINE parseT #-} instance Monad m => Monoid (ZeptoT m a) where mempty = fail "mempty" {-# INLINE mempty #-} mappend = mplus {-# INLINE mappend #-} instance Monad m => Alternative (ZeptoT m) where empty = fail "empty" {-# INLINE empty #-} (<|>) = mplus {-# INLINE (<|>) #-} -- | Consume input while the predicate returns 'True'. takeWhile :: Monad m => (Word8 -> Bool) -> ZeptoT m ByteString takeWhile p = do (h,t) <- gets (B.span p . input) put (S t) return h {-# INLINE takeWhile #-} -- | Consume @n@ bytes of input. take :: Monad m => Int -> ZeptoT m ByteString take !n = do s <- gets input if B.length s >= n then put (S (B.unsafeDrop n s)) >> return (B.unsafeTake n s) else fail "insufficient input" {-# INLINE take #-} -- | Match a string exactly. string :: Monad m => ByteString -> ZeptoT m () string s = do i <- gets input if s `B.isPrefixOf` i then put (S (B.unsafeDrop (B.length s) i)) >> return () else fail "string" {-# INLINE string #-} -- | Indicate whether the end of the input has been reached. atEnd :: Monad m => ZeptoT m Bool atEnd = do i <- gets input return $! B.null i {-# INLINE atEnd #-}
beni55/attoparsec
Data/Attoparsec/Zepto.hs
bsd-3-clause
4,901
0
17
1,266
1,438
757
681
121
2
module Test where import Data.Time.Clock import Types testToken = SessionToken 1 "" credentials = Plaintext "test" "abc" testUser = getCurrentTime >>= (\t -> return $ User 0 "test" "abc" "Test" "test@test.edu" (Just "5555555555") (Just "562 E. 12th Street") t)
hherman1/CatanServ
src/Test.hs
bsd-3-clause
264
0
11
42
83
45
38
6
1
{- | Module : $Header$ Description : Static QVTR analysis Copyright : (c) Daniel Calegari Universidad de la Republica, Uruguay 2013 License : GPLv2 or higher, see LICENSE.txt Maintainer : dcalegar@fing.edu.uy Stability : provisional Portability : portable -} module QVTR.StatAna where import QVTR.As import QVTR.Sign import qualified CSMOF.As as CSMOFAs import qualified CSMOF.Sign as CSMOFSign import qualified CSMOF.StatAna as CSMOFStatAna import Common.Result import Common.GlobalAnnotations import Common.ExtSign import Common.AS_Annotation import qualified Data.Map as Map import qualified Data.Set as Set import qualified Common.Lib.Rel as Rel basicAna :: (Transformation, Sign, GlobalAnnos) -> Result (Transformation, ExtSign Sign (), [Named Sen]) basicAna (trans, _, _) = let (sign, diagSign) = buildSignature trans (sen, diagSen) = buildSentences sign trans in Result (reverse diagSign ++ reverse diagSen) $ Just (trans, mkExtSign sign, sen) buildSignature :: Transformation -> (Sign, [Diagnosis]) buildSignature (Transformation _ souMet tarMet kS rels) = let souMetSign = CSMOFStatAna.buildSignature (third souMet) tarMetSign = CSMOFStatAna.buildSignature (third tarMet) (relat, diagn) = buildRelations souMetSign tarMetSign rels (keyD, diagn2) = buildKeyDefs souMetSign tarMetSign kS in (Sign { sourceSign = souMetSign , targetSign = tarMetSign , nonTopRelations = fst relat , topRelations = snd relat , keyDefs = keyD } , diagn ++ diagn2) buildRelations :: CSMOFSign.Sign -> CSMOFSign.Sign -> [Relation] -> ((Map.Map String RuleDef, Map.Map String RuleDef), [Diagnosis]) buildRelations souMetSign tarMetSign rels = let (nonTopRel, topRel) = separateTopFromNonTop rels calledTopRules = map createCalledTopRule topRel (nonTopRuleDef, diagn1) = foldr (createRuleDef souMetSign tarMetSign) (Map.empty, []) (nonTopRel ++ calledTopRules) (topRuleDef, diagn2) = foldr (createRuleDef souMetSign tarMetSign) (Map.empty, []) topRel in ((nonTopRuleDef, topRuleDef), diagn1 ++ diagn2) separateTopFromNonTop :: [Relation] -> ([Relation], [Relation]) separateTopFromNonTop rels = case rels of [] -> ([], []) r : rest -> let result = separateTopFromNonTop rest in if isTop r then (fst result, r : snd result) else (r : fst result, snd result) isTop :: Relation -> Bool isTop (Relation tp _ _ _ _ _ _ _) = tp createRuleDef :: CSMOFSign.Sign -> CSMOFSign.Sign -> Relation -> (Map.Map String RuleDef, [Diagnosis]) -> (Map.Map String RuleDef, [Diagnosis]) createRuleDef souMetSign tarMetSign (Relation tp rName _ prD souD tarD _ _) (mapRD, diag) = let (varTyp, diag2) = getTypesFromVars souMetSign tarMetSign prD souD tarD in if tp then case Map.lookup ("Top_" ++ rName) mapRD of Nothing -> (Map.insert ("Top_" ++ rName) (RuleDef ("Top_" ++ rName) tp []) mapRD, diag ++ diag2) Just r -> (mapRD, mkDiag Error "rule names must be unique" (QVTR.Sign.name r) : (diag ++ diag2)) else case Map.lookup rName mapRD of Nothing -> (Map.insert rName (RuleDef rName tp varTyp) mapRD, diag ++ diag2) Just r -> (mapRD, mkDiag Error "rule names must be unique" (QVTR.Sign.name r) : (diag ++ diag2)) -- Generate rule parameters from primitive domains, source and target object domains getTypesFromVars :: CSMOFSign.Sign -> CSMOFSign.Sign -> [PrimitiveDomain] -> Domain -> Domain -> ([CSMOFSign.TypeClass], [Diagnosis]) getTypesFromVars souMetSign tarMetSign primD souD tarD = let (souDomObj, d1) = getDomainType souMetSign souD (tarDomObj, d2) = getDomainType tarMetSign tarD (pTypes, d3) = unzip $ map (getPrimitiveDomainType souMetSign tarMetSign) primD primTypes = getSomething pTypes in case souDomObj of Nothing -> case tarDomObj of Nothing -> (primTypes, d1 ++ d2 ++ concat d3) Just tDO -> (tDO : primTypes, concat d3) Just sDO -> case tarDomObj of Nothing -> (sDO : primTypes, d1 ++ d2 ++ concat d3) Just tDO -> (sDO : (tDO : primTypes), concat d3) getDomainType :: CSMOFSign.Sign -> Domain -> (Maybe CSMOFSign.TypeClass, [Diagnosis]) getDomainType metSign (Domain _ (ObjectTemplate _ _ dType _)) = getType (Set.toList (CSMOFSign.types metSign)) dType getPrimitiveDomainType :: CSMOFSign.Sign -> CSMOFSign.Sign -> PrimitiveDomain -> (Maybe CSMOFSign.TypeClass, [Diagnosis]) getPrimitiveDomainType souMetSign tarMetSign (PrimitiveDomain _ prType) = let (typ, diag) = getType (Set.toList (CSMOFSign.types souMetSign)) prType in case typ of Nothing -> let (typ2, diag2) = getType (Set.toList (CSMOFSign.types tarMetSign)) prType in case typ2 of Nothing -> (typ2, diag ++ diag2) Just _ -> (typ2, []) Just _ -> (typ, []) getType :: [CSMOFSign.TypeClass] -> String -> (Maybe CSMOFSign.TypeClass, [Diagnosis]) getType types dType = case types of [] -> (Nothing, [mkDiag Error "type not found" dType]) typ : rest -> if CSMOFSign.name typ == dType then (Just typ, []) else getType rest dType getSomething :: [Maybe a] -> [a] getSomething list = case list of [] -> [] el : rest -> case el of Nothing -> getSomething rest Just typ -> typ : getSomething rest -- Creates a non-top version of a top rule in order to generate a parametrized version of itself createCalledTopRule :: Relation -> Relation createCalledTopRule (Relation tp a b c d e f g) = Relation (not tp) a b c d e f g buildKeyDefs :: CSMOFSign.Sign -> CSMOFSign.Sign -> [Key] -> ([(String, String)], [Diagnosis]) buildKeyDefs _ _ [] = ([], []) buildKeyDefs souMet tarMet (k : rest) = let (restK, diag) = buildKeyDefs souMet tarMet rest (ke, diag2) = buildKeyDef souMet tarMet k in case ke of Nothing -> (restK, diag ++ diag2) Just el -> (el : restK, diag ++ diag2) buildKeyDef :: CSMOFSign.Sign -> CSMOFSign.Sign -> Key -> (Maybe (String, String), [Diagnosis]) buildKeyDef souMet tarMet k = let (typ, diag) = getType (Set.toList (CSMOFSign.types souMet)) (typeName k) in case typ of Nothing -> let (typ2, diag2) = getType (Set.toList (CSMOFSign.types tarMet)) (typeName k) in case typ2 of Nothing -> (Nothing, mkDiag Error "type not found" (typeName k) : (diag ++ diag2)) Just _ -> if propKeysCheckOK tarMet (typeName k) (properties k) then (Just (metamodel k, typeName k), []) else (Nothing, mkDiag Error "property not found" (properties k) : (diag ++ diag2)) Just _ -> if propKeysCheckOK souMet (typeName k) (properties k) then (Just (metamodel k, typeName k), []) else (Nothing, mkDiag Error "property not found" (properties k) : diag) -- ------ Sentences -------- buildSentences :: Sign -> Transformation -> ([Named Sen], [Diagnosis]) buildSentences sign (Transformation _ souMet tarMet kes rels) = let (_, sMetN, _) = souMet (_, tMetN, _) = tarMet (keyConstr, diag) = buildKeyConstr sign sMetN tMetN kes (qvtRules, diag2) = buildRules sign souMet tarMet rels in (keyConstr ++ qvtRules, diag ++ diag2) buildKeyConstr :: Sign -> String -> String -> [Key] -> ([Named Sen], [Diagnosis]) buildKeyConstr _ _ _ [] = ([], []) buildKeyConstr sign sMetN tMetN (k : rest) = let (restK, diag) = buildKeyConstr sign sMetN tMetN rest (ke, diag2) = buildKeyC sign sMetN tMetN k in case ke of Nothing -> (restK, diag ++ diag2) Just el -> (el : restK, diag ++ diag2) buildKeyC :: Sign -> String -> String -> Key -> (Maybe (Named Sen), [Diagnosis]) buildKeyC sign sMetN tMetN k = if sMetN == metamodel k || tMetN == metamodel k then let (typ, diag) = getType (Set.toList (CSMOFSign.types (sourceSign sign))) (typeName k) in case typ of Nothing -> let (typ2, diag2) = getType (Set.toList (CSMOFSign.types (targetSign sign))) (typeName k) in case typ2 of Nothing -> (Nothing, mkDiag Error "type not found" (typeName k) : (diag ++ diag2)) Just _ -> if propKeysCheckOK (targetSign sign) (typeName k) (properties k) then (Just (makeNamed "" KeyConstr { keyConst = k }), []) else (Nothing, mkDiag Error "property not found" (properties k) : (diag ++ diag2)) Just _ -> if propKeysCheckOK (sourceSign sign) (typeName k) (properties k) then (Just (makeNamed "" KeyConstr { keyConst = k }), []) else (Nothing, mkDiag Error "property not found" (properties k) : diag) else (Nothing, [mkDiag Error "metamodel does not exist" (sMetN ++ "-" ++ tMetN)]) propKeysCheckOK :: CSMOFSign.Sign -> String -> [PropKey] -> Bool propKeysCheckOK _ _ [] = True propKeysCheckOK metSign kType (ke : rest) = propKeyCheckOK metSign kType ke && propKeysCheckOK metSign kType rest propKeyCheckOK :: CSMOFSign.Sign -> String -> PropKey -> Bool propKeyCheckOK (CSMOFSign.Sign _ typRel _ _ props _ _) kType (SimpleProp pN) = findProperty typRel props kType pN propKeyCheckOK (CSMOFSign.Sign _ typRel _ _ props _ _) kType (OppositeProp oppPType oppPName) = findOppProperty typRel props kType oppPType oppPName findProperty :: Rel.Rel CSMOFSign.TypeClass -> Set.Set CSMOFSign.PropertyT -> String -> String -> Bool findProperty typRel props kType pN = let classes = kType : Set.toList (superClasses (Rel.map CSMOFSign.name typRel) kType) in findPropertyByTypeAndRole (Set.toList props) classes pN findPropertyByTypeAndRole :: [CSMOFSign.PropertyT] -> [String] -> String -> Bool findPropertyByTypeAndRole [] _ _ = False findPropertyByTypeAndRole (p : rest) classes pN = (elem (CSMOFSign.name (CSMOFSign.sourceType p)) classes && CSMOFSign.targetRole p == pN) || (elem (CSMOFSign.name (CSMOFSign.targetType p)) classes && CSMOFSign.sourceRole p == pN) || findPropertyByTypeAndRole rest classes pN superClasses :: Rel.Rel String -> String -> Set.Set String superClasses relT tc = Set.fold reach Set.empty $ Rel.succs relT tc where reach e s = if Set.member e s then s else Set.fold reach (Set.insert e s) $ Rel.succs relT e findPropertyInHierarchy :: Rel.Rel CSMOFSign.TypeClass -> Set.Set CSMOFSign.PropertyT -> String -> String -> Maybe CSMOFSign.PropertyT findPropertyInHierarchy typRel props kType pN = let classes = kType : Set.toList (superClasses (Rel.map CSMOFSign.name typRel) kType) in findPropertyElemByTypeAndRole (Set.toList props) classes pN findPropertyElemByTypeAndRole :: [CSMOFSign.PropertyT] -> [String] -> String -> Maybe CSMOFSign.PropertyT findPropertyElemByTypeAndRole [] _ _ = Nothing findPropertyElemByTypeAndRole (p : rest) classes pN = if (elem (CSMOFSign.name (CSMOFSign.sourceType p)) classes && CSMOFSign.targetRole p == pN) || (elem (CSMOFSign.name (CSMOFSign.targetType p)) classes && CSMOFSign.sourceRole p == pN) then Just p else findPropertyElemByTypeAndRole rest classes pN findOppProperty :: Rel.Rel CSMOFSign.TypeClass -> Set.Set CSMOFSign.PropertyT -> String -> String -> String -> Bool findOppProperty typRel props kType oppPType oppPName = let classes = oppPType : Set.toList (superClasses (Rel.map CSMOFSign.name typRel) oppPType) in findOppPropertyByTypeAndRole (Set.toList props) classes oppPName kType findOppPropertyByTypeAndRole :: [CSMOFSign.PropertyT] -> [String] -> String -> String -> Bool findOppPropertyByTypeAndRole [] _ _ _ = False findOppPropertyByTypeAndRole (p : rest) classes pN kType = (elem (CSMOFSign.name (CSMOFSign.sourceType p)) classes && CSMOFSign.targetRole p == pN && CSMOFSign.name (CSMOFSign.targetType p) == kType) || (elem (CSMOFSign.name (CSMOFSign.targetType p)) classes && CSMOFSign.sourceRole p == pN && CSMOFSign.name (CSMOFSign.sourceType p) == kType) || findOppPropertyByTypeAndRole rest classes pN kType getTargetType :: String -> CSMOFSign.PropertyT -> String getTargetType pN p = CSMOFSign.name $ if CSMOFSign.targetRole p == pN then CSMOFSign.targetType p else CSMOFSign.sourceType p getOppositeType :: String -> CSMOFSign.PropertyT -> String getOppositeType pN p = CSMOFSign.name $ if CSMOFSign.sourceRole p == pN then CSMOFSign.targetType p else CSMOFSign.sourceType p third :: (String, String, CSMOFAs.Metamodel) -> CSMOFAs.Metamodel third (_, _, c) = c buildRules :: Sign -> (String, String, CSMOFAs.Metamodel) -> (String, String, CSMOFAs.Metamodel) -> [Relation] -> ([Named Sen], [Diagnosis]) buildRules sign souMet tarMet rul = let (rel, diag) = checkRules sign souMet tarMet rul in (map (\ r -> makeNamed "" QVTSen { rule = r }) rel, diag) checkRules :: Sign -> (String, String, CSMOFAs.Metamodel) -> (String, String, CSMOFAs.Metamodel) -> [Relation] -> ([RelationSen], [Diagnosis]) checkRules _ _ _ [] = ([], []) checkRules sign souMet tarMet (r : rest) = let (rul, diag) = checkRule sign souMet tarMet r (restRul, restDiag) = checkRules sign souMet tarMet rest in (rul ++ restRul, diag ++ restDiag) checkRule :: Sign -> (String, String, CSMOFAs.Metamodel) -> (String, String, CSMOFAs.Metamodel) -> Relation -> ([RelationSen], [Diagnosis]) checkRule sign _ _ (Relation tp rN vS prD souDom tarDom whenC whereC) = let rName = if tp then "Top_" ++ rN else rN (rDefNonTop, rDiagNonTop) = case Map.lookup rN (nonTopRelations sign) of Nothing -> (RuleDef "" False [], [mkDiag Error "non top relation not found" rName]) Just r -> (r, []) (rDef, rDiag) = if tp then case Map.lookup rName (topRelations sign) of Nothing -> (RuleDef "" False [], [mkDiag Error "top relation not found" rName]) Just r -> (r, []) else (RuleDef "" False [], []) pSet = collectParSet prD souDom tarDom vSet = collectVarSet vS prD souDom tarDom (souPat, diagSPat) = buildPattern souDom (sourceSign sign) vSet (tarPat, diagTPat) = buildPattern tarDom (targetSign sign) vSet (whenCl, diagW1Pat) = checkWhenWhere whenC (whereCl, diagW2Pat) = checkWhenWhere whereC in if tp then (RelationSen rDef vSet [] souPat tarPat whenCl whereCl : -- Top Rule [RelationSen rDefNonTop vSet pSet souPat tarPat whenCl whereCl], -- Non Top Rule rDiag ++ rDiagNonTop ++ diagSPat ++ diagTPat ++ diagW1Pat ++ diagW2Pat) else ([RelationSen rDefNonTop vSet pSet souPat tarPat whenCl whereCl], rDiag ++ rDiagNonTop ++ diagSPat ++ diagTPat ++ diagW1Pat ++ diagW2Pat) collectParSet :: [PrimitiveDomain] -> Domain -> Domain -> [RelVar] collectParSet prD souDom tarDom = let prDVS = collectPrimDomVarSet prD souVar = RelVar (domType $ template souDom) (domVar $ template souDom) tarVar = RelVar (domType $ template tarDom) (domVar $ template tarDom) in [souVar, tarVar] ++ prDVS collectVarSet :: [RelVar] -> [PrimitiveDomain] -> Domain -> Domain -> [RelVar] collectVarSet varS prD souDom tarDom = let souDomVS = collectDomainVarSet souDom tarDomVS = collectDomainVarSet tarDom prDVS = collectPrimDomVarSet prD in varS ++ prDVS ++ souDomVS ++ tarDomVS collectPrimDomVarSet :: [PrimitiveDomain] -> [RelVar] collectPrimDomVarSet = map (\ n -> RelVar (primType n) (primName n)) collectDomainVarSet :: Domain -> [RelVar] collectDomainVarSet dom = collectRecursiveVars (Just $ template dom) collectRecursiveVars :: Maybe ObjectTemplate -> [RelVar] collectRecursiveVars Nothing = [] collectRecursiveVars (Just ot) = let otVar = RelVar (domType ot) (domVar ot) in otVar : foldr ((++) . collectRecursiveVars . objTemp) [] (templateList ot) buildPattern :: Domain -> CSMOFSign.Sign -> [RelVar] -> (Pattern, [Diagnosis]) buildPattern dom sign vSet = let (patR, diag) = collectRecursiveRelInvoc (domVar (template dom)) (domType (template dom)) (templateList (template dom)) sign vSet patPr = collectRecursivePreds vSet (Just $ template dom) in (Pattern (collectDomainVarSet dom) patR patPr, diag) collectRecursiveRelInvoc :: String -> String -> [PropertyTemplate] -> CSMOFSign.Sign -> [RelVar] -> ([(CSMOFSign.PropertyT, RelVar, RelVar)], [Diagnosis]) collectRecursiveRelInvoc _ _ [] _ _ = ([], []) collectRecursiveRelInvoc nam typ (pt : restPT) sign vSet = case objTemp pt of Nothing -> ([], []) Just ot -> let prop = findPropertyInHierarchy (CSMOFSign.typeRel sign) (CSMOFSign.properties sign) typ (pName pt) (restProps, diagn) = collectRecursiveRelInvoc nam typ restPT sign vSet (recPr, recDiag) = collectRecursiveRelInvoc (domVar ot) (domType ot) (templateList ot) sign vSet in case prop of Nothing -> ([], mkDiag Error "property not found" pt : (diagn ++ recDiag)) Just p -> let souV = RelVar typ nam tarV = getVarFromTemplate pt vSet in case tarV of Nothing -> (restProps ++ recPr, diagn ++ recDiag) -- it is a OCL expression, not a variable Just relVar -> ((p, souV, relVar) : (restProps ++ recPr), diagn ++ recDiag) getVarFromTemplate :: PropertyTemplate -> [RelVar] -> Maybe RelVar getVarFromTemplate (PropertyTemplate _ ocl _) relV = case ocl of Nothing -> Nothing Just (StringExp (VarExp v)) -> findVarFromName v relV _ -> Nothing findVarFromName :: String -> [RelVar] -> Maybe RelVar findVarFromName _ [] = Nothing findVarFromName nam (v : restV) = if varName v == nam then Just v else findVarFromName nam restV collectRecursivePreds :: [RelVar] -> Maybe ObjectTemplate -> [(String, String, OCL)] collectRecursivePreds _ Nothing = [] collectRecursivePreds vSet (Just ot) = let tList = templateList ot oclExps = foldr ((++) . getOclExpre (domVar ot) vSet) [] tList in oclExps ++ foldr ((++) . collectRecursivePreds vSet . objTemp) [] tList getOclExpre :: String -> [RelVar] -> PropertyTemplate -> [(String, String, OCL)] getOclExpre otN _ (PropertyTemplate pN ocl objT) = case ocl of Nothing -> case objT of Nothing -> [] Just o -> [(pN, otN, StringExp (VarExp (domVar o)))] -- ToDo Diagnosis Just s -> [(pN, otN, s)] -- ToDo Diagnosis checkWhenWhere :: Maybe WhenWhere -> (Maybe WhenWhere, [Diagnosis]) checkWhenWhere ww = (ww, []) -- ToDo Diagnosis {- ToDo :: Diagnosis las Keys no son vacias los tipos en RelVar existen los tipos en PrimitiveDomain existen los nombres de variables en RelVar, PrimitiveDomain, Domain no se repiten el domModelId del source y target Domain son los de la transformacion los domMeta del source (de todos los obj templ) es el del source de la trans. Idem para el target los domType del source y target existen en el source y target meta, respectivamente los pName son propiedades que existen en cada domType no hago nada con las oclExpre para cada RelInVok de un WhenWhere, el nombre de la regla existe para cada RelInvok los parametros son variables definidas y tienen los tipos de la relacion -} -- Get every ObjectTemplate from a Domain (recursive) getObjectTemplates :: Domain -> [ObjectTemplate] getObjectTemplates dom = template dom : getObjectTemplatesFromOT (template dom) getObjectTemplatesFromOT :: ObjectTemplate -> [ObjectTemplate] getObjectTemplatesFromOT ot = let otList = getOT $ templateList ot in foldr ((++) . getObjectTemplatesFromOT) [] otList getOT :: [PropertyTemplate] -> [ObjectTemplate] getOT list = case list of [] -> [] el : rest -> case objTemp el of Nothing -> getOT rest Just typ -> typ : getOT rest
keithodulaigh/Hets
QVTR/StatAna.hs
gpl-2.0
21,548
0
22
6,059
6,819
3,558
3,261
395
6
{-# OPTIONS_GHC -fno-warn-orphans #-} import Blaze.ByteString.Builder (toLazyByteString) import Blaze.ByteString.Builder.Char.Utf8 (fromString) import Control.DeepSeq (NFData(rnf)) import Criterion.Main import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Internal as BL main :: IO () main = do defaultMain [ --bgroup "call" [ -- bench "incrementCount" $ nf undefined -- bench "resetCount" $ nf undefined --] ]
qnikst/distributed-process-client-server
benchmarks/src/CounterServer.hs
bsd-3-clause
475
0
8
86
91
59
32
10
1
{-# language LambdaCase #-} {-# language OverloadedLists #-} {-# language OverloadedStrings #-} {-# language PatternSynonyms #-} {-# language QuasiQuotes #-} {-# language TypeApplications #-} module Planetary.Library.FrankExamples (resolvedDecls) where import Control.Lens import Control.Monad.Except import Control.Monad.IO.Class (liftIO) import Data.Text (Text) import Data.Traversable (for) import qualified Data.Text as T import System.IO (hFlush, stdout) import NeatInterpolation import Network.IPLD import Planetary.Core import Planetary.Library.HaskellForeign hiding (resolvedDecls) import Planetary.Support.Ids import Planetary.Support.NameResolution import Planetary.Support.Parser import Planetary.Util -- Examples from the Frank paper. -- We need some ffi definitions for working with chars / strings -- (eraseCharLit, textMap, charHandler1, charHandler2) lookupArgs :: EvalState -> Maybe (Vector TmI) lookupArgs st = do let addrs = undefined -- (_, addrs) <- st ^? evalEnv . _head let store = st ^. evalStore for addrs $ \addr -> do ipld <- store ^? ix addr fromIpld ipld eraseCharLit :: TmI eraseCharLit = todo "eraseCharLit" -- mkForeignTm @Text textId [] "\b \b" -- TODO: we actually map with a data constructor textMap :: Handler textMap st | Just [Closure _binderNames _env body, ForeignValue _ _ uid] <- lookupArgs st = do fText <- lookupForeign uid let str = T.unpack fText fun :: Char -> ForeignM Char fun char = do charPtr <- ForeignValue charId [] <$> writeForeign char -- HACK XXX ouch $ st & evalFocus .~ charPtr pure char result <- T.pack <$> traverse fun str result' <- writeForeign result pure $ st & evalFocus .~ ForeignValue textId [] result' textMap _ = throwError (FailedForeignFun "textMap") -- charHandler1 :: TmI -> TmI -> Char -> TmI charHandler1 :: Handler charHandler1 st | Just [Closure _ env1 b1, Closure _ env2 b2, ForeignValue _ _ uid] <- lookupArgs st = do char <- lookupForeign uid pure $ st & evalFocus .~ case char of '\b' -> b1 c -> todo "AppN (mkForeignTm @Char charId [] c) [b2]" charHandler1 _ = throwError (FailedForeignFun "charHandler1") -- charHandler2 :: TmI -> TmI -> TmI -> Char -> TmI charHandler2 :: Handler charHandler2 st | Just [b1@Closure{}, b2@Closure{}, b3@Closure{}, ForeignValue _ _ uid] <- lookupArgs st = do Closure _names env focus <- (<$> lookupForeign uid) $ \case '0' -> b1 ' ' -> b2 _ -> b3 pure $ st & evalFocus .~ focus -- TODO: really not sure if this method of setting env is right. If so, -- duplicate in charHandler1 & evalEnv .~ env charHandler2 _ = throwError (FailedForeignFun "charHandler2") inch :: Handler inch st | Just [] <- lookupArgs st = do c <- liftIO getChar -- Taken from Shonky/Semantics let c' = if c == '\DEL' then '\b' else c c'' <- writeForeign c' pure $ st & evalFocus .~ ForeignValue charId [] c'' inch _ = throwError (FailedForeignFun "inch") ouch :: Handler ouch st | Just [ForeignValue _ _ uid] <- lookupArgs st = do c <- lookupForeign uid liftIO $ putChar c >> hFlush stdout pure $ st & evalFocus .~ DataConstructor unitId 0 [] ouch _ = throwError (FailedForeignFun "ouch") externals :: Handlers externals = [ (consoleId, [ inch, ouch ]) , (textId, [ textMap ]) , (charHandlerId, [ charHandler1, charHandler2 ]) ] ambientHandlers :: AmbientHandlers ambientHandlers = AmbientHandlers externals -- runIt :: IO () -- runIt = print . fst =<< run env [] main -- TODO: -- * fix up textMap -- * how is this actually run? decls :: [Decl Text] store :: ValueStore (decls, store) = forceDeclarations [text| data Zero = -- no constructors data Unit = | <unit> data Bool = | <ff> | <tt> data Pair X Y = | <pair X Y> -- TODO NatF is duplicated in Eval.Test data NatF Nat = | <zero> | <suc Nat> -- TODO ListF is duplicated in HaskellForeign.Test data ListF X list = | <nil> | <cons X <list X>> interface Send X = | send : X -> <Unit> interface Receive X = | receive : X interface State S = | get : S | put : S -> Unit interface Abort = | aborting : <Zero> interface LookAhead = | peek : char | accept : <Unit> interface Console = | inch : char | ouch : char -> <Unit> -- XXX inductive data LogF [e] X Log = | <start {[e]X}> | <inched <Log [e] X> {char -> [e]X}> | <ouched <Log [e] X>> data Buffer = | <empty> | <hold char> interface Choose = | choose : <Bool> data Toss = | <heads> | <tails> -- HACK: Writing this so name resolution will complete. The example uses the -- name List though technically it's ListF but we don't have type synonyms or -- whatever. This only works because we're not typechecking (though we should). data List = main = letrec input : forall X. {<LogF [<LookAhead>, <Abort>, <Console>] X> -> Buffer -> X -> [Console]X} = \log buffer x -> handle x : X with LookAhead: | <peek -> k> -> case buffer of | <hold c> -> input <Buffer.0 c> (k c) | <empty> -> on Console.0! (charHandler1 (rollback l) -- '\b' (\c -> input <LogF.1 l k> <Buffer.0 c> (k c)) -- other char ) | <accept -> k> -> case buffer of | <hold c> -> snd (Console.1 c) (input <LogF.2 l> empty (k unit)) | <empty> -> input l empty (k unit) Abort: | <aborting -> k> -> rollback log | x -> x rollback : forall X. {<LogF [<LookAhead>, <Abort>, <Console>] X> -> [<Console>]X} = \x -> case x of | <start p> -> parse p | <ouched l> -> snd (textMap Console.1 "\b \b") (rollback l) | <inched l k> -> input l empty (k LookAhead.0!) parse : forall X. {{[<LookAhead>, <Abort>, <Console>]X} -> [<Console>]X} = \p -> input <LogF.0 p> empty p! on : forall X Y. {X -> {X -> Y} -> Y} = \x f -> f x snd : forall X Y. {X -> Y -> X} = \x y -> y zeros : forall. {Int -> [<LookAhead>, <Abort>]Int} = \n -> on LookAhead.0! (charHandler2 (snd LookAhead.1! (zeros (add n 1))) -- '0' (snd LookAhead.1! n) -- ' ' (abort!) -- other char ) -- in (parse (zeros zero) : [<Console>]Int) in parse (zeros zero) -- is this a module? fns = letrec fst : forall X Y. {X -> Y -> X} = \x y -> x if_ : forall X. {<Bool> -> {X} -> {X} -> X} = \val t f -> case val of | <tt> -> t! | <ff> -> f! -- TODO: consider why Abort doesn't appear in the signature -- catch : forall X. {<Abort>X -> {X} -> X} catch : forall X. {X -> {X} -> X} = \x h -> handle x : X with Abort: | <aborting -> _> -> h! -- handle the abort -- TODO: we require renaming the value here? | x -> x -- it returned a value, pass on in catch pipe = letrec pipe : forall [e] X Y. { {{[e, <Abort>, <Send X>] Unit} -> [e, <Abort>, <Receive X>] Y} -> [e, <Abort>] Y} -- TODO change the lambda delimiter from `->` to `.` like the paper? = \x y -> handle y! : [e, <Abort>] Y with Send X: | <send x -> s> -> handle y! : [e, <Abort>] Y with Receive X: | <receive -> r> -> pipe (s unit) (r x) | y -> y | x -> case x of | <unit> -> handle y! : [e, <Abort>] Y with Receive X: | <aborting -> r> -> abort! | y -> y in pipe |] -- TODO charId, eraseCharLitId, addId, zeroId :: Cid charId = mkCid "TODO charId" eraseCharLitId = mkCid "TODO eraseCharLitId" addId = mkCid "TODO addId" zeroId = mkCid "TODO zeroId" predefined :: UIdMap Text Cid predefined = [ ("char", charId) , ("eraseCharLit", eraseCharLitId) , ("Int", intId) , ("add", addId) , ("zero", zeroId) ] resolvedDecls :: ResolvedDecls Right resolvedDecls = resolveDecls predefined decls
joelburget/interplanetary-computation
src/Planetary/Library/FrankExamples.hs
bsd-3-clause
8,065
0
16
2,255
1,164
608
556
108
3
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 @Uniques@ are used to distinguish entities in the compiler (@Ids@, @Classes@, etc.) from each other. Thus, @Uniques@ are the basic comparison key in the compiler. If there is any single operation that needs to be fast, it is @Unique@ comparison. Unsurprisingly, there is quite a bit of huff-and-puff directed to that end. Some of the other hair in this code is to be able to use a ``splittable @UniqueSupply@'' if requested/possible (not standard Haskell). -} {-# LANGUAGE CPP, BangPatterns, MagicHash #-} module Unique ( -- * Main data types Unique, Uniquable(..), -- ** Constructors, destructors and operations on 'Unique's hasKey, cmpByUnique, pprUnique, mkUniqueGrimily, -- Used in UniqSupply only! getKey, -- Used in Var, UniqFM, Name only! mkUnique, unpkUnique, -- Used in BinIface only incrUnique, -- Used for renumbering deriveUnique, -- Ditto newTagUnique, -- Used in CgCase initTyVarUnique, -- ** Making built-in uniques -- now all the built-in Uniques (and functions to make them) -- [the Oh-So-Wonderful Haskell module system wins again...] mkAlphaTyVarUnique, mkPrimOpIdUnique, mkTupleTyConUnique, mkTupleDataConUnique, mkCTupleTyConUnique, mkPreludeMiscIdUnique, mkPreludeDataConUnique, mkPreludeTyConUnique, mkPreludeClassUnique, mkPArrDataConUnique, mkCoVarUnique, mkVarOccUnique, mkDataOccUnique, mkTvOccUnique, mkTcOccUnique, mkRegSingleUnique, mkRegPairUnique, mkRegClassUnique, mkRegSubUnique, mkCostCentreUnique, tyConRepNameUnique, dataConWorkerUnique, dataConRepNameUnique, mkBuiltinUnique, mkPseudoUniqueD, mkPseudoUniqueE, mkPseudoUniqueH ) where #include "HsVersions.h" import BasicTypes import FastString import Outputable import Util -- just for implementing a fast [0,61) -> Char function import GHC.Exts (indexCharOffAddr#, Char(..), Int(..)) import Data.Char ( chr, ord ) import Data.Bits {- ************************************************************************ * * \subsection[Unique-type]{@Unique@ type and operations} * * ************************************************************************ The @Chars@ are ``tag letters'' that identify the @UniqueSupply@. Fast comparison is everything on @Uniques@: -} --why not newtype Int? -- | The type of unique identifiers that are used in many places in GHC -- for fast ordering and equality tests. You should generate these with -- the functions from the 'UniqSupply' module data Unique = MkUnique {-# UNPACK #-} !Int {- Now come the functions which construct uniques from their pieces, and vice versa. The stuff about unique *supplies* is handled further down this module. -} unpkUnique :: Unique -> (Char, Int) -- The reverse mkUniqueGrimily :: Int -> Unique -- A trap-door for UniqSupply getKey :: Unique -> Int -- for Var incrUnique :: Unique -> Unique stepUnique :: Unique -> Int -> Unique deriveUnique :: Unique -> Int -> Unique newTagUnique :: Unique -> Char -> Unique mkUniqueGrimily = MkUnique {-# INLINE getKey #-} getKey (MkUnique x) = x incrUnique (MkUnique i) = MkUnique (i + 1) stepUnique (MkUnique i) n = MkUnique (i + n) -- deriveUnique uses an 'X' tag so that it won't clash with -- any of the uniques produced any other way -- SPJ says: this looks terribly smelly to me! deriveUnique (MkUnique i) delta = mkUnique 'X' (i + delta) -- newTagUnique changes the "domain" of a unique to a different char newTagUnique u c = mkUnique c i where (_,i) = unpkUnique u -- pop the Char in the top 8 bits of the Unique(Supply) -- No 64-bit bugs here, as long as we have at least 32 bits. --JSM -- and as long as the Char fits in 8 bits, which we assume anyway! mkUnique :: Char -> Int -> Unique -- Builds a unique from pieces -- NOT EXPORTED, so that we can see all the Chars that -- are used in this one module mkUnique c i = MkUnique (tag .|. bits) where tag = ord c `shiftL` 24 bits = i .&. 16777215 {-``0x00ffffff''-} unpkUnique (MkUnique u) = let -- as long as the Char may have its eighth bit set, we -- really do need the logical right-shift here! tag = chr (u `shiftR` 24) i = u .&. 16777215 {-``0x00ffffff''-} in (tag, i) {- ************************************************************************ * * \subsection[Uniquable-class]{The @Uniquable@ class} * * ************************************************************************ -} -- | Class of things that we can obtain a 'Unique' from class Uniquable a where getUnique :: a -> Unique hasKey :: Uniquable a => a -> Unique -> Bool x `hasKey` k = getUnique x == k instance Uniquable FastString where getUnique fs = mkUniqueGrimily (uniqueOfFS fs) instance Uniquable Int where getUnique i = mkUniqueGrimily i cmpByUnique :: Uniquable a => a -> a -> Ordering cmpByUnique x y = (getUnique x) `cmpUnique` (getUnique y) {- ************************************************************************ * * \subsection[Unique-instances]{Instance declarations for @Unique@} * * ************************************************************************ And the whole point (besides uniqueness) is fast equality. We don't use `deriving' because we want {\em precise} control of ordering (equality on @Uniques@ is v common). -} -- Note [Unique Determinism] -- ~~~~~~~~~~~~~~~~~~~~~~~~~ -- The order of allocated @Uniques@ is not stable across rebuilds. -- The main reason for that is that typechecking interface files pulls -- @Uniques@ from @UniqSupply@ and the interface file for the module being -- currently compiled can, but doesn't have to exist. -- -- It gets more complicated if you take into account that the interface -- files are loaded lazily and that building multiple files at once has to -- work for any subset of interface files present. When you add parallelism -- this makes @Uniques@ hopelessly random. -- -- As such, to get deterministic builds, the order of the allocated -- @Uniques@ should not affect the final result. -- see also wiki/DeterministicBuilds eqUnique, ltUnique, leUnique :: Unique -> Unique -> Bool eqUnique (MkUnique u1) (MkUnique u2) = u1 == u2 ltUnique (MkUnique u1) (MkUnique u2) = u1 < u2 leUnique (MkUnique u1) (MkUnique u2) = u1 <= u2 cmpUnique :: Unique -> Unique -> Ordering cmpUnique (MkUnique u1) (MkUnique u2) = if u1 == u2 then EQ else if u1 < u2 then LT else GT instance Eq Unique where a == b = eqUnique a b a /= b = not (eqUnique a b) instance Ord Unique where a < b = ltUnique a b a <= b = leUnique a b a > b = not (leUnique a b) a >= b = not (ltUnique a b) compare a b = cmpUnique a b ----------------- instance Uniquable Unique where getUnique u = u -- We do sometimes make strings with @Uniques@ in them: showUnique :: Unique -> String showUnique uniq = case unpkUnique uniq of (tag, u) -> finish_show tag u (iToBase62 u) finish_show :: Char -> Int -> String -> String finish_show 't' u _pp_u | u < 26 = -- Special case to make v common tyvars, t1, t2, ... -- come out as a, b, ... (shorter, easier to read) [chr (ord 'a' + u)] finish_show tag _ pp_u = tag : pp_u pprUnique :: Unique -> SDoc pprUnique u = text (showUnique u) instance Outputable Unique where ppr = pprUnique instance Show Unique where show uniq = showUnique uniq {- ************************************************************************ * * \subsection[Utils-base62]{Base-62 numbers} * * ************************************************************************ A character-stingy way to read/write numbers (notably Uniques). The ``62-its'' are \tr{[0-9a-zA-Z]}. We don't handle negative Ints. Code stolen from Lennart. -} iToBase62 :: Int -> String iToBase62 n_ = ASSERT(n_ >= 0) go n_ "" where go n cs | n < 62 = let !c = chooseChar62 n in c : cs | otherwise = go q (c : cs) where (q, r) = quotRem n 62 !c = chooseChar62 r chooseChar62 :: Int -> Char {-# INLINE chooseChar62 #-} chooseChar62 (I# n) = C# (indexCharOffAddr# chars62 n) chars62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"# {- ************************************************************************ * * \subsection[Uniques-prelude]{@Uniques@ for wired-in Prelude things} * * ************************************************************************ Allocation of unique supply characters: v,t,u : for renumbering value-, type- and usage- vars. B: builtin C-E: pseudo uniques (used in native-code generator) X: uniques derived by deriveUnique _: unifiable tyvars (above) 0-9: prelude things below (no numbers left any more..) :: (prelude) parallel array data constructors other a-z: lower case chars for unique supplies. Used so far: d desugarer f AbsC flattener g SimplStg n Native codegen r Hsc name cache s simplifier -} mkAlphaTyVarUnique :: Int -> Unique mkPreludeClassUnique :: Int -> Unique mkPreludeTyConUnique :: Int -> Unique mkTupleTyConUnique :: Boxity -> Arity -> Unique mkCTupleTyConUnique :: Arity -> Unique mkPreludeDataConUnique :: Arity -> Unique mkTupleDataConUnique :: Boxity -> Arity -> Unique mkPrimOpIdUnique :: Int -> Unique mkPreludeMiscIdUnique :: Int -> Unique mkPArrDataConUnique :: Int -> Unique mkCoVarUnique :: Int -> Unique mkAlphaTyVarUnique i = mkUnique '1' i mkCoVarUnique i = mkUnique 'g' i mkPreludeClassUnique i = mkUnique '2' i -------------------------------------------------- -- Wired-in type constructor keys occupy *two* slots: -- * u: the TyCon itself -- * u+1: the TyConRepName of the TyCon mkPreludeTyConUnique i = mkUnique '3' (2*i) mkTupleTyConUnique Boxed a = mkUnique '4' (2*a) mkTupleTyConUnique Unboxed a = mkUnique '5' (2*a) mkCTupleTyConUnique a = mkUnique 'k' (2*a) tyConRepNameUnique :: Unique -> Unique tyConRepNameUnique u = incrUnique u -- Data constructor keys occupy *two* slots. The first is used for the -- data constructor itself and its wrapper function (the function that -- evaluates arguments as necessary and calls the worker). The second is -- used for the worker function (the function that builds the constructor -- representation). -------------------------------------------------- -- Wired-in data constructor keys occupy *three* slots: -- * u: the DataCon itself -- * u+1: its worker Id -- * u+2: the TyConRepName of the promoted TyCon -- Prelude data constructors are too simple to need wrappers. mkPreludeDataConUnique i = mkUnique '6' (3*i) -- Must be alphabetic mkTupleDataConUnique Boxed a = mkUnique '7' (3*a) -- ditto (*may* be used in C labels) mkTupleDataConUnique Unboxed a = mkUnique '8' (3*a) dataConRepNameUnique, dataConWorkerUnique :: Unique -> Unique dataConWorkerUnique u = incrUnique u dataConRepNameUnique u = stepUnique u 2 -------------------------------------------------- mkPrimOpIdUnique op = mkUnique '9' op mkPreludeMiscIdUnique i = mkUnique '0' i -- No numbers left anymore, so I pick something different for the character tag mkPArrDataConUnique a = mkUnique ':' (2*a) -- The "tyvar uniques" print specially nicely: a, b, c, etc. -- See pprUnique for details initTyVarUnique :: Unique initTyVarUnique = mkUnique 't' 0 mkPseudoUniqueD, mkPseudoUniqueE, mkPseudoUniqueH, mkBuiltinUnique :: Int -> Unique mkBuiltinUnique i = mkUnique 'B' i mkPseudoUniqueD i = mkUnique 'D' i -- used in NCG for getUnique on RealRegs mkPseudoUniqueE i = mkUnique 'E' i -- used in NCG spiller to create spill VirtualRegs mkPseudoUniqueH i = mkUnique 'H' i -- used in NCG spiller to create spill VirtualRegs mkRegSingleUnique, mkRegPairUnique, mkRegSubUnique, mkRegClassUnique :: Int -> Unique mkRegSingleUnique = mkUnique 'R' mkRegSubUnique = mkUnique 'S' mkRegPairUnique = mkUnique 'P' mkRegClassUnique = mkUnique 'L' mkCostCentreUnique :: Int -> Unique mkCostCentreUnique = mkUnique 'C' mkVarOccUnique, mkDataOccUnique, mkTvOccUnique, mkTcOccUnique :: FastString -> Unique -- See Note [The Unique of an OccName] in OccName mkVarOccUnique fs = mkUnique 'i' (uniqueOfFS fs) mkDataOccUnique fs = mkUnique 'd' (uniqueOfFS fs) mkTvOccUnique fs = mkUnique 'v' (uniqueOfFS fs) mkTcOccUnique fs = mkUnique 'c' (uniqueOfFS fs)
tjakway/ghcjvm
compiler/basicTypes/Unique.hs
bsd-3-clause
13,651
0
12
3,576
2,043
1,112
931
163
3
<?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="si-LK"> <title>Report Generation</title> <maps> <homeID>reports</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>
kingthorin/zap-extensions
addOns/reports/src/main/javahelp/org/zaproxy/addon/reports/resources/help_si_LK/helpset_si_LK.hs
apache-2.0
966
77
66
156
407
206
201
-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="bs-BA"> <title>TreeTools</title> <maps> <homeID>treetools</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>
thc202/zap-extensions
addOns/treetools/src/main/javahelp/help_bs_BA/helpset_bs_BA.hs
apache-2.0
960
77
66
155
404
205
199
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Plugins.Monitors.Cpu -- Copyright : (c) 2011 Jose Antonio Ortega Ruiz -- (c) 2007-2010 Andrea Rossato -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A. Ortega Ruiz <jao@gnu.org> -- Stability : unstable -- Portability : unportable -- -- A cpu monitor for Xmobar -- ----------------------------------------------------------------------------- module Plugins.Monitors.Cpu (startCpu) where import Plugins.Monitors.Common import qualified Data.ByteString.Lazy.Char8 as B import Data.IORef (IORef, newIORef, readIORef, writeIORef) import System.Console.GetOpt data CpuOpts = CpuOpts { loadIconPattern :: Maybe IconPattern } defaultOpts :: CpuOpts defaultOpts = CpuOpts { loadIconPattern = Nothing } options :: [OptDescr (CpuOpts -> CpuOpts)] options = [ Option "" ["load-icon-pattern"] (ReqArg (\x o -> o { loadIconPattern = Just $ parseIconPattern x }) "") "" ] parseOpts :: [String] -> IO CpuOpts parseOpts argv = case getOpt Permute options argv of (o, _, []) -> return $ foldr id defaultOpts o (_, _, errs) -> ioError . userError $ concat errs cpuConfig :: IO MConfig cpuConfig = mkMConfig "Cpu: <total>%" ["bar","vbar","ipat","total","user","nice","system","idle","iowait"] type CpuDataRef = IORef [Int] cpuData :: IO [Int] cpuData = cpuParser `fmap` B.readFile "/proc/stat" cpuParser :: B.ByteString -> [Int] cpuParser = map (read . B.unpack) . tail . B.words . head . B.lines parseCpu :: CpuDataRef -> IO [Float] parseCpu cref = do a <- readIORef cref b <- cpuData writeIORef cref b let dif = zipWith (-) b a tot = fromIntegral $ sum dif percent = map ((/ tot) . fromIntegral) dif return percent formatCpu :: CpuOpts -> [Float] -> Monitor [String] formatCpu _ [] = return $ replicate 8 "" formatCpu opts xs = do let t = sum $ take 3 xs b <- showPercentBar (100 * t) t v <- showVerticalBar (100 * t) t d <- showIconPattern (loadIconPattern opts) t ps <- showPercentsWithColors (t:xs) return (b:v:d:ps) runCpu :: CpuDataRef -> [String] -> Monitor String runCpu cref argv = do c <- io (parseCpu cref) opts <- io $ parseOpts argv l <- formatCpu opts c parseTemplate l startCpu :: [String] -> Int -> (String -> IO ()) -> IO () startCpu a r cb = do cref <- newIORef [] _ <- parseCpu cref runM a cpuConfig (runCpu cref) r cb
dragosboca/xmobar
src/Plugins/Monitors/Cpu.hs
bsd-3-clause
2,516
0
14
551
835
440
395
57
2
module Renaming.QualServer ( foo ) where {- foo is imported qualified as in QualClient. Renaming should preserve the qualification there -} foo :: Char foo = 'a'
RefactoringTools/HaRe
test/testdata/Renaming/QualServer.hs
bsd-3-clause
174
0
4
39
22
14
8
5
1
{-# LANGUAGE MagicHash #-} -- | Asserts that absent bindings of UnliftedRep are properly WWed module Unlifted where import GHC.Exts fac :: Int -> Int fac n = product [1..n] data MMutVar s a = MMutVar (MutVar# s a) Int mutVar :: MMutVar s a -> Int mutVar (MMutVar _ n) = fac n {-# NOINLINE mutVar #-} data AArray a = AArray (Array# a) Int array :: AArray a -> Int array (AArray _ n) = fac n {-# NOINLINE array #-}
sdiehl/ghc
testsuite/tests/stranal/should_compile/T15627.hs
bsd-3-clause
418
0
8
88
141
76
65
13
1
-- !!! Re-exporting qualified module. module M where import Prelude () -- Forces the import to come from Mod136_A import Mod136_A x = zipWith5
ezyang/ghc
testsuite/tests/module/mod136.hs
bsd-3-clause
149
0
4
30
20
14
6
4
1
{-# LANGUAGE MagicHash #-} module Main (main) where import GHC.Prim import GHC.Types main :: IO () main = print (I# (1# +# 2# *# 3# +# 4#))
beni55/ghcjs
test/pkg/ghc-prim/t6026.hs
mit
144
0
11
31
59
33
26
6
1
{-# LANGUAGE OverloadedStrings #-} module Api.Types.Feature ( APIFeature (..) ) where import Control.Monad (mzero) import Data.Aeson import qualified Features.Feature as F data APIFeature = APIFeature { featureID :: F.FeatureFile , description :: F.Feature } deriving (Show) instance ToJSON APIFeature where toJSON (APIFeature (F.FeatureFile featID) (F.Feature desc)) = object [ "featureID" .= featID , "description" .= desc ] instance FromJSON APIFeature where parseJSON (Object v) = APIFeature <$> v .: "featureID" <*> v .: "description" parseJSON _ = mzero
gust/feature-creature
legacy/lib/Api/Types/Feature.hs
mit
716
0
11
234
175
98
77
18
0
--type declaration on functions removeNonUppercase :: [Char] -> [Char] removeNonUppercase st = [ c | c <- st, elem c ['A'..'Z']] -- the last parametr is the reutnr type addThree :: Int -> Int -> Int -> Int addThree x y z = x + y + z --data types: -- Int -- Integer (not bounded) -- Float -- Double -- Bool -- Char
luisgepeto/HaskellLearning
03 Types and Typeclasses/01_believe_the_type.hs
mit
325
0
8
75
95
54
41
4
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Application ( makeApplication , getApplicationDev , makeFoundation ) where import Import import Settings import Yesod.Auth import Yesod.Default.Config import Yesod.Default.Main import Yesod.Default.Handlers import Network.Wai.Middleware.RequestLogger ( mkRequestLogger, outputFormat, OutputFormat (..), IPAddrSource (..), destination ) import qualified Network.Wai.Middleware.RequestLogger as RequestLogger import qualified Database.Persist import Network.HTTP.Client.Conduit (newManager) import System.Log.FastLogger (newStdoutLoggerSet, defaultBufSize) import Network.Wai.Logger (clockDateCacher) import Data.Default (def) import Yesod.Core.Types (loggerSet, Logger (Logger)) -- Import all relevant handler modules here. -- Don't forget to add new modules to your cabal file! import Handler.Home import Handler.Random import Handler.Input -- This line actually creates our YesodDispatch instance. It is the second half -- of the call to mkYesodData which occurs in Foundation.hs. Please see the -- comments there for more details. mkYesodDispatch "App" resourcesApp -- This function allocates resources (such as a database connection pool), -- performs initialization and creates a WAI application. This is also the -- place to put your migrate statements to have automatic database -- migrations handled by Yesod. makeApplication :: AppConfig DefaultEnv Extra -> IO (Application, LogFunc) makeApplication conf = do foundation <- makeFoundation conf -- Initialize the logging middleware logWare <- mkRequestLogger def { outputFormat = if development then Detailed True else Apache FromSocket , destination = RequestLogger.Logger $ loggerSet $ appLogger foundation } -- Create the WAI application and apply middlewares app <- toWaiAppPlain foundation let logFunc = messageLoggerSource foundation (appLogger foundation) return (logWare $ defaultMiddlewaresNoLogging app, logFunc) -- | Loads up any necessary settings, creates your foundation datatype, and -- performs some initialization. makeFoundation :: AppConfig DefaultEnv Extra -> IO App makeFoundation conf = do manager <- newManager s <- staticSite dbconf <- withYamlEnvironment "config/mongoDB.yml" (appEnv conf) Database.Persist.loadConfig >>= Database.Persist.applyEnv p <- Database.Persist.createPoolConfig (dbconf :: Settings.PersistConf) loggerSet' <- newStdoutLoggerSet defaultBufSize (getter, _) <- clockDateCacher let logger = Yesod.Core.Types.Logger loggerSet' getter foundation = App { settings = conf , getStatic = s , connPool = p , httpManager = manager , persistConfig = dbconf , appLogger = logger } return foundation -- for yesod devel getApplicationDev :: IO (Int, Application) getApplicationDev = defaultDevelApp loader (fmap fst . makeApplication) where loader = Yesod.Default.Config.loadConfig (configSettings Development) { csParseExtra = parseExtra }
dschalk/score
Haskell/score/Application.hs
mit
3,186
0
13
663
578
328
250
-1
-1
{-# LANGUAGE NoMonomorphismRestriction #-} module Plugins.Gallery.Gallery.Manual39 where import Diagrams.Prelude import Graphics.Rendering.Diagrams.Points s = square 2 -- a squarish thing. blueSquares = decoratePath s {- 1 -} (replicate 4 (s {- 2 -} # scale 0.5) # fc blue) paths = lc purple . stroke $ star (StarSkip 2) s {- 3 -} aster = centerXY . lc green . strokeT . mconcat . take 5 . iterate (rotateBy (1/5)) $ s {- 4 -} example = (blueSquares <> aster <> paths) # lw 0.05
andrey013/pluginstest
Plugins/Gallery/Gallery/Manual39.hs
mit
545
0
11
150
170
91
79
12
1
import Data.Bits import Data.Map.Lazy (Map, (!)) import qualified Data.Map.Lazy as Map import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as IO import Text.Parsec import Text.Parsec.Text type Connection = (Wire, Operation) type Connections = Map Wire Operation newtype Wire = Wire String deriving (Eq, Ord, Show) data Input = Signal Value | InputWire Wire deriving (Eq, Show) data Operation = Input Input | And Input Input | Or Input Input | LeftShift Input Int | RightShift Input Int | Not Input deriving (Eq, Show) type Value = Integer type Values = Map Wire Value wire = Wire "a" overrideWire = Wire "b" main = do connections <- Map.fromList <$> map parseInput <$> Text.lines <$> IO.getContents let values = compute connections let overriddenConnections = Map.insert overrideWire (Input $ Signal $ values ! wire) connections let overriddenValues = compute overriddenConnections print (overriddenValues ! wire) parseInput :: Text -> Connection parseInput text = either (error . show) id $ parse parser "" text where parser = do op <- operation string " -> " w <- wire return $ (w, op) operation = choice $ map try [opAnd, opOr, opLeftShift, opRightShift, opNot, Input <$> input] input = try signal <|> try inputWire signal = Signal <$> value inputWire = InputWire <$> wire opAnd = do a <- input space string "AND" space b <- input return $ And a b opOr = do a <- input space string "OR" space b <- input return $ Or a b opLeftShift = do i <- input space string "LSHIFT" space amount <- int return $ LeftShift i amount opRightShift = do i <- input space string "RSHIFT" space amount <- int return $ RightShift i amount opNot = do string "NOT" space i <- input return $ Not i wire = Wire <$> many1 letter value = read <$> many1 digit int = read <$> many1 digit compute :: Connections -> Values compute connections = values where values :: Values values = Map.map value connections value :: Operation -> Value value (Input input) = inputValue input value (And a b) = inputValue a .&. inputValue b value (Or a b) = inputValue a .|. inputValue b value (LeftShift input amount) = inputValue input `shiftL` amount value (RightShift input amount) = inputValue input `shiftR` amount value (Not input) = complement (inputValue input) inputValue :: Input -> Value inputValue (Signal signalValue) = signalValue inputValue (InputWire wire) = values ! wire
SamirTalwar/advent-of-code
2015/AOC_07_2.hs
mit
2,719
0
14
741
945
478
467
93
7
module Light.Shape.Paraboloid -- ADT ( Paraboloid, paraboloid, paraboloidRadius, paraboloidHeight -- Default Instances , unitParaboloid ) where import Light.Math import Light.Geometry import Light.Shape data Paraboloid = Paraboloid { paraboloidTransform :: Transform , paraboloidRadius :: Double , paraboloidHeight :: Double } deriving (Show, Read) paraboloid :: Double -> Double -> Paraboloid paraboloid = Paraboloid identityTransform unitParaboloid :: Paraboloid unitParaboloid = paraboloid 1 1 instance Transformable Paraboloid where transform t' (Paraboloid t r h) = Paraboloid (compose t' t) r h instance Shape Paraboloid where shapeTransform = paraboloidTransform bound (Paraboloid _ r h) = fromPoints [ Point (-r) (-r) 0, Point r r h ] surfaceArea (Paraboloid _ r h) = (pi/6) * (r/(h*h)) * ((r*r + 4*h*h) * 3/2 - r*r*r) intersections theRay (Paraboloid t r h) = filter f $ quadratic a b c where r' = transform (inverse t) theRay rdx = dx $ rayDirection r' rdy = dy $ rayDirection r' rdz = dz $ rayDirection r' rox = px $ rayOrigin r' roy = py $ rayOrigin r' roz = pz $ rayOrigin r' a = ( h*rdx*rdx + h*rdy*rdy)/(r*r) b = (2*h*rox*rdx + 2*h*roy*rdy)/(r*r) - rdz c = ( h*rox*rox + h*roy*roy)/(r*r) - roz f time = let rz = pz (r' `atTime` time) in time > 0 && rz >= 0 && rz <= h
jtdubs/Light
src/Light/Shape/Paraboloid.hs
mit
1,588
0
17
524
619
328
291
33
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE DeriveGeneric #-} module FP15.Evaluator.Types ( module FP15.Evaluator.Types , module FP15.Evaluator.RuntimeError , module FP15.Evaluator.FPRef , module FP15.Evaluator.ContractType , module FP15.Evaluator.FPValue , module FP15.Evaluator.FP ) where import GHC.Generics import Control.DeepSeq import FP15.Name import FP15.Value import FP15.Evaluator.RuntimeError import FP15.Evaluator.FPRef import FP15.Evaluator.FPValue import FP15.Evaluator.ContractType import FP15.Evaluator.FP(FP(..)) -- * Expression type Ident = String data BaseExpr = Const Value | Func (Located Ident) | Compose [BaseExpr] | If BaseExpr BaseExpr BaseExpr | Fork [BaseExpr] | Hook [BaseExpr] | Map BaseExpr | Filter BaseExpr | While BaseExpr BaseExpr | Mark Ident BaseExpr | Get Int | With BaseExpr BaseExpr | Pop BaseExpr deriving (Eq, Show, Read, Generic) instance NFData BaseExpr where rnf x = seq x () type FPResult = FP FPValue -- | An FP15 function, which takes a 'Value' and returns a 'Value' or a -- 'RuntimeError'. type FPFunc = FPValue -> FPResult {-# ANN module "HLint: ignore Use import/export shortcut" #-}
Ming-Tang/FP15
src/FP15/Evaluator/Types.hs
mit
1,321
0
8
343
277
171
106
37
0
module Test where foo :: (Eq a) => a -> a foo x = x
Pnom/haskell-ast-pretty
Test/examples/SingleClassAsst.hs
mit
52
0
6
15
30
17
13
3
1
{-# OPTIONS_GHC -F -pgmF htfpp #-} import Test.Framework import {-@ HTF_TESTS @-} Test.Data.SetMultiMap main = htfMain $ htf_thisModulesTests : htf_importedTests
scravy/multimap
src/Test.hs
mit
167
0
6
25
27
16
11
4
1
module Types where import Gol3d.Life hiding ( Position ) import Gol3d.Pattern import Gol3d.Render import Data.IORef import Graphics.UI.GLUT import qualified Data.Map as M data CamState = CamState { camPos :: Vector3 GLfloat , camAngle :: Vector2 GLfloat , cursorRadius :: GLfloat } -- | An internally managed cache of key states. -- We need this since GLUT doesn't give us a way to poll key states. type KeyboardState = M.Map Key KeyState data State = State { cellDrawConfig :: CellDrawConfig -- ^ The configuration used to draw the "Cell"s in the -- stored "CellMap". , cursorDrawConfig :: CellDrawConfig -- ^ The configuration used to draw the cursor. , camState :: CamState -- ^ The current state of the camera. , kbdState :: KeyboardState -- ^ An internally managed cache of key states. , cellMap :: CellMap -- ^ The current map of cells. , evolveDelta :: Int -- ^ The time between "CellMap" evolutions. , lastEvolve :: Int -- ^ The time of the last evolution. , moveSpeed :: GLfloat -- ^ The radius of the vision sphere , angleSpeed :: GLfloat -- ^ radians per pixel , gameMode :: GameMode -- ^ Current mode of the game; affects input handling , isPlaying :: Bool -- ^ Whether patterns autoupdate after "evolveDelta" ms. , lastKeyPoll :: Int -- ^ The last time keys were polled. , keyPollDelta :: Int -- ^ How often keys are polled. } defaultState = State { cellDrawConfig = defaultCellDrawConfig , cursorDrawConfig = defaultCursorDrawConfig , camState = CamState { camPos = Vector3 0 0 0 , camAngle = Vector2 0 0 , cursorRadius = 5.0 } , kbdState = M.empty , cellMap = toCellMap glider3 , evolveDelta = 50 , lastEvolve = 0 , lastKeyPoll = 0 , keyPollDelta = 17 , moveSpeed = 0.25 , angleSpeed = 0.005 , gameMode = BuildMode , isPlaying = False } data GameMode = BuildMode | ViewMode deriving (Eq, Ord, Show, Read) type StateR = IORef State
labcoders/gol3d-hs
src/Types.hs
mit
2,859
0
9
1,340
353
225
128
42
1
{- | Module : $Header$ Description : xml input for Hets development graphs Copyright : (c) Simon Ulbricht, DFKI GmbH 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : tekknix@informatik.uni-bremen.de Stability : provisional Portability : non-portable (DevGraph) convert an Xml-Graph into an XGraph-Structure. -} module Static.XGraph where import Static.DgUtils import Common.AnalyseAnnos (getGlobalAnnos) import Common.Consistency (Conservativity (..)) import Common.GlobalAnnotations (GlobalAnnos, emptyGlobalAnnos) import Common.LibName import Common.Result (Result (..)) import Common.Utils (readMaybe) import Common.XUpdate (getAttrVal, readAttrVal) import Control.Monad import Data.List import Data.Maybe (fromMaybe) import qualified Data.Set as Set import qualified Data.Map as Map import Text.XML.Light {- ------------- Data Types -} -- represent element information in the order they can be processed later data XGraph = XGraph { libName :: LibName , globAnnos :: GlobalAnnos , nextLinkId :: EdgeId , thmLinks :: [XLink] , startNodes :: [XNode] , xg_body :: XTree } {- outer list must be executed in order; inner lists represent all def-links -node bundles that can be processed in one step -} type XTree = [[([XLink], XNode)]] type EdgeMap = Map.Map String (Map.Map String [XLink]) data XNode = XNode { nodeName :: NodeName , logicName :: String , symbs :: (Bool, String) -- ^ hidden? , specs :: String -- ^ Sentences , nd_cons :: Conservativity } | XRef { nodeName :: NodeName , refNode :: String , refLib :: String , specs :: String } data XLink = XLink { source :: String , target :: String , edgeId :: EdgeId , lType :: DGEdgeType , rule :: DGRule , cons :: Conservativity , prBasis :: ProofBasis , mr_name :: String , mr_source :: Maybe String , mapping :: String } instance Show XNode where show xn = showName (nodeName xn) instance Show XLink where show xl = showEdgeId (edgeId xl) ++ ": " ++ source xl ++ " -> " ++ target xl instance Ord XLink where compare xl1 xl2 = compare (edgeId xl1, source xl1, target xl1) (edgeId xl2, source xl2, target xl2) instance Eq XLink where a == b = compare a b == EQ {- ------------ Functions -} insertXLink :: XLink -> EdgeMap -> EdgeMap insertXLink l = Map.insertWith (Map.unionWith (++)) (target l) $ Map.singleton (source l) [l] mkEdgeMap :: [XLink] -> EdgeMap mkEdgeMap = foldl (flip insertXLink) Map.empty xGraph :: Element -> Result XGraph xGraph xml = do allNodes <- extractXNodes xml allLinks <- extractXLinks xml _ <- foldM (\ s l -> let e = edgeId l in if Set.member e s then fail $ "duplicate edge id: " ++ show e else return $ Set.insert e s) Set.empty allLinks nodeMap <- foldM (\ m n -> let s = showName $ nodeName n in if Map.member s m then fail $ "duplicate node name: " ++ s else return $ Map.insert s n m) Map.empty allNodes let (thmLk, defLk) = partition (\ l -> case edgeTypeModInc $ lType l of ThmType _ _ _ _ -> True _ -> False) allLinks edgeMap = mkEdgeMap defLk (initN, restN) = Map.partitionWithKey (\ n _ -> Set.notMember n $ Map.keysSet edgeMap) nodeMap tgts = Map.keysSet nodeMap missingTgts = Set.difference (Map.keysSet edgeMap) tgts srcs = Set.unions $ map Map.keysSet $ Map.elems edgeMap missingSrcs = Set.difference srcs tgts unless (Set.null missingTgts) $ fail $ "missing nodes for edge targets " ++ show missingTgts unless (Set.null missingSrcs) $ fail $ "missing nodes for edge sources " ++ show missingSrcs nm <- getAttrVal "libname" xml fl <- getAttrVal "filename" xml let ln = setFilePath fl noTime $ emptyLibName nm ga <- extractGlobalAnnos xml i' <- fmap readEdgeId $ getAttrVal "nextlinkid" xml xg <- builtXGraph (Map.keysSet initN) edgeMap restN [] return $ XGraph ln ga i' thmLk (Map.elems initN) xg builtXGraph :: Monad m => Set.Set String -> EdgeMap -> Map.Map String XNode -> XTree -> m XTree builtXGraph ns xls xns xg = if Map.null xls && Map.null xns then return xg else do when (Map.null xls) $ fail $ "unprocessed nodes: " ++ show (Map.keysSet xns) when (Map.null xns) $ fail $ "unprocessed links: " ++ show (map edgeId $ concat $ concatMap Map.elems $ Map.elems xls) let (sls, rls) = Map.partition ((`Set.isSubsetOf` ns) . Map.keysSet) xls bs = Map.intersectionWith (,) sls xns when (Map.null bs) $ fail $ "cannot continue with source nodes:\n " ++ show (Set.difference (Set.unions $ map Map.keysSet $ Map.elems rls) ns) ++ "\nfor given nodes: " ++ show ns builtXGraph (Set.union ns $ Map.keysSet bs) rls (Map.difference xns bs) $ map (\ (m, x) -> (concat $ Map.elems m, x)) (Map.elems bs) : xg extractXNodes :: Monad m => Element -> m [XNode] extractXNodes = mapM mkXNode . findChildren (unqual "DGNode") extractXLinks :: Monad m => Element -> m [XLink] extractXLinks = mapM mkXLink . findChildren (unqual "DGLink") mkXNode :: Monad m => Element -> m XNode mkXNode el = let get f s = f . map strContent . deepSearch [s] get' = get unlines in do nm <- extractNodeName el case findChild (unqual "Reference") el of Just rf -> do rfNm <- getAttrVal "node" rf rfLib <- getAttrVal "library" rf return $ XRef nm rfNm rfLib $ get' "Axiom" el ++ get' "Theorem" el Nothing -> let hdSyms = case findChild (unqual "Hidden") el of Nothing -> case findChild (unqual "Declarations") el of -- Case #1: No declared or hidden symbols Nothing -> (False, "") -- Case #2: Node has declared symbols (DGBasicSpec) Just ch -> (False, get' "Symbol" ch) -- Case #3: Node has hidden symbols (DGRestricted) Just ch -> (True, get (intercalate ", ") "Symbol" ch) spcs = get' "Axiom" el ++ get' "Theorem" el in do lgN <- getAttrVal "logic" el xp0 <- getAttrVal "relxpath" el nm0 <- getAttrVal "refname" el xp1 <- readXPath (nm0 ++ xp0) return $ XNode nm { xpath = reverse xp1 } lgN hdSyms spcs $ readCons el extractNodeName :: Monad m => Element -> m NodeName extractNodeName e = liftM parseNodeName $ getAttrVal "name" e mkXLink :: Monad m => Element -> m XLink mkXLink el = do sr <- getAttrVal "source" el tr <- getAttrVal "target" el ei <- extractEdgeId el tp <- case findChild (unqual "Type") el of Just tp' -> return $ revertDGEdgeTypeName $ strContent tp' Nothing -> fail "links type description is missing" rl <- case findChild (unqual "Rule") el of Nothing -> return $ DGRule "no rule" Just r' -> case findChildren (unqual "MovedTheorems") el of [] -> return $ DGRule $ strContent r' mThs -> liftM DGRuleLocalInference $ mapM (\ e -> do nmOld <- getAttrVal "name" e nmNew <- getAttrVal "renamedTo" e return (nmOld, nmNew)) mThs prB <- mapM (getAttrVal "linkref") $ findChildren (unqual "ProofBasis") el (mrNm, mrSrc) <- case findChild (unqual "GMorphism") el of Nothing -> fail "Links morphism description is missing!" Just mor -> do nm <- getAttrVal "name" mor return (nm, findAttr (unqual "morphismsource") mor) let parseSymbMap = intercalate ", " . map ( intercalate " |-> " . map strContent . elChildren ) . deepSearch ["map"] prBs = ProofBasis $ foldr (Set.insert . readEdgeId) Set.empty prB cc = readCons el return $ XLink sr tr ei tp rl cc prBs mrNm mrSrc $ parseSymbMap el readCons :: Element -> Conservativity readCons el = case findChild (unqual "ConsStatus") el of Nothing -> None Just c' -> fromMaybe None $ readMaybe $ strContent c' extractEdgeId :: Monad m => Element -> m EdgeId extractEdgeId = liftM EdgeId . readAttrVal "XGraph.extractEdgeId" "linkid" readEdgeId :: String -> EdgeId readEdgeId = EdgeId . fromMaybe (-1) . readMaybe -- | custom xml-search for not only immediate children deepSearch :: [String] -> Element -> [Element] deepSearch tags' ele = rekSearch ele where tags = map unqual tags' rekSearch e = filtr e ++ concatMap filtr (elChildren e) filtr = filterChildrenName (`elem` tags) -- | extracts the global annotations from the xml-graph extractGlobalAnnos :: Element -> Result GlobalAnnos extractGlobalAnnos dgEle = case findChild (unqual "Global") dgEle of Nothing -> return emptyGlobalAnnos Just gl -> parseAnnotations gl parseAnnotations :: Element -> Result GlobalAnnos parseAnnotations = getGlobalAnnos . unlines . map strContent . findChildren (unqual "Annotation")
nevrenato/Hets_Fork
Static/XGraph.hs
gpl-2.0
9,093
0
23
2,427
2,887
1,441
1,446
178
5
{-# LANGUAGE FlexibleContexts #-} ---------------------------------------------------------------------- -- HexDumping utility. ---------------------------------------------------------------------- module Text.HexDump (hexDump, padHex) where import qualified Data.ByteString.Lazy as L import Data.Convertible.Text (ConvertSuccess, cs) import Data.List (intercalate) import Data.Char (isPrint, isAscii, chr) import Numeric (showHex) -- Convert a chunk of bytestring data into a "nice" hex representation. hexDump :: ConvertSuccess a L.ByteString => a -> String hexDump = hexDump' 0 . cs hexDump' :: Integer -> L.ByteString -> String hexDump' addr d | L.length d == 0 && addr > 0 = "" hexDump' addr d = padHex 8 addr ++ " " ++ rpad 23 ' ' (hexify left) ++ " " ++ rpad 23 ' ' (hexify right) ++ " |" ++ rpad 8 ' ' (asciify left) ++ " " ++ rpad 8 ' ' (asciify right) ++ "|\n" ++ hexDump' (addr + 16) rest where (heads, rest) = L.splitAt 16 d nums = L.unpack heads (left, right) = splitAt 8 nums hexify = intercalate " " . map (padHex 2) asciify = map (safeChar . chr . fromIntegral) padHex :: (Integral a) => Int -> a -> String padHex len num = padding ++ hex where hex = showHex num "" padding = replicate (len - length hex) '0' safeChar :: Char -> Char safeChar c | isPrint c && isAscii c = c safeChar _ = '.' rpad :: Int -> Char -> String -> String rpad len ch text = text ++ replicate (len - length text) ch
d3zd3z/harchive
src/Text/HexDump.hs
gpl-2.0
1,500
0
16
335
520
270
250
32
1
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-} -- | -- Module: DebVersionCmp -- Copyright: (c) 2011 Joachim Breitner -- License: GPL-2 -- module DebVersionCmp where import System.IO.Unsafe import Foreign.Ptr import Foreign.Marshal import Foreign.C.Types import Foreign.C.String import qualified Data.ByteString as BS data ParsedVersion data DpkgError foreign import ccall unsafe "dpkg/dpkg-db.h parseversion" c_ParseVersion :: Ptr ParsedVersion -> CString -> Ptr DpkgError -> IO CInt foreign import ccall unsafe "dpkg/version.h dpkg_version_compare" c_VersionCompare :: Ptr ParsedVersion -> Ptr ParsedVersion -> IO CInt foreign export ccall "thisname" blubb :: () blubb :: () blubb = () versionCompare :: BS.ByteString -> BS.ByteString -> Ordering versionCompare v1 v2 = unsafePerformIO $ -- 12 bytes is enough to carry a struct versionrevision allocaBytes 12 $ \ptr1 -> allocaBytes 12 $ \ptr2 -> allocaBytes 16 $ \eptr -> BS.useAsCString v1 $ \v1p -> BS.useAsCString v2 $ \v2p -> do r1 <- c_ParseVersion ptr1 v1p eptr if (r1 /= 0) then peekCString (castPtr (eptr `plusPtr` 8)) >>= \err -> error $ "Failed to parse " ++ show v1 ++ ": " ++ err else do r2 <- c_ParseVersion ptr2 v2p eptr if (r2 /= 0) then peekCString (castPtr (eptr `plusPtr` 8)) >>= \err -> error $ "Failed to parse " ++ show v2 ++ ": " ++ err else do r3 <- c_VersionCompare ptr1 ptr2 return $ if r3 < 0 then LT else if r3 == 0 then EQ else GT
nomeata/sat-britney
DebVersionCmp.hs
gpl-2.0
1,554
0
26
363
441
236
205
-1
-1
module Dist (distArg, distOverride, distRemote, distTag, distTarget, hackageRelease, ltsStream) where import Data.Maybe (fromMaybe) import Distribution.Fedora (Dist(..), distBranch, distOverride) import SimpleCmdArgs (Parser, argumentWith, auto) -- | Used for Koji sidetag when needed. sidetag :: Dist -> Maybe String --sidetag (Fedora n) | n >= 33 = Just "build-side-19539" sidetag _ = Nothing -- | Maps `Dist` to build tag distTag :: Dist -> String --distTag (Fedora n) | n >= 33 = "f33-build-side-19539" distTag d = show d ++ "-" ++ fromMaybe "build" (sidetag d) -- | Maps `Dist` to target tag distTarget :: Dist -> String --distTarget (Fedora n) | n >= 33 = "f33-build-side-19539" distTarget d = show d ++ maybe "" ("-" ++) (sidetag d) -- | optparse-application DIST arg distArg :: Parser Dist distArg = argumentWith auto "DIST" -- | Maps `Dist` to remote branch: eg "origin/master" distRemote :: Dist -> Dist -> String distRemote branch d = "origin/" ++ distBranch branch d -- | Fedora release being tracked in Hackage Distro data hackageRelease :: Dist hackageRelease = Fedora 35 -- | Stackage LTS stream major version ltsStream :: String ltsStream = "lts-16"
fedora-haskell/fedora-haskell-tools
src/Dist.hs
gpl-3.0
1,198
0
8
218
254
144
110
25
1
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} -------------------------------------------------------------------------------- -- | -- Module : Tct.Processor.Transformations -- Copyright : (c) Martin Avanzini <martin.avanzini@uibk.ac.at>, -- Georg Moser <georg.moser@uibk.ac.at>, -- Andreas Schnabl <andreas.schnabl@uibk.ac.at>, -- License : LGPL (see COPYING) -- -- Maintainer : Martin Avanzini <martin.avanzini@uibk.ac.at> -- Stability : unstable -- Portability : unportable -- -- This module gives the infrastructure for /transformation processors/. -- Transformation processors transform an input problem into zero or more -- subproblems, reflecting the complexity of the input problem. -- Transformations abort if the input problem cannot be simplified. -- Use 'try' to continue with the input problem. -------------------------------------------------------------------------------- module Tct.Processor.Transformations ( -- * Using Transformations TheTransformer (..) -- ** Lifting to Processors , (>>|) , (>>||) -- * Defining new Transformations -- | In order to define a new transformation, -- define an instance of 'Transformer' and 'TransformationProof'. -- Use 'withArgs' for providing an instance constructor, compare "Tct.instances". -- Use 'transformationProcessor' to lift the defined transformation to a processor. , Transformer (..) , TransformationProof (..) , Transformation (..) , withArgs , modifyArguments , transformationProcessor -- ** Transformation Result , Result (..) , proofFromResult , subProblemsFromResult , isProgressResult , mapResult , sanitiseResult -- ** Transformation Proof , Proof (..) , subProblems , findProof , transformationProof , answerFromSubProof -- * Existential Quantification , SomeTransformation (..) , SomeTransProof (..) , someTransformation , someProof -- * Subsumed Processor -- | The following utilities are used only internally. , liftMS , mkSubsumed -- * Misc , transformerToXml , thenApply ) where import Control.Monad (liftM) import Data.Maybe (catMaybes) import Data.Char (isAlphaNum) import Text.PrettyPrint.HughesPJ hiding (empty, (<>)) import qualified Text.PrettyPrint.HughesPJ as PP import qualified Data.Set as Set import Data.List (partition) import Termlib.Problem import qualified Termlib.Trs as Trs import qualified Termlib.Utils as Util import Tct.Utils.Enum import qualified Tct.Utils.Xml as Xml import qualified Tct.Utils.Xml.Encoding as XmlE import Tct.Utils.PPrint import qualified Tct.Processor as P import qualified Tct.Proof as Proof import qualified Tct.Processor.Standard as S import qualified Tct.Processor.Args as A import Tct.Processor.Args.Instances import Tct.Processor.Args hiding (name, description, synopsis) -------------------------------------------------------------------------------- --- Transformation Proofs transformerToXml :: Transformer t => TheTransformer t -> Xml.XmlContent transformerToXml tinst = Xml.elt "transformer" [] [ Xml.elt "name" [] [Xml.text $ filter isAlphaNum $ name t] , Xml.elt "arguments" [] $ A.toXml (arguments t) (transformationArgs tinst) , Xml.elt "description" [] [Xml.text $ unwords $ description t]] where t = transformation tinst -- | Every transformer needs to implement this class. -- Minimal definition: 'answer' and 'pprintTProof'. class TransformationProof t where -- | Construct an 'P.Answer' from the 'Proof'. answer :: P.Processor sub => Proof t sub -> P.Answer -- | Construct an Xml-node from a transformation proof. -- The default implementation wraps the pretty-printed output -- in a 'proofdata' node tproofToXml :: (Transformer t) => TheTransformer t -> Problem -> ProofOf t -> (String, [Xml.XmlContent]) tproofToXml t prob proof = ( name (transformation t) , [ Xml.elt "proofdata" [] [Xml.text $ show $ pprintTProof t prob proof P.ProofOutput] ]) proofToXml :: (Transformer t, P.Processor sub) => Proof t sub -> Xml.XmlContent proofToXml proof = Xml.elt "transformation" [] [ transformerToXml tinst , XmlE.complexityProblem input ans , Xml.elt "transformationDetail" [] [Xml.elt n [] cnt] , Xml.elt (if progressed then "progress" else "noprogress") [] [] , Xml.elt "subProofs" [] [Proof.toXml p | (_,p) <- subproofs ]] where (n, cnt) = tproofToXml tinst input tproof subproofs = subProofs proof tproof = transformationProof proof tinst = appliedTransformer proof input = inputProblem proof ans = answer proof progressed = isProgressResult $ transformationResult proof -- | Pretty print the transformation proof. pprintTProof :: TheTransformer t -> Problem -> ProofOf t -> P.PPMode -> Doc -- | Pretty printer of the 'Proof'. A default implementation is given. pprintProof :: (Transformer t, P.Processor sub) => Proof t sub -> P.PPMode -> Doc pprintProof proof mde = ppTransformationDetails $+$ case subprobs of [] -> text "No progress on transformation, no sub-problems were generated." [_] -> ppDetails Nothing _ -> ppOverviews $+$ text "" $+$ ppDetails (Just "Proofs for generated problems") where nproof = proof subproofs = subProofs nproof subprobs = subProblems nproof tproof = transformationProof nproof t = appliedTransformer nproof input = inputProblem nproof ppTransformationDetails | mde == P.OverviewOutput = PP.empty | otherwise = pprintTProof t input tproof mde $+$ text "" ppOverviews = text "Overall, the transformation results in the following sub-problem(s):" $+$ text "" $+$ block "Generated new problems" (ppOverview `map` subprobs) ppOverview (sn@(SN i), prob_i) = (sn, ppProb prob_i (findProof i proof)) ppDetails mheading = case subproofs of [] -> text "No subproblems were checked." _ -> maybe (vcat . map snd) block mheading $ ppDetail `map` subproofs ppDetail (i,proof_i) = (i,P.pprintProof proof_i mde) ppProb prob_i Nothing = Util.pprint prob_i ppProb prob_i (Just proof_i) = Util.pprint prob_i $+$ text "" $+$ (text "This problem" <+> (if P.succeeded proof_i then text "was proven" <+> Util.pprint (P.answer proof_i) else text "remains open") PP.<> text ".") normalisedProof :: (Transformer t, P.Processor sub) => Proof t sub -> Proof SomeTransformation P.SomeProcessor normalisedProof = someProof someProof :: (Transformer t, P.Processor sub) => Proof t sub -> Proof SomeTransformation P.SomeProcessor someProof proof = Proof { transformationResult = mapResult (SomeTransProof t) $ transformationResult proof , inputProblem = prob , appliedTransformer = someTransformation t , appliedSubprocessor = P.someInstance sub , subProofs = P.someProcessorProof `mapEnum` subProofs proof } where t = appliedTransformer proof sub = appliedSubprocessor proof prob = inputProblem proof -- | Result type for a transformation. data Result t = NoProgress (ProofOf t) -- ^ The transformation did not simplify the problem. | Progress (ProofOf t) (Enumeration Problem) -- ^ The transformation resulted in the given subproblems. -- | This is the proof of a transformation lifted to a processor. data Proof t sub = Proof { transformationResult :: Result t -- ^ The 'Result' generated by the transformation , inputProblem :: Problem -- ^ The input problem , appliedTransformer :: TheTransformer t -- ^ The instance of the applied transformation , appliedSubprocessor :: P.InstanceOf sub -- ^ The instance of the applied subprocessor , subProofs :: Enumeration (P.Proof sub) -- ^ An enumeration of the subproofs } -- | If the proof contains exactly one subproblem, return the -- computed certificate of this problem. Otherwise, return 'P.MaybeAnswer'. answerFromSubProof :: (P.Processor sub) => Proof t sub -> P.Answer answerFromSubProof proof = case subProofs proof of [(_, subproof)] -> P.answer subproof _ -> P.MaybeAnswer proofFromResult :: Result t -> (ProofOf t) proofFromResult (NoProgress t) = t proofFromResult (Progress t _) = t isProgressResult :: Result r -> Bool isProgressResult (Progress {}) = True isProgressResult (NoProgress {}) = False subProblemsFromResult :: Result r -> Enumeration Problem subProblemsFromResult (Progress _ ps) = ps subProblemsFromResult (NoProgress _) = [] mapResult :: (ProofOf t1 -> ProofOf t2) -> Result t1 -> Result t2 mapResult f (NoProgress p) = NoProgress (f p) mapResult f (Progress p ps) = Progress (f p) ps sanitiseResult :: Result t1 -> Result t1 sanitiseResult (Progress p ps) = Progress p $ mapEnum sanitise ps sanitiseResult res = res transformationProof :: Proof t sub -> ProofOf t transformationProof tproof = case transformationResult tproof of NoProgress p -> p Progress p _ -> p subProblems :: Proof t sub -> Enumeration Problem subProblems tproof = subProblemsFromResult $ transformationResult tproof findProof :: (Numbering a) => a -> Proof t sub -> Maybe (P.Proof sub) findProof e p = find e (subProofs p) -------------------------------------------------------------------------------- --- Transformation Class -- | This datatype defines a specific instance of a transformation. data TheTransformer t = TheTransformer { transformation :: t -- ^ The Transformation. , transformationArgs :: Domains (ArgumentsOf t) -- ^ Arguments of the transformation. } -- | The main class a transformation implements. class (Arguments (ArgumentsOf t), TransformationProof t) => Transformer t where -- | Unique name. name :: t -> String -- | Description of the transformation. description :: t -> [String] description = const [] -- | Arguments of the transformation, cf. "Tct.Processor.Args". type ArgumentsOf t -- | Proof type of the transformation. type ProofOf t -- | Description of the arguments, cf. module "Tct.Processor.Args". arguments :: t -> (ArgumentsOf t) -- | Optional name specific to instances. Defaults to the transformation name. instanceName :: TheTransformer t -> String instanceName = name . transformation -- | This is the main method of a transformation. Given a concrete -- instance, it translates a complexity problem into a 'Result'. transform :: P.SolverM m => TheTransformer t -> Problem -> m (Result t) -- | If 'True', then the processor will pretend that -- the input problem was simplified, independent on the result of 'transform'. -- This is used for implementing transformation 'Try', and should not be defined. continue :: TheTransformer t -> Bool continue _ = False -------------------------------------------------------------------------------- -- SomeTransformation data SomeTransformation = forall t. (Transformer t) => SomeTransformation t (Domains (ArgumentsOf t)) data SomeTransProof = forall t. (Transformer t, TransformationProof t) => SomeTransProof (TheTransformer t) (ProofOf t) onSomeProof :: P.Processor sub' => (forall t sub. (Transformer t, P.Processor sub) => Proof t sub -> a) -> Proof SomeTransformation sub' -> a f `onSomeProof` proof = case transformationProof proof of SomeTransProof tinst tproof -> f proof' where proof' = proof { transformationResult = case transformationResult proof of NoProgress _ -> NoProgress tproof Progress _ ps -> Progress tproof ps , appliedTransformer = tinst } instance TransformationProof SomeTransformation where answer proof = answer `onSomeProof` proof pprintProof proof = pprintProof `onSomeProof` proof pprintTProof _ prob (SomeTransProof t p) = pprintTProof t prob p proofToXml proof = proofToXml `onSomeProof` proof tproofToXml _ prob (SomeTransProof t p) = tproofToXml t prob p normalisedProof proof = case transformationProof proof of SomeTransProof tinst tproof -> normalisedProof $ proof { transformationResult = case transformationResult proof of NoProgress _ -> NoProgress tproof Progress _ ps -> Progress tproof ps , appliedTransformer = tinst } instance Transformer SomeTransformation where name (SomeTransformation t _) = name t continue (TheTransformer (SomeTransformation t as) _) = continue (TheTransformer t as) instanceName (TheTransformer (SomeTransformation t as) _) = instanceName (TheTransformer t as) description (SomeTransformation t _) = description t type ArgumentsOf SomeTransformation= Unit type ProofOf SomeTransformation = SomeTransProof arguments _ = Unit transform inst@(TheTransformer (SomeTransformation t as) ()) prob = mk `liftM` transform inst{transformation=t, transformationArgs = as} prob where mk (NoProgress p) = NoProgress (SomeTransProof tinst p) mk (Progress p ts) = Progress (SomeTransProof tinst p) ts tinst = TheTransformer t as -------------------------------------------------------------------------------- --- Transformation Processor subsumes :: Problem -> Problem -> Bool p1 `subsumes` p2 = check strictTrs && check strictDPs && check trsComponents && check dpComponents where -- checkStr f = toSet (f p2) `Set.isProperSubsetOf` toSet (f p1) check f = toSet (f p2) `Set.isSubsetOf` toSet (f p1) toSet = Set.fromList . Trs.rules -- | Provides a lifting from 'Transformer' to 'S.Processor'. data Transformation t sub = Transformation t instance ( Transformer t , P.Processor sub) => S.Processor (Transformation t sub) where type ProofOf (Transformation t sub) = Proof SomeTransformation P.SomeProcessor type ArgumentsOf (Transformation t sub) = Arg Bool :+: Arg Bool :+: Arg Bool :+: ArgumentsOf t :+: Arg (Proc sub) name (Transformation t) = name t instanceName inst = instanceName tinst where _ :+: _ :+: _ :+: as :+: _ = S.processorArgs inst Transformation t = S.processor inst tinst = TheTransformer t as description (Transformation t) = description t arguments (Transformation t) = opt { A.name = "strict" , A.description = unlines [ "If this flag is set and the transformation fails, this processor aborts." , "Otherwise, it applies the subprocessor on the untransformed input."] , A.defaultValue = False } :+: opt { A.name = "parallel" , A.description = "Decides whether the given subprocessor should be applied in parallel." , A.defaultValue = False } :+: opt { A.name = "checkSubsumed" , A.description = unlines [ "This flag determines whether the processor should reuse proofs in case that one generated problem subsumes another one." , "A problem (A) is subsumed by problem (B) if the complexity of (A) is bounded from above by the complexity of (B)." , "Currently we only take subset-inclusions of the different components into account." ] , A.defaultValue = False } :+: arguments t :+: arg { A.name = "subprocessor" , A.description = "The processor that is applied on the transformed problem(s)" } solve inst prob = do res <- sanitiseResult `liftM` transform tinst prob case res of NoProgress _ -> if continue tinst || not str then do sp <- P.apply sub prob return $ mkProof res (enumeration' [liftMS Nothing sp]) else return $ mkProof res [] Progress _ ps -> do let (subsumed, unsubsumed) | checkSubsume = splitSubsumed ps | otherwise = ([], ps) esubproofs <- P.evalList par (P.succeeded . snd) [P.apply sub p' >>= \ r -> return (e,r) | (e,p') <- unsubsumed] let subproofs = case esubproofs of { Left (fld,sps) -> fld:sps; Right sps -> sps } unsubsumedProofs = mapEnum (liftMS Nothing) subproofs subsumedProofs = catMaybes [ do proof_i <- find e_i subproofs return $ (SN e_j, liftMS (Just p_i) proof_i) | (SN e_i, p_i, SN e_j) <- subsumed ] return $ mkProof res $ unsubsumedProofs ++ subsumedProofs where (Transformation t) = S.processor inst tinst = TheTransformer t args str :+: par :+: checkSubsume :+: args :+: sub = S.processorArgs inst splitSubsumed [] = ([],[]) splitSubsumed ((e_i, p_i):ps) = ([ (e_i, p_i, e_j) | (e_j, _) <- subs_i ] ++ subs', unsubs') where (subs_i, unsubs_i) = partition (\ (_, p_j) -> p_i `subsumes` p_j) ps (subs', unsubs') = splitSubsumed unsubs_i mkProof res subproofs = normalisedProof $ Proof { transformationResult = res , inputProblem = prob , appliedSubprocessor = (SSI sub) , appliedTransformer = tinst , subProofs = subproofs} instance ( Transformer t, P.Processor sub ) => P.ComplexityProof (Proof t sub) where pprintProof proof P.StrategyOutput = pprintProof proof P.StrategyOutput pprintProof proof mde | not (isProgressResult (transformationResult proof)) = case subProofs proof of [(_, subproof)] -> P.pprintProof (P.result subproof) mde _ -> pprintProof proof mde | otherwise = pprintProof proof mde answer proof | not (isProgressResult (transformationResult proof)) = answerFromSubProof proof | otherwise = answer proof toXml proof = proofToXml proof -- | Constructor for instances. withArgs :: (Transformer t) => (Transformation t sub) -> (Domains (ArgumentsOf t)) -> TheTransformer t (Transformation t) `withArgs` as = TheTransformer t as -- | Modify parameters of instance modifyArguments :: (Transformer t) => (Domains (ArgumentsOf t) -> Domains (ArgumentsOf t)) -> (TheTransformer t -> TheTransformer t) modifyArguments f (TheTransformer t as) = TheTransformer t (f as) -- | Lifts transformations to standard processors. transformationProcessor :: (Arguments (ArgumentsOf t), ParsableArguments (ArgumentsOf t), Transformer t) => t -> S.StdProcessor (Transformation t sub) transformationProcessor t = S.StdProcessor (Transformation t) -------------------------------------------------------------------------------- --- utility functions for constructing and modifying transformations someTransformation :: Transformer t => TheTransformer t -> TheTransformer SomeTransformation someTransformation inst = inst { transformation = SomeTransformation (transformation inst) (transformationArgs inst) , transformationArgs = ()} type TransformationInstance t sub = P.InstanceOf (S.StdProcessor (Transformation t sub)) infixr 2 `thenApply` thenApply :: (P.Processor sub, Transformer t) => TheTransformer t -> P.InstanceOf sub -> TransformationInstance t sub thenApply ti@(TheTransformer t args) sub = (S.StdProcessor $ Transformation t) `S.withArgs` (not (continue ti) :+: False :+: False :+: args :+: sub) infixr 2 >>| -- | The processor @t '>>|' p@ first applies the transformation @t@. If this succeeds, the processor @p@ -- is applied on the resulting subproblems. Otherwise @t '>>|' p@ fails. (>>|) :: (P.Processor sub, Transformer t) => TheTransformer t -> P.InstanceOf sub -> TransformationInstance t sub (>>|) = thenApply infixr 2 `thenApplyPar` thenApplyPar :: (P.Processor sub, Transformer t) => TheTransformer t -> P.InstanceOf sub -> TransformationInstance t sub thenApplyPar ti@(TheTransformer t args) sub = (S.StdProcessor $ Transformation t) `S.withArgs` (not (continue ti) :+: True :+: False :+: args :+: sub) infixr 2 >>|| -- | Like '>>|' but resulting subproblems are solved in parallel by the given processor. (>>||) :: (P.Processor sub, Transformer t) => TheTransformer t -> P.InstanceOf sub -> TransformationInstance t sub (>>||) = thenApplyPar -- parallelSubgoals :: (P.Processor sub, Transformer t) => TransformationInstance t sub -> TransformationInstance t sub -- parallelSubgoals = S.modifyArguments $ \ (str :+: _ :+: subs :+: as :+: sub) -> str :+: True :+: subs :+: as :+: sub --- utility functions for constructing and modifying transformations -- checkSubsumed :: (P.Processor sub, Transformer t) => TransformationInstance t sub -> TransformationInstance t sub -- checkSubsumed = S.modifyArguments $ \ (str :+: par :+: _ :+: as :+: sub) -> str :+: par :+: True :+: as :+: sub -------------------------------------------------------------------------------- --- subsumed processor data Subsumed sub = Subsumed sub data MaybeSubsumed proof = MaybeSubsumed (Maybe Problem) proof liftMS :: Maybe Problem -> P.Proof proc -> P.Proof (Subsumed proc) liftMS mprob proof = proof { P.appliedProcessor = SSI (P.appliedProcessor proof) , P.result = MaybeSubsumed mprob (P.result proof) } instance P.ComplexityProof proof => P.ComplexityProof (MaybeSubsumed proof) where answer (MaybeSubsumed _ proof) = P.answer proof pprintProof (MaybeSubsumed Nothing proof) mde = P.pprintProof proof mde pprintProof (MaybeSubsumed (Just p) proof) mde = Util.paragraph "The complexity of the input problem is bounded by the complexity of the problem" $+$ text "" $+$ indent (Util.pprint p) $+$ text "" $+$ Util.paragraph "on which the subprocessor has allready been applied. We reuse following proof:" $+$ text "" $+$ P.pprintProof proof mde toXml (MaybeSubsumed Nothing proof) = P.toXml proof toXml (MaybeSubsumed _ proof) = P.toXml proof instance P.Processor proc => P.Processor (Subsumed proc) where data InstanceOf (Subsumed proc) = SSI (P.InstanceOf proc) type ProofOf (Subsumed proc) = MaybeSubsumed (P.ProofOf proc) name (Subsumed proc) = P.name proc instanceName (SSI inst) = P.instanceName inst processorToXml (SSI inst) = P.processorToXml inst solve_ (SSI inst) prob = MaybeSubsumed Nothing `liftM` P.solve_ inst prob solvePartial_ (SSI inst) rs prob = mk `liftM` P.solvePartial inst rs prob where mk pp = pp { P.ppResult = MaybeSubsumed Nothing $ P.ppResult pp} mkSubsumed :: P.InstanceOf proc -> P.InstanceOf (Subsumed proc) mkSubsumed = SSI
mzini/TcT
source/Tct/Processor/Transformations.hs
gpl-3.0
26,014
0
24
8,191
5,597
2,945
2,652
353
2
{- Copyright (C) 2013 Ellis Whitehead This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> -} {-# LANGUAGE OverloadedStrings #-} module OnTopOfThings.Commands.Utils ( refToUuid , processRefArgsAndFlags , processRefFlags , saveProperty ) where import Control.Applicative ((<$>), (<*>), empty) import Control.Monad (mplus) import Data.Maybe import Data.Monoid import Debug.Trace import System.Console.CmdArgs.Explicit import qualified Data.Map as M import qualified Data.Set as Set import qualified Data.UUID as U import qualified Data.UUID.V4 as U4 -- Database-related imports import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger (NoLoggingT) import Control.Monad.Trans.Control (MonadBaseControl) import Control.Monad.Trans.Resource (ResourceT) import Database.Persist.Sqlite -- Time-related imports import Data.Time.Clock import Data.Time.Format import Data.Time.ISO8601 import System.Locale (defaultTimeLocale) import Args import Command import DatabaseTables import DatabaseUtils import Utils import OnTopOfThings.Parsers.NumberList refToUuid :: String -> SqlPersistT (NoLoggingT (ResourceT IO)) (Validation String) refToUuid ref = do uuid' <- databaseLookupUuid ref case uuid' of Nothing -> return (Left ["Couldn't find ref: "++ref]) Just uuid -> return (Right uuid) processRefArgsAndFlags :: Options -> String -> SqlPersistT (NoLoggingT (ResourceT IO)) (Validation Options) processRefArgsAndFlags opts0 name = do case ids_ of Left msgs -> return (Left msgs) Right ids -> do uuids_ <- mapM refToUuid ids return $ do uuids <- concatEithersN uuids_ optionsReplaceParamN name uuids (opts0 { optionsArgs = [] }) where idArgs0 = optionsArgs opts0 flags0 = optionsFlags opts0 idFlags0 = catMaybes $ map (\(n, value) -> if n == name then Just value else Nothing) flags0 ids0 = idArgs0 ++ idFlags0 ids_ = (concatEithersN $ map parseNumberList ids0) >>= \ll -> (Right $ concat ll) processRefFlags :: Options -> String -> SqlPersistT (NoLoggingT (ResourceT IO)) (Validation Options) processRefFlags opts0 name = do case ids_ of Left msgs -> return (Left msgs) Right ids -> do uuids_ <- mapM refToUuid ids return $ do uuids <- concatEithersN uuids_ optionsReplaceParamN name uuids (opts0 { optionsArgs = [] }) where flags0 = optionsFlags opts0 ids0 = catMaybes $ map (\(n, value) -> if n == name then Just value else Nothing) flags0 ids_ = (concatEithersN $ map parseNumberList ids0) >>= \ll -> (Right $ concat ll) --instance Monad (Either e) where -- (Left msgs) >>= f = Left msgs -- (Right x) >>= f = f x -- return = Right ----createFolderItems :: UTCTime -> Options -> SqlPersistT (NoLoggingT (ResourceT IO)) (Validation [Item]) --createItem :: UTCTime -> Options -> Validation Item ----createItem _ opts | trace ("Utils.createItem: "++(show opts)) False = undefined --createItem time opts = do -- id <- get "id" -- type_ <- get "type" -- title <- get "title" -- status <- get "status" -- parent <- getMaybe "parent" -- stage <- getMaybe "stage" -- name <- getMaybe "name" -- title <- getMaybe "title" -- content <- getMaybe "content" -- closed <- getMaybeDate "closed" -- start <- getMaybe "start" -- end <- getMaybe "end" -- due <- getMaybe "due" -- defer <- getMaybe "defer" -- -- index -- return $ Item id time "default" type_ status parent name title content stage closed start end due defer Nothing -- where -- map = optionsMap opts -- get name = case M.lookup name map of -- Just (Just x) -> Right x -- _ -> Left ["missing value for `" ++ name ++ "`"] -- getMaybe name = case M.lookup name map of -- Just (Just s) -> Right (Just s) -- _ -> Right Nothing -- getMaybeDate :: String -> Validation (Maybe UTCTime) -- getMaybeDate name = case M.lookup name map of -- Just (Just s) -> -- (parseISO8601 s) `maybeToValidation` ["Could not parse time: " ++ s] >>= \time -> Right (Just time) -- _ -> Right Nothing -- --updateItem :: UTCTime -> M.Map String (Maybe String) -> Item -> Validation Item --updateItem time map item0 = -- Item <$> -- get "id" itemUuid <*> -- Right (itemCreated item0) <*> -- Right (itemCreator item0) <*> -- get "type" itemType <*> -- get "status" itemStatus <*> -- getMaybe "parent" itemParent <*> -- getMaybe "name" itemName <*> -- getMaybe "title" itemTitle <*> -- getMaybe "content" itemContent <*> -- getMaybe "stage" itemStage <*> -- getMaybeDate "closed" itemClosed <*> -- getMaybe "start" itemStart <*> -- getMaybe "end" itemEnd <*> -- getMaybe "due" itemDue <*> -- getMaybe "defer" itemDefer <*> -- Right (itemIndex item0) -- where -- get :: String -> (Item -> String) -> Validation String -- get name fn = case M.lookup name map of -- Just (Just s) -> Right s -- _ -> Right (fn item0) -- -- getMaybe :: String -> (Item -> Maybe String) -> Validation (Maybe String) -- getMaybe name fn = case M.lookup name map of -- Just (Just s) -> Right (Just s) -- _ -> Right (fn item0) -- -- getMaybeDate :: String -> (Item -> Maybe UTCTime) -> Validation (Maybe UTCTime) -- getMaybeDate name fn = case M.lookup name map of -- Just (Just s) -> (parseISO8601 s) `maybeToValidation` ["Could not parse time: " ++ s] >>= \time -> Right (Just time) -- _ -> Right (fn item0) -- itemFields = ["id", "type", "title", "status", "parent", "stage", "label", "index", "closed", "start", "end", "due", "review"] saveProperty :: String -> Mod -> SqlPersistT (NoLoggingT (ResourceT IO)) () saveProperty uuid (ModEqual name value) = do if elem name itemFields then return () else do deleteWhere [PropertyTable ==. "item", PropertyUuid ==. uuid, PropertyName ==. name] insert $ Property "item" uuid name value return () saveProperty uuid (ModUnset name) = do if elem name itemFields then return () else do deleteWhere [PropertyTable ==. "item", PropertyUuid ==. uuid, PropertyName ==. name] return () saveProperty uuid (ModAdd name value) = do if elem name itemFields then return () else do insert $ Property "item" uuid name value return () saveProperty uuid (ModRemove name value) = do if elem name itemFields then return () else do deleteWhere [PropertyTable ==. "item", PropertyUuid ==. uuid, PropertyName ==. name, PropertyValue ==. value] return () saveProperty _ arg = do liftIO $ print $ "Don't know how to handle arg: " ++ (show arg)
ellis/OnTopOfThings
old-20150308/src/OnTopOfThings/Commands/Utils.hs
gpl-3.0
7,067
0
19
1,421
1,254
699
555
84
5
{-# 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.FusionTables.Table.ImportTable -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Imports a new table. -- -- /See:/ <https://developers.google.com/fusiontables Fusion Tables API Reference> for @fusiontables.table.importTable@. module Network.Google.Resource.FusionTables.Table.ImportTable ( -- * REST Resource TableImportTableResource -- * Creating a Request , tableImportTable , TableImportTable -- * Request Lenses , titName , titDelimiter , titEncoding ) where import Network.Google.FusionTables.Types import Network.Google.Prelude -- | A resource alias for @fusiontables.table.importTable@ method which the -- 'TableImportTable' request conforms to. type TableImportTableResource = "fusiontables" :> "v2" :> "tables" :> "import" :> QueryParam "name" Text :> QueryParam "delimiter" Text :> QueryParam "encoding" Text :> QueryParam "alt" AltJSON :> Post '[JSON] Table :<|> "upload" :> "fusiontables" :> "v2" :> "tables" :> "import" :> QueryParam "name" Text :> QueryParam "delimiter" Text :> QueryParam "encoding" Text :> QueryParam "alt" AltJSON :> QueryParam "uploadType" AltMedia :> AltMedia :> Post '[JSON] Table -- | Imports a new table. -- -- /See:/ 'tableImportTable' smart constructor. data TableImportTable = TableImportTable' { _titName :: !Text , _titDelimiter :: !(Maybe Text) , _titEncoding :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TableImportTable' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'titName' -- -- * 'titDelimiter' -- -- * 'titEncoding' tableImportTable :: Text -- ^ 'titName' -> TableImportTable tableImportTable pTitName_ = TableImportTable' {_titName = pTitName_, _titDelimiter = Nothing, _titEncoding = Nothing} -- | The name to be assigned to the new table. titName :: Lens' TableImportTable Text titName = lens _titName (\ s a -> s{_titName = a}) -- | The delimiter used to separate cell values. This can only consist of a -- single character. Default is ,. titDelimiter :: Lens' TableImportTable (Maybe Text) titDelimiter = lens _titDelimiter (\ s a -> s{_titDelimiter = a}) -- | The encoding of the content. Default is UTF-8. Use auto-detect if you -- are unsure of the encoding. titEncoding :: Lens' TableImportTable (Maybe Text) titEncoding = lens _titEncoding (\ s a -> s{_titEncoding = a}) instance GoogleRequest TableImportTable where type Rs TableImportTable = Table type Scopes TableImportTable = '["https://www.googleapis.com/auth/fusiontables"] requestClient TableImportTable'{..} = go (Just _titName) _titDelimiter _titEncoding (Just AltJSON) fusionTablesService where go :<|> _ = buildClient (Proxy :: Proxy TableImportTableResource) mempty instance GoogleRequest (MediaUpload TableImportTable) where type Rs (MediaUpload TableImportTable) = Table type Scopes (MediaUpload TableImportTable) = Scopes TableImportTable requestClient (MediaUpload TableImportTable'{..} body) = go (Just _titName) _titDelimiter _titEncoding (Just AltJSON) (Just AltMedia) body fusionTablesService where _ :<|> go = buildClient (Proxy :: Proxy TableImportTableResource) mempty
brendanhay/gogol
gogol-fusiontables/gen/Network/Google/Resource/FusionTables/Table/ImportTable.hs
mpl-2.0
4,563
0
27
1,281
690
386
304
96
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Tags.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a GTM Tag. -- -- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.workspaces.tags.create@. module Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Tags.Create ( -- * REST Resource AccountsContainersWorkspacesTagsCreateResource -- * Creating a Request , accountsContainersWorkspacesTagsCreate , AccountsContainersWorkspacesTagsCreate -- * Request Lenses , acwtccParent , acwtccXgafv , acwtccUploadProtocol , acwtccAccessToken , acwtccUploadType , acwtccPayload , acwtccCallback ) where import Network.Google.Prelude import Network.Google.TagManager.Types -- | A resource alias for @tagmanager.accounts.containers.workspaces.tags.create@ method which the -- 'AccountsContainersWorkspacesTagsCreate' request conforms to. type AccountsContainersWorkspacesTagsCreateResource = "tagmanager" :> "v2" :> Capture "parent" Text :> "tags" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Tag :> Post '[JSON] Tag -- | Creates a GTM Tag. -- -- /See:/ 'accountsContainersWorkspacesTagsCreate' smart constructor. data AccountsContainersWorkspacesTagsCreate = AccountsContainersWorkspacesTagsCreate' { _acwtccParent :: !Text , _acwtccXgafv :: !(Maybe Xgafv) , _acwtccUploadProtocol :: !(Maybe Text) , _acwtccAccessToken :: !(Maybe Text) , _acwtccUploadType :: !(Maybe Text) , _acwtccPayload :: !Tag , _acwtccCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccountsContainersWorkspacesTagsCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acwtccParent' -- -- * 'acwtccXgafv' -- -- * 'acwtccUploadProtocol' -- -- * 'acwtccAccessToken' -- -- * 'acwtccUploadType' -- -- * 'acwtccPayload' -- -- * 'acwtccCallback' accountsContainersWorkspacesTagsCreate :: Text -- ^ 'acwtccParent' -> Tag -- ^ 'acwtccPayload' -> AccountsContainersWorkspacesTagsCreate accountsContainersWorkspacesTagsCreate pAcwtccParent_ pAcwtccPayload_ = AccountsContainersWorkspacesTagsCreate' { _acwtccParent = pAcwtccParent_ , _acwtccXgafv = Nothing , _acwtccUploadProtocol = Nothing , _acwtccAccessToken = Nothing , _acwtccUploadType = Nothing , _acwtccPayload = pAcwtccPayload_ , _acwtccCallback = Nothing } -- | GTM Workspace\'s API relative path. Example: -- accounts\/{account_id}\/containers\/{container_id}\/workspaces\/{workspace_id} acwtccParent :: Lens' AccountsContainersWorkspacesTagsCreate Text acwtccParent = lens _acwtccParent (\ s a -> s{_acwtccParent = a}) -- | V1 error format. acwtccXgafv :: Lens' AccountsContainersWorkspacesTagsCreate (Maybe Xgafv) acwtccXgafv = lens _acwtccXgafv (\ s a -> s{_acwtccXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). acwtccUploadProtocol :: Lens' AccountsContainersWorkspacesTagsCreate (Maybe Text) acwtccUploadProtocol = lens _acwtccUploadProtocol (\ s a -> s{_acwtccUploadProtocol = a}) -- | OAuth access token. acwtccAccessToken :: Lens' AccountsContainersWorkspacesTagsCreate (Maybe Text) acwtccAccessToken = lens _acwtccAccessToken (\ s a -> s{_acwtccAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). acwtccUploadType :: Lens' AccountsContainersWorkspacesTagsCreate (Maybe Text) acwtccUploadType = lens _acwtccUploadType (\ s a -> s{_acwtccUploadType = a}) -- | Multipart request metadata. acwtccPayload :: Lens' AccountsContainersWorkspacesTagsCreate Tag acwtccPayload = lens _acwtccPayload (\ s a -> s{_acwtccPayload = a}) -- | JSONP acwtccCallback :: Lens' AccountsContainersWorkspacesTagsCreate (Maybe Text) acwtccCallback = lens _acwtccCallback (\ s a -> s{_acwtccCallback = a}) instance GoogleRequest AccountsContainersWorkspacesTagsCreate where type Rs AccountsContainersWorkspacesTagsCreate = Tag type Scopes AccountsContainersWorkspacesTagsCreate = '["https://www.googleapis.com/auth/tagmanager.edit.containers"] requestClient AccountsContainersWorkspacesTagsCreate'{..} = go _acwtccParent _acwtccXgafv _acwtccUploadProtocol _acwtccAccessToken _acwtccUploadType _acwtccCallback (Just AltJSON) _acwtccPayload tagManagerService where go = buildClient (Proxy :: Proxy AccountsContainersWorkspacesTagsCreateResource) mempty
brendanhay/gogol
gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Workspaces/Tags/Create.hs
mpl-2.0
5,822
0
18
1,245
786
459
327
120
1
module Freekick.Libsoccer.Calendar where import Libaddutil.Primitives import Freekick.Libsoccer.TournamentInstance import Freekick.Libsoccer.Stage import Data.Maybe data Calendar = Calendar { currentdate :: Date , tournaments :: [TournamentInstance] } deriving (Eq, Show) newCalendar :: Date -> Calendar newCalendar d = Calendar d [] addTournamentInstanceToCalendar :: Calendar -> TournamentInstance -> Calendar addTournamentInstanceToCalendar Calendar{currentdate=d, tournaments=tl} t = Calendar d (t:tl) showCalendar :: Calendar -> IO () showCalendar c = do putStrLn $ showDate $ currentdate c printDatesAndMatches $ tournaments c increaseDate :: Calendar -> Calendar increaseDate c = c{currentdate = (currentdate c) `addDaysToDate` 1} playTodaysMatches :: Calendar -> IO Calendar playTodaysMatches c = do let ts = tournaments c nn <- mapM (playMatchesOfTheDay (currentdate c)) ts let (newt, ccha) = unzip nn let fint = updateTournamentInstances newt (concat ccha) let newc = c{tournaments = fint} return newc collectTournamentUpdates :: TournamentInstance -> [([String], StageTarget)] collectTournamentUpdates t = updateTournamentInstance t updateTournamentInstances :: [TournamentInstance] -> [([String], StageTarget)] -> [TournamentInstance] updateTournamentInstances [] _ = [] updateTournamentInstances ts [] = ts updateTournamentInstances (t:ts) (c@(ns, (tt, _)):cs) = if Freekick.Libsoccer.TournamentInstance.name t == tt then (addClubsByNames t ns) : updateTournamentInstances ts (c:cs) else t : updateTournamentInstances ts (c:cs) findTournamentInstance :: String -> [TournamentInstance] -> Maybe TournamentInstance findTournamentInstance _ [] = Nothing findTournamentInstance n (t:ts) = if Freekick.Libsoccer.TournamentInstance.name t == n then Just t else findTournamentInstance n ts
anttisalonen/freekick
haskell/libfreekick/Freekick/Libsoccer/Calendar.hs
agpl-3.0
1,968
0
12
385
601
319
282
38
2
module Ch8Exercises where {- Multiple Choice: - 1 -> d - 2 -> b - 3 -> d - 4 -> b -} cattyConny :: String -> String -> String cattyConny x y = x ++ " mrow " ++ y flippy:: String -> String -> String flippy = flip cattyConny appedCatty :: String -> String appedCatty = cattyConny "woops" frappe :: String -> String frappe = flippy "haha" {- Currying Review - 1 -> String - 2 -> String - 3 -> String - 4 -> String - 5 -> String - 6 -> String -} {- recursion - dividedBy 15 2 - go 15 2 0 - go 13 2 1 - go 11 2 2 - go 9 2 3 - go 7 2 4 - go 5 2 5 - go 3 2 6 - go 1 2 7 -} -- really I'd want a to be Ord as well so I can handle the negative number case -- instead of bottoming out sumNums :: (Eq a, Num a) => a -> a sumNums x | x == 0 = 0 | otherwise = x + sumNums(x - 1) multiplyNums :: (Integral a) => a -> a -> a -- multiplyNums x y = go 1 where go count | count == y = x | otherwise = x + go(count + 1) data DividedResult = Result Integer | DividedByZero deriving (Show) dividedBy :: Integral a => a -> a-> DividedResult dividedBy num denom | denom == 0 = DividedByZero | otherwise = signCheck (go (abs num) (abs denom) 0) where go n d count | n < d = count | otherwise = go (n - d) d (count + 1) signCheck result | num > 0 && denom < 0 = Result (negate result) | num < 0 && denom > 0 = Result (negate result) | otherwise = Result result mc91 n | n > 100 = n - 10 | otherwise = mc91 . mc91 $ n + 11
thewoolleyman/haskellbook
08/06/maor/ch8exercises.hs
unlicense
1,657
0
12
598
506
251
255
36
1
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 709 {-# LANGUAGE AutoDeriveTypeable #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.Trans.RWS.Lazy -- Copyright : (c) Andy Gill 2001, -- (c) Oregon Graduate Institute of Science and Technology, 2001 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : R.Paterson@city.ac.uk -- Stability : experimental -- Portability : portable -- -- A monad transformer that combines 'ReaderT', 'WriterT' and 'StateT'. -- This version is lazy; for a strict version with the same interface, -- see "Control.Monad.Trans.RWS.Strict". ----------------------------------------------------------------------------- module Control.Monad.Trans.RWS.Lazy ( -- * The RWS monad RWS, rws, runRWS, evalRWS, execRWS, mapRWS, withRWS, -- * The RWST monad transformer RWST(..), evalRWST, execRWST, mapRWST, withRWST, -- * Reader operations reader, ask, local, asks, -- * Writer operations writer, tell, listen, listens, pass, censor, -- * State operations state, get, put, modify, gets, -- * Lifting other operations liftCallCC, liftCallCC', liftCatch, ) where import Control.Monad.IO.Class import Control.Monad.Signatures import Control.Monad.Trans.Class import Data.Functor.Identity import Control.Applicative import Control.Monad import Control.Monad.Fix import Data.Monoid -- | A monad containing an environment of type @r@, output of type @w@ -- and an updatable state of type @s@. type RWS r w s = RWST r w s Identity -- | Construct an RWS computation from a function. -- (The inverse of 'runRWS'.) rws :: (r -> s -> (a, s, w)) -> RWS r w s a rws f = RWST (\ r s -> Identity (f r s)) -- | Unwrap an RWS computation as a function. -- (The inverse of 'rws'.) runRWS :: RWS r w s a -> r -> s -> (a, s, w) runRWS m r s = runIdentity (runRWST m r s) -- | Evaluate a computation with the given initial state and environment, -- returning the final value and output, discarding the final state. evalRWS :: RWS r w s a -- ^RWS computation to execute -> r -- ^initial environment -> s -- ^initial value -> (a, w) -- ^final value and output evalRWS m r s = let (a, _, w) = runRWS m r s in (a, w) -- | Evaluate a computation with the given initial state and environment, -- returning the final state and output, discarding the final value. execRWS :: RWS r w s a -- ^RWS computation to execute -> r -- ^initial environment -> s -- ^initial value -> (s, w) -- ^final state and output execRWS m r s = let (_, s', w) = runRWS m r s in (s', w) -- | Map the return value, final state and output of a computation using -- the given function. -- -- * @'runRWS' ('mapRWS' f m) r s = f ('runRWS' m r s)@ mapRWS :: ((a, s, w) -> (b, s, w')) -> RWS r w s a -> RWS r w' s b mapRWS f = mapRWST (Identity . f . runIdentity) -- | @'withRWS' f m@ executes action @m@ with an initial environment -- and state modified by applying @f@. -- -- * @'runRWS' ('withRWS' f m) r s = 'uncurry' ('runRWS' m) (f r s)@ withRWS :: (r' -> s -> (r, s)) -> RWS r w s a -> RWS r' w s a withRWS = withRWST -- --------------------------------------------------------------------------- -- | A monad transformer adding reading an environment of type @r@, -- collecting an output of type @w@ and updating a state of type @s@ -- to an inner monad @m@. newtype RWST r w s m a = RWST { runRWST :: r -> s -> m (a, s, w) } -- | Evaluate a computation with the given initial state and environment, -- returning the final value and output, discarding the final state. evalRWST :: (Monad m) => RWST r w s m a -- ^computation to execute -> r -- ^initial environment -> s -- ^initial value -> m (a, w) -- ^computation yielding final value and output evalRWST m r s = do ~(a, _, w) <- runRWST m r s return (a, w) -- | Evaluate a computation with the given initial state and environment, -- returning the final state and output, discarding the final value. execRWST :: (Monad m) => RWST r w s m a -- ^computation to execute -> r -- ^initial environment -> s -- ^initial value -> m (s, w) -- ^computation yielding final state and output execRWST m r s = do ~(_, s', w) <- runRWST m r s return (s', w) -- | Map the inner computation using the given function. -- -- * @'runRWST' ('mapRWST' f m) r s = f ('runRWST' m r s)@ mapRWST :: (m (a, s, w) -> n (b, s, w')) -> RWST r w s m a -> RWST r w' s n b mapRWST f m = RWST $ \ r s -> f (runRWST m r s) -- | @'withRWST' f m@ executes action @m@ with an initial environment -- and state modified by applying @f@. -- -- * @'runRWST' ('withRWST' f m) r s = 'uncurry' ('runRWST' m) (f r s)@ withRWST :: (r' -> s -> (r, s)) -> RWST r w s m a -> RWST r' w s m a withRWST f m = RWST $ \ r s -> uncurry (runRWST m) (f r s) instance (Functor m) => Functor (RWST r w s m) where fmap f m = RWST $ \ r s -> fmap (\ ~(a, s', w) -> (f a, s', w)) $ runRWST m r s instance (Monoid w, Functor m, Monad m) => Applicative (RWST r w s m) where pure = return (<*>) = ap instance (Monoid w, Functor m, MonadPlus m) => Alternative (RWST r w s m) where empty = mzero (<|>) = mplus instance (Monoid w, Monad m) => Monad (RWST r w s m) where return a = RWST $ \ _ s -> return (a, s, mempty) m >>= k = RWST $ \ r s -> do ~(a, s', w) <- runRWST m r s ~(b, s'',w') <- runRWST (k a) r s' return (b, s'', w `mappend` w') fail msg = RWST $ \ _ _ -> fail msg instance (Monoid w, MonadPlus m) => MonadPlus (RWST r w s m) where mzero = RWST $ \ _ _ -> mzero m `mplus` n = RWST $ \ r s -> runRWST m r s `mplus` runRWST n r s instance (Monoid w, MonadFix m) => MonadFix (RWST r w s m) where mfix f = RWST $ \ r s -> mfix $ \ ~(a, _, _) -> runRWST (f a) r s instance (Monoid w) => MonadTrans (RWST r w s) where lift m = RWST $ \ _ s -> do a <- m return (a, s, mempty) instance (Monoid w, MonadIO m) => MonadIO (RWST r w s m) where liftIO = lift . liftIO -- --------------------------------------------------------------------------- -- Reader operations -- | Constructor for computations in the reader monad (equivalent to 'asks'). reader :: (Monoid w, Monad m) => (r -> a) -> RWST r w s m a reader = asks -- | Fetch the value of the environment. ask :: (Monoid w, Monad m) => RWST r w s m r ask = RWST $ \ r s -> return (r, s, mempty) -- | Execute a computation in a modified environment -- -- * @'runRWST' ('local' f m) r s = 'runRWST' m (f r) s@ local :: (r -> r) -> RWST r w s m a -> RWST r w s m a local f m = RWST $ \ r s -> runRWST m (f r) s -- | Retrieve a function of the current environment. -- -- * @'asks' f = 'liftM' f 'ask'@ asks :: (Monoid w, Monad m) => (r -> a) -> RWST r w s m a asks f = RWST $ \ r s -> return (f r, s, mempty) -- --------------------------------------------------------------------------- -- Writer operations -- | Construct a writer computation from a (result, output) pair. writer :: (Monad m) => (a, w) -> RWST r w s m a writer (a, w) = RWST $ \ _ s -> return (a, s, w) -- | @'tell' w@ is an action that produces the output @w@. tell :: (Monad m) => w -> RWST r w s m () tell w = RWST $ \ _ s -> return ((),s,w) -- | @'listen' m@ is an action that executes the action @m@ and adds its -- output to the value of the computation. -- -- * @'runRWST' ('listen' m) r s = 'liftM' (\\ (a, w) -> ((a, w), w)) ('runRWST' m r s)@ listen :: (Monad m) => RWST r w s m a -> RWST r w s m (a, w) listen m = RWST $ \ r s -> do ~(a, s', w) <- runRWST m r s return ((a, w), s', w) -- | @'listens' f m@ is an action that executes the action @m@ and adds -- the result of applying @f@ to the output to the value of the computation. -- -- * @'listens' f m = 'liftM' (id *** f) ('listen' m)@ -- -- * @'runRWST' ('listens' f m) r s = 'liftM' (\\ (a, w) -> ((a, f w), w)) ('runRWST' m r s)@ listens :: (Monad m) => (w -> b) -> RWST r w s m a -> RWST r w s m (a, b) listens f m = RWST $ \ r s -> do ~(a, s', w) <- runRWST m r s return ((a, f w), s', w) -- | @'pass' m@ is an action that executes the action @m@, which returns -- a value and a function, and returns the value, applying the function -- to the output. -- -- * @'runRWST' ('pass' m) r s = 'liftM' (\\ ((a, f), w) -> (a, f w)) ('runRWST' m r s)@ pass :: (Monad m) => RWST r w s m (a, w -> w) -> RWST r w s m a pass m = RWST $ \ r s -> do ~((a, f), s', w) <- runRWST m r s return (a, s', f w) -- | @'censor' f m@ is an action that executes the action @m@ and -- applies the function @f@ to its output, leaving the return value -- unchanged. -- -- * @'censor' f m = 'pass' ('liftM' (\\ x -> (x,f)) m)@ -- -- * @'runRWST' ('censor' f m) r s = 'liftM' (\\ (a, w) -> (a, f w)) ('runRWST' m r s)@ censor :: (Monad m) => (w -> w) -> RWST r w s m a -> RWST r w s m a censor f m = RWST $ \ r s -> do ~(a, s', w) <- runRWST m r s return (a, s', f w) -- --------------------------------------------------------------------------- -- State operations -- | Construct a state monad computation from a state transformer function. state :: (Monoid w, Monad m) => (s -> (a,s)) -> RWST r w s m a state f = RWST $ \ _ s -> let (a,s') = f s in return (a, s', mempty) -- | Fetch the current value of the state within the monad. get :: (Monoid w, Monad m) => RWST r w s m s get = RWST $ \ _ s -> return (s, s, mempty) -- | @'put' s@ sets the state within the monad to @s@. put :: (Monoid w, Monad m) => s -> RWST r w s m () put s = RWST $ \ _ _ -> return ((), s, mempty) -- | @'modify' f@ is an action that updates the state to the result of -- applying @f@ to the current state. -- -- * @'modify' f = 'get' >>= ('put' . f)@ modify :: (Monoid w, Monad m) => (s -> s) -> RWST r w s m () modify f = RWST $ \ _ s -> return ((), f s, mempty) -- | Get a specific component of the state, using a projection function -- supplied. -- -- * @'gets' f = 'liftM' f 'get'@ gets :: (Monoid w, Monad m) => (s -> a) -> RWST r w s m a gets f = RWST $ \ _ s -> return (f s, s, mempty) -- | Uniform lifting of a @callCC@ operation to the new monad. -- This version rolls back to the original state on entering the -- continuation. liftCallCC :: (Monoid w) => CallCC m (a,s,w) (b,s,w) -> CallCC (RWST r w s m) a b liftCallCC callCC f = RWST $ \ r s -> callCC $ \ c -> runRWST (f (\ a -> RWST $ \ _ _ -> c (a, s, mempty))) r s -- | In-situ lifting of a @callCC@ operation to the new monad. -- This version uses the current state on entering the continuation. liftCallCC' :: (Monoid w) => CallCC m (a,s,w) (b,s,w) -> CallCC (RWST r w s m) a b liftCallCC' callCC f = RWST $ \ r s -> callCC $ \ c -> runRWST (f (\ a -> RWST $ \ _ s' -> c (a, s', mempty))) r s -- | Lift a @catchE@ operation to the new monad. liftCatch :: Catch e m (a,s,w) -> Catch e (RWST r w s m) a liftCatch catchE m h = RWST $ \ r s -> runRWST m r s `catchE` \ e -> runRWST (h e) r s
holoed/Junior
lib/transformers-0.4.3.0/Control/Monad/Trans/RWS/Lazy.hs
apache-2.0
11,343
0
17
2,974
3,429
1,895
1,534
162
1
{- History.hs Copyright (c) 2014 by Sebastien Soudan. Apache License Version 2.0, January 2004 -} -- | Move history module. -- Based on DList to have O(1) inserts -- We only convert it back to List to get it diplayed -- module History where import Data.DList as DL import Move(Move) type History = DList Move -- | Create a new empty history newHistory :: History newHistory = DL.empty -- | Append a move to the history appendHistory :: History -> Move -> History appendHistory = DL.snoc -- | Convert the history to a list of String historyToList :: History -> [String] historyToList = DL.toList . DL.map show
ssoudan/hsChess
src/History.hs
apache-2.0
639
0
7
137
96
59
37
10
1
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-} {-# LANGUAGE OverloadedStrings, GADTs, FlexibleContexts #-} import Data.Text (Text, append) import qualified Data.Text.Lazy as L import Data.Monoid (mconcat, (<>)) import Control.Monad.IO.Class import Database.Esqueleto import Database.Persist.Sqlite (runSqlite, runMigration) import Database.Persist.TH (mkPersist, mkMigrate, persistLowerCase, share, sqlSettings) import Web.Scotty as S share [mkPersist sqlSettings, mkMigrate "migrateTables"] [persistLowerCase| Comment body Text authorName Text thread ThreadId deriving Show Thread slug Text |] {-TODO: monad for threads?-} fillDB = runSqlite "sqltemp.sqlite" $ do runMigration migrateTables t <- insert $ Thread "thread/1/slug/" insert $ Comment "Hello" "Curtis" t insert $ Comment "World" "Justin" t insert $ Comment "Goodbye" "Curtis" t getComments = runSqlite "sqltemp.sqlite" $ do comments <- select $ from $ \c -> return c return $ map (prettyComment . entityVal) comments prettyComment c = commentAuthorName c <> ": " <> commentBody c main :: IO () main = do fillDB (comment:_) <- getComments scotty 3000 $ do S.get "/:word" $ do html $ mconcat $ map L.fromStrict ["<h1>Scotty, ", comment, " me up!</h1>"]
cgag/scotty-esqueleto-example
src/comments.hs
apache-2.0
1,312
0
15
250
352
185
167
29
1
import Criterion.Main import Numeric.Sum as Sum import System.Random.MWC import qualified Data.Vector.Unboxed as U main = do gen <- createSystemRandom v <- uniformVector gen 10000000 :: IO (U.Vector Double) defaultMain [ bench "naive" $ whnf U.sum v , bench "pairwise" $ whnf pairwiseSum v , bench "kahan" $ whnf (sumVector kahan) v , bench "kbn" $ whnf (sumVector kbn) v , bench "kb2" $ whnf (sumVector kb2) v ]
bos/math-functions
math-functions-bench/Summation.hs
bsd-2-clause
446
0
12
101
167
84
83
13
1
{-# OPTIONS -fglasgow-exts -#include "../include/gui/qtc_hs_QAbstractProxyModel.h" #-} ----------------------------------------------------------------------------- {-| Module : QAbstractProxyModel.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:26 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QAbstractProxyModel ( QqAbstractProxyModel(..) ,sourceModel ,qAbstractProxyModel_delete ,qAbstractProxyModel_deleteLater ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QuserMethod (QAbstractProxyModel ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QAbstractProxyModel_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QAbstractProxyModel_userMethod" qtc_QAbstractProxyModel_userMethod :: Ptr (TQAbstractProxyModel a) -> CInt -> IO () instance QuserMethod (QAbstractProxyModelSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QAbstractProxyModel_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QAbstractProxyModel ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QAbstractProxyModel_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QAbstractProxyModel_userMethodVariant" qtc_QAbstractProxyModel_userMethodVariant :: Ptr (TQAbstractProxyModel a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QAbstractProxyModelSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QAbstractProxyModel_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqAbstractProxyModel x1 where qAbstractProxyModel :: x1 -> IO (QAbstractProxyModel ()) instance QqAbstractProxyModel (()) where qAbstractProxyModel () = withQAbstractProxyModelResult $ qtc_QAbstractProxyModel foreign import ccall "qtc_QAbstractProxyModel" qtc_QAbstractProxyModel :: IO (Ptr (TQAbstractProxyModel ())) instance QqAbstractProxyModel ((QObject t1)) where qAbstractProxyModel (x1) = withQAbstractProxyModelResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel1 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel1" qtc_QAbstractProxyModel1 :: Ptr (TQObject t1) -> IO (Ptr (TQAbstractProxyModel ())) instance Qqdata (QAbstractProxyModel ()) ((QModelIndex t1)) (IO (QVariant ())) where qdata x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_data cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_data" qtc_QAbstractProxyModel_data :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQVariant ())) instance Qqdata (QAbstractProxyModelSc a) ((QModelIndex t1)) (IO (QVariant ())) where qdata x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_data cobj_x0 cobj_x1 instance Qqdata_nf (QAbstractProxyModel ()) ((QModelIndex t1)) (IO (QVariant ())) where qdata_nf x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_data cobj_x0 cobj_x1 instance Qqdata_nf (QAbstractProxyModelSc a) ((QModelIndex t1)) (IO (QVariant ())) where qdata_nf x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_data cobj_x0 cobj_x1 instance Qqdata (QAbstractProxyModel ()) ((QModelIndex t1, Int)) (IO (QVariant ())) where qdata x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_data1_h cobj_x0 cobj_x1 (toCInt x2) foreign import ccall "qtc_QAbstractProxyModel_data1_h" qtc_QAbstractProxyModel_data1_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> CInt -> IO (Ptr (TQVariant ())) instance Qqdata (QAbstractProxyModelSc a) ((QModelIndex t1, Int)) (IO (QVariant ())) where qdata x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_data1_h cobj_x0 cobj_x1 (toCInt x2) instance Qqdata_nf (QAbstractProxyModel ()) ((QModelIndex t1, Int)) (IO (QVariant ())) where qdata_nf x0 (x1, x2) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_data1_h cobj_x0 cobj_x1 (toCInt x2) instance Qqdata_nf (QAbstractProxyModelSc a) ((QModelIndex t1, Int)) (IO (QVariant ())) where qdata_nf x0 (x1, x2) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_data1_h cobj_x0 cobj_x1 (toCInt x2) instance Qflags (QAbstractProxyModel ()) ((QModelIndex t1)) (IO (ItemFlags)) where flags x0 (x1) = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_flags_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_flags_h" qtc_QAbstractProxyModel_flags_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> IO CLong instance Qflags (QAbstractProxyModelSc a) ((QModelIndex t1)) (IO (ItemFlags)) where flags x0 (x1) = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_flags_h cobj_x0 cobj_x1 instance QheaderData (QAbstractProxyModel ()) ((Int, QtOrientation, Int)) where headerData x0 (x1, x2, x3) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_headerData_h cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) (toCInt x3) foreign import ccall "qtc_QAbstractProxyModel_headerData_h" qtc_QAbstractProxyModel_headerData_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CLong -> CInt -> IO (Ptr (TQVariant ())) instance QheaderData (QAbstractProxyModelSc a) ((Int, QtOrientation, Int)) where headerData x0 (x1, x2, x3) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_headerData_h cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) (toCInt x3) instance QheaderData_nf (QAbstractProxyModel ()) ((Int, QtOrientation, Int)) where headerData_nf x0 (x1, x2, x3) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_headerData_h cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) (toCInt x3) instance QheaderData_nf (QAbstractProxyModelSc a) ((Int, QtOrientation, Int)) where headerData_nf x0 (x1, x2, x3) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_headerData_h cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) (toCInt x3) instance QmapFromSource (QAbstractProxyModel ()) ((QModelIndex t1)) where mapFromSource x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_mapFromSource_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_mapFromSource_h" qtc_QAbstractProxyModel_mapFromSource_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQModelIndex ())) instance QmapFromSource (QAbstractProxyModelSc a) ((QModelIndex t1)) where mapFromSource x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_mapFromSource_h cobj_x0 cobj_x1 instance QmapSelectionFromSource (QAbstractProxyModel ()) ((QItemSelection t1)) where mapSelectionFromSource x0 (x1) = withQItemSelectionResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_mapSelectionFromSource_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_mapSelectionFromSource_h" qtc_QAbstractProxyModel_mapSelectionFromSource_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQItemSelection ())) instance QmapSelectionFromSource (QAbstractProxyModelSc a) ((QItemSelection t1)) where mapSelectionFromSource x0 (x1) = withQItemSelectionResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_mapSelectionFromSource_h cobj_x0 cobj_x1 instance QmapSelectionToSource (QAbstractProxyModel ()) ((QItemSelection t1)) where mapSelectionToSource x0 (x1) = withQItemSelectionResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_mapSelectionToSource_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_mapSelectionToSource_h" qtc_QAbstractProxyModel_mapSelectionToSource_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQItemSelection ())) instance QmapSelectionToSource (QAbstractProxyModelSc a) ((QItemSelection t1)) where mapSelectionToSource x0 (x1) = withQItemSelectionResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_mapSelectionToSource_h cobj_x0 cobj_x1 instance QmapToSource (QAbstractProxyModel ()) ((QModelIndex t1)) where mapToSource x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_mapToSource_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_mapToSource_h" qtc_QAbstractProxyModel_mapToSource_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQModelIndex ())) instance QmapToSource (QAbstractProxyModelSc a) ((QModelIndex t1)) where mapToSource x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_mapToSource_h cobj_x0 cobj_x1 instance Qrevert (QAbstractProxyModel ()) (()) where revert x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_revert_h cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_revert_h" qtc_QAbstractProxyModel_revert_h :: Ptr (TQAbstractProxyModel a) -> IO () instance Qrevert (QAbstractProxyModelSc a) (()) where revert x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_revert_h cobj_x0 instance QsetSourceModel (QAbstractProxyModel ()) ((QAbstractItemModel t1)) where setSourceModel x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_setSourceModel_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_setSourceModel_h" qtc_QAbstractProxyModel_setSourceModel_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQAbstractItemModel t1) -> IO () instance QsetSourceModel (QAbstractProxyModelSc a) ((QAbstractItemModel t1)) where setSourceModel x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_setSourceModel_h cobj_x0 cobj_x1 sourceModel :: QAbstractProxyModel a -> (()) -> IO (QAbstractItemModel ()) sourceModel x0 () = withQAbstractItemModelResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_sourceModel cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_sourceModel" qtc_QAbstractProxyModel_sourceModel :: Ptr (TQAbstractProxyModel a) -> IO (Ptr (TQAbstractItemModel ())) instance Qsubmit (QAbstractProxyModel ()) (()) where submit x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_submit_h cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_submit_h" qtc_QAbstractProxyModel_submit_h :: Ptr (TQAbstractProxyModel a) -> IO CBool instance Qsubmit (QAbstractProxyModelSc a) (()) where submit x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_submit_h cobj_x0 qAbstractProxyModel_delete :: QAbstractProxyModel a -> IO () qAbstractProxyModel_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_delete cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_delete" qtc_QAbstractProxyModel_delete :: Ptr (TQAbstractProxyModel a) -> IO () qAbstractProxyModel_deleteLater :: QAbstractProxyModel a -> IO () qAbstractProxyModel_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_deleteLater cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_deleteLater" qtc_QAbstractProxyModel_deleteLater :: Ptr (TQAbstractProxyModel a) -> IO () instance QbeginInsertColumns (QAbstractProxyModel ()) ((QModelIndex t1, Int, Int)) where beginInsertColumns x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_beginInsertColumns cobj_x0 cobj_x1 (toCInt x2) (toCInt x3) foreign import ccall "qtc_QAbstractProxyModel_beginInsertColumns" qtc_QAbstractProxyModel_beginInsertColumns :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO () instance QbeginInsertColumns (QAbstractProxyModelSc a) ((QModelIndex t1, Int, Int)) where beginInsertColumns x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_beginInsertColumns cobj_x0 cobj_x1 (toCInt x2) (toCInt x3) instance QbeginInsertRows (QAbstractProxyModel ()) ((QModelIndex t1, Int, Int)) where beginInsertRows x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_beginInsertRows cobj_x0 cobj_x1 (toCInt x2) (toCInt x3) foreign import ccall "qtc_QAbstractProxyModel_beginInsertRows" qtc_QAbstractProxyModel_beginInsertRows :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO () instance QbeginInsertRows (QAbstractProxyModelSc a) ((QModelIndex t1, Int, Int)) where beginInsertRows x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_beginInsertRows cobj_x0 cobj_x1 (toCInt x2) (toCInt x3) instance QbeginRemoveColumns (QAbstractProxyModel ()) ((QModelIndex t1, Int, Int)) where beginRemoveColumns x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_beginRemoveColumns cobj_x0 cobj_x1 (toCInt x2) (toCInt x3) foreign import ccall "qtc_QAbstractProxyModel_beginRemoveColumns" qtc_QAbstractProxyModel_beginRemoveColumns :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO () instance QbeginRemoveColumns (QAbstractProxyModelSc a) ((QModelIndex t1, Int, Int)) where beginRemoveColumns x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_beginRemoveColumns cobj_x0 cobj_x1 (toCInt x2) (toCInt x3) instance QbeginRemoveRows (QAbstractProxyModel ()) ((QModelIndex t1, Int, Int)) where beginRemoveRows x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_beginRemoveRows cobj_x0 cobj_x1 (toCInt x2) (toCInt x3) foreign import ccall "qtc_QAbstractProxyModel_beginRemoveRows" qtc_QAbstractProxyModel_beginRemoveRows :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO () instance QbeginRemoveRows (QAbstractProxyModelSc a) ((QModelIndex t1, Int, Int)) where beginRemoveRows x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_beginRemoveRows cobj_x0 cobj_x1 (toCInt x2) (toCInt x3) instance Qbuddy (QAbstractProxyModel ()) ((QModelIndex t1)) (IO (QModelIndex ())) where buddy x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_buddy_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_buddy_h" qtc_QAbstractProxyModel_buddy_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQModelIndex ())) instance Qbuddy (QAbstractProxyModelSc a) ((QModelIndex t1)) (IO (QModelIndex ())) where buddy x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_buddy_h cobj_x0 cobj_x1 instance QcanFetchMore (QAbstractProxyModel ()) ((QModelIndex t1)) where canFetchMore x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_canFetchMore_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_canFetchMore_h" qtc_QAbstractProxyModel_canFetchMore_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> IO CBool instance QcanFetchMore (QAbstractProxyModelSc a) ((QModelIndex t1)) where canFetchMore x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_canFetchMore_h cobj_x0 cobj_x1 instance QchangePersistentIndex (QAbstractProxyModel ()) ((QModelIndex t1, QModelIndex t2)) where changePersistentIndex x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractProxyModel_changePersistentIndex cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QAbstractProxyModel_changePersistentIndex" qtc_QAbstractProxyModel_changePersistentIndex :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO () instance QchangePersistentIndex (QAbstractProxyModelSc a) ((QModelIndex t1, QModelIndex t2)) where changePersistentIndex x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractProxyModel_changePersistentIndex cobj_x0 cobj_x1 cobj_x2 instance QcolumnCount (QAbstractProxyModel ()) (()) where columnCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_columnCount_h cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_columnCount_h" qtc_QAbstractProxyModel_columnCount_h :: Ptr (TQAbstractProxyModel a) -> IO CInt instance QcolumnCount (QAbstractProxyModelSc a) (()) where columnCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_columnCount_h cobj_x0 instance QcolumnCount (QAbstractProxyModel ()) ((QModelIndex t1)) where columnCount x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_columnCount1_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_columnCount1_h" qtc_QAbstractProxyModel_columnCount1_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> IO CInt instance QcolumnCount (QAbstractProxyModelSc a) ((QModelIndex t1)) where columnCount x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_columnCount1_h cobj_x0 cobj_x1 instance QcreateIndex (QAbstractProxyModel ()) ((Int, Int)) where createIndex x0 (x1, x2) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_createIndex cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QAbstractProxyModel_createIndex" qtc_QAbstractProxyModel_createIndex :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> IO (Ptr (TQModelIndex ())) instance QcreateIndex (QAbstractProxyModelSc a) ((Int, Int)) where createIndex x0 (x1, x2) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_createIndex cobj_x0 (toCInt x1) (toCInt x2) instance QcreateIndex (QAbstractProxyModel ()) ((Int, Int, Int)) where createIndex x0 (x1, x2, x3) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_createIndex2 cobj_x0 (toCInt x1) (toCInt x2) (toCUInt x3) foreign import ccall "qtc_QAbstractProxyModel_createIndex2" qtc_QAbstractProxyModel_createIndex2 :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> CUInt -> IO (Ptr (TQModelIndex ())) instance QcreateIndex (QAbstractProxyModelSc a) ((Int, Int, Int)) where createIndex x0 (x1, x2, x3) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_createIndex2 cobj_x0 (toCInt x1) (toCInt x2) (toCUInt x3) instance QcreateIndex (QAbstractProxyModel ()) ((Int, Int, QVoid t3)) where createIndex x0 (x1, x2, x3) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_createIndex3 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 foreign import ccall "qtc_QAbstractProxyModel_createIndex3" qtc_QAbstractProxyModel_createIndex3 :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> Ptr (TQVoid t3) -> IO (Ptr (TQModelIndex ())) instance QcreateIndex (QAbstractProxyModelSc a) ((Int, Int, QVoid t3)) where createIndex x0 (x1, x2, x3) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_createIndex3 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 instance QdropMimeData (QAbstractProxyModel ()) ((QMimeData t1, DropAction, Int, Int, QModelIndex t5)) where dropMimeData x0 (x1, x2, x3, x4, x5) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x5 $ \cobj_x5 -> qtc_QAbstractProxyModel_dropMimeData_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) (toCInt x3) (toCInt x4) cobj_x5 foreign import ccall "qtc_QAbstractProxyModel_dropMimeData_h" qtc_QAbstractProxyModel_dropMimeData_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQMimeData t1) -> CLong -> CInt -> CInt -> Ptr (TQModelIndex t5) -> IO CBool instance QdropMimeData (QAbstractProxyModelSc a) ((QMimeData t1, DropAction, Int, Int, QModelIndex t5)) where dropMimeData x0 (x1, x2, x3, x4, x5) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x5 $ \cobj_x5 -> qtc_QAbstractProxyModel_dropMimeData_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) (toCInt x3) (toCInt x4) cobj_x5 instance QendInsertColumns (QAbstractProxyModel ()) (()) where endInsertColumns x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_endInsertColumns cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_endInsertColumns" qtc_QAbstractProxyModel_endInsertColumns :: Ptr (TQAbstractProxyModel a) -> IO () instance QendInsertColumns (QAbstractProxyModelSc a) (()) where endInsertColumns x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_endInsertColumns cobj_x0 instance QendInsertRows (QAbstractProxyModel ()) (()) where endInsertRows x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_endInsertRows cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_endInsertRows" qtc_QAbstractProxyModel_endInsertRows :: Ptr (TQAbstractProxyModel a) -> IO () instance QendInsertRows (QAbstractProxyModelSc a) (()) where endInsertRows x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_endInsertRows cobj_x0 instance QendRemoveColumns (QAbstractProxyModel ()) (()) where endRemoveColumns x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_endRemoveColumns cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_endRemoveColumns" qtc_QAbstractProxyModel_endRemoveColumns :: Ptr (TQAbstractProxyModel a) -> IO () instance QendRemoveColumns (QAbstractProxyModelSc a) (()) where endRemoveColumns x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_endRemoveColumns cobj_x0 instance QendRemoveRows (QAbstractProxyModel ()) (()) where endRemoveRows x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_endRemoveRows cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_endRemoveRows" qtc_QAbstractProxyModel_endRemoveRows :: Ptr (TQAbstractProxyModel a) -> IO () instance QendRemoveRows (QAbstractProxyModelSc a) (()) where endRemoveRows x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_endRemoveRows cobj_x0 instance QfetchMore (QAbstractProxyModel ()) ((QModelIndex t1)) where fetchMore x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_fetchMore_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_fetchMore_h" qtc_QAbstractProxyModel_fetchMore_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> IO () instance QfetchMore (QAbstractProxyModelSc a) ((QModelIndex t1)) where fetchMore x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_fetchMore_h cobj_x0 cobj_x1 instance QhasChildren (QAbstractProxyModel ()) (()) where hasChildren x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_hasChildren_h cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_hasChildren_h" qtc_QAbstractProxyModel_hasChildren_h :: Ptr (TQAbstractProxyModel a) -> IO CBool instance QhasChildren (QAbstractProxyModelSc a) (()) where hasChildren x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_hasChildren_h cobj_x0 instance QhasChildren (QAbstractProxyModel ()) ((QModelIndex t1)) where hasChildren x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_hasChildren1_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_hasChildren1_h" qtc_QAbstractProxyModel_hasChildren1_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> IO CBool instance QhasChildren (QAbstractProxyModelSc a) ((QModelIndex t1)) where hasChildren x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_hasChildren1_h cobj_x0 cobj_x1 instance Qindex (QAbstractProxyModel ()) ((Int, Int)) (IO (QModelIndex ())) where index x0 (x1, x2) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_index_h cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QAbstractProxyModel_index_h" qtc_QAbstractProxyModel_index_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> IO (Ptr (TQModelIndex ())) instance Qindex (QAbstractProxyModelSc a) ((Int, Int)) (IO (QModelIndex ())) where index x0 (x1, x2) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_index_h cobj_x0 (toCInt x1) (toCInt x2) instance Qindex (QAbstractProxyModel ()) ((Int, Int, QModelIndex t3)) (IO (QModelIndex ())) where index x0 (x1, x2, x3) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_index1_h cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 foreign import ccall "qtc_QAbstractProxyModel_index1_h" qtc_QAbstractProxyModel_index1_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO (Ptr (TQModelIndex ())) instance Qindex (QAbstractProxyModelSc a) ((Int, Int, QModelIndex t3)) (IO (QModelIndex ())) where index x0 (x1, x2, x3) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_index1_h cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 instance QinsertColumn (QAbstractProxyModel ()) ((Int)) (IO (Bool)) where insertColumn x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_insertColumn cobj_x0 (toCInt x1) foreign import ccall "qtc_QAbstractProxyModel_insertColumn" qtc_QAbstractProxyModel_insertColumn :: Ptr (TQAbstractProxyModel a) -> CInt -> IO CBool instance QinsertColumn (QAbstractProxyModelSc a) ((Int)) (IO (Bool)) where insertColumn x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_insertColumn cobj_x0 (toCInt x1) instance QinsertColumn (QAbstractProxyModel ()) ((Int, QModelIndex t2)) (IO (Bool)) where insertColumn x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractProxyModel_insertColumn1 cobj_x0 (toCInt x1) cobj_x2 foreign import ccall "qtc_QAbstractProxyModel_insertColumn1" qtc_QAbstractProxyModel_insertColumn1 :: Ptr (TQAbstractProxyModel a) -> CInt -> Ptr (TQModelIndex t2) -> IO CBool instance QinsertColumn (QAbstractProxyModelSc a) ((Int, QModelIndex t2)) (IO (Bool)) where insertColumn x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractProxyModel_insertColumn1 cobj_x0 (toCInt x1) cobj_x2 instance QinsertColumns (QAbstractProxyModel ()) ((Int, Int)) (IO (Bool)) where insertColumns x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_insertColumns_h cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QAbstractProxyModel_insertColumns_h" qtc_QAbstractProxyModel_insertColumns_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> IO CBool instance QinsertColumns (QAbstractProxyModelSc a) ((Int, Int)) (IO (Bool)) where insertColumns x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_insertColumns_h cobj_x0 (toCInt x1) (toCInt x2) instance QinsertColumns (QAbstractProxyModel ()) ((Int, Int, QModelIndex t3)) (IO (Bool)) where insertColumns x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_insertColumns1_h cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 foreign import ccall "qtc_QAbstractProxyModel_insertColumns1_h" qtc_QAbstractProxyModel_insertColumns1_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO CBool instance QinsertColumns (QAbstractProxyModelSc a) ((Int, Int, QModelIndex t3)) (IO (Bool)) where insertColumns x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_insertColumns1_h cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 instance QinsertRow (QAbstractProxyModel ()) ((Int)) (IO (Bool)) where insertRow x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_insertRow cobj_x0 (toCInt x1) foreign import ccall "qtc_QAbstractProxyModel_insertRow" qtc_QAbstractProxyModel_insertRow :: Ptr (TQAbstractProxyModel a) -> CInt -> IO CBool instance QinsertRow (QAbstractProxyModelSc a) ((Int)) (IO (Bool)) where insertRow x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_insertRow cobj_x0 (toCInt x1) instance QinsertRow (QAbstractProxyModel ()) ((Int, QModelIndex t2)) (IO (Bool)) where insertRow x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractProxyModel_insertRow1 cobj_x0 (toCInt x1) cobj_x2 foreign import ccall "qtc_QAbstractProxyModel_insertRow1" qtc_QAbstractProxyModel_insertRow1 :: Ptr (TQAbstractProxyModel a) -> CInt -> Ptr (TQModelIndex t2) -> IO CBool instance QinsertRow (QAbstractProxyModelSc a) ((Int, QModelIndex t2)) (IO (Bool)) where insertRow x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractProxyModel_insertRow1 cobj_x0 (toCInt x1) cobj_x2 instance QinsertRows (QAbstractProxyModel ()) ((Int, Int)) (IO (Bool)) where insertRows x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_insertRows_h cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QAbstractProxyModel_insertRows_h" qtc_QAbstractProxyModel_insertRows_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> IO CBool instance QinsertRows (QAbstractProxyModelSc a) ((Int, Int)) (IO (Bool)) where insertRows x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_insertRows_h cobj_x0 (toCInt x1) (toCInt x2) instance QinsertRows (QAbstractProxyModel ()) ((Int, Int, QModelIndex t3)) (IO (Bool)) where insertRows x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_insertRows1_h cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 foreign import ccall "qtc_QAbstractProxyModel_insertRows1_h" qtc_QAbstractProxyModel_insertRows1_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO CBool instance QinsertRows (QAbstractProxyModelSc a) ((Int, Int, QModelIndex t3)) (IO (Bool)) where insertRows x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_insertRows1_h cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 instance Qparent (QAbstractProxyModel ()) ((QModelIndex t1)) (IO (QModelIndex ())) where parent x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_parent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_parent_h" qtc_QAbstractProxyModel_parent_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQModelIndex ())) instance Qparent (QAbstractProxyModelSc a) ((QModelIndex t1)) (IO (QModelIndex ())) where parent x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_parent_h cobj_x0 cobj_x1 instance QremoveColumns (QAbstractProxyModel ()) ((Int, Int)) (IO (Bool)) where removeColumns x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_removeColumns_h cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QAbstractProxyModel_removeColumns_h" qtc_QAbstractProxyModel_removeColumns_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> IO CBool instance QremoveColumns (QAbstractProxyModelSc a) ((Int, Int)) (IO (Bool)) where removeColumns x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_removeColumns_h cobj_x0 (toCInt x1) (toCInt x2) instance QremoveColumns (QAbstractProxyModel ()) ((Int, Int, QModelIndex t3)) (IO (Bool)) where removeColumns x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_removeColumns1_h cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 foreign import ccall "qtc_QAbstractProxyModel_removeColumns1_h" qtc_QAbstractProxyModel_removeColumns1_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO CBool instance QremoveColumns (QAbstractProxyModelSc a) ((Int, Int, QModelIndex t3)) (IO (Bool)) where removeColumns x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_removeColumns1_h cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 instance QremoveRows (QAbstractProxyModel ()) ((Int, Int)) (IO (Bool)) where removeRows x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_removeRows_h cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QAbstractProxyModel_removeRows_h" qtc_QAbstractProxyModel_removeRows_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> IO CBool instance QremoveRows (QAbstractProxyModelSc a) ((Int, Int)) (IO (Bool)) where removeRows x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_removeRows_h cobj_x0 (toCInt x1) (toCInt x2) instance QremoveRows (QAbstractProxyModel ()) ((Int, Int, QModelIndex t3)) (IO (Bool)) where removeRows x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_removeRows1_h cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 foreign import ccall "qtc_QAbstractProxyModel_removeRows1_h" qtc_QAbstractProxyModel_removeRows1_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO CBool instance QremoveRows (QAbstractProxyModelSc a) ((Int, Int, QModelIndex t3)) (IO (Bool)) where removeRows x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_removeRows1_h cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 instance Qreset (QAbstractProxyModel ()) (()) (IO ()) where reset x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_reset cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_reset" qtc_QAbstractProxyModel_reset :: Ptr (TQAbstractProxyModel a) -> IO () instance Qreset (QAbstractProxyModelSc a) (()) (IO ()) where reset x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_reset cobj_x0 instance QrowCount (QAbstractProxyModel ()) (()) where rowCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_rowCount_h cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_rowCount_h" qtc_QAbstractProxyModel_rowCount_h :: Ptr (TQAbstractProxyModel a) -> IO CInt instance QrowCount (QAbstractProxyModelSc a) (()) where rowCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_rowCount_h cobj_x0 instance QrowCount (QAbstractProxyModel ()) ((QModelIndex t1)) where rowCount x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_rowCount1_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_rowCount1_h" qtc_QAbstractProxyModel_rowCount1_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> IO CInt instance QrowCount (QAbstractProxyModelSc a) ((QModelIndex t1)) where rowCount x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_rowCount1_h cobj_x0 cobj_x1 instance QsetData (QAbstractProxyModel ()) ((QModelIndex t1, QVariant t2)) (IO (Bool)) where setData x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractProxyModel_setData_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QAbstractProxyModel_setData_h" qtc_QAbstractProxyModel_setData_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> IO CBool instance QsetData (QAbstractProxyModelSc a) ((QModelIndex t1, QVariant t2)) (IO (Bool)) where setData x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractProxyModel_setData_h cobj_x0 cobj_x1 cobj_x2 instance QsetData (QAbstractProxyModel ()) ((QModelIndex t1, QVariant t2, Int)) (IO (Bool)) where setData x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractProxyModel_setData1_h cobj_x0 cobj_x1 cobj_x2 (toCInt x3) foreign import ccall "qtc_QAbstractProxyModel_setData1_h" qtc_QAbstractProxyModel_setData1_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> CInt -> IO CBool instance QsetData (QAbstractProxyModelSc a) ((QModelIndex t1, QVariant t2, Int)) (IO (Bool)) where setData x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractProxyModel_setData1_h cobj_x0 cobj_x1 cobj_x2 (toCInt x3) instance QsetHeaderData (QAbstractProxyModel ()) ((Int, QtOrientation, QVariant t3)) where setHeaderData x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_setHeaderData_h cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) cobj_x3 foreign import ccall "qtc_QAbstractProxyModel_setHeaderData_h" qtc_QAbstractProxyModel_setHeaderData_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CLong -> Ptr (TQVariant t3) -> IO CBool instance QsetHeaderData (QAbstractProxyModelSc a) ((Int, QtOrientation, QVariant t3)) where setHeaderData x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_setHeaderData_h cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) cobj_x3 instance QsetHeaderData (QAbstractProxyModel ()) ((Int, QtOrientation, QVariant t3, Int)) where setHeaderData x0 (x1, x2, x3, x4) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_setHeaderData1_h cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) cobj_x3 (toCInt x4) foreign import ccall "qtc_QAbstractProxyModel_setHeaderData1_h" qtc_QAbstractProxyModel_setHeaderData1_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CLong -> Ptr (TQVariant t3) -> CInt -> IO CBool instance QsetHeaderData (QAbstractProxyModelSc a) ((Int, QtOrientation, QVariant t3, Int)) where setHeaderData x0 (x1, x2, x3, x4) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractProxyModel_setHeaderData1_h cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) cobj_x3 (toCInt x4) instance Qsort (QAbstractProxyModel ()) ((Int)) where sort x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_sort_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QAbstractProxyModel_sort_h" qtc_QAbstractProxyModel_sort_h :: Ptr (TQAbstractProxyModel a) -> CInt -> IO () instance Qsort (QAbstractProxyModelSc a) ((Int)) where sort x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_sort_h cobj_x0 (toCInt x1) instance Qsort (QAbstractProxyModel ()) ((Int, SortOrder)) where sort x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_sort1_h cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QAbstractProxyModel_sort1_h" qtc_QAbstractProxyModel_sort1_h :: Ptr (TQAbstractProxyModel a) -> CInt -> CLong -> IO () instance Qsort (QAbstractProxyModelSc a) ((Int, SortOrder)) where sort x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_sort1_h cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) instance Qqspan (QAbstractProxyModel ()) ((QModelIndex t1)) where qspan x0 (x1) = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_span_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_span_h" qtc_QAbstractProxyModel_span_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQSize ())) instance Qqspan (QAbstractProxyModelSc a) ((QModelIndex t1)) where qspan x0 (x1) = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_span_h cobj_x0 cobj_x1 instance Qspan (QAbstractProxyModel ()) ((QModelIndex t1)) where span x0 (x1) = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_span_qth_h cobj_x0 cobj_x1 csize_ret_w csize_ret_h foreign import ccall "qtc_QAbstractProxyModel_span_qth_h" qtc_QAbstractProxyModel_span_qth_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQModelIndex t1) -> Ptr CInt -> Ptr CInt -> IO () instance Qspan (QAbstractProxyModelSc a) ((QModelIndex t1)) where span x0 (x1) = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_span_qth_h cobj_x0 cobj_x1 csize_ret_w csize_ret_h instance QsupportedDropActions (QAbstractProxyModel ()) (()) where supportedDropActions x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_supportedDropActions_h cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_supportedDropActions_h" qtc_QAbstractProxyModel_supportedDropActions_h :: Ptr (TQAbstractProxyModel a) -> IO CLong instance QsupportedDropActions (QAbstractProxyModelSc a) (()) where supportedDropActions x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_supportedDropActions_h cobj_x0 instance QchildEvent (QAbstractProxyModel ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_childEvent" qtc_QAbstractProxyModel_childEvent :: Ptr (TQAbstractProxyModel a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QAbstractProxyModelSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QAbstractProxyModel ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractProxyModel_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractProxyModel_connectNotify" qtc_QAbstractProxyModel_connectNotify :: Ptr (TQAbstractProxyModel a) -> CWString -> IO () instance QconnectNotify (QAbstractProxyModelSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractProxyModel_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QAbstractProxyModel ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_customEvent" qtc_QAbstractProxyModel_customEvent :: Ptr (TQAbstractProxyModel a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QAbstractProxyModelSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QAbstractProxyModel ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractProxyModel_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractProxyModel_disconnectNotify" qtc_QAbstractProxyModel_disconnectNotify :: Ptr (TQAbstractProxyModel a) -> CWString -> IO () instance QdisconnectNotify (QAbstractProxyModelSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractProxyModel_disconnectNotify cobj_x0 cstr_x1 instance Qevent (QAbstractProxyModel ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_event_h" qtc_QAbstractProxyModel_event_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QAbstractProxyModelSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_event_h cobj_x0 cobj_x1 instance QeventFilter (QAbstractProxyModel ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractProxyModel_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QAbstractProxyModel_eventFilter_h" qtc_QAbstractProxyModel_eventFilter_h :: Ptr (TQAbstractProxyModel a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QAbstractProxyModelSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractProxyModel_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QAbstractProxyModel ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractProxyModel_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractProxyModel_receivers" qtc_QAbstractProxyModel_receivers :: Ptr (TQAbstractProxyModel a) -> CWString -> IO CInt instance Qreceivers (QAbstractProxyModelSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractProxyModel_receivers cobj_x0 cstr_x1 instance Qsender (QAbstractProxyModel ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_sender cobj_x0 foreign import ccall "qtc_QAbstractProxyModel_sender" qtc_QAbstractProxyModel_sender :: Ptr (TQAbstractProxyModel a) -> IO (Ptr (TQObject ())) instance Qsender (QAbstractProxyModelSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractProxyModel_sender cobj_x0 instance QtimerEvent (QAbstractProxyModel ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractProxyModel_timerEvent" qtc_QAbstractProxyModel_timerEvent :: Ptr (TQAbstractProxyModel a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QAbstractProxyModelSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractProxyModel_timerEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QAbstractProxyModel.hs
bsd-2-clause
49,524
0
15
7,509
15,315
7,836
7,479
-1
-1
module Propellor.Property.User where import System.Posix import Propellor.Base import qualified Propellor.Property.File as File data Eep = YesReallyDeleteHome accountFor :: User -> Property NoInfo accountFor user@(User u) = check (isNothing <$> catchMaybeIO (homedir user)) $ cmdProperty "adduser" [ "--disabled-password" , "--gecos", "" , u ] `describe` ("account for " ++ u) -- | Removes user home directory!! Use with caution. nuked :: User -> Eep -> Property NoInfo nuked user@(User u) _ = check (isJust <$> catchMaybeIO (homedir user)) $ cmdProperty "userdel" [ "-r" , u ] `describe` ("nuked user " ++ u) -- | Only ensures that the user has some password set. It may or may -- not be a password from the PrivData. hasSomePassword :: User -> Property HasInfo hasSomePassword user = hasSomePassword' user hostContext -- | While hasSomePassword uses the name of the host as context, -- this allows specifying a different context. This is useful when -- you want to use the same password on multiple hosts, for example. hasSomePassword' :: IsContext c => User -> c -> Property HasInfo hasSomePassword' user context = check ((/= HasPassword) <$> getPasswordStatus user) $ hasPassword' user context -- | Ensures that a user's password is set to a password from the PrivData. -- (Will change any existing password.) -- -- A user's password can be stored in the PrivData in either of two forms; -- the full cleartext <Password> or a <CryptPassword> hash. The latter -- is obviously more secure. hasPassword :: User -> Property HasInfo hasPassword user = hasPassword' user hostContext hasPassword' :: IsContext c => User -> c -> Property HasInfo hasPassword' (User u) context = go `requires` shadowConfig True where go = withSomePrivData srcs context $ property (u ++ " has password") . setPassword srcs = [ PrivDataSource (CryptPassword u) "a crypt(3)ed password, which can be generated by, for example: perl -e 'print crypt(shift, q{$6$}.shift)' 'somepassword' 'somesalt'" , PrivDataSource (Password u) ("a password for " ++ u) ] setPassword :: (((PrivDataField, PrivData) -> Propellor Result) -> Propellor Result) -> Propellor Result setPassword getpassword = getpassword $ go where go (Password user, password) = chpasswd (User user) (privDataVal password) [] go (CryptPassword user, hash) = chpasswd (User user) (privDataVal hash) ["--encrypted"] go (f, _) = error $ "Unexpected type of privdata: " ++ show f -- | Makes a user's password be the passed String. Highly insecure: -- The password is right there in your config file for anyone to see! hasInsecurePassword :: User -> String -> Property NoInfo hasInsecurePassword u@(User n) p = property (n ++ " has insecure password") $ chpasswd u p [] chpasswd :: User -> String -> [String] -> Propellor Result chpasswd (User user) v ps = makeChange $ withHandle StdinHandle createProcessSuccess (proc "chpasswd" ps) $ \h -> do hPutStrLn h $ user ++ ":" ++ v hClose h lockedPassword :: User -> Property NoInfo lockedPassword user@(User u) = check (not <$> isLockedPassword user) $ cmdProperty "passwd" [ "--lock" , u ] `describe` ("locked " ++ u ++ " password") data PasswordStatus = NoPassword | LockedPassword | HasPassword deriving (Eq) getPasswordStatus :: User -> IO PasswordStatus getPasswordStatus (User u) = parse . words <$> readProcess "passwd" ["-S", u] where parse (_:"L":_) = LockedPassword parse (_:"NP":_) = NoPassword parse (_:"P":_) = HasPassword parse _ = NoPassword isLockedPassword :: User -> IO Bool isLockedPassword user = (== LockedPassword) <$> getPasswordStatus user homedir :: User -> IO FilePath homedir (User user) = homeDirectory <$> getUserEntryForName user hasGroup :: User -> Group -> Property NoInfo hasGroup (User user) (Group group') = check test $ cmdProperty "adduser" [ user , group' ] `describe` unwords ["user", user, "in group", group'] where test = not . elem group' . words <$> readProcess "groups" [user] -- | Controls whether shadow passwords are enabled or not. shadowConfig :: Bool -> Property NoInfo shadowConfig True = check (not <$> shadowExists) $ cmdProperty "shadowconfig" ["on"] `describe` "shadow passwords enabled" shadowConfig False = check shadowExists $ cmdProperty "shadowconfig" ["off"] `describe` "shadow passwords disabled" shadowExists :: IO Bool shadowExists = doesFileExist "/etc/shadow" -- | Ensures that a user has a specified login shell, and that the shell -- is enabled in /etc/shells. hasLoginShell :: User -> FilePath -> Property NoInfo hasLoginShell user loginshell = shellSetTo user loginshell `requires` shellEnabled loginshell shellSetTo :: User -> FilePath -> Property NoInfo shellSetTo (User u) loginshell = check needchangeshell $ cmdProperty "chsh" ["--shell", loginshell, u] `describe` (u ++ " has login shell " ++ loginshell) where needchangeshell = do currshell <- userShell <$> getUserEntryForName u return (currshell /= loginshell) -- | Ensures that /etc/shells contains a shell. shellEnabled :: FilePath -> Property NoInfo shellEnabled loginshell = "/etc/shells" `File.containsLine` loginshell
np/propellor
src/Propellor/Property/User.hs
bsd-2-clause
5,121
52
12
862
1,441
752
689
87
4
{-# LANGUAGE OverloadedStrings #-} module RequestParserSpec where import Control.Exception import Control.Monad import Data.Attoparsec import qualified Data.ByteString as ByteString import Network.Panpipes.HTTP.RequestParser import Network.Panpipes.HTTP.Types (Method) import qualified Network.Panpipes.HTTP.Types as Types (PartialRequest(..)) import Network.Panpipes.HTTP.Types hiding (PartialRequest(..)) import Test.Hspec spec :: Spec spec = do describe "method" $ it "parses http method" $ forM_ [ ("OPTION" , Option) , ("GET" , Get) , ("HEAD" , Head) , ("DELETE" , Delete) , ("TRACE" , Trace) , ("CONNECT", Connect) , ("POST" , Post) , ("PUT" , Put) ] $ \(input, expected) -> parse_ method input `shouldBe` expected describe "version" $ do it "parses http version" $ do parse_ version "HTTP/1.0" `shouldBe` Version { major = 1, minor = 0 } parse_ version "HTTP/1.1" `shouldBe` Version { major = 1, minor = 1 } parse_ version "HTTP/2.2" `shouldBe` Version { major = 2, minor = 2 } it "cannot parse illegal input" $ evaluate(parse_ version "1.0") `shouldThrow` anyErrorCall describe "headers" $ do it "parses a http headers" $ parse_ headers "K1: V1\r\n" `shouldBe` [("K1", "V1")] it "parses http headers" $ do let input = "K1:V1\r\nK2: V2\r\n" parse_ headers input `shouldBe` [("K1", "V1"), ("K2", "V2")] it "accepts multi-line value" $ do let input1 = "K1:V1\r\nK2: V2\r\n -A\r\n" parse_ headers input1 `shouldBe` [("K1", "V1"), ("K2", "V2 -A")] let input2 = "K1:V1\r\nK2: V2\r\n \t -B\r\n" parse_ headers input2 `shouldBe` [("K1", "V1"), ("K2", "V2 -B")] it "does not accept the header having space(s) before `:`" $ do parse_ headers "K1: V1\r\nK2 : V2\r\n" `shouldBe` [("K1", "V1")] parse_ headers "K1 : V1\r\nK2: V2\r\n" `shouldBe` [] parse_ headers "K1 : V1\r\n" `shouldBe` [] describe "request" $ it "parses http request excepting for body" $ do let req = ByteString.concat [ "POST /enlighten/calais.asmx HTTP/1.1\r\n" , "Host: localhost\r\n" , "Content-Type: text/xml;\r\n" , " charset=utf-8\r\n" , "Content-Length: length\r\n" , "\r\n" , "BODY" ] parse_ request req `shouldBe` Types.PartialRequest { Types.method = Post , Types.uri = "/enlighten/calais.asmx" , Types.version = Version 1 1 , Types.headers = [ ("Host", "localhost") , ("Content-Type", "text/xml; charset=utf-8") , ("Content-Length", "length") ] } where parse_ p input = let parser r = case r of Partial f -> parser $ f ByteString.empty Done _ a -> a Fail _ _ a -> error a in parser $ parse p input
quantumman/Panpipes
test/RequestParserSpec.hs
bsd-3-clause
3,302
0
16
1,195
813
451
362
69
3
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE Rank2Types #-} module Ling.SubTerms ( SubTerms(subTerms) , transProgramTerms , varDecTerms , absTerms ) where import Ling.Norm import Ling.Prelude import Ling.Session.Core class SubTerms a where subTerms :: Traversal' a Term transProgramTerms :: (Defs -> Endom Term) -> Endom Program transProgramTerms = transProgramDecs . (over subTerms .) varDecTerms :: Traversal' VarDec Term varDecTerms = argBody . _Just absTerms :: Traversal' (VarDec, Term) Term absTerms = varDecTerms `beside` id instance SubTerms a => SubTerms (Maybe a) where subTerms = _Just . subTerms instance SubTerms a => SubTerms [a] where subTerms = list . subTerms instance (SubTerms a, SubTerms b) => SubTerms (a, b) where subTerms = subTerms `beside` subTerms instance SubTerms Session where subTerms f = \case TermS p t -> termS p <$> f t Array k ss -> Array k <$> subTerms f ss IO rw vd s -> IO rw <$> varDecTerms f vd <*> subTerms f s instance SubTerms Sessions where subTerms = _Sessions . subTerms instance SubTerms RFactor where subTerms = _RFactor instance SubTerms RSession where subTerms f (s `Repl` r) = Repl <$> subTerms f s <*> subTerms f r instance SubTerms ChanDec where subTerms f (ChanDec c r os) = ChanDec c <$> subTerms f r <*> subTerms f os instance SubTerms CPatt where subTerms f = \case ChanP cd -> ChanP <$> subTerms f cd ArrayP k pats -> ArrayP k <$> subTerms f pats instance SubTerms Assertion where subTerms f = \case Equal lhs rhs mty -> Equal <$> f lhs <*> f rhs <*> _Just f mty instance SubTerms Dec where subTerms f = \case Sig d mty t -> Sig d <$> _Just f mty <*> f t d@Dat{} -> pure d Assert a -> Assert <$> subTerms f a
np/ling
Ling/SubTerms.hs
bsd-3-clause
1,762
0
12
393
659
331
328
52
1
module Data.Sort ( -- * The Vanilla Sorts L.sort , L.sortBy , L.sortOn -- * Sorting Associations , monoidSortAssocs , monoidSortAssocsBy , groupSortAssocs , groupSortAssocsBy -- * Sorting with Monoids , monoidSort , monoidSortOn , monoidSortBy -- * Unique Sorts , uniqueSort , uniqueSortOn , uniqueSortBy -- * Group Sorting , groupSort , groupSortOn , groupSortBy ) where import qualified Data.List as L import Data.Monoid import Data.Ord -- | Sort the list of associations, aggregating duplicates with the -- monoid. monoidSortAssocs :: (Monoid a,Ord k) => [(k,a)] -> [(k,a)] monoidSortAssocs = monoidSortAssocsBy compare -- | Sort the list of associations, aggregating duplicates with the -- monoid and ordering the keys with the argument compare function. monoidSortAssocsBy :: (Monoid a) => (k->k->Ordering) -> [(k,a)] -> [(k,a)] monoidSortAssocsBy cmp = groupSortAssocsBy cmp $ const monoid_group -- | Sort the list of associations, aggregating duplicates with the -- supplied function. groupSortAssocs :: Ord k => (k->a->[a]->b) -> [(k,a)] -> [(k,b)] groupSortAssocs = groupSortAssocsBy compare -- | Sort the list of associations, aggregating duplicates with the -- supplied function and ordering the keys with the argument -- compare function. groupSortAssocsBy :: (k->k->Ordering) -> (k->a->[a]->b) -> [(k,a)] -> [(k,b)] groupSortAssocsBy cmp0 grp0 = groupSortBy cmp grp where cmp (k,_) (k',_) = cmp0 k k' grp (k,y) ps = (,) k $ grp0 k y $ map snd ps -- | Sort the list, agregating duplicates with the monoid. monoidSort :: (Monoid a,Ord a) => [a] -> [a] monoidSort = monoidSortBy compare -- | Sort the list, agregating duplicates with the monoid and -- ordering the elements by the items generated by the -- argument function. monoidSortOn :: (Monoid a,Ord k) => (a->k) -> [a] -> [a] monoidSortOn chg = groupSortOn chg $ const monoid_group -- | Sort the list, agregating duplicates with the monoid -- and ordering the keys with the argument compare function. monoidSortBy :: Monoid a => (a->a->Ordering) -> [a] -> [a] monoidSortBy cmp = groupSortBy cmp monoid_group -- | Sort the list, discarding duplicates. uniqueSort :: Ord a => [a] -> [a] uniqueSort = uniqueSortBy compare -- | Sort the list, discarding duplicates and -- ordering the elements by the items generated by the -- argument function. uniqueSortOn :: Ord k => (a->k) -> [a] -> [a] uniqueSortOn chg = groupSortOn chg $ const const -- | Sort the list, discarding duplicates and ordering the keys with -- the argument compare function. uniqueSortBy :: (a->a->Ordering) -> [a] -> [a] uniqueSortBy cmp = groupSortBy cmp const -- | Sort a list of elements with a stable sort, grouping together the -- equal elements with the argument grouping function groupSort :: (Ord a) => (a->[a]->b) -> [a] -> [b] groupSort = groupSortBy compare -- | Sort a list of elements with a stable sort, using the argument -- @compare@ function determine the ordering, grouping together the -- equal elements with the grouping function groupSortOn :: Ord k => (a->k) -> (k->a->[a]->b) -> [a] -> [b] groupSortOn chg grp = groupSortBy (comparing fst) grp_val . map inj where grp_val a as = grp k (snd a) $ map snd as where k = fst a inj x = k `seq` (k,x) where k = chg x -- | Sort a list of elements with a stable sort, grouping together the -- equal elements with the argument grouping function. groupSortBy :: (a->a->Ordering) -> (a->[a]->b) -> [a] -> [b] groupSortBy cmp grp = aggregate . L.sortBy cmp where aggregate [] = [] aggregate (h:t) = seq g $ g : aggregate rst where g = grp h eqs (eqs,rst) = span is_le t is_le x = case cmp x h of LT -> True EQ -> True GT -> False -- the monoid_group helper monoid_group :: Monoid a => a -> [a] -> a monoid_group x xs = x <> mconcat xs
cdornan/sort
src/Data/Sort.hs
bsd-3-clause
4,249
0
12
1,156
1,135
629
506
81
4
-- | Api for watching and notifying file changes. -- Currently, this is based on inotify, but people may want to -- provide implementations of this module for non-inotify-supported -- platforms. module System.Plugins.Auto.FileSystemWatcher ( FSWatcher , FSWatchDescriptor , initFSWatcher , addWatch , removeWatch ) where import Control.Concurrent.MVar (MVar,readMVar,modifyMVar,modifyMVar_,newMVar) import System.INotify (INotify, WatchDescriptor, Event(..), EventVariety(..),initINotify) import qualified System.INotify as I(addWatch, removeWatch) import System.FilePath (splitFileName) import qualified Data.Map as Map import Data.Map (Map) -- | A FSWatcher watches several files for changes. If a file is deleted from the -- containing folder, it keeps watching the folder in case the file is added -- again. data FSWatcher = FSWatcher INotify -- INotify handle (MVar (Map FilePath -- Folder containing the file ( WatchDescriptor -- Watch descriptor of the folder , Map String -- File being observed (Event -> IO ()) -- Handler to run on file events ) ) ) -- | Identifier used to stop watching files. data FSWatchDescriptor = FSWatchDescriptor FSWatcher FilePath -- | Initializes a watcher. initFSWatcher :: IO FSWatcher initFSWatcher = do iN <- initINotify fmvar <- newMVar Map.empty return$ FSWatcher iN fmvar -- Replacement for splitFileName which returns "." instead of an empty folder. splitFileName' :: FilePath -> (FilePath,String) splitFileName' fp = let (d,f) = splitFileName fp in (if null d then "." else d,f) -- | Runs the callback IO action on modifications to the file at the given path. -- -- Each file can have only one callback IO action. Registering a new IO action -- discards any previously registered callback. -- -- The returned FSWatchDescriptor value can be used to stop watching the file. addWatch :: FSWatcher -> FilePath -> IO () -> IO FSWatchDescriptor addWatch piN@(FSWatcher iN fmvar) fp hdl = let (d,f) = splitFileName' fp in modifyMVar fmvar$ \fm -> case Map.lookup d fm of Nothing -> do wd <- I.addWatch iN [Modify, Move, Delete] d $ \e -> do case e of Ignored -> return () Deleted { filePath = f' } -> callHandler e d f' MovedIn { filePath = f' } -> callHandler e d f' Modified { maybeFilePath = Just f' } -> callHandler e d f' _ -> return () return ( Map.insert d (wd,Map.singleton f (const hdl)) fm , FSWatchDescriptor piN fp ) Just (wd,ffm) -> return ( Map.insert d (wd,Map.insert f (const hdl) ffm) fm , FSWatchDescriptor piN fp ) where callHandler e d f = do fm <- readMVar fmvar case Map.lookup d fm of Nothing -> return () Just (_,ffm) -> case Map.lookup f ffm of Nothing -> return () Just mhdl -> mhdl e -- | Stops watching the file associated to the given file descriptor. removeWatch :: FSWatchDescriptor -> IO () removeWatch (FSWatchDescriptor (FSWatcher _iN fmvar) fp) = let (d,f) = splitFileName' fp in modifyMVar_ fmvar$ \fm -> case Map.lookup d fm of Nothing -> error$ "removeWatchP: invalid handle for file "++fp Just (wd,ffm) -> let ffm' = Map.delete f ffm in if Map.null ffm' then I.removeWatch wd >> return (Map.delete d fm) else return (Map.insert d (wd,ffm') fm)
sheganinans/plugins-auto
System/Plugins/Auto/FileSystemWatcher.hs
bsd-3-clause
3,872
0
25
1,259
925
488
437
62
8
module Main where import Data.List import Data.Ord import Data.Char import Data.Maybe data Cell = Cell Int Int Int -- row, column, value -- solve solve :: [Cell] -> Maybe [Cell] solve xs = if length xs == 9*9 then Just xs else listToMaybe . catMaybes $ [solve (x:xs) | x <- (movesToConsider xs)] movesToConsider :: [Cell] -> [Cell] movesToConsider xs = filter moveIsOk (allMovesForCell row col) where (row, col) = findFirstEmptyCell xs moveIsOk x = not (any (cellsCollide x) xs) findFirstEmptyCell :: [Cell] -> (Int,Int) findFirstEmptyCell xs = case (find (not . samePos) (zip allCells (sortedCells xs))) of Just (a,b) -> a _ -> allCells !! (length xs) where allCells = [(x,y) | x <- [0..8], y <- [0..8]] :: [(Int,Int)] samePos ((r1,c1), (Cell r2 c2 _)) = r1 == r2 && c1 == c2 allMovesForCell :: Int -> Int -> [Cell] allMovesForCell row col = [Cell row col x | x <- [1..9]] cellsCollide :: Cell -> Cell -> Bool cellsCollide (Cell r1 c1 v1) (Cell r2 c2 v2) = (r1 == r2 && c1 == c2) || (v1 == v2 && (r1 == r2 || c1 == c2 || (zone r1 c1) == (zone r2 c2))) zone :: Int -> Int -> Int zone row col = 3*y + x where x = quot col 3 y = quot row 3 -- parse parseS :: String -> [Cell] parseS input = [Cell (indexToRow i) (indexToCol i) (digitToInt c) | (i,c) <- zip [0..81] chars, c /= '.'] where chars = concat (lines input) indexToRow index = quot index 9 indexToCol index = rem index 9 -- display sortedCells :: [Cell] -> [Cell] sortedCells = sortBy (comparing cellIndex) formatS :: Maybe [Cell] -> String formatS = (wrap 18) . concat . (map formatCell) . sortedCells . (fromMaybe []) formatCell :: Cell -> String formatCell (Cell _ _ value) = if value == 0 then ". " else (show value) ++ " " wrap :: Int -> String -> String wrap width [] = [] wrap width xs = line ++ "\n" ++ (wrap width rest) where (line, rest) = splitAt width xs cellIndex :: Cell -> Int cellIndex (Cell row col _) = row*9 + col -- main main = interact (formatS . solve . parseS)
hampus/sudoku
haskell/Main.hs
bsd-3-clause
2,078
0
13
514
985
522
463
47
2
{-# LANGUAGE RecordWildCards #-} module Dhall.LSP.Backend.Diagnostics ( DhallError , diagnose , Diagnosis(..) , explain , embedsWithRanges , offsetToPosition , Position , positionFromMegaparsec , positionToOffset , Range(..) , rangeFromDhall , subtractPosition ) where import Dhall.Core (Expr (Embed, Note), subExpressions) import Dhall.Parser (SourcedException (..), Src (..), unwrap) import Dhall.TypeCheck ( DetailedTypeError (..) , ErrorMessages (..) , TypeError (..) ) import Dhall.LSP.Backend.Dhall import Dhall.LSP.Backend.Parsing (getImportLink) import Dhall.LSP.Util import Control.Lens (toListOf) import Control.Monad.Trans.Writer (Writer, execWriter, tell) import Data.Text (Text) import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Text as Text import qualified Dhall.Pretty import qualified Dhall.TypeCheck as TypeCheck import qualified Prettyprinter.Render.Text as Pretty.Text import qualified Text.Megaparsec as Megaparsec -- | A (line, col) pair representing a position in a source file; 0-based. type Position = (Int, Int) -- | A source code range. data Range = Range {left, right :: Position} -- | A diagnosis, optionally tagged with a source code range. data Diagnosis = Diagnosis { -- | Where the diagnosis came from, e.g. Dhall.TypeCheck. doctor :: Text, range :: Maybe Range, -- ^ The range of code the diagnosis concerns diagnosis :: Text } -- | Give a short diagnosis for a given error that can be shown to the end user. diagnose :: DhallError -> [Diagnosis] diagnose (ErrorInternal e) = [Diagnosis { .. }] where doctor = "Dhall" range = Nothing diagnosis = "An internal error has occurred while trying to process the Dhall file: " <> tshow e diagnose (ErrorImportSourced (SourcedException src e)) = [Diagnosis { .. }] where doctor = "Dhall.Import" range = Just (rangeFromDhall src) diagnosis = tshow e diagnose (ErrorTypecheck (TypeError _ expr message)) = [Diagnosis { .. }] where doctor = "Dhall.TypeCheck" range = fmap rangeFromDhall (note expr) diagnosis = "Error: " <> Pretty.Text.renderStrict (Dhall.Pretty.layout short) ErrorMessages{..} = TypeCheck.prettyTypeMessage message diagnose (ErrorParse e) = [ Diagnosis { .. } | (diagnosis, range) <- zip diagnoses (map Just ranges) ] where doctor = "Dhall.Parser" errors = (NonEmpty.toList . Megaparsec.bundleErrors . unwrap) e diagnoses = map (Text.pack . Megaparsec.parseErrorTextPretty) errors positions = map (positionFromMegaparsec . snd) . fst $ Megaparsec.attachSourcePos Megaparsec.errorOffset errors (Megaparsec.bundlePosState (unwrap e)) texts = map parseErrorText errors ranges = [ rangeFromDhall (Src left' left' text) -- bit of a hack, but convenient. | (left, text) <- zip positions texts , let left' = positionToMegaparsec left ] {- Since Dhall doesn't use custom errors (corresponding to the FancyError ParseError constructor) we only need to handle the case of plain Megaparsec errors (i.e. TrivialError), and only those who actually include a list of tokens that we can compute the length of. -} parseErrorText :: Megaparsec.ParseError Text s -> Text parseErrorText (Megaparsec.TrivialError _ (Just (Megaparsec.Tokens text)) _) = Text.pack (NonEmpty.toList text) parseErrorText _ = "" -- | Give a detailed explanation for the given error; if no detailed explanation -- is available return @Nothing@ instead. explain :: DhallError -> Maybe Diagnosis explain (ErrorTypecheck e@(TypeError _ expr _)) = Just (Diagnosis { .. }) where doctor = "Dhall.TypeCheck" range = fmap rangeFromDhall (note expr) diagnosis = tshow (DetailedTypeError e) explain _ = Nothing -- only type errors have detailed explanations so far -- Given an annotated AST return the note at the top-most node. note :: Expr s a -> Maybe s note (Note s _) = Just s note _ = Nothing -- Megaparsec's positions are 1-based while ours are 0-based. positionFromMegaparsec :: Megaparsec.SourcePos -> Position positionFromMegaparsec (Megaparsec.SourcePos _ line col) = (Megaparsec.unPos line - 1, Megaparsec.unPos col - 1) -- Line and column numbers can't be negative. Clamps to 0 just in case. positionToMegaparsec :: Position -> Megaparsec.SourcePos positionToMegaparsec (line, col) = Megaparsec.SourcePos "" (Megaparsec.mkPos $ max 0 line + 1) (Megaparsec.mkPos $ max 0 col + 1) addRelativePosition :: Position -> Position -> Position addRelativePosition (x1, y1) (0, dy2) = (x1, y1 + dy2) addRelativePosition (x1, _) (dx2, y2) = (x1 + dx2, y2) -- | prop> addRelativePosition pos (subtractPosition pos pos') == pos' subtractPosition :: Position -> Position -> Position subtractPosition (x1, y1) (x2, y2) | x1 == x2 = (0, y2 - y1) | otherwise = (x2 - x1, y2) -- | Convert a source range from Dhalls @Src@ format. The returned range is -- "tight", that is, does not contain any trailing whitespace. rangeFromDhall :: Src -> Range rangeFromDhall (Src left _right text) = Range (x1,y1) (x2,y2) where (x1,y1) = positionFromMegaparsec left (dx2,dy2) = offsetToPosition text . Text.length $ Text.stripEnd text (x2,y2) = addRelativePosition (x1,y1) (dx2,dy2) -- Convert a (line,column) position into the corresponding character offset -- and back, such that the two are inverses of eachother. positionToOffset :: Text -> Position -> Int positionToOffset txt (line, col) = if line < length ls then Text.length . unlines' $ take line ls ++ [Text.take col (ls !! line)] else Text.length txt -- position lies outside txt where ls = NonEmpty.toList (lines' txt) offsetToPosition :: Text -> Int -> Position offsetToPosition txt off = (length ls - 1, Text.length (NonEmpty.last ls)) where ls = lines' (Text.take off txt) -- | Collect all `Embed` constructors (i.e. imports if the expression has type -- `Expr Src Import`) wrapped in a Note constructor and return them together -- with their associated range in the source code. embedsWithRanges :: Expr Src a -> [(Range, a)] embedsWithRanges = map (\(src, a) -> (rangeFromDhall . getImportLink $ src, a)) . execWriter . go where go :: Expr Src a -> Writer [(Src, a)] () go (Note src (Embed a)) = tell [(src, a)] go expr = mapM_ go (toListOf subExpressions expr)
Gabriel439/Haskell-Dhall-Library
dhall-lsp-server/src/Dhall/LSP/Backend/Diagnostics.hs
bsd-3-clause
6,598
0
14
1,440
1,677
936
741
115
2
{-# LANGUAGE OverloadedStrings, UnicodeSyntax #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes, TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-| Module : Reflex.Dom.HTML5.Elements.Tabular Description : HTML5 tabular elements Copyright : (c) gspia 2017 License : BSD Maintainer : gspia = Tabular This module contains table and its children elements: caption, colgroup, thead, tbody, tfoot, tr Moreover: td, th, col, row The naming convention follows that of Elements. -} module Reflex.Dom.HTML5.Elements.Tabular where import Data.Foldable (fold) import Data.Maybe (catMaybes, fromMaybe, maybeToList) import Data.Monoid ((<>)) import qualified Data.Text as T -- import Foreign.JavaScript.TH -- import Reflex.Dom.Main -- import Reflex.Dom.Builder.Immediate -- import Reflex.Dom.Core import Reflex.Dom.Core (DomBuilder, Element, EventResult, Dynamic, PostBuild, DomBuilderSpace, elAttr', elDynAttr', el') import qualified Reflex.Dom.HTML5.Attrs as A ------------------------------------------------------------------------------ -- | Caption-element has only Global attributes. data Caption = Caption { _captionGlobals ∷ Maybe A.Globals , _captionCustom ∷ Maybe A.Attr } -- | Caption has 'A.AttrMap' instance. instance A.AttrMap Caption where attrMap bm = fold $ catMaybes [ A.attrMap <$> _captionGlobals bm ] <> maybeToList (_captionCustom bm) -- | Default value for Caption has no attributes set (no globals nor custom). defCaption ∷ Caption defCaption = Caption Nothing Nothing -- | An instance.. instance Semigroup Caption where (<>) (Caption a1 a2) (Caption b1 b2) = Caption (a1 <> b1) (a2 <> b2) -- | Caption is a monoid (attributes can be appended). instance Monoid Caption where mempty = defCaption mappend = (<>) -- | An instance. instance A.AttrHasGlobals Caption where attrSetGlobals pp bm = bm { _captionGlobals = Just pp } -- Global A.attributes require the following instances. -- | An instance. instance A.AttrHasAccessKey Caption where attrSetAccessKey pp g = g { _captionGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasAnmval Caption where attrSetAnmval pp g = g { _captionGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasContentEditable Caption where attrSetContentEditable pp g = g { _captionGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasContextMenu Caption where attrSetContextMenu pp g = g { _captionGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasClass Caption where attrSetClassName pp g = g { _captionGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasDnmval Caption where attrSetDnmval pp g = g { _captionGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasDir Caption where attrSetDir pp g = g { _captionGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasDraggable Caption where attrSetDraggable pp g = g { _captionGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasHidden Caption where attrSetHidden pp g = g { _captionGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasId Caption where attrSetId pp g = g { _captionGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasLang Caption where attrSetLang pp g = g { _captionGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasRole Caption where attrSetRole pp g = g { _captionGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasSlot Caption where attrSetSlot pp g = g { _captionGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasSpellCheck Caption where attrSetSpellCheck pp g = g { _captionGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasStyle Caption where attrSetStyle pp g = g { _captionGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasTabIndex Caption where attrSetTabIndex pp g = g { _captionGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasTitle Caption where attrSetTitle pp g = g { _captionGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrHasTranslate Caption where attrSetTranslate pp g = g { _captionGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_captionGlobals g))) } -- | An instance. instance A.AttrGetClassName Caption where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_captionGlobals g) -- | An instance. instance A.AttrHasCustom Caption where attrSetCustom pp g = g { _captionCustom = Just pp } -- | A short-hand notion for @ elAttr\' \"caption\" ... @ caption' ∷ forall t m a. (DomBuilder t m) ⇒ Caption → m a → m (Element EventResult (DomBuilderSpace m) t, a) caption' bm = elAttr' "caption" (A.attrMap bm) -- | A short-hand notion for @ elAttr \"caption\" ... @ caption ∷ forall t m a. (DomBuilder t m) ⇒ Caption → m a → m a caption bm children = snd <$> caption' bm children -- | A short-hand notion for @ el\' \"caption\" ... @ captionN' ∷ forall t m a. (DomBuilder t m) ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a) captionN' = el' "caption" -- | A short-hand notion for @ el \"caption\" ... @ captionN ∷ forall t m a. (DomBuilder t m) ⇒ m a → m a captionN children = snd <$> captionN' children -- | A short-hand notion for @ elDynAttr\' \"caption\" ... @ captionD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Caption → m a → m (Element EventResult (DomBuilderSpace m) t, a) captionD' bm = elDynAttr' "caption" (A.attrMap <$> bm) -- | A short-hand notion for @ elDynAttr \"caption\" ... @ captionD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Caption → m a → m a captionD bm children = snd <$> captionD' bm children ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Col-element data Col = Col { _colGlobals ∷ Maybe A.Globals , _colSpan ∷ Maybe A.Span , _colCustom ∷ Maybe A.Attr } -- | Col has 'A.AttrMap' instance. instance A.AttrMap Col where attrMap bm = fold $ catMaybes [ A.attrMap <$> _colGlobals bm , A.attrMap <$> _colSpan bm ] <> maybeToList (_colCustom bm) -- | Default value for Col has no attributes set (no globals nor custom) -- nor a 'Span'. defCol ∷ Col defCol = Col Nothing Nothing Nothing -- | An instance. instance Semigroup Col where (<>) (Col a1 a2 a3) (Col b1 b2 b3) = Col (a1 <> b1) (a2 <> b2) (a3 <> b3) -- | An instance. instance Monoid Col where mempty = defCol mappend = (<>) -- | An instance. instance A.AttrHasGlobals Col where attrSetGlobals pp bm = bm { _colGlobals = Just pp } -- Global A.attributes require the following instances. -- | An instance. instance A.AttrHasAccessKey Col where attrSetAccessKey pp g = g { _colGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasAnmval Col where attrSetAnmval pp g = g { _colGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasContentEditable Col where attrSetContentEditable pp g = g { _colGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasContextMenu Col where attrSetContextMenu pp g = g { _colGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasClass Col where attrSetClassName pp g = g { _colGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasDnmval Col where attrSetDnmval pp g = g { _colGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasDir Col where attrSetDir pp g = g { _colGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasDraggable Col where attrSetDraggable pp g = g { _colGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasHidden Col where attrSetHidden pp g = g { _colGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasId Col where attrSetId pp g = g { _colGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasLang Col where attrSetLang pp g = g { _colGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasRole Col where attrSetRole pp g = g { _colGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasSlot Col where attrSetSlot pp g = g { _colGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasSpellCheck Col where attrSetSpellCheck pp g = g { _colGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasStyle Col where attrSetStyle pp g = g { _colGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasTabIndex Col where attrSetTabIndex pp g = g { _colGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasTitle Col where attrSetTitle pp g = g { _colGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrHasTranslate Col where attrSetTranslate pp g = g { _colGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_colGlobals g))) } -- | An instance. instance A.AttrGetClassName Col where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_colGlobals g) -- | An instance. instance A.AttrHasSpan Col where attrSetSpan pp g = g { _colSpan = Just pp } -- | An instance. instance A.AttrHasCustom Col where attrSetCustom pp g = g { _colCustom = Just pp } -- | A short-hand notion for @ elAttr\' \"col\" ... @ col' ∷ forall t m a. DomBuilder t m ⇒ Col → m a → m (Element EventResult (DomBuilderSpace m) t, a) col' bm = elAttr' "col" (A.attrMap bm) -- | A short-hand notion for @ elAttr \"col\" ... @ col ∷ forall t m a. DomBuilder t m ⇒ Col → m a → m a col bm children = snd <$> col' bm children -- | A short-hand notion for @ el\' \"col\" ... @ colN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a) colN' = el' "col" -- | A short-hand notion for @ el \"col\" ... @ colN ∷ forall t m a. DomBuilder t m ⇒ m a → m a colN children = snd <$> colN' children -- | A short-hand notion for @ elDynAttr\' \"col\" ... @ colD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Col → m a → m (Element EventResult (DomBuilderSpace m) t, a) colD' bm = elDynAttr' "col" (A.attrMap <$> bm) -- | A short-hand notion for @ elDynAttr \"col\" ... @ colD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Col → m a → m a colD bm children = snd <$> colD' bm children ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | ColGroup-element data ColGroup = ColGroup { _colGroupGlobals ∷ Maybe A.Globals , _colGroupSpan ∷ Maybe A.Span , _colGroupCustom ∷ Maybe A.Attr } -- | ColGroup has 'A.AttrMap' instance. instance A.AttrMap ColGroup where attrMap bm = fold $ catMaybes [ A.attrMap <$> _colGroupGlobals bm , A.attrMap <$> _colGroupSpan bm ] <> maybeToList (_colGroupCustom bm) -- | Default value for ColGroup has no attributes set (no globals nor custom) -- nor a 'Span'. defColGroup ∷ ColGroup defColGroup = ColGroup Nothing Nothing Nothing -- | An instance. instance Semigroup ColGroup where (<>) (ColGroup a1 a2 a3) (ColGroup b1 b2 b3) = ColGroup (a1 <> b1) (a2 <> b2) (a3 <> b3) -- | An instance. instance Monoid ColGroup where mempty = defColGroup mappend = (<>) -- | An instance. instance A.AttrHasGlobals ColGroup where attrSetGlobals pp bm = bm { _colGroupGlobals = Just pp } -- Global A.attributes require the following instances. -- | An instance. instance A.AttrHasAccessKey ColGroup where attrSetAccessKey pp g = g { _colGroupGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasAnmval ColGroup where attrSetAnmval pp g = g { _colGroupGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasContentEditable ColGroup where attrSetContentEditable pp g = g { _colGroupGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasContextMenu ColGroup where attrSetContextMenu pp g = g { _colGroupGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasClass ColGroup where attrSetClassName pp g = g { _colGroupGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasDnmval ColGroup where attrSetDnmval pp g = g { _colGroupGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasDir ColGroup where attrSetDir pp g = g { _colGroupGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasDraggable ColGroup where attrSetDraggable pp g = g { _colGroupGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasHidden ColGroup where attrSetHidden pp g = g { _colGroupGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasId ColGroup where attrSetId pp g = g { _colGroupGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasLang ColGroup where attrSetLang pp g = g { _colGroupGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasRole ColGroup where attrSetRole pp g = g { _colGroupGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasSlot ColGroup where attrSetSlot pp g = g { _colGroupGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasSpellCheck ColGroup where attrSetSpellCheck pp g = g { _colGroupGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasStyle ColGroup where attrSetStyle pp g = g { _colGroupGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasTabIndex ColGroup where attrSetTabIndex pp g = g { _colGroupGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasTitle ColGroup where attrSetTitle pp g = g { _colGroupGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrHasTranslate ColGroup where attrSetTranslate pp g = g { _colGroupGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_colGroupGlobals g))) } -- | An instance. instance A.AttrGetClassName ColGroup where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_colGroupGlobals g) -- | An instance. instance A.AttrHasSpan ColGroup where attrSetSpan pp g = g { _colGroupSpan = Just pp } -- | An instance. instance A.AttrHasCustom ColGroup where attrSetCustom pp g = g { _colGroupCustom = Just pp } -- | A short-hand notion for @ elAttr\' \"colgroup\" ... @ colGroup' ∷ forall t m a. DomBuilder t m ⇒ ColGroup → m a → m (Element EventResult (DomBuilderSpace m) t, a) colGroup' bm = elAttr' "colgroup" (A.attrMap bm) -- | A short-hand notion for @ elAttr \"colgroup\" ... @ colGroup ∷ forall t m a. DomBuilder t m ⇒ ColGroup → m a → m a colGroup bm children = snd <$> colGroup' bm children -- | A short-hand notion for @ el\' \"colgroup\" ... @ colGroupN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a) colGroupN' = el' "colgroup" -- | A short-hand notion for @ el \"colgroup\" ... @ colGroupN ∷ forall t m a. DomBuilder t m ⇒ m a → m a colGroupN children = snd <$> colGroupN' children -- | A short-hand notion for @ elDynAttr\' \"colgroup\" ... @ colGroupD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t ColGroup → m a → m (Element EventResult (DomBuilderSpace m) t, a) colGroupD' bm = elDynAttr' "colgroup" (A.attrMap <$> bm) -- | A short-hand notion for @ elDynAttr \"colgroup\" ... @ colGroupD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t ColGroup → m a → m a colGroupD bm children = snd <$> colGroupD' bm children ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Table-element -- A.Attribute border has been marked as obsolete in HTML 5.3. data Table = Table { _tableGlobals ∷ Maybe A.Globals -- , _tableBorder ∷ Maybe A.Border , _tableCustom ∷ Maybe A.Attr } -- | Table has 'A.AttrMap' instance. instance A.AttrMap Table where attrMap bm = fold $ catMaybes [ A.attrMap <$> _tableGlobals bm -- , A.attrMap <$> _tableBorder bm ] <> maybeToList (_tableCustom bm) -- | Default value for Table has no attributes set (no globals nor custom). defTable ∷ Table defTable = Table Nothing Nothing -- | An instance. instance Semigroup Table where (<>) (Table a1 a2) (Table b1 b2) = Table (a1 <> b1) (a2 <> b2) -- | An instance. instance Monoid Table where mempty = defTable mappend = (<>) -- | An instance. instance A.AttrHasGlobals Table where attrSetGlobals pp bm = bm { _tableGlobals = Just pp } -- Global A.attributes require the following instances. -- | An instance. instance A.AttrHasAccessKey Table where attrSetAccessKey pp g = g { _tableGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasAnmval Table where attrSetAnmval pp g = g { _tableGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasContentEditable Table where attrSetContentEditable pp g = g { _tableGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasContextMenu Table where attrSetContextMenu pp g = g { _tableGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasClass Table where attrSetClassName pp g = g { _tableGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasDnmval Table where attrSetDnmval pp g = g { _tableGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasDir Table where attrSetDir pp g = g { _tableGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasDraggable Table where attrSetDraggable pp g = g { _tableGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasHidden Table where attrSetHidden pp g = g { _tableGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasId Table where attrSetId pp g = g { _tableGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasLang Table where attrSetLang pp g = g { _tableGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasRole Table where attrSetRole pp g = g { _tableGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasSlot Table where attrSetSlot pp g = g { _tableGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasSpellCheck Table where attrSetSpellCheck pp g = g { _tableGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasStyle Table where attrSetStyle pp g = g { _tableGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasTabIndex Table where attrSetTabIndex pp g = g { _tableGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasTitle Table where attrSetTitle pp g = g { _tableGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrHasTranslate Table where attrSetTranslate pp g = g { _tableGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_tableGlobals g))) } -- | An instance. instance A.AttrGetClassName Table where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_tableGlobals g) -- instance A.AttrHasBorder Table where attrSetBorder pp g = g { _tableBorder = Just pp } -- | An instance. instance A.AttrHasCustom Table where attrSetCustom pp g = g { _tableCustom = Just pp } -- | A short-hand notion for @ elAttr\' \"table\" ... @ table' ∷ forall t m a. DomBuilder t m ⇒ Table → m a → m (Element EventResult (DomBuilderSpace m) t, a) table' bm = elAttr' "table" (A.attrMap bm) -- | A short-hand notion for @ elAttr \"table\" ... @ table ∷ forall t m a. DomBuilder t m ⇒ Table → m a → m a table bm children = snd <$> table' bm children -- | A short-hand notion for @ el\' \"table\" ... @ tableN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a) tableN' = el' "table" -- | A short-hand notion for @ el \"table\" ... @ tableN ∷ forall t m a. DomBuilder t m ⇒ m a → m a tableN children = snd <$> tableN' children -- | A short-hand notion for @ elDynAttr\' \"table\" ... @ tableD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Table → m a → m (Element EventResult (DomBuilderSpace m) t, a) tableD' bm = elDynAttr' "table" (A.attrMap <$> bm) -- | A short-hand notion for @ elDynAttr \"table\" ... @ tableD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Table → m a → m a tableD bm children = snd <$> tableD' bm children ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Thead-element has only Global attributes. data Thead = Thead { _theadGlobals ∷ Maybe A.Globals , _theadCustom ∷ Maybe A.Attr } -- | Thead has 'A.AttrMap' instance. instance A.AttrMap Thead where attrMap bm = fold $ catMaybes [ A.attrMap <$> _theadGlobals bm ] <> maybeToList (_theadCustom bm) -- | Default value for Thead has no attributes set (no globals nor custom). defThead ∷ Thead defThead = Thead Nothing Nothing -- | An instance. instance Semigroup Thead where (<>) (Thead a1 a2) (Thead b1 b2) = Thead (a1 <> b1) (a2 <> b2) -- | An instance. instance Monoid Thead where mempty = defThead mappend = (<>) -- | An instance. instance A.AttrHasGlobals Thead where attrSetGlobals pp bm = bm { _theadGlobals = Just pp } -- Global A.attributes require the following instances. -- | An instance. instance A.AttrHasAccessKey Thead where attrSetAccessKey pp g = g { _theadGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasAnmval Thead where attrSetAnmval pp g = g { _theadGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasContentEditable Thead where attrSetContentEditable pp g = g { _theadGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasContextMenu Thead where attrSetContextMenu pp g = g { _theadGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasClass Thead where attrSetClassName pp g = g { _theadGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasDnmval Thead where attrSetDnmval pp g = g { _theadGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasDir Thead where attrSetDir pp g = g { _theadGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasDraggable Thead where attrSetDraggable pp g = g { _theadGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasHidden Thead where attrSetHidden pp g = g { _theadGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasId Thead where attrSetId pp g = g { _theadGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasLang Thead where attrSetLang pp g = g { _theadGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasRole Thead where attrSetRole pp g = g { _theadGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasSlot Thead where attrSetSlot pp g = g { _theadGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasSpellCheck Thead where attrSetSpellCheck pp g = g { _theadGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasStyle Thead where attrSetStyle pp g = g { _theadGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasTabIndex Thead where attrSetTabIndex pp g = g { _theadGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasTitle Thead where attrSetTitle pp g = g { _theadGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrHasTranslate Thead where attrSetTranslate pp g = g { _theadGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_theadGlobals g))) } -- | An instance. instance A.AttrGetClassName Thead where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_theadGlobals g) -- | An instance. instance A.AttrHasCustom Thead where attrSetCustom pp g = g { _theadCustom = Just pp } -- | A short-hand notion for @ elAttr\' \"thead\" ... @ thead' ∷ forall t m a. DomBuilder t m ⇒ Thead → m a → m (Element EventResult (DomBuilderSpace m) t, a) thead' bm = elAttr' "thead" (A.attrMap bm) -- | A short-hand notion for @ elAttr \"thead\" ... @ thead ∷ forall t m a. DomBuilder t m ⇒ Thead → m a → m a thead bm children = snd <$> thead' bm children -- | A short-hand notion for @ el\' \"thead\" ... @ theadN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a) theadN' = el' "thead" -- | A short-hand notion for @ el \"thead\" ... @ theadN ∷ forall t m a. DomBuilder t m ⇒ m a → m a theadN children = snd <$> theadN' children -- | A short-hand notion for @ elDynAttr\' \"thead\" ... @ theadD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Thead → m a → m (Element EventResult (DomBuilderSpace m) t, a) theadD' bm = elDynAttr' "thead" (A.attrMap <$> bm) -- | A short-hand notion for @ elDynAttr \"thead\" ... @ theadD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Thead → m a → m a theadD bm children = snd <$> theadD' bm children ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Tbody-element has only Global attributes. data Tbody = Tbody { _tbodyGlobals ∷ Maybe A.Globals , _tbodyCustom ∷ Maybe A.Attr } -- | Tbody has 'A.AttrMap' instance. instance A.AttrMap Tbody where attrMap bm = fold $ catMaybes [ A.attrMap <$> _tbodyGlobals bm ] <> maybeToList (_tbodyCustom bm) -- | Default value for Tbody has no attributes set (no globals nor custom). defTbody ∷ Tbody defTbody = Tbody Nothing Nothing -- | An instance. instance Semigroup Tbody where (<>) (Tbody a1 a2) (Tbody b1 b2) = Tbody (a1 <> b1) (a2 <> b2) -- | An instance. instance Monoid Tbody where mempty = defTbody mappend = (<>) -- | An instance. instance A.AttrHasGlobals Tbody where attrSetGlobals pp bm = bm { _tbodyGlobals = Just pp } -- Global A.attributes require the following instances. -- | An instance. instance A.AttrHasAccessKey Tbody where attrSetAccessKey pp g = g { _tbodyGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasAnmval Tbody where attrSetAnmval pp g = g { _tbodyGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasContentEditable Tbody where attrSetContentEditable pp g = g { _tbodyGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasContextMenu Tbody where attrSetContextMenu pp g = g { _tbodyGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasClass Tbody where attrSetClassName pp g = g { _tbodyGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasDnmval Tbody where attrSetDnmval pp g = g { _tbodyGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasDir Tbody where attrSetDir pp g = g { _tbodyGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasDraggable Tbody where attrSetDraggable pp g = g { _tbodyGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasHidden Tbody where attrSetHidden pp g = g { _tbodyGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasId Tbody where attrSetId pp g = g { _tbodyGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasLang Tbody where attrSetLang pp g = g { _tbodyGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasRole Tbody where attrSetRole pp g = g { _tbodyGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasSlot Tbody where attrSetSlot pp g = g { _tbodyGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasSpellCheck Tbody where attrSetSpellCheck pp g = g { _tbodyGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasStyle Tbody where attrSetStyle pp g = g { _tbodyGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasTabIndex Tbody where attrSetTabIndex pp g = g { _tbodyGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasTitle Tbody where attrSetTitle pp g = g { _tbodyGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrHasTranslate Tbody where attrSetTranslate pp g = g { _tbodyGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_tbodyGlobals g))) } -- | An instance. instance A.AttrGetClassName Tbody where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_tbodyGlobals g) -- | An instance. instance A.AttrHasCustom Tbody where attrSetCustom pp g = g { _tbodyCustom = Just pp } -- | A short-hand notion for @ elAttr\' \"tbody\" ... @ tbody' ∷ forall t m a. DomBuilder t m ⇒ Tbody → m a → m (Element EventResult (DomBuilderSpace m) t, a) tbody' bm = elAttr' "tbody" (A.attrMap bm) -- | A short-hand notion for @ elAttr \"tbody\" ... @ tbody ∷ forall t m a. DomBuilder t m ⇒ Tbody → m a → m a tbody bm children = snd <$> tbody' bm children -- | A short-hand notion for @ el\' \"tbody\" ... @ tbodyN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a) tbodyN' = el' "tbody" -- | A short-hand notion for @ el \"tbody\" ... @ tbodyN ∷ forall t m a. DomBuilder t m ⇒ m a → m a tbodyN children = snd <$> tbodyN' children -- | A short-hand notion for @ elDynAttr\' \"tbody\" ... @ tbodyD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Tbody → m a → m (Element EventResult (DomBuilderSpace m) t, a) tbodyD' bm = elDynAttr' "tbody" (A.attrMap <$> bm) -- | A short-hand notion for @ elDynAttr \"tbody\" ... @ tbodyD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Tbody → m a → m a tbodyD bm children = snd <$> tbodyD' bm children ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Tfoot-element has only Global attributes. data Tfoot = Tfoot { _tfootGlobals ∷ Maybe A.Globals , _tfootCustom ∷ Maybe A.Attr } -- | Tfoot has 'A.AttrMap' instance. instance A.AttrMap Tfoot where attrMap bm = fold $ catMaybes [ A.attrMap <$> _tfootGlobals bm ] <> maybeToList (_tfootCustom bm) -- | Default value for Tfoot has no attributes set (no globals nor custom). defTfoot ∷ Tfoot defTfoot = Tfoot Nothing Nothing -- | An instance. instance Semigroup Tfoot where (<>) (Tfoot a1 a2) (Tfoot b1 b2) = Tfoot (a1 <> b1) (a2 <> b2) -- | An instance. instance Monoid Tfoot where mempty = defTfoot mappend = (<>) -- | An instance. instance A.AttrHasGlobals Tfoot where attrSetGlobals pp bm = bm { _tfootGlobals = Just pp } -- Global A.attributes require the following instances. -- | An instance. instance A.AttrHasAccessKey Tfoot where attrSetAccessKey pp g = g { _tfootGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasAnmval Tfoot where attrSetAnmval pp g = g { _tfootGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasContentEditable Tfoot where attrSetContentEditable pp g = g { _tfootGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasContextMenu Tfoot where attrSetContextMenu pp g = g { _tfootGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasClass Tfoot where attrSetClassName pp g = g { _tfootGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasDnmval Tfoot where attrSetDnmval pp g = g { _tfootGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasDir Tfoot where attrSetDir pp g = g { _tfootGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasDraggable Tfoot where attrSetDraggable pp g = g { _tfootGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasHidden Tfoot where attrSetHidden pp g = g { _tfootGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasId Tfoot where attrSetId pp g = g { _tfootGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasLang Tfoot where attrSetLang pp g = g { _tfootGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasRole Tfoot where attrSetRole pp g = g { _tfootGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasSlot Tfoot where attrSetSlot pp g = g { _tfootGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasSpellCheck Tfoot where attrSetSpellCheck pp g = g { _tfootGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasStyle Tfoot where attrSetStyle pp g = g { _tfootGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasTabIndex Tfoot where attrSetTabIndex pp g = g { _tfootGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasTitle Tfoot where attrSetTitle pp g = g { _tfootGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrHasTranslate Tfoot where attrSetTranslate pp g = g { _tfootGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_tfootGlobals g))) } -- | An instance. instance A.AttrGetClassName Tfoot where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_tfootGlobals g) -- | An instance. instance A.AttrHasCustom Tfoot where attrSetCustom pp g = g { _tfootCustom = Just pp } -- | A short-hand notion for @ elAttr\' \"tfoot\" ... @ tfoot' ∷ forall t m a. DomBuilder t m ⇒ Tfoot → m a → m (Element EventResult (DomBuilderSpace m) t, a) tfoot' bm = elAttr' "tfoot" (A.attrMap bm) -- | A short-hand notion for @ elAttr \"tfoot\" ... @ tfoot ∷ forall t m a. DomBuilder t m ⇒ Tfoot → m a → m a tfoot bm children = snd <$> tfoot' bm children -- | A short-hand notion for @ el\' \"tfoot\" ... @ tfootN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a) tfootN' = el' "tfoot" -- | A short-hand notion for @ el \"tfoot\" ... @ tfootN ∷ forall t m a. DomBuilder t m ⇒ m a → m a tfootN children = snd <$> tfootN' children -- | A short-hand notion for @ elDynAttr\' \"tfoot\" ... @ tfootD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Tfoot → m a → m (Element EventResult (DomBuilderSpace m) t, a) tfootD' bm = elDynAttr' "tfoot" (A.attrMap <$> bm) -- | A short-hand notion for @ elDynAttr \"tfoot\" ... @ tfootD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Tfoot → m a → m a tfootD bm children = snd <$> tfootD' bm children ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Th-element data Th = Th { _thGlobals ∷ Maybe A.Globals , _thAbbr ∷ Maybe A.Abbr , _thColSpan ∷ Maybe A.ColSpan , _thHeaders ∷ Maybe A.Headers , _thRowSpan ∷ Maybe A.RowSpan , _thScope ∷ Maybe A.Scope , _thCustom ∷ Maybe A.Attr } -- | Th has 'A.AttrMap' instance. instance A.AttrMap Th where attrMap bm = fold $ catMaybes [ A.attrMap <$> _thGlobals bm , A.attrMap <$> _thAbbr bm , A.attrMap <$> _thColSpan bm , A.attrMap <$> _thHeaders bm , A.attrMap <$> _thRowSpan bm , A.attrMap <$> _thScope bm ] <> maybeToList (_thCustom bm) -- | Default value for Th has no attributes set (no globals nor other). defTh ∷ Th defTh = Th Nothing Nothing Nothing Nothing Nothing Nothing Nothing -- | An instance. instance Semigroup Th where (<>) (Th a1 a2 a3 a4 a5 a6 a7) (Th b1 b2 b3 b4 b5 b6 b7) = Th (a1 <> b1) (a2 <> b2) (a3 <> b3) (a4 <> b4) (a5 <> b5) (a6 <> b6) (a7 <> b7) -- | An instance. instance Monoid Th where mempty = defTh mappend = (<>) -- | An instance. instance A.AttrHasGlobals Th where attrSetGlobals pp bm = bm { _thGlobals = Just pp } -- Global A.attributes require the following instances. -- | An instance. instance A.AttrHasAccessKey Th where attrSetAccessKey pp g = g { _thGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasAnmval Th where attrSetAnmval pp g = g { _thGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasContentEditable Th where attrSetContentEditable pp g = g { _thGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasContextMenu Th where attrSetContextMenu pp g = g { _thGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasClass Th where attrSetClassName pp g = g { _thGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasDnmval Th where attrSetDnmval pp g = g { _thGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasDir Th where attrSetDir pp g = g { _thGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasDraggable Th where attrSetDraggable pp g = g { _thGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasHidden Th where attrSetHidden pp g = g { _thGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasId Th where attrSetId pp g = g { _thGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasLang Th where attrSetLang pp g = g { _thGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasRole Th where attrSetRole pp g = g { _thGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasSlot Th where attrSetSlot pp g = g { _thGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasSpellCheck Th where attrSetSpellCheck pp g = g { _thGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasStyle Th where attrSetStyle pp g = g { _thGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasTabIndex Th where attrSetTabIndex pp g = g { _thGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasTitle Th where attrSetTitle pp g = g { _thGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrHasTranslate Th where attrSetTranslate pp g = g { _thGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_thGlobals g))) } -- | An instance. instance A.AttrGetClassName Th where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_thGlobals g) -- | An instance. instance A.AttrHasAbbr Th where attrSetAbbr pp g = g { _thAbbr = Just pp } -- | An instance. instance A.AttrHasColSpan Th where attrSetColSpan pp g = g { _thColSpan = Just pp } -- | An instance. instance A.AttrHasHeaders Th where attrSetHeaders pp g = g { _thHeaders = Just pp } -- | An instance. instance A.AttrHasRowSpan Th where attrSetRowSpan pp g = g { _thRowSpan = Just pp } -- | An instance. instance A.AttrHasScope Th where attrSetScope pp g = g { _thScope = Just pp } -- | An instance. instance A.AttrHasCustom Th where attrSetCustom pp g = g { _thCustom = Just pp } -- | A short-hand notion for @ elAttr\' \"th\" ... @ th' ∷ forall t m a. DomBuilder t m ⇒ Th → m a → m (Element EventResult (DomBuilderSpace m) t, a) th' bm = elAttr' "th" (A.attrMap bm) -- | A short-hand notion for @ elAttr \"th\" ... @ th ∷ forall t m a. DomBuilder t m ⇒ Th → m a → m a th bm children = snd <$> th' bm children -- | A short-hand notion for @ el\' \"th\" ... @ thN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a) thN' = el' "th" -- | A short-hand notion for @ el \"th\" ... @ thN ∷ forall t m a. DomBuilder t m ⇒ m a → m a thN children = snd <$> thN' children -- | A short-hand notion for @ elDynAttr\' \"th\" ... @ thD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Th → m a → m (Element EventResult (DomBuilderSpace m) t, a) thD' bm = elDynAttr' "th" (A.attrMap <$> bm) -- | A short-hand notion for @ elDynAttr \"th\" ... @ thD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Th → m a → m a thD bm children = snd <$> thD' bm children ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Td-element data Td = Td { _tdGlobals ∷ Maybe A.Globals , _tdColSpan ∷ Maybe A.ColSpan , _tdHeaders ∷ Maybe A.Headers , _tdRowSpan ∷ Maybe A.RowSpan , _tdCustom ∷ Maybe A.Attr } -- | Td has 'A.AttrMap' instance. instance A.AttrMap Td where attrMap bm = fold $ catMaybes [ A.attrMap <$> _tdGlobals bm , A.attrMap <$> _tdColSpan bm , A.attrMap <$> _tdHeaders bm , A.attrMap <$> _tdRowSpan bm ] <> maybeToList (_tdCustom bm) -- | Default value for Td has no attributes set (no globals nor other). defTd ∷ Td defTd = Td Nothing Nothing Nothing Nothing Nothing -- | An instance. instance Semigroup Td where (<>) (Td a1 a2 a3 a4 a5) (Td b1 b2 b3 b4 b5) = Td (a1 <> b1) (a2 <> b2) (a3 <> b3) (a4 <> b4) (a5 <> b5) -- | An instance. instance Monoid Td where mempty = defTd mappend = (<>) -- | An instance. instance A.AttrHasGlobals Td where attrSetGlobals pp bm = bm { _tdGlobals = Just pp } -- Global A.attributes require the following instances. -- | An instance. instance A.AttrHasAccessKey Td where attrSetAccessKey pp g = g { _tdGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasAnmval Td where attrSetAnmval pp g = g { _tdGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasContentEditable Td where attrSetContentEditable pp g = g { _tdGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasContextMenu Td where attrSetContextMenu pp g = g { _tdGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasClass Td where attrSetClassName pp g = g { _tdGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasDnmval Td where attrSetDnmval pp g = g { _tdGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasDir Td where attrSetDir pp g = g { _tdGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasDraggable Td where attrSetDraggable pp g = g { _tdGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasHidden Td where attrSetHidden pp g = g { _tdGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasId Td where attrSetId pp g = g { _tdGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasLang Td where attrSetLang pp g = g { _tdGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasRole Td where attrSetRole pp g = g { _tdGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasSlot Td where attrSetSlot pp g = g { _tdGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasSpellCheck Td where attrSetSpellCheck pp g = g { _tdGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasStyle Td where attrSetStyle pp g = g { _tdGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasTabIndex Td where attrSetTabIndex pp g = g { _tdGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasTitle Td where attrSetTitle pp g = g { _tdGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrHasTranslate Td where attrSetTranslate pp g = g { _tdGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_tdGlobals g))) } -- | An instance. instance A.AttrGetClassName Td where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_tdGlobals g) -- | An instance. instance A.AttrHasColSpan Td where attrSetColSpan pp g = g { _tdColSpan = Just pp } -- | An instance. instance A.AttrHasHeaders Td where attrSetHeaders pp g = g { _tdHeaders = Just pp } -- | An instance. instance A.AttrHasRowSpan Td where attrSetRowSpan pp g = g { _tdRowSpan = Just pp } -- | An instance. instance A.AttrHasCustom Td where attrSetCustom pp g = g { _tdCustom = Just pp } -- | A short-hand notion for @ elAttr\' \"td\" ... @ td' ∷ forall t m a. DomBuilder t m ⇒ Td → m a → m (Element EventResult (DomBuilderSpace m) t, a) td' bm = elAttr' "td" (A.attrMap bm) -- | A short-hand notion for @ elAttr \"td\" ... @ td ∷ forall t m a. DomBuilder t m ⇒ Td → m a → m a td bm children = snd <$> td' bm children -- | A short-hand notion for @ el\' \"td\" ... @ tdN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a) tdN' = el' "td" -- | A short-hand notion for @ el \"td\" ... @ tdN ∷ forall t m a. DomBuilder t m ⇒ m a → m a tdN children = snd <$> tdN' children -- | A short-hand notion for @ elDynAttr\' \"td\" ... @ tdD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Td → m a → m (Element EventResult (DomBuilderSpace m) t, a) tdD' bm = elDynAttr' "td" (A.attrMap <$> bm) -- | A short-hand notion for @ elDynAttr \"td\" ... @ tdD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Td → m a → m a tdD bm children = snd <$> tdD' bm children ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Tr-element has only Global attributes. data Tr = Tr { _trGlobals ∷ Maybe A.Globals , _trCustom ∷ Maybe A.Attr } -- | Tr has 'A.AttrMap' instance. instance A.AttrMap Tr where attrMap bm = fold $ catMaybes [ A.attrMap <$> _trGlobals bm ] <> maybeToList (_trCustom bm) -- | Default value for Tr has no attributes set (no globals nor other). defTr ∷ Tr defTr = Tr Nothing Nothing -- | An instance. instance Semigroup Tr where (<>) (Tr a1 a2) (Tr b1 b2) = Tr (a1 <> b1) (a2 <> b2) -- | An instance. instance Monoid Tr where mempty = defTr mappend = (<>) -- | An instance. instance A.AttrHasGlobals Tr where attrSetGlobals pp bm = bm { _trGlobals = Just pp } -- Global A.attributes require the following instances. -- | An instance. instance A.AttrHasAccessKey Tr where attrSetAccessKey pp g = g { _trGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasAnmval Tr where attrSetAnmval pp g = g { _trGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasContentEditable Tr where attrSetContentEditable pp g = g { _trGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasContextMenu Tr where attrSetContextMenu pp g = g { _trGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasClass Tr where attrSetClassName pp g = g { _trGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasDnmval Tr where attrSetDnmval pp g = g { _trGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasDir Tr where attrSetDir pp g = g { _trGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasDraggable Tr where attrSetDraggable pp g = g { _trGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasHidden Tr where attrSetHidden pp g = g { _trGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasId Tr where attrSetId pp g = g { _trGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasLang Tr where attrSetLang pp g = g { _trGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasRole Tr where attrSetRole pp g = g { _trGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasSlot Tr where attrSetSlot pp g = g { _trGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasSpellCheck Tr where attrSetSpellCheck pp g = g { _trGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasStyle Tr where attrSetStyle pp g = g { _trGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasTabIndex Tr where attrSetTabIndex pp g = g { _trGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasTitle Tr where attrSetTitle pp g = g { _trGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrHasTranslate Tr where attrSetTranslate pp g = g { _trGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_trGlobals g))) } -- | An instance. instance A.AttrGetClassName Tr where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_trGlobals g) -- | An instance. instance A.AttrHasCustom Tr where attrSetCustom pp g = g { _trCustom = Just pp } -- | A short-hand notion for @ elAttr\' \"tr\" ... @ tr' ∷ forall t m a. DomBuilder t m ⇒ Tr → m a → m (Element EventResult (DomBuilderSpace m) t, a) tr' bm = elAttr' "tr" (A.attrMap bm) -- | A short-hand notion for @ elAttr \"tr\" ... @ tr ∷ forall t m a. DomBuilder t m ⇒ Tr → m a → m a tr bm children = snd <$> tr' bm children -- | A short-hand notion for @ el\' \"tr\" ... @ trN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a) trN' = el' "tr" -- | A short-hand notion for @ el \"tr\" ... @ trN ∷ forall t m a. DomBuilder t m ⇒ m a → m a trN children = snd <$> trN' children -- | A short-hand notion for @ elDynAttr\' \"tr\" ... @ trD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Tr → m a → m (Element EventResult (DomBuilderSpace m) t, a) trD' bm = elDynAttr' "tr" (A.attrMap <$> bm) -- | A short-hand notion for @ elDynAttr \"tr\" ... @ trD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Tr → m a → m a trD bm children = snd <$> trD' bm children
gspia/reflex-dom-htmlea
lib/src/Reflex/Dom/HTML5/Elements/Tabular.hs
bsd-3-clause
58,705
0
14
11,302
18,123
9,461
8,662
708
1
module Test where import System.Directory (canonicalizePath) -- add :: Int -> Int -> Int add x y = x + y pwd :: IO FilePath pwd = canonicalizePath "."
jystic/vim-ghc
examples/Test.hs
bsd-3-clause
154
0
5
32
45
25
20
5
1
module ChineseGraphics where import Haste import Haste.DOM import Haste.Graphics.Canvas import Haste.Events import ChineseCheckers import Table import ChineseBitmaps import qualified Control.Concurrent as CC import qualified Haste.Concurrent as HC import qualified Data.Map.Strict as Map radius :: Double radius = 30 initTable2' can = mapM_ (renderSquare can 15 20) drawSquare :: Double -> Double -> Square -> Picture () drawSquare space size (Square (Piece color) _ (x,y)) = do setFillColor color fill $ circle (size*fromIntegral x + space*fromIntegral (x+5),size* fromIntegral y+space* fromIntegral (y+5)) size drawSquare space size (Square Empty col (x,y)) = do setFillColor white fill $ circle (size*fromIntegral x + space*fromIntegral (x+5),size* fromIntegral y+space* fromIntegral (y+5)) size initTableCoords :: [Square] -> [((Int,Int),(Double,Double))] initTableCoords = map (initTableCoord2 15 20) initTableCoord :: Double -> Double -> Square -> ((Int,Int),(Double,Double)) initTableCoord space size (Square _ _ (x,y)) = ((x,y), (size*fromIntegral x + space*fromIntegral (x+5),size* fromIntegral y+space* fromIntegral (y+5))) initTableCoord2 :: Double -> Double -> Square -> ((Int,Int),(Double,Double)) initTableCoord2 space size (Square _ _ (x,y)) = ((x,y), (size/2 + size*fromIntegral x + space*fromIntegral (x+5), size/2 + size* fromIntegral y+space* fromIntegral (y+5))) -- | Generate a canvas with the specified width and height in pixels makeCanvas :: Int -> Int -> IO Elem makeCanvas width height = do canvas <- newElem "canvas" setStyle canvas "border" "1px solid black" setStyle canvas "backgroundColor" "white" set canvas [ prop "width" =: show width , prop "height" =: show height ] return canvas -- | Generate a button with the given text mkButton :: String -> IO Elem mkButton text = do button <- newElem "button" set button [prop "innerHTML" =: text] return button --drawGame :: CC.MVar GameState -> CC.Chan (GameState) -> parent -> IO HandlerInfo -- | Inits the graphics drawGame stateOfGame outbox par = do gameState <- CC.takeMVar stateOfGame canvas <- makeCanvas 1400 800 appendChild par canvas canvas2 <- makeCanvas 500 800 appendChild par canvas2 Just can <- fromElem canvas :: IO (Maybe Canvas) Just can2 <- fromElem canvas2 :: IO (Maybe Canvas) button <- mkButton "Rotate player" appendChild par button initTable2' can $ gameTable gameState CC.putMVar stateOfGame gameState onEvent can Click $ \mouse -> do state <- CC.readMVar stateOfGame case currentPlayer state == "pelle" of -- must save the clients name somehow True -> let (x,y) = mouseCoords mouse in case mapCoords (fromIntegral x,fromIntegral y) of Nothing -> return () Just (x1,y1) -> do gameState <- CC.takeMVar stateOfGame let newState = playerAction gameState (x1,y1) case fromCoord newState of Just (x,y) -> do CC.putMVar stateOfGame newState CC.putMVar outbox $ Move (x1,y1) (x,y) initTable2' can (gameTable newState) -- renderSquare2 can 15 20 (squareContent (gameTable newState) (x,y)) (x,y) renderOnTop can2 $ text (50,50) "hejsan2" case playerDone (players newState) newState of Nothing -> graphicGameOver can Just x -> CC.putMVar stateOfGame x Nothing -> do CC.putMVar stateOfGame newState initTable2' can (gameTable $ playerAction gameState (x1,y1)) -- render can2 $ text (50,50) ((currentPlayer $ playerAction gameState (x1,y1)) ++ "s speltur!!!" ++ ((showColor . snd . head) $ players newState)) renderSquare2 can 15 20 (squareContent (gameTable newState) (x,y)) (x,y) where colors = map snd False -> return () onEvent button Click $ \_ -> do gameState <- CC.takeMVar stateOfGame let newState = rotatePlayer gameState render can2 $ scale (5,5) $ text (0,10) $ currentPlayer newState ++ "s speltur!!!" ++ (showColor . snd . head) (players newState) -- render can2 $ text (50,50) ( (currentPlayer (newState)) ++ "s speltur!!!" ++ ((showColor . snd . head) $ players newState)) CC.putMVar stateOfGame $ rotatePlayer gameState -- render can2 $ text (150,150) (currentPlayer $ rotatePlayer gameState) -- | Render the game over text graphicGameOver can = do bitmap <- loadBitmap "file:////home/benjamin/Documents/cooltext170130995424459.gif" renderOnTop can $ draw bitmap (10,10) playerDone :: [(String,Color)] -> GameState -> Maybe GameState playerDone [] t = Nothing playerDone ((s,c):xs) state | playerHome c (gameTable state) = Just GameState {gameTable = gameTable state , currentPlayer = currentPlayer state , players = xs , fromCoord = fromCoord state , playerMoveAgain = playerMoveAgain state} | otherwise = Just state skrep :: GameState -> GameState skrep gs = GameState {gameTable = startTable, currentPlayer = mao $ tail (players gs), players = tail (players gs) ++ [head (players gs)], fromCoord = fromCoord gs, playerMoveAgain = False} where mao [(x,y)] = x mapCoords :: (Double,Double) -> Maybe (Int,Int) mapCoords c1 = case mapCoords' c1 of [] -> Nothing _ -> Just . fst . head $ mapCoords' c1 mapCoords' :: (Double,Double) -> [((Int,Int),(Double,Double))] mapCoords' c1 = filter wasDas $ initTableCoords startTable where wasDas (c2,c3) = distance c1 c3 <= radius -- | Calculate the distance between two points distance :: (Double,Double) -> (Double,Double) -> Double distance (x1,y1) (x2,y2) = sqrt $ (x1-x2)^2 + (y1-y2)^2 showColor :: Color -> String showColor color | color == red = "Red" | color == blue = "Blue" | color == yellow = "Yellow" | color == orange = "Orange" | color == green = "Green" | color == purple = "Purple"
DATx02-16-14/ChineseCheckers
src/ChineseGraphics.hs
bsd-3-clause
6,659
0
30
2,021
2,078
1,051
1,027
116
5
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE JavaScriptFFI #-} {-# LANGUAGE OverloadedStrings #-} module Etude ( someFunc ) where import Control.Monad import Control.Monad.IO.Class (MonadIO(..)) import GHCJS.DOM (currentDocument, currentWindow) import GHCJS.DOM.Document (getElementById, getBodyUnsafe, createTextNode, getBody) import qualified GHCJS.DOM.Document as D (click) import GHCJS.DOM.HTMLElement (setInnerText, toHTMLElement, getOuterText) import GHCJS.DOM.Element (setInnerHTML, getInnerHTML) import GHCJS.DOM.HTMLTextAreaElement as TextArea import GHCJS.DOM.Window (alert, getLocation) import GHCJS.DOM.EventM (on, mouseClientXY) import GHCJS.DOM.JSFFI.Generated.Location (replace) import GHCJS.DOM.Types (Window, Document, toDocument, Element) import qualified GHCJS.Types as T import qualified GHCJS.Foreign as F import qualified GHCJS.Foreign.Callback as CB import qualified GHCJS.Concurrent as CC foreign import javascript unsafe "$1[\"alert\"]($2)" my_alert :: Window -> T.JSString -> IO () foreign import javascript unsafe "window.alert($1)" my_alert2 :: T.JSString -> IO () foreign import javascript unsafe "$1[\"onload\"] = $2" my_onload :: Window -> CB.Callback a -> IO() foreign import javascript unsafe "window.onload = $1" my_onload2 :: CB.Callback a -> IO() foreign import javascript unsafe "$1.click($2)" my_click :: Element -> CB.Callback a -> IO() foreign import javascript unsafe "document.onlick = $1" my_click2 :: CB.Callback a -> IO () someFunc :: IO() someFunc = do putStrLn "I am working!" >> putStrLn "and then..." Just win <- currentWindow asyncCB <- CB.asyncCallback $ do my_alert win "my first callback!" >> putStrLn "onload!" syncCB <- CB.syncCallback CC.ContinueAsync $ do putStrLn " call back!!!" --my_onload win asyncCB my_onload2 syncCB --my_onload2 asyncCB --my_click2 asyncCB CB.releaseCallback asyncCB CB.releaseCallback syncCB putStrLn "Over!2"
jangsa/GHCJSEtude
src/Etude.hs
bsd-3-clause
1,963
17
12
290
510
285
225
39
1
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-2006 GHC.Rename.Env contains functions which convert RdrNames into Names. -} {-# LANGUAGE CPP, MultiWayIf, NamedFieldPuns #-} module GHC.Rename.Env ( newTopSrcBinder, lookupLocatedTopBndrRn, lookupTopBndrRn, lookupLocatedOccRn, lookupOccRn, lookupOccRn_maybe, lookupLocalOccRn_maybe, lookupInfoOccRn, lookupLocalOccThLvl_maybe, lookupLocalOccRn, lookupTypeOccRn, lookupGlobalOccRn, lookupGlobalOccRn_maybe, lookupOccRn_overloaded, lookupGlobalOccRn_overloaded, lookupExactOcc, ChildLookupResult(..), lookupSubBndrOcc_helper, combineChildLookupResult, -- Called by lookupChildrenExport HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn, lookupSigCtxtOccRn, lookupInstDeclBndr, lookupRecFieldOcc, lookupFamInstName, lookupConstructorFields, lookupGreAvailRn, -- Rebindable Syntax lookupSyntaxName, lookupSyntaxName', lookupSyntaxNames, lookupIfThenElse, -- Constructing usage information addUsedGRE, addUsedGREs, addUsedDataCons, dataTcOccs, --TODO: Move this somewhere, into utils? ) where #include "HsVersions.h" import GhcPrelude import GHC.Iface.Load ( loadInterfaceForName, loadSrcInterface_maybe ) import GHC.Iface.Env import GHC.Hs import RdrName import HscTypes import TcEnv import TcRnMonad import RdrHsSyn ( filterCTuple, setRdrNameSpace ) import TysWiredIn import Name import NameSet import NameEnv import Avail import Module import ConLike import DataCon import TyCon import ErrUtils ( MsgDoc ) import PrelNames ( rOOT_MAIN ) import BasicTypes ( pprWarningTxtForMsg, TopLevelFlag(..)) import SrcLoc import Outputable import UniqSet ( uniqSetAny ) import Util import Maybes import DynFlags import FastString import Control.Monad import ListSetOps ( minusList ) import qualified GHC.LanguageExtensions as LangExt import GHC.Rename.Unbound import GHC.Rename.Utils import qualified Data.Semigroup as Semi import Data.Either ( partitionEithers ) import Data.List (find) {- ********************************************************* * * Source-code binders * * ********************************************************* Note [Signature lazy interface loading] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GHC's lazy interface loading can be a bit confusing, so this Note is an empirical description of what happens in one interesting case. When compiling a signature module against an its implementation, we do NOT load interface files associated with its names until after the type checking phase. For example: module ASig where data T f :: T -> T Suppose we compile this with -sig-of "A is ASig": module B where data T = T f T = T module A(module B) where import B During type checking, we'll load A.hi because we need to know what the RdrEnv for the module is, but we DO NOT load the interface for B.hi! It's wholly unnecessary: our local definition 'data T' in ASig is all the information we need to finish type checking. This is contrast to type checking of ordinary Haskell files, in which we would not have the local definition "data T" and would need to consult B.hi immediately. (Also, this situation never occurs for hs-boot files, since you're not allowed to reexport from another module.) After type checking, we then check that the types we provided are consistent with the backing implementation (in checkHiBootOrHsigIface). At this point, B.hi is loaded, because we need something to compare against. I discovered this behavior when trying to figure out why type class instances for Data.Map weren't in the EPS when I was type checking a test very much like ASig (sigof02dm): the associated interface hadn't been loaded yet! (The larger issue is a moot point, since an instance declared in a signature can never be a duplicate.) This behavior might change in the future. Consider this alternate module B: module B where {-# DEPRECATED T, f "Don't use" #-} data T = T f T = T One might conceivably want to report deprecation warnings when compiling ASig with -sig-of B, in which case we need to look at B.hi to find the deprecation warnings during renaming. At the moment, you don't get any warning until you use the identifier further downstream. This would require adjusting addUsedGRE so that during signature compilation, we do not report deprecation warnings for LocalDef. See also Note [Handling of deprecations] -} newTopSrcBinder :: Located RdrName -> RnM Name newTopSrcBinder (L loc rdr_name) | Just name <- isExact_maybe rdr_name = -- This is here to catch -- (a) Exact-name binders created by Template Haskell -- (b) The PrelBase defn of (say) [] and similar, for which -- the parser reads the special syntax and returns an Exact RdrName -- We are at a binding site for the name, so check first that it -- the current module is the correct one; otherwise GHC can get -- very confused indeed. This test rejects code like -- data T = (,) Int Int -- unless we are in GHC.Tup if isExternalName name then do { this_mod <- getModule ; unless (this_mod == nameModule name) (addErrAt loc (badOrigBinding rdr_name)) ; return name } else -- See Note [Binders in Template Haskell] in Convert.hs do { this_mod <- getModule ; externaliseName this_mod name } | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = do { this_mod <- getModule ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN) (addErrAt loc (badOrigBinding rdr_name)) -- When reading External Core we get Orig names as binders, -- but they should agree with the module gotten from the monad -- -- We can get built-in syntax showing up here too, sadly. If you type -- data T = (,,,) -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon -- uses setRdrNameSpace to make it into a data constructors. At that point -- the nice Exact name for the TyCon gets swizzled to an Orig name. -- Hence the badOrigBinding error message. -- -- Except for the ":Main.main = ..." definition inserted into -- the Main module; ugh! -- Because of this latter case, we call newGlobalBinder with a module from -- the RdrName, not from the environment. In principle, it'd be fine to -- have an arbitrary mixture of external core definitions in a single module, -- (apart from module-initialisation issues, perhaps). ; newGlobalBinder rdr_mod rdr_occ loc } | otherwise = do { when (isQual rdr_name) (addErrAt loc (badQualBndrErr rdr_name)) -- Binders should not be qualified; if they are, and with a different -- module name, we get a confusing "M.T is not in scope" error later ; stage <- getStage ; if isBrackStage stage then -- We are inside a TH bracket, so make an *Internal* name -- See Note [Top-level Names in Template Haskell decl quotes] in GHC.Rename.Names do { uniq <- newUnique ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) } else do { this_mod <- getModule ; traceRn "newTopSrcBinder" (ppr this_mod $$ ppr rdr_name $$ ppr loc) ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc } } {- ********************************************************* * * Source code occurrences * * ********************************************************* Looking up a name in the GHC.Rename.Env. Note [Type and class operator definitions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We want to reject all of these unless we have -XTypeOperators (#3265) data a :*: b = ... class a :*: b where ... data (:*:) a b = .... class (:*:) a b where ... The latter two mean that we are not just looking for a *syntactically-infix* declaration, but one that uses an operator OccName. We use OccName.isSymOcc to detect that case, which isn't terribly efficient, but there seems to be no better way. -} -- Can be made to not be exposed -- Only used unwrapped in rnAnnProvenance lookupTopBndrRn :: RdrName -> RnM Name lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n case nopt of Just n' -> return n' Nothing -> do traceRn "lookupTopBndrRn fail" (ppr n) unboundName WL_LocalTop n lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name) lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name) -- Look up a top-level source-code binder. We may be looking up an unqualified 'f', -- and there may be several imported 'f's too, which must not confuse us. -- For example, this is OK: -- import Foo( f ) -- infix 9 f -- The 'f' here does not need to be qualified -- f x = x -- Nor here, of course -- So we have to filter out the non-local ones. -- -- A separate function (importsFromLocalDecls) reports duplicate top level -- decls, so here it's safe just to choose an arbitrary one. -- -- There should never be a qualified name in a binding position in Haskell, -- but there can be if we have read in an external-Core file. -- The Haskell parser checks for the illegal qualified name in Haskell -- source files, so we don't need to do so here. lookupTopBndrRn_maybe rdr_name = lookupExactOrOrig rdr_name Just $ do { -- Check for operators in type or class declarations -- See Note [Type and class operator definitions] let occ = rdrNameOcc rdr_name ; when (isTcOcc occ && isSymOcc occ) (do { op_ok <- xoptM LangExt.TypeOperators ; unless op_ok (addErr (opDeclErr rdr_name)) }) ; env <- getGlobalRdrEnv ; case filter isLocalGRE (lookupGRE_RdrName rdr_name env) of [gre] -> return (Just (gre_name gre)) _ -> return Nothing -- Ambiguous (can't happen) or unbound } ----------------------------------------------- -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames]. -- This adds an error if the name cannot be found. lookupExactOcc :: Name -> RnM Name lookupExactOcc name = do { result <- lookupExactOcc_either name ; case result of Left err -> do { addErr err ; return name } Right name' -> return name' } -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames]. -- This never adds an error, but it may return one. lookupExactOcc_either :: Name -> RnM (Either MsgDoc Name) -- See Note [Looking up Exact RdrNames] lookupExactOcc_either name | Just thing <- wiredInNameTyThing_maybe name , Just tycon <- case thing of ATyCon tc -> Just tc AConLike (RealDataCon dc) -> Just (dataConTyCon dc) _ -> Nothing , isTupleTyCon tycon = do { checkTupSize (tyConArity tycon) ; return (Right name) } | isExternalName name = return (Right name) | otherwise = do { env <- getGlobalRdrEnv ; let -- See Note [Splicing Exact names] main_occ = nameOccName name demoted_occs = case demoteOccName main_occ of Just occ -> [occ] Nothing -> [] gres = [ gre | occ <- main_occ : demoted_occs , gre <- lookupGlobalRdrEnv env occ , gre_name gre == name ] ; case gres of [gre] -> return (Right (gre_name gre)) [] -> -- See Note [Splicing Exact names] do { lcl_env <- getLocalRdrEnv ; if name `inLocalRdrEnvScope` lcl_env then return (Right name) else do { th_topnames_var <- fmap tcg_th_topnames getGblEnv ; th_topnames <- readTcRef th_topnames_var ; if name `elemNameSet` th_topnames then return (Right name) else return (Left exact_nm_err) } } gres -> return (Left (sameNameErr gres)) -- Ugh! See Note [Template Haskell ambiguity] } where exact_nm_err = hang (text "The exact Name" <+> quotes (ppr name) <+> ptext (sLit "is not in scope")) 2 (vcat [ text "Probable cause: you used a unique Template Haskell name (NameU), " , text "perhaps via newName, but did not bind it" , text "If that's it, then -ddump-splices might be useful" ]) sameNameErr :: [GlobalRdrElt] -> MsgDoc sameNameErr [] = panic "addSameNameErr: empty list" sameNameErr gres@(_ : _) = hang (text "Same exact name in multiple name-spaces:") 2 (vcat (map pp_one sorted_names) $$ th_hint) where sorted_names = sortWith nameSrcLoc (map gre_name gres) pp_one name = hang (pprNameSpace (occNameSpace (getOccName name)) <+> quotes (ppr name) <> comma) 2 (text "declared at:" <+> ppr (nameSrcLoc name)) th_hint = vcat [ text "Probable cause: you bound a unique Template Haskell name (NameU)," , text "perhaps via newName, in different name-spaces." , text "If that's it, then -ddump-splices might be useful" ] ----------------------------------------------- lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name -- This is called on the method name on the left-hand side of an -- instance declaration binding. eg. instance Functor T where -- fmap = ... -- ^^^^ called on this -- Regardless of how many unqualified fmaps are in scope, we want -- the one that comes from the Functor class. -- -- Furthermore, note that we take no account of whether the -- name is only in scope qualified. I.e. even if method op is -- in scope as M.op, we still allow plain 'op' on the LHS of -- an instance decl -- -- The "what" parameter says "method" or "associated type", -- depending on what we are looking up lookupInstDeclBndr cls what rdr = do { when (isQual rdr) (addErr (badQualBndrErr rdr)) -- In an instance decl you aren't allowed -- to use a qualified name for the method -- (Although it'd make perfect sense.) ; mb_name <- lookupSubBndrOcc False -- False => we don't give deprecated -- warnings when a deprecated class -- method is defined. We only warn -- when it's used cls doc rdr ; case mb_name of Left err -> do { addErr err; return (mkUnboundNameRdr rdr) } Right nm -> return nm } where doc = what <+> text "of class" <+> quotes (ppr cls) ----------------------------------------------- lookupFamInstName :: Maybe Name -> Located RdrName -> RnM (Located Name) -- Used for TyData and TySynonym family instances only, -- See Note [Family instance binders] lookupFamInstName (Just cls) tc_rdr -- Associated type; c.f GHC.Rename.Binds.rnMethodBind = wrapLocM (lookupInstDeclBndr cls (text "associated type")) tc_rdr lookupFamInstName Nothing tc_rdr -- Family instance; tc_rdr is an *occurrence* = lookupLocatedOccRn tc_rdr ----------------------------------------------- lookupConstructorFields :: Name -> RnM [FieldLabel] -- Look up the fields of a given constructor -- * For constructors from this module, use the record field env, -- which is itself gathered from the (as yet un-typechecked) -- data type decls -- -- * For constructors from imported modules, use the *type* environment -- since imported modules are already compiled, the info is conveniently -- right there lookupConstructorFields con_name = do { this_mod <- getModule ; if nameIsLocalOrFrom this_mod con_name then do { field_env <- getRecFieldEnv ; traceTc "lookupCF" (ppr con_name $$ ppr (lookupNameEnv field_env con_name) $$ ppr field_env) ; return (lookupNameEnv field_env con_name `orElse` []) } else do { con <- tcLookupConLike con_name ; traceTc "lookupCF 2" (ppr con) ; return (conLikeFieldLabels con) } } -- In CPS style as `RnM r` is monadic lookupExactOrOrig :: RdrName -> (Name -> r) -> RnM r -> RnM r lookupExactOrOrig rdr_name res k | Just n <- isExact_maybe rdr_name -- This happens in derived code = res <$> lookupExactOcc n | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = res <$> lookupOrig rdr_mod rdr_occ | otherwise = k ----------------------------------------------- -- | Look up an occurrence of a field in record construction or pattern -- matching (but not update). When the -XDisambiguateRecordFields -- flag is on, take account of the data constructor name to -- disambiguate which field to use. -- -- See Note [DisambiguateRecordFields]. lookupRecFieldOcc :: Maybe Name -- Nothing => just look it up as usual -- Just con => use data con to disambiguate -> RdrName -> RnM Name lookupRecFieldOcc mb_con rdr_name | Just con <- mb_con , isUnboundName con -- Avoid error cascade = return (mkUnboundNameRdr rdr_name) | Just con <- mb_con = do { flds <- lookupConstructorFields con ; env <- getGlobalRdrEnv ; let lbl = occNameFS (rdrNameOcc rdr_name) mb_field = do fl <- find ((== lbl) . flLabel) flds -- We have the label, now check it is in -- scope (with the correct qualifier if -- there is one, hence calling pickGREs). gre <- lookupGRE_FieldLabel env fl guard (not (isQual rdr_name && null (pickGREs rdr_name [gre]))) return (fl, gre) ; case mb_field of Just (fl, gre) -> do { addUsedGRE True gre ; return (flSelector fl) } Nothing -> lookupGlobalOccRn rdr_name } -- See Note [Fall back on lookupGlobalOccRn in lookupRecFieldOcc] | otherwise -- This use of Global is right as we are looking up a selector which -- can only be defined at the top level. = lookupGlobalOccRn rdr_name {- Note [DisambiguateRecordFields] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we are looking up record fields in record construction or pattern matching, we can take advantage of the data constructor name to resolve fields that would otherwise be ambiguous (provided the -XDisambiguateRecordFields flag is on). For example, consider: data S = MkS { x :: Int } data T = MkT { x :: Int } e = MkS { x = 3 } When we are renaming the occurrence of `x` in `e`, instead of looking `x` up directly (and finding both fields), lookupRecFieldOcc will search the fields of `MkS` to find the only possible `x` the user can mean. Of course, we still have to check the field is in scope, using lookupGRE_FieldLabel. The handling of qualified imports is slightly subtle: the occurrence may be unqualified even if the field is imported only qualified (but if the occurrence is qualified, the qualifier must be correct). For example: module A where data S = MkS { x :: Int } data T = MkT { x :: Int } module B where import qualified A (S(..)) import A (T(MkT)) e1 = MkT { x = 3 } -- x not in scope, so fail e2 = A.MkS { B.x = 3 } -- module qualifier is wrong, so fail e3 = A.MkS { x = 3 } -- x in scope (lack of module qualifier permitted) In case `e1`, lookupGRE_FieldLabel will return Nothing. In case `e2`, lookupGRE_FieldLabel will return the GRE for `A.x`, but then the guard will fail because the field RdrName `B.x` is qualified and pickGREs rejects the GRE. In case `e3`, lookupGRE_FieldLabel will return the GRE for `A.x` and the guard will succeed because the field RdrName `x` is unqualified. Note [Fall back on lookupGlobalOccRn in lookupRecFieldOcc] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Whenever we fail to find the field or it is not in scope, mb_field will be False, and we fall back on looking it up normally using lookupGlobalOccRn. We don't report an error immediately because the actual problem might be located elsewhere. For example (#9975): data Test = Test { x :: Int } pattern Test wat = Test { x = wat } Here there are multiple declarations of Test (as a data constructor and as a pattern synonym), which will be reported as an error. We shouldn't also report an error about the occurrence of `x` in the pattern synonym RHS. However, if the pattern synonym gets added to the environment first, we will try and fail to find `x` amongst the (nonexistent) fields of the pattern synonym. Alternatively, the scope check can fail due to Template Haskell. Consider (#12130): module Foo where import M b = $(funny) module M(funny) where data T = MkT { x :: Int } funny :: Q Exp funny = [| MkT { x = 3 } |] When we splice, `MkT` is not lexically in scope, so lookupGRE_FieldLabel will fail. But there is no need for disambiguation anyway, because `x` is an original name, and lookupGlobalOccRn will find it. -} -- | Used in export lists to lookup the children. lookupSubBndrOcc_helper :: Bool -> Bool -> Name -> RdrName -> RnM ChildLookupResult lookupSubBndrOcc_helper must_have_parent warn_if_deprec parent rdr_name | isUnboundName parent -- Avoid an error cascade = return (FoundName NoParent (mkUnboundNameRdr rdr_name)) | otherwise = do gre_env <- getGlobalRdrEnv let original_gres = lookupGlobalRdrEnv gre_env (rdrNameOcc rdr_name) -- Disambiguate the lookup based on the parent information. -- The remaining GREs are things that we *could* export here, note that -- this includes things which have `NoParent`. Those are sorted in -- `checkPatSynParent`. traceRn "parent" (ppr parent) traceRn "lookupExportChild original_gres:" (ppr original_gres) traceRn "lookupExportChild picked_gres:" (ppr $ picked_gres original_gres) case picked_gres original_gres of NoOccurrence -> noMatchingParentErr original_gres UniqueOccurrence g -> if must_have_parent then noMatchingParentErr original_gres else checkFld g DisambiguatedOccurrence g -> checkFld g AmbiguousOccurrence gres -> mkNameClashErr gres where -- Convert into FieldLabel if necessary checkFld :: GlobalRdrElt -> RnM ChildLookupResult checkFld g@GRE{gre_name, gre_par} = do addUsedGRE warn_if_deprec g return $ case gre_par of FldParent _ mfs -> FoundFL (fldParentToFieldLabel gre_name mfs) _ -> FoundName gre_par gre_name fldParentToFieldLabel :: Name -> Maybe FastString -> FieldLabel fldParentToFieldLabel name mfs = case mfs of Nothing -> let fs = occNameFS (nameOccName name) in FieldLabel fs False name Just fs -> FieldLabel fs True name -- Called when we find no matching GREs after disambiguation but -- there are three situations where this happens. -- 1. There were none to begin with. -- 2. None of the matching ones were the parent but -- a. They were from an overloaded record field so we can report -- a better error -- b. The original lookup was actually ambiguous. -- For example, the case where overloading is off and two -- record fields are in scope from different record -- constructors, neither of which is the parent. noMatchingParentErr :: [GlobalRdrElt] -> RnM ChildLookupResult noMatchingParentErr original_gres = do overload_ok <- xoptM LangExt.DuplicateRecordFields case original_gres of [] -> return NameNotFound [g] -> return $ IncorrectParent parent (gre_name g) (ppr $ gre_name g) [p | Just p <- [getParent g]] gss@(g:_:_) -> if all isRecFldGRE gss && overload_ok then return $ IncorrectParent parent (gre_name g) (ppr $ expectJust "noMatchingParentErr" (greLabel g)) [p | x <- gss, Just p <- [getParent x]] else mkNameClashErr gss mkNameClashErr :: [GlobalRdrElt] -> RnM ChildLookupResult mkNameClashErr gres = do addNameClashErrRn rdr_name gres return (FoundName (gre_par (head gres)) (gre_name (head gres))) getParent :: GlobalRdrElt -> Maybe Name getParent (GRE { gre_par = p } ) = case p of ParentIs cur_parent -> Just cur_parent FldParent { par_is = cur_parent } -> Just cur_parent NoParent -> Nothing picked_gres :: [GlobalRdrElt] -> DisambigInfo -- For Unqual, find GREs that are in scope qualified or unqualified -- For Qual, find GREs that are in scope with that qualification picked_gres gres | isUnqual rdr_name = mconcat (map right_parent gres) | otherwise = mconcat (map right_parent (pickGREs rdr_name gres)) right_parent :: GlobalRdrElt -> DisambigInfo right_parent p = case getParent p of Just cur_parent | parent == cur_parent -> DisambiguatedOccurrence p | otherwise -> NoOccurrence Nothing -> UniqueOccurrence p -- This domain specific datatype is used to record why we decided it was -- possible that a GRE could be exported with a parent. data DisambigInfo = NoOccurrence -- The GRE could never be exported. It has the wrong parent. | UniqueOccurrence GlobalRdrElt -- The GRE has no parent. It could be a pattern synonym. | DisambiguatedOccurrence GlobalRdrElt -- The parent of the GRE is the correct parent | AmbiguousOccurrence [GlobalRdrElt] -- For example, two normal identifiers with the same name are in -- scope. They will both be resolved to "UniqueOccurrence" and the -- monoid will combine them to this failing case. instance Outputable DisambigInfo where ppr NoOccurrence = text "NoOccurence" ppr (UniqueOccurrence gre) = text "UniqueOccurrence:" <+> ppr gre ppr (DisambiguatedOccurrence gre) = text "DiambiguatedOccurrence:" <+> ppr gre ppr (AmbiguousOccurrence gres) = text "Ambiguous:" <+> ppr gres instance Semi.Semigroup DisambigInfo where -- This is the key line: We prefer disambiguated occurrences to other -- names. _ <> DisambiguatedOccurrence g' = DisambiguatedOccurrence g' DisambiguatedOccurrence g' <> _ = DisambiguatedOccurrence g' NoOccurrence <> m = m m <> NoOccurrence = m UniqueOccurrence g <> UniqueOccurrence g' = AmbiguousOccurrence [g, g'] UniqueOccurrence g <> AmbiguousOccurrence gs = AmbiguousOccurrence (g:gs) AmbiguousOccurrence gs <> UniqueOccurrence g' = AmbiguousOccurrence (g':gs) AmbiguousOccurrence gs <> AmbiguousOccurrence gs' = AmbiguousOccurrence (gs ++ gs') instance Monoid DisambigInfo where mempty = NoOccurrence mappend = (Semi.<>) -- Lookup SubBndrOcc can never be ambiguous -- -- Records the result of looking up a child. data ChildLookupResult = NameNotFound -- We couldn't find a suitable name | IncorrectParent Name -- Parent Name -- Name of thing we were looking for SDoc -- How to print the name [Name] -- List of possible parents | FoundName Parent Name -- We resolved to a normal name | FoundFL FieldLabel -- We resolved to a FL -- | Specialised version of msum for RnM ChildLookupResult combineChildLookupResult :: [RnM ChildLookupResult] -> RnM ChildLookupResult combineChildLookupResult [] = return NameNotFound combineChildLookupResult (x:xs) = do res <- x case res of NameNotFound -> combineChildLookupResult xs _ -> return res instance Outputable ChildLookupResult where ppr NameNotFound = text "NameNotFound" ppr (FoundName p n) = text "Found:" <+> ppr p <+> ppr n ppr (FoundFL fls) = text "FoundFL:" <+> ppr fls ppr (IncorrectParent p n td ns) = text "IncorrectParent" <+> hsep [ppr p, ppr n, td, ppr ns] lookupSubBndrOcc :: Bool -> Name -- Parent -> SDoc -> RdrName -> RnM (Either MsgDoc Name) -- Find all the things the rdr-name maps to -- and pick the one with the right parent namep lookupSubBndrOcc warn_if_deprec the_parent doc rdr_name = do res <- lookupExactOrOrig rdr_name (FoundName NoParent) $ -- This happens for built-in classes, see mod052 for example lookupSubBndrOcc_helper True warn_if_deprec the_parent rdr_name case res of NameNotFound -> return (Left (unknownSubordinateErr doc rdr_name)) FoundName _p n -> return (Right n) FoundFL fl -> return (Right (flSelector fl)) IncorrectParent {} -- See [Mismatched class methods and associated type families] -- in TcInstDecls. -> return $ Left (unknownSubordinateErr doc rdr_name) {- Note [Family instance binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data family F a data instance F T = X1 | X2 The 'data instance' decl has an *occurrence* of F (and T), and *binds* X1 and X2. (This is unlike a normal data type declaration which would bind F too.) So we want an AvailTC F [X1,X2]. Now consider a similar pair: class C a where data G a instance C S where data G S = Y1 | Y2 The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G. But there is a small complication: in an instance decl, we don't use qualified names on the LHS; instead we use the class to disambiguate. Thus: module M where import Blib( G ) class C a where data G a instance C S where data G S = Y1 | Y2 Even though there are two G's in scope (M.G and Blib.G), the occurrence of 'G' in the 'instance C S' decl is unambiguous, because C has only one associated type called G. This is exactly what happens for methods, and it is only consistent to do the same thing for types. That's the role of the function lookupTcdName; the (Maybe Name) give the class of the encloseing instance decl, if any. Note [Looking up Exact RdrNames] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Exact RdrNames are generated by Template Haskell. See Note [Binders in Template Haskell] in Convert. For data types and classes have Exact system Names in the binding positions for constructors, TyCons etc. For example [d| data T = MkT Int |] when we splice in and Convert to HsSyn RdrName, we'll get data (Exact (system Name "T")) = (Exact (system Name "MkT")) ... These System names are generated by Convert.thRdrName But, constructors and the like need External Names, not System Names! So we do the following * In GHC.Rename.Env.newTopSrcBinder we spot Exact RdrNames that wrap a non-External Name, and make an External name for it. This is the name that goes in the GlobalRdrEnv * When looking up an occurrence of an Exact name, done in GHC.Rename.Env.lookupExactOcc, we find the Name with the right unique in the GlobalRdrEnv, and use the one from the envt -- it will be an External Name in the case of the data type/constructor above. * Exact names are also use for purely local binders generated by TH, such as \x_33. x_33 Both binder and occurrence are Exact RdrNames. The occurrence gets looked up in the LocalRdrEnv by GHC.Rename.Env.lookupOccRn, and misses, because lookupLocalRdrEnv always returns Nothing for an Exact Name. Now we fall through to lookupExactOcc, which will find the Name is not in the GlobalRdrEnv, so we just use the Exact supplied Name. Note [Splicing Exact names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider the splice $(do { x <- newName "x"; return (VarE x) }) This will generate a (HsExpr RdrName) term that mentions the Exact RdrName "x_56" (or whatever), but does not bind it. So when looking such Exact names we want to check that it's in scope, otherwise the type checker will get confused. To do this we need to keep track of all the Names in scope, and the LocalRdrEnv does just that; we consult it with RdrName.inLocalRdrEnvScope. There is another wrinkle. With TH and -XDataKinds, consider $( [d| data Nat = Zero data T = MkT (Proxy 'Zero) |] ) After splicing, but before renaming we get this: data Nat_77{tc} = Zero_78{d} data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] ) The occurrence of 'Zero in the data type for T has the right unique, but it has a TcClsName name-space in its OccName. (This is set by the ctxt_ns argument of Convert.thRdrName.) When we check that is in scope in the GlobalRdrEnv, we need to look up the DataName namespace too. (An alternative would be to make the GlobalRdrEnv also have a Name -> GRE mapping.) Note [Template Haskell ambiguity] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The GlobalRdrEnv invariant says that if occ -> [gre1, ..., gren] then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv). This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre). So how can we get multiple gres in lookupExactOcc_maybe? Because in TH we might use the same TH NameU in two different name spaces. eg (#7241): $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]]) Here we generate a type constructor and data constructor with the same unique, but different name spaces. It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would mean looking up the OccName in every name-space, just in case, and that seems a bit brutal. So it's just done here on lookup. But we might need to revisit that choice. Note [Usage for sub-bndrs] ~~~~~~~~~~~~~~~~~~~~~~~~~~ If you have this import qualified M( C( f ) ) instance M.C T where f x = x then is the qualified import M.f used? Obviously yes. But the RdrName used in the instance decl is unqualified. In effect, we fill in the qualification by looking for f's whose class is M.C But when adding to the UsedRdrNames we must make that qualification explicit (saying "used M.f"), otherwise we get "Redundant import of M.f". So we make up a suitable (fake) RdrName. But be careful import qualified M import M( C(f) ) instance C T where f x = x Here we want to record a use of 'f', not of 'M.f', otherwise we'll miss the fact that the qualified import is redundant. -------------------------------------------------- -- Occurrences -------------------------------------------------- -} lookupLocatedOccRn :: Located RdrName -> RnM (Located Name) lookupLocatedOccRn = wrapLocM lookupOccRn lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name) -- Just look in the local environment lookupLocalOccRn_maybe rdr_name = do { local_env <- getLocalRdrEnv ; return (lookupLocalRdrEnv local_env rdr_name) } lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel)) -- Just look in the local environment lookupLocalOccThLvl_maybe name = do { lcl_env <- getLclEnv ; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) } -- lookupOccRn looks up an occurrence of a RdrName lookupOccRn :: RdrName -> RnM Name lookupOccRn rdr_name = do { mb_name <- lookupOccRn_maybe rdr_name ; case mb_name of Just name -> return name Nothing -> reportUnboundName rdr_name } -- Only used in one place, to rename pattern synonym binders. -- See Note [Renaming pattern synonym variables] in GHC.Rename.Binds lookupLocalOccRn :: RdrName -> RnM Name lookupLocalOccRn rdr_name = do { mb_name <- lookupLocalOccRn_maybe rdr_name ; case mb_name of Just name -> return name Nothing -> unboundName WL_LocalOnly rdr_name } -- lookupPromotedOccRn looks up an optionally promoted RdrName. lookupTypeOccRn :: RdrName -> RnM Name -- see Note [Demotion] lookupTypeOccRn rdr_name | isVarOcc (rdrNameOcc rdr_name) -- See Note [Promoted variables in types] = badVarInType rdr_name | otherwise = do { mb_name <- lookupOccRn_maybe rdr_name ; case mb_name of Just name -> return name Nothing -> lookup_demoted rdr_name } lookup_demoted :: RdrName -> RnM Name lookup_demoted rdr_name | Just demoted_rdr <- demoteRdrName rdr_name -- Maybe it's the name of a *data* constructor = do { data_kinds <- xoptM LangExt.DataKinds ; star_is_type <- xoptM LangExt.StarIsType ; let star_info = starInfo star_is_type rdr_name ; if data_kinds then do { mb_demoted_name <- lookupOccRn_maybe demoted_rdr ; case mb_demoted_name of Nothing -> unboundNameX WL_Any rdr_name star_info Just demoted_name -> do { whenWOptM Opt_WarnUntickedPromotedConstructors $ addWarn (Reason Opt_WarnUntickedPromotedConstructors) (untickedPromConstrWarn demoted_name) ; return demoted_name } } else do { -- We need to check if a data constructor of this name is -- in scope to give good error messages. However, we do -- not want to give an additional error if the data -- constructor happens to be out of scope! See #13947. mb_demoted_name <- discardErrs $ lookupOccRn_maybe demoted_rdr ; let suggestion | isJust mb_demoted_name = suggest_dk | otherwise = star_info ; unboundNameX WL_Any rdr_name suggestion } } | otherwise = reportUnboundName rdr_name where suggest_dk = text "A data constructor of that name is in scope; did you mean DataKinds?" untickedPromConstrWarn name = text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot $$ hsep [ text "Use" , quotes (char '\'' <> ppr name) , text "instead of" , quotes (ppr name) <> dot ] badVarInType :: RdrName -> RnM Name badVarInType rdr_name = do { addErr (text "Illegal promoted term variable in a type:" <+> ppr rdr_name) ; return (mkUnboundNameRdr rdr_name) } {- Note [Promoted variables in types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this (#12686): x = True data Bad = Bad 'x The parser treats the quote in 'x as saying "use the term namespace", so we'll get (Bad x{v}), with 'x' in the VarName namespace. If we don't test for this, the renamer will happily rename it to the x bound at top level, and then the typecheck falls over because it doesn't have 'x' in scope when kind-checking. Note [Demotion] ~~~~~~~~~~~~~~~ When the user writes: data Nat = Zero | Succ Nat foo :: f Zero -> Int 'Zero' in the type signature of 'foo' is parsed as: HsTyVar ("Zero", TcClsName) When the renamer hits this occurrence of 'Zero' it's going to realise that it's not in scope. But because it is renaming a type, it knows that 'Zero' might be a promoted data constructor, so it will demote its namespace to DataName and do a second lookup. The final result (after the renamer) will be: HsTyVar ("Zero", DataName) -} lookupOccRnX_maybe :: (RdrName -> RnM (Maybe r)) -> (Name -> r) -> RdrName -> RnM (Maybe r) lookupOccRnX_maybe globalLookup wrapper rdr_name = runMaybeT . msum . map MaybeT $ [ fmap wrapper <$> lookupLocalOccRn_maybe rdr_name , globalLookup rdr_name ] lookupOccRn_maybe :: RdrName -> RnM (Maybe Name) lookupOccRn_maybe = lookupOccRnX_maybe lookupGlobalOccRn_maybe id lookupOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [Name])) lookupOccRn_overloaded overload_ok = lookupOccRnX_maybe global_lookup Left where global_lookup :: RdrName -> RnM (Maybe (Either Name [Name])) global_lookup n = runMaybeT . msum . map MaybeT $ [ lookupGlobalOccRn_overloaded overload_ok n , fmap Left . listToMaybe <$> lookupQualifiedNameGHCi n ] lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name) -- Looks up a RdrName occurrence in the top-level -- environment, including using lookupQualifiedNameGHCi -- for the GHCi case -- No filter function; does not report an error on failure -- Uses addUsedRdrName to record use and deprecations lookupGlobalOccRn_maybe rdr_name = lookupExactOrOrig rdr_name Just $ runMaybeT . msum . map MaybeT $ [ fmap gre_name <$> lookupGreRn_maybe rdr_name , listToMaybe <$> lookupQualifiedNameGHCi rdr_name ] -- This test is not expensive, -- and only happens for failed lookups lookupGlobalOccRn :: RdrName -> RnM Name -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global -- environment. Adds an error message if the RdrName is not in scope. -- You usually want to use "lookupOccRn" which also looks in the local -- environment. lookupGlobalOccRn rdr_name = do { mb_name <- lookupGlobalOccRn_maybe rdr_name ; case mb_name of Just n -> return n Nothing -> do { traceRn "lookupGlobalOccRn" (ppr rdr_name) ; unboundName WL_Global rdr_name } } lookupInfoOccRn :: RdrName -> RnM [Name] -- lookupInfoOccRn is intended for use in GHCi's ":info" command -- It finds all the GREs that RdrName could mean, not complaining -- about ambiguity, but rather returning them all -- C.f. #9881 lookupInfoOccRn rdr_name = lookupExactOrOrig rdr_name (:[]) $ do { rdr_env <- getGlobalRdrEnv ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env) ; qual_ns <- lookupQualifiedNameGHCi rdr_name ; return (ns ++ (qual_ns `minusList` ns)) } -- | Like 'lookupOccRn_maybe', but with a more informative result if -- the 'RdrName' happens to be a record selector: -- -- * Nothing -> name not in scope (no error reported) -- * Just (Left x) -> name uniquely refers to x, -- or there is a name clash (reported) -- * Just (Right xs) -> name refers to one or more record selectors; -- if overload_ok was False, this list will be -- a singleton. lookupGlobalOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [Name])) lookupGlobalOccRn_overloaded overload_ok rdr_name = lookupExactOrOrig rdr_name (Just . Left) $ do { res <- lookupGreRn_helper rdr_name ; case res of GreNotFound -> return Nothing OneNameMatch gre -> do let wrapper = if isRecFldGRE gre then Right . (:[]) else Left return $ Just (wrapper (gre_name gre)) MultipleNames gres | all isRecFldGRE gres && overload_ok -> -- Don't record usage for ambiguous selectors -- until we know which is meant return $ Just (Right (map gre_name gres)) MultipleNames gres -> do addNameClashErrRn rdr_name gres return (Just (Left (gre_name (head gres)))) } -------------------------------------------------- -- Lookup in the Global RdrEnv of the module -------------------------------------------------- data GreLookupResult = GreNotFound | OneNameMatch GlobalRdrElt | MultipleNames [GlobalRdrElt] lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt) -- Look up the RdrName in the GlobalRdrEnv -- Exactly one binding: records it as "used", return (Just gre) -- No bindings: return Nothing -- Many bindings: report "ambiguous", return an arbitrary (Just gre) -- Uses addUsedRdrName to record use and deprecations lookupGreRn_maybe rdr_name = do res <- lookupGreRn_helper rdr_name case res of OneNameMatch gre -> return $ Just gre MultipleNames gres -> do traceRn "lookupGreRn_maybe:NameClash" (ppr gres) addNameClashErrRn rdr_name gres return $ Just (head gres) GreNotFound -> return Nothing {- Note [ Unbound vs Ambiguous Names ] lookupGreRn_maybe deals with failures in two different ways. If a name is unbound then we return a `Nothing` but if the name is ambiguous then we raise an error and return a dummy name. The reason for this is that when we call `lookupGreRn_maybe` we are speculatively looking for whatever we are looking up. If we don't find it, then we might have been looking for the wrong thing and can keep trying. On the other hand, if we find a clash then there is no way to recover as we found the thing we were looking for but can no longer resolve which the correct one is. One example of this is in `lookupTypeOccRn` which first looks in the type constructor namespace before looking in the data constructor namespace to deal with `DataKinds`. There is however, as always, one exception to this scheme. If we find an ambiguous occurrence of a record selector and DuplicateRecordFields is enabled then we defer the selection until the typechecker. -} -- Internal Function lookupGreRn_helper :: RdrName -> RnM GreLookupResult lookupGreRn_helper rdr_name = do { env <- getGlobalRdrEnv ; case lookupGRE_RdrName rdr_name env of [] -> return GreNotFound [gre] -> do { addUsedGRE True gre ; return (OneNameMatch gre) } gres -> return (MultipleNames gres) } lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo) -- Used in export lists -- If not found or ambiguous, add error message, and fake with UnboundName -- Uses addUsedRdrName to record use and deprecations lookupGreAvailRn rdr_name = do mb_gre <- lookupGreRn_helper rdr_name case mb_gre of GreNotFound -> do traceRn "lookupGreAvailRn" (ppr rdr_name) name <- unboundName WL_Global rdr_name return (name, avail name) MultipleNames gres -> do addNameClashErrRn rdr_name gres let unbound_name = mkUnboundNameRdr rdr_name return (unbound_name, avail unbound_name) -- Returning an unbound name here prevents an error -- cascade OneNameMatch gre -> return (gre_name gre, availFromGRE gre) {- ********************************************************* * * Deprecations * * ********************************************************* Note [Handling of deprecations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * We report deprecations at each *occurrence* of the deprecated thing (see #5867) * We do not report deprecations for locally-defined names. For a start, we may be exporting a deprecated thing. Also we may use a deprecated thing in the defn of another deprecated things. We may even use a deprecated thing in the defn of a non-deprecated thing, when changing a module's interface. * addUsedGREs: we do not report deprecations for sub-binders: - the ".." completion for records - the ".." in an export item 'T(..)' - the things exported by a module export 'module M' -} addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM () -- Remember use of in-scope data constructors (#7969) addUsedDataCons rdr_env tycon = addUsedGREs [ gre | dc <- tyConDataCons tycon , Just gre <- [lookupGRE_Name rdr_env (dataConName dc)] ] addUsedGRE :: Bool -> GlobalRdrElt -> RnM () -- Called for both local and imported things -- Add usage *and* warn if deprecated addUsedGRE warn_if_deprec gre = do { when warn_if_deprec (warnIfDeprecated gre) ; unless (isLocalGRE gre) $ do { env <- getGblEnv ; traceRn "addUsedGRE" (ppr gre) ; updMutVar (tcg_used_gres env) (gre :) } } addUsedGREs :: [GlobalRdrElt] -> RnM () -- Record uses of any *imported* GREs -- Used for recording used sub-bndrs -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations] addUsedGREs gres | null imp_gres = return () | otherwise = do { env <- getGblEnv ; traceRn "addUsedGREs" (ppr imp_gres) ; updMutVar (tcg_used_gres env) (imp_gres ++) } where imp_gres = filterOut isLocalGRE gres warnIfDeprecated :: GlobalRdrElt -> RnM () warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss }) | (imp_spec : _) <- iss = do { dflags <- getDynFlags ; this_mod <- getModule ; when (wopt Opt_WarnWarningsDeprecations dflags && not (nameIsLocalOrFrom this_mod name)) $ -- See Note [Handling of deprecations] do { iface <- loadInterfaceForName doc name ; case lookupImpDeprec iface gre of Just txt -> addWarn (Reason Opt_WarnWarningsDeprecations) (mk_msg imp_spec txt) Nothing -> return () } } | otherwise = return () where occ = greOccName gre name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name doc = text "The name" <+> quotes (ppr occ) <+> ptext (sLit "is mentioned explicitly") mk_msg imp_spec txt = sep [ sep [ text "In the use of" <+> pprNonVarNameSpace (occNameSpace occ) <+> quotes (ppr occ) , parens imp_msg <> colon ] , pprWarningTxtForMsg txt ] where imp_mod = importSpecModule imp_spec imp_msg = text "imported from" <+> ppr imp_mod <> extra extra | imp_mod == moduleName name_mod = Outputable.empty | otherwise = text ", but defined in" <+> ppr name_mod lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt lookupImpDeprec iface gre = mi_warn_fn (mi_final_exts iface) (greOccName gre) `mplus` -- Bleat if the thing, case gre_par gre of -- or its parent, is warn'd ParentIs p -> mi_warn_fn (mi_final_exts iface) (nameOccName p) FldParent { par_is = p } -> mi_warn_fn (mi_final_exts iface) (nameOccName p) NoParent -> Nothing {- Note [Used names with interface not loaded] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's (just) possible to find a used Name whose interface hasn't been loaded: a) It might be a WiredInName; in that case we may not load its interface (although we could). b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger These are seen as "used" by the renamer (if -XRebindableSyntax) is on), but the typechecker may discard their uses if in fact the in-scope fromRational is GHC.Read.fromRational, (see tcPat.tcOverloadedLit), and the typechecker sees that the type is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst). In that obscure case it won't force the interface in. In both cases we simply don't permit deprecations; this is, after all, wired-in stuff. ********************************************************* * * GHCi support * * ********************************************************* A qualified name on the command line can refer to any module at all: we try to load the interface if we don't already have it, just as if there was an "import qualified M" declaration for every module. For example, writing `Data.List.sort` will load the interface file for `Data.List` as if the user had written `import qualified Data.List`. If we fail we just return Nothing, rather than bleating about "attempting to use module ‘D’ (./D.hs) which is not loaded" which is what loadSrcInterface does. It is enabled by default and disabled by the flag `-fno-implicit-import-qualified`. Note [Safe Haskell and GHCi] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We DON'T do this Safe Haskell as we need to check imports. We can and should instead check the qualified import but at the moment this requires some refactoring so leave as a TODO -} lookupQualifiedNameGHCi :: RdrName -> RnM [Name] lookupQualifiedNameGHCi rdr_name = -- We want to behave as we would for a source file import here, -- and respect hiddenness of modules/packages, hence loadSrcInterface. do { dflags <- getDynFlags ; is_ghci <- getIsGHCi ; go_for_it dflags is_ghci } where go_for_it dflags is_ghci | Just (mod,occ) <- isQual_maybe rdr_name , is_ghci , gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour , not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi] = do { res <- loadSrcInterface_maybe doc mod False Nothing ; case res of Succeeded iface -> return [ name | avail <- mi_exports iface , name <- availNames avail , nameOccName name == occ ] _ -> -- Either we couldn't load the interface, or -- we could but we didn't find the name in it do { traceRn "lookupQualifiedNameGHCi" (ppr rdr_name) ; return [] } } | otherwise = do { traceRn "lookupQualifiedNameGHCi: off" (ppr rdr_name) ; return [] } doc = text "Need to find" <+> ppr rdr_name {- Note [Looking up signature names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ lookupSigOccRn is used for type signatures and pragmas Is this valid? module A import M( f ) f :: Int -> Int f x = x It's clear that the 'f' in the signature must refer to A.f The Haskell98 report does not stipulate this, but it will! So we must treat the 'f' in the signature in the same way as the binding occurrence of 'f', using lookupBndrRn However, consider this case: import M( f ) f :: Int -> Int g x = x We don't want to say 'f' is out of scope; instead, we want to return the imported 'f', so that later on the renamer will correctly report "misplaced type sig". Note [Signatures for top level things] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ data HsSigCtxt = ... | TopSigCtxt NameSet | .... * The NameSet says what is bound in this group of bindings. We can't use isLocalGRE from the GlobalRdrEnv, because of this: f x = x $( ...some TH splice... ) f :: Int -> Int When we encounter the signature for 'f', the binding for 'f' will be in the GlobalRdrEnv, and will be a LocalDef. Yet the signature is mis-placed * For type signatures the NameSet should be the names bound by the value bindings; for fixity declarations, the NameSet should also include class sigs and record selectors infix 3 `f` -- Yes, ok f :: C a => a -> a -- No, not ok class C a where f :: a -> a -} data HsSigCtxt = TopSigCtxt NameSet -- At top level, binding these names -- See Note [Signatures for top level things] | LocalBindCtxt NameSet -- In a local binding, binding these names | ClsDeclCtxt Name -- Class decl for this class | InstDeclCtxt NameSet -- Instance decl whose user-written method -- bindings are for these methods | HsBootCtxt NameSet -- Top level of a hs-boot file, binding these names | RoleAnnotCtxt NameSet -- A role annotation, with the names of all types -- in the group instance Outputable HsSigCtxt where ppr (TopSigCtxt ns) = text "TopSigCtxt" <+> ppr ns ppr (LocalBindCtxt ns) = text "LocalBindCtxt" <+> ppr ns ppr (ClsDeclCtxt n) = text "ClsDeclCtxt" <+> ppr n ppr (InstDeclCtxt ns) = text "InstDeclCtxt" <+> ppr ns ppr (HsBootCtxt ns) = text "HsBootCtxt" <+> ppr ns ppr (RoleAnnotCtxt ns) = text "RoleAnnotCtxt" <+> ppr ns lookupSigOccRn :: HsSigCtxt -> Sig GhcPs -> Located RdrName -> RnM (Located Name) lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig) -- | Lookup a name in relation to the names in a 'HsSigCtxt' lookupSigCtxtOccRn :: HsSigCtxt -> SDoc -- ^ description of thing we're looking up, -- like "type family" -> Located RdrName -> RnM (Located Name) lookupSigCtxtOccRn ctxt what = wrapLocM $ \ rdr_name -> do { mb_name <- lookupBindGroupOcc ctxt what rdr_name ; case mb_name of Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) } Right name -> return name } lookupBindGroupOcc :: HsSigCtxt -> SDoc -> RdrName -> RnM (Either MsgDoc Name) -- Looks up the RdrName, expecting it to resolve to one of the -- bound names passed in. If not, return an appropriate error message -- -- See Note [Looking up signature names] lookupBindGroupOcc ctxt what rdr_name | Just n <- isExact_maybe rdr_name = lookupExactOcc_either n -- allow for the possibility of missing Exacts; -- see Note [dataTcOccs and Exact Names] -- Maybe we should check the side conditions -- but it's a pain, and Exact things only show -- up when you know what you are doing | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = do { n' <- lookupOrig rdr_mod rdr_occ ; return (Right n') } | otherwise = case ctxt of HsBootCtxt ns -> lookup_top (`elemNameSet` ns) TopSigCtxt ns -> lookup_top (`elemNameSet` ns) RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns) LocalBindCtxt ns -> lookup_group ns ClsDeclCtxt cls -> lookup_cls_op cls InstDeclCtxt ns -> if uniqSetAny isUnboundName ns -- #16610 then return (Right $ mkUnboundNameRdr rdr_name) else lookup_top (`elemNameSet` ns) where lookup_cls_op cls = lookupSubBndrOcc True cls doc rdr_name where doc = text "method of class" <+> quotes (ppr cls) lookup_top keep_me = do { env <- getGlobalRdrEnv ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name) names_in_scope = -- If rdr_name lacks a binding, only -- recommend alternatives from related -- namespaces. See #17593. filter (\n -> nameSpacesRelated (rdrNameSpace rdr_name) (nameNameSpace n)) $ map gre_name $ filter isLocalGRE $ globalRdrEnvElts env candidates_msg = candidates names_in_scope ; case filter (keep_me . gre_name) all_gres of [] | null all_gres -> bale_out_with candidates_msg | otherwise -> bale_out_with local_msg (gre:_) -> return (Right (gre_name gre)) } lookup_group bound_names -- Look in the local envt (not top level) = do { mname <- lookupLocalOccRn_maybe rdr_name ; env <- getLocalRdrEnv ; let candidates_msg = candidates $ localRdrEnvElts env ; case mname of Just n | n `elemNameSet` bound_names -> return (Right n) | otherwise -> bale_out_with local_msg Nothing -> bale_out_with candidates_msg } bale_out_with msg = return (Left (sep [ text "The" <+> what <+> text "for" <+> quotes (ppr rdr_name) , nest 2 $ text "lacks an accompanying binding"] $$ nest 2 msg)) local_msg = parens $ text "The" <+> what <+> ptext (sLit "must be given where") <+> quotes (ppr rdr_name) <+> text "is declared" -- Identify all similar names and produce a message listing them candidates :: [Name] -> MsgDoc candidates names_in_scope = case similar_names of [] -> Outputable.empty [n] -> text "Perhaps you meant" <+> pp_item n _ -> sep [ text "Perhaps you meant one of these:" , nest 2 (pprWithCommas pp_item similar_names) ] where similar_names = fuzzyLookup (unpackFS $ occNameFS $ rdrNameOcc rdr_name) $ map (\x -> ((unpackFS $ occNameFS $ nameOccName x), x)) names_in_scope pp_item x = quotes (ppr x) <+> parens (pprDefinedAt x) --------------- lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [(RdrName, Name)] -- GHC extension: look up both the tycon and data con or variable. -- Used for top-level fixity signatures and deprecations. -- Complain if neither is in scope. -- See Note [Fixity signature lookup] lookupLocalTcNames ctxt what rdr_name = do { mb_gres <- mapM lookup (dataTcOccs rdr_name) ; let (errs, names) = partitionEithers mb_gres ; when (null names) $ addErr (head errs) -- Bleat about one only ; return names } where lookup rdr = do { this_mod <- getModule ; nameEither <- lookupBindGroupOcc ctxt what rdr ; return (guard_builtin_syntax this_mod rdr nameEither) } -- Guard against the built-in syntax (ex: `infixl 6 :`), see #15233 guard_builtin_syntax this_mod rdr (Right name) | Just _ <- isBuiltInOcc_maybe (occName rdr) , this_mod /= nameModule name = Left (hsep [text "Illegal", what, text "of built-in syntax:", ppr rdr]) | otherwise = Right (rdr, name) guard_builtin_syntax _ _ (Left err) = Left err dataTcOccs :: RdrName -> [RdrName] -- Return both the given name and the same name promoted to the TcClsName -- namespace. This is useful when we aren't sure which we are looking at. -- See also Note [dataTcOccs and Exact Names] dataTcOccs rdr_name | isDataOcc occ || isVarOcc occ = [rdr_name, rdr_name_tc] | otherwise = [rdr_name] where occ = rdrNameOcc rdr_name rdr_name_tc = case rdr_name of -- The (~) type operator is always in scope, so we need a special case -- for it here, or else :info (~) fails in GHCi. -- See Note [eqTyCon (~) is built-in syntax] Unqual occ | occNameFS occ == fsLit "~" -> eqTyCon_RDR _ -> setRdrNameSpace rdr_name tcName {- Note [dataTcOccs and Exact Names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Exact RdrNames can occur in code generated by Template Haskell, and generally those references are, well, exact. However, the TH `Name` type isn't expressive enough to always track the correct namespace information, so we sometimes get the right Unique but wrong namespace. Thus, we still have to do the double-lookup for Exact RdrNames. There is also an awkward situation for built-in syntax. Example in GHCi :info [] This parses as the Exact RdrName for nilDataCon, but we also want the list type constructor. Note that setRdrNameSpace on an Exact name requires the Name to be External, which it always is for built in syntax. -} {- ************************************************************************ * * Rebindable names Dealing with rebindable syntax is driven by the Opt_RebindableSyntax dynamic flag. In "deriving" code we don't want to use rebindable syntax so we switch off the flag locally * * ************************************************************************ Haskell 98 says that when you say "3" you get the "fromInteger" from the Standard Prelude, regardless of what is in scope. However, to experiment with having a language that is less coupled to the standard prelude, we're trying a non-standard extension that instead gives you whatever "Prelude.fromInteger" happens to be in scope. Then you can import Prelude () import MyPrelude as Prelude to get the desired effect. At the moment this just happens for * fromInteger, fromRational on literals (in expressions and patterns) * negate (in expressions) * minus (arising from n+k patterns) * "do" notation We store the relevant Name in the HsSyn tree, in * HsIntegral/HsFractional/HsIsString * NegApp * NPlusKPat * HsDo respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName, fromRationalName etc), but the renamer changes this to the appropriate user name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does. We treat the original (standard) names as free-vars too, because the type checker checks the type of the user thing against the type of the standard thing. -} lookupIfThenElse :: RnM (Maybe (SyntaxExpr GhcRn), FreeVars) -- Different to lookupSyntaxName because in the non-rebindable -- case we desugar directly rather than calling an existing function -- Hence the (Maybe (SyntaxExpr GhcRn)) return type lookupIfThenElse = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if not rebindable_on then return (Nothing, emptyFVs) else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse")) ; return ( Just (mkRnSyntaxExpr ite) , unitFV ite ) } } lookupSyntaxName' :: Name -- ^ The standard name -> RnM Name -- ^ Possibly a non-standard name lookupSyntaxName' std_name = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if not rebindable_on then return std_name else -- Get the similarly named thing from the local environment lookupOccRn (mkRdrUnqual (nameOccName std_name)) } lookupSyntaxName :: Name -- The standard name -> RnM (SyntaxExpr GhcRn, FreeVars) -- Possibly a non-standard -- name lookupSyntaxName std_name = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if not rebindable_on then return (mkRnSyntaxExpr std_name, emptyFVs) else -- Get the similarly named thing from the local environment do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name)) ; return (mkRnSyntaxExpr usr_name, unitFV usr_name) } } lookupSyntaxNames :: [Name] -- Standard names -> RnM ([HsExpr GhcRn], FreeVars) -- See comments with HsExpr.ReboundNames -- this works with CmdTop, which wants HsExprs, not SyntaxExprs lookupSyntaxNames std_names = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if not rebindable_on then return (map (HsVar noExtField . noLoc) std_names, emptyFVs) else do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names ; return (map (HsVar noExtField . noLoc) usr_names, mkFVs usr_names) } } -- Error messages opDeclErr :: RdrName -> SDoc opDeclErr n = hang (text "Illegal declaration of a type or class operator" <+> quotes (ppr n)) 2 (text "Use TypeOperators to declare operators in type and declarations") badOrigBinding :: RdrName -> SDoc badOrigBinding name | Just _ <- isBuiltInOcc_maybe occ = text "Illegal binding of built-in syntax:" <+> ppr occ -- Use an OccName here because we don't want to print Prelude.(,) | otherwise = text "Cannot redefine a Name retrieved by a Template Haskell quote:" <+> ppr name -- This can happen when one tries to use a Template Haskell splice to -- define a top-level identifier with an already existing name, e.g., -- -- $(pure [ValD (VarP 'succ) (NormalB (ConE 'True)) []]) -- -- (See #13968.) where occ = rdrNameOcc $ filterCTuple name
sdiehl/ghc
compiler/GHC/Rename/Env.hs
bsd-3-clause
69,555
89
28
19,638
8,933
4,626
4,307
752
13
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Install -- Copyright : (c) 2005 David Himmelstrup -- 2007 Bjorn Bringert -- 2007-2010 Duncan Coutts -- License : BSD-like -- -- Maintainer : cabal-devel@haskell.org -- Stability : provisional -- Portability : portable -- -- High level interface to package installation. ----------------------------------------------------------------------------- module Distribution.Client.Install ( install, upgrade, ) where import Data.List ( unfoldr, find, nub, sort ) import Data.Maybe ( isJust, fromMaybe ) import Control.Exception as Exception ( handleJust ) #if MIN_VERSION_base(4,0,0) import Control.Exception as Exception ( Exception(toException), catches, Handler(Handler), IOException ) import System.Exit ( ExitCode ) #else import Control.Exception as Exception ( Exception(IOException, ExitException) ) #endif import Distribution.Compat.Exception ( SomeException, catchIO, catchExit ) import Control.Monad ( when, unless ) import System.Directory ( getTemporaryDirectory, doesFileExist, createDirectoryIfMissing ) import System.FilePath ( (</>), (<.>), takeDirectory ) import System.IO ( openFile, IOMode(AppendMode) ) import System.IO.Error ( isDoesNotExistError, ioeGetFileName ) import Distribution.Client.Targets import Distribution.Client.Dependency import Distribution.Client.FetchUtils import qualified Distribution.Client.Haddock as Haddock (regenerateHaddockIndex) -- import qualified Distribution.Client.Info as Info import Distribution.Client.IndexUtils as IndexUtils ( getAvailablePackages, getInstalledPackages ) import qualified Distribution.Client.InstallPlan as InstallPlan import Distribution.Client.InstallPlan (InstallPlan) import Distribution.Client.Setup ( GlobalFlags(..) , ConfigFlags(..), configureCommand, filterConfigureFlags , ConfigExFlags(..), InstallFlags(..) ) import Distribution.Client.Config ( defaultCabalDir ) import Distribution.Client.Tar (extractTarGzFile) import Distribution.Client.Types as Available import Distribution.Client.BuildReports.Types ( ReportLevel(..) ) import Distribution.Client.SetupWrapper ( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions ) import qualified Distribution.Client.BuildReports.Anonymous as BuildReports import qualified Distribution.Client.BuildReports.Storage as BuildReports ( storeAnonymous, storeLocal, fromInstallPlan ) import qualified Distribution.Client.InstallSymlink as InstallSymlink ( symlinkBinaries ) import qualified Distribution.Client.Win32SelfUpgrade as Win32SelfUpgrade import qualified Distribution.Client.World as World import Paths_cabal_install (getBinDir) import Distribution.Simple.Compiler ( CompilerId(..), Compiler(compilerId), compilerFlavor , PackageDB(..), PackageDBStack ) import Distribution.Simple.Program (ProgramConfiguration, defaultProgramConfiguration) import qualified Distribution.Simple.InstallDirs as InstallDirs import qualified Distribution.Client.PackageIndex as PackageIndex import Distribution.Client.PackageIndex (PackageIndex) import Distribution.Simple.Setup ( haddockCommand, HaddockFlags(..), emptyHaddockFlags , buildCommand, BuildFlags(..), emptyBuildFlags , toFlag, fromFlag, fromFlagOrDefault, flagToMaybe ) import qualified Distribution.Simple.Setup as Cabal ( installCommand, InstallFlags(..), emptyInstallFlags ) import Distribution.Simple.Utils ( rawSystemExit, comparing ) import Distribution.Simple.InstallDirs as InstallDirs ( PathTemplate, fromPathTemplate, toPathTemplate, substPathTemplate , initialPathTemplateEnv, installDirsTemplateEnv ) import Distribution.Package ( PackageIdentifier, packageName, packageVersion , Package(..), PackageFixedDeps(..) , Dependency(..), thisPackageVersion ) import qualified Distribution.PackageDescription as PackageDescription import Distribution.PackageDescription ( PackageDescription ) import Distribution.PackageDescription.Configuration ( finalizePackageDescription ) import Distribution.Version ( Version, anyVersion, thisVersion ) import Distribution.Simple.Utils as Utils ( notice, info, debug, warn, die, intercalate, withTempDirectory ) import Distribution.Client.Utils ( inDir, mergeBy, MergeResult(..) ) import Distribution.System ( Platform, buildPlatform, OS(Windows), buildOS ) import Distribution.Text ( display ) import Distribution.Verbosity as Verbosity ( Verbosity, showForCabal, verbose ) import Distribution.Simple.BuildPaths ( exeExtension ) --TODO: -- * assign flags to packages individually -- * complain about flags that do not apply to any package given as target -- so flags do not apply to dependencies, only listed, can use flag -- constraints for dependencies -- * only record applicable flags in world file -- * allow flag constraints -- * allow installed constraints -- * allow flag and installed preferences -- * change world file to use cabal section syntax -- * allow persistent configure flags for each package individually -- ------------------------------------------------------------ -- * Top level user actions -- ------------------------------------------------------------ -- | Installs the packages needed to satisfy a list of dependencies. -- install, upgrade :: Verbosity -> PackageDBStack -> [Repo] -> Compiler -> ProgramConfiguration -> GlobalFlags -> ConfigFlags -> ConfigExFlags -> InstallFlags -> [UserTarget] -> IO () install verbosity packageDBs repos comp conf globalFlags configFlags configExFlags installFlags userTargets0 = do installed <- getInstalledPackages verbosity comp packageDBs conf availableDb <- getAvailablePackages verbosity repos let -- For install, if no target is given it means we use the -- current directory as the single target userTargets | null userTargets0 = [UserTargetLocalDir "."] | otherwise = userTargets0 pkgSpecifiers <- resolveUserTargets verbosity globalFlags (packageIndex availableDb) userTargets notice verbosity "Resolving dependencies..." installPlan <- foldProgress logMsg die return $ planPackages comp configFlags configExFlags installFlags installed availableDb pkgSpecifiers printPlanMessages verbosity installed installPlan dryRun unless dryRun $ do installPlan' <- performInstallations verbosity context installed installPlan postInstallActions verbosity context userTargets installPlan' where context :: InstallContext context = (packageDBs, repos, comp, conf, globalFlags, configFlags, configExFlags, installFlags) dryRun = fromFlag (installDryRun installFlags) logMsg message rest = debug verbosity message >> rest upgrade _ _ _ _ _ _ _ _ _ _ = die $ "Use the 'cabal install' command instead of 'cabal upgrade'.\n" ++ "You can install the latest version of a package using 'cabal install'. " ++ "The 'cabal upgrade' command has been removed because people found it " ++ "confusing and it often led to broken packages.\n" ++ "If you want the old upgrade behaviour then use the install command " ++ "with the --upgrade-dependencies flag (but check first with --dry-run " ++ "to see what would happen). This will try to pick the latest versions " ++ "of all dependencies, rather than the usual behaviour of trying to pick " ++ "installed versions of all dependencies. If you do use " ++ "--upgrade-dependencies, it is recommended that you do not upgrade core " ++ "packages (e.g. by using appropriate --constraint= flags)." type InstallContext = ( PackageDBStack , [Repo] , Compiler , ProgramConfiguration , GlobalFlags , ConfigFlags , ConfigExFlags , InstallFlags ) -- ------------------------------------------------------------ -- * Installation planning -- ------------------------------------------------------------ planPackages :: Compiler -> ConfigFlags -> ConfigExFlags -> InstallFlags -> PackageIndex InstalledPackage -> AvailablePackageDb -> [PackageSpecifier AvailablePackage] -> Progress String String InstallPlan planPackages comp configFlags configExFlags installFlags installed availableDb pkgSpecifiers = resolveDependencies buildPlatform (compilerId comp) resolverParams >>= if onlyDeps then adjustPlanOnlyDeps else return where resolverParams = setPreferenceDefault (if upgradeDeps then PreferAllLatest else PreferLatestForSelected) . addPreferences -- preferences from the config file or command line [ PackageVersionPreference name ver | Dependency name ver <- configPreferences configExFlags ] . addConstraints -- version constraints from the config file or command line [ PackageVersionConstraint name ver | Dependency name ver <- configConstraints configFlags ] . addConstraints --FIXME: this just applies all flags to all targets which -- is silly. We should check if the flags are appropriate [ PackageFlagsConstraint (pkgSpecifierTarget pkgSpecifier) flags | let flags = configConfigurationsFlags configFlags , not (null flags) , pkgSpecifier <- pkgSpecifiers ] . (if reinstall then reinstallTargets else id) $ standardInstallPolicy installed availableDb pkgSpecifiers --TODO: this is a general feature and should be moved to D.C.Dependency -- Also, the InstallPlan.remove should return info more precise to the -- problem, rather than the very general PlanProblem type. adjustPlanOnlyDeps :: InstallPlan -> Progress String String InstallPlan adjustPlanOnlyDeps = either (Fail . explain) Done . InstallPlan.remove isTarget where isTarget pkg = packageName pkg `elem` targetnames targetnames = map pkgSpecifierTarget pkgSpecifiers explain :: [InstallPlan.PlanProblem] -> String explain problems = "Cannot select only the dependencies (as requested by the " ++ "'--only-dependencies' flag), " ++ (case pkgids of [pkgid] -> "the package " ++ display pkgid ++ " is " _ -> "the packages " ++ intercalate ", " (map display pkgids) ++ " are ") ++ "required by a dependency of one of the other targets." where pkgids = nub [ depid | InstallPlan.PackageMissingDeps _ depids <- problems , depid <- depids , packageName depid `elem` targetnames ] reinstall = fromFlag (installReinstall installFlags) upgradeDeps = fromFlag (installUpgradeDeps installFlags) onlyDeps = fromFlag (installOnlyDeps installFlags) -- ------------------------------------------------------------ -- * Informational messages -- ------------------------------------------------------------ printPlanMessages :: Verbosity -> PackageIndex InstalledPackage -> InstallPlan -> Bool -> IO () printPlanMessages verbosity installed installPlan dryRun = do when nothingToInstall $ notice verbosity $ "No packages to be installed. All the requested packages are " ++ "already installed.\n If you want to reinstall anyway then use " ++ "the --reinstall flag." when (dryRun || verbosity >= verbose) $ printDryRun verbosity installed installPlan where nothingToInstall = null (InstallPlan.ready installPlan) printDryRun :: Verbosity -> PackageIndex InstalledPackage -> InstallPlan -> IO () printDryRun verbosity installed plan = case unfoldr next plan of [] -> return () pkgs | verbosity >= Verbosity.verbose -> notice verbosity $ unlines $ "In order, the following would be installed:" : map showPkgAndReason pkgs | otherwise -> notice verbosity $ unlines $ "In order, the following would be installed (use -v for more details):" : map (display . packageId) pkgs where next plan' = case InstallPlan.ready plan' of [] -> Nothing (pkg:_) -> Just (pkg, InstallPlan.completed pkgid result plan') where pkgid = packageId pkg result = BuildOk DocsNotTried TestsNotTried --FIXME: This is a bit of a hack, -- pretending that each package is installed showPkgAndReason pkg' = display (packageId pkg') ++ " " ++ case PackageIndex.lookupPackageName installed (packageName pkg') of [] -> "(new package)" ps -> case find ((==packageId pkg') . packageId) ps of Nothing -> "(new version)" Just pkg -> "(reinstall)" ++ case changes pkg pkg' of [] -> "" diff -> " changes: " ++ intercalate ", " diff changes pkg pkg' = map change . filter changed $ mergeBy (comparing packageName) (nub . sort . depends $ pkg) (nub . sort . depends $ pkg') change (OnlyInLeft pkgid) = display pkgid ++ " removed" change (InBoth pkgid pkgid') = display pkgid ++ " -> " ++ display (packageVersion pkgid') change (OnlyInRight pkgid') = display pkgid' ++ " added" changed (InBoth pkgid pkgid') = pkgid /= pkgid' changed _ = True -- ------------------------------------------------------------ -- * Post installation stuff -- ------------------------------------------------------------ -- | Various stuff we do after successful or unsuccessfully installing a bunch -- of packages. This includes: -- -- * build reporting, local and remote -- * symlinking binaries -- * updating indexes -- * updating world file -- * error reporting -- postInstallActions :: Verbosity -> InstallContext -> [UserTarget] -> InstallPlan -> IO () postInstallActions verbosity (packageDBs, _, comp, conf, globalFlags, configFlags, _, installFlags) targets installPlan = do unless oneShot $ World.insert verbosity worldFile --FIXME: does not handle flags [ World.WorldPkgInfo dep [] | UserTargetNamed dep <- targets ] let buildReports = BuildReports.fromInstallPlan installPlan BuildReports.storeLocal (installSummaryFile installFlags) buildReports when (reportingLevel >= AnonymousReports) $ BuildReports.storeAnonymous buildReports when (reportingLevel == DetailedReports) $ storeDetailedBuildReports verbosity logsDir buildReports regenerateHaddockIndex verbosity packageDBs comp conf configFlags installFlags installPlan symlinkBinaries verbosity configFlags installFlags installPlan printBuildFailures installPlan where reportingLevel = fromFlag (installBuildReports installFlags) logsDir = fromFlag (globalLogsDir globalFlags) oneShot = fromFlag (installOneShot installFlags) worldFile = fromFlag $ globalWorldFile globalFlags storeDetailedBuildReports :: Verbosity -> FilePath -> [(BuildReports.BuildReport, Repo)] -> IO () storeDetailedBuildReports verbosity logsDir reports = sequence_ [ do dotCabal <- defaultCabalDir let logFileName = display (BuildReports.package report) <.> "log" logFile = logsDir </> logFileName reportsDir = dotCabal </> "reports" </> remoteRepoName remoteRepo reportFile = reportsDir </> logFileName handleMissingLogFile $ do buildLog <- readFile logFile createDirectoryIfMissing True reportsDir -- FIXME writeFile reportFile (show (BuildReports.show report, buildLog)) | (report, Repo { repoKind = Left remoteRepo }) <- reports , isLikelyToHaveLogFile (BuildReports.installOutcome report) ] where isLikelyToHaveLogFile BuildReports.ConfigureFailed {} = True isLikelyToHaveLogFile BuildReports.BuildFailed {} = True isLikelyToHaveLogFile BuildReports.InstallFailed {} = True isLikelyToHaveLogFile BuildReports.InstallOk {} = True isLikelyToHaveLogFile _ = False handleMissingLogFile = Exception.handleJust missingFile $ \ioe -> warn verbosity $ "Missing log file for build report: " ++ fromMaybe "" (ioeGetFileName ioe) #if MIN_VERSION_base(4,0,0) missingFile ioe #else missingFile (IOException ioe) #endif | isDoesNotExistError ioe = Just ioe missingFile _ = Nothing regenerateHaddockIndex :: Verbosity -> [PackageDB] -> Compiler -> ProgramConfiguration -> ConfigFlags -> InstallFlags -> InstallPlan -> IO () regenerateHaddockIndex verbosity packageDBs comp conf configFlags installFlags installPlan | haddockIndexFileIsRequested && shouldRegenerateHaddockIndex = do defaultDirs <- InstallDirs.defaultInstallDirs (compilerFlavor comp) (fromFlag (configUserInstall configFlags)) True let indexFileTemplate = fromFlag (installHaddockIndex installFlags) indexFile = substHaddockIndexFileName defaultDirs indexFileTemplate notice verbosity $ "Updating documentation index " ++ indexFile --TODO: might be nice if the install plan gave us the new InstalledPackageInfo installed <- getInstalledPackages verbosity comp packageDBs conf Haddock.regenerateHaddockIndex verbosity installed conf indexFile | otherwise = return () where haddockIndexFileIsRequested = fromFlag (installDocumentation installFlags) && isJust (flagToMaybe (installHaddockIndex installFlags)) -- We want to regenerate the index if some new documentation was actually -- installed. Since the index is per-user, we don't do it for global -- installs or special cases where we're installing into a specific db. shouldRegenerateHaddockIndex = normalUserInstall && someDocsWereInstalled installPlan where someDocsWereInstalled = any installedDocs . InstallPlan.toList normalUserInstall = (UserPackageDB `elem` packageDBs) && all (not . isSpecificPackageDB) packageDBs installedDocs (InstallPlan.Installed _ (BuildOk DocsOk _)) = True installedDocs _ = False isSpecificPackageDB (SpecificPackageDB _) = True isSpecificPackageDB _ = False substHaddockIndexFileName defaultDirs = fromPathTemplate . substPathTemplate env where env = env0 ++ installDirsTemplateEnv absoluteDirs env0 = InstallDirs.compilerTemplateEnv (compilerId comp) ++ InstallDirs.platformTemplateEnv (buildPlatform) absoluteDirs = InstallDirs.substituteInstallDirTemplates env0 templateDirs templateDirs = InstallDirs.combineInstallDirs fromFlagOrDefault defaultDirs (configInstallDirs configFlags) symlinkBinaries :: Verbosity -> ConfigFlags -> InstallFlags -> InstallPlan -> IO () symlinkBinaries verbosity configFlags installFlags plan = do failed <- InstallSymlink.symlinkBinaries configFlags installFlags plan case failed of [] -> return () [(_, exe, path)] -> warn verbosity $ "could not create a symlink in " ++ bindir ++ " for " ++ exe ++ " because the file exists there already but is not " ++ "managed by cabal. You can create a symlink for this executable " ++ "manually if you wish. The executable file has been installed at " ++ path exes -> warn verbosity $ "could not create symlinks in " ++ bindir ++ " for " ++ intercalate ", " [ exe | (_, exe, _) <- exes ] ++ " because the files exist there already and are not " ++ "managed by cabal. You can create symlinks for these executables " ++ "manually if you wish. The executable files have been installed at " ++ intercalate ", " [ path | (_, _, path) <- exes ] where bindir = fromFlag (installSymlinkBinDir installFlags) printBuildFailures :: InstallPlan -> IO () printBuildFailures plan = case [ (pkg, reason) | InstallPlan.Failed pkg reason <- InstallPlan.toList plan ] of [] -> return () failed -> die . unlines $ "Error: some packages failed to install:" : [ display (packageId pkg) ++ printFailureReason reason | (pkg, reason) <- failed ] where printFailureReason reason = case reason of DependentFailed pkgid -> " depends on " ++ display pkgid ++ " which failed to install." DownloadFailed e -> " failed while downloading the package." ++ " The exception was:\n " ++ show e UnpackFailed e -> " failed while unpacking the package." ++ " The exception was:\n " ++ show e ConfigureFailed e -> " failed during the configure step." ++ " The exception was:\n " ++ show e BuildFailed e -> " failed during the building phase." ++ " The exception was:\n " ++ show e InstallFailed e -> " failed during the final install step." ++ " The exception was:\n " ++ show e -- ------------------------------------------------------------ -- * Actually do the installations -- ------------------------------------------------------------ data InstallMisc = InstallMisc { rootCmd :: Maybe FilePath, libVersion :: Maybe Version } performInstallations :: Verbosity -> InstallContext -> PackageIndex InstalledPackage -> InstallPlan -> IO InstallPlan performInstallations verbosity (packageDBs, _, comp, conf, globalFlags, configFlags, configExFlags, installFlags) installed installPlan = do executeInstallPlan installPlan $ \cpkg -> installConfiguredPackage platform compid configFlags cpkg $ \configFlags' src pkg -> fetchAvailablePackage verbosity src $ \src' -> installLocalPackage verbosity (packageId pkg) src' $ \mpath -> installUnpackedPackage verbosity (setupScriptOptions installed) miscOptions configFlags' installFlags compid pkg mpath useLogFile where platform = InstallPlan.planPlatform installPlan compid = InstallPlan.planCompiler installPlan setupScriptOptions index = SetupScriptOptions { useCabalVersion = maybe anyVersion thisVersion (libVersion miscOptions), useCompiler = Just comp, -- Hack: we typically want to allow the UserPackageDB for finding the -- Cabal lib when compiling any Setup.hs even if we're doing a global -- install. However we also allow looking in a specific package db. usePackageDB = if UserPackageDB `elem` packageDBs then packageDBs else let (db@GlobalPackageDB:dbs) = packageDBs in db : UserPackageDB : dbs, --TODO: use Ord instance: -- insert UserPackageDB packageDBs usePackageIndex = if UserPackageDB `elem` packageDBs then Just index else Nothing, useProgramConfig = conf, useDistPref = fromFlagOrDefault (useDistPref defaultSetupScriptOptions) (configDistPref configFlags), useLoggingHandle = Nothing, useWorkingDir = Nothing } reportingLevel = fromFlag (installBuildReports installFlags) logsDir = fromFlag (globalLogsDir globalFlags) useLogFile :: Maybe (PackageIdentifier -> FilePath) useLogFile = fmap substLogFileName logFileTemplate where logFileTemplate :: Maybe PathTemplate logFileTemplate --TODO: separate policy from mechanism | reportingLevel == DetailedReports = Just $ toPathTemplate $ logsDir </> "$pkgid" <.> "log" | otherwise = flagToMaybe (installLogFile installFlags) substLogFileName template pkg = fromPathTemplate . substPathTemplate env $ template where env = initialPathTemplateEnv (packageId pkg) (compilerId comp) miscOptions = InstallMisc { rootCmd = if fromFlag (configUserInstall configFlags) then Nothing -- ignore --root-cmd if --user. else flagToMaybe (installRootCmd installFlags), libVersion = flagToMaybe (configCabalVersion configExFlags) } executeInstallPlan :: Monad m => InstallPlan -> (ConfiguredPackage -> m BuildResult) -> m InstallPlan executeInstallPlan plan installPkg = case InstallPlan.ready plan of [] -> return plan (pkg: _) -> do buildResult <- installPkg pkg let plan' = updatePlan (packageId pkg) buildResult plan executeInstallPlan plan' installPkg where updatePlan pkgid (Right buildSuccess) = InstallPlan.completed pkgid buildSuccess updatePlan pkgid (Left buildFailure) = InstallPlan.failed pkgid buildFailure depsFailure where depsFailure = DependentFailed pkgid -- So this first pkgid failed for whatever reason (buildFailure). -- All the other packages that depended on this pkgid, which we -- now cannot build, we mark as failing due to 'DependentFailed' -- which kind of means it was not their fault. -- | Call an installer for an 'AvailablePackage' but override the configure -- flags with the ones given by the 'ConfiguredPackage'. In particular the -- 'ConfiguredPackage' specifies an exact 'FlagAssignment' and exactly -- versioned package dependencies. So we ignore any previous partial flag -- assignment or dependency constraints and use the new ones. -- installConfiguredPackage :: Platform -> CompilerId -> ConfigFlags -> ConfiguredPackage -> (ConfigFlags -> PackageLocation (Maybe FilePath) -> PackageDescription -> a) -> a installConfiguredPackage platform comp configFlags (ConfiguredPackage (AvailablePackage _ gpkg source) flags deps) installPkg = installPkg configFlags { configConfigurationsFlags = flags, configConstraints = map thisPackageVersion deps } source pkg where pkg = case finalizePackageDescription flags (const True) platform comp [] gpkg of Left _ -> error "finalizePackageDescription ConfiguredPackage failed" Right (desc, _) -> desc fetchAvailablePackage :: Verbosity -> PackageLocation (Maybe FilePath) -> (PackageLocation FilePath -> IO BuildResult) -> IO BuildResult fetchAvailablePackage verbosity src installPkg = do fetched <- checkFetched src case fetched of Just src' -> installPkg src' Nothing -> onFailure DownloadFailed $ fetchPackage verbosity src >>= installPkg installLocalPackage :: Verbosity -> PackageIdentifier -> PackageLocation FilePath -> (Maybe FilePath -> IO BuildResult) -> IO BuildResult installLocalPackage verbosity pkgid location installPkg = case location of LocalUnpackedPackage dir -> installPkg (Just dir) LocalTarballPackage tarballPath -> installLocalTarballPackage verbosity pkgid tarballPath installPkg RemoteTarballPackage _ tarballPath -> installLocalTarballPackage verbosity pkgid tarballPath installPkg RepoTarballPackage _ _ tarballPath -> installLocalTarballPackage verbosity pkgid tarballPath installPkg installLocalTarballPackage :: Verbosity -> PackageIdentifier -> FilePath -> (Maybe FilePath -> IO BuildResult) -> IO BuildResult installLocalTarballPackage verbosity pkgid tarballPath installPkg = do tmp <- getTemporaryDirectory withTempDirectory verbosity tmp (display pkgid) $ \tmpDirPath -> onFailure UnpackFailed $ do info verbosity $ "Extracting " ++ tarballPath ++ " to " ++ tmpDirPath ++ "..." let relUnpackedPath = display pkgid absUnpackedPath = tmpDirPath </> relUnpackedPath descFilePath = absUnpackedPath </> display (packageName pkgid) <.> "cabal" extractTarGzFile tmpDirPath relUnpackedPath tarballPath exists <- doesFileExist descFilePath when (not exists) $ die $ "Package .cabal file not found: " ++ show descFilePath installPkg (Just absUnpackedPath) installUnpackedPackage :: Verbosity -> SetupScriptOptions -> InstallMisc -> ConfigFlags -> InstallFlags -> CompilerId -> PackageDescription -> Maybe FilePath -- ^ Directory to change to before starting the installation. -> Maybe (PackageIdentifier -> FilePath) -- ^ File to log output to (if any) -> IO BuildResult installUnpackedPackage verbosity scriptOptions miscOptions configFlags installConfigFlags compid pkg workingDir useLogFile = -- Configure phase onFailure ConfigureFailed $ do setup configureCommand configureFlags -- Build phase onFailure BuildFailed $ do setup buildCommand' buildFlags -- Doc generation phase docsResult <- if shouldHaddock then (do setup haddockCommand haddockFlags return DocsOk) `catchIO` (\_ -> return DocsFailed) `catchExit` (\_ -> return DocsFailed) else return DocsNotTried -- Tests phase testsResult <- return TestsNotTried --TODO: add optional tests -- Install phase onFailure InstallFailed $ withWin32SelfUpgrade verbosity configFlags compid pkg $ do case rootCmd miscOptions of (Just cmd) -> reexec cmd Nothing -> setup Cabal.installCommand installFlags return (Right (BuildOk docsResult testsResult)) where configureFlags = filterConfigureFlags configFlags { configVerbosity = toFlag verbosity' } buildCommand' = buildCommand defaultProgramConfiguration buildFlags _ = emptyBuildFlags { buildDistPref = configDistPref configFlags, buildVerbosity = toFlag verbosity' } shouldHaddock = fromFlag (installDocumentation installConfigFlags) haddockFlags _ = emptyHaddockFlags { haddockDistPref = configDistPref configFlags, haddockVerbosity = toFlag verbosity' } installFlags _ = Cabal.emptyInstallFlags { Cabal.installDistPref = configDistPref configFlags, Cabal.installVerbosity = toFlag verbosity' } verbosity' | isJust useLogFile = max Verbosity.verbose verbosity | otherwise = verbosity setup cmd flags = do logFileHandle <- case useLogFile of Nothing -> return Nothing Just mkLogFileName -> do let logFileName = mkLogFileName (packageId pkg) logDir = takeDirectory logFileName unless (null logDir) $ createDirectoryIfMissing True logDir logFile <- openFile logFileName AppendMode return (Just logFile) setupWrapper verbosity scriptOptions { useLoggingHandle = logFileHandle , useWorkingDir = workingDir } (Just pkg) cmd flags [] reexec cmd = do -- look for our on executable file and re-exec ourselves using -- a helper program like sudo to elevate priviledges: bindir <- getBinDir let self = bindir </> "cabal" <.> exeExtension weExist <- doesFileExist self if weExist then inDir workingDir $ rawSystemExit verbosity cmd [self, "install", "--only" ,"--verbose=" ++ showForCabal verbosity] else die $ "Unable to find cabal executable at: " ++ self -- helper onFailure :: (SomeException -> BuildFailure) -> IO BuildResult -> IO BuildResult onFailure result action = #if MIN_VERSION_base(4,0,0) action `catches` [ Handler $ \ioe -> handler (ioe :: IOException) , Handler $ \exit -> handler (exit :: ExitCode) ] where handler :: Exception e => e -> IO BuildResult handler = return . Left . result . toException #else action `catchIO` (return . Left . result . IOException) `catchExit` (return . Left . result . ExitException) #endif -- ------------------------------------------------------------ -- * Wierd windows hacks -- ------------------------------------------------------------ withWin32SelfUpgrade :: Verbosity -> ConfigFlags -> CompilerId -> PackageDescription -> IO a -> IO a withWin32SelfUpgrade _ _ _ _ action | buildOS /= Windows = action withWin32SelfUpgrade verbosity configFlags compid pkg action = do defaultDirs <- InstallDirs.defaultInstallDirs compFlavor (fromFlag (configUserInstall configFlags)) (PackageDescription.hasLibs pkg) Win32SelfUpgrade.possibleSelfUpgrade verbosity (exeInstallPaths defaultDirs) action where pkgid = packageId pkg (CompilerId compFlavor _) = compid exeInstallPaths defaultDirs = [ InstallDirs.bindir absoluteDirs </> exeName <.> exeExtension | exe <- PackageDescription.executables pkg , PackageDescription.buildable (PackageDescription.buildInfo exe) , let exeName = prefix ++ PackageDescription.exeName exe ++ suffix prefix = substTemplate prefixTemplate suffix = substTemplate suffixTemplate ] where fromFlagTemplate = fromFlagOrDefault (InstallDirs.toPathTemplate "") prefixTemplate = fromFlagTemplate (configProgPrefix configFlags) suffixTemplate = fromFlagTemplate (configProgSuffix configFlags) templateDirs = InstallDirs.combineInstallDirs fromFlagOrDefault defaultDirs (configInstallDirs configFlags) absoluteDirs = InstallDirs.absoluteInstallDirs pkgid compid InstallDirs.NoCopyDest templateDirs substTemplate = InstallDirs.fromPathTemplate . InstallDirs.substPathTemplate env where env = InstallDirs.initialPathTemplateEnv pkgid compid
yihuang/cabal-install
Distribution/Client/Install.hs
bsd-3-clause
35,968
0
20
9,901
6,585
3,443
3,142
627
9
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Snaplet.Authentication.Schema where import Control.Lens (view) import Control.Monad import Control.Monad.IO.Class import Crypto.BCrypt import Data.Aeson.TH (deriveJSON) import Data.Text hiding (head) import Data.Text.Encoding import Data.Time.Clock import Database.Esqueleto import Database.Persist.TH import GHC.Generics (Generic) import Kashmir.Aeson import Kashmir.Database.Postgresql import Snaplet.Authentication.Types import Kashmir.Email import Kashmir.Github as Github import Kashmir.UUID import Prelude hiding (id) share [mkPersist sqlSettings, mkMigrate "migrateAccounts"] [persistLowerCase| Account accountId UUID sqltype=uuid created UTCTime Primary accountId deriving Read Show Eq Generic AccountUidpwd accountId UUID sqltype=uuid email Email sqltype=text password Text sqltype=text Primary email UniqueEmail email deriving Read Show Eq Generic AccountGithub githubUserLogin Text sqltype=text accountId AccountId sqltype=uuid accessToken AccessToken sqltype=text Primary accountId Unique GithubUserUnique githubUserLogin deriving Read Show Eq Generic |] $(deriveJSON (dropPrefixJSONOptions "account") ''Account) -- TODO Update more details. createOrUpdateGithubUser :: UUID -> UTCTime -> AccessToken -> GithubUser -> SqlPersistM (Key Account) createOrUpdateGithubUser uuid created theToken githubUser = let savepointName = "upsert_github" in do void $ createSavepoint savepointName accountKey <- insert $ Account uuid created maybeGithubKey <- insertUnlessDuplicate AccountGithub { accountGithubAccountId = accountKey , accountGithubGithubUserLogin = view githubUserLogin githubUser , accountGithubAccessToken = theToken } case maybeGithubKey of Just _ -> releaseSavepoint savepointName >> return accountKey Nothing -> do let match g = where_ (g ^. AccountGithubGithubUserLogin ==. val (view githubUserLogin githubUser)) void $ rollbackToSavepoint savepointName update $ \g -> do set g [ AccountGithubAccessToken =. val theToken , AccountGithubGithubUserLogin =. val (view githubUserLogin githubUser) ] match g accountIds <- select . from $ \g -> do match g return (g ^. AccountGithubAccountId) return . unValue . head $ accountIds -- TODO This should handle failed inserts somehow. createPasswordUser :: UUID -> UTCTime -> Registration -> SqlPersistM (Maybe Account) createPasswordUser uuid created payload = do Just hashedPassword <- liftIO $ hashPasswordUsingPolicy fastBcryptHashingPolicy (encodeUtf8 (registrationPassword payload)) let account = Account uuid created let accountUidpwd = AccountUidpwd { accountUidpwdAccountId = uuid , accountUidpwdEmail = registrationEmail payload , accountUidpwdPassword = decodeUtf8 hashedPassword } insertBy accountUidpwd >>= \case Left existingEntity -> return Nothing Right _ -> do _ <- insert account return $ Just account
krisajenkins/snaplet-auth
src/Snaplet/Authentication/Schema.hs
bsd-3-clause
4,033
0
23
1,113
668
347
321
95
2
-- WettedArea.hs {-# OPTIONS_GHC -Wall #-} module Aero.Drag.WettedArea( wettedArea , wingWettedArea , grossFuseWettedArea , paraboloidArea , cylinderArea , printWettedArea ) where import Design.Config(Config(..)) import Warn(warn) wettedArea :: Floating a => Config a -> a wettedArea config@(Config { exposedWingArea_ft2 = wingArea , thicknessToChordRatio = tOverC }) = warn msg totalWettedArea where msg = "WARNING: wetted area neglecting tail" wingWettedArea' = wingWettedArea wingArea tOverC grossFuseWettedArea' = grossFuseWettedArea config totalWettedArea = wingWettedArea' + grossFuseWettedArea' grossFuseWettedArea :: Floating a => Config a -> a grossFuseWettedArea (Config { diameter_feet = diameter , totalLength_feet = overallLength , noseFineness = fNose , tailFineness = fTail }) = noseArea + tailArea + centerArea where centerLength = overallLength - diameter*fNose - diameter*fTail noseArea = paraboloidArea diameter fNose tailArea = paraboloidArea diameter fTail centerArea = cylinderArea diameter centerLength wingWettedArea :: Fractional a => a -> a -> a wingWettedArea wingArea tOverC = 2.0*(1 + 0.2*tOverC)*wingArea --coneSectionArea d0 d1 h0 -- | d0 == d1 = 2*pi*r0*h0 -- | d0 > d1 = area d0 d1 -- | otherwise = area d1 d0 -- where -- area d0 d1 = sTotal - s1 -- -- r0 = 0.5*d0 -- r1 = 0.5*d1 -- h1 = h0*r1/(r0 - r1) -- sTotal = pi*r0*sqrt( r0^2 + (h0+h1)^2 ) -- s1 = pi*r1*sqrt( r1^2 + h1^2 ) cylinderArea :: Floating a => a -> a -> a cylinderArea d h = pi*d*h paraboloidArea :: Floating a => a -> a -> a paraboloidArea d fineness = pi*r/(6*h*h)*( (r*r + 4*h*h)**(3/2) - r*r*r ) where r = 0.5*d h = fineness*d printWettedArea :: (Show a, Floating a) => Config a -> IO () printWettedArea (Config { diameter_feet = diameter , totalLength_feet = overallLength , noseFineness = fNose , tailFineness = fTail , exposedWingArea_ft2 = wingArea , thicknessToChordRatio = tOverC }) = do let centerLength = overallLength - diameter*fNose - diameter*fTail noseArea = paraboloidArea diameter fNose tailArea = paraboloidArea diameter fTail centerArea = cylinderArea diameter centerLength totalFuseArea = noseArea + tailArea + centerArea wingWettedArea' = wingWettedArea wingArea tOverC totalWettedArea = totalFuseArea + wingWettedArea' putStrLn $ "nose cone area: " ++ show noseArea ++ " ft^2" putStrLn $ "tail cone area: " ++ show tailArea ++ " ft^2" putStrLn $ "main fuse area: " ++ show centerArea ++ " ft^2" putStrLn $ "total fuselage area: " ++ show totalFuseArea ++ " ft^2" putStrLn "" putStrLn $ "wing wetted area: " ++ show wingWettedArea' ++ " ft^2" putStrLn $ "total wetted area: " ++ show totalWettedArea ++ " ft^2"
ghorn/conceptual-design
Aero/Drag/WettedArea.hs
bsd-3-clause
3,273
0
15
1,050
756
402
354
57
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module MateVMRuntime.GenerationalGC where import Foreign import qualified Foreign.Marshal.Alloc as Alloc import Control.Monad.State import qualified Data.Map as M import Data.Map(Map,(!)) import qualified Data.Set as S import Data.List import MateVMRuntime.BlockAllocation import MateVMRuntime.GC import MateVMRuntime.Debug import MateVMRuntime.MemoryManager import MateVMRuntime.RtsOptions import qualified MateVMRuntime.StackTrace as T maxGen :: Int maxGen = 2 -- means 0,1,2 instance AllocationManager GcState where initMemoryManager = initGen mallocBytesT = mallocBytesGen performCollection = collectGen collectLoh = collectLohTwoSpace heapSize = error "heap size in GenGC not implemented" validRef = error "valid ref in GenGC not implemented" initGen :: Int -> IO GcState initGen size' = do freshAllocState <- mkAllocC size' return GcState { generations = foldr (\i m -> M.insert i (generation' i) m) M.empty [0..maxGen], allocs = 0, allocatedBytes = 0 , loh = S.empty, allocState = freshAllocState } where generation' i = GenState { freeBlocks = [], activeBlocks = M.empty, collections = 0, generation = i } mallocBytesGen :: GenInfo -> Int -> StateT GcState IO (Ptr b) mallocBytesGen gen size' = if size' > loThreshhold then allocateLoh size' else do ptr <- runBlockAllocatorC gen size' current <- get put $ current { allocs = 1 + allocs current } logGcT $ printf "object got: %s\n" (show ptr) return ptr allocateLoh :: Int -> StateT GcState IO (Ptr b) allocateLoh size' = do current <- get let currentLoh = loh current ptr <- liftIO $ Alloc.mallocBytes size' put $ current { loh = S.insert (ptrToIntPtr ptr) currentLoh } liftIO $ printfGc $ printf "LOH: allocated %d bytes in loh %s" size' (show ptr) return ptr collectLohTwoSpace :: (RefObj a) => [a] -> StateT GcState IO () collectLohTwoSpace xs = do current <- get intptrs <- liftIO $ mapM getIntPtr xs let oldLoh = loh current let newSet = S.fromList intptrs let toRemove = oldLoh `S.difference` newSet liftIO $ printfGc $ printf "objs in loh: %d" (S.size oldLoh) liftIO $ printfGc $ printf "old loh: %s" (show $ showRefs $ S.toList oldLoh) liftIO $ printfGc $ printf "to remove: %s" (show $ showRefs $ S.toList toRemove) liftIO $ mapM (free . intPtrToPtr) (S.toList toRemove) put current { loh = newSet } -- given an element in generation x -> where to evaucuate to sourceGenToTargetGen :: Int -> Int sourceGenToTargetGen 0 = 1 sourceGenToTargetGen 1 = 2 sourceGenToTargetGen 2 = 2 sourceGenToTargetGen x = error $ "source object is in strange generation: " ++ show x collectGen :: (RefObj b) => Map b RefUpdateAction -> StateT GcState IO () collectGen roots = do cnt <- liftM allocs get performCollectionGen (calculateGeneration cnt) roots --performCollectionGen Nothing roots calculateGeneration :: Int -> Maybe Int calculateGeneration x | x < 20 = Nothing | x < 50 = Just 0 | x < 60 = Just 1 | otherwise = Just 2 performCollectionGen :: (RefObj b) => Maybe Int -> Map b RefUpdateAction -> StateT GcState IO () performCollectionGen Nothing _ = logGcT "skipping GC. not necessary atm. tune gc settings if required" performCollectionGen (Just generation') roots = do current <- get put current { allocs = 0 } logGcT $ printf "!!! runn gen%d collection" generation' let rootList = map fst $ M.toList roots logGcT $ printf "rootSet: %s\n " (show rootList) toKill <- performCollectionGen' generation' rootList logGcT "patch gc roots.." liftIO $ patchGCRoots roots logGcT "all done \\o/" freeGensIOC toKill buildPatchAction :: [T.StackDescription] -> [IntPtr] -> IO (Map (Ptr b) RefUpdateAction) buildPatchAction [] _ = return M.empty buildPatchAction stack roots = do let rootsOnStack = roots ++ concatMap T.candidates stack rootCandidates <- mapM dereference rootsOnStack let realRoots = filter ((/= 0) . snd) rootCandidates return $ foldr buildRootPatcher2 M.empty realRoots buildRootPatcher2 :: (IntPtr,IntPtr) -> Map (Ptr b) RefUpdateAction -> Map (Ptr b) RefUpdateAction buildRootPatcher2 (ptr,obj) = M.insertWith both ptr' patch where patch newLocation = do printfGc $ printf "patch new ref: 0x%08x on stackloc: 0x%08x .. " (fromIntegral newLocation :: Int) (fromIntegral ptr :: Int) poke (intPtrToPtr ptr) newLocation printfPlain "=>patched.\n" ptr' = intPtrToPtr obj both newPatch oldPatch newLocation = do newPatch newLocation oldPatch newLocation replaceIndices :: Eq a => [Int] -> Map Int a -> (Int -> a) -> Map Int a replaceIndices indices m repl = foldr replace m indices where replace index = M.insert index (repl index) takeIndices :: Map Int a -> [Int] -> [a] takeIndices xs = map (\x -> xs!x) switchStates :: Int -> StateT GcState IO [GenState] switchStates collection = do let toBeReplaced = [0..collection] --all collections up to collection should be replaced by empty ones current <- get let gens = generations current let newGens = replaceIndices toBeReplaced gens mkGenState logGcT $ printf "new generations: %s" (show newGens) put current { generations = newGens } logGcT $ printf "generations to be killed: %s" (show toBeReplaced) return $ takeIndices gens toBeReplaced performCollectionGen' :: (RefObj a) => Int -> [a] -> StateT GcState IO [GenState] performCollectionGen' collection refs' = do toKill <- switchStates collection logGcT "==>Phase 1. Marking..\n" objFilter <- markedOrInvalid allLifeRefs <- liftIO $ liftM (nub . concat) $ mapM (markTree'' objFilter mark refs') refs' logGcT "==>Done Phase 1.\n" toEvacuate <- liftIO $ filterM (getIntPtr >=> return . hasMTable) allLifeRefs if gcLogEnabled then liftIO $ mapM_ (getIntPtr >=> \x -> printfGc $ printf " 0x%08x" (fromIntegral x ::Int) ) toEvacuate else return () (largeObjs,lifeRefs) <- liftIO $ extractLargeObjects toEvacuate logGcT "\nPhase 2. Evacuating...\n" evacuate' (\objGen -> targetGen objGen <= collection) getRefInfo lifeRefs logGcT "Phase 2. Done.\n" if useLoh then do logGcT "killing unsued large objs\n" collectLoh largeObjs logGcT "cleaned up loh\n" else return (); liftIO $ patchAllRefs (getIntPtr >=> \x -> return $ x /= 0) lifeRefs logGcT "patched2.\n" return toKill getRefInfo :: (RefObj a) => a -> IO GenInfo getRefInfo obj = do intPtr <- getIntPtr obj let begin = shift (shift intPtr (-blockSizePowerOfTwo)) blockSizePowerOfTwo generation' <- peek (intPtrToPtr begin) printfGc $ printf "got a reference in generation: %d\n" generation' return GenInfo { targetGen = min 2 generation' }
LouisJenkinsCS/Minimal-JVM
MateVMRuntime/GenerationalGC.hs
bsd-3-clause
7,339
0
16
1,924
2,157
1,056
1,101
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} -------------------------------------------------------------------------- -- | -- Module: Game.Waddle.Types -- Copyright: (c) 2015 Martin Grabmueller -- License: BSD3 -- -- Maintainer: martin@grabmueller.de -- Stability: provisional -- Portability: portable -- -- All public data types used by the Waddle library. The 'Wad' type -- is a good entry point into understanding the types. -- -- I recommend the Unofficial Doom Specification by Matthew S Fell, -- available at <http://aiforge.net/test/wadview/dmspec16.txt> and the -- Doom Wiki at <http://doomwiki.org> for details. ---------------------------------------------------------------------------- module Game.Waddle.Types ( -- * Exceptions WadException(..), -- * WAD file structures Wad(..), LumpName, WadHeader(..), WadEntry(..), -- * Sprites and textures Sprite(..), Picture(..), Post(..), Texture(..), Patch(..), PatchDescriptor(..), Flat(..), -- * Palettes and colormaps Colormap(..), Palettes(..), -- * Level geometry and details Level(..), Thing(..), ThingType(..), thingTypeFromNumber, Vertex(..), SideDef(..), LineDef(..), Sector(..), Node(..), SSector(..), Seg(..), Reject(..), Blocklist, Blockmap(..) ) where import Control.Exception import Data.Typeable import Data.Int import Data.Word import Data.ByteString(ByteString) import Data.CaseInsensitive(CI) import Data.Map(Map) -- | Exception thrown when reading and decoding WAD files. -- data WadException = WadExceptionFormatError String String -- ^ General WAD file format error. The first string is the -- context where the error occured, the second contains details on -- the error. | WadExceptionDecodeError String String -- ^ Decoding of the general WAD format or individual lumps -- failed. The first string is the context where the error -- occured, the second contains details on the error. deriving (Eq, Show, Typeable) instance Exception WadException -- | WAD structure, including the file contents and decoded common -- lumps. -- data Wad = Wad { wadHeader :: WadHeader, -- ^ WAD header. wadDirectory :: [WadEntry], -- ^ All WAD directory entries, in the same order as in the file. wadLumps :: [ByteString], -- ^ All WAD lumps, each entry matching the corresponding entry in wadDirectory. wadLumpLookup :: Map (CI LumpName) ByteString, -- ^ Mapping from lump names to lump content. wadFlats :: Map (CI LumpName) Flat, -- ^ Mapping from lump names to flats (floors and ceilings). wadSprites :: Map (CI LumpName) Sprite, -- ^ Mapping from lump names to sprites (monsters and things). wadPatches :: Map (CI LumpName) Patch, -- ^ Mapping from lump names to patches (parts of wall textures). wadTextures :: Map (CI LumpName) Texture, -- ^ Mapping from lump names to wall textures. wadLevels :: Map (CI LumpName) Level, -- ^ Mapping from lump names to levels. wadPNames :: Map Int LumpName, -- ^ Mapping from patch indices to patch names. wadColormap :: Maybe Colormap, -- ^ WAD colormap for mapping palette entries according to light -- levels. wadPalettes :: Maybe Palettes -- ^ Palettes for mapping color indices to RGB tuples. } -- | WAD file header. -- data WadHeader = WadHeader { wadHeaderIdentifier :: ByteString, -- ^ Normally \"IWAD\" or \"PWAD\", always of length 4. wadHeaderLumpCount :: Int32, -- ^ Number of lumps in the file. wadHeaderDirectoryOffset :: Int32 -- ^ Byte offset (relative to beginning of the file) of the WAD -- directory. } -- | Entry in WAd directory. -- data WadEntry = WadEntry { wadEntryOffset :: Int32, -- ^ Offset of the lump data in the file. wadEntrySize :: Int32, -- ^ Size (in bytes) of the lump data. wadEntryName :: ByteString -- ^ Name of the lump. Note that trailing NULs are stripped when the -- name is read in. } -- | Lump name. This is at mot 8 bytes long, and internally, all -- trailing NULs are stripped. -- type LumpName = ByteString -- | One level. -- data Level = Level { levelName :: LumpName, -- ^ Level name, E?M? style for DOOM 1 maps, MAP?? for DOOM 2 maps. levelThings :: [Thing], -- ^ List of things that are to be placed in the level on start. levelVertices :: [Vertex], -- ^ List of vertices referenced by linedefs, segs, etc. levelLineDefs :: [LineDef], -- ^ List of linedefs. levelSideDefs :: [SideDef], -- ^ List of sidedefs. levelSegs :: [Seg], -- ^ List of segs (parts of linedefs referenced in BSP tree. levelSSectors :: [SSector], -- ^ List of ssectors (sub-sectors), created from sectors during BSP -- building. A ssector is made up of segs. levelSectors :: [Sector], -- ^ List of sectors of the level. levelNodes :: [Node], -- ^ BSP tree nodes. levelReject :: Maybe Reject, -- ^ Reject bitmap. Used for determining whether one sector can be -- seen from another. levelBlockmap :: Maybe Blockmap -- ^ Blockmap. For each block of the map, lists the linedefs -- intersecting that block. Used for actor-wall collision -- detection. } -- | Picture. Sprites and wall patches are stored in this format. -- data Picture = Picture { pictureWidth :: Int, -- ^ Width of the picture. pictureHeight :: Int, -- ^ Height of the picture. pictureLeftOffset :: Int, -- ^ Offset of the left side to the origin of the picture. pictureTopOffset :: Int, -- ^ Offset of the top to the origin of the picture. picturePosts :: [[Post]] -- ^ Each element in this list is a column, where each column is a -- list of posts. } -- | A 'Post' is a part of a column. There can (and often will) be -- gaps in columns for transparent parts in sprites and walls. -- data Post = Post { postTop :: Word8, -- ^ Where to start drawing this part of the column. postPixels :: ByteString -- ^ Pixels of this post. The length of this field defines how -- many pixels to draw. } deriving (Show) -- | Sprites are used for players, monsters, and things in general. -- data Sprite = Sprite { spriteName :: LumpName, -- ^ Lump name for this sprite. spritePicture :: Picture -- ^ Picture for the sprite. It is drawn relative to the thing's -- position. } -- | Flats are images for texturing floors and ceiling. -- data Flat = Flat { flatName :: LumpName, -- ^ Name of this flat. flatData :: ByteString -- ^ Always 64 x 64 = 4096 bytes. } -- | A wall patch. Wall textures are made up of one or more patches, -- which are positioned as defined by the patch descriptors in the -- 'Texture' value. -- data Patch = Patch { patchName :: LumpName, -- ^ Name of this patch. patchPicture :: Picture -- ^ Picture for the patch. The offsets in the picture are ignored, -- because positioning is defined in the patch descriptor -- referencing this patch. } -- | Things are parts of levels. When a level is loaded, the things -- define where to place players, monsters, items and so on. -- data Thing = Thing { thingX :: Int16, -- ^ X position of the thing. thingY :: Int16, -- ^ Y position of the thing. thingAngle :: Int16, -- ^ Angle the thing is looking at when created. This only affects -- things that have a direction, such as players and monsters. thingType :: ThingType, -- ^ Kind of thing. thingFlags :: Int16 -- ^ Flags of the thing. Not decoded yet. } -- | A vertex defines the X\/Y coordinates of linedefs, segs etc. -- -- They are referenced by their position in the VERTEXES lump of the -- level they are used in. data Vertex = Vertex { vertexX :: Int16, -- ^ X coordinate. vertexY :: Int16 -- ^ Y coordinate. } -- | Linedefs make up the geometry of a level and additionally define -- most of the interactivity. -- data LineDef = LineDef { lineDefStartVertex :: Int16, -- ^ The linedef starts at the vertex with this index, lineDefEndVertex :: Int16, -- ^ ... and ends at the vertex with this index. lineDefFlags :: Int16, -- ^ Linedef flags. Not decoded yet. lineDefEffect :: Int16, -- ^ Linedef effect. Not decoded yet. lineDefTag :: Int16, -- ^ Linedef tag. Triggers on this linedef affect sectors witht the -- same tag. lineDefRightSideDef :: Int16, -- ^ Right sidedef of this linedef. Defines textures and sector -- this linedef is connected to. lineDefLeftSideDef :: Maybe Int16 -- ^ For two-sided linedefs, this is the left side. } -- | A sidedef defines the textures to use on walls and to what sector -- the wall is connected. -- -- Linedefs can have one or two sidedefs. data SideDef = SideDef { sideDefXOffset :: Int16, -- ^ X offset of the sidedef. sideDefYOffset :: Int16, -- ^ Y offset of the sidedef. sideDefUpperTextureName :: ByteString, -- ^ Name of upper texture. sideDefLowerTextureName :: ByteString, -- ^ Name of lower texture. sideDefMiddleTextureName :: ByteString, -- ^ Name of middle texture. sideDefSector :: Int16 -- ^ Index of sector this sidedef faces. } -- | Segs are split up linedefs that are produced by the BSP -- construction process. Whenever a BSP node splits a linedef, two -- segs are created representing both sides of the split. -- data Seg = Seg { segStartVertex :: Int16, -- ^ Index of start vertex. segEndVertex :: Int16, -- ^ Index of end vertex. segAngle :: Int16, -- ^ Angle of the seg. segLineDef :: Int16, -- ^ Index of linedef this seg is part of. segDirection :: Int16, -- ^ 0 if seg is in same diretion as linedef, 1 otherwise. segOffset :: Int16 -- ^ Offset of the seg relative to the linedef. } -- | A SSector (sub-sector?) is also produced by the BSP construction -- process. All sectors are split into ssectors (convex polygons). -- data SSector = SSector { ssectorSegCount :: Int16, -- ^ Number of segs that make up this ssector. ssectorSegStart :: Int16 -- ^ Index of first seg of this sector. } -- | Sectors are defined by enclosing linedefs, and the properties -- below. In WADs, each region of a map with different ceiling or -- floor heights or textures, or different specials and tags need to -- be their own sectors. -- data Sector = Sector { sectorFloorHeight :: Int16, -- ^ Height of floor. sectorCeilingHeight :: Int16, -- ^ Height of ceiling. sectorFloorFlat :: LumpName, -- ^ Name of flat for floor texturing. sectorCeilingFlat :: LumpName, -- ^ Name of flat for ceiling texturing. sectorLightLevel :: Int16, -- ^ Light level of sector. Used as index in COLORMAP for darkening -- colors. sectorSpecial :: Int16, -- ^ Sector special. Not decoded yet. sectorTag :: Int16 -- ^ Sector tag. Not decoded yet. } -- | Node of the BSP tree. This is created by the BSP construction -- process and is used to speed up rendering. -- data Node = Node { nodeX :: Int16, -- ^ X position of start of node line. nodeY :: Int16, -- ^ Y position of start of node line. nodeDX :: Int16, -- ^ Delta X for end of node line. nodeDY :: Int16, -- ^ Delta Y for end of node line. nodeRightBBUY :: Int16, -- ^ Upper Y coordinate of right bounding box. nodeRightBBLY :: Int16, -- ^ Lower Y coordinate of right bounding box. nodeRightBBLX :: Int16, -- ^ Lower X coordinate of right bounding box. nodeRightBBUX :: Int16, -- ^ Upper X coordinate of right bounding box. nodeLeftBBUY :: Int16, -- ^ Upper Y coordinate of left bounding box. nodeLeftBBLY :: Int16, -- ^ Lower Y coordinate of left bounding box. nodeLeftBBLX :: Int16, -- ^ Lower X coordinate of left bounding box. nodeLeftBBUX :: Int16, -- ^ Upper X coordinate of left bounding box. nodeRightNodeOrSSector :: Either Int16 Int16, -- ^ When Left, index of right recursive node, when Right index of -- right ssector. nodeLeftNodeOrSSector :: Either Int16 Int16 -- ^ When Left, index of left recursive node, when Right index of -- left ssector. } -- | Reject array. This is a bit map and not decoded yet. -- data Reject = Reject { rejectBytes :: ByteString } -- | Blocklist is a list of linedef indices. -- type Blocklist = [Int16] -- | Blockmap, determines which blocks intersect with linedefs. -- data Blockmap = Blockmap { blockmapOriginX :: Int16, -- ^ X origin in level coordinates. blockmapOriginY :: Int16, -- ^ Y origin in level coordinates. blockmapColumns :: Int16, -- ^ Number of columns. blockmapRows :: Int16, -- ^ Number of rows. blockmapBlocklists :: [Blocklist] -- ^ Blocklists for all blocks, left-to-right, bottom-to-top in -- level coordinates. } -- | 14 palettes, each a list of 256 RGB tuples. -- data Palettes = Palettes [[(Word8, Word8, Word8)]] -- | Colormap contains 34 maps, 256 bytes each. -- data Colormap = Colormap [ByteString] -- | Patch descriptor. -- data PatchDescriptor = PatchDescriptor { patchDescriptorXOffset :: Int16, -- ^ X offset in wall coordinate system for this patch. patchDescriptorYOffset :: Int16, -- ^ Y offset in wall coordinate system for this patch. patchDescriptorPNameIndex :: Int16, -- ^ Index in PNAMES of the picture to use. patchDescriptorStepDir :: Int16, -- ^ Documented in UDS, but usage unknown. patchDescriptorColorMap :: Int16 -- ^ Documented in UDS, but usage unknown. } -- | Wall texture. -- data Texture = Texture { textureName :: LumpName, -- ^ Name of the texture. textureWidth :: Int16, -- ^ Texture width. textureHeight :: Int16, -- ^ Texture height. texturePatchDescriptors :: [PatchDescriptor] -- ^ List of patches, in the order they appear in the WAD. } -- | All supported thing types. Unrecogized types are encoded as -- 'ThingTypeOther'. -- data ThingType = ZeroThing -- Appears in PLUTONIA.WAD | Player1StartPos | Player2StartPos | Player3StartPos | Player4StartPos | DeathMatchStartPos | FormerHuman | WolfensteinOfficer | FormerHumanSergeant | FormerHumanCommando | Imp | Demon | Spectre | LostSoul | Cacodemon | HellKnight | BaronOfHell | Arachnotron | PainElemental | Revenant | Mancubus | ArchVile | Spiderdemon | Cyberdemon | BossBrain | TeleportLanding | BossShooter | SpawnSpot | Chainsaw | Shotgun | SuperShotgun | Chaingun | RocketLauncher | Plasmagun | BFG9000 | AmmoClip | ShotgunShells | Rocket | CellCharge | BoxOfAmmo | BoxOfShells | BoxOfRockets | CellChargePack | Backpack | StimPack | Medikit | HealthPotion | SpiritArmor | SecurityArmor | CombatArmor | MegaSphere | SoulSphere | Invulnerability | BerserkPack | Invisibility | RadiationSuit | ComputerMap | LightAmplificationGoggles | BlueKeyCard | RedKeyCard | YellowKeyCard | BlueSkullKey | RedSkullKey | YellowSkullKey | Barrel | BurningBarrel | Candle | Candelabra | TallTechnocolumn | TallGreenPillar | TallRedPillar | ShortGreenPillar | ShortGreenPillarWithHeart | ShortGreenPillarWithBeatingHeart | ShortRedPillar | ShortRedPillarWithSkull | Stalagmite | BurntGrayTree | LargeBrownTree | TallBlueFirestick | TallGreenFirestick | TallRedFirestick | ShortBlueFirestick | ShortGreenFirestick | ShortRedFirestick | FloorLamp | TallTechnoLamp | ShortTechnoLamp | EvilEyeSymbol | FlamingSkullRock | ImpaledHuman | TwitchingImpaledHuman | SkullOnPole | FiveSkullShishKebap | PileOfSkullsAndCandles | HangingVictim | HangingVictimTwitching | HangingPairOfLegs | HangingVictim1Leg | HangingLeg | HangingVictimNoGuts | HangingVictimNoGutsBrain | HangingTorsoLookingDown | HangingTorsoOpenSkull | HangingTorsoLookingUp | HangingTorsoNoBrain | HangingBilly | DeadPlayer | DeadFormerHuman | DeadFormerSergeant | DeadImp | DeadDemon | DeadCacodemon | DeadLostSoulInvisible | BloodyMessExplodedPlayer | BloodyMessAsAbove | PoolOfBlood | PoolOfGuts | SmallPoolOfGuts | PoolOfBrains | HangingVictimTwitching2 | HangingVictimArmsSpread | HangingVictim1Legged | HangingPairOfLegs2 | HangingLeg2 | ThingTypeOther Int deriving (Show) -- | Convert an integer thing type as found in the WAD file to -- Haskell. -- thingTypeFromNumber :: Integral a => a -> ThingType thingTypeFromNumber n = case n of -- Mostly taken from: UDS in the version at -- http://web.archive.org/web/20100906191901/http://the-stable.lancs.ac.uk/~esasb1/doom/uds/things.html -- 0 -> ZeroThing -- Appears in PLUTONIA.WAD 1 -> Player1StartPos 2 -> Player2StartPos 3 -> Player3StartPos 4 -> Player4StartPos 11 -> DeathMatchStartPos 3004 -> FormerHuman 84 -> WolfensteinOfficer 9 -> FormerHumanSergeant 65 -> FormerHumanCommando 3001 -> Imp 3002 -> Demon 58 -> Spectre 3006 -> LostSoul 3005 -> Cacodemon 69 -> HellKnight 3003 -> BaronOfHell 68 -> Arachnotron 71 -> PainElemental 66 -> Revenant 67 -> Mancubus 64 -> ArchVile 7 -> Spiderdemon 16 -> Cyberdemon 88 -> BossBrain 14 -> TeleportLanding 89 -> BossShooter 87 -> SpawnSpot 2005 -> Chainsaw 2001 -> Shotgun 82 -> SuperShotgun 2002 -> Chaingun 2003 -> RocketLauncher 2004 -> Plasmagun 2006 -> BFG9000 2007 -> AmmoClip 2008 -> ShotgunShells 2010 -> Rocket 2047 -> CellCharge 2048 -> BoxOfAmmo 2049 -> BoxOfShells 2046 -> BoxOfRockets 17 -> CellChargePack 8 -> Backpack 2011 -> StimPack 2012 -> Medikit 2014 -> HealthPotion 2015 -> SpiritArmor 2018 -> SecurityArmor 2019 -> CombatArmor 83 -> MegaSphere 2013 -> SoulSphere 2022 -> Invulnerability 2023 -> BerserkPack 2024 -> Invisibility 2025 -> RadiationSuit 2026 -> ComputerMap 2045 -> LightAmplificationGoggles 5 -> BlueKeyCard 13 -> RedKeyCard 6 -> YellowKeyCard 40 -> BlueSkullKey 38 -> RedSkullKey 39 -> YellowSkullKey 2035 -> Barrel 70 -> BurningBarrel 34 -> Candle 35 -> Candelabra 48 -> TallTechnocolumn 30 -> TallGreenPillar 32 -> TallRedPillar 31 -> ShortGreenPillar 24 -> ShortGreenPillarWithHeart 36 -> ShortGreenPillarWithBeatingHeart -- According to http://doom.wikia.com/wiki/Thing_types 33 -> ShortRedPillar 37 -> ShortRedPillarWithSkull 47 -> Stalagmite 43 -> BurntGrayTree 54 -> LargeBrownTree 44 -> TallBlueFirestick 45 -> TallGreenFirestick 46 -> TallRedFirestick 55 -> ShortBlueFirestick 56 -> ShortGreenFirestick 57 -> ShortRedFirestick 2028 -> FloorLamp 85 -> TallTechnoLamp 86 -> ShortTechnoLamp 41 -> EvilEyeSymbol 42 -> FlamingSkullRock 25 -> ImpaledHuman 26 -> TwitchingImpaledHuman 27 -> SkullOnPole 28 -> FiveSkullShishKebap 29 -> PileOfSkullsAndCandles 50 -> HangingVictim 49 -> HangingVictimTwitching 52 -> HangingPairOfLegs 51 -> HangingVictim1Leg 53 -> HangingLeg 73 -> HangingVictimNoGuts 74 -> HangingVictimNoGutsBrain 75 -> HangingTorsoLookingDown 76 -> HangingTorsoOpenSkull 77 -> HangingTorsoLookingUp 78 -> HangingTorsoNoBrain 72 -> HangingBilly 15 -> DeadPlayer 18 -> DeadFormerHuman 19 -> DeadFormerSergeant 20 -> DeadImp 21 -> DeadDemon 22 -> DeadCacodemon 23 -> DeadLostSoulInvisible 10 -> BloodyMessExplodedPlayer 12 -> BloodyMessAsAbove -- 24 -> PoolOfBlood -- Duplicate with ShortGreenPillarWithHeart above 79 -> PoolOfGuts 80 -> SmallPoolOfGuts 81 -> PoolOfBrains 63 -> HangingVictimTwitching 59 -> HangingVictimArmsSpread 61 -> HangingVictim1Legged 60 -> HangingPairOfLegs 62 -> HangingLeg _ -> ThingTypeOther (fromIntegral n)
mgrabmueller/waddle
Game/Waddle/Types.hs
bsd-3-clause
19,807
0
11
4,469
2,718
1,710
1,008
431
125
module Problem34 where import Problem32 (digits) -- -- Problem 34: Digit factorials -- -- 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. -- -- Find the sum of all numbers which are equal to the sum of the factorial of -- their digits. -- -- Note: as 1! = 1 and 2! = 2 are not sums they are not included. problem34 :: Int problem34 = sum [ d | d <- [10..10^maxLen] , digitsFacSum d == d ] where maxLen = 7 -- 9.999.999 > 7*(fac 9) digitsFacSum :: Int -> Int digitsFacSum = sum . map fac . digits fac :: Int -> Int fac 0 = 1 fac 1 = 1 fac n = n * fac (n-1)
c0deaddict/project-euler
src/Part1/Problem34.hs
bsd-3-clause
594
0
10
155
145
82
63
14
1
-- {-# OPTIONS_GHC -fcontext-stack=22 #-} {- This modules provides functions for working with topocentric coordinate systems. -} module Astro.Place.Topocentric where import Astro.AD.Place import Astro.Coords import Astro.Place import Numeric.Units.Dimensional.Prelude import Numeric.Units.Dimensional.AD import Numeric.Units.Dimensional.LinearAlgebra import Numeric.Units.Dimensional.LinearAlgebra.VectorAD (diffV) import Numeric.Units.Dimensional.LinearAlgebra.PosVel hiding (latitude, longitude) import qualified Prelude -- | Calculates the axis of the topocentric coordinate system defined -- by the given geodetic place. The axis definitions are those used by -- Soop (p.222): -- X -- towards local East, -- Y -- towards local North, -- Z -- towards local Zenith. -- Note that the our Zenith is defined by the reference ellipsoid (as -- opposed to e.g. the geoid). topocentricX, topocentricY, topocentricZ :: RealFloat a => GeodeticPlace a -> Axis a topocentricX p = normalize $ diffV (\x -> c $ geodeticToECR (lift p){longitude = GeoLongitude x}) (geoLongitude $ longitude p) topocentricY p = normalize $ diffV (\x -> c $ geodeticToECR (lift p){latitude = GeodeticLatitude x}) (geodeticLatitude $ latitude p) topocentricZ p = normalize $ diffV (\x -> c $ geodeticToECR (lift p){height = x}) (height p) -- | Calculates the topocentric coordinate system for the given -- geodetic place. The returned topocentric coordinate system is -- specified in the geocentric rotating coordinate system. topocentricCoordSys :: RealFloat a => GeodeticPlace a -> CoordSys a topocentricCoordSys p = consRow (topocentricX p) $ consRow (topocentricY p) $ rowMatrix (topocentricZ p) -- | Converts a position in the geocentric rotating coordinate system -- to a position in the topocentric coordinate system defined by the -- given geodetic place. ecrToTopocentric :: RealFloat a => GeodeticPlace a -> Coord ECR a -> Coord Topocentric a ecrToTopocentric gs sc = C $ topocentricCoordSys gs `matVec` diffCoords sc (geodeticToECR gs) -- Causes NaNs when the geodetic place is at the center of the ellipsoid! topocentricToECR :: RealFloat a => GeodeticPlace a -> Coord Topocentric a -> Coord ECR a topocentricToECR gs sc = C $ (transpose (topocentricCoordSys gs) `matVec` c sc) `elemAdd` c (geodeticToECR gs) elevation :: RealFloat a => Coord Topocentric a -> Angle a elevation = declination . s azimuth :: RealFloat a => Coord Topocentric a -> Angle a azimuth = az . s where az v = tau / _4 - rightAscension v -- From N/Y towards E/X. range :: RealFloat a => Coord Topocentric a -> Length a range = radius . s -- | Compute elevation in the topocentric coordinate system -- defined by the geodetic place. The input position should be defined -- in the geocentric coordinate system. elevation' :: RealFloat a => GeodeticPlace a -> Coord ECR a -> Angle a elevation' gs = elevation . ecrToTopocentric gs -- | Compute azimuth in the topocentric coordinate system -- defined by the geodetic place. The input position should be defined -- in the geocentric coordinate system. azimuth' :: RealFloat a => GeodeticPlace a -> Coord ECR a -> Angle a azimuth' gs = azimuth . ecrToTopocentric gs -- | Computes the range from the given geodetic place to the given -- geocentric position. range' :: RealFloat a => GeodeticPlace a -> Coord ECR a -> Length a range' gs = norm . diffCoords (geodeticToECR gs) -- More efficient. --range gs = radius . s . ecrToTopocentric gs -- Rather inefficient! -- Convert a tripple of azimuth, elevation, and range observations into -- cartesian coordinates in the topocentric system of the measurement -- source. azElRgToCoords :: RealFloat a => Angle a -> Angle a -> Length a -> Coord Topocentric a azElRgToCoords az el rg = S $ Sph rg (tau / _4 - el) (negate az + tau / _4)
bjornbm/astro
src/Astro/Place/Topocentric.hs
bsd-3-clause
3,863
0
13
687
870
454
416
43
1
import Test.Tasty import Test_2_EvaluatingSimpleExpressions -- -- The following command runs all the tests for part 2: -- -- stack test diy-lang-haskell:test-2 -- main :: IO () main = defaultMain $ testGroup "\nDIY Lang: Testing Part 2" [ evaluatingSimpleExpressionsTests ]
joelchelliah/diy-lang-haskell
test/Test_only_2.hs
bsd-3-clause
308
0
7
73
41
24
17
6
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StaticPointers #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Main where import Control.Distributed.Closure import Control.Distributed.Closure.TH import Data.Binary import Data.Bool (bool) import Data.Typeable import GHC.StaticPtr import Test.Hspec import Test.Hspec.QuickCheck import qualified Test.QuickCheck as QC data T a = T a data T1 a b = T1 a b data T2 = T2 type family F a -- Test that the result of this splice compiles. withStatic [d| instance Show a => Show (T a) where show = undefined instance (Eq a, Show a) => Eq (T a) where (==) = undefined instance Show (F a) => Show (T1 a b) where show = undefined instance Show T2 where show = undefined |] -- * Basic generators (parameterized by size) -- | Generates a basic closure using @cpure@ genPure :: forall a. (Static (Serializable a), QC.Arbitrary a) => Int -> QC.Gen (Closure a) genPure i = cpure (closureDict :: Closure (Dict (Serializable a))) <$> QC.resize (max 0 (i-1)) QC.arbitrary -- | Generates a basic closure using @closure@ genStatic :: QC.Arbitrary (StaticPtr a) => Int -> QC.Gen (Closure a) -- static pointers are considered to contribute 0 to the size, hence ignore the -- size parameter. genStatic _i = closure <$> QC.arbitrary -- | Reifies basic datatypes (they must be @Serializable@ types). Only two types -- here because we already have to enumerate a lot of cases manually (see below). data Type a where TInt :: Type Int TBool :: Type Bool instance Static (Binary Int) where closureDict = static Dict instance Static (Typeable Int) where closureDict = static Dict instance Static (Binary Bool) where closureDict = static Dict instance Static (Typeable Bool) where closureDict = static Dict -- | Existentially quantified version of 'Type'. So that they can be generated. data AType where AType :: Typeable a => Type a -> AType instance QC.Arbitrary (AType) where arbitrary = QC.elements [ AType TInt, AType TBool ] -- | Composed types. Very few choices because of the combinatorics. data Sig a where Zero :: Type a -> Sig a One :: Type a -> Type b -> Sig (a->b) Two :: Type a -> Type b -> Type c -> Sig (a->b->c) -- | Extend a type with an extra parameter. May fail since functions in 'Sig' -- have a maximum of two arguments. push :: Type a -> Sig b -> Maybe (Sig (a -> b)) push a (Zero b) = Just $ One a b push a (One b c) = Just $ Two a b c push _ (Two _ _ _) = Nothing -- | Non-recursive generator of atomic values for each type. genSimple :: Sig a -> Int -> QC.Gen (Closure a) genSimple (Zero TInt) = genPure genSimple (Zero TBool) = genPure genSimple (One TInt TInt) = genStatic genSimple (One TBool TInt) = genStatic genSimple (One TInt TBool) = genStatic `gap` genPure @Int genSimple (One TBool TBool) = genStatic genSimple (Two TInt TInt TInt) = genStatic genSimple (Two TBool TInt TInt) = gflip genStatic genSimple (Two TInt TBool TInt) = genStatic genSimple (Two TBool TBool TInt) = genStatic genSimple (Two TInt TInt TBool) = genStatic genSimple (Two TBool TInt TBool) = genStatic genSimple (Two TInt TBool TBool) = gflip genStatic genSimple (Two TBool TBool TBool) = genStatic gflip :: (Typeable a, Typeable b, Typeable c) => (Int -> QC.Gen (Closure (a->b->c))) -> Int -> QC.Gen (Closure (b->a->c)) gflip g i = (cap (static flip)) <$> g i gap :: Typeable a => (Int -> QC.Gen (Closure (a->b))) -> (Int -> QC.Gen (Closure a)) -> Int -> QC.Gen (Closure b) gap gf gx i = do f <- gf i x <- gx i return $ f `cap` x -- | Generate closures of a given type by randomly choosing to make the closure -- a 'cap'. Stays within the boundaries of 'Sig' so that the type of the -- function is also 'QC.Arbitrary'. genClosure :: Sig a -> Int -> QC.Gen (Closure a) genClosure sig size | size < 10 = genSimple sig size genClosure sig size = do stop <- QC.frequency [(2, return True), (1, return False)] if stop then genSimple sig size else do let upper = div size 3 lower = max 0 (size - 1 - upper) AType pivot <- QC.arbitrary case push pivot sig of Nothing -> genSimple sig size Just sig' -> do -- if the @size@ is big enough, then 1/3 of the time, if we can extend -- the signature, build a closure with @cap@ function <- genClosure sig' upper argument <- genClosure (Zero pivot) lower return $ function `cap` argument -- * Generating static pointers -- -- Must be from explicit lists since static pointers are, well, static. The -- combinatorics is unpleasant. instance QC.Arbitrary (StaticPtr (Int -> Int)) where arbitrary = QC.elements [ static id , static pred , static succ , static (3*) ] instance QC.Arbitrary (StaticPtr (Bool -> Int)) where arbitrary = QC.elements [ static (bool 0 1) , static (bool 57 42)] instance QC.Arbitrary (StaticPtr (Bool -> Bool)) where arbitrary = QC.elements [ static id , static not ] instance QC.Arbitrary (StaticPtr (Int -> Int -> Int)) where arbitrary = QC.elements [ static const , static (+) , static (*) , static (-) , static (\x y -> 2*x + y) ] instance QC.Arbitrary (StaticPtr (Int -> Bool -> Int)) where arbitrary = QC.elements [ static const , static (\n b -> if b then n else -n) , static (bool 0) ] instance QC.Arbitrary (StaticPtr (Bool -> Bool -> Int)) where arbitrary = QC.elements [ static (\x y -> bool 0 1 (x&&y)) , static (\x y -> bool 57 42 (x||y)) ] instance QC.Arbitrary (StaticPtr (Int -> Int -> Bool)) where arbitrary = QC.elements [ static (==) , static (>=) , static (<=) , static (<) , static (>) ] instance QC.Arbitrary (StaticPtr (Bool -> Int -> Bool)) where arbitrary = QC.elements [ static const , static (\b n -> b && (n >= 0)) , static (\b n -> b || (n < 0)) , static (\b n -> if b then n >=0 else n < 0) ] instance QC.Arbitrary (StaticPtr (Bool -> Bool -> Bool)) where arbitrary = QC.elements [ static (&&) , static (||)] -- * Instances instance QC.Arbitrary (Closure Int) where arbitrary = QC.sized $ genClosure (Zero TInt) instance QC.Arbitrary (Closure (Int -> Int)) where arbitrary = QC.sized $ genClosure (One TInt TInt) instance Show (Closure a) where show _ = "<closure>" instance Show (StaticPtr a) where show _ = "<static>" -- | Extensional equality on closures (/i.e./ closures are equal if they -- represent equal values) instance Eq a => Eq (Closure a) where cl1 == cl2 = unclosure cl1 == unclosure cl2 -- * Tests main :: IO () main = hspec $ do describe "unclosure" $ do prop "is inverse to cpure" $ \x y z -> (unclosure . cpure $cdict) x == (x :: Int) && (unclosure . cpure $cdict) y == (y :: Bool) && (unclosure . cpure $cdict) z == (z :: Maybe Int) prop "is inverse to cduplicate" $ \x -> (unclosure . cduplicate) x == (x :: Closure Int) prop "is inverse to closure of id" $ \(x :: Int) -> (unclosure . closure) (static id) x == x prop "is inverse to closure" $ \(f :: StaticPtr (Int -> Int)) (x :: Int) -> (unclosure . closure) f x == deRefStaticPtr f x describe "laws" $ do prop "identity" $ \(v :: Closure Int) -> unclosure (static id `cap` v) == id (unclosure v) prop "composition" $ \(u :: Closure (Int -> Int)) (v :: Closure (Int -> Int)) (w :: Closure Int) -> closure (static (.)) `cap` u `cap` v `cap` w == u `cap` (v `cap` w) prop "homomorphism" $ \(f :: Closure (Int -> Int)) x -> unclosure (f `cap` x) == (unclosure f) (unclosure x) describe "serialization" $ do prop "decode is left inverse to encode" $ \v -> (decode . encode) v == (v :: Closure Int)
tweag/distributed-closure
tests/test.hs
bsd-3-clause
8,272
0
22
2,127
2,842
1,474
1,368
193
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-| Module: Control.Remote.Monad.JSON where Copyright: (C) 2015, The University of Kansas License: BSD-style (see the file LICENSE) Maintainer: Justin Dawson Stability: Alpha Portability: GHC -} module Control.Remote.Monad.JSON ( -- * JSON-RPC DSL RPC, -- abstract method, notification, -- * Invoke the JSON RPC Remote Monad send, Session, weakSession, strongSession, applicativeSession, SendAPI(..), -- * Types Args(..) ) where import Control.Monad.State import Control.Natural import Control.Remote.Monad.JSON.Types import Control.Remote.Monad import qualified Control.Remote.Packet.Applicative as AP import qualified Control.Remote.Packet.Strong as SP import qualified Control.Remote.Packet.Weak as WP import Data.Aeson import qualified Data.HashMap.Strict as HM import Data.Text (Text) -- | Sets up a JSON-RPC method call with the function name and arguments method :: FromJSON a => Text -> Args -> RPC a method nm args = RPC $ primitive $ Method nm args -- | Sets up a JSON-RPC notification call with the function name and arguments notification :: Text -> Args -> RPC () notification nm args = RPC $ primitive $ Notification nm args runWeakRPC :: forall a . (SendAPI ~> IO) -> WP.WeakPacket Prim a -> IO a runWeakRPC f (WP.Primitive m) = do case knownResult m of Just a -> do () <- f $ Async $ toJSON $ NotificationCall m return a Nothing -> do let tid = 1 v <- f (Sync (toJSON $ mkMethodCall m tid)) res <- parseReply v parseMethodResult m tid res runStrongRPC :: (SendAPI ~> IO) -> SP.StrongPacket Prim a -> IO a runStrongRPC f packet = go packet ([]++) where go :: forall a . SP.StrongPacket Prim a -> ([Prim ()]->[Prim ()]) -> IO a go (SP.Command n cs) ls = go cs (ls . ([n] ++)) go (SP.Done) ls = do let toSend = (map(toJSON . NotificationCall) (ls [])) () <- sendBatchAsync f toSend return () go (SP.Procedure m) ls = do let tid = 1 let toSend = (map (toJSON . NotificationCall) (ls []) ) ++ [toJSON $ mkMethodCall m tid] res <- sendBatchSync f toSend parseMethodResult m tid res sendBatchAsync :: (SendAPI ~> IO) -> [Value] -> IO () sendBatchAsync _ [] = return () -- never send empty packet sendBatchAsync f [x] = f (Async x) -- send singleton packet sendBatchAsync f xs = f (Async (toJSON xs)) -- send batch packet -- There must be at least one command in the list sendBatchSync :: (SendAPI ~> IO) -> [Value] -> IO (HM.HashMap IDTag Value) sendBatchSync f xs = f (Sync (toJSON xs)) >>= parseReply -- send batch packet runApplicativeRPC :: (SendAPI ~> IO) -> AP.ApplicativePacket Prim a -> IO a runApplicativeRPC f packet = do case knownResult packet of Just a -> do () <- sendBatchAsync f (map toJSON $ ls0 []) return a Nothing -> do rs <- sendBatchSync f (map toJSON $ ls0 []) ff0 rs where (ls0,ff0) = evalState (go packet) 1 go:: forall a . AP.ApplicativePacket Prim a -> State IDTag ([JSONCall]->[JSONCall], HM.HashMap IDTag Value -> IO a) go (AP.Zip comb g h) = do (ls1,g') <- go g (ls2,h') <- go h return ( (ls1 .ls2), \mp -> comb <$> g' mp <*> h' mp) go (AP.Pure a ) = return (([]++), \_ -> return a) go (AP.Primitive m@(Notification{})) = return (([NotificationCall m]++), \_ -> return ()) go (AP.Primitive m@(Method{})) = do tid <-get put (succ tid) return (([mkMethodCall m tid]++) , \mp -> parseMethodResult m tid mp ) -- | Takes a function that handles the sending of Async and Sync messages, -- and sends each Notification and Method one at a time weakSession :: (SendAPI :~> IO) -> Session weakSession f = Session $ runMonad (wrapNT $ runWeakRPC (unwrapNT f)) -- | Takes a function that handles the sending of Async and Sync messages, -- and bundles Notifications together terminated by an optional Method strongSession :: (SendAPI :~> IO) -> Session strongSession f = Session $ runMonad (wrapNT $ runStrongRPC (unwrapNT f)) -- | Takes a function that handles the sending of Async and Sync messages, -- and bundles together Notifications and Procedures that are used in -- Applicative calls applicativeSession :: (SendAPI :~> IO) -> Session applicativeSession f = Session $ runMonad (wrapNT $ runApplicativeRPC (unwrapNT f)) -- | Send RPC Notifications and Methods by using the given session send :: Session -> RPC a -> IO a send (Session f) (RPC m) = f # m
ku-fpg/remote-json
Control/Remote/Monad/JSON.hs
bsd-3-clause
5,848
1
18
2,099
1,541
803
738
95
5
{-# LANGUAGE JavaScriptFFI, GeneralizedNewtypeDeriving #-} module GHCJS.Three.Box3 where import GHCJS.Types import GHCJS.Three.Monad import GHCJS.Three.Vector newtype Box3 = Box3 { box3Object :: BaseObject } deriving ThreeJSVal foreign import javascript unsafe "($1)['min']" thr_boxMin :: JSVal -> Three JSVal foreign import javascript unsafe "($1)['max']" thr_boxMax :: JSVal -> Three JSVal foreign import javascript unsafe "($1)['getCenter']()" thr_boxCenter :: JSVal -> Three JSVal foreign import javascript unsafe "($1)['getSize']()" thr_boxSize :: JSVal -> Three JSVal boxMin :: Box3 -> Three Vector3 boxMin b = thr_boxMin (toJSVal b) >>= toVector3 . fromJSVal boxMax :: Box3 -> Three Vector3 boxMax b = thr_boxMax (toJSVal b) >>= toVector3 . fromJSVal boxCenter :: Box3 -> Three Vector3 boxCenter b = thr_boxCenter (toJSVal b) >>= toVector3 . fromJSVal boxSize :: Box3 -> Three Vector3 boxSize b = thr_boxSize (toJSVal b) >>= toVector3 . fromJSVal
manyoo/ghcjs-three
src/GHCJS/Three/Box3.hs
bsd-3-clause
989
11
9
168
276
144
132
24
1
import qualified Interpreter main = Interpreter.withInterpreter [] $ \repl -> do putStrLn "sleeping for 1 second..." Interpreter.eval repl "import Control.Concurrent" Interpreter.eval repl "threadDelay 1000000" putStrLn "done"
beni55/doctest-haskell
tests/hunit/TestInterpreterTermination/test_program.hs
mit
236
0
10
35
58
26
32
6
1
{-# LANGUAGE OverloadedStrings #-} module Color ( Color (..) , fColor , reset , bold ) where import Data.Text import qualified Prelude as P data Color = White | Black | Blue | Green | Red | Brown | Purple | Orange | Yellow | Lime | Teal | Cyan | Royal | Pink | Grey | Silver colorCode :: Color -> Text colorCode White = "00" colorCode Black = "01" colorCode Blue = "02" colorCode Green = "03" colorCode Red = "04" colorCode Brown = "05" colorCode Purple = "06" colorCode Orange = "07" colorCode Yellow = "08" colorCode Lime = "09" colorCode Teal = "10" colorCode Cyan = "11" colorCode Royal = "12" colorCode Pink = "13" colorCode Grey = "14" colorCode Silver = "15" fColor :: Color -> Text fColor c = '\^C' `cons` colorCode c bold :: Text bold = "\^B" reset :: Text reset = "\^P"
jochem88/btjchm
Color.hs
mit
1,010
0
6
381
269
153
116
46
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.ECS.ListTasks -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns a list of tasks for a specified cluster. You can filter the -- results by family name, by a particular container instance, or by the -- desired status of the task with the 'family', 'containerInstance', and -- 'desiredStatus' parameters. -- -- /See:/ <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListTasks.html AWS API Reference> for ListTasks. -- -- This operation returns paginated results. module Network.AWS.ECS.ListTasks ( -- * Creating a Request listTasks , ListTasks -- * Request Lenses , ltDesiredStatus , ltCluster , ltFamily , ltNextToken , ltStartedBy , ltServiceName , ltContainerInstance , ltMaxResults -- * Destructuring the Response , listTasksResponse , ListTasksResponse -- * Response Lenses , ltrsNextToken , ltrsTaskARNs , ltrsResponseStatus ) where import Network.AWS.ECS.Types import Network.AWS.ECS.Types.Product import Network.AWS.Pager import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'listTasks' smart constructor. data ListTasks = ListTasks' { _ltDesiredStatus :: !(Maybe DesiredStatus) , _ltCluster :: !(Maybe Text) , _ltFamily :: !(Maybe Text) , _ltNextToken :: !(Maybe Text) , _ltStartedBy :: !(Maybe Text) , _ltServiceName :: !(Maybe Text) , _ltContainerInstance :: !(Maybe Text) , _ltMaxResults :: !(Maybe Int) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListTasks' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ltDesiredStatus' -- -- * 'ltCluster' -- -- * 'ltFamily' -- -- * 'ltNextToken' -- -- * 'ltStartedBy' -- -- * 'ltServiceName' -- -- * 'ltContainerInstance' -- -- * 'ltMaxResults' listTasks :: ListTasks listTasks = ListTasks' { _ltDesiredStatus = Nothing , _ltCluster = Nothing , _ltFamily = Nothing , _ltNextToken = Nothing , _ltStartedBy = Nothing , _ltServiceName = Nothing , _ltContainerInstance = Nothing , _ltMaxResults = Nothing } -- | The task status that you want to filter the 'ListTasks' results with. -- Specifying a 'desiredStatus' of 'STOPPED' will limit the results to -- tasks that are in the 'STOPPED' status, which can be useful for -- debugging tasks that are not starting properly or have died or finished. -- The default status filter is 'RUNNING'. ltDesiredStatus :: Lens' ListTasks (Maybe DesiredStatus) ltDesiredStatus = lens _ltDesiredStatus (\ s a -> s{_ltDesiredStatus = a}); -- | The short name or full Amazon Resource Name (ARN) of the cluster that -- hosts the tasks you want to list. If you do not specify a cluster, the -- default cluster is assumed.. ltCluster :: Lens' ListTasks (Maybe Text) ltCluster = lens _ltCluster (\ s a -> s{_ltCluster = a}); -- | The name of the family that you want to filter the 'ListTasks' results -- with. Specifying a 'family' will limit the results to tasks that belong -- to that family. ltFamily :: Lens' ListTasks (Maybe Text) ltFamily = lens _ltFamily (\ s a -> s{_ltFamily = a}); -- | The 'nextToken' value returned from a previous paginated 'ListTasks' -- request where 'maxResults' was used and the results exceeded the value -- of that parameter. Pagination continues from the end of the previous -- results that returned the 'nextToken' value. This value is 'null' when -- there are no more results to return. ltNextToken :: Lens' ListTasks (Maybe Text) ltNextToken = lens _ltNextToken (\ s a -> s{_ltNextToken = a}); -- | The 'startedBy' value that you want to filter the task results with. -- Specifying a 'startedBy' value will limit the results to tasks that were -- started with that value. ltStartedBy :: Lens' ListTasks (Maybe Text) ltStartedBy = lens _ltStartedBy (\ s a -> s{_ltStartedBy = a}); -- | The name of the service that you want to filter the 'ListTasks' results -- with. Specifying a 'serviceName' will limit the results to tasks that -- belong to that service. ltServiceName :: Lens' ListTasks (Maybe Text) ltServiceName = lens _ltServiceName (\ s a -> s{_ltServiceName = a}); -- | The container instance UUID or full Amazon Resource Name (ARN) of the -- container instance that you want to filter the 'ListTasks' results with. -- Specifying a 'containerInstance' will limit the results to tasks that -- belong to that container instance. ltContainerInstance :: Lens' ListTasks (Maybe Text) ltContainerInstance = lens _ltContainerInstance (\ s a -> s{_ltContainerInstance = a}); -- | The maximum number of task results returned by 'ListTasks' in paginated -- output. When this parameter is used, 'ListTasks' only returns -- 'maxResults' results in a single page along with a 'nextToken' response -- element. The remaining results of the initial request can be seen by -- sending another 'ListTasks' request with the returned 'nextToken' value. -- This value can be between 1 and 100. If this parameter is not used, then -- 'ListTasks' returns up to 100 results and a 'nextToken' value if -- applicable. ltMaxResults :: Lens' ListTasks (Maybe Int) ltMaxResults = lens _ltMaxResults (\ s a -> s{_ltMaxResults = a}); instance AWSPager ListTasks where page rq rs | stop (rs ^. ltrsNextToken) = Nothing | stop (rs ^. ltrsTaskARNs) = Nothing | otherwise = Just $ rq & ltNextToken .~ rs ^. ltrsNextToken instance AWSRequest ListTasks where type Rs ListTasks = ListTasksResponse request = postJSON eCS response = receiveJSON (\ s h x -> ListTasksResponse' <$> (x .?> "nextToken") <*> (x .?> "taskArns" .!@ mempty) <*> (pure (fromEnum s))) instance ToHeaders ListTasks where toHeaders = const (mconcat ["X-Amz-Target" =# ("AmazonEC2ContainerServiceV20141113.ListTasks" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON ListTasks where toJSON ListTasks'{..} = object (catMaybes [("desiredStatus" .=) <$> _ltDesiredStatus, ("cluster" .=) <$> _ltCluster, ("family" .=) <$> _ltFamily, ("nextToken" .=) <$> _ltNextToken, ("startedBy" .=) <$> _ltStartedBy, ("serviceName" .=) <$> _ltServiceName, ("containerInstance" .=) <$> _ltContainerInstance, ("maxResults" .=) <$> _ltMaxResults]) instance ToPath ListTasks where toPath = const "/" instance ToQuery ListTasks where toQuery = const mempty -- | /See:/ 'listTasksResponse' smart constructor. data ListTasksResponse = ListTasksResponse' { _ltrsNextToken :: !(Maybe Text) , _ltrsTaskARNs :: !(Maybe [Text]) , _ltrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListTasksResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ltrsNextToken' -- -- * 'ltrsTaskARNs' -- -- * 'ltrsResponseStatus' listTasksResponse :: Int -- ^ 'ltrsResponseStatus' -> ListTasksResponse listTasksResponse pResponseStatus_ = ListTasksResponse' { _ltrsNextToken = Nothing , _ltrsTaskARNs = Nothing , _ltrsResponseStatus = pResponseStatus_ } -- | The 'nextToken' value to include in a future 'ListTasks' request. When -- the results of a 'ListTasks' request exceed 'maxResults', this value can -- be used to retrieve the next page of results. This value is 'null' when -- there are no more results to return. ltrsNextToken :: Lens' ListTasksResponse (Maybe Text) ltrsNextToken = lens _ltrsNextToken (\ s a -> s{_ltrsNextToken = a}); -- | The list of task Amazon Resource Name (ARN) entries for the 'ListTasks' -- request. ltrsTaskARNs :: Lens' ListTasksResponse [Text] ltrsTaskARNs = lens _ltrsTaskARNs (\ s a -> s{_ltrsTaskARNs = a}) . _Default . _Coerce; -- | The response status code. ltrsResponseStatus :: Lens' ListTasksResponse Int ltrsResponseStatus = lens _ltrsResponseStatus (\ s a -> s{_ltrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-ecs/gen/Network/AWS/ECS/ListTasks.hs
mpl-2.0
9,138
0
13
2,096
1,362
812
550
150
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.DataPipeline.PutPipelineDefinition -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Adds tasks, schedules, and preconditions to the specified pipeline. You -- can use 'PutPipelineDefinition' to populate a new pipeline. -- -- 'PutPipelineDefinition' also validates the configuration as it adds it -- to the pipeline. Changes to the pipeline are saved unless one of the -- following three validation errors exists in the pipeline. -- -- 1. An object is missing a name or identifier field. -- 2. A string or reference field is empty. -- 3. The number of objects in the pipeline exceeds the maximum allowed -- objects. -- 4. The pipeline is in a FINISHED state. -- -- Pipeline object definitions are passed to the 'PutPipelineDefinition' -- action and returned by the GetPipelineDefinition action. -- -- /See:/ <http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_PutPipelineDefinition.html AWS API Reference> for PutPipelineDefinition. module Network.AWS.DataPipeline.PutPipelineDefinition ( -- * Creating a Request putPipelineDefinition , PutPipelineDefinition -- * Request Lenses , ppdParameterObjects , ppdParameterValues , ppdPipelineId , ppdPipelineObjects -- * Destructuring the Response , putPipelineDefinitionResponse , PutPipelineDefinitionResponse -- * Response Lenses , ppdrsValidationErrors , ppdrsValidationWarnings , ppdrsResponseStatus , ppdrsErrored ) where import Network.AWS.DataPipeline.Types import Network.AWS.DataPipeline.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Contains the parameters for PutPipelineDefinition. -- -- /See:/ 'putPipelineDefinition' smart constructor. data PutPipelineDefinition = PutPipelineDefinition' { _ppdParameterObjects :: !(Maybe [ParameterObject]) , _ppdParameterValues :: !(Maybe [ParameterValue]) , _ppdPipelineId :: !Text , _ppdPipelineObjects :: ![PipelineObject] } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PutPipelineDefinition' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ppdParameterObjects' -- -- * 'ppdParameterValues' -- -- * 'ppdPipelineId' -- -- * 'ppdPipelineObjects' putPipelineDefinition :: Text -- ^ 'ppdPipelineId' -> PutPipelineDefinition putPipelineDefinition pPipelineId_ = PutPipelineDefinition' { _ppdParameterObjects = Nothing , _ppdParameterValues = Nothing , _ppdPipelineId = pPipelineId_ , _ppdPipelineObjects = mempty } -- | The parameter objects used with the pipeline. ppdParameterObjects :: Lens' PutPipelineDefinition [ParameterObject] ppdParameterObjects = lens _ppdParameterObjects (\ s a -> s{_ppdParameterObjects = a}) . _Default . _Coerce; -- | The parameter values used with the pipeline. ppdParameterValues :: Lens' PutPipelineDefinition [ParameterValue] ppdParameterValues = lens _ppdParameterValues (\ s a -> s{_ppdParameterValues = a}) . _Default . _Coerce; -- | The ID of the pipeline. ppdPipelineId :: Lens' PutPipelineDefinition Text ppdPipelineId = lens _ppdPipelineId (\ s a -> s{_ppdPipelineId = a}); -- | The objects that define the pipeline. These objects overwrite the -- existing pipeline definition. ppdPipelineObjects :: Lens' PutPipelineDefinition [PipelineObject] ppdPipelineObjects = lens _ppdPipelineObjects (\ s a -> s{_ppdPipelineObjects = a}) . _Coerce; instance AWSRequest PutPipelineDefinition where type Rs PutPipelineDefinition = PutPipelineDefinitionResponse request = postJSON dataPipeline response = receiveJSON (\ s h x -> PutPipelineDefinitionResponse' <$> (x .?> "validationErrors" .!@ mempty) <*> (x .?> "validationWarnings" .!@ mempty) <*> (pure (fromEnum s)) <*> (x .:> "errored")) instance ToHeaders PutPipelineDefinition where toHeaders = const (mconcat ["X-Amz-Target" =# ("DataPipeline.PutPipelineDefinition" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON PutPipelineDefinition where toJSON PutPipelineDefinition'{..} = object (catMaybes [("parameterObjects" .=) <$> _ppdParameterObjects, ("parameterValues" .=) <$> _ppdParameterValues, Just ("pipelineId" .= _ppdPipelineId), Just ("pipelineObjects" .= _ppdPipelineObjects)]) instance ToPath PutPipelineDefinition where toPath = const "/" instance ToQuery PutPipelineDefinition where toQuery = const mempty -- | Contains the output of PutPipelineDefinition. -- -- /See:/ 'putPipelineDefinitionResponse' smart constructor. data PutPipelineDefinitionResponse = PutPipelineDefinitionResponse' { _ppdrsValidationErrors :: !(Maybe [ValidationError]) , _ppdrsValidationWarnings :: !(Maybe [ValidationWarning]) , _ppdrsResponseStatus :: !Int , _ppdrsErrored :: !Bool } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PutPipelineDefinitionResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ppdrsValidationErrors' -- -- * 'ppdrsValidationWarnings' -- -- * 'ppdrsResponseStatus' -- -- * 'ppdrsErrored' putPipelineDefinitionResponse :: Int -- ^ 'ppdrsResponseStatus' -> Bool -- ^ 'ppdrsErrored' -> PutPipelineDefinitionResponse putPipelineDefinitionResponse pResponseStatus_ pErrored_ = PutPipelineDefinitionResponse' { _ppdrsValidationErrors = Nothing , _ppdrsValidationWarnings = Nothing , _ppdrsResponseStatus = pResponseStatus_ , _ppdrsErrored = pErrored_ } -- | The validation errors that are associated with the objects defined in -- 'pipelineObjects'. ppdrsValidationErrors :: Lens' PutPipelineDefinitionResponse [ValidationError] ppdrsValidationErrors = lens _ppdrsValidationErrors (\ s a -> s{_ppdrsValidationErrors = a}) . _Default . _Coerce; -- | The validation warnings that are associated with the objects defined in -- 'pipelineObjects'. ppdrsValidationWarnings :: Lens' PutPipelineDefinitionResponse [ValidationWarning] ppdrsValidationWarnings = lens _ppdrsValidationWarnings (\ s a -> s{_ppdrsValidationWarnings = a}) . _Default . _Coerce; -- | The response status code. ppdrsResponseStatus :: Lens' PutPipelineDefinitionResponse Int ppdrsResponseStatus = lens _ppdrsResponseStatus (\ s a -> s{_ppdrsResponseStatus = a}); -- | Indicates whether there were validation errors, and the pipeline -- definition is stored but cannot be activated until you correct the -- pipeline and call 'PutPipelineDefinition' to commit the corrected -- pipeline. ppdrsErrored :: Lens' PutPipelineDefinitionResponse Bool ppdrsErrored = lens _ppdrsErrored (\ s a -> s{_ppdrsErrored = a});
fmapfmapfmap/amazonka
amazonka-datapipeline/gen/Network/AWS/DataPipeline/PutPipelineDefinition.hs
mpl-2.0
7,778
0
15
1,556
1,045
628
417
122
1
module Flickr.API ( module Flickr.Monad, module Flickr.Types, module Flickr.Utils, module Flickr.Auth ) where import Flickr.Monad import Flickr.Types import Flickr.Utils import Flickr.Auth
sof/flickr
Flickr/API.hs
bsd-3-clause
232
0
5
64
52
33
19
10
0
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Data/Attoparsec/Internal/Types.hs" #-} {-# LANGUAGE BangPatterns, GeneralizedNewtypeDeriving, OverloadedStrings, Rank2Types, RecordWildCards, TypeFamilies #-} -- | -- Module : Data.Attoparsec.Internal.Types -- Copyright : Bryan O'Sullivan 2007-2015 -- License : BSD3 -- -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : unknown -- -- Simple, efficient parser combinators, loosely based on the Parsec -- library. module Data.Attoparsec.Internal.Types ( Parser(..) , State , Failure , Success , Pos(..) , IResult(..) , More(..) , (<>) , Chunk(..) ) where import Control.Applicative as App (Applicative(..), (<$>)) import Control.Applicative (Alternative(..)) import Control.DeepSeq (NFData(rnf)) import Control.Monad (MonadPlus(..)) import qualified Control.Monad.Fail as Fail (MonadFail(..)) import Data.Monoid as Mon (Monoid(..)) import Data.Semigroup (Semigroup(..)) import Data.Word (Word8) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.ByteString.Internal (w2c) import Data.Text (Text) import qualified Data.Text as Text import Data.Text.Unsafe (Iter(..)) import Prelude hiding (getChar, succ) import qualified Data.Attoparsec.ByteString.Buffer as B import qualified Data.Attoparsec.Text.Buffer as T newtype Pos = Pos { fromPos :: Int } deriving (Eq, Ord, Show, Num) -- | The result of a parse. This is parameterised over the type @i@ -- of string that was processed. -- -- This type is an instance of 'Functor', where 'fmap' transforms the -- value in a 'Done' result. data IResult i r = Fail i [String] String -- ^ The parse failed. The @i@ parameter is the input that had -- not yet been consumed when the failure occurred. The -- @[@'String'@]@ is a list of contexts in which the error -- occurred. The 'String' is the message describing the error, if -- any. | Partial (i -> IResult i r) -- ^ Supply this continuation with more input so that the parser -- can resume. To indicate that no more input is available, pass -- an empty string to the continuation. -- -- __Note__: if you get a 'Partial' result, do not call its -- continuation more than once. | Done i r -- ^ The parse succeeded. The @i@ parameter is the input that had -- not yet been consumed (if any) when the parse succeeded. instance (Show i, Show r) => Show (IResult i r) where showsPrec d ir = showParen (d > 10) $ case ir of (Fail t stk msg) -> showString "Fail" . f t . f stk . f msg (Partial _) -> showString "Partial _" (Done t r) -> showString "Done" . f t . f r where f :: Show a => a -> ShowS f x = showChar ' ' . showsPrec 11 x instance (NFData i, NFData r) => NFData (IResult i r) where rnf (Fail t stk msg) = rnf t `seq` rnf stk `seq` rnf msg rnf (Partial _) = () rnf (Done t r) = rnf t `seq` rnf r {-# INLINE rnf #-} instance Functor (IResult i) where fmap _ (Fail t stk msg) = Fail t stk msg fmap f (Partial k) = Partial (fmap f . k) fmap f (Done t r) = Done t (f r) -- | The core parser type. This is parameterised over the type @i@ -- of string being processed. -- -- This type is an instance of the following classes: -- -- * 'Monad', where 'fail' throws an exception (i.e. fails) with an -- error message. -- -- * 'Functor' and 'Applicative', which follow the usual definitions. -- -- * 'MonadPlus', where 'mzero' fails (with no error message) and -- 'mplus' executes the right-hand parser if the left-hand one -- fails. When the parser on the right executes, the input is reset -- to the same state as the parser on the left started with. (In -- other words, attoparsec is a backtracking parser that supports -- arbitrary lookahead.) -- -- * 'Alternative', which follows 'MonadPlus'. newtype Parser i a = Parser { runParser :: forall r. State i -> Pos -> More -> Failure i (State i) r -> Success i (State i) a r -> IResult i r } type family State i type instance State ByteString = B.Buffer type instance State Text = T.Buffer type Failure i t r = t -> Pos -> More -> [String] -> String -> IResult i r type Success i t a r = t -> Pos -> More -> a -> IResult i r -- | Have we read all available input? data More = Complete | Incomplete deriving (Eq, Show) instance Semigroup More where c@Complete <> _ = c _ <> m = m instance Mon.Monoid More where mappend = (<>) mempty = Incomplete instance Monad (Parser i) where fail = Fail.fail {-# INLINE fail #-} return = App.pure {-# INLINE return #-} m >>= k = Parser $ \t !pos more lose succ -> let succ' t' !pos' more' a = runParser (k a) t' pos' more' lose succ in runParser m t pos more lose succ' {-# INLINE (>>=) #-} (>>) = (*>) {-# INLINE (>>) #-} instance Fail.MonadFail (Parser i) where fail err = Parser $ \t pos more lose _succ -> lose t pos more [] msg where msg = "Failed reading: " ++ err {-# INLINE fail #-} plus :: Parser i a -> Parser i a -> Parser i a plus f g = Parser $ \t pos more lose succ -> let lose' t' _pos' more' _ctx _msg = runParser g t' pos more' lose succ in runParser f t pos more lose' succ instance MonadPlus (Parser i) where mzero = fail "mzero" {-# INLINE mzero #-} mplus = plus instance Functor (Parser i) where fmap f p = Parser $ \t pos more lose succ -> let succ' t' pos' more' a = succ t' pos' more' (f a) in runParser p t pos more lose succ' {-# INLINE fmap #-} apP :: Parser i (a -> b) -> Parser i a -> Parser i b apP d e = do b <- d a <- e return (b a) {-# INLINE apP #-} instance Applicative (Parser i) where pure v = Parser $ \t pos more _lose succ -> succ t pos more v {-# INLINE pure #-} (<*>) = apP {-# INLINE (<*>) #-} m *> k = m >>= \_ -> k {-# INLINE (*>) #-} x <* y = x >>= \a -> y >> pure a {-# INLINE (<*) #-} instance Semigroup (Parser i a) where (<>) = plus {-# INLINE (<>) #-} instance Monoid (Parser i a) where mempty = fail "mempty" {-# INLINE mempty #-} mappend = (<>) {-# INLINE mappend #-} instance Alternative (Parser i) where empty = fail "empty" {-# INLINE empty #-} (<|>) = plus {-# INLINE (<|>) #-} many v = many_v where many_v = some_v <|> pure [] some_v = (:) App.<$> v <*> many_v {-# INLINE many #-} some v = some_v where many_v = some_v <|> pure [] some_v = (:) <$> v <*> many_v {-# INLINE some #-} -- | A common interface for input chunks. class Monoid c => Chunk c where type ChunkElem c -- | Test if the chunk is empty. nullChunk :: c -> Bool -- | Append chunk to a buffer. pappendChunk :: State c -> c -> State c -- | Position at the end of a buffer. The first argument is ignored. atBufferEnd :: c -> State c -> Pos -- | Return the buffer element at the given position along with its length. bufferElemAt :: c -> Pos -> State c -> Maybe (ChunkElem c, Int) -- | Map an element to the corresponding character. -- The first argument is ignored. chunkElemToChar :: c -> ChunkElem c -> Char instance Chunk ByteString where type ChunkElem ByteString = Word8 nullChunk = BS.null {-# INLINE nullChunk #-} pappendChunk = B.pappend {-# INLINE pappendChunk #-} atBufferEnd _ = Pos . B.length {-# INLINE atBufferEnd #-} bufferElemAt _ (Pos i) buf | i < B.length buf = Just (B.unsafeIndex buf i, 1) | otherwise = Nothing {-# INLINE bufferElemAt #-} chunkElemToChar _ = w2c {-# INLINE chunkElemToChar #-} instance Chunk Text where type ChunkElem Text = Char nullChunk = Text.null {-# INLINE nullChunk #-} pappendChunk = T.pappend {-# INLINE pappendChunk #-} atBufferEnd _ = Pos . T.length {-# INLINE atBufferEnd #-} bufferElemAt _ (Pos i) buf | i < T.length buf = let Iter c l = T.iter buf i in Just (c, l) | otherwise = Nothing {-# INLINE bufferElemAt #-} chunkElemToChar _ = id {-# INLINE chunkElemToChar #-}
phischu/fragnix
tests/packages/scotty/Data.Attoparsec.Internal.Types.hs
bsd-3-clause
8,279
0
15
2,170
2,172
1,196
976
174
1
module Turing.Laufzeit.Inter where -- $Id$ import Turing.Type import Turing.Laufzeit.Type import Inter.Types import Reporter import ToDoc import Informed step :: String -- name der variante -> Laufzeit -> Var TM Laufzeit ( Turing Char Integer ) step v l = Var { problem = TM , variant = "STEP" ++ v , key = \ matrikel -> do return matrikel , gen = \ matrikel -> do inform $ text "Konstruieren Sie eine Turingmaschine" inform $ text "mit Laufzeitfunktion" <+> info l return l , gen_i = \ matrikel -> l }
Erdwolf/autotool-bonn
src/Turing/Laufzeit/Inter.hs
gpl-2.0
558
2
12
146
164
90
74
20
1